qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
304,525 | <p>I am trying to implement Panel Color in the Inspector Control for a custom block but can't seem to figure it out. Below is the JSX code that attempts it. It renders the block, but when it's in focus, it encounters a <a href="http://reactjs.org/docs/error-decoder.html?invariant=130&args[]=undefined&args[]=" rel="noreferrer">Minified React error #130</a>.</p>
<pre><code>const { registerBlockType, InspectorControls, PanelColor } = wp.blocks;
registerBlockType( 'test/test', {
title: 'Test',
icon: 'universal-access-alt',
category: 'layout',
edit( { attributes, className, setAttributes } ) {
const { backgroundColor } = attributes;
const onChangeBackgroundColor = newBackgroundColor => {
setAttributes( { backgroundColor: newBackgroundColor } );
};
return (
<div className={ className }>
{ !! focus && (
<InspectorControls>
<PanelColor
title={ 'Background Color' }
value={ backgroundColor }
onChange={ onChangeBackgroundColor }
/>
</InspectorControls>
) }
</div>
);
},
save( { attributes, className } ) {
const { backgroundColor } = attributes;
return (
<div className={ className }>
</div>
);
},
} );
</code></pre>
| [
{
"answer_id": 304562,
"author": "developerjack",
"author_id": 144350,
"author_profile": "https://wordpress.stackexchange.com/users/144350",
"pm_score": 4,
"selected": true,
"text": "<p>Many <code>wp.blocks.*</code> controls have been moved to <code>wp.editor.*</code> (see <a href=\"http... | 2018/05/26 | [
"https://wordpress.stackexchange.com/questions/304525",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106269/"
] | I am trying to implement Panel Color in the Inspector Control for a custom block but can't seem to figure it out. Below is the JSX code that attempts it. It renders the block, but when it's in focus, it encounters a [Minified React error #130](http://reactjs.org/docs/error-decoder.html?invariant=130&args[]=undefined&args[]=).
```
const { registerBlockType, InspectorControls, PanelColor } = wp.blocks;
registerBlockType( 'test/test', {
title: 'Test',
icon: 'universal-access-alt',
category: 'layout',
edit( { attributes, className, setAttributes } ) {
const { backgroundColor } = attributes;
const onChangeBackgroundColor = newBackgroundColor => {
setAttributes( { backgroundColor: newBackgroundColor } );
};
return (
<div className={ className }>
{ !! focus && (
<InspectorControls>
<PanelColor
title={ 'Background Color' }
value={ backgroundColor }
onChange={ onChangeBackgroundColor }
/>
</InspectorControls>
) }
</div>
);
},
save( { attributes, className } ) {
const { backgroundColor } = attributes;
return (
<div className={ className }>
</div>
);
},
} );
``` | Many `wp.blocks.*` controls have been moved to `wp.editor.*` (see [release notes](https://github.com/WordPress/gutenberg/blob/v2.9.2/docs/reference/deprecated.md#310)).
Specifically `wp.blocks.InspectorControls` is now `wp.editor.InspectorControls` - you'll need to change the first line of your code.
*Note: `registerBlockType` is still imported from `wp.blocks.*` iirc.*
As a side note, I've also found that the `focus &&` trick no longer required as GB automatically displays the InspectorControls when the block is focused. |
304,558 | <p>I am using the code below to sort code as per <code>meta_value</code>. But in this specific Column I have dates displayed for example: 20 April 2018 or 01 June 2018</p>
<p>The sorting works sort of but now when I order the columns it displays it like 29 April 2018, 29 May 2018, 29 June 2018, 28 April 2018, 28 May 2018, 28 June 2018...and so and so on...</p>
<p>Is there a way to sort that column in a proper date format like 29 April 2018, 28 April 2018, 27 April 2018 etc....???</p>
<p>Code I am using as follows:</p>
<pre><code>add_filter( 'manage_edit-post_sortable_columns', 'closing_sortable_columns' );
function closing_sortable_columns( $columns ) {
$columns['closing'] = 'closing';
return $columns;
}
add_action( 'pre_get_posts', 'closing_column_orderby' );
function closing_column_orderby( $query ) {
if( ! is_admin() )
return;
$orderby = $query->get( 'orderby');
if( 'closing' == $orderby ) {
$query->set('meta_key','closing');
$query->set('orderby','meta_value_num');
}
}
</code></pre>
<p>I tried to change <code>meta_value_num</code> to <code>asc</code> but this just mixes up everything and makes the overview even worse.</p>
| [
{
"answer_id": 304559,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 0,
"selected": false,
"text": "<p>You need dates to be stored in a sortable format. For example, MySQL date format (which is the date format Wo... | 2018/05/27 | [
"https://wordpress.stackexchange.com/questions/304558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138622/"
] | I am using the code below to sort code as per `meta_value`. But in this specific Column I have dates displayed for example: 20 April 2018 or 01 June 2018
The sorting works sort of but now when I order the columns it displays it like 29 April 2018, 29 May 2018, 29 June 2018, 28 April 2018, 28 May 2018, 28 June 2018...and so and so on...
Is there a way to sort that column in a proper date format like 29 April 2018, 28 April 2018, 27 April 2018 etc....???
Code I am using as follows:
```
add_filter( 'manage_edit-post_sortable_columns', 'closing_sortable_columns' );
function closing_sortable_columns( $columns ) {
$columns['closing'] = 'closing';
return $columns;
}
add_action( 'pre_get_posts', 'closing_column_orderby' );
function closing_column_orderby( $query ) {
if( ! is_admin() )
return;
$orderby = $query->get( 'orderby');
if( 'closing' == $orderby ) {
$query->set('meta_key','closing');
$query->set('orderby','meta_value_num');
}
}
```
I tried to change `meta_value_num` to `asc` but this just mixes up everything and makes the overview even worse. | By default meta values will be treated as strings, leading to the result that you get. As you can see from the [codex on `wp_query`](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters) you can force a comparison with different formats by defining a `meta_type`. Like this:
```
$query->set('meta_type','DATETIME');
``` |
304,568 | <p>I have a website which uses wordpress. It was initially uploaded and used without SSL. After installing a server certificate and adding the apache virtualhost file for the ssl site, I tried loading the https version. It loaded with a lot of warnings about insecure content being trimmed. The resulting webpage was looking ugly because a lot of css and javascript files related to the wordpress theme were not being loaded because of insecure http protocol.</p>
<p>I changed the .htaccess to the following:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://drjoel.info/$1 [R,L]
</IfModule>
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code></pre>
<p>I then followed the codex instructions and changed the "Home" and "Site URL" in the mysql database to https from http. When I tried loading again, the browser kept showing "Too many redirects" error. I checked using verbosity and debug option in wget. This is what I get:</p>
<pre><code>---request begin---
GET / HTTP/1.1
User-Agent: Wget/1.19.1 (linux-gnu)
Accept: */*
Accept-Encoding: identity
Host: drjoel.info
Connection: Keep-Alive
Cookie: __cfduid=d700f224676946c9ea07ab3eb7cf5cb861527424630
---request end---
HTTP request sent, awaiting response...
---response begin---
HTTP/1.1 302 Found
Date: Sun, 27 May 2018 12:37:11 GMT
Content-Type: text/html; charset=iso-8859-1
Transfer-Encoding: chunked
Connection: keep-alive
Location: https://drjoel.info/
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
CF-RAY: 42188807c86caaaa-SIN
---response end---
302 Found
URI content encoding = ‘iso-8859-1’
Location: https://drjoel.info/ [following]
Skipping 204 bytes of body: [<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="https://drjoel.info/">here</a>.</p>
</body></html>
] done.
URI content encoding = None
Converted file name 'index.html' (UTF-8) -> 'index.html' (UTF-8)
--2018-05-27 18:07:11-- https://drjoel.info/
Reusing existing connection to drjoel.info:443.
Reusing fd 3.
</code></pre>
<p>This is being repeated about 20 times before wget aborts.
What's going wrong? What is the correct technique to enable SSL for a site on Wordpress?</p>
| [
{
"answer_id": 304559,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 0,
"selected": false,
"text": "<p>You need dates to be stored in a sortable format. For example, MySQL date format (which is the date format Wo... | 2018/05/27 | [
"https://wordpress.stackexchange.com/questions/304568",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28555/"
] | I have a website which uses wordpress. It was initially uploaded and used without SSL. After installing a server certificate and adding the apache virtualhost file for the ssl site, I tried loading the https version. It loaded with a lot of warnings about insecure content being trimmed. The resulting webpage was looking ugly because a lot of css and javascript files related to the wordpress theme were not being loaded because of insecure http protocol.
I changed the .htaccess to the following:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://drjoel.info/$1 [R,L]
</IfModule>
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
```
I then followed the codex instructions and changed the "Home" and "Site URL" in the mysql database to https from http. When I tried loading again, the browser kept showing "Too many redirects" error. I checked using verbosity and debug option in wget. This is what I get:
```
---request begin---
GET / HTTP/1.1
User-Agent: Wget/1.19.1 (linux-gnu)
Accept: */*
Accept-Encoding: identity
Host: drjoel.info
Connection: Keep-Alive
Cookie: __cfduid=d700f224676946c9ea07ab3eb7cf5cb861527424630
---request end---
HTTP request sent, awaiting response...
---response begin---
HTTP/1.1 302 Found
Date: Sun, 27 May 2018 12:37:11 GMT
Content-Type: text/html; charset=iso-8859-1
Transfer-Encoding: chunked
Connection: keep-alive
Location: https://drjoel.info/
Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
CF-RAY: 42188807c86caaaa-SIN
---response end---
302 Found
URI content encoding = ‘iso-8859-1’
Location: https://drjoel.info/ [following]
Skipping 204 bytes of body: [<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="https://drjoel.info/">here</a>.</p>
</body></html>
] done.
URI content encoding = None
Converted file name 'index.html' (UTF-8) -> 'index.html' (UTF-8)
--2018-05-27 18:07:11-- https://drjoel.info/
Reusing existing connection to drjoel.info:443.
Reusing fd 3.
```
This is being repeated about 20 times before wget aborts.
What's going wrong? What is the correct technique to enable SSL for a site on Wordpress? | By default meta values will be treated as strings, leading to the result that you get. As you can see from the [codex on `wp_query`](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters) you can force a comparison with different formats by defining a `meta_type`. Like this:
```
$query->set('meta_type','DATETIME');
``` |
304,571 | <p>Where is this CSS code?</p>
<p>I mean the <code>margin-top: 46px !important!;</code>
I need to change it to <code>1px</code> to rid of top margin. But i didn't found it in any theme's files.</p>
<p><strong>Note: I have searched the texts in all files using <a href="https://www.fileseek.ca/Download/" rel="nofollow noreferrer">FileSeek Pro</a></strong>. But didn't found anything. (even with Inspect Element in the Firefox)</p>
<p><a href="https://i.stack.imgur.com/wKtNt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wKtNt.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 304574,
"author": "Afnan abbasi",
"author_id": 144224,
"author_profile": "https://wordpress.stackexchange.com/users/144224",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what you can do about this:</p>\n\n<ul>\n<li>There may be a plugin which is loading this CSS so... | 2018/05/27 | [
"https://wordpress.stackexchange.com/questions/304571",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137466/"
] | Where is this CSS code?
I mean the `margin-top: 46px !important!;`
I need to change it to `1px` to rid of top margin. But i didn't found it in any theme's files.
**Note: I have searched the texts in all files using [FileSeek Pro](https://www.fileseek.ca/Download/)**. But didn't found anything. (even with Inspect Element in the Firefox)
[](https://i.stack.imgur.com/wKtNt.jpg) | The CSS code you're seeing is added by core of WP when admin bar is showing.
The function that outputs it is called [`_admin_bar_bump_cb()`](https://developer.wordpress.org/reference/functions/_admin_bar_bump_cb/) and it's called as hook on `wp_head`.
So how to get rid of it? Just remove this action from that hook:
```
function remove_admin_bar_bump() {
remove_action( 'wp_head', '_admin_bar_bump_cb' );
}
add_action('get_header', 'remove_admin_bar_bump');
```
Then you can add it in your CSS and use `body.admin-bar` as context if you want to add some styles only if the admin bar is visible. |
304,582 | <p>I want to hide widgets from home page when user logged in
I need help..</p>
| [
{
"answer_id": 304584,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": -1,
"selected": false,
"text": "<p>You can use third-party WordPress plugin \"<strong>AH Display Widgets</strong>\" to show/hide widget... | 2018/05/27 | [
"https://wordpress.stackexchange.com/questions/304582",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144363/"
] | I want to hide widgets from home page when user logged in
I need help.. | Probably simplest, though not always optimal, is to use CSS. In the vast majority of WordPress themes (ones assigning body classes), `logged-in` and `home` will be applied to the body tag automatically, when appropriate, and every widget gets a unique ID wherever it's displayed.
So, if I wanted to hide a given widget to logged in users, on the home page only, I'd use Chrome Inspector or other inspection tool to find the widget, find the ID assigned to its div tag, open the Customizer, open Additional CSS, and add the following code - say if the widget's ID turned out to be `text-24`:
```
/*CONCEAL text-24 WIDGET FROM LOGGED IN USERS ON HOME PAGE */
.home.logged-in #text-24 {
display: none;
}
```
(If I wanted it to remain visible to admin users - like myself - I'd need to do a little more work, for instance by adding a user class to body classes, or by using the `admin-bar` class if I happened to be hiding the Admin Bar already from users below Administrator level.) |
304,585 | <p>In a WordPress post, these multiple values exist for a custom metadata with the key "client"</p>
<pre><code>client=>Andy
client=>Johny
client=>April
</code></pre>
<p>I want to add a new metadata only if its value does not exist,</p>
<p>Result wanted:
client=>Andy will not be added because it already exists.</p>
<p>client=>Susan will be added because it does not exist
The post will now have these metadata values</p>
<pre><code>client=>Andy
client=>Johny
client=>April
client=>Susan
</code></pre>
| [
{
"answer_id": 304590,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>OK, so you have some code that uses <code>add_post_meta</code> and you want to make it add only unique... | 2018/05/27 | [
"https://wordpress.stackexchange.com/questions/304585",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132569/"
] | In a WordPress post, these multiple values exist for a custom metadata with the key "client"
```
client=>Andy
client=>Johny
client=>April
```
I want to add a new metadata only if its value does not exist,
Result wanted:
client=>Andy will not be added because it already exists.
client=>Susan will be added because it does not exist
The post will now have these metadata values
```
client=>Andy
client=>Johny
client=>April
client=>Susan
``` | OK, so you have some code that uses `add_post_meta` and you want to make it add only unique values.
The problem in here is that [`add_post_meta`](https://codex.wordpress.org/Function_Reference/add_post_meta) does exactly what it's name is saying - it adds a post meta value. There is 4th arg for that function that's called `unique`, but it work based on key and not value.
All of that means that you have to do the checking by yourself... So you'll have to get all meta values using [`get_post_meta`](https://developer.wordpress.org/reference/functions/get_post_meta/) for that key and check if there already exists a meta with given value...
So how can that look like?
Somewhere in your code is a line looking like this:
```
add_post_meta( $post_id, $meta_key, $meta_value );
```
Just change it to this:
```
$existing_pms = get_post_meta( $post_id, $meta_key );
if ( ! in_array( $meta_value, $existing_pms ) ) {
add_post_meta( $post_id, $meta_key, $meta_value );
}
``` |
304,601 | <p>all Inner pages are working fine but home page is not working admin is working fine </p>
<p>home page not working I have added wp-confing file </p>
<pre><code>define('WP_DEBUG', true);
define('WP_ALLOW_REPAIR', true);
define( 'WP_DEBUG_DISPLAY', true );
</code></pre>
<p>but not get any error </p>
<p>home page dispaly blank
I have check all plugin disable but still error are coming </p>
| [
{
"answer_id": 304590,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>OK, so you have some code that uses <code>add_post_meta</code> and you want to make it add only unique... | 2018/05/28 | [
"https://wordpress.stackexchange.com/questions/304601",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135085/"
] | all Inner pages are working fine but home page is not working admin is working fine
home page not working I have added wp-confing file
```
define('WP_DEBUG', true);
define('WP_ALLOW_REPAIR', true);
define( 'WP_DEBUG_DISPLAY', true );
```
but not get any error
home page dispaly blank
I have check all plugin disable but still error are coming | OK, so you have some code that uses `add_post_meta` and you want to make it add only unique values.
The problem in here is that [`add_post_meta`](https://codex.wordpress.org/Function_Reference/add_post_meta) does exactly what it's name is saying - it adds a post meta value. There is 4th arg for that function that's called `unique`, but it work based on key and not value.
All of that means that you have to do the checking by yourself... So you'll have to get all meta values using [`get_post_meta`](https://developer.wordpress.org/reference/functions/get_post_meta/) for that key and check if there already exists a meta with given value...
So how can that look like?
Somewhere in your code is a line looking like this:
```
add_post_meta( $post_id, $meta_key, $meta_value );
```
Just change it to this:
```
$existing_pms = get_post_meta( $post_id, $meta_key );
if ( ! in_array( $meta_value, $existing_pms ) ) {
add_post_meta( $post_id, $meta_key, $meta_value );
}
``` |
304,614 | <p>This is both a question on 'how to do this', as well as 'should I do this'. </p>
<p>I have the ACF-heavy site, where I would like to make the permalinks based on one of the ACF-fields (let's call it <code>foo</code>). If the <code>foo</code>-field has the value <code>123</code>, then I would like the permalink to that page to be <code>http://example.org/s123</code> (the <code>s</code> is to avoid the collision with post-id's in the permalink). If that URL is taken, then it should call it <code>http://example.org/s123-1</code> and so forth. </p>
<p>The ACF-field is set on a custom post type. And the site contains some important information, so I'd rather leave this functionality out, than to use a plugin. So it needs to be something that goes in the <code>functions.php</code>-file. </p>
<p>Is it possible to make this? And is it unwise to mess with WordPress' permalink structure (other that what is allowed in the permalink-settings-page)? </p>
<p><strong>Addition</strong></p>
<p>I can see that if you make CPT's have 'root'-permalinks, that that <a href="https://wordpress.stackexchange.com/questions/304738/permalinks-for-cpt-breaks-permalinks-to-pages">breaks the permalinks for posts and pages</a>. :-/</p>
<p>... I didn't know that it was this hard to let a CPT have a nice/simple permalink. </p>
| [
{
"answer_id": 304926,
"author": "DevLime",
"author_id": 144484,
"author_profile": "https://wordpress.stackexchange.com/users/144484",
"pm_score": 0,
"selected": false,
"text": "<p>This may be oversimplifying what I'm reading but rather than using ACF fields to control the permalink, to ... | 2018/05/28 | [
"https://wordpress.stackexchange.com/questions/304614",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128304/"
] | This is both a question on 'how to do this', as well as 'should I do this'.
I have the ACF-heavy site, where I would like to make the permalinks based on one of the ACF-fields (let's call it `foo`). If the `foo`-field has the value `123`, then I would like the permalink to that page to be `http://example.org/s123` (the `s` is to avoid the collision with post-id's in the permalink). If that URL is taken, then it should call it `http://example.org/s123-1` and so forth.
The ACF-field is set on a custom post type. And the site contains some important information, so I'd rather leave this functionality out, than to use a plugin. So it needs to be something that goes in the `functions.php`-file.
Is it possible to make this? And is it unwise to mess with WordPress' permalink structure (other that what is allowed in the permalink-settings-page)?
**Addition**
I can see that if you make CPT's have 'root'-permalinks, that that [breaks the permalinks for posts and pages](https://wordpress.stackexchange.com/questions/304738/permalinks-for-cpt-breaks-permalinks-to-pages). :-/
... I didn't know that it was this hard to let a CPT have a nice/simple permalink. | URLs made from CF
-----------------
Well, you can do this in many ways... One of them would be to use `parse_request` filter and modify it's behavior, but it can easily mess something up.
Another way would be to use `save_post` action and modify the posts `post_name`, so WordPress will work like normal, but the `post_name` will be generated based on your custom field and not based on title. This is the solution I would go for. Why? Because then you can use WP functions to assure that the links are unique...
So here's the code:
```
function change_post_name_on_save($post_ID, $post, $update ) {
global $wpdb;
$post = get_post( $post_ID );
$cf_post_name = wp_unique_post_slug( sanitize_title( 's' . get_post_field('foo', $post_ID), $post_ID ), $post_ID, $post->post_status, $post->post_type, $post->post_parent );
if ( ! in_array( $post->post_status, array( 'publish', 'trash' ) ) ) {
// no changes for post that is already published or trashed
$wpdb->update( $wpdb->posts, array( 'post_name' => $cf_post_name ), array( 'ID' => $post_ID ) );
clean_post_cache( $post_ID );
} elseif ( 'publish' == $post->post_status ) {
if ( $post->ID == $post->post_name ) {
// it was published just now
$wpdb->update( $wpdb->posts, array( 'post_name' => $cf_post_name ), array( 'ID' => $post_ID ) );
clean_post_cache( $post_ID );
}
}
}
add_action( 'save_post', 'change_post_name_on_save', 20, 3 );
```
It's not the prettiest one, because ACF fields are saved after the post, so you'll have to overwrite the `post_name` after the post is already saved. But it should work just fine.
CPTs in root
------------
And there's the second part of your question: How to make CPTs URLs without CPT slug...
WordPress uses Rewrite Rules to parse the request. It means that if the request matches one of the rule, it will be parsed using that rule.
The rule for pages is one of the last rule made to catch most of the requests that didn't match any earlier rules. So if you add your CPT without any slug, then pages rule won't be fired up...
One way to fix this is to register CPT with a slug and then change their links and WPs behavior. Here's the code:
```
function register_mycpt() {
$arguments = array(
'label' => 'MyCPT',
'public' => true,
'hierarchical' => false,
...
'has_archive' => false,
'rewrite' => true
);
register_post_type('mycpt', $arguments);
}
add_action( 'init', 'register_mycpt' );
```
Now the URLs for these posts will look like these:
```
http://example.com/mycpt/{post_name}/
```
But we can easily change this using `post_type_link` filter:
```
function change_mycpt_post_type_link( $url, $post, $leavename ) {
if ( 'mycpt' == $post->post_type ) {
$url = site_url('/') . $post->post_name . '/';
}
return $url;
}
add_filter( 'post_type_link', 'change_mycpt_post_type_link', 10, 3 );
```
Now the URLs will be correct, but... They won't work. They will be parsed using rewrite rule for pages and will cause 404 error (since there is no page with such URL). But we can fix that too:
```
function try_mycpt_before_page_in_parse_request( $wp ) {
global $wpdb;
if ( is_admin() ) return;
if ( array_key_exists( 'name', $wp->query_vars ) ) {
$post_name = $wp->query_vars['name'];
$id = $wpdb->get_var( $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_name = %s ",
'mycpt', $post_name
) );
if ( $id ) {
$wp->query_vars['mycpt'] = $post_name;
$wp->query_vars['post_type'] = 'mycpt';
}
}
}
add_action( 'parse_request', 'try_mycpt_before_page_in_parse_request' );
``` |
304,631 | <p><a href="https://i.stack.imgur.com/lY553.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lY553.jpg" alt="["></a>Home page on my wordpress site displays url code before showing the text of my featured posts. They display normally once the post is called in their respective pages so the issue is just on the home page. How do I prevent this from happening? Screenshot of the problem and address for my home page included here.<a href="http://myredsabbatical.com/" rel="nofollow noreferrer">2</a></p>
<pre><code> <?php
/**
* The template file for single post page.
*
* @package The Daybook
* @version 1.1
* @author Elite Layers <admin@elitelayers.com>
* @copyright Copyright (c) 2017, Elite Layers
* @link http://demo.elitelayers.com/thedaybook/
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License v2 or later
*/
get_header(); ?>
<div id="thedaybook-content" class="section">
<div class="block">
<div class="container">
<div class="row">
<?php /* insert affiliate disclosure */
$affiliate_disclaimer = get_field( 'ad_affiliate_disclaimer' );
if( in_array( 'yes', $affiliate_disclaimer ) ) { ?>
<p class="disclaimer"><strong>Heads up:</strong> My posts may contain affiliate links. If you buy something through one of those links, it won't cost you a penny more, but I might get a small commission to help to keep the lights on. I don't recommend any products I have not tried and love. <a class="nowrap" href="/legal/#affiliate"><small>Learn More &raquo;</small></a></p>
<?php } /* end affiliate disclosure */ ?>
<main id="main" class="<?php echo esc_attr(thedaybook_content_class());?>">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php get_template_part('parts/content','single'); ?>
<?php endwhile; ?>
<?php endif; ?>
</main>
<aside class="<?php echo esc_attr(thedaybook_sidebar_class());?>">
<?php get_sidebar();?>
</aside>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 304793,
"author": "Aurovrata",
"author_id": 52120,
"author_profile": "https://wordpress.stackexchange.com/users/52120",
"pm_score": 1,
"selected": false,
"text": "<p>If you <a href=\"https://codex.wordpress.org/Create_A_Network?\" rel=\"nofollow noreferrer\">install your W... | 2018/05/28 | [
"https://wordpress.stackexchange.com/questions/304631",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144393/"
] | [](https://i.stack.imgur.com/lY553.jpg)Home page on my wordpress site displays url code before showing the text of my featured posts. They display normally once the post is called in their respective pages so the issue is just on the home page. How do I prevent this from happening? Screenshot of the problem and address for my home page included here.[2](http://myredsabbatical.com/)
```
<?php
/**
* The template file for single post page.
*
* @package The Daybook
* @version 1.1
* @author Elite Layers <admin@elitelayers.com>
* @copyright Copyright (c) 2017, Elite Layers
* @link http://demo.elitelayers.com/thedaybook/
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License v2 or later
*/
get_header(); ?>
<div id="thedaybook-content" class="section">
<div class="block">
<div class="container">
<div class="row">
<?php /* insert affiliate disclosure */
$affiliate_disclaimer = get_field( 'ad_affiliate_disclaimer' );
if( in_array( 'yes', $affiliate_disclaimer ) ) { ?>
<p class="disclaimer"><strong>Heads up:</strong> My posts may contain affiliate links. If you buy something through one of those links, it won't cost you a penny more, but I might get a small commission to help to keep the lights on. I don't recommend any products I have not tried and love. <a class="nowrap" href="/legal/#affiliate"><small>Learn More »</small></a></p>
<?php } /* end affiliate disclosure */ ?>
<main id="main" class="<?php echo esc_attr(thedaybook_content_class());?>">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php get_template_part('parts/content','single'); ?>
<?php endwhile; ?>
<?php endif; ?>
</main>
<aside class="<?php echo esc_attr(thedaybook_sidebar_class());?>">
<?php get_sidebar();?>
</aside>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
``` | If you [install your WordPress Multisite](https://codex.wordpress.org/Create_A_Network?) (wpms) from scratch on the server this issue should not arise. However, if you have installed your wpms on a local machine first and then moved/copied the entire installation including the database to your server, then you have to ensure that,
1. you modify the domain in your database. I am not aware of any plugins that handle wpms installation till date. However, I use the [Interconnect/it search and replace db tool](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/). You need to search for 'localhost/folder' and replace with 'your-domain.com'. The best results is to ensure that you have a similar setup on the localhost as the server. If you are looking to setup wpms with subdomains, I suggest you create the child sites on the server after successful installation, and export/import pages/posts for the local machine to the server.
2. you also need to change the wp-config.php wpms settings,
`define('DOMAIN_CURRENT_SITE', 'localhost');
define('PATH_CURRENT_SITE', '/local-folder/');`
to
`define('DOMAIN_CURRENT_SITE', 'your-domain.com');
define('PATH_CURRENT_SITE', '/'); //or a sub-folder name is not a root installation.`
keep in mind that a lot of things can go wrong with such a procedure, and therefore it is always much simpler to install your wpms from scratch on the server and export/import content from one local to server.
[EDIT] In case you have created a fresh installation, then the likely issue is that you have either a problem with your [htaccess](https://codex.wordpress.org/Create_A_Network?#Enabling_the_Network) file or with the site\_url/home\_url [settings](https://codex.wordpress.org/Changing_The_Site_URL).
If you have misconfigured your site\_rule/home\_url in your dashboard then you need to change it directly in your database. Follow these [instructions](https://codex.wordpress.org/Changing_The_Site_URL#Changing_the_URL_directly_in_the_database), and assuming from your question that you have installed your WordPress files in the sub-folder `/wp`, make sure that,
1. If you want to access your site with: `domain.com` and your dashboard with `domain.com/wp-admin`, then
`siteurl = http://domain.com
home = http:/domain.com/wp`
2. If you want to access your site with `domain.com/wp` and your dashboard with `domain.com/wp/wp-admin` then,
`siteurl = http://domain.com/wp
home = http:/domain.com/wp`
[EDIT 2] One more possible reason is the browser caching. 301 redirects are cached by the browser, so clear your cache. You can inspect what kind of redirection your browser is experiencing by looking at the request trace on the [network tab of the inspector console](https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor). This can give you a clue as to where the redirection is being applied. |
304,709 | <p>I have several forms that send mails. Some of the mails should be sent as html, others as plain text. Right now I set the html option like this:</p>
<pre><code>add_action( 'phpmailer_init', 'mailer_config', 10, 1);
function mailer_config(PHPMailer $mailer){
$mailer->IsHTML(true);
}
</code></pre>
<p>But this implies that all the mails are sent as html. How to change this behaviour on a per-form/mail basis?</p>
| [
{
"answer_id": 304724,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an (untested) <em>PHPMailer</em> example to check for e.g. the <em>subject</em> and the <em>content ty... | 2018/05/29 | [
"https://wordpress.stackexchange.com/questions/304709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10381/"
] | I have several forms that send mails. Some of the mails should be sent as html, others as plain text. Right now I set the html option like this:
```
add_action( 'phpmailer_init', 'mailer_config', 10, 1);
function mailer_config(PHPMailer $mailer){
$mailer->IsHTML(true);
}
```
But this implies that all the mails are sent as html. How to change this behaviour on a per-form/mail basis? | Ok, following @birgire suggestions, I finally ended up using `wp_mail_content_type` filter in conjunction with an hidden field on my form. Php code is this:
```
add_filter( 'wp_mail_content_type', 'set_mailer_content_type' );
function set_mailer_content_type( $content_type ) {
if(isset($_POST['ishtmlform'])){ return 'text/html'; } // in-page/form hidden field
return 'text/plain';
}
```
This allowed me to have more than one form per-page, with different content type settings (for example one that sends text/plain and another that sends text/html, right in the same html page).
Side notes, slightly offtopic:
* internally, `wp_mail()` just sets `PhpMailer->isHTML(true)` if you set content type == `'text/html'`. You can find the source in `wp-includes/pluggable.php`
* Keep in mind that if you set `'text/html'`, than you have to send real html code, and by this I mean that message body must contain at least html, head, title and body tags, not just some plain text with some br or link in it, because otherwise it will likely marked as 'not plain text' and your mail indentified as spam. |
304,729 | <p>I have a hierarchical taxonomy <code>filter</code> that contains locations and genres for posts with the custom type <code>artist</code>:</p>
<pre><code>- Genre
-- Hip Hop
-- Trap
-- Rap
- Location
-- Europe
--- Germany
--- Sweden
--- Austria
-- Asia
--- China
--- Japan
--- Taiwan
</code></pre>
<p>Now I would like to use get_terms() to only get the Countries (children of 'Location' without children of their own). I thought this should work:</p>
<pre><code>$location_parent = get_term(123, 'filter');
$countries = get_terms(array(
'taxonomy' => $location_parent->taxonomy,
'hide_empty' => false,
'child_of' => $location_parent->term_id,
'childless' => true
));
</code></pre>
<p>...but it somehow doesn't. <code>child_of</code> and <code>childless</code> seem to get in each other's way. Any ideas?</p>
| [
{
"answer_id": 304858,
"author": "IvanMunoz",
"author_id": 143424,
"author_profile": "https://wordpress.stackexchange.com/users/143424",
"pm_score": 0,
"selected": false,
"text": "<p><strong>childless</strong> means:</p>\n\n<p>(boolean) Returns terms that have no children if taxonomy is ... | 2018/05/29 | [
"https://wordpress.stackexchange.com/questions/304729",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/18713/"
] | I have a hierarchical taxonomy `filter` that contains locations and genres for posts with the custom type `artist`:
```
- Genre
-- Hip Hop
-- Trap
-- Rap
- Location
-- Europe
--- Germany
--- Sweden
--- Austria
-- Asia
--- China
--- Japan
--- Taiwan
```
Now I would like to use get\_terms() to only get the Countries (children of 'Location' without children of their own). I thought this should work:
```
$location_parent = get_term(123, 'filter');
$countries = get_terms(array(
'taxonomy' => $location_parent->taxonomy,
'hide_empty' => false,
'child_of' => $location_parent->term_id,
'childless' => true
));
```
...but it somehow doesn't. `child_of` and `childless` seem to get in each other's way. Any ideas? | OK, so this is what I came up with:
```
function get_childless_term_children( $parent_id, $taxonomy ) {
// get all childless $terms of this $taxonomy
$terms = get_terms(array(
'taxonomy' => $taxonomy,
'childless' => true,
));
foreach( $terms as $key => $term ) {
// remove $terms that aren't descendants (= children) of $parent_id
if( !in_array( $parent_id, get_ancestors( $term->term_id, $taxonomy ) ) ) {
unset( $terms[$key] );
}
}
return $terms;
}
```
What this does: Get all childless terms that are children of `$parent_id`. |
304,734 | <p>How to format the <strong>meta_value</strong> column's json from the <strong>post_meta</strong> table in wordpress to get only the proper values.</p>
<p>I have the value something like:</p>
<pre><code>$posttype= Mage::helper('wordpress')->getPostType2();
$posttype = explode(',',$posttype);
echo 'Post type:';
echo '<pre>';print_r($posttype);
</code></pre>
<p><strong>Output:</strong></p>
<blockquote>
<p>Array ( [0] => a:12:{s:3:"key";s:19:"field_57bdd83367bb1";s:5:"label";s:4:"Type";s:4:"name";s:4:"type";s:4:"type";s:6:"select";s:12:"instructions";s:0:"";s:8:"required";s:1:"0";s:7:"choices";a:7:{s:7:"Article";s:7:"article";s:9:"Blog Post";s:9:"blog_post";s:16:"Artists & Makers";s:16:"artistsandmakers";s:6:"Videos";s:6:"videos";s:12:"In The Press";s:12:"in_the_press";s:14:"Did You Know ?";s:12:"did_you_know";s:14:"Glossary A - Z";s:8:"glossary";}s:13:"default_value";s:39:"blog_post in_the_press did_you_know ";s:10:"allow_null";s:1:"0";s:8:"multiple";s:1:"1";s:17:"conditional_logic";a:3:{s:6:"status";s:1:"0";s:5:"rules";a:1:{i:0;a:2:{s:5:"field";s:4:"null";s:8:"operator";s:2:"==";}}s:8:"allorany";s:3:"all";}s:8:"order_no";i:0;} )</p>
</blockquote>
<p>I need to get only the values like in a dropdown</p>
<p><strong>Article</strong></p>
<p><strong>Blog Post</strong></p>
<p><strong>Artists & Makers</strong></p>
<pre><code><div class="category-list">
<?php // echo $this->__('All Types') ?>
<select id="blogcat">
<option><?php echo $this->__('Article Type') ?></option>
<option value=""><?php echo $this->__('All Types..') ?></option>
<option value="<?php echo $posttype;?>"> </option>
<?php foreach($posttype as $value) { ?>
<?php $namecheck = preg_replace('/\s*/', '', strtolower($value['name']));
if ($value['slug'] != 'artists-and-makers'&&$namecheck != 'artistsandmakers') : ?>
<option value="<?php echo $value['slug'];?>"><?php echo $value['name'];?> </option>
<?php echo 'TRUE';?>
<?php endif; ?>
<?php } ?>
<option value="events"><?php echo $this->__('Events') ?></option>
</select>
</div>
</code></pre>
| [
{
"answer_id": 304772,
"author": "SeventhSteel",
"author_id": 17276,
"author_profile": "https://wordpress.stackexchange.com/users/17276",
"pm_score": 2,
"selected": false,
"text": "<p>Part 1 - To remove the double quotes/extra characters:</p>\n\n<p>Instead of trying regular expressions, ... | 2018/05/29 | [
"https://wordpress.stackexchange.com/questions/304734",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144468/"
] | How to format the **meta\_value** column's json from the **post\_meta** table in wordpress to get only the proper values.
I have the value something like:
```
$posttype= Mage::helper('wordpress')->getPostType2();
$posttype = explode(',',$posttype);
echo 'Post type:';
echo '<pre>';print_r($posttype);
```
**Output:**
>
> Array ( [0] => a:12:{s:3:"key";s:19:"field\_57bdd83367bb1";s:5:"label";s:4:"Type";s:4:"name";s:4:"type";s:4:"type";s:6:"select";s:12:"instructions";s:0:"";s:8:"required";s:1:"0";s:7:"choices";a:7:{s:7:"Article";s:7:"article";s:9:"Blog Post";s:9:"blog\_post";s:16:"Artists & Makers";s:16:"artistsandmakers";s:6:"Videos";s:6:"videos";s:12:"In The Press";s:12:"in\_the\_press";s:14:"Did You Know ?";s:12:"did\_you\_know";s:14:"Glossary A - Z";s:8:"glossary";}s:13:"default\_value";s:39:"blog\_post in\_the\_press did\_you\_know ";s:10:"allow\_null";s:1:"0";s:8:"multiple";s:1:"1";s:17:"conditional\_logic";a:3:{s:6:"status";s:1:"0";s:5:"rules";a:1:{i:0;a:2:{s:5:"field";s:4:"null";s:8:"operator";s:2:"==";}}s:8:"allorany";s:3:"all";}s:8:"order\_no";i:0;} )
>
>
>
I need to get only the values like in a dropdown
**Article**
**Blog Post**
**Artists & Makers**
```
<div class="category-list">
<?php // echo $this->__('All Types') ?>
<select id="blogcat">
<option><?php echo $this->__('Article Type') ?></option>
<option value=""><?php echo $this->__('All Types..') ?></option>
<option value="<?php echo $posttype;?>"> </option>
<?php foreach($posttype as $value) { ?>
<?php $namecheck = preg_replace('/\s*/', '', strtolower($value['name']));
if ($value['slug'] != 'artists-and-makers'&&$namecheck != 'artistsandmakers') : ?>
<option value="<?php echo $value['slug'];?>"><?php echo $value['name'];?> </option>
<?php echo 'TRUE';?>
<?php endif; ?>
<?php } ?>
<option value="events"><?php echo $this->__('Events') ?></option>
</select>
</div>
``` | Part 1 - To remove the double quotes/extra characters:
Instead of trying regular expressions, since the output is somewhat predictable, I would try the following instead of the getCapitalLetters function:
```
function strip_cruft( $str ) {
$str = str_replace( '";s', '', $str );
$str = str_replace( '"', '', $str );
return $str;
}
```
Part 2 - To output a populated dropdown:
Use the above function and remember to add a value in between the opening and closing tags:
```
<?php foreach($posttype as $post) {
$post = strip_cruft( $post ); ?>
<option value="<?php echo esc_attr( $post ); ?>">
<?php echo esc_html( $post ); ?>
</option>
<?php } ?>
```
If you'd like them to be all lowercase, you can use WordPress's `sanitize_title` function. |
304,735 | <p>I want a non-WordPress page that can be accessed from a parent directory that is a WordPress page.</p>
<p>For example, I want <code>http://example.com/city/</code> to be a WordPress page. However, I want to upload a non-WordPress page into the folder <code>/city/pricing/</code> on the server. When I try this, I can go to <code>http://example.com/city/pricing/</code> and it works, but then WordPress won't load <code>http://example.com/city/</code> because the server sees the <code>/city/</code> directory and is looking for an index file.</p>
<p>Is it even possible for me to create <code>/city/</code> as a WordPress page, but have <code>/city/pricing/</code> as a non-WordPress, static HTML page? If not, I can a different solution, but I wanted to see if this is possible first.</p>
| [
{
"answer_id": 304739,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it by adding a rule to htaccess that will load that page for that specific URL, and add the ru... | 2018/05/29 | [
"https://wordpress.stackexchange.com/questions/304735",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130837/"
] | I want a non-WordPress page that can be accessed from a parent directory that is a WordPress page.
For example, I want `http://example.com/city/` to be a WordPress page. However, I want to upload a non-WordPress page into the folder `/city/pricing/` on the server. When I try this, I can go to `http://example.com/city/pricing/` and it works, but then WordPress won't load `http://example.com/city/` because the server sees the `/city/` directory and is looking for an index file.
Is it even possible for me to create `/city/` as a WordPress page, but have `/city/pricing/` as a non-WordPress, static HTML page? If not, I can a different solution, but I wanted to see if this is possible first. | As @MarkKaplun suggests, it would be preferable to store this non-WordPress file in a different area of the filesystem altogether and rewrite the URL in `.htaccess`. Instead of mimicking the WordPress URL in the physical directory structure - which will likely only cause you (more) problems (not least that you would need to override the WordPress front-controller).
For example, instead of saving your non-WordPress page at `/city/pricing/index.php`, save it at `/non-wordress/city-pricing.php` (for example) or `/non-wordress/city/pricing/index.php` (if it helps, in development, to copy the path structure - but this makes no difference to the resulting URL, since this directory structure is completely hidden from the end user).
Then in `.htaccess` *before* the WordPress front-controller (ie. *before* the `# BEGIN WordPress` section) you can do something like:
```
RewriteRule ^city/pricing/$ /non-wordpress/city-pricing.php [L]
```
This *internally rewrites* `/city/pricing/` to `/non-wordpress/city-pricing.php` - this is entirely hidden from the end user.
But stress, this *must* go before the WordPress front-controller, otherwise you'll simply get a 404. |
304,738 | <p>I have a CPT that I would like to have the 'root'-permalinks:</p>
<p>So for the page: 'Foo Bar' I would like that to have the URL:</p>
<pre><code>https://example.org/foo-bar
</code></pre>
<p>I've found out that I achieve this by registering the CPT with the following line in the <code>args</code> for <code>register_post_type( 'my_CPT', $args );</code>:</p>
<pre><code>'rewrite' => array('slug' => '/', 'with_front' => false)
</code></pre>
<p>However... When I add that, then my permalinks for my pages don't work. I would ideally give them these permalinks:</p>
<pre><code>https://example.org/page/some-page
</code></pre>
<p>How do I do that?</p>
| [
{
"answer_id": 304742,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Pages are hardcoded to be the default parsing possibility to any URL (or to say it differently, if nothin... | 2018/05/29 | [
"https://wordpress.stackexchange.com/questions/304738",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128304/"
] | I have a CPT that I would like to have the 'root'-permalinks:
So for the page: 'Foo Bar' I would like that to have the URL:
```
https://example.org/foo-bar
```
I've found out that I achieve this by registering the CPT with the following line in the `args` for `register_post_type( 'my_CPT', $args );`:
```
'rewrite' => array('slug' => '/', 'with_front' => false)
```
However... When I add that, then my permalinks for my pages don't work. I would ideally give them these permalinks:
```
https://example.org/page/some-page
```
How do I do that? | Pages are hardcoded to be the default parsing possibility to any URL (or to say it differently, if nothing else matches, wordpress will try to find a page there).
Therefor it is unwise to put permalink structure with no "prefix", but if you really want it that way, just add a page with a "page" slug and make all other pages its sons. This will work great if you do not have many pages and you will have zero code that hacks at parsing and permalink generation to worry about ;) |
304,818 | <p>I developed my theme. and I set header.php. </p>
<p>And in Header.php, I set like this.</p>
<pre><code><title>My Site Name</title>
</code></pre>
<p>This makes search-engine confuse. Every page and posts title in head tag are same with site-name. </p>
<p>Do you have tips to set the title and meta tag for SEO? </p>
| [
{
"answer_id": 304828,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>To properly set the title tag in a theme you shouldn't put it in header.php manually. Your header.php sh... | 2018/05/30 | [
"https://wordpress.stackexchange.com/questions/304818",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133185/"
] | I developed my theme. and I set header.php.
And in Header.php, I set like this.
```
<title>My Site Name</title>
```
This makes search-engine confuse. Every page and posts title in head tag are same with site-name.
Do you have tips to set the title and meta tag for SEO? | To properly set the title tag in a theme you shouldn't put it in header.php manually. Your header.php should have `wp_head()` somewhere between `<head></head>`, then you can let WordPress set the title tag by [adding support for `title-tag` to your theme](https://codex.wordpress.org/Title_Tag#Adding_Theme_Support):
```
function wpse_304818_theme_setup() {
add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'wpse_304818_theme_setup' );
``` |
304,839 | <p>I have a CPT called "domaines" (its like vineyards in french).
My site have 2 languages (french and english), configured with Polylang for <strong>pages</strong> and <strong>menus</strong> translation.</p>
<p>I don't want to use Polylang features for my "domaine" CPT translations to avoid duplicating posts : I want to use ACF for translations (with a condition on the current language inside the template) because there is only 3 fields to translate (and I have more than 1000 posts).</p>
<p>I want an URL like : www.domainame.com/<strong>en</strong>/domaines/my_slug
The www.domainame.com/domaines/my_slug already exists (it's my original post in french).</p>
<p>There is a way to create a "virtual" page on "/en/" with the same content as "/" ?</p>
<p>Thank you</p>
| [
{
"answer_id": 304828,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>To properly set the title tag in a theme you shouldn't put it in header.php manually. Your header.php sh... | 2018/05/30 | [
"https://wordpress.stackexchange.com/questions/304839",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73871/"
] | I have a CPT called "domaines" (its like vineyards in french).
My site have 2 languages (french and english), configured with Polylang for **pages** and **menus** translation.
I don't want to use Polylang features for my "domaine" CPT translations to avoid duplicating posts : I want to use ACF for translations (with a condition on the current language inside the template) because there is only 3 fields to translate (and I have more than 1000 posts).
I want an URL like : www.domainame.com/**en**/domaines/my\_slug
The www.domainame.com/domaines/my\_slug already exists (it's my original post in french).
There is a way to create a "virtual" page on "/en/" with the same content as "/" ?
Thank you | To properly set the title tag in a theme you shouldn't put it in header.php manually. Your header.php should have `wp_head()` somewhere between `<head></head>`, then you can let WordPress set the title tag by [adding support for `title-tag` to your theme](https://codex.wordpress.org/Title_Tag#Adding_Theme_Support):
```
function wpse_304818_theme_setup() {
add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'wpse_304818_theme_setup' );
``` |
304,859 | <pre><code><?php
namespace wp_gdpr_wc\controller;
use wp_gdpr\lib\Gdpr_Container;
use wp_gdpr_wc\lib\Gdpr_Wc_Translation;
use wp_gdpr_wc\model\Wc_Model;
class Controller_Wc {
const REQUEST_TYPE = 3;
/**
* Controller_Form_Submit constructor.
*/
public function __construct() {
add_action( 'woocommerce_after_order_notes', array( $this, 'checkout_consent_checkbox' ) );
}
</code></pre>
<p>Usually I could remove it like this <code>remove_action( 'woocommerce_after_order_notes', 'Controller_Wc::checkout_consent_checkbox');</code> but here seems like it's not working.</p>
| [
{
"answer_id": 304861,
"author": "Alex",
"author_id": 142375,
"author_profile": "https://wordpress.stackexchange.com/users/142375",
"pm_score": 5,
"selected": true,
"text": "<p>I did it using this function <code>remove_filters_with_method_name( 'woocommerce_after_order_notes', 'checkout_... | 2018/05/30 | [
"https://wordpress.stackexchange.com/questions/304859",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142375/"
] | ```
<?php
namespace wp_gdpr_wc\controller;
use wp_gdpr\lib\Gdpr_Container;
use wp_gdpr_wc\lib\Gdpr_Wc_Translation;
use wp_gdpr_wc\model\Wc_Model;
class Controller_Wc {
const REQUEST_TYPE = 3;
/**
* Controller_Form_Submit constructor.
*/
public function __construct() {
add_action( 'woocommerce_after_order_notes', array( $this, 'checkout_consent_checkbox' ) );
}
```
Usually I could remove it like this `remove_action( 'woocommerce_after_order_notes', 'Controller_Wc::checkout_consent_checkbox');` but here seems like it's not working. | I did it using this function `remove_filters_with_method_name( 'woocommerce_after_order_notes', 'checkout_consent_checkbox', 10 );`
```
function remove_filters_with_method_name( $hook_name = '', $method_name = '', $priority = 0 ) {
global $wp_filter;
// Take only filters on right hook name and priority
if ( ! isset( $wp_filter[ $hook_name ][ $priority ] ) || ! is_array( $wp_filter[ $hook_name ][ $priority ] ) ) {
return false;
}
// Loop on filters registered
foreach ( (array) $wp_filter[ $hook_name ][ $priority ] as $unique_id => $filter_array ) {
// Test if filter is an array ! (always for class/method)
if ( isset( $filter_array['function'] ) && is_array( $filter_array['function'] ) ) {
// Test if object is a class and method is equal to param !
if ( is_object( $filter_array['function'][0] ) && get_class( $filter_array['function'][0] ) && $filter_array['function'][1] == $method_name ) {
// Test for WordPress >= 4.7 WP_Hook class (https://make.wordpress.org/core/2016/09/08/wp_hook-next-generation-actions-and-filters/)
if ( is_a( $wp_filter[ $hook_name ], 'WP_Hook' ) ) {
unset( $wp_filter[ $hook_name ]->callbacks[ $priority ][ $unique_id ] );
} else {
unset( $wp_filter[ $hook_name ][ $priority ][ $unique_id ] );
}
}
}
}
return false;
}
``` |
304,860 | <p>Is there anyway I can add the user ID to the woocommerce customer dashboard?
thanks!</p>
| [
{
"answer_id": 304863,
"author": "Steve",
"author_id": 23132,
"author_profile": "https://wordpress.stackexchange.com/users/23132",
"pm_score": 1,
"selected": false,
"text": "<p>As with most mature plugins, Woocommerce offers a number of hooks to easily customize content such as the custo... | 2018/05/30 | [
"https://wordpress.stackexchange.com/questions/304860",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144494/"
] | Is there anyway I can add the user ID to the woocommerce customer dashboard?
thanks! | WooCommerce doesn't provide any such hook to display User ID on the dashbaord.
But you can add it by overwriting dashboard template into your theme file. You can view in brief of how to overwrite templates from below WooCommerce reference link.
<https://docs.woocommerce.com/document/template-structure/>
You need to copy template **dashboard.php** file from WooCommerce plugin template to **woocommerce/myaccount/** folder in your theme.
You can use a code to display **User ID** anywhere on the dashboard page.
```
<?php echo esc_html( $current_user->ID ); ?>
``` |
304,872 | <p>I've checked multiple questions and can't seem to find the answer.</p>
<p>How can I update a list of URLs to either include "-google" at the end of the permalink, or set the URL to a custom url. My list of URLs is 100+ and I have what the URL is and what the URL should be. </p>
<p><strong>For example:</strong></p>
<pre><code>https://examplesite.com/customer/customer-name
</code></pre>
<p><em>change to:</em></p>
<pre><code>https://examplesite.com/customer/google-customer-name
</code></pre>
<p><strong>I have already updated the URLs in the post_content using this below:</strong></p>
<pre><code>UPDATE wp_posts SET post_content = REPLACE (post_content,'https://examplesite.com/customer/customer-name','https://examplesite.com/customer/google-customer-name');
</code></pre>
<p>That worked for the post content, but it's not a solution to update the permalink of those pages, which is what I need.</p>
| [
{
"answer_id": 304863,
"author": "Steve",
"author_id": 23132,
"author_profile": "https://wordpress.stackexchange.com/users/23132",
"pm_score": 1,
"selected": false,
"text": "<p>As with most mature plugins, Woocommerce offers a number of hooks to easily customize content such as the custo... | 2018/05/30 | [
"https://wordpress.stackexchange.com/questions/304872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144544/"
] | I've checked multiple questions and can't seem to find the answer.
How can I update a list of URLs to either include "-google" at the end of the permalink, or set the URL to a custom url. My list of URLs is 100+ and I have what the URL is and what the URL should be.
**For example:**
```
https://examplesite.com/customer/customer-name
```
*change to:*
```
https://examplesite.com/customer/google-customer-name
```
**I have already updated the URLs in the post\_content using this below:**
```
UPDATE wp_posts SET post_content = REPLACE (post_content,'https://examplesite.com/customer/customer-name','https://examplesite.com/customer/google-customer-name');
```
That worked for the post content, but it's not a solution to update the permalink of those pages, which is what I need. | WooCommerce doesn't provide any such hook to display User ID on the dashbaord.
But you can add it by overwriting dashboard template into your theme file. You can view in brief of how to overwrite templates from below WooCommerce reference link.
<https://docs.woocommerce.com/document/template-structure/>
You need to copy template **dashboard.php** file from WooCommerce plugin template to **woocommerce/myaccount/** folder in your theme.
You can use a code to display **User ID** anywhere on the dashboard page.
```
<?php echo esc_html( $current_user->ID ); ?>
``` |
304,878 | <p>I'm trying to display a list of posts from a certain category that I can paginate through. Since I've read that <code>get_posts()</code> doesn't support pagination but <code>WP_Query</code> does, I'm using the latter.</p>
<p>Here's my query:</p>
<pre><code> $mainPosts = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 1,
'category_name' => 'main',
));
</code></pre>
<p>I originally has <code>posts_per_page</code> set to 10, but I've set to 1. No matter what I try, I get an error similar to the following:</p>
<pre><code>Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 140513280 bytes) in /app/public/wp-includes/functions.php on line 3730
</code></pre>
<p>I understand that this would happen if I am trying to pull thousands of posts or performing some kind of very expensive query, but this category has a total of 5-6 posts. I can <code>print_r</code> the returned object and see that it's only pulling the single post that I specified.</p>
<p>I should note that this only occurs if I try to run <code>while ($mainPosts->have_posts()) { ... }</code>. </p>
<p>Here's the full code of what I am doing with the query:</p>
<pre><code>if ($mainPosts->have_posts()) {
while ($mainPosts->have_posts()) {
$postItemImage = the_post_thumbnail_url();
$postPermalink = the_permalink();
$postTitle = the_title();
$postDay = the_date('F jS Y');
$postExcerpt = the_excerpt();
echo "<div class='row post-item'><div class='col-6 post-item-left'>
<div class='post-item-image' style='background-image:url(\"{$postItemImage}\")'></div></div>
<div class='col-6 post-item-detail'><h3>{$postTitle}</h3><div class='post-item-detail-header'>{$postDay}</div>
<div class='post-item-detail-main'>{$postExcerpt}</div><a href='{$postPermalink}'>Read more</a></div></div>";
}
}
</code></pre>
<p>What am I doing wrong here and how can I list the few posts using <code>WP_Query</code> without having this memory allocation issue?</p>
<p><strong>Edit:</strong> I've found that using a <code>break;</code> seems to resolve the memory allocation issue, however this is of course undesirable if I intend to run the loop more than once. </p>
| [
{
"answer_id": 304879,
"author": "idpokute",
"author_id": 87895,
"author_profile": "https://wordpress.stackexchange.com/users/87895",
"pm_score": 1,
"selected": false,
"text": "<p>Probably some of your plugins use memory. If I were you, I would turn off all the plugins and try it again. ... | 2018/05/30 | [
"https://wordpress.stackexchange.com/questions/304878",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81297/"
] | I'm trying to display a list of posts from a certain category that I can paginate through. Since I've read that `get_posts()` doesn't support pagination but `WP_Query` does, I'm using the latter.
Here's my query:
```
$mainPosts = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 1,
'category_name' => 'main',
));
```
I originally has `posts_per_page` set to 10, but I've set to 1. No matter what I try, I get an error similar to the following:
```
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 140513280 bytes) in /app/public/wp-includes/functions.php on line 3730
```
I understand that this would happen if I am trying to pull thousands of posts or performing some kind of very expensive query, but this category has a total of 5-6 posts. I can `print_r` the returned object and see that it's only pulling the single post that I specified.
I should note that this only occurs if I try to run `while ($mainPosts->have_posts()) { ... }`.
Here's the full code of what I am doing with the query:
```
if ($mainPosts->have_posts()) {
while ($mainPosts->have_posts()) {
$postItemImage = the_post_thumbnail_url();
$postPermalink = the_permalink();
$postTitle = the_title();
$postDay = the_date('F jS Y');
$postExcerpt = the_excerpt();
echo "<div class='row post-item'><div class='col-6 post-item-left'>
<div class='post-item-image' style='background-image:url(\"{$postItemImage}\")'></div></div>
<div class='col-6 post-item-detail'><h3>{$postTitle}</h3><div class='post-item-detail-header'>{$postDay}</div>
<div class='post-item-detail-main'>{$postExcerpt}</div><a href='{$postPermalink}'>Read more</a></div></div>";
}
}
```
What am I doing wrong here and how can I list the few posts using `WP_Query` without having this memory allocation issue?
**Edit:** I've found that using a `break;` seems to resolve the memory allocation issue, however this is of course undesirable if I intend to run the loop more than once. | Your query looks OK, so I doubt that it will cause any problems. But then... Let's take a look at your loop:
```
if ($mainPosts->have_posts()) {
while ($mainPosts->have_posts()) {
$postItemImage = the_post_thumbnail_url();
...
echo "...";
}
}
```
First of all you don't have any else in there, so there is no point in this if. But there is even bigger problem with this loop...
It will be an infinite loop, because there is no `$mainPosts->the_post()`, so it doesn't "consume" posts, so there are always all of them when checking loop condition.
This will work fine:
```
while ($mainPosts->have_posts()) {
$mainPosts->the_post();
$postItemImage = the_post_thumbnail_url();
...
echo "...";
}
``` |
304,882 | <p>First let me know you that I have made a blog before and I have customize it according to the post format but I have customize it on the blog main page i.e. index.php.</p>
<p>Now I am making a another blog and I want to customize it by post format but this time I want to customize the post on the read page i.e. single.php (according to post type).</p>
<p>Is it possible to make it or we can only customize the post format on index.php.</p>
<p><strong>Update:</strong> </p>
<p><strong>Sorry:-</strong></p>
<p>Its post format not post type</p>
| [
{
"answer_id": 304879,
"author": "idpokute",
"author_id": 87895,
"author_profile": "https://wordpress.stackexchange.com/users/87895",
"pm_score": 1,
"selected": false,
"text": "<p>Probably some of your plugins use memory. If I were you, I would turn off all the plugins and try it again. ... | 2018/05/30 | [
"https://wordpress.stackexchange.com/questions/304882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108146/"
] | First let me know you that I have made a blog before and I have customize it according to the post format but I have customize it on the blog main page i.e. index.php.
Now I am making a another blog and I want to customize it by post format but this time I want to customize the post on the read page i.e. single.php (according to post type).
Is it possible to make it or we can only customize the post format on index.php.
**Update:**
**Sorry:-**
Its post format not post type | Your query looks OK, so I doubt that it will cause any problems. But then... Let's take a look at your loop:
```
if ($mainPosts->have_posts()) {
while ($mainPosts->have_posts()) {
$postItemImage = the_post_thumbnail_url();
...
echo "...";
}
}
```
First of all you don't have any else in there, so there is no point in this if. But there is even bigger problem with this loop...
It will be an infinite loop, because there is no `$mainPosts->the_post()`, so it doesn't "consume" posts, so there are always all of them when checking loop condition.
This will work fine:
```
while ($mainPosts->have_posts()) {
$mainPosts->the_post();
$postItemImage = the_post_thumbnail_url();
...
echo "...";
}
``` |
304,906 | <p>I've registered a Customizer section called "Other Logos" and have used the <code>WP_Customize_Image_Control()</code> object to upload images that show up in the Customizer. I'm customizing Twentyseventeen in a child-theme. </p>
<p>When I try to use <code>get_theme_mod()</code> or <code>get_option()</code>, to return an <code>src</code> for the <code>img</code> tag, I am not getting a result I understand.</p>
<p>A <code>var_dump()</code> of a test variable seems to show <code>get_theme_mod()</code> OR <code>get_option()</code> returning an array Object instead of a string.
The object contains the correct image src URL that I'm looking to input in my theme files but I'm not sure how to get at it at this point. </p>
<p>From my <code>functions.php</code></p>
<pre><code>function nscoctwentyseventeen_customize_register( $wp_customize ) {
$wp_customize->add_section(
'nscoctwentyseventeen_other_logos',
array(
'title' => __( 'Other Logos', 'nscoctwentyseventeen' ), //2nd arg matches child theme name
'capability' => 'edit_theme_options',
'priority' => 6,
'description' => __('Add other logos here', 'nscoctwentyseventeen'), //2nd arg matches child theme name
)
);
$wp_customize->add_setting('nscoctwentyseventeen_punchout_logo[image_upload_test]', array(
'default' => 'image.jpg',
'capability' => 'edit_theme_options',
'type' => 'option',
));
$wp_customize->add_setting('nscoctwentyseventeen_stamp_logo[image_upload_test]', array(
'default' => 'image.jpg',
'capability' => 'edit_theme_options',
'type' => 'option',
));
$wp_customize->add_setting('nscoctwentyseventeen_color_logo[image_upload_test]', array(
'default' => 'image.jpg',
'capability' => 'edit_theme_options',
'type' => 'option',
));
// Add a control to upload the punchout logo
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'nscoctwentyseventeen_punchout_logo',
array(
'width' => 250,
'height' => 250,
'flex-width' => true,
'selector' => '.punchout_logo',
'label' => __('Upload Punchout Logo', 'nscoctwentyseventeen'),
'section' => 'nscoctwentyseventeen_other_logos',
'settings' => 'nscoctwentyseventeen_punchout_logo[image_upload_test]',
)
)
);
// Add a control to upload the stamp logo
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'nscoctwentyseventeen_stamp_logo',
array(
'width' => 250,
'height' => 250,
'flex-width' => true,
'selector' => '.stamp_logo',
'label' => __('Upload Stamp Logo', 'nscoctwentyseventeen'),
'section' => 'nscoctwentyseventeen_other_logos',
'settings' => 'nscoctwentyseventeen_stamp_logo[image_upload_test]',
)
)
);
// Add a control to upload the punchout logo
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'nscoctwentyseventeen_color_logo',
array(
'width' => 250,
'height' => 250,
'flex-width' => true,
'selector' => '.color_logo',
'label' => __('Upload Color Logo', 'nscoctwentyseventeen'),
'section' => 'nscoctwentyseventeen_other_logos',
'settings' => 'nscoctwentyseventeen_color_logo[image_upload_test]',
)
)
);
}
add_action( 'customize_register', 'nscoctwentyseventeen_customize_register' );
</code></pre>
<p>In the theme file <code>footer.php</code>:</p>
<pre><code><div class="widget-column custom-branding">
<?php
$colorlogoURL = get_option( 'nscoctwentyseventeen_color_logo' );
echo var_dump($colorlogoURL);
?>
<img src="<?php echo $colorlogoURL?>">
</div>
</code></pre>
<p>This results in the following output.</p>
<p>From <code>var_dump()</code>:</p>
<pre><code>array(1) { ["image_upload_test"]=> string(78) "https://www.example.com/wp-content/uploads/2018/02/myimage.png" }
</code></pre>
<p>In html: </p>
<pre><code><img src="&lt;br /&gt;&#10;&lt;b&gt;Notice&lt;/b&gt;: Undefined offset: 1 in &lt;b&gt;/home/user/public_html/example/wp1/wp-content/themes/nscoctwentyseventeen/template-parts/footer/footer-widgets.php&lt;/b&gt; on line &lt;b&gt;25&lt;/b&gt;&lt;br /&gt;&#10;">
</code></pre>
<p>I've used <code>esc_url()</code> on the variable without any change.
I've tried <code>'type' => "theme_mod"</code>, in lieu of <code>'type' => "option"</code>. </p>
<p>There is something here that is incredibly simple that I must be missing, and a ton of searching the codex, and forum I'm at a loss to figure out this particular problem. </p>
<p>I'm using Wordpress 4.9.6, with PHP 7.1</p>
| [
{
"answer_id": 304923,
"author": "eSparkBiz Team",
"author_id": 144575,
"author_profile": "https://wordpress.stackexchange.com/users/144575",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Step 1:</strong> Click on setting option</p>\n\n<p><a href=\"https://i.stack.imgur.com/dqm3G... | 2018/05/30 | [
"https://wordpress.stackexchange.com/questions/304906",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143897/"
] | I've registered a Customizer section called "Other Logos" and have used the `WP_Customize_Image_Control()` object to upload images that show up in the Customizer. I'm customizing Twentyseventeen in a child-theme.
When I try to use `get_theme_mod()` or `get_option()`, to return an `src` for the `img` tag, I am not getting a result I understand.
A `var_dump()` of a test variable seems to show `get_theme_mod()` OR `get_option()` returning an array Object instead of a string.
The object contains the correct image src URL that I'm looking to input in my theme files but I'm not sure how to get at it at this point.
From my `functions.php`
```
function nscoctwentyseventeen_customize_register( $wp_customize ) {
$wp_customize->add_section(
'nscoctwentyseventeen_other_logos',
array(
'title' => __( 'Other Logos', 'nscoctwentyseventeen' ), //2nd arg matches child theme name
'capability' => 'edit_theme_options',
'priority' => 6,
'description' => __('Add other logos here', 'nscoctwentyseventeen'), //2nd arg matches child theme name
)
);
$wp_customize->add_setting('nscoctwentyseventeen_punchout_logo[image_upload_test]', array(
'default' => 'image.jpg',
'capability' => 'edit_theme_options',
'type' => 'option',
));
$wp_customize->add_setting('nscoctwentyseventeen_stamp_logo[image_upload_test]', array(
'default' => 'image.jpg',
'capability' => 'edit_theme_options',
'type' => 'option',
));
$wp_customize->add_setting('nscoctwentyseventeen_color_logo[image_upload_test]', array(
'default' => 'image.jpg',
'capability' => 'edit_theme_options',
'type' => 'option',
));
// Add a control to upload the punchout logo
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'nscoctwentyseventeen_punchout_logo',
array(
'width' => 250,
'height' => 250,
'flex-width' => true,
'selector' => '.punchout_logo',
'label' => __('Upload Punchout Logo', 'nscoctwentyseventeen'),
'section' => 'nscoctwentyseventeen_other_logos',
'settings' => 'nscoctwentyseventeen_punchout_logo[image_upload_test]',
)
)
);
// Add a control to upload the stamp logo
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'nscoctwentyseventeen_stamp_logo',
array(
'width' => 250,
'height' => 250,
'flex-width' => true,
'selector' => '.stamp_logo',
'label' => __('Upload Stamp Logo', 'nscoctwentyseventeen'),
'section' => 'nscoctwentyseventeen_other_logos',
'settings' => 'nscoctwentyseventeen_stamp_logo[image_upload_test]',
)
)
);
// Add a control to upload the punchout logo
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'nscoctwentyseventeen_color_logo',
array(
'width' => 250,
'height' => 250,
'flex-width' => true,
'selector' => '.color_logo',
'label' => __('Upload Color Logo', 'nscoctwentyseventeen'),
'section' => 'nscoctwentyseventeen_other_logos',
'settings' => 'nscoctwentyseventeen_color_logo[image_upload_test]',
)
)
);
}
add_action( 'customize_register', 'nscoctwentyseventeen_customize_register' );
```
In the theme file `footer.php`:
```
<div class="widget-column custom-branding">
<?php
$colorlogoURL = get_option( 'nscoctwentyseventeen_color_logo' );
echo var_dump($colorlogoURL);
?>
<img src="<?php echo $colorlogoURL?>">
</div>
```
This results in the following output.
From `var_dump()`:
```
array(1) { ["image_upload_test"]=> string(78) "https://www.example.com/wp-content/uploads/2018/02/myimage.png" }
```
In html:
```
<img src="<br /> <b>Notice</b>: Undefined offset: 1 in <b>/home/user/public_html/example/wp1/wp-content/themes/nscoctwentyseventeen/template-parts/footer/footer-widgets.php</b> on line <b>25</b><br /> ">
```
I've used `esc_url()` on the variable without any change.
I've tried `'type' => "theme_mod"`, in lieu of `'type' => "option"`.
There is something here that is incredibly simple that I must be missing, and a ton of searching the codex, and forum I'm at a loss to figure out this particular problem.
I'm using Wordpress 4.9.6, with PHP 7.1 | Checking the demo, I see that you put `padding` and `margin` as zero, that's great. The reason you are seeing the space is that there is some content with white color and you are confusing it as space(padding or margin).
[](https://i.stack.imgur.com/7vadW.jpg) |
304,908 | <p>I'm looking to split line items with a quantity > 1, into individual line items AFTER the order is received. I'm read a lot about this and see a bunch of great scripts that do this before the checkout process occurs such as <a href="https://businessbloomer.com/woocommerce-display-separate-cart-items-product-quantity-1/" rel="nofollow noreferrer">https://businessbloomer.com/woocommerce-display-separate-cart-items-product-quantity-1/</a> and <a href="https://stackoverflow.com/questions/32485152/woocommerce-treat-cart-items-separate-if-quantity-is-more-than-1?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa">https://stackoverflow.com/questions/32485152/woocommerce-treat-cart-items-separate-if-quantity-is-more-than-1?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa</a>.</p>
<p>Does anyone have any thoughts about how to do this AFTER the order has been completed? Or right on order creation in WooCommerce? I want anything with quantity > 1 to be broken out into individual line items.</p>
<p>So I believe I'll need to access all line items and then find those with quantity > 1 and then add new line items and decrement the quantity until it all balances out. Where I could use some help is how to create a line item? I know I can inspect them as shown below:</p>
<pre><code>function inspect_line_items()
{
$order = wc_get_order( 390 );
foreach ($order->get_items() as $item_id => $item_data) {
// Get an instance of corresponding the WC_Product object
$product = $item_data->get_product();
$product_name = $product->get_name(); // Get the product name
$item_quantity = $item_data->get_quantity(); // Get the item quantity
$item_total = $item_data->get_total(); // Get the item line total
// Displaying this data (to check)
if ($item_quantity >1 ){
echo 'HALP!';
}
}
}
</code></pre>
<p>Ok I'm continuing to try and I've been able to add line items (this isn't prod just testing it out, obviously this has some gaps :) ). That being said I can add a new item after checkout, and then with another hook change the order status back to processing. The issue is now the prices that are displayed. Even if I decrement the quantity for a particular item, it will still show the full/original cost. I tried updating the sub_total and total fields and then I get this funky Discount: line item. Any thoughts? Am I one the right track here?</p>
<pre><code>add_action( 'woocommerce_checkout_create_order', 'change_total_on_checking', 20, 1 );
function change_total_on_checking( $order ) {
// Get order total
$total = $order->get_total();
$items = $order->get_items();
foreach ($order->get_items() as $item_id => $item_data) {
// Get an instance of corresponding the WC_Product object
$product = $item_data->get_product();
$product_id = $item_data->get_id();
$product_name = $product->get_name();
$price = $product->get_price();
$item_quantity = $item_data->get_quantity();
$item_data['quantity'] = $item_data['quantity'] - 1 ; // Get the item quantity
//$item_data['total'] = $item_data['total'] - $price;
//$item_data['sub_total'] = $item_data['sub_total'] - $price;
$item_total = $item_data->get_total(); // Get the item line total
//do_action('woocommerce_add_to_order', $item_data['id'], $item_data['product_id'], $item_quantity, $item_data['variation_id']);
WC()->cart->add_to_cart( $product_id, $item_quantity );
$order->add_product( $product, 1);
$order->calculate_totals(); // updating totals
$order->save(); // Save the order data
}
}
add_action( 'woocommerce_thankyou', 'woocommerce_thankyou_change_order_status', 10, 1 );
function woocommerce_thankyou_change_order_status( $order_id ){
if( ! $order_id ) return;
$order = wc_get_order( $order_id );
$order->update_status( 'processing' );
}
</code></pre>
| [
{
"answer_id": 305010,
"author": "HectorOfTroy407",
"author_id": 70239,
"author_profile": "https://wordpress.stackexchange.com/users/70239",
"pm_score": 2,
"selected": true,
"text": "<p>So I ended up combining a few answer out there and split out orders when adding to the cart, and also ... | 2018/05/30 | [
"https://wordpress.stackexchange.com/questions/304908",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70239/"
] | I'm looking to split line items with a quantity > 1, into individual line items AFTER the order is received. I'm read a lot about this and see a bunch of great scripts that do this before the checkout process occurs such as <https://businessbloomer.com/woocommerce-display-separate-cart-items-product-quantity-1/> and <https://stackoverflow.com/questions/32485152/woocommerce-treat-cart-items-separate-if-quantity-is-more-than-1?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa>.
Does anyone have any thoughts about how to do this AFTER the order has been completed? Or right on order creation in WooCommerce? I want anything with quantity > 1 to be broken out into individual line items.
So I believe I'll need to access all line items and then find those with quantity > 1 and then add new line items and decrement the quantity until it all balances out. Where I could use some help is how to create a line item? I know I can inspect them as shown below:
```
function inspect_line_items()
{
$order = wc_get_order( 390 );
foreach ($order->get_items() as $item_id => $item_data) {
// Get an instance of corresponding the WC_Product object
$product = $item_data->get_product();
$product_name = $product->get_name(); // Get the product name
$item_quantity = $item_data->get_quantity(); // Get the item quantity
$item_total = $item_data->get_total(); // Get the item line total
// Displaying this data (to check)
if ($item_quantity >1 ){
echo 'HALP!';
}
}
}
```
Ok I'm continuing to try and I've been able to add line items (this isn't prod just testing it out, obviously this has some gaps :) ). That being said I can add a new item after checkout, and then with another hook change the order status back to processing. The issue is now the prices that are displayed. Even if I decrement the quantity for a particular item, it will still show the full/original cost. I tried updating the sub\_total and total fields and then I get this funky Discount: line item. Any thoughts? Am I one the right track here?
```
add_action( 'woocommerce_checkout_create_order', 'change_total_on_checking', 20, 1 );
function change_total_on_checking( $order ) {
// Get order total
$total = $order->get_total();
$items = $order->get_items();
foreach ($order->get_items() as $item_id => $item_data) {
// Get an instance of corresponding the WC_Product object
$product = $item_data->get_product();
$product_id = $item_data->get_id();
$product_name = $product->get_name();
$price = $product->get_price();
$item_quantity = $item_data->get_quantity();
$item_data['quantity'] = $item_data['quantity'] - 1 ; // Get the item quantity
//$item_data['total'] = $item_data['total'] - $price;
//$item_data['sub_total'] = $item_data['sub_total'] - $price;
$item_total = $item_data->get_total(); // Get the item line total
//do_action('woocommerce_add_to_order', $item_data['id'], $item_data['product_id'], $item_quantity, $item_data['variation_id']);
WC()->cart->add_to_cart( $product_id, $item_quantity );
$order->add_product( $product, 1);
$order->calculate_totals(); // updating totals
$order->save(); // Save the order data
}
}
add_action( 'woocommerce_thankyou', 'woocommerce_thankyou_change_order_status', 10, 1 );
function woocommerce_thankyou_change_order_status( $order_id ){
if( ! $order_id ) return;
$order = wc_get_order( $order_id );
$order->update_status( 'processing' );
}
``` | So I ended up combining a few answer out there and split out orders when adding to the cart, and also when updating the cart. The below works, though it's purely a front end customization. Hope this helps someone else!
```
function bbloomer_split_product_individual_cart_items( $cart_item_data, $product_id ){
$unique_cart_item_key = uniqid();
$cart_item_data['unique_key'] = $unique_cart_item_key;
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'bbloomer_split_product_individual_cart_items', 10, 2 );
add_action( 'woocommerce_after_cart_item_quantity_update', 'limit_cart_item_quantity', 20, 4 );
function limit_cart_item_quantity( $cart_item_key, $quantity, $old_quantity, $cart ){
// Here the quantity limit
$limit = 1;
$orders_added = $quantity - $limit;
if( $quantity > $limit ){
//Set existing line item quantity to the limit of 1
$cart->cart_contents[ $cart_item_key ]['quantity'] = $limit;
//get product id of item that was updated
$product_id = $cart->cart_contents[ $cart_item_key ][ 'product_id' ];
for( $i = 0; $i< $orders_added; $i++ ){
//iterate over the number of orders you must as with quantity one
$unique_cart_item_key = uniqid();
//create unique cart item ID, this is what breaks it out as a separate line item
$cart_item_data = array();
//initialize cart_item_data array where the unique_cart_item_key will be stored
$cart_item_data['unique_key'] = $unique_cart_item_key;
//set the cart_item_data at unique_key = to the newly created unique_key
//add that shit! this does not take into account variable products
$cart->add_to_cart( $product_id, 1, 0, 0, $cart_item_data );
}
// Add a custom notice
wc_add_notice( __('We Split out quantities of more than one into invididual line items for tracking purposes, please update quantities as needed'), 'notice' );
}
}
``` |
304,960 | <p>I'm trying to recieve post ID from link using ACF link field:</p>
<pre><code><?php
$link = get_sub_field('offer_link');
$id = get_the_ID();
if( $link ): ?>
<a href="#post-<?php echo $id; ?>" target="<?php echo $link['target']; ?>"><?php echo $link['title']; ?></a>
<?php endif; ?>
</code></pre>
<p>but instead of ID of link I get the ID of current page. How should it be done?</p>
| [
{
"answer_id": 304967,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>You can get a post's ID from a URL with <code>url_to_postid()</code>. Just pass it the URL to get the I... | 2018/05/31 | [
"https://wordpress.stackexchange.com/questions/304960",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125792/"
] | I'm trying to recieve post ID from link using ACF link field:
```
<?php
$link = get_sub_field('offer_link');
$id = get_the_ID();
if( $link ): ?>
<a href="#post-<?php echo $id; ?>" target="<?php echo $link['target']; ?>"><?php echo $link['title']; ?></a>
<?php endif; ?>
```
but instead of ID of link I get the ID of current page. How should it be done? | The [Page Link documentation](https://www.advancedcustomfields.com/resources/page-link/) actually shows how to retrieve the ID from a Page Link field. Just needed to do this myself and came across it. It worked well for me.
```
<?php
// vars
$post_id = get_field('url', false, false);
// check
if( $post_id ): ?>
<a href="<?php echo get_the_permalink($post_id); ?>"><?php echo get_the_title($post_id); ?></a>
<?php endif; ?>
```
The "false, false" parameters allow you to retrieve more details. |
304,981 | <p>I call <code>$wpdb->query()</code> on a query like</p>
<pre><code>INSERT INTO wp_ctt_timetables (name, homework, tod, class, dow, lesson) VALUES ('', '', '', 3, 0, 0);
INSERT INTO wp_ctt_timetables (name, homework, tod, class, dow, lesson) VALUES ('', '', '', 3, 0, 1);
INSERT INTO wp_ctt_timetables (name, homework, tod, class, dow, lesson) VALUES ('', '', '', 3, 0, 2);
INSERT INTO wp_ctt_timetables (name, homework, tod, class, dow, lesson) VALUES ('', '', '', 3, 0, 3);
-- and so on
</code></pre>
<p>But it doesn't work and says this to the error log:</p>
<blockquote>
<p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO wp_ctt_timetables (name, homework, tod, class, dow, lesson) VALUES (' at line 2</p>
</blockquote>
| [
{
"answer_id": 305116,
"author": "XedinUnknown",
"author_id": 64825,
"author_profile": "https://wordpress.stackexchange.com/users/64825",
"pm_score": 3,
"selected": true,
"text": "<h2>TL;DR</h2>\n\n<p>This is not possible with <code>wpdb</code>. Use <a href=\"https://developer.wordpress.... | 2018/05/31 | [
"https://wordpress.stackexchange.com/questions/304981",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144617/"
] | I call `$wpdb->query()` on a query like
```
INSERT INTO wp_ctt_timetables (name, homework, tod, class, dow, lesson) VALUES ('', '', '', 3, 0, 0);
INSERT INTO wp_ctt_timetables (name, homework, tod, class, dow, lesson) VALUES ('', '', '', 3, 0, 1);
INSERT INTO wp_ctt_timetables (name, homework, tod, class, dow, lesson) VALUES ('', '', '', 3, 0, 2);
INSERT INTO wp_ctt_timetables (name, homework, tod, class, dow, lesson) VALUES ('', '', '', 3, 0, 3);
-- and so on
```
But it doesn't work and says this to the error log:
>
> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO wp\_ctt\_timetables (name, homework, tod, class, dow, lesson) VALUES (' at line 2
>
>
> | TL;DR
-----
This is not possible with `wpdb`. Use [`dbDelta()`](https://developer.wordpress.org/reference/functions/dbdelta/). Even better, use something else to run raw queries.
Explanation
-----------
`wpdb->query()` [uses](https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/wp-db.php#L1924) the [`mysql_query()`](http://php.net/manual/en/function.mysql-query.php) function. From PHP manual:
>
> mysql\_query() sends a unique query (**multiple queries are not supported**) to the currently active database on the server that's associated with the specified link\_identifier.
>
>
>
In order for that to work, `wpdb` would have to use [`mysqli_multi_query()`](http://php.net/manual/en/mysqli.multi-query.php). But you are dealing with WordPress here: it still runs with the deprecated `mysql` extension.
Solution 1
----------
I imagined that WP would have something to aid with migrations, and apparently it does: [`dbDelta()`](https://developer.wordpress.org/reference/functions/dbdelta/). This is a 438-line-long monster, so I will save you some time:
It doesn't give you a list of separated queries. It returns a list of updates that are performed by the queries - if you were to run them with the second parameter being `true`. Inside, it splits the query by semicolons, and then does such magix that it's impossible to tell what happens. If used incorrectly, this function may open a portal into Oblivion. Looks like it actually skips certain queries, like those that create [global tables](https://codex.wordpress.org/Database_Description#Multisite_Table_Overview). It will normalize whitespace, quote column names. If the query is creating WP tables that already exist, but something in the schema is different, such as indices or column types, it will try to alter the tables without re-creating them, so that they can match what your query would create. **I do not know why it is able to successfully run queries where the semicolon doesn't terminate a query, such as part of the string**.
If you thought that you can use [IoC](https://en.wikipedia.org/wiki/Inversion_of_control) and pass the `wpdb` object to your cool standardized interface implementation, then you're out of luck.
Solution 2
----------
Use another DB adapter or extension. In most cases, if you need to run migrations, such as create tables and insert many rows, it's not a problem if you don't use `wpdb` (and thus have to create another DB connection), because this is only going to happen very rarely. Also, due to the crazy transformations done by `dbDelta()`, it's probably more reliable to find a way to run raw queries.
* `mysqli_multi_query()` is a function of the `mysqli` (not outdated) extension that can easily run multiple statements at once.
* [`PDO`](http://php.net/manual/en/book.pdo.php) can run multiple queries in [emulation mode](https://phpdelusions.net/pdo#emulation). |
305,065 | <p>I'm trying to write a plugin installer, akin to TGMPA, but just for its core functionality of actually installing the plugin and nothing more.</p>
<p>I've identified that <code>Plugin_Upgrader</code> is what I need and decided to emulate this.</p>
<pre><code>$plugin = THEME_DIR . '/Inc/Plugins/my-shortcodes.zip';
$options = array(
'package' => $plugin,
'destination' => WP_PLUGIN_DIR,
'clear_destination' => false,
'clear_working' => true,
'is_multi' => true,
'hook_extra' => array(
'plugin' => $plugin,
),
);
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
class My_Upgrader extends Plugin_Upgrader
{
public function run( $options )
{
$result = parent::run( $options );
return $result;
}
}
$upgrader = new My_Upgrader;
$upgrader->run($options);
$upgrader->install( $plugin );
</code></pre>
<p>Unfortunately, this throws the following error:</p>
<pre><code>Uncaught Error: Call to undefined function request_filesystem_credentials()
in C:\xampp\htdocs\wordpress\wp-admin\includes\class-wp-upgrader-skin.php:93
Stack trace: #0 C:\xampp\htdocs\wordpress\wp-admin\includes\class-wp-
upgrader.php(187): WP_Upgrader_Skin->request_filesystem_credentials(false,
'C:\\xampp\\htdocs...', false) #1 C:\xampp\htdocs\wordpress\wp-
admin\includes\class-wp-upgrader.php(693): WP_Upgrader->fs_connect(Array) #2
C:\xampp\htdocs\wordpress\wp-content\themes\amaranth\header.php(53):
WP_Upgrader->run(Array) #3 C:\xampp\htdocs\wordpress\wp-
content\themes\amaranth\header.php(59): My_Upgrader->run(Array) #4
C:\xampp\htdocs\wordpress\wp-includes\template.php(688):
require_once('C:\\xampp\\htdocs...') #5 C:\xampp\htdocs\wordpress\wp-
includes\template.php(647): load_template('C:\\xampp\\htdocs...', true) #6
C:\xampp\htdocs\wordpress\wp-includes\general-template.php(41):
locate_template(Array, true) #7 C:\xampp\htdocs\wordpress\wp-
content\themes\amaranth\index.php(15): get_header() #8 C:\xampp\htdoc in
C:\xampp\htdocs\wordpress\wp-admin\includes\class-wp-upgrader-skin.php on
line 93
</code></pre>
<p>It has something to do with its...skin? Am I missing something?</p>
<p>A few notes:</p>
<ul>
<li>I understand that the Filesystem module would default to FTP if it
can't write to <code>wp-content</code>, as such, this error might pop up, but
it's not the case. WP can write to <code>wp-content</code>.</li>
</ul>
<p><strong><em>Disclaimer: This is a very dumb installer, but I gotta start somewhere. Any suggestions are welcome.</em></strong></p>
| [
{
"answer_id": 305015,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<h2>What constitutes personal data?</h2>\n\n<p>The GDPR applies to ‘personal data’ meaning any information relating ... | 2018/06/01 | [
"https://wordpress.stackexchange.com/questions/305065",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143406/"
] | I'm trying to write a plugin installer, akin to TGMPA, but just for its core functionality of actually installing the plugin and nothing more.
I've identified that `Plugin_Upgrader` is what I need and decided to emulate this.
```
$plugin = THEME_DIR . '/Inc/Plugins/my-shortcodes.zip';
$options = array(
'package' => $plugin,
'destination' => WP_PLUGIN_DIR,
'clear_destination' => false,
'clear_working' => true,
'is_multi' => true,
'hook_extra' => array(
'plugin' => $plugin,
),
);
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
class My_Upgrader extends Plugin_Upgrader
{
public function run( $options )
{
$result = parent::run( $options );
return $result;
}
}
$upgrader = new My_Upgrader;
$upgrader->run($options);
$upgrader->install( $plugin );
```
Unfortunately, this throws the following error:
```
Uncaught Error: Call to undefined function request_filesystem_credentials()
in C:\xampp\htdocs\wordpress\wp-admin\includes\class-wp-upgrader-skin.php:93
Stack trace: #0 C:\xampp\htdocs\wordpress\wp-admin\includes\class-wp-
upgrader.php(187): WP_Upgrader_Skin->request_filesystem_credentials(false,
'C:\\xampp\\htdocs...', false) #1 C:\xampp\htdocs\wordpress\wp-
admin\includes\class-wp-upgrader.php(693): WP_Upgrader->fs_connect(Array) #2
C:\xampp\htdocs\wordpress\wp-content\themes\amaranth\header.php(53):
WP_Upgrader->run(Array) #3 C:\xampp\htdocs\wordpress\wp-
content\themes\amaranth\header.php(59): My_Upgrader->run(Array) #4
C:\xampp\htdocs\wordpress\wp-includes\template.php(688):
require_once('C:\\xampp\\htdocs...') #5 C:\xampp\htdocs\wordpress\wp-
includes\template.php(647): load_template('C:\\xampp\\htdocs...', true) #6
C:\xampp\htdocs\wordpress\wp-includes\general-template.php(41):
locate_template(Array, true) #7 C:\xampp\htdocs\wordpress\wp-
content\themes\amaranth\index.php(15): get_header() #8 C:\xampp\htdoc in
C:\xampp\htdocs\wordpress\wp-admin\includes\class-wp-upgrader-skin.php on
line 93
```
It has something to do with its...skin? Am I missing something?
A few notes:
* I understand that the Filesystem module would default to FTP if it
can't write to `wp-content`, as such, this error might pop up, but
it's not the case. WP can write to `wp-content`.
***Disclaimer: This is a very dumb installer, but I gotta start somewhere. Any suggestions are welcome.*** | Well, this has little to do with WordPress development as such, even if there is now a [special privacy function](https://developer.wordpress.org/reference/functions/the_privacy_policy_link/), but since I´ve been writing about online privacy for over 25 years now I´ll gladly answer. Let´s take a [look at the principles](https://en.wikipedia.org/wiki/General_Data_Protection_Regulation):
1. Lawful basis. Since you are collecting data with a form, it is clear what data is collected and what for. You could add two optional notes to be filled in in the backend 'what will we use your data for' and 'what data do we store', so your users are more aware of their obligations towards the visitors of their website. These notes could also be shown in the frontend.
2. Responsibility, data protection and pseudonymisation. These are mainly security issues that your plugin can do little about, except maybe applying cryptography when storing the information. But that would mean the data can only be accessed through your plugin.
3. Right of access. This too is something that could be added to the form as a note: tell the visitor what he can do to access/erase his information after he has filled in the form.
4. Right to erasure. See above. Also: does your plugin provide only manual erasure options or scheduled erasure as well? The plugin could help reduce load on the users if data older than, say, one year is automatically removed.
5. Records of processing activities. Does your plugin allow users to modify data collected? In that case, does it store old values? This may be a little bit overkill for a simple form, but if you are collecting sensitive data (such as medical records) keeping track of modifications might be wise. Processing also involves other stuff that users do with the collected data, but that is not your responsibility as a plugin developer.
6. Data protection officer and breaches. Not your responsibility.
So, you are mostly done. The most important addition might be to include a note on your options page explaining GDPR to users of your plugin and allowing them to pass information on their rights to their website's visitors. At this point you have built the necessary technical tools into your plugin, but you should also support transparency.
**Update**: Sample texts
* We will use your name and email address [what data we store] only to send you a maximum of one newsletter every month [exactly what we store it for]. Every newsletter will include a link that lets you unsubscribe [right to erase].
* We store the data in the questionnaire together with your name and contact info [what data we store] for our research purposes [exactly what we store it for]. Your name and contact info are only stored so we get into contact with you for clarifications of the questionnaire. We delete your name and contact info automatically after three months [erasure info, after this the rest of the data is no longer personal data unless the questionnaire asks personal stuff]. The questionnaire data we will keep as long as is necessary for the research. |
305,076 | <p>I've already read <a href="https://wordpress.stackexchange.com/questions/72525/how-to-switch-between-the-primary-menus-programmatically">How to switch between the Primary Menus programmatically?</a> but it doesn't actually answer the question. The accepted answer is just two workarounds but not an actual answer to the question.</p>
<p>When my theme is activated, I create several menus and I would like to mark one of them as the Primary Menu.</p>
<p>Is there a wordpress function I can call to make my programmatically created menu the Primary Menu? I'm an experienced developer, but I'm new to wordpress and the terminology in the functions makes it very hard to search the codex to find what I'm looking for. Any help is appreciated.</p>
| [
{
"answer_id": 305080,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like you are looking for this:</p>\n\n<p>Add to <code>functions.php</code></p>\n\n<pre><code>$l... | 2018/06/01 | [
"https://wordpress.stackexchange.com/questions/305076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112418/"
] | I've already read [How to switch between the Primary Menus programmatically?](https://wordpress.stackexchange.com/questions/72525/how-to-switch-between-the-primary-menus-programmatically) but it doesn't actually answer the question. The accepted answer is just two workarounds but not an actual answer to the question.
When my theme is activated, I create several menus and I would like to mark one of them as the Primary Menu.
Is there a wordpress function I can call to make my programmatically created menu the Primary Menu? I'm an experienced developer, but I'm new to wordpress and the terminology in the functions makes it very hard to search the codex to find what I'm looking for. Any help is appreciated. | I dug through the wordpress code to see what was happening when I submitted the form from the admin UI to see what function it was calling (and did a `var_export()` on the variable being passed in) and saw it was calling `set_theme_mod( 'nav_menu_locations', $menu_locations );`. I've updated my code to use this and it seems to be working:
```
$locations = get_theme_mod('nav_menu_locations');
$locations['primary'] = $menu_id;
set_theme_mod( 'nav_menu_locations', $locations );
```
One of the things that threw me off when I was trying to figure out how to do this is that the documentation for `get_theme_mod()` says that it returns a string, but in this case it is returning an array and so I didn't think it was going to work. |
305,127 | <p>I have created some theme page and I want to call <a href="https://wordpress.org/plugins/wp-customer-reviews/" rel="nofollow noreferrer">WP Customer Reviews</a> shortcode </p>
<pre><code> echo do_shortcode('[WPCR_SHOW POSTID="' . $post->ID . '" NUM="1" HIDEREVIEWS="0" HIDERESPONSE="1" HIDECUSTOM="1" SHOWFORM="0"]');
</code></pre>
<p>but it returns </p>
<blockquote>
<p>[WPCR_SHOW POSTID="3498" NUM="1" HIDEREVIEWS="0" HIDERESPONSE="1"
HIDECUSTOM="1" SHOWFORM="0"]</p>
</blockquote>
<p>Here is my full source code.
File is in <strong><em>wp-content\themes\couponxl - child\category_details.php</em></strong></p>
<pre><code><?php
/* Template Name: Category Details */
get_header();
$search_sidebar_location = couponxl_get_option('search_sidebar_location');
if ($_GET['paged']) {
$cur_page = $_GET['paged'];
$offset = $_GET['paged'] * 4;
} else {
$cur_page = 1;
$offset = 1;
}
get_template_part('includes/title');
?>
<section>
<div class="container">
<?php
$content = get_the_content();
if (!empty($content)):
?>
<div class="white-block">
<div class="white-block-content">
<div class="page-content clearfix">
<?php echo apply_filters('the_content', $content) ?>
</div>
</div>
</div>
<?php
endif;
?>
<div class="row">
<?php if ($search_sidebar_location == 'left'): ?>
<?php get_sidebar('coupon') ?>
<?php endif; ?>
<div class="col-md-<?php echo is_active_sidebar('sidebar-coupon') ? '9' : '12' ?>">
<?php echo do_shortcode("[wcps id='3414']"); ?>
<div class="row masonry masonry-item">
<?php
$args = array('posts_per_page' => 5, 'taxonomy' => 'product_cat', 'terms' => $_GET['cat'],
'paged' => $cur_page, 'post_type' => 'product', 'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $_GET['cat'], // Where term_id of Term 1 is "1".
)
));
$postslist = new WP_Query($args);
$coupons = $postslist;
$page_links_total = $coupons->max_num_pages;
$pagination_args = array(
'prev_next' => true,
'total' => $page_links_total,
'current' => $cur_page,
'prev_next' => true,
'type' => 'array',
);
$pagination_args['format'] = '?paged=%#%';
$page_links = paginate_links($pagination_args);
$pagination = couponxl_format_pagination($page_links);
if (!empty($postslist->posts)) {
foreach ($postslist->posts as $post) {
?>
<div class="white-block offer-box coupon-box <?php echo esc_attr($offer_view) ?> <?php echo $col == '12' ? 'clearfix' : '' ?>">
<div class="col-md-6 product-list">
<div class="white-block-media <?php echo $col == '12' ? 'col-sm-4' : '' ?>">
<div class="embed-responsive embed-responsive-16by9 ">
<?php
$store_id = get_post_meta(get_the_ID(), 'location', true);
couponxl_store_logo($store_id);
?>
</div>
<?php if (couponxl_is_plugin_active('couponxl-cpt/couponxl-cpt.php')) : ?>
<?php couponxl_cpt_share(); ?>
<?php endif; ?>
</div>
<?php
echo '<label class="flag-new">' . $label = get_post_meta($post->ID, 'label', true) . '</label>';
echo '<label class="flag-discount" style="color: #f32398;">-' . $discount = get_post_meta($post->ID, 'discount', true) . '%</label>';
echo '<label class="wishlist-button">' . do_shortcode('[woosw id = ' . $post->ID . ']') . '</label>';
?>
<div class="white-block-content <?php echo $col == '12' ? 'col-sm-8' : '' ?>">
<?php
echo do_shortcode('[WPCR_SHOW POSTID="'.$post->ID.'" NUM="1" HIDEREVIEWS="0" HIDERESPONSE="1" HIDECUSTOM="1" SHOWFORM="0"]');
if (get_post_meta($post->ID, 'expires_in', true)) {
$earlier = new DateTime(date("Y-m-d"));
$later = new DateTime(date('Y-m-d', strtotime(get_post_meta($post->ID, 'expires_in', true))));
$diff = $later->diff($earlier)->format("%a");
if (!empty($diff)) {
echo '<span class="expire-date">Expires in: <span class="expire-text">' . $diff . ' days</span></span>';
} else {
echo '<span class="expire-date"> </span>';
}
}
?>
<h3>
<a href="<?php the_permalink() ?>">
<?php the_title(); ?>
</a>
</h3>
<ul class="list-unstyled list-inline bottom-meta">
<li>
<i class="fa fa-dot-circle-o icon-margin"></i>
<?php echo couponxl_taxonomy('product_cat', 1) ?>
</li>
<li>
<i class="fa fa-map-marker icon-margin"></i>
<?php echo couponxl_taxonomy('location', 1) ?>
</li>
</ul>
</div>
<div class="white-block-footer <?php echo $col == '12' ? 'col-sm-12' : '' ?>">
<div class="white-block-content">
<?php
$price = get_post_meta(get_the_ID(), '_regular_price', true);
$sale = get_post_meta(get_the_ID(), '_sale_price', true);
?>
<?php if ($sale) : ?>
<span class="price-style">
<span class="woocommerce-Price-amount amount">
<i class="">RM</i><?php echo $sale; ?>
<i class="fa">RM</i>
<del><?php echo $price; ?></del>
</span>
</span>
<?php elseif ($price) : ?>
<span class="price-style">
<span class="woocommerce-Price-amount amount">
<i class="fa">RM</i> <?php
echo $price;
?>
</span>
</span>
<?php endif; ?>
<span class="span-class1">
<a class="btn single_add_to_cart_button alt" href="<?= site_url() . '/cart/?add-to-cart=' . $post->ID ?>">Add to cart</a>
</span>
</div>
</div>
</div>
<?php
}
}else {
?>
<div class="white-block-content">
<p class="nothing-found">Currently there is no products for this category.</p>
</div>
<?php }
?>
</div>
</div>
</div>
<?php //endif; ?>
</div>
<?php if (!empty($pagination)): ?>
<div class="col-sm-4 masonry-item paginate">
<ul class="pagination">
<?php echo $pagination; ?>
</ul>
</div>
<?php endif; ?>
</div>
</section>
<?php get_footer(); ?>
</code></pre>
<p>I have already enabled WP Customer Reviews for that product.</p>
<p><a href="https://i.stack.imgur.com/9xVl9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9xVl9.png" alt="enter image description here"></a></p>
<p>Can anyone help me to do that?</p>
| [
{
"answer_id": 305109,
"author": "Prashant Rawal",
"author_id": 119111,
"author_profile": "https://wordpress.stackexchange.com/users/119111",
"pm_score": 0,
"selected": false,
"text": "<p>Let me first tell you how the firewall work. Firewall acts as a shield between your wordpress websit... | 2018/06/02 | [
"https://wordpress.stackexchange.com/questions/305127",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44959/"
] | I have created some theme page and I want to call [WP Customer Reviews](https://wordpress.org/plugins/wp-customer-reviews/) shortcode
```
echo do_shortcode('[WPCR_SHOW POSTID="' . $post->ID . '" NUM="1" HIDEREVIEWS="0" HIDERESPONSE="1" HIDECUSTOM="1" SHOWFORM="0"]');
```
but it returns
>
> [WPCR\_SHOW POSTID="3498" NUM="1" HIDEREVIEWS="0" HIDERESPONSE="1"
> HIDECUSTOM="1" SHOWFORM="0"]
>
>
>
Here is my full source code.
File is in ***wp-content\themes\couponxl - child\category\_details.php***
```
<?php
/* Template Name: Category Details */
get_header();
$search_sidebar_location = couponxl_get_option('search_sidebar_location');
if ($_GET['paged']) {
$cur_page = $_GET['paged'];
$offset = $_GET['paged'] * 4;
} else {
$cur_page = 1;
$offset = 1;
}
get_template_part('includes/title');
?>
<section>
<div class="container">
<?php
$content = get_the_content();
if (!empty($content)):
?>
<div class="white-block">
<div class="white-block-content">
<div class="page-content clearfix">
<?php echo apply_filters('the_content', $content) ?>
</div>
</div>
</div>
<?php
endif;
?>
<div class="row">
<?php if ($search_sidebar_location == 'left'): ?>
<?php get_sidebar('coupon') ?>
<?php endif; ?>
<div class="col-md-<?php echo is_active_sidebar('sidebar-coupon') ? '9' : '12' ?>">
<?php echo do_shortcode("[wcps id='3414']"); ?>
<div class="row masonry masonry-item">
<?php
$args = array('posts_per_page' => 5, 'taxonomy' => 'product_cat', 'terms' => $_GET['cat'],
'paged' => $cur_page, 'post_type' => 'product', 'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $_GET['cat'], // Where term_id of Term 1 is "1".
)
));
$postslist = new WP_Query($args);
$coupons = $postslist;
$page_links_total = $coupons->max_num_pages;
$pagination_args = array(
'prev_next' => true,
'total' => $page_links_total,
'current' => $cur_page,
'prev_next' => true,
'type' => 'array',
);
$pagination_args['format'] = '?paged=%#%';
$page_links = paginate_links($pagination_args);
$pagination = couponxl_format_pagination($page_links);
if (!empty($postslist->posts)) {
foreach ($postslist->posts as $post) {
?>
<div class="white-block offer-box coupon-box <?php echo esc_attr($offer_view) ?> <?php echo $col == '12' ? 'clearfix' : '' ?>">
<div class="col-md-6 product-list">
<div class="white-block-media <?php echo $col == '12' ? 'col-sm-4' : '' ?>">
<div class="embed-responsive embed-responsive-16by9 ">
<?php
$store_id = get_post_meta(get_the_ID(), 'location', true);
couponxl_store_logo($store_id);
?>
</div>
<?php if (couponxl_is_plugin_active('couponxl-cpt/couponxl-cpt.php')) : ?>
<?php couponxl_cpt_share(); ?>
<?php endif; ?>
</div>
<?php
echo '<label class="flag-new">' . $label = get_post_meta($post->ID, 'label', true) . '</label>';
echo '<label class="flag-discount" style="color: #f32398;">-' . $discount = get_post_meta($post->ID, 'discount', true) . '%</label>';
echo '<label class="wishlist-button">' . do_shortcode('[woosw id = ' . $post->ID . ']') . '</label>';
?>
<div class="white-block-content <?php echo $col == '12' ? 'col-sm-8' : '' ?>">
<?php
echo do_shortcode('[WPCR_SHOW POSTID="'.$post->ID.'" NUM="1" HIDEREVIEWS="0" HIDERESPONSE="1" HIDECUSTOM="1" SHOWFORM="0"]');
if (get_post_meta($post->ID, 'expires_in', true)) {
$earlier = new DateTime(date("Y-m-d"));
$later = new DateTime(date('Y-m-d', strtotime(get_post_meta($post->ID, 'expires_in', true))));
$diff = $later->diff($earlier)->format("%a");
if (!empty($diff)) {
echo '<span class="expire-date">Expires in: <span class="expire-text">' . $diff . ' days</span></span>';
} else {
echo '<span class="expire-date"> </span>';
}
}
?>
<h3>
<a href="<?php the_permalink() ?>">
<?php the_title(); ?>
</a>
</h3>
<ul class="list-unstyled list-inline bottom-meta">
<li>
<i class="fa fa-dot-circle-o icon-margin"></i>
<?php echo couponxl_taxonomy('product_cat', 1) ?>
</li>
<li>
<i class="fa fa-map-marker icon-margin"></i>
<?php echo couponxl_taxonomy('location', 1) ?>
</li>
</ul>
</div>
<div class="white-block-footer <?php echo $col == '12' ? 'col-sm-12' : '' ?>">
<div class="white-block-content">
<?php
$price = get_post_meta(get_the_ID(), '_regular_price', true);
$sale = get_post_meta(get_the_ID(), '_sale_price', true);
?>
<?php if ($sale) : ?>
<span class="price-style">
<span class="woocommerce-Price-amount amount">
<i class="">RM</i><?php echo $sale; ?>
<i class="fa">RM</i>
<del><?php echo $price; ?></del>
</span>
</span>
<?php elseif ($price) : ?>
<span class="price-style">
<span class="woocommerce-Price-amount amount">
<i class="fa">RM</i> <?php
echo $price;
?>
</span>
</span>
<?php endif; ?>
<span class="span-class1">
<a class="btn single_add_to_cart_button alt" href="<?= site_url() . '/cart/?add-to-cart=' . $post->ID ?>">Add to cart</a>
</span>
</div>
</div>
</div>
<?php
}
}else {
?>
<div class="white-block-content">
<p class="nothing-found">Currently there is no products for this category.</p>
</div>
<?php }
?>
</div>
</div>
</div>
<?php //endif; ?>
</div>
<?php if (!empty($pagination)): ?>
<div class="col-sm-4 masonry-item paginate">
<ul class="pagination">
<?php echo $pagination; ?>
</ul>
</div>
<?php endif; ?>
</div>
</section>
<?php get_footer(); ?>
```
I have already enabled WP Customer Reviews for that product.
[](https://i.stack.imgur.com/9xVl9.png)
Can anyone help me to do that? | There is no "WordPress Firewall".
A [firewall](https://en.wikipedia.org/wiki/Firewall_(computing)) acts either on the network or on the host, never on a later stage such as a specific software running on a server.
Everything that claims to be a firewall specific for WordPress is a scam. See the linked Wikipedia article for the details. |
305,132 | <p>I am developing a plugin, let's call it DahPlugin, that provides additional customizer options for a free theme I developed. Let's call this theme DahTheme (I don't want to shamelessly plug either one of them here).</p>
<p>So what I am trying to accomplish is, I would like for <strong>DahPlugin</strong> to be automatically <strong>deactivated</strong> the when the user changes themes away from <strong>DahTheme</strong>.</p>
<p>I found this code snippet here: <a href="https://wordpress.stackexchange.com/questions/225355/disable-active-plugins-for-specific-theme">disable active plugins for specific theme</a>, which works really well if you want to disable plugins if a certain theme is active.</p>
<p>So I decided I would be clever and utilize it in my theme and switch the logic. So I changed the comparison operator from <code>==</code> (<em>equal</em>) to <code>!=</code> (<em>not equal</em>)...my thinking: If the current theme name is not equal to "<strong>DahTheme</strong>", then deactivate "<strong>DahPlugin</strong>" and here is what it looks like:</p>
<pre><code>if ( ! function_exists('disable_plugins')) :
function disable_plugins(){
include_once(ABSPATH.'wp-admin/includes/plugin.php');
$current_theme = wp_get_theme();
$current_theme_name = $current_theme->Name;
if($current_theme_name == 'DahTheme'){
if ( is_plugin_active('dahplugin/dahplugin.php') ) {
deactivate_plugins('dahplugin/dahplugin.php');
}
}
}
add_action('after_switch_theme','disable_plugins');
endif;
</code></pre>
<p>Aaaaaaand it doesn't work...lol! Of course this happens whenever I think I'm being clever.</p>
<p>So I have been racking my brain and looking all over the place to try and figure out what or why it isn't working and I can't seem to find that either.</p>
<p>Can anyone show me why it's not working and why my line of thinking is wrong. That would be greatly appreciated.</p>
<p>Thanks in advance for any help.</p>
| [
{
"answer_id": 305133,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't tested this, so it might not work correctly, but the essence of what you're trying to do i... | 2018/06/02 | [
"https://wordpress.stackexchange.com/questions/305132",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65047/"
] | I am developing a plugin, let's call it DahPlugin, that provides additional customizer options for a free theme I developed. Let's call this theme DahTheme (I don't want to shamelessly plug either one of them here).
So what I am trying to accomplish is, I would like for **DahPlugin** to be automatically **deactivated** the when the user changes themes away from **DahTheme**.
I found this code snippet here: [disable active plugins for specific theme](https://wordpress.stackexchange.com/questions/225355/disable-active-plugins-for-specific-theme), which works really well if you want to disable plugins if a certain theme is active.
So I decided I would be clever and utilize it in my theme and switch the logic. So I changed the comparison operator from `==` (*equal*) to `!=` (*not equal*)...my thinking: If the current theme name is not equal to "**DahTheme**", then deactivate "**DahPlugin**" and here is what it looks like:
```
if ( ! function_exists('disable_plugins')) :
function disable_plugins(){
include_once(ABSPATH.'wp-admin/includes/plugin.php');
$current_theme = wp_get_theme();
$current_theme_name = $current_theme->Name;
if($current_theme_name == 'DahTheme'){
if ( is_plugin_active('dahplugin/dahplugin.php') ) {
deactivate_plugins('dahplugin/dahplugin.php');
}
}
}
add_action('after_switch_theme','disable_plugins');
endif;
```
Aaaaaaand it doesn't work...lol! Of course this happens whenever I think I'm being clever.
So I have been racking my brain and looking all over the place to try and figure out what or why it isn't working and I can't seem to find that either.
Can anyone show me why it's not working and why my line of thinking is wrong. That would be greatly appreciated.
Thanks in advance for any help. | I haven't tested this, so it might not work correctly, but the essence of what you're trying to do is hook into the `after_switch_theme` hook and see if the `$old_name` is DahTheme. If it is, that means that the current theme isn't DahTheme, so you want to deactivate the plugin.
```
function wpse_after_switch_theme( $old_name, $old_theme ) {
if( 'DahTheme' === $old_name ) {
//* You may or may not need to include wp-admin/includes/plugin.php here
deactivate_plugins( 'dahplugin/dahplugin.php' );
}
}
add_action( 'after_switch_theme', 'wpse_after_switch_theme', 10, 2 );
``` |
305,143 | <pre><code><h1 class="page-title"><?php esc_html_e( 'Oops! Something went wrong.', '_amnth' ); ?></h1>
</code></pre>
<p>I think this should simply use the <code>__()</code> function, since it's a static string and it cannot be dynamic and in contrast, HTML.</p>
<p>At the same time, here's some source code from WooCommerce itself:</p>
<pre><code><th class="product-name"><?php esc_html_e( 'Product', 'woocommerce' ); ?></th>
</code></pre>
<p>So, is it whenever you output a string, dynamic or not, to HTML, you should also escape it with <code>esc_html</code> and so, even if it's just a string being output, you should use <code>esc_html_e</code>?</p>
<p><strong>Please assume extremely strict escaping rules, where everything needs to be escaped in the right way. (Even so, using esc_html_e seems overkill to the power of 10 ).</strong> </p>
| [
{
"answer_id": 305166,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>It depends... As in almost any case...</p>\n\n<blockquote>\n <p>So, is it whenever you output a stri... | 2018/06/02 | [
"https://wordpress.stackexchange.com/questions/305143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143406/"
] | ```
<h1 class="page-title"><?php esc_html_e( 'Oops! Something went wrong.', '_amnth' ); ?></h1>
```
I think this should simply use the `__()` function, since it's a static string and it cannot be dynamic and in contrast, HTML.
At the same time, here's some source code from WooCommerce itself:
```
<th class="product-name"><?php esc_html_e( 'Product', 'woocommerce' ); ?></th>
```
So, is it whenever you output a string, dynamic or not, to HTML, you should also escape it with `esc_html` and so, even if it's just a string being output, you should use `esc_html_e`?
**Please assume extremely strict escaping rules, where everything needs to be escaped in the right way. (Even so, using esc\_html\_e seems overkill to the power of 10 ).** | You should always escape output. end of sentence, and end of story.
The questions is like asking if you can use globals and goto. Sure they are part of the language and in some edge cases they are the only way to produce working and readable code, but the guide is to never use them unless you can prove you have too.
Going down from the theoretical to the practical, it is not true that `__` is static string, as if it was static you would not have used it at all, and just used the literal string instead. It is even worse, as the function is **meant** to supply an easy way to override a string to any other string, a string you might have no idea about its content.
The only place where escaping might result in a bad result on the front end is when someone tries to add html tags to the string as part of the translation, but this is extremely rare case, especially if you had the translators in mind while creating code that does the output.
Following the discussion in the comments, I feel like maybe I should state the reasoning in a different way. Translations should be treated as user input, since users can actually edit them, or use plugin to change them. And all user inputs should be suspect, if not for security reasons than for broken html reasons, and therefor it should be validated, sanitized and escaped.
With a more traditional user input you sometimes can avoid escaping by doing a more rigorous validation and sanitation, but you have no chance of doing that with regard to translation, and escaping is your almost only tool to be able to protect against security holes, and broken html. |
305,164 | <p>We often use the Oembed function provided by the Wordpress to embed media.</p>
<p>I have a condition where I am running a loop to fetch certain posts from a custom post type, but I want to skip posts in which Oembed is empty.</p>
<p>How to check if Oembed is empty or has a URL in meta of single.php.</p>
<p>I tried something like this →</p>
<pre><code><?php $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
<?php $embed = wp_oembed_get( $url ); ?>
</code></pre>
<h1>PHP Needed →</h1>
<p>Now how to check if <code>$embed</code> is empty or not?</p>
<h1>Update as requested →</h1>
<p>The front end will be like <a href="https://s3.amazonaws.com/sitepoint007/empty_post.png" rel="nofollow noreferrer">this</a>, and it pulled by running a WP custom loop like this.</p>
<p>But there can be a situation like this where the OEMBED is empty like <a href="https://www.screencast.com/t/PTDnDB23FjR" rel="nofollow noreferrer">this</a>.</p>
<p>So what I want is when such situation exists the loop should exclude that post and for that, we need <code>if condition</code> that checks If oembed is empty or not.</p>
<p><a href="https://i.stack.imgur.com/pQYBL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pQYBL.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 305165,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>It’s a little hard to guess what’s your question really is and what exactly you want to check...</p>\... | 2018/06/03 | [
"https://wordpress.stackexchange.com/questions/305164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
] | We often use the Oembed function provided by the Wordpress to embed media.
I have a condition where I am running a loop to fetch certain posts from a custom post type, but I want to skip posts in which Oembed is empty.
How to check if Oembed is empty or has a URL in meta of single.php.
I tried something like this →
```
<?php $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
<?php $embed = wp_oembed_get( $url ); ?>
```
PHP Needed →
============
Now how to check if `$embed` is empty or not?
Update as requested →
=====================
The front end will be like [this](https://s3.amazonaws.com/sitepoint007/empty_post.png), and it pulled by running a WP custom loop like this.
But there can be a situation like this where the OEMBED is empty like [this](https://www.screencast.com/t/PTDnDB23FjR).
So what I want is when such situation exists the loop should exclude that post and for that, we need `if condition` that checks If oembed is empty or not.
[](https://i.stack.imgur.com/pQYBL.png) | The [`wp_oembed_get()`](https://codex.wordpress.org/Function_Reference/wp_oembed_get) only works for supported oEmbed providers. The return value is also is a URL of false, as mentioned per codex:
>
> If $url is a valid url to a supported provider, the function returns
> the embed code provided to it from the oEmbed protocol. Otherwise, it
> will return false.
>
>
>
Therefore, is the input is empty, the return value would be false, so you could simply check:
```
if ( $embed ) {
// Valid
}
``` |
305,195 | <p>Suppose the editor on my admin dashboard creates the following HTML (when I print to the webpage using <code>the_content()</code>:</p>
<pre><code><blockquote>Hello this is the best quote in the world!</blockquote>
<blockquote>Hello this is the second best quote in the world!</blockquote>
<blockquote>Hello this is the third best quote in the world!</blockquote>
<h2>This is a heading for a paragraph</h2>
<p>This is some paragraph.</p>
.
.
.
</code></pre>
<p>From this, I want to group together the quotes in a <code>div</code> and group the rest of the content of the page in a separate <code>div</code>. Something like this:</p>
<pre><code><div class="my-blockquotes">
<blockquote>Hello this is the best quote in the world!</blockquote>
<blockquote>Hello this is the second best quote in the world!</blockquote>
<blockquote>Hello this is the third best quote in the world!</blockquote>
</div>
<div class="main-content">
<h2>This is a heading for a paragraph</h2>
<p>This is some paragraph.</p>
.
.
.
</div>
</code></pre>
<p><strong>Basically, is there a way to change the structure of the HTML that <code>the_content()</code> generates?</strong> I tried searching about walker classes, but that's not available for <code>the_content()</code>. I tried hacky fixes like using shortcodes, but could not come up with a solution.</p>
| [
{
"answer_id": 305196,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 3,
"selected": true,
"text": "<p>You can use <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"nofoll... | 2018/06/03 | [
"https://wordpress.stackexchange.com/questions/305195",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144745/"
] | Suppose the editor on my admin dashboard creates the following HTML (when I print to the webpage using `the_content()`:
```
<blockquote>Hello this is the best quote in the world!</blockquote>
<blockquote>Hello this is the second best quote in the world!</blockquote>
<blockquote>Hello this is the third best quote in the world!</blockquote>
<h2>This is a heading for a paragraph</h2>
<p>This is some paragraph.</p>
.
.
.
```
From this, I want to group together the quotes in a `div` and group the rest of the content of the page in a separate `div`. Something like this:
```
<div class="my-blockquotes">
<blockquote>Hello this is the best quote in the world!</blockquote>
<blockquote>Hello this is the second best quote in the world!</blockquote>
<blockquote>Hello this is the third best quote in the world!</blockquote>
</div>
<div class="main-content">
<h2>This is a heading for a paragraph</h2>
<p>This is some paragraph.</p>
.
.
.
</div>
```
**Basically, is there a way to change the structure of the HTML that `the_content()` generates?** I tried searching about walker classes, but that's not available for `the_content()`. I tried hacky fixes like using shortcodes, but could not come up with a solution. | You can use [`the_content`](https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content) [filter](https://codex.wordpress.org/Plugin_API/Hooks), to literally filter the content into your structure.
Somthing like this
```
<?php
add_filter('the_content',function($the_content){
// find blockquotes
$regex = '/<blockquote>(.+?)<\/blockquote>([\n|$])/i';
$blockquotes = preg_match_all($regex,$the_content,$matches);
// remove blockquotes
$main_content = preg_replace($regex,'',$the_content);
// rebuild blockqoutes
$my_blockquotes = '';
foreach ($matches[1] as $blockquote) {
$my_blockquotes .= "<blockquote>{$blockquote}</blockquote>";
}
// rebuild content
$new_content = '';
if (!empty($my_blockquotes)) {
$new_content = "
<div class='my-blockquotes'>
{$my_blockquotes}
</div>\n";
}
$new_content .= "
<div class='main-content'>
{$main_content}
</div>\n";
return $new_content;
});
```
but you'll notice this still might feel a little *hacky* as you're separating user-supplied content where unexpected user error can still happen. For example: line-breaks may be inconsistent between blockquotes.
You'd be better off creating [a custom metabox](https://developer.wordpress.org/plugins/metadata/custom-meta-boxes/) and/or using [post\_meta](https://codex.wordpress.org/Custom_Fields) to store these blockquotes individually, as meta data to the post. You can then throw them in before your content (with out parsing with regex) via `the_content` still, or you can edit your template files of your theme, or hook into another action in your theme. |
305,205 | <pre><code> <div class="vp-field vp-checkbox vp-checked-field vp-meta-single" data-vp-type="vp-checkbox" id="_custom_meta[category][]">
<div class="label">
<label>Categories</label>
</div>
<div class="field">
<div class="input">
<label>
<input class="vp-input" type="checkbox" name="_custom_meta[category][]" value="star">
<span></span>star</label>
<label>
<input class="vp-input" type="checkbox" name="_custom_meta[category][]" value="triangle">
<span></span>triangle</label>
<label>
<input class="vp-input" type="checkbox" name="_custom_meta[category][]" value="square">
<span></span>square
</label>
</div>
</div>
</div>'
</code></pre>
<p>I am trying to update the post meta checkboxes, but the below is not working. Any suggestions what i am doing wrong.</p>
<pre><code> $features[0] = "star";
$features[1] = "triangle";
$features[2] = "square";
update_post_meta($post_id, "category",$features);
</code></pre>
| [
{
"answer_id": 305210,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 0,
"selected": false,
"text": "<p>Your code:</p>\n\n<pre><code>$features[0] = \"star\";\n$features[1] = \"triangle\";\n$features[2] = \"square\";... | 2018/06/03 | [
"https://wordpress.stackexchange.com/questions/305205",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137606/"
] | ```
<div class="vp-field vp-checkbox vp-checked-field vp-meta-single" data-vp-type="vp-checkbox" id="_custom_meta[category][]">
<div class="label">
<label>Categories</label>
</div>
<div class="field">
<div class="input">
<label>
<input class="vp-input" type="checkbox" name="_custom_meta[category][]" value="star">
<span></span>star</label>
<label>
<input class="vp-input" type="checkbox" name="_custom_meta[category][]" value="triangle">
<span></span>triangle</label>
<label>
<input class="vp-input" type="checkbox" name="_custom_meta[category][]" value="square">
<span></span>square
</label>
</div>
</div>
</div>'
```
I am trying to update the post meta checkboxes, but the below is not working. Any suggestions what i am doing wrong.
```
$features[0] = "star";
$features[1] = "triangle";
$features[2] = "square";
update_post_meta($post_id, "category",$features);
``` | Ok, so probably the meta data is saved correctly, now we are going to retrieve it.
I'm not sure where and how you're adding this code, it looks like a metabox?
The checkboxes aren't magicly getting checked, you need to add some logic to it.
First we need to have a closer look how you save the checkbox data.
We want to save to the DB which checkboxes are checked.
This array:
```
$features = array();
$features[0] = "star";
$features[1] = "triangle";
$features[2] = "square";
```
Is not going to tell us which categories are checked.
We want to save the array like this:
```
$features = array();
$features['star'] = 1; // checked
$features['square'] = 0; // not checked
$features['triangle'] = 1; // checked
```
---
Above the checkbox HTML you need to get the features data (post\_meta) from the DB.
Add this above the html:
```
<?php
global $post;
$features = get_post_meta( $post->ID, 'category', true );
?>
```
When you want to check a checkbox you need to add the attribute `checked="checked"` to it.
We only want to do this if the features array from the DB is telling us to do so.
You can achieve this with this checkbox html:
```
<input type="checkbox" name="checkbox_name" id="checkbox_id" value="triangle" <?php echo (isset($features['triangle']) && $features['triangle']) ? 'checked="checked"' : '' ?> />
```
This:
```
<?php echo (isset($features['triangle']) && $features['triangle']) ? 'checked="checked"' : '' ?>
```
Checks if the array key (triangle) is present in the `$features` array and if the value is set to 1 (or any positive value). If yes, it outputs `checked="checked"`, if not, it does nothing.
Regards, Bjorn |
305,240 | <p>I have <code>wp_nav_menu</code></p>
<pre><code><nav class="site-nav links-to-floor">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#our-menu">Our Menu</a></li>
<li><a href="#">Events</a></li>
<li><a href="#">Galleries</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</nav>
</code></pre>
<p>I want to add <code>data-id="1" data-slug="home"</code> to <code><li></code></p>
<pre><code><nav class="site-nav links-to-floor">
<ul>
<li data-id="1" data-slug="home"><a href="#home">Home</a></li>
<li data-id="2" data-slug="our-menu"><a href="#our-menu">Our Menu</a></li>
<li data-id="3" data-slug="events"><a href="#">Events</a></li>
<li data-id="4" data-slug="galleries"><a href="#">Galleries</a></li>
<li data-id="5" data-slug="contact-us"><a href="#">Contact Us</a></li>
</ul>
</nav>
</code></pre>
| [
{
"answer_id": 305242,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>You have at least three options, depending on how extensive your demands are:</p>\n\n<ol>\n<li>There is a filter... | 2018/06/04 | [
"https://wordpress.stackexchange.com/questions/305240",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144773/"
] | I have `wp_nav_menu`
```
<nav class="site-nav links-to-floor">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#our-menu">Our Menu</a></li>
<li><a href="#">Events</a></li>
<li><a href="#">Galleries</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</nav>
```
I want to add `data-id="1" data-slug="home"` to `<li>`
```
<nav class="site-nav links-to-floor">
<ul>
<li data-id="1" data-slug="home"><a href="#home">Home</a></li>
<li data-id="2" data-slug="our-menu"><a href="#our-menu">Our Menu</a></li>
<li data-id="3" data-slug="events"><a href="#">Events</a></li>
<li data-id="4" data-slug="galleries"><a href="#">Galleries</a></li>
<li data-id="5" data-slug="contact-us"><a href="#">Contact Us</a></li>
</ul>
</nav>
``` | You have at least three options, depending on how extensive your demands are:
1. There is a filter towards the end of [`wp_nav_menu`](https://developer.wordpress.org/reference/functions/wp_nav_menu/) that lets you change the function's output. If the menu is fixed you could use this to do a simple find and replace on the html-string. This is an easy solution, but if you change your menu, you have to change the function.
2. A bit more complicated is replacing the whole generation process of `wp_nav_menu` with a [custom walker](https://wordpress.stackexchange.com/questions/14037/menu-items-description-custom-walker-for-wp-nav-menu) that generates the data-elements from information you can pull out of existing information from the admin menu page. This is what you seem to have in mind.
3. The most complicated approach would be to add a metabox to the admin menu page, which would allow you to add different data-items for every menu item. You would then still need a walker function as well. Probably not worth the effort. |
305,246 | <p>The Buddypress 3.0 uses <strong>bp-nouveau</strong> template as default. How can I override the CSS and other template files in WordPress theme? Earlier it would be done by copying <strong>bp-legacy</strong> folder into the WordPress theme folder and renaming it to <strong>buddypress</strong> but it does not seem to work for the bp-nouveau theme. Even if I copy it to the theme folder, BuddyPress continues to use the files from the buddypress pluginlocation.</p>
<p>I could not find any information about Buddypress 3.0 template structure in the codex. </p>
| [
{
"answer_id": 332068,
"author": "cdrck",
"author_id": 163449,
"author_profile": "https://wordpress.stackexchange.com/users/163449",
"pm_score": 2,
"selected": false,
"text": "<p>I know it is an old question but im pasting this here in case someone is looking for the same answer.</p>\n\n... | 2018/06/04 | [
"https://wordpress.stackexchange.com/questions/305246",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144778/"
] | The Buddypress 3.0 uses **bp-nouveau** template as default. How can I override the CSS and other template files in WordPress theme? Earlier it would be done by copying **bp-legacy** folder into the WordPress theme folder and renaming it to **buddypress** but it does not seem to work for the bp-nouveau theme. Even if I copy it to the theme folder, BuddyPress continues to use the files from the buddypress pluginlocation.
I could not find any information about Buddypress 3.0 template structure in the codex. | I know it is an old question but im pasting this here in case someone is looking for the same answer.
**Overloading Template Compatibility theme files**
Template compatibility also runs a check to see if two directories or folders exist in a theme:
```
'buddypress'
'community'
```
If either of these two folders exist in your theme and they contain BP template files then those files will be used in preference to the bp plugins versions.
Therefore, you can modify any bp theme compatibility template by copying it over from:
```
/bp-templates/bp-legacy/buddypress/
```
To:
```
/my-theme/community/ or /my-theme/buddypress/
```
N.B. Inside the subfolder `‘community’` **you must preserve the path structure/folders** that exist in the BP original /buddypress/ folder so /activity/ must be created to hold index.php or any of the other activity templates.
Additionally to keep things neat & tidy you can keep your custom parent template file ‘community.php’ in these folders as well rather than your theme root.
You may override the css by adding a folder /css/\* to your theme root if you then, either, copy buddypress.css from /bp-legacy/ or create a new file named buddypress.css this file will be used instead of the buddypress version.
\* As of BP 1.8 the paths for assets i.e styles and JS has been modified to look to your ‘buddypress’ or ‘community’ folders first, this means you will be able to locate your /css/ folder inside your buddypress one.
Source: <https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/> |
305,249 | <p>I'm developing a website where the username is a document number, called CPF (think of it as a national ID), which has the following mask:</p>
<pre><code>000.000.000-00
</code></pre>
<p>I'm storing the usernames as plain numbers, but all our forms must have the mask above, which in turn makes it so the <code>_POST['user_login']</code> always goes with the dash and dots. This is an example of a user's login/username:</p>
<pre><code>$_POST['user_login'] = '123.456.789-00'
$actual_username_ondb = '12345678900'
</code></pre>
<p>This wasn't a problem for logging in, as I hook into the <a href="https://codex.wordpress.org/Plugin_API/Action_Reference/wp_authenticate" rel="nofollow noreferrer">wp_authenticate</a> action hook <em>(not the pluggable function!)</em> and I filter the username before continuing (and also check if the number is a valid CPF):</p>
<pre><code>/**
* Hooks before login and filters out the CPF mask if it exists
*/
add_action( 'wp_authenticate' , 'filter_username' );
function filter_username(&$username) {
$cpf = preg_replace('/[^0-9]/is', '', $username);
if (is_valid_cpf($cpf)) {
$username = $cpf;
}
}
</code></pre>
<p>However, now I'm dealing with the lost password form, and I couldn't find any way to do the same as above, i.e.: filter <code>$_POST['user_login']</code> before going on with the password retrieval.</p>
<p>If there's any way to do it, it'd be via the hook <code>lostpassword_post</code>, because that's the earliest hook in the <a href="https://developer.wordpress.org/reference/functions/retrieve_password/" rel="nofollow noreferrer">retrieve_password()</a> function, but unfortunately it only triggers after the data is already parsed, so I don't know how it could be done.</p>
| [
{
"answer_id": 332068,
"author": "cdrck",
"author_id": 163449,
"author_profile": "https://wordpress.stackexchange.com/users/163449",
"pm_score": 2,
"selected": false,
"text": "<p>I know it is an old question but im pasting this here in case someone is looking for the same answer.</p>\n\n... | 2018/06/04 | [
"https://wordpress.stackexchange.com/questions/305249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28130/"
] | I'm developing a website where the username is a document number, called CPF (think of it as a national ID), which has the following mask:
```
000.000.000-00
```
I'm storing the usernames as plain numbers, but all our forms must have the mask above, which in turn makes it so the `_POST['user_login']` always goes with the dash and dots. This is an example of a user's login/username:
```
$_POST['user_login'] = '123.456.789-00'
$actual_username_ondb = '12345678900'
```
This wasn't a problem for logging in, as I hook into the [wp\_authenticate](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_authenticate) action hook *(not the pluggable function!)* and I filter the username before continuing (and also check if the number is a valid CPF):
```
/**
* Hooks before login and filters out the CPF mask if it exists
*/
add_action( 'wp_authenticate' , 'filter_username' );
function filter_username(&$username) {
$cpf = preg_replace('/[^0-9]/is', '', $username);
if (is_valid_cpf($cpf)) {
$username = $cpf;
}
}
```
However, now I'm dealing with the lost password form, and I couldn't find any way to do the same as above, i.e.: filter `$_POST['user_login']` before going on with the password retrieval.
If there's any way to do it, it'd be via the hook `lostpassword_post`, because that's the earliest hook in the [retrieve\_password()](https://developer.wordpress.org/reference/functions/retrieve_password/) function, but unfortunately it only triggers after the data is already parsed, so I don't know how it could be done. | I know it is an old question but im pasting this here in case someone is looking for the same answer.
**Overloading Template Compatibility theme files**
Template compatibility also runs a check to see if two directories or folders exist in a theme:
```
'buddypress'
'community'
```
If either of these two folders exist in your theme and they contain BP template files then those files will be used in preference to the bp plugins versions.
Therefore, you can modify any bp theme compatibility template by copying it over from:
```
/bp-templates/bp-legacy/buddypress/
```
To:
```
/my-theme/community/ or /my-theme/buddypress/
```
N.B. Inside the subfolder `‘community’` **you must preserve the path structure/folders** that exist in the BP original /buddypress/ folder so /activity/ must be created to hold index.php or any of the other activity templates.
Additionally to keep things neat & tidy you can keep your custom parent template file ‘community.php’ in these folders as well rather than your theme root.
You may override the css by adding a folder /css/\* to your theme root if you then, either, copy buddypress.css from /bp-legacy/ or create a new file named buddypress.css this file will be used instead of the buddypress version.
\* As of BP 1.8 the paths for assets i.e styles and JS has been modified to look to your ‘buddypress’ or ‘community’ folders first, this means you will be able to locate your /css/ folder inside your buddypress one.
Source: <https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/> |
305,280 | <p>I'm trying to include all my css and JS files of a theme using <code>functions.php</code>. Following is what I have done so far:</p>
<pre><code> <?php
function blogroom() {
wp_enqueue_style('bootstrap', get_stylesheet_directory_uri() . '/assets/lib/bootstrap/dist/css/bootstrap.min.css');
wp_enqueue_style('loaders', get_stylesheet_directory_uri() . '/assets/lib/loaders.css/loaders.min.css');
wp_enqueue_style('iconsmind', get_stylesheet_directory_uri() . '/assets/lib/iconsmind/iconsmind.css');
wp_enqueue_style('hamburgers', get_stylesheet_directory_uri() . '/assets/lib/hamburgers/dist/hamburgers.min.css');
wp_enqueue_style('font-awesome-css', get_stylesheet_directory_uri() . '/assets/lib/font-awesome/css/font-awesome.min.css');
wp_enqueue_style('theme-style', get_stylesheet_directory_uri() . '/assets/css/style.css');
wp_enqueue_style('theme-style', get_stylesheet_directory_uri() . '/assets/css/custom.css');
wp_register_script( 'bootstrap-js', get_template_directory_uri() . '/assets/lib/bootstrap/dist/js/bootstrap.min.js');
wp_register_script( 'imageloaded', get_template_directory_uri() . '/assets/lib/imagesloaded/imagesloaded.pkgd.min.js', array( 'bootstrap-js' ) );
wp_register_script( 'tweenmax', get_template_directory_uri() . '/assets/lib/gsap/src/minified/TweenMax.min.js', array('imageloaded') );
wp_register_script( 'scroll-to-plugin', get_template_directory_uri() . '/assets/lib/gsap/src/minified/plugins/ScrollToPlugin.min.js', array('tweenmax') );
wp_register_script( 'customToEase', get_template_directory_uri() . '/assets/lib/CustomEase.min.js', array('scroll-to-plugin') );
wp_register_script( 'configJs', get_template_directory_uri() . '/assets/js/config.js', array('customToEase') );
wp_register_script( 'zanimation', get_template_directory_uri() . '/assets/js/zanimation.js', array('configJs') );
wp_register_script( 'corejs', get_template_directory_uri() . '/assets/js/core.js', array('zanimation') );
wp_register_script( 'mainjs', get_template_directory_uri() . '/assets/js/main.js', array('corejs') );
wp_enqueue_script( 'mainjs' );
}
add_action( 'wp_enqueue_scripts', 'blogroom' );
?>
</code></pre>
<p>Here, this only loads my CSS file and not my js files. Not a single javascript file is loaded. Can someone please help? </p>
| [
{
"answer_id": 332068,
"author": "cdrck",
"author_id": 163449,
"author_profile": "https://wordpress.stackexchange.com/users/163449",
"pm_score": 2,
"selected": false,
"text": "<p>I know it is an old question but im pasting this here in case someone is looking for the same answer.</p>\n\n... | 2018/06/04 | [
"https://wordpress.stackexchange.com/questions/305280",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144795/"
] | I'm trying to include all my css and JS files of a theme using `functions.php`. Following is what I have done so far:
```
<?php
function blogroom() {
wp_enqueue_style('bootstrap', get_stylesheet_directory_uri() . '/assets/lib/bootstrap/dist/css/bootstrap.min.css');
wp_enqueue_style('loaders', get_stylesheet_directory_uri() . '/assets/lib/loaders.css/loaders.min.css');
wp_enqueue_style('iconsmind', get_stylesheet_directory_uri() . '/assets/lib/iconsmind/iconsmind.css');
wp_enqueue_style('hamburgers', get_stylesheet_directory_uri() . '/assets/lib/hamburgers/dist/hamburgers.min.css');
wp_enqueue_style('font-awesome-css', get_stylesheet_directory_uri() . '/assets/lib/font-awesome/css/font-awesome.min.css');
wp_enqueue_style('theme-style', get_stylesheet_directory_uri() . '/assets/css/style.css');
wp_enqueue_style('theme-style', get_stylesheet_directory_uri() . '/assets/css/custom.css');
wp_register_script( 'bootstrap-js', get_template_directory_uri() . '/assets/lib/bootstrap/dist/js/bootstrap.min.js');
wp_register_script( 'imageloaded', get_template_directory_uri() . '/assets/lib/imagesloaded/imagesloaded.pkgd.min.js', array( 'bootstrap-js' ) );
wp_register_script( 'tweenmax', get_template_directory_uri() . '/assets/lib/gsap/src/minified/TweenMax.min.js', array('imageloaded') );
wp_register_script( 'scroll-to-plugin', get_template_directory_uri() . '/assets/lib/gsap/src/minified/plugins/ScrollToPlugin.min.js', array('tweenmax') );
wp_register_script( 'customToEase', get_template_directory_uri() . '/assets/lib/CustomEase.min.js', array('scroll-to-plugin') );
wp_register_script( 'configJs', get_template_directory_uri() . '/assets/js/config.js', array('customToEase') );
wp_register_script( 'zanimation', get_template_directory_uri() . '/assets/js/zanimation.js', array('configJs') );
wp_register_script( 'corejs', get_template_directory_uri() . '/assets/js/core.js', array('zanimation') );
wp_register_script( 'mainjs', get_template_directory_uri() . '/assets/js/main.js', array('corejs') );
wp_enqueue_script( 'mainjs' );
}
add_action( 'wp_enqueue_scripts', 'blogroom' );
?>
```
Here, this only loads my CSS file and not my js files. Not a single javascript file is loaded. Can someone please help? | I know it is an old question but im pasting this here in case someone is looking for the same answer.
**Overloading Template Compatibility theme files**
Template compatibility also runs a check to see if two directories or folders exist in a theme:
```
'buddypress'
'community'
```
If either of these two folders exist in your theme and they contain BP template files then those files will be used in preference to the bp plugins versions.
Therefore, you can modify any bp theme compatibility template by copying it over from:
```
/bp-templates/bp-legacy/buddypress/
```
To:
```
/my-theme/community/ or /my-theme/buddypress/
```
N.B. Inside the subfolder `‘community’` **you must preserve the path structure/folders** that exist in the BP original /buddypress/ folder so /activity/ must be created to hold index.php or any of the other activity templates.
Additionally to keep things neat & tidy you can keep your custom parent template file ‘community.php’ in these folders as well rather than your theme root.
You may override the css by adding a folder /css/\* to your theme root if you then, either, copy buddypress.css from /bp-legacy/ or create a new file named buddypress.css this file will be used instead of the buddypress version.
\* As of BP 1.8 the paths for assets i.e styles and JS has been modified to look to your ‘buddypress’ or ‘community’ folders first, this means you will be able to locate your /css/ folder inside your buddypress one.
Source: <https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/> |
305,347 | <p>I'm trying to replace the default image picked by yoast (featured image) with a custom with the relative og:image:width and og:image:height, but seems a mission impossible!</p>
<p>I tryed with this:</p>
<pre><code>function my_own_og_function() {
$my_image_url = 'http://www.mywebsite.net/wp-content/uploads/TEST-A.jpg';
$GLOBALS['wpseo_og']->image( $my_image_url ); // This will echo out the og tag in line with other WPSEO og tags
}
add_action( 'wpseo_opengraph', 'my_own_og_function', 29 );
</code></pre>
<p>But yes, the image is replaced, only is without og:image:width and og:image:height</p>
<p>So i'm wondering, is there away to make it possible? Please, i need your help to make this, i have spent all the night trying to achive what i'm looking for... Thanks a lot! :)</p>
| [
{
"answer_id": 332068,
"author": "cdrck",
"author_id": 163449,
"author_profile": "https://wordpress.stackexchange.com/users/163449",
"pm_score": 2,
"selected": false,
"text": "<p>I know it is an old question but im pasting this here in case someone is looking for the same answer.</p>\n\n... | 2018/06/05 | [
"https://wordpress.stackexchange.com/questions/305347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144842/"
] | I'm trying to replace the default image picked by yoast (featured image) with a custom with the relative og:image:width and og:image:height, but seems a mission impossible!
I tryed with this:
```
function my_own_og_function() {
$my_image_url = 'http://www.mywebsite.net/wp-content/uploads/TEST-A.jpg';
$GLOBALS['wpseo_og']->image( $my_image_url ); // This will echo out the og tag in line with other WPSEO og tags
}
add_action( 'wpseo_opengraph', 'my_own_og_function', 29 );
```
But yes, the image is replaced, only is without og:image:width and og:image:height
So i'm wondering, is there away to make it possible? Please, i need your help to make this, i have spent all the night trying to achive what i'm looking for... Thanks a lot! :) | I know it is an old question but im pasting this here in case someone is looking for the same answer.
**Overloading Template Compatibility theme files**
Template compatibility also runs a check to see if two directories or folders exist in a theme:
```
'buddypress'
'community'
```
If either of these two folders exist in your theme and they contain BP template files then those files will be used in preference to the bp plugins versions.
Therefore, you can modify any bp theme compatibility template by copying it over from:
```
/bp-templates/bp-legacy/buddypress/
```
To:
```
/my-theme/community/ or /my-theme/buddypress/
```
N.B. Inside the subfolder `‘community’` **you must preserve the path structure/folders** that exist in the BP original /buddypress/ folder so /activity/ must be created to hold index.php or any of the other activity templates.
Additionally to keep things neat & tidy you can keep your custom parent template file ‘community.php’ in these folders as well rather than your theme root.
You may override the css by adding a folder /css/\* to your theme root if you then, either, copy buddypress.css from /bp-legacy/ or create a new file named buddypress.css this file will be used instead of the buddypress version.
\* As of BP 1.8 the paths for assets i.e styles and JS has been modified to look to your ‘buddypress’ or ‘community’ folders first, this means you will be able to locate your /css/ folder inside your buddypress one.
Source: <https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/> |
305,353 | <p>I'm using a theme child of <a href="https://wordpress.org/themes/ultra/" rel="nofollow noreferrer">Ultra Theme</a>. This theme is using this : </p>
<pre><code>add_theme_support( 'title-tag' );
</code></pre>
<p>I'd like to customize the title tag of all posts & pages, here is my code : </p>
<pre><code>add_filter( 'wp_title', 'my_custom_title', 10, 2);
function my_custom_title() {
return("Foo bar");
}
</code></pre>
<p>The code is not working and I can't figure out why !</p>
| [
{
"answer_id": 305546,
"author": "Sami",
"author_id": 102593,
"author_profile": "https://wordpress.stackexchange.com/users/102593",
"pm_score": 0,
"selected": false,
"text": "<p>This seems to be the problem's root :</p>\n\n<pre><code>add_theme_support( 'title-tag' );\n</code></pre>\n\n<p... | 2018/06/05 | [
"https://wordpress.stackexchange.com/questions/305353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102593/"
] | I'm using a theme child of [Ultra Theme](https://wordpress.org/themes/ultra/). This theme is using this :
```
add_theme_support( 'title-tag' );
```
I'd like to customize the title tag of all posts & pages, here is my code :
```
add_filter( 'wp_title', 'my_custom_title', 10, 2);
function my_custom_title() {
return("Foo bar");
}
```
The code is not working and I can't figure out why ! | When adding `title-tag` support in a theme, the title tag can be filtered by several filters, but not `wp_title`. The reason is that if the theme supports `title-tag`, WordPress uses [`wp_get_document_title()`](https://developer.wordpress.org/reference/functions/wp_get_document_title/) instead of [`wp_title()`](https://developer.wordpress.org/reference/functions/wp_title/).
For themes with support for `title-tag` you can use [`document_title_parts`](https://developer.wordpress.org/reference/hooks/document_title_parts/):
```
add_filter( 'document_title_parts', 'filter_document_title_parts' );
function filter_document_title_parts( $title_parts ) {
$title_parts['title'] = 'The title';
$title_parts['tagline'] = 'A tagline';
$title_parts['site'] = 'My Site';
return $title_parts;
}
```
Or [`pre_get_document_title`](https://developer.wordpress.org/reference/hooks/pre_get_document_title/):
```
add_filter( 'pre_get_document_title', 'filter_document_title' );
function filter_document_title( $title ) {
$title = 'The title';
return $title;
}
``` |
305,354 | <p>I am using the following hook to loop over my menu items and apply a class based on certain criteria.</p>
<pre><code>add_filter( 'nav_menu_css_class', 'highlight_base_category', 1, 3 );
</code></pre>
<p>The <code>nav_menu_css_class</code> filter runs for each individual menu item, but I want to completely halt the filter once the class has been applied to one menu item, to prevent more than one menu item having the same class.</p>
<p>I've been looking at setting a global boolean, or using a session, but it seems messy. </p>
<p>Is there a way of breaking out of the filter for the entirety of the current page request, or a global flag i could set and check each time a menu item is filtered?</p>
| [
{
"answer_id": 305356,
"author": "Chris J Allen",
"author_id": 44848,
"author_profile": "https://wordpress.stackexchange.com/users/44848",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like I just remove said filter, then it'll get reattached on the next page request.</p>\n\n<pre><... | 2018/06/05 | [
"https://wordpress.stackexchange.com/questions/305354",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44848/"
] | I am using the following hook to loop over my menu items and apply a class based on certain criteria.
```
add_filter( 'nav_menu_css_class', 'highlight_base_category', 1, 3 );
```
The `nav_menu_css_class` filter runs for each individual menu item, but I want to completely halt the filter once the class has been applied to one menu item, to prevent more than one menu item having the same class.
I've been looking at setting a global boolean, or using a session, but it seems messy.
Is there a way of breaking out of the filter for the entirety of the current page request, or a global flag i could set and check each time a menu item is filtered? | Yes, there is such way. All you need to do is to unregister your filter inside it:
```
function highlight_base_category( $classes, $item, $args ) {
// most probably you have some if statement here
if ( /* YOU CONDITION */ ) {
// your code
remove_filter( 'nav_menu_css_class', 'highlight_base_category', 1 );
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'highlight_base_category', 1, 3 );
``` |
305,372 | <p>Like many other, I would like to have:
<em>domain.com/post-title</em>
changed into
<em>domain.com/blog/post-title</em>
but only for the post type 'post', not for 'page' and especially not for the custom post types (of which my theme seems to have many).</p>
<p>I have done my research on this forum and other sources and I know the general answer seems to be:</p>
<blockquote>
<p>When you register your post type, the with_front argument of rewrite should be false.</p>
</blockquote>
<pre><code>$args = array(
'rewrite' => array( 'with_front' => false ),
);
register_post_type( 'your-post-type', $args );
</code></pre>
<p>Unfortunately, this does not help the beginners. We don't know what is meant by the instructions above. Apparently we should somehow re-register the default post type "post" (although the post type "post" already exists and is in use), but we don't know how and where to do that. If anyone can shed some light on the necessary procedure for changing the blog posts URLs, I would be most grateful.</p>
| [
{
"answer_id": 346935,
"author": "Rajilesh Panoli",
"author_id": 68892,
"author_profile": "https://wordpress.stackexchange.com/users/68892",
"pm_score": 0,
"selected": false,
"text": "<p>Did you tried this?</p>\n\n<pre><code>function generate_rewrite_rules( $wp_rewrite ) {\n $new_ru... | 2018/06/05 | [
"https://wordpress.stackexchange.com/questions/305372",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/53991/"
] | Like many other, I would like to have:
*domain.com/post-title*
changed into
*domain.com/blog/post-title*
but only for the post type 'post', not for 'page' and especially not for the custom post types (of which my theme seems to have many).
I have done my research on this forum and other sources and I know the general answer seems to be:
>
> When you register your post type, the with\_front argument of rewrite should be false.
>
>
>
```
$args = array(
'rewrite' => array( 'with_front' => false ),
);
register_post_type( 'your-post-type', $args );
```
Unfortunately, this does not help the beginners. We don't know what is meant by the instructions above. Apparently we should somehow re-register the default post type "post" (although the post type "post" already exists and is in use), but we don't know how and where to do that. If anyone can shed some light on the necessary procedure for changing the blog posts URLs, I would be most grateful. | I found the answer [here](https://wordpress.stackexchange.com/a/230313/128304). Remember to pop in there and give it a like.
I'll post it here, for people in a rush.
---
Put this into the `functions.php`-file:
```
function wp1482371_custom_post_type_args( $args, $post_type ) {
if ( $post_type == "post" ) {
$args['rewrite'] = array(
'slug' => 'blog'
);
}
return $args;
}
add_filter( 'register_post_type_args', 'wp1482371_custom_post_type_args', 20, 2 );
```
(Tested and works).
*Remember!!*
**Remember A)** Remember to update your permalinks afterwards (by going into **Settings** >> **Permalinks** >> **Click 'Save Changes'** ).
**Remember B)** If you get wierd results, then try opening an incognito-window and see if it words there. WordPress has a feature that redirects to '[Nearest Matching URL](http://biostall.com/prevent-wordpress-redirecting-to-nearest-matching-url/)', that can seem confusing, when playing around with permalinks.
---
You could also try to find a Plugin that does it. I wouldn't do that, since it's quite extensive to add a plugin for that sole purpose. But hey, - sometimes it can be satisfying to shoot birds with canons (no bird was harmed making this joke). |
305,378 | <p>I have a custom WordPress table using wp_list_table, with a search field: the search works well, but I am seeing that the search value isn't added to the pagination links when there are multiple pages of results. Here is my complete code:</p>
<pre><code>if ( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class Customers_List extends WP_List_Table {
/** Class constructor */
public function __construct() {
parent::__construct( [
'singular' => __( 'Order', 'sp' ), //singular name of the listed records
'plural' => __( 'Orders', 'sp' ), //plural name of the listed records
'ajax' => false //does this table support ajax?
] );
}
/**
* Retrieve customers data from the database
*
* @param int $per_page
* @param int $page_number
*
* @return mixed
*/
public static function get_customers( $per_page = 5, $page_number = 1 ) {
global $wpdb;
$sql = "SELECT * FROM old_order";
if( ! empty( $_REQUEST['s'] ) ){
$search = esc_sql( $_REQUEST['s'] );
$sql .= " WHERE firstname LIKE '%{$search}%'";
$sql .= " OR lastname LIKE '%{$search}%'";
$sql .= " OR order_id = '{$search}'";
}
if ( ! empty( $_REQUEST['orderby'] ) ) {
$sql .= ' ORDER BY ' . esc_sql( $_REQUEST['orderby'] );
$sql .= ! empty( $_REQUEST['order'] ) ? ' ' . esc_sql( $_REQUEST['order'] ) : ' ASC';
}
$sql .= " LIMIT $per_page";
$sql .= ' OFFSET ' . ( $page_number - 1 ) * $per_page;
// echo $sql;
$result = $wpdb->get_results( $sql, 'ARRAY_A' );
return $result;
}
/**
* Delete a customer record.
*
* @param int $id customer ID
*/
public static function delete_customer( $id ) {
global $wpdb;
$wpdb->delete(
"old_order",
[ 'ID' => $id ],
[ '%d' ]
);
}
/**
* Returns the count of records in the database.
*
* @return null|string
*/
public static function record_count() {
global $wpdb;
$sql = "SELECT COUNT(*) FROM old_order";
if( ! empty( $_REQUEST['s'] ) ){
$search = esc_sql( $_REQUEST['s'] );
$sql .= " WHERE firstname LIKE '%{$search}%'";
$sql .= " OR lastname LIKE '%{$search}%'";
$sql .= " OR order_id LIKE '%{$search}%'";
}
return $wpdb->get_var( $sql );
}
/** Text displayed when no customer data is available */
public function no_items() {
_e( 'No orders available..', 'sp' );
}
/**
* Render a column when no column specific method exist.
*
* @param array $item
* @param string $column_name
*
* @return mixed
*/
public function column_default( $item, $column_name ) {
switch ( $column_name ) {
case 'order_id':
return $item[ $column_name ];
case 'firstname':
return $item[ $column_name ];
case 'lastname':
return $item[ $column_name ];
case 'total':
return "$" . number_format( $item[ $column_name ] );
case 'date_added':
return date('m/d/Y g:i:s A', strtotime( $item[ $column_name ] ) );
default:
return print_r( $item, true ); //Show the whole array for troubleshooting purposes
}
}
/**
* Render the bulk edit checkbox
*
* @param array $item
*
* @return string
*/
function column_cb( $item ) {
return sprintf(
'<input type="checkbox" name="bulk-delete[]" value="%s" />', $item['ID']
);
}
/**
* Method for name column
*
* @param array $item an array of DB data
*
* @return string
*/
function column_name( $item ) {
$delete_nonce = wp_create_nonce( 'sp_delete_customer' );
$title = '<strong>' . $item['name'] . '</strong>';
$actions = [
'delete' => sprintf( '<a href="?page=%s&action=%s&customer=%s&_wpnonce=%s">Delete</a>', esc_attr( $_REQUEST['page'] ), 'delete', absint( $item['ID'] ), $delete_nonce )
];
return $title . $this->row_actions( $actions );
}
/**
* Associative array of columns
*
* @return array
*/
function get_columns() {
$columns = [
'cb' => '<input type="checkbox" />',
'order_id' => __( 'Order ID', 'sp' ),
'firstname' => __( 'First Name', 'sp' ),
'lastname' => __( 'Last Name', 'sp' ),
'total' => __( 'Total', 'sp' ),
'date_added' => __( 'Date Added', 'sp' )
];
return $columns;
}
/**
* Columns to make sortable.
*
* @return array
*/
public function get_sortable_columns() {
$sortable_columns = array(
'order_id' => array( 'order_id', true ),
'firstname' => array( 'firstname', true ),
'lastname' => array( 'lastname', true )
);
return $sortable_columns;
}
/**
* Returns an associative array containing the bulk action
*
* @return array
*/
public function get_bulk_actions() {
$actions = [
'bulk-delete' => 'Delete'
];
return $actions;
}
/**
* Handles data query and filter, sorting, and pagination.
*/
public function prepare_items( ) {
$this->_column_headers = $this->get_column_info();
/** Process bulk action */
$this->process_bulk_action();
$per_page = $this->get_items_per_page( 'customers_per_page', 20 );
$current_page = $this->get_pagenum();
$total_items = self::record_count();
$this->set_pagination_args( [
'total_items' => $total_items, //WE have to calculate the total number of items
'per_page' => $per_page //WE have to determine how many items to show on a page
] );
$this->items = self::get_customers( $per_page, $current_page );
}
public function process_bulk_action() {
//Detect when a bulk action is being triggered...
if ( 'delete' === $this->current_action() ) {
// In our file that handles the request, verify the nonce.
$nonce = esc_attr( $_REQUEST['_wpnonce'] );
if ( ! wp_verify_nonce( $nonce, 'sp_delete_customer' ) ) {
die( 'Go get a life script kiddies' );
}
else {
self::delete_customer( absint( $_GET['customer'] ) );
// esc_url_raw() is used to prevent converting ampersand in url to "#038;"
// add_query_arg() return the current url
wp_redirect( esc_url_raw(add_query_arg()) );
exit;
}
}
// If the delete bulk action is triggered
if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-delete' )
|| ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-delete' )
) {
$delete_ids = esc_sql( $_POST['bulk-delete'] );
// loop over the array of record IDs and delete them
foreach ( $delete_ids as $id ) {
self::delete_customer( $id );
}
// esc_url_raw() is used to prevent converting ampersand in url to "#038;"
// add_query_arg() return the current url
wp_redirect( esc_url_raw(add_query_arg()) );
exit;
}
}
}
class SP_Plugin {
// class instance
static $instance;
// customer WP_List_Table object
public $customers_obj;
// class constructor
public function __construct() {
add_filter( 'set-screen-option', [ __CLASS__, 'set_screen' ], 10, 3 );
add_action( 'admin_menu', [ $this, 'plugin_menu' ] );
}
public static function set_screen( $status, $option, $value ) {
return $value;
}
public function plugin_menu() {
$hook = add_menu_page(
'Order Lookup',
'Order Lookup',
'manage_options',
'wp_list_table_class',
[ $this, 'plugin_settings_page' ]
);
add_action( "load-$hook", [ $this, 'screen_option' ] );
}
/**
* Plugin settings page
*/
public function plugin_settings_page() {
?>
<div class="wrap">
<h2>Previous Order System Lookup</h2>
<div id="poststuff">
<div id="post-body" class="metabox-holder columns-2">
<div id="post-body-content">
<div class="meta-box-sortables ui-sortable">
<form method="get">
<?php
$this->customers_obj->prepare_items();
$this->customers_obj->search_box('Search', 'search');
$this->customers_obj->display(); ?>
</form>
</div>
</div>
</div>
<br class="clear">
</div>
</div>
<?php
}
/**
* Screen options
*/
public function screen_option() {
$option = 'per_page';
$args = [
'label' => 'Customers',
'default' => 20,
'option' => 'customers_per_page'
];
add_screen_option( $option, $args );
$this->customers_obj = new Customers_List();
}
/** Singleton instance */
public static function get_instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
}
add_action( 'plugins_loaded', function () {
SP_Plugin::get_instance();
} );
</code></pre>
<p>Everything works as intended, except for adding the search value to the pagination links when there are multiple pages. So when you click on 'next' it removed the search value and returns all the results (on the next page). I used this Gist as a reference: <a href="https://gist.github.com/paulund/7659452" rel="nofollow noreferrer">https://gist.github.com/paulund/7659452</a></p>
| [
{
"answer_id": 306141,
"author": "keithp",
"author_id": 144861,
"author_profile": "https://wordpress.stackexchange.com/users/144861",
"pm_score": 2,
"selected": false,
"text": "<p>I solved my issue by passing the page variable as a hidden field:</p>\n\n<pre><code><form method=\"get\"&... | 2018/06/05 | [
"https://wordpress.stackexchange.com/questions/305378",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144861/"
] | I have a custom WordPress table using wp\_list\_table, with a search field: the search works well, but I am seeing that the search value isn't added to the pagination links when there are multiple pages of results. Here is my complete code:
```
if ( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class Customers_List extends WP_List_Table {
/** Class constructor */
public function __construct() {
parent::__construct( [
'singular' => __( 'Order', 'sp' ), //singular name of the listed records
'plural' => __( 'Orders', 'sp' ), //plural name of the listed records
'ajax' => false //does this table support ajax?
] );
}
/**
* Retrieve customers data from the database
*
* @param int $per_page
* @param int $page_number
*
* @return mixed
*/
public static function get_customers( $per_page = 5, $page_number = 1 ) {
global $wpdb;
$sql = "SELECT * FROM old_order";
if( ! empty( $_REQUEST['s'] ) ){
$search = esc_sql( $_REQUEST['s'] );
$sql .= " WHERE firstname LIKE '%{$search}%'";
$sql .= " OR lastname LIKE '%{$search}%'";
$sql .= " OR order_id = '{$search}'";
}
if ( ! empty( $_REQUEST['orderby'] ) ) {
$sql .= ' ORDER BY ' . esc_sql( $_REQUEST['orderby'] );
$sql .= ! empty( $_REQUEST['order'] ) ? ' ' . esc_sql( $_REQUEST['order'] ) : ' ASC';
}
$sql .= " LIMIT $per_page";
$sql .= ' OFFSET ' . ( $page_number - 1 ) * $per_page;
// echo $sql;
$result = $wpdb->get_results( $sql, 'ARRAY_A' );
return $result;
}
/**
* Delete a customer record.
*
* @param int $id customer ID
*/
public static function delete_customer( $id ) {
global $wpdb;
$wpdb->delete(
"old_order",
[ 'ID' => $id ],
[ '%d' ]
);
}
/**
* Returns the count of records in the database.
*
* @return null|string
*/
public static function record_count() {
global $wpdb;
$sql = "SELECT COUNT(*) FROM old_order";
if( ! empty( $_REQUEST['s'] ) ){
$search = esc_sql( $_REQUEST['s'] );
$sql .= " WHERE firstname LIKE '%{$search}%'";
$sql .= " OR lastname LIKE '%{$search}%'";
$sql .= " OR order_id LIKE '%{$search}%'";
}
return $wpdb->get_var( $sql );
}
/** Text displayed when no customer data is available */
public function no_items() {
_e( 'No orders available..', 'sp' );
}
/**
* Render a column when no column specific method exist.
*
* @param array $item
* @param string $column_name
*
* @return mixed
*/
public function column_default( $item, $column_name ) {
switch ( $column_name ) {
case 'order_id':
return $item[ $column_name ];
case 'firstname':
return $item[ $column_name ];
case 'lastname':
return $item[ $column_name ];
case 'total':
return "$" . number_format( $item[ $column_name ] );
case 'date_added':
return date('m/d/Y g:i:s A', strtotime( $item[ $column_name ] ) );
default:
return print_r( $item, true ); //Show the whole array for troubleshooting purposes
}
}
/**
* Render the bulk edit checkbox
*
* @param array $item
*
* @return string
*/
function column_cb( $item ) {
return sprintf(
'<input type="checkbox" name="bulk-delete[]" value="%s" />', $item['ID']
);
}
/**
* Method for name column
*
* @param array $item an array of DB data
*
* @return string
*/
function column_name( $item ) {
$delete_nonce = wp_create_nonce( 'sp_delete_customer' );
$title = '<strong>' . $item['name'] . '</strong>';
$actions = [
'delete' => sprintf( '<a href="?page=%s&action=%s&customer=%s&_wpnonce=%s">Delete</a>', esc_attr( $_REQUEST['page'] ), 'delete', absint( $item['ID'] ), $delete_nonce )
];
return $title . $this->row_actions( $actions );
}
/**
* Associative array of columns
*
* @return array
*/
function get_columns() {
$columns = [
'cb' => '<input type="checkbox" />',
'order_id' => __( 'Order ID', 'sp' ),
'firstname' => __( 'First Name', 'sp' ),
'lastname' => __( 'Last Name', 'sp' ),
'total' => __( 'Total', 'sp' ),
'date_added' => __( 'Date Added', 'sp' )
];
return $columns;
}
/**
* Columns to make sortable.
*
* @return array
*/
public function get_sortable_columns() {
$sortable_columns = array(
'order_id' => array( 'order_id', true ),
'firstname' => array( 'firstname', true ),
'lastname' => array( 'lastname', true )
);
return $sortable_columns;
}
/**
* Returns an associative array containing the bulk action
*
* @return array
*/
public function get_bulk_actions() {
$actions = [
'bulk-delete' => 'Delete'
];
return $actions;
}
/**
* Handles data query and filter, sorting, and pagination.
*/
public function prepare_items( ) {
$this->_column_headers = $this->get_column_info();
/** Process bulk action */
$this->process_bulk_action();
$per_page = $this->get_items_per_page( 'customers_per_page', 20 );
$current_page = $this->get_pagenum();
$total_items = self::record_count();
$this->set_pagination_args( [
'total_items' => $total_items, //WE have to calculate the total number of items
'per_page' => $per_page //WE have to determine how many items to show on a page
] );
$this->items = self::get_customers( $per_page, $current_page );
}
public function process_bulk_action() {
//Detect when a bulk action is being triggered...
if ( 'delete' === $this->current_action() ) {
// In our file that handles the request, verify the nonce.
$nonce = esc_attr( $_REQUEST['_wpnonce'] );
if ( ! wp_verify_nonce( $nonce, 'sp_delete_customer' ) ) {
die( 'Go get a life script kiddies' );
}
else {
self::delete_customer( absint( $_GET['customer'] ) );
// esc_url_raw() is used to prevent converting ampersand in url to "#038;"
// add_query_arg() return the current url
wp_redirect( esc_url_raw(add_query_arg()) );
exit;
}
}
// If the delete bulk action is triggered
if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-delete' )
|| ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-delete' )
) {
$delete_ids = esc_sql( $_POST['bulk-delete'] );
// loop over the array of record IDs and delete them
foreach ( $delete_ids as $id ) {
self::delete_customer( $id );
}
// esc_url_raw() is used to prevent converting ampersand in url to "#038;"
// add_query_arg() return the current url
wp_redirect( esc_url_raw(add_query_arg()) );
exit;
}
}
}
class SP_Plugin {
// class instance
static $instance;
// customer WP_List_Table object
public $customers_obj;
// class constructor
public function __construct() {
add_filter( 'set-screen-option', [ __CLASS__, 'set_screen' ], 10, 3 );
add_action( 'admin_menu', [ $this, 'plugin_menu' ] );
}
public static function set_screen( $status, $option, $value ) {
return $value;
}
public function plugin_menu() {
$hook = add_menu_page(
'Order Lookup',
'Order Lookup',
'manage_options',
'wp_list_table_class',
[ $this, 'plugin_settings_page' ]
);
add_action( "load-$hook", [ $this, 'screen_option' ] );
}
/**
* Plugin settings page
*/
public function plugin_settings_page() {
?>
<div class="wrap">
<h2>Previous Order System Lookup</h2>
<div id="poststuff">
<div id="post-body" class="metabox-holder columns-2">
<div id="post-body-content">
<div class="meta-box-sortables ui-sortable">
<form method="get">
<?php
$this->customers_obj->prepare_items();
$this->customers_obj->search_box('Search', 'search');
$this->customers_obj->display(); ?>
</form>
</div>
</div>
</div>
<br class="clear">
</div>
</div>
<?php
}
/**
* Screen options
*/
public function screen_option() {
$option = 'per_page';
$args = [
'label' => 'Customers',
'default' => 20,
'option' => 'customers_per_page'
];
add_screen_option( $option, $args );
$this->customers_obj = new Customers_List();
}
/** Singleton instance */
public static function get_instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
}
add_action( 'plugins_loaded', function () {
SP_Plugin::get_instance();
} );
```
Everything works as intended, except for adding the search value to the pagination links when there are multiple pages. So when you click on 'next' it removed the search value and returns all the results (on the next page). I used this Gist as a reference: <https://gist.github.com/paulund/7659452> | I solved my issue by passing the page variable as a hidden field:
```
<form method="get">
<input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>" />
<?php
$this->customers_obj->prepare_items();
$this->customers_obj->search_box('Search', 'search');
$this->customers_obj->display(); ?>
</form>
``` |
305,425 | <pre><code><?php
namespace wp_gdpr_wc\controller;
use wp_gdpr\lib\Gdpr_Language;
class Controller_Menu_Page_Wc {
const PRIVACY_POLICY_TEXT_WOO_REQUEST = 'gdpr_priv_pov_text_woo_request';
const NOT_CONSENT_WOO_REQUEST = 'gdpr_not_consent_woo_request';
/**
* Controller_Menu_Page constructor.
*/
public function __construct() {
add_action( 'add_on_settings_menu_page', array( $this, 'build_form_to_enter_license' ), 11 );
//display woocommerce privacy policies
add_action( 'gdpr_display_custom_privacy_policy', array( $this, 'display_woocommerce_privacy_policies' ) );
add_action( 'gdpr_save_custom_privacy_policy', array( $this, 'save_woocommerce_privacy_policies' ), 10, 1 );
}
/**
* build form to include licens
*/
public function build_form_to_enter_license() {
require_once GDPR_WC_DIR . 'view/admin/menu-page.php';
}
/**
* Display WooCommerce privacy policies
*
* @since 1.1
*/
public function display_woocommerce_privacy_policies() {
$privacy_policy_strings = static::get_privacy_policy_strings();
include GDPR_WC_DIR . 'view/admin/privacy-policy.php';
}
/**
* Saves WooCommerce privacy policies
*
* @since 1.1
*/
public function save_woocommerce_privacy_policies( $lang ) {
update_option( self::PRIVACY_POLICY_TEXT_WOO_REQUEST . $lang, $_REQUEST['gdpr_priv_pov_text_woo_request'] );
}
/**
* TODO re-read the default text
*
* Returns WooCommerce privacy policy strings
*
* @return array
*
* @since 1.1
*/
public static function get_privacy_policy_strings() {
$lang = new Gdpr_Language();
$lang = $lang->get_language();
$privacy_policy_text_woo_request = get_option( self::PRIVACY_POLICY_TEXT_WOO_REQUEST . $lang, null );
$not_consent_woo_request = get_option( self::NOT_CONSENT_WOO_REQUEST . $lang, null );
if ( ! isset( $privacy_policy_text_woo_request ) ) {
$string = __( 'I consent to having %s collect my personal data and use it for administrative purposes.
For more info check our privacy policy where you\'ll get more info on where, how and why we store your data.', 'wp_gdpr' );
$blog_name = get_bloginfo( 'name' );
$privacy_policy_text_data_request = sprintf( $string, $blog_name );
update_option( self::PRIVACY_POLICY_TEXT_WOO_REQUEST . $lang, $privacy_policy_text_data_request );
}
if ( ! isset( $not_consent_woo_request ) ) {
$string = __( 'The consent checkbox was not checked.', 'wp_gdpr' );
$not_consent_woo_request = $string;
update_option( self::NOT_CONSENT_WOO_REQUEST . $lang, $not_consent_woo_request );
}
$privacy_policy_strings = array(
self::PRIVACY_POLICY_TEXT_WOO_REQUEST => $privacy_policy_text_woo_request,
self::NOT_CONSENT_WOO_REQUEST => $not_consent_woo_request
);
return $privacy_policy_strings;
}
}
</code></pre>
<p>I want to edit this text <code>$string = __( 'I consent to having %s collect my personal data and use it for administrative purposes. For more info check our privacy policy where you\'ll get more info on where, how and why we store your data.', 'wp_gdpr' );</code>
How can I do it since there are no hooks in the plugin? I thought maybe to extend the class, but I don't know if it's possible to edit an existing function.</p>
<p>I tried this and it's not working.</p>
<pre><code>use wp_gdpr_wc\controller\Controller_Menu_Page_Wc;
class test extends Controller_Menu_Page_Wc{
public static function get_privacy_policy_strings() {
$lang = new Gdpr_Language();
$lang = $lang->get_language();
$privacy_policy_text_woo_request = get_option( self::PRIVACY_POLICY_TEXT_WOO_REQUEST . $lang, null );
$not_consent_woo_request = get_option( self::NOT_CONSENT_WOO_REQUEST . $lang, null );
if ( ! isset( $privacy_policy_text_woo_request ) ) {
$string = __( 'I consent to having %s collect my personal data and use it for administrative purposes.
For more info check our privacy policyss where you\'ll get more info on where, how and why we store your data.', 'wp_gdpr' );
$blog_name = get_bloginfo( 'name' );
$privacy_policy_text_data_request = sprintf( $string, $blog_name );
update_option( self::PRIVACY_POLICY_TEXT_WOO_REQUEST . $lang, $privacy_policy_text_data_request );
}
if ( ! isset( $not_consent_woo_request ) ) {
$string = __( 'The consent checkbox was not checked.', 'wp_gdpr' );
$not_consent_woo_request = $string;
update_option( self::NOT_CONSENT_WOO_REQUEST . $lang, $not_consent_woo_request );
}
$privacy_policy_strings = array(
self::PRIVACY_POLICY_TEXT_WOO_REQUEST => $privacy_policy_text_woo_request,
self::NOT_CONSENT_WOO_REQUEST => $not_consent_woo_request
);
return $privacy_policy_strings;
}
}
</code></pre>
<p>Edit: Fortunately I could edit that text from <code>wp_options</code> table in database, If someone has any idea how to do it from code, that would be useful for times!</p>
| [
{
"answer_id": 305426,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": false,
"text": "<p>Editing other plugins' or themes' files that don't have proper hooks or filters is complicated.</p>\n\n<p>Chan... | 2018/06/06 | [
"https://wordpress.stackexchange.com/questions/305425",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142375/"
] | ```
<?php
namespace wp_gdpr_wc\controller;
use wp_gdpr\lib\Gdpr_Language;
class Controller_Menu_Page_Wc {
const PRIVACY_POLICY_TEXT_WOO_REQUEST = 'gdpr_priv_pov_text_woo_request';
const NOT_CONSENT_WOO_REQUEST = 'gdpr_not_consent_woo_request';
/**
* Controller_Menu_Page constructor.
*/
public function __construct() {
add_action( 'add_on_settings_menu_page', array( $this, 'build_form_to_enter_license' ), 11 );
//display woocommerce privacy policies
add_action( 'gdpr_display_custom_privacy_policy', array( $this, 'display_woocommerce_privacy_policies' ) );
add_action( 'gdpr_save_custom_privacy_policy', array( $this, 'save_woocommerce_privacy_policies' ), 10, 1 );
}
/**
* build form to include licens
*/
public function build_form_to_enter_license() {
require_once GDPR_WC_DIR . 'view/admin/menu-page.php';
}
/**
* Display WooCommerce privacy policies
*
* @since 1.1
*/
public function display_woocommerce_privacy_policies() {
$privacy_policy_strings = static::get_privacy_policy_strings();
include GDPR_WC_DIR . 'view/admin/privacy-policy.php';
}
/**
* Saves WooCommerce privacy policies
*
* @since 1.1
*/
public function save_woocommerce_privacy_policies( $lang ) {
update_option( self::PRIVACY_POLICY_TEXT_WOO_REQUEST . $lang, $_REQUEST['gdpr_priv_pov_text_woo_request'] );
}
/**
* TODO re-read the default text
*
* Returns WooCommerce privacy policy strings
*
* @return array
*
* @since 1.1
*/
public static function get_privacy_policy_strings() {
$lang = new Gdpr_Language();
$lang = $lang->get_language();
$privacy_policy_text_woo_request = get_option( self::PRIVACY_POLICY_TEXT_WOO_REQUEST . $lang, null );
$not_consent_woo_request = get_option( self::NOT_CONSENT_WOO_REQUEST . $lang, null );
if ( ! isset( $privacy_policy_text_woo_request ) ) {
$string = __( 'I consent to having %s collect my personal data and use it for administrative purposes.
For more info check our privacy policy where you\'ll get more info on where, how and why we store your data.', 'wp_gdpr' );
$blog_name = get_bloginfo( 'name' );
$privacy_policy_text_data_request = sprintf( $string, $blog_name );
update_option( self::PRIVACY_POLICY_TEXT_WOO_REQUEST . $lang, $privacy_policy_text_data_request );
}
if ( ! isset( $not_consent_woo_request ) ) {
$string = __( 'The consent checkbox was not checked.', 'wp_gdpr' );
$not_consent_woo_request = $string;
update_option( self::NOT_CONSENT_WOO_REQUEST . $lang, $not_consent_woo_request );
}
$privacy_policy_strings = array(
self::PRIVACY_POLICY_TEXT_WOO_REQUEST => $privacy_policy_text_woo_request,
self::NOT_CONSENT_WOO_REQUEST => $not_consent_woo_request
);
return $privacy_policy_strings;
}
}
```
I want to edit this text `$string = __( 'I consent to having %s collect my personal data and use it for administrative purposes. For more info check our privacy policy where you\'ll get more info on where, how and why we store your data.', 'wp_gdpr' );`
How can I do it since there are no hooks in the plugin? I thought maybe to extend the class, but I don't know if it's possible to edit an existing function.
I tried this and it's not working.
```
use wp_gdpr_wc\controller\Controller_Menu_Page_Wc;
class test extends Controller_Menu_Page_Wc{
public static function get_privacy_policy_strings() {
$lang = new Gdpr_Language();
$lang = $lang->get_language();
$privacy_policy_text_woo_request = get_option( self::PRIVACY_POLICY_TEXT_WOO_REQUEST . $lang, null );
$not_consent_woo_request = get_option( self::NOT_CONSENT_WOO_REQUEST . $lang, null );
if ( ! isset( $privacy_policy_text_woo_request ) ) {
$string = __( 'I consent to having %s collect my personal data and use it for administrative purposes.
For more info check our privacy policyss where you\'ll get more info on where, how and why we store your data.', 'wp_gdpr' );
$blog_name = get_bloginfo( 'name' );
$privacy_policy_text_data_request = sprintf( $string, $blog_name );
update_option( self::PRIVACY_POLICY_TEXT_WOO_REQUEST . $lang, $privacy_policy_text_data_request );
}
if ( ! isset( $not_consent_woo_request ) ) {
$string = __( 'The consent checkbox was not checked.', 'wp_gdpr' );
$not_consent_woo_request = $string;
update_option( self::NOT_CONSENT_WOO_REQUEST . $lang, $not_consent_woo_request );
}
$privacy_policy_strings = array(
self::PRIVACY_POLICY_TEXT_WOO_REQUEST => $privacy_policy_text_woo_request,
self::NOT_CONSENT_WOO_REQUEST => $not_consent_woo_request
);
return $privacy_policy_strings;
}
}
```
Edit: Fortunately I could edit that text from `wp_options` table in database, If someone has any idea how to do it from code, that would be useful for times! | There is a filter you can use, but it is well hidden. Take a look at the [WordPress function `__`](https://developer.wordpress.org/reference/functions/__/). As you can see it calls another function, [`translate`](https://developer.wordpress.org/reference/functions/translate/). And there it is, a filter called `gettext`. You can use it to intercept any (translated) text that is run through `__`.
Basically, what you do is overwrite the translation, which will be the same as the original text if no translation is available for the current language. Like this:
```
add_filter ('gettext','wpse305425_change_string',10,3);
function wpse305425_change_string ($translation, $text, $domain) {
if ($text == 'I consent to ...') $translation = 'your text';
return $translation;
}
``` |
305,472 | <p>I basically want to add an embedded form at the end of every blog post just below the main content area (I tried adding in the footer but it gets skipped due to showing up at the very bottom of the page). Where exactly do I put the code in the editor?</p>
| [
{
"answer_id": 305426,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": false,
"text": "<p>Editing other plugins' or themes' files that don't have proper hooks or filters is complicated.</p>\n\n<p>Chan... | 2018/06/06 | [
"https://wordpress.stackexchange.com/questions/305472",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144928/"
] | I basically want to add an embedded form at the end of every blog post just below the main content area (I tried adding in the footer but it gets skipped due to showing up at the very bottom of the page). Where exactly do I put the code in the editor? | There is a filter you can use, but it is well hidden. Take a look at the [WordPress function `__`](https://developer.wordpress.org/reference/functions/__/). As you can see it calls another function, [`translate`](https://developer.wordpress.org/reference/functions/translate/). And there it is, a filter called `gettext`. You can use it to intercept any (translated) text that is run through `__`.
Basically, what you do is overwrite the translation, which will be the same as the original text if no translation is available for the current language. Like this:
```
add_filter ('gettext','wpse305425_change_string',10,3);
function wpse305425_change_string ($translation, $text, $domain) {
if ($text == 'I consent to ...') $translation = 'your text';
return $translation;
}
``` |
305,488 | <p>I have been trying over and over but have come up empty handed. I have followed this tutorial (<a href="https://www.atomicsmash.co.uk/blog/customising-the-woocommerce-my-account-section/" rel="nofollow noreferrer">https://www.atomicsmash.co.uk/blog/customising-the-woocommerce-my-account-section/</a>) to create a new php page for 'My accounts' menu. for some reason it will not link to the new endpoint and constantly revert to dashboard...</p>
<p>here is the code I have added to my themes function.php file;</p>
<pre><code>/**
* Register new endpoints to use inside My Account page.
*/
add_action( 'init', 'my_account_new_endpoints' );
function my_account_new_endpoints() {
add_rewrite_endpoint( 'earnings', EP_ROOT | EP_PAGES );
}
/**
* Get new endpoint content
*/
// Awards
add_action( 'woocommerce_earnings_endpoint', 'earnings_endpoint_content' );
function earnings_endpoint_content() {
get_template_part('earnings');
}
/**
* Edit my account menu order
*/
function my_account_menu_order() {
$menuOrder = array(
'dashboard' => __( 'Dashboard', 'woocommerce' ),
'orders' => __( 'Your Orders', 'woocommerce' ),
'earnings' => __( 'Earnings', 'woocommerce' ),
//'downloads' => __( 'Download', 'woocommerce' ),
'edit-address' => __( 'Addresses', 'woocommerce' ),
'edit-account' => __( 'Account Details', 'woocommerce' ),
'customer-logout' => __( 'Logout', 'woocommerce' ),
);
return $menuOrder;
}
add_filter ( 'woocommerce_account_menu_items', 'my_account_menu_order' );
</code></pre>
<p>I have saved and flushed the permalinks settings multiple times too... no luck. The new page I have added is in woocommerce/templates/myaccount/earnings.php</p>
<p>the earnings.php page simply has this so I know when and if I get it;</p>
<pre><code><?php
echo ‘HELLO MOM’;
</code></pre>
<p>Thank you in advance :)</p>
| [
{
"answer_id": 312165,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 0,
"selected": false,
"text": "<p>In your code, you have not added endpoint to query vars.</p>\n\n<p>Missing code:</p>\n\n<pre><code>function cus... | 2018/06/07 | [
"https://wordpress.stackexchange.com/questions/305488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144937/"
] | I have been trying over and over but have come up empty handed. I have followed this tutorial (<https://www.atomicsmash.co.uk/blog/customising-the-woocommerce-my-account-section/>) to create a new php page for 'My accounts' menu. for some reason it will not link to the new endpoint and constantly revert to dashboard...
here is the code I have added to my themes function.php file;
```
/**
* Register new endpoints to use inside My Account page.
*/
add_action( 'init', 'my_account_new_endpoints' );
function my_account_new_endpoints() {
add_rewrite_endpoint( 'earnings', EP_ROOT | EP_PAGES );
}
/**
* Get new endpoint content
*/
// Awards
add_action( 'woocommerce_earnings_endpoint', 'earnings_endpoint_content' );
function earnings_endpoint_content() {
get_template_part('earnings');
}
/**
* Edit my account menu order
*/
function my_account_menu_order() {
$menuOrder = array(
'dashboard' => __( 'Dashboard', 'woocommerce' ),
'orders' => __( 'Your Orders', 'woocommerce' ),
'earnings' => __( 'Earnings', 'woocommerce' ),
//'downloads' => __( 'Download', 'woocommerce' ),
'edit-address' => __( 'Addresses', 'woocommerce' ),
'edit-account' => __( 'Account Details', 'woocommerce' ),
'customer-logout' => __( 'Logout', 'woocommerce' ),
);
return $menuOrder;
}
add_filter ( 'woocommerce_account_menu_items', 'my_account_menu_order' );
```
I have saved and flushed the permalinks settings multiple times too... no luck. The new page I have added is in woocommerce/templates/myaccount/earnings.php
the earnings.php page simply has this so I know when and if I get it;
```
<?php
echo ‘HELLO MOM’;
```
Thank you in advance :) | Try adding this code to your add\_action 'init' function.
```
// Let WooCommerce add a new custom endpoint "earnings" for you
add_filter( 'woocommerce_get_query_vars', function( $vars ) {
$vars['earnings'] = 'earnings';
return $vars;
} );
// Add "earnings" to the WooCommerce account menu
add_filter( 'woocommerce_account_menu_items', function( $items ) {
$items['earnings'] = __( 'My earnings', 'your-text-domain' );
return $items;
} );
// Display your custom title on the new endpoint page
// Pattern: woocommerce_endpoint_{$your_endpoint}_title
add_filter( 'woocommerce_endpoint_earnings_title', function( $title ) {
return __( 'My earnings', 'your-text-domain' );
} );
// Display your custom content on the new endpoint page
// Pattern: woocommerce_account_{$your_endpoint}_endpoint
add_action( 'woocommerce_account_earnings_endpoint', function() {
echo __( 'Hello World', 'your-text-domain' );
} );
// Only for testing, REMOVE afterwards!
flush_rewrite_rules();
``` |
305,495 | <p>I'm using Wordpress 4.9+ which I believe enabled with REST api by default. My permalinks are set to <code>Month and Name</code> And I'm using Foxhound React theme for my site.</p>
<p>Now my rest api should be available in</p>
<p><code>http://example.com/wp-json/wp/v2/posts</code></p>
<p>But its available in </p>
<p><code>http://example.com/index.php/wp-json/wp/v2/posts</code></p>
<p>This is why my theme gets 404 error when tries to get data from api.</p>
<p><a href="https://i.stack.imgur.com/5YQgA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5YQgA.png" alt="image error"></a></p>
<p>Now my question is how do I make my REST available without the <code>/index.php</code> prefix</p>
<p>I've manually deployed everything in aws ubuntu micro with a Lamp server. Wordpress files are in the root folder (<code>/var/www/html/</code>)</p>
<p>Also I have tried mod_rewrite module using the following steps</p>
<pre><code>a2enmod rewrite
sudo service apache2 restart
</code></pre>
<p>And this is my <code>.htaccess</code> file</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
| [
{
"answer_id": 305498,
"author": "AA Shakil",
"author_id": 135258,
"author_profile": "https://wordpress.stackexchange.com/users/135258",
"pm_score": 1,
"selected": false,
"text": "<p>You are may trying to get your url like <code>http://example.com/...../posts</code> instead of <code>http... | 2018/06/07 | [
"https://wordpress.stackexchange.com/questions/305495",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144940/"
] | I'm using Wordpress 4.9+ which I believe enabled with REST api by default. My permalinks are set to `Month and Name` And I'm using Foxhound React theme for my site.
Now my rest api should be available in
`http://example.com/wp-json/wp/v2/posts`
But its available in
`http://example.com/index.php/wp-json/wp/v2/posts`
This is why my theme gets 404 error when tries to get data from api.
[](https://i.stack.imgur.com/5YQgA.png)
Now my question is how do I make my REST available without the `/index.php` prefix
I've manually deployed everything in aws ubuntu micro with a Lamp server. Wordpress files are in the root folder (`/var/www/html/`)
Also I have tried mod\_rewrite module using the following steps
```
a2enmod rewrite
sudo service apache2 restart
```
And this is my `.htaccess` file
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
``` | You need to set the permalink structure of your website.
1. Goto **Settings > Permalink**.
2. Remove `index.php` from the *Custom Structure*.
3. Click on `Save Changes`.
It re-generate your permalink structure. And you'll be able to access the posts with `http://example.com/index.php/wp-json/wp/v2/posts`
**Updated:**
`.htaccess` code like below:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /dev.fresh/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /dev.fresh/index.php [L]
</IfModule>
# END WordPress
```
**Note: Change `dev.fresh` with your own domain.** |
305,502 | <p>I have added some custom styles to the TinyMCE editor using the <code>tiny_mce_before_init</code> filter hook. They work by adding classes to the block-level element. See the code below: </p>
<pre><code>function byron_mce_before_init($settings) {
$style_formats = [
[
'title' => 'Lead',
'block' => 'p',
'classes' => 'lead',
],
[
'title' => 'Tagline',
'block' => 'h5',
'classes' => 'tagline',
],
];
$settings['style_formats'] = json_encode($style_formats);
return $settings;
}
add_filter('tiny_mce_before_init', 'byron_mce_before_init');
</code></pre>
<p>The problem I am having, is that when switching between the styles defined above, the class is not removed; in stead, the new class is appended to the old class in stead of replacing it. I can't seem to figure out how to remove the old classes when switching between styles. Any help would be greatly appreciated.</p>
| [
{
"answer_id": 308144,
"author": "Nat",
"author_id": 73029,
"author_profile": "https://wordpress.stackexchange.com/users/73029",
"pm_score": 3,
"selected": true,
"text": "<p>Seems the question was asked at community.tinymce.com and the answer is here:\n<a href=\"https://community.tinymc... | 2018/06/07 | [
"https://wordpress.stackexchange.com/questions/305502",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106941/"
] | I have added some custom styles to the TinyMCE editor using the `tiny_mce_before_init` filter hook. They work by adding classes to the block-level element. See the code below:
```
function byron_mce_before_init($settings) {
$style_formats = [
[
'title' => 'Lead',
'block' => 'p',
'classes' => 'lead',
],
[
'title' => 'Tagline',
'block' => 'h5',
'classes' => 'tagline',
],
];
$settings['style_formats'] = json_encode($style_formats);
return $settings;
}
add_filter('tiny_mce_before_init', 'byron_mce_before_init');
```
The problem I am having, is that when switching between the styles defined above, the class is not removed; in stead, the new class is appended to the old class in stead of replacing it. I can't seem to figure out how to remove the old classes when switching between styles. Any help would be greatly appreciated. | Seems the question was asked at community.tinymce.com and the answer is here:
<https://community.tinymce.com/communityQuestion?id=90661000000IiyjAAC>
You can't make the style you've defined remove any previous classes, but what you can do is 'apply' the style again by selecting it from the dropdown list and it will be removed - i.e. the class will be removed from the tag. You can then choose a different style from the drop-down list and the class relevant to that style will be added to the tag. |
305,521 | <p>I have the following, which is successfully pulling the title, thumbnail, and custom field data (YouTube link) from a referenced post, but the content displayed is that of the parent:</p>
<pre><code>function woo_videos_tab_content() {
$posts = get_field('videos');
if( $posts ): ?>
<div class="row">
<?php foreach( $posts as $p ): ?>
<div class="col-sm-4">
<?php
if ( has_post_thumbnail()) : ?>
<a data-remodal-target="modal-<?php echo $p->ID; ?>" class="video-link" title="<?php echo get_the_title( $p->ID ); ?>" >
<?php echo get_the_post_thumbnail( $p->ID, 'video-thumb' ); ?>
<i class="fa fa-youtube-play fa-4x"></i>
</a>
<h4><?php echo get_the_title( $p->ID ); ?></h4>
// Issue with the line below
<?php echo get_the_content( $p->ID ); ?>
<div class="remodal" data-remodal-id="modal-<?php echo $p->ID; ?>">
<button data-remodal-action="close" class="remodal-close"></button>
<h2><?php echo get_the_title( $p->ID ); ?></h2>
<iframe src="<?php the_field('youtube_link', $p->ID); ?>?enablejsapi=1&version=3" allowfullscreen="" width="560" height="315" frameborder="0" allowscriptaccess="always"></iframe>
</div>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<?php endif;
}
</code></pre>
<p>Should I be pulling the content via another method? I had assumed what worked for title / thumbnail / custom field would work for the content.</p>
| [
{
"answer_id": 305523,
"author": "idpokute",
"author_id": 87895,
"author_profile": "https://wordpress.stackexchange.com/users/87895",
"pm_score": 1,
"selected": false,
"text": "<p>You are using the methods with incorrect parameter.</p>\n\n<p>First of all, get_the_content function doesn't... | 2018/06/07 | [
"https://wordpress.stackexchange.com/questions/305521",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111367/"
] | I have the following, which is successfully pulling the title, thumbnail, and custom field data (YouTube link) from a referenced post, but the content displayed is that of the parent:
```
function woo_videos_tab_content() {
$posts = get_field('videos');
if( $posts ): ?>
<div class="row">
<?php foreach( $posts as $p ): ?>
<div class="col-sm-4">
<?php
if ( has_post_thumbnail()) : ?>
<a data-remodal-target="modal-<?php echo $p->ID; ?>" class="video-link" title="<?php echo get_the_title( $p->ID ); ?>" >
<?php echo get_the_post_thumbnail( $p->ID, 'video-thumb' ); ?>
<i class="fa fa-youtube-play fa-4x"></i>
</a>
<h4><?php echo get_the_title( $p->ID ); ?></h4>
// Issue with the line below
<?php echo get_the_content( $p->ID ); ?>
<div class="remodal" data-remodal-id="modal-<?php echo $p->ID; ?>">
<button data-remodal-action="close" class="remodal-close"></button>
<h2><?php echo get_the_title( $p->ID ); ?></h2>
<iframe src="<?php the_field('youtube_link', $p->ID); ?>?enablejsapi=1&version=3" allowfullscreen="" width="560" height="315" frameborder="0" allowscriptaccess="always"></iframe>
</div>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<?php endif;
}
```
Should I be pulling the content via another method? I had assumed what worked for title / thumbnail / custom field would work for the content. | Function [`get_the_content`](https://codex.wordpress.org/Function_Reference/get_the_content) doesn't take `post_ID` as param. It has 2 params:
* `$more_link_text` - (string) (optional) Content for when there is
more text.
* `$stripteaser` - (boolean) (optional) Strip teaser content
before the more text.
So you can't use it as in your code `get_the_content( $p->ID );` - this will get content of current post and use `$p->ID` as more link text.
So how to get the content of any post based on post ID?
You can use [`get_post_field`](https://codex.wordpress.org/Function_Reference/get_post_field) function:
```
echo apply_filters( 'the_content', get_post_field( 'post_content', $p->ID ) );
``` |
305,533 | <p>I have a method that is hooked to the <code>rest_api_init</code></p>
<pre><code> /**
* Set allowed headers for the rest request
*/
public function set_allowed_rest_headers() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter(
'rest_pre_serve_request', function( $value ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( 'some url pulled from options' ) );
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE, PATCH' );
header( 'Access-Control-Allow-Credentials: true' );
return $value;
}
);
}
</code></pre>
<p>I want to test this using <code>phpunit</code>.</p>
<p>I've created a test case</p>
<pre><code><?php
/**
* Class Test_Admin
*
* @package test
*/
/**
* Class that tests the REST functionality.
*/
class Test_Rest extends WP_UnitTestCase {
/**
* Initial set up for the test
*/
public function setUp() {
parent::setUp();
/**
* Global $wp_rest_server variable
*
* @var WP_REST_Server $wp_rest_server Mock REST server.
*/
global $wp_rest_server;
$wp_rest_server = new \WP_REST_Server();
$this->server = $wp_rest_server;
do_action( 'rest_api_init' );
}
/**
* Tear down after test ends
*/
public function tearDown() {
parent::tearDown();
global $wp_rest_server;
$wp_rest_server = null;
}
/**
* Test if the REST API headers are set
*
* @since 1.1.0
*/
public function test_allowed_rest_headers() {
$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$headers = $request->get_headers();
$headers2 = $response->get_headers();
error_log( print_r( $headers, true ) );
error_log( print_r( $headers2, true ) );
}
}
</code></pre>
<p>The assertion that response is <code>200</code> is passing, but the <code>error_log</code> returns nothing for the request headers, and </p>
<pre><code>Array
(
[X-WP-Total] => 0
[X-WP-TotalPages] => 0
)
</code></pre>
<p>For the response headers. But I'd need to test that the <code>Access-Control-Allow-*</code> headers are set correctly.</p>
<p>How to do that (besides manually setting them during the unit test)?</p>
<p>I've tried calling the <code>set_allowed_rest_headers()</code> method inside the test, but nothing.</p>
| [
{
"answer_id": 305537,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>The question actually has nothing specific to wordpress, but maybe it is worth answering.</p>\n\n<p>There... | 2018/06/07 | [
"https://wordpress.stackexchange.com/questions/305533",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58895/"
] | I have a method that is hooked to the `rest_api_init`
```
/**
* Set allowed headers for the rest request
*/
public function set_allowed_rest_headers() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter(
'rest_pre_serve_request', function( $value ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( 'some url pulled from options' ) );
header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE, PATCH' );
header( 'Access-Control-Allow-Credentials: true' );
return $value;
}
);
}
```
I want to test this using `phpunit`.
I've created a test case
```
<?php
/**
* Class Test_Admin
*
* @package test
*/
/**
* Class that tests the REST functionality.
*/
class Test_Rest extends WP_UnitTestCase {
/**
* Initial set up for the test
*/
public function setUp() {
parent::setUp();
/**
* Global $wp_rest_server variable
*
* @var WP_REST_Server $wp_rest_server Mock REST server.
*/
global $wp_rest_server;
$wp_rest_server = new \WP_REST_Server();
$this->server = $wp_rest_server;
do_action( 'rest_api_init' );
}
/**
* Tear down after test ends
*/
public function tearDown() {
parent::tearDown();
global $wp_rest_server;
$wp_rest_server = null;
}
/**
* Test if the REST API headers are set
*
* @since 1.1.0
*/
public function test_allowed_rest_headers() {
$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
$response = $this->server->dispatch( $request );
$this->assertEquals( 200, $response->get_status() );
$headers = $request->get_headers();
$headers2 = $response->get_headers();
error_log( print_r( $headers, true ) );
error_log( print_r( $headers2, true ) );
}
}
```
The assertion that response is `200` is passing, but the `error_log` returns nothing for the request headers, and
```
Array
(
[X-WP-Total] => 0
[X-WP-TotalPages] => 0
)
```
For the response headers. But I'd need to test that the `Access-Control-Allow-*` headers are set correctly.
How to do that (besides manually setting them during the unit test)?
I've tried calling the `set_allowed_rest_headers()` method inside the test, but nothing. | The question actually has nothing specific to wordpress, but maybe it is worth answering.
There is simply no code of your own in that sample that can be/is worth testing, therefor there isn't much to unit test.
Lets look at the details. `add_filter` is integration with core code, `remove_filter` is integration with core code and `header` is integration with PHP core. If you remove all of those lines you are left with zero code.
Or to say it differently, the three functions mentions above are changing the global state and not your internal state, and while you might be able to construct a relevant test, in the end you are going to be testing them much more than testing your own code.
What you need here is an integration test, set a wordpress instance with your code, send an api request and inspect the result. |
305,547 | <p>I switched my web from http to https by using "Better search and replace" and everything worked fine - at first sight.</p>
<p>All resources were deliverd via https and the Firefox showed a green lock. But when now uploading a new image I saw that it will be delivered via http.</p>
<p>I immediatle checked my db but in options/home and options/siteurl <strong>the entry is https</strong>. In wp-config I also use define('FORCE_SSL_ADMIN', true);. And now the curious thing: When checking the WordPress Address (URL) under "Settings/General" there is a http-entry which cannot be edited.</p>
<p><strong><a href="https://i.stack.imgur.com/6dCyO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6dCyO.png" alt="The db says https but the backend says http"></a></strong></p>
<p><strong>The db says https but the backend says http...</strong> I´m really helpless... What can I do?</p>
| [
{
"answer_id": 305554,
"author": "LuisD",
"author_id": 144974,
"author_profile": "https://wordpress.stackexchange.com/users/144974",
"pm_score": 2,
"selected": false,
"text": "<p>It is possible to hardcode the value of the \"Wordpress Address (URL)\" and \"Site Address(URL)\" options wit... | 2018/06/07 | [
"https://wordpress.stackexchange.com/questions/305547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116916/"
] | I switched my web from http to https by using "Better search and replace" and everything worked fine - at first sight.
All resources were deliverd via https and the Firefox showed a green lock. But when now uploading a new image I saw that it will be delivered via http.
I immediatle checked my db but in options/home and options/siteurl **the entry is https**. In wp-config I also use define('FORCE\_SSL\_ADMIN', true);. And now the curious thing: When checking the WordPress Address (URL) under "Settings/General" there is a http-entry which cannot be edited.
**[](https://i.stack.imgur.com/6dCyO.png)**
**The db says https but the backend says http...** I´m really helpless... What can I do? | It is possible to hardcode the value of the "Wordpress Address (URL)" and "Site Address(URL)" options within your *wp-config.php* file. When the value of either field is hardcoded this way, it takes precedence over the respective value set in the database. This is why you cannot edit the field via the Wordpress Admin Page ( the value is hardcoded ).
My suggestion to resolving your issue is this:
1) Open your *wp-config.php* file
2) Look for a line of code similar to the one below
```
define('WP_SITEURL','http://www.example.com');
```
3) delete it
That's it! You should now be able to edit the "Wordpress Address (URL)" from the admin page.
Reference: <https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php> |
305,574 | <p>How to add Category name to post title (H1)? “PostTitle + CategoryName”?</p>
<p>My <strong>h1</strong> post title code:</p>
<pre><code><?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</code></pre>
| [
{
"answer_id": 305554,
"author": "LuisD",
"author_id": 144974,
"author_profile": "https://wordpress.stackexchange.com/users/144974",
"pm_score": 2,
"selected": false,
"text": "<p>It is possible to hardcode the value of the \"Wordpress Address (URL)\" and \"Site Address(URL)\" options wit... | 2018/06/07 | [
"https://wordpress.stackexchange.com/questions/305574",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144992/"
] | How to add Category name to post title (H1)? “PostTitle + CategoryName”?
My **h1** post title code:
```
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
``` | It is possible to hardcode the value of the "Wordpress Address (URL)" and "Site Address(URL)" options within your *wp-config.php* file. When the value of either field is hardcoded this way, it takes precedence over the respective value set in the database. This is why you cannot edit the field via the Wordpress Admin Page ( the value is hardcoded ).
My suggestion to resolving your issue is this:
1) Open your *wp-config.php* file
2) Look for a line of code similar to the one below
```
define('WP_SITEURL','http://www.example.com');
```
3) delete it
That's it! You should now be able to edit the "Wordpress Address (URL)" from the admin page.
Reference: <https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php> |
305,583 | <p>I want my entire site in English, but the dates to be in another language.</p>
<p>I tried to set PHP local like this:</p>
<pre><code>setlocale(LC_ALL, 'he');
</code></pre>
<p>Setting my whole website to another language from the admin panel does change the time language, but I don't want this.
Any ideas on how to accomplish that?</p>
| [
{
"answer_id": 305736,
"author": "Slam",
"author_id": 82256,
"author_profile": "https://wordpress.stackexchange.com/users/82256",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds like you want to create a multilingual site; even if you aren't displaying multiple languages on the a... | 2018/06/08 | [
"https://wordpress.stackexchange.com/questions/305583",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145001/"
] | I want my entire site in English, but the dates to be in another language.
I tried to set PHP local like this:
```
setlocale(LC_ALL, 'he');
```
Setting my whole website to another language from the admin panel does change the time language, but I don't want this.
Any ideas on how to accomplish that? | It sounds like you want to create a multilingual site; even if you aren't displaying multiple languages on the admin side, it sounds like you want one language in the backend and another on the frontend.
You might want to check out [WPBeginner's article on multi-language WordPress](http://www.wpbeginner.com/beginners-guide/how-to-easily-create-a-multilingual-wordpress-site/).
If *all* you are changing is the date language, and you are comfortable editing template, then you can [alter the date displays alone using PHP](https://stackoverflow.com/questions/4975854/translating-php-date-for-multilingual-site). |
305,607 | <p>I have a simple Wordpress Custimizer section being added. The section shows and the controls are rendered and can be seen if you click it before it vanishes or if you stop the page load before it vanishes (Which leads me to believe it is JavaScript related). I can't figure out why?</p>
<p><strong>UPDATE - The section disappears as soon as the preview loads and the JavaScript for the preview is loaded</strong></p>
<p>Here's a video of all three above described actions:
<a href="https://drive.google.com/file/d/16lJqbwCMDUanFlp1C1WsVHcTeyAS6MLu/view" rel="nofollow noreferrer">https://drive.google.com/file/d/16lJqbwCMDUanFlp1C1WsVHcTeyAS6MLu/view</a></p>
<p>Here's the class responsible for modifying the customizer:</p>
<pre><code><?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}/**
* Kickstarter Theme Customizer Class (class-kickstater-customizer.php)
*
* @package WordPress
* @subpackage OGZ_Kickstarter
* @since 1.0
* @version 1.0
*/
require_once 'customizer/class-kickstarter-cutomizer-controls.php';
require_once 'customizer/class-kickstarter-cutomizer-sections.php';
require_once 'customizer/class-kickstarter-cutomizer-settings.php';
class Kickstarter_Customizer {
/**
* OGZ Kickstarter Theme Mods
*
* @since 1.0.0
* @var array $theme_mods
*/
private $theme_mods;
/**
* Instance of WordPress core WP_Customize_Manager object
*
* @since 1.0.0
* @var WP_Customize_Manager $customizer
*/
private $customizer;
/**
* Kickstarter customizer controls class
*
* @since 1.0.0
* @var Kickstarter_Customizer_Controls $controls
*/
private $controls;
/**
* Kickstarter customizer sections class
*
* @since 1.0.0
* @var Kickstarter_Customizer_Sections $sections
*/
private $sections;
/**
* Kickstarter customizer settings class
*
* @since 1.0.0
* @var Kickstarter_Customizer_Settings $settings
*/
private $settings;
/**
* Kickstarter_Customizer constructor.
*
* @since 1.0.0
* @param array $theme_mods
*/
public function __construct( $theme_mods ) {
global $wp_customize;
$this->customizer = $wp_customize;
$this->theme_mods = $theme_mods;
$this->settings = new Kickstarter_Customizer_Settings( $this->customizer );
$this->controls = new Kickstarter_Customizer_Controls( $this->customizer );
$this->sections = new Kickstarter_Customizer_Sections( $this->customizer );
}
public function init() {
add_action( 'customize_register', [ $this, 'kickstarter_customizer' ] );
}
/**
* Adds Kickstarter theme customizer settings
*
* @since 1.0.0
* @return void
*/
public function kickstarter_customizer() {
$this->settings->init();
$this->sections->init();
$this->controls->init();
}
}
</code></pre>
<p>The Settings class:</p>
<pre><code><?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}/**
* Kickstarter Theme Customizer Settings Class (class-kickstater-customizer-settings.php)
*
* @package WordPress
* @subpackage OGZ_Kickstarter
* @since 1.0
* @version 1.0
*/
require_once 'settings/boolean/class-kickstarter-boolean-setting.php';
class Kickstarter_Customizer_Settings {
/**
* WordPress Customize Manager
*
* @var WP_Customize_Manager $customizer
*/
private $customizer;
/**
* Kickstarter_Customizer_Settings constructor.
*
* @param WP_Customize_Manager $customizer
*/
public function __construct( $customizer ) {
$this->customizer = $customizer;
}
/**
* Register the kickstarter theme settings
*
* @since 1.0.0
* @return void
*/
public function init() {
/*
* Theme Settings Section Settings
*/
// Theme Layout Choice
$this->customizer->add_setting( 'kickstarter_theme_layout', [
'default' => 0,
'sanitize_callback' => 'absint',
'transport' => 'refresh'
] );
// Mobile Menu Layout Choice
$this->customizer->add_setting( 'kickstarter_mobile_menu_layout', [
'default' => 0,
'sanitize_callback' => 'absint',
'transport' => 'refresh'
] );
// Header Layout Choice
$this->customizer->add_setting( 'kickstarter_header_layout', [
'default' => 0,
'sanitize_callback' => 'absint',
'transport' => 'refresh'
] );
}
</code></pre>
<p>The sections class:</p>
<pre><code><?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}/**
* Kickstarter Theme Customizer Sections Class (class-kickstater-customizer-sections.php)
*
* @package WordPress
* @subpackage OGZ_Kickstarter
* @since 1.0
* @version 1.0
*/
class Kickstarter_Customizer_Sections {
/**
* WordPress Customize Manager
*
* @var WP_Customize_Manager $customizer
*/
private $customizer;
/**
* Kickstarter_Customizer_Settings constructor.
*
* @param WP_Customize_Manager $customizer
*/
public function __construct( $customizer ) {
$this->customizer = $customizer;
}
/**
* Register the kickstarter customizer sections
*
* @since 1.0.0
* @return void
*/
public function init() {
//Add Kickstarter customizer sections
$this->customizer->add_section( 'kickstarter_theme_settings', [
'title' => __( 'Theme Settings', 'ogz_kickstarter' ),
'priority' => 1,
] );
}
}
</code></pre>
<p>The controls class:</p>
<pre><code><?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}/**
* Kickstarter Theme Customizer Controls Class (class-kickstater-customizer-controls.php)
*
* @package WordPress
* @subpackage OGZ_Kickstarter
* @since 1.0
* @version 1.0
*/
class Kickstarter_Customizer_Controls {
/**
* WordPress Customize Manager
*
* @var WP_Customize_Manager $customizer
*/
private $customizer;
/**
* Kickstarter_Customizer_Settings constructor.
*
* @param WP_Customize_Manager $customizer
*/
public function __construct( $customizer ) {
$this->customizer = $customizer;
}
/**
* Registers the Kickstarter Customizer controls
*
* @since 1.0.0
* @return void
*/
public function init() {
// Theme Layout Select Control
$this->customizer->add_control( 'kickstarter_theme_layout', [
'type' => 'select',
'priority' => 5,
'section' => 'kickstarter_theme_settings',
'label' => __( 'Theme Layout Style', 'ogz_kickstarter' ),
'choices' => [
__( 'Boxed Layout', 'ogz_kickstarter' ),
__( 'Full Width Layout', 'ogz_kickstarter' ),
],
] );
// Mobile Menu Layout Select Control
$this->customizer->add_control( 'kickstarter_mobile_menu_layout', [
'type' => 'select',
'priority' => 10,
'section' => 'kickstarter_theme_settings', // Required, core or custom.
'label' => __( 'Mobile Menu Layout Style', 'ogz_kickstarter' ),
'choices' => [
__( 'Slide Down', 'ogz_kickstarter' ),
__( 'Slide Up', 'ogz_kickstarter' ),
__( 'Slide In From Left', 'ogz_kickstarter' ),
__( 'Slide In From Right', 'ogz_kickstarter' ),
__( 'Off Canvas Menu - Slide In From Left', 'ogz_kickstarter' ),
__( 'Off Canvas Menu - Slide In From Right', 'ogz_kickstarter' ),
],
] );
// Header Layout Select Control
$this->customizer->add_control( 'kickstarter_header_layout', [
'type' => 'select',
'label' => __( 'Header Layout', 'ogz_kickstarter' ),
'section' => 'kickstarter_theme_settings', // Required, core or custom.
'priority' => 5,
'choices' => [
__( 'Left Logo With Right Side Navigation', 'ogz_kickstarter' ),
__( 'Centered Logo With Bottom Navigation', 'ogz_kickstarter' ),
__( 'Sidebar Like Header Layout', 'ogz_kickstarter' ),
__( 'Half Screen Hero With Bottom Navigation', 'ogz_kickstarter' ),
__( 'Full Screen Hero', 'ogz_kickstarter' ),
],
] );
}
}
</code></pre>
<p>Does anybody have any thoughts or suggestions? I appreciate it.</p>
| [
{
"answer_id": 305593,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 0,
"selected": false,
"text": "<p>When i move/migrate a WP site, i usually use this handy tool:\n<a href=\"https://interconnectit.com/products/se... | 2018/06/08 | [
"https://wordpress.stackexchange.com/questions/305607",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115290/"
] | I have a simple Wordpress Custimizer section being added. The section shows and the controls are rendered and can be seen if you click it before it vanishes or if you stop the page load before it vanishes (Which leads me to believe it is JavaScript related). I can't figure out why?
**UPDATE - The section disappears as soon as the preview loads and the JavaScript for the preview is loaded**
Here's a video of all three above described actions:
<https://drive.google.com/file/d/16lJqbwCMDUanFlp1C1WsVHcTeyAS6MLu/view>
Here's the class responsible for modifying the customizer:
```
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}/**
* Kickstarter Theme Customizer Class (class-kickstater-customizer.php)
*
* @package WordPress
* @subpackage OGZ_Kickstarter
* @since 1.0
* @version 1.0
*/
require_once 'customizer/class-kickstarter-cutomizer-controls.php';
require_once 'customizer/class-kickstarter-cutomizer-sections.php';
require_once 'customizer/class-kickstarter-cutomizer-settings.php';
class Kickstarter_Customizer {
/**
* OGZ Kickstarter Theme Mods
*
* @since 1.0.0
* @var array $theme_mods
*/
private $theme_mods;
/**
* Instance of WordPress core WP_Customize_Manager object
*
* @since 1.0.0
* @var WP_Customize_Manager $customizer
*/
private $customizer;
/**
* Kickstarter customizer controls class
*
* @since 1.0.0
* @var Kickstarter_Customizer_Controls $controls
*/
private $controls;
/**
* Kickstarter customizer sections class
*
* @since 1.0.0
* @var Kickstarter_Customizer_Sections $sections
*/
private $sections;
/**
* Kickstarter customizer settings class
*
* @since 1.0.0
* @var Kickstarter_Customizer_Settings $settings
*/
private $settings;
/**
* Kickstarter_Customizer constructor.
*
* @since 1.0.0
* @param array $theme_mods
*/
public function __construct( $theme_mods ) {
global $wp_customize;
$this->customizer = $wp_customize;
$this->theme_mods = $theme_mods;
$this->settings = new Kickstarter_Customizer_Settings( $this->customizer );
$this->controls = new Kickstarter_Customizer_Controls( $this->customizer );
$this->sections = new Kickstarter_Customizer_Sections( $this->customizer );
}
public function init() {
add_action( 'customize_register', [ $this, 'kickstarter_customizer' ] );
}
/**
* Adds Kickstarter theme customizer settings
*
* @since 1.0.0
* @return void
*/
public function kickstarter_customizer() {
$this->settings->init();
$this->sections->init();
$this->controls->init();
}
}
```
The Settings class:
```
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}/**
* Kickstarter Theme Customizer Settings Class (class-kickstater-customizer-settings.php)
*
* @package WordPress
* @subpackage OGZ_Kickstarter
* @since 1.0
* @version 1.0
*/
require_once 'settings/boolean/class-kickstarter-boolean-setting.php';
class Kickstarter_Customizer_Settings {
/**
* WordPress Customize Manager
*
* @var WP_Customize_Manager $customizer
*/
private $customizer;
/**
* Kickstarter_Customizer_Settings constructor.
*
* @param WP_Customize_Manager $customizer
*/
public function __construct( $customizer ) {
$this->customizer = $customizer;
}
/**
* Register the kickstarter theme settings
*
* @since 1.0.0
* @return void
*/
public function init() {
/*
* Theme Settings Section Settings
*/
// Theme Layout Choice
$this->customizer->add_setting( 'kickstarter_theme_layout', [
'default' => 0,
'sanitize_callback' => 'absint',
'transport' => 'refresh'
] );
// Mobile Menu Layout Choice
$this->customizer->add_setting( 'kickstarter_mobile_menu_layout', [
'default' => 0,
'sanitize_callback' => 'absint',
'transport' => 'refresh'
] );
// Header Layout Choice
$this->customizer->add_setting( 'kickstarter_header_layout', [
'default' => 0,
'sanitize_callback' => 'absint',
'transport' => 'refresh'
] );
}
```
The sections class:
```
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}/**
* Kickstarter Theme Customizer Sections Class (class-kickstater-customizer-sections.php)
*
* @package WordPress
* @subpackage OGZ_Kickstarter
* @since 1.0
* @version 1.0
*/
class Kickstarter_Customizer_Sections {
/**
* WordPress Customize Manager
*
* @var WP_Customize_Manager $customizer
*/
private $customizer;
/**
* Kickstarter_Customizer_Settings constructor.
*
* @param WP_Customize_Manager $customizer
*/
public function __construct( $customizer ) {
$this->customizer = $customizer;
}
/**
* Register the kickstarter customizer sections
*
* @since 1.0.0
* @return void
*/
public function init() {
//Add Kickstarter customizer sections
$this->customizer->add_section( 'kickstarter_theme_settings', [
'title' => __( 'Theme Settings', 'ogz_kickstarter' ),
'priority' => 1,
] );
}
}
```
The controls class:
```
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}/**
* Kickstarter Theme Customizer Controls Class (class-kickstater-customizer-controls.php)
*
* @package WordPress
* @subpackage OGZ_Kickstarter
* @since 1.0
* @version 1.0
*/
class Kickstarter_Customizer_Controls {
/**
* WordPress Customize Manager
*
* @var WP_Customize_Manager $customizer
*/
private $customizer;
/**
* Kickstarter_Customizer_Settings constructor.
*
* @param WP_Customize_Manager $customizer
*/
public function __construct( $customizer ) {
$this->customizer = $customizer;
}
/**
* Registers the Kickstarter Customizer controls
*
* @since 1.0.0
* @return void
*/
public function init() {
// Theme Layout Select Control
$this->customizer->add_control( 'kickstarter_theme_layout', [
'type' => 'select',
'priority' => 5,
'section' => 'kickstarter_theme_settings',
'label' => __( 'Theme Layout Style', 'ogz_kickstarter' ),
'choices' => [
__( 'Boxed Layout', 'ogz_kickstarter' ),
__( 'Full Width Layout', 'ogz_kickstarter' ),
],
] );
// Mobile Menu Layout Select Control
$this->customizer->add_control( 'kickstarter_mobile_menu_layout', [
'type' => 'select',
'priority' => 10,
'section' => 'kickstarter_theme_settings', // Required, core or custom.
'label' => __( 'Mobile Menu Layout Style', 'ogz_kickstarter' ),
'choices' => [
__( 'Slide Down', 'ogz_kickstarter' ),
__( 'Slide Up', 'ogz_kickstarter' ),
__( 'Slide In From Left', 'ogz_kickstarter' ),
__( 'Slide In From Right', 'ogz_kickstarter' ),
__( 'Off Canvas Menu - Slide In From Left', 'ogz_kickstarter' ),
__( 'Off Canvas Menu - Slide In From Right', 'ogz_kickstarter' ),
],
] );
// Header Layout Select Control
$this->customizer->add_control( 'kickstarter_header_layout', [
'type' => 'select',
'label' => __( 'Header Layout', 'ogz_kickstarter' ),
'section' => 'kickstarter_theme_settings', // Required, core or custom.
'priority' => 5,
'choices' => [
__( 'Left Logo With Right Side Navigation', 'ogz_kickstarter' ),
__( 'Centered Logo With Bottom Navigation', 'ogz_kickstarter' ),
__( 'Sidebar Like Header Layout', 'ogz_kickstarter' ),
__( 'Half Screen Hero With Bottom Navigation', 'ogz_kickstarter' ),
__( 'Full Screen Hero', 'ogz_kickstarter' ),
],
] );
}
}
```
Does anybody have any thoughts or suggestions? I appreciate it. | When i move/migrate a WP site, i usually use this handy tool:
<https://interconnectit.com/products/search-and-replace-for-wordpress-databases/>
With this tool you can replace strings in the database.
Upload srdb to the root and extract (example.com/srdb/\_all\_files).
Then go to <http://example.com/srdb>.
You should do the following replace.
Search: example.com/wordpress
Replace by: example.com
**NOTE:**
ALWAYS MAKE A FULL DATABASE BACK-UP WHEN YOU USE THIS TOOL! USE ON YOUR OWN RISK.
**NOTE 2:**
DO NOT FORGET TO COMPLETELY REMOVE IT WHEN YOU'RE DONE! |
305,633 | <p>I come from Drupal 8, where I am used to template files for each entity (piece of data). As far as I understood in WP every page template does look after it's own content via theming it via code that sits in the (page / post) tpl file itself.</p>
<p>I believe there must be a nicer way to theme an "ACF Flexible Field" than duplicating my template code into each page tpl the field maybe could be outputted in. </p>
<p>Can I define "one" tpl file that is used for every output instead?</p>
<p>Are there any Objects? Or inc's that I can create to deal with the field?
I understand that putting all the code into each page tpl makes it easy... but its also very static and it produces double code.</p>
| [
{
"answer_id": 305635,
"author": "Florian",
"author_id": 10595,
"author_profile": "https://wordpress.stackexchange.com/users/10595",
"pm_score": 1,
"selected": false,
"text": "<p>You can include template partials via <a href=\"https://developer.wordpress.org/reference/functions/get_templ... | 2018/06/08 | [
"https://wordpress.stackexchange.com/questions/305633",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145033/"
] | I come from Drupal 8, where I am used to template files for each entity (piece of data). As far as I understood in WP every page template does look after it's own content via theming it via code that sits in the (page / post) tpl file itself.
I believe there must be a nicer way to theme an "ACF Flexible Field" than duplicating my template code into each page tpl the field maybe could be outputted in.
Can I define "one" tpl file that is used for every output instead?
Are there any Objects? Or inc's that I can create to deal with the field?
I understand that putting all the code into each page tpl makes it easy... but its also very static and it produces double code. | And to add to previous answers, you can not only use `get_template_part`, but also use it's second param and combine it with ACFs `get_row_layout`.
So let's say that somewhere in your template is:
```
<?php while ( have_posts() ) : the_post(); ?>
<article>
... SOME CODE
<?php while ( have_rows( 'YOUR_FIELD_NAME' ) ) : the_row(); ?>
... HERE SHOULD GO THE CODE FOR ACF FIELD
<?php endwhile; ?>
... SOME OTHER CODE
</article>
<?php endwhile; ?>
```
You can change it to:
```
<?php while ( have_posts() ) : the_post(); ?>
<article>
... SOME CODE
<?php
while ( have_rows( 'YOUR_FIELD_NAME' ) ) :
the_row();
get_template_part( 'block', get_row_layout() );
endwhile;
?>
... SOME OTHER CODE
</article>
<?php endwhile; ?>
```
Then you can create your custom templates named: `block.php` (it will be used as fallback), `block-layout_1.php` (it will be used for layout called "layout\_1", and so on. |
305,645 | <p>I need to check the speed of a couple of WordPress pages on a few different hosts (WordPress installations on different could hosting providers and managed hosts) to determine the fastest.</p>
<p>Problem is that I will gain access to the original site only when I have determined the fastest host, Then I can migrate the site to the new host.</p>
<p>I've been thinking of downloading the static page and somehow hosting it on different hosts to check the page speed.</p>
<p>My question is: How would I host the static page on WP?</p>
| [
{
"answer_id": 305635,
"author": "Florian",
"author_id": 10595,
"author_profile": "https://wordpress.stackexchange.com/users/10595",
"pm_score": 1,
"selected": false,
"text": "<p>You can include template partials via <a href=\"https://developer.wordpress.org/reference/functions/get_templ... | 2018/06/08 | [
"https://wordpress.stackexchange.com/questions/305645",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145041/"
] | I need to check the speed of a couple of WordPress pages on a few different hosts (WordPress installations on different could hosting providers and managed hosts) to determine the fastest.
Problem is that I will gain access to the original site only when I have determined the fastest host, Then I can migrate the site to the new host.
I've been thinking of downloading the static page and somehow hosting it on different hosts to check the page speed.
My question is: How would I host the static page on WP? | And to add to previous answers, you can not only use `get_template_part`, but also use it's second param and combine it with ACFs `get_row_layout`.
So let's say that somewhere in your template is:
```
<?php while ( have_posts() ) : the_post(); ?>
<article>
... SOME CODE
<?php while ( have_rows( 'YOUR_FIELD_NAME' ) ) : the_row(); ?>
... HERE SHOULD GO THE CODE FOR ACF FIELD
<?php endwhile; ?>
... SOME OTHER CODE
</article>
<?php endwhile; ?>
```
You can change it to:
```
<?php while ( have_posts() ) : the_post(); ?>
<article>
... SOME CODE
<?php
while ( have_rows( 'YOUR_FIELD_NAME' ) ) :
the_row();
get_template_part( 'block', get_row_layout() );
endwhile;
?>
... SOME OTHER CODE
</article>
<?php endwhile; ?>
```
Then you can create your custom templates named: `block.php` (it will be used as fallback), `block-layout_1.php` (it will be used for layout called "layout\_1", and so on. |
305,665 | <p>For some custom functionality in Woocommerce, I need to copy order items with all metadata from one order to another order programatically. The source order is of type <code>WC_Order</code> while destination order type is <code>WC_Subscription</code> which extends <code>WC_Order</code> and is a custom order type.</p>
<p>I have tried with a following function but it doesn't work. Although the order total is updated which matches to source order but the items in order are not added.</p>
<pre><code>function wc_copy_order_items( &$from_order, &$to_order ) {
if ( ! is_a( $from_order, 'WC_Abstract_Order' ) || ! is_a( $to_order, 'WC_Abstract_Order' ) ) {
throw new InvalidArgumentException( _x( 'Invalid data. Orders expected aren\'t orders.', 'In wc_copy_order_items error message. Refers to origin and target order objects.', 'woocommerce-subscriptions' ) );
}
$from_order_all_items = $from_order->get_items( array( 'line_item', 'fee', 'shipping' ) );
foreach( $from_order_all_items as $item ) {
$to_order->add_item( $item );
}
$to_order->save();
}
</code></pre>
<p>I have also tried with woocommerce admin function <code>wc_save_order_items</code> by hooking into <code>woocommerce_process_shop_order_meta</code> while saving source order from admin but that also results in only update in totals of destination order and do not add items.</p>
<pre><code>wc_save_order_items( $source_order_id, $_POST );
</code></pre>
<p>Basically, I want to copy all the data including all meta data and custom fields from source order to destination order. I've managed to copy other metadata by somehow but I can't get it right for copying order items with item metadata. </p>
<p>Please help me to find why above function doesn't work and guide me for a solution to copy order items between two orders.</p>
| [
{
"answer_id": 305693,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, you need this for custom WOO functionality.</p>\n\n<p>But <code>WC_Subscription</code> is from the WOO Subs... | 2018/06/08 | [
"https://wordpress.stackexchange.com/questions/305665",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140368/"
] | For some custom functionality in Woocommerce, I need to copy order items with all metadata from one order to another order programatically. The source order is of type `WC_Order` while destination order type is `WC_Subscription` which extends `WC_Order` and is a custom order type.
I have tried with a following function but it doesn't work. Although the order total is updated which matches to source order but the items in order are not added.
```
function wc_copy_order_items( &$from_order, &$to_order ) {
if ( ! is_a( $from_order, 'WC_Abstract_Order' ) || ! is_a( $to_order, 'WC_Abstract_Order' ) ) {
throw new InvalidArgumentException( _x( 'Invalid data. Orders expected aren\'t orders.', 'In wc_copy_order_items error message. Refers to origin and target order objects.', 'woocommerce-subscriptions' ) );
}
$from_order_all_items = $from_order->get_items( array( 'line_item', 'fee', 'shipping' ) );
foreach( $from_order_all_items as $item ) {
$to_order->add_item( $item );
}
$to_order->save();
}
```
I have also tried with woocommerce admin function `wc_save_order_items` by hooking into `woocommerce_process_shop_order_meta` while saving source order from admin but that also results in only update in totals of destination order and do not add items.
```
wc_save_order_items( $source_order_id, $_POST );
```
Basically, I want to copy all the data including all meta data and custom fields from source order to destination order. I've managed to copy other metadata by somehow but I can't get it right for copying order items with item metadata.
Please help me to find why above function doesn't work and guide me for a solution to copy order items between two orders. | Just change the `$item_id` to `$to_order_item_id` and you don't even have to touch the `order_item_meta` since it is still associated with the proper `$item_id`. So your `foreach` from above would be ...
```
foreach($order->get_items() as $item_id=>$item) {
wc_update_order_item($item_id, array('order_id'=>$to_order_item_id));
}
```
Then you could even calculate the new totals of both orders after by using ...
```
$original_order = new WC_Order($original_order_id);
$original_order->calculate_totals();
$order = new WC_Order($to_order_item_id);
$order->calculate_totals();
```
I also discovered sometimes woocommerce will not let you change the `order item` data so I ended up doing the same as above but with a `straight to the database` update instead ...
```
global $wpdb;
$table = 'wp_woocommerce_order_items';
$data = array('order_id'=>$to_order_item_id);
foreach($order->get_items() as $item_id=>$item) {
$where = array('order_item_id'=>$item_id);
$updated = $wpdb->update($table, $data, $where);
if($updated === false) {
echo 'sorry dawg, there was an error';
}
else {
echo 'you got the soup!';
}
}
``` |
305,695 | <p>I Developed one Newspaper portal in WordPress. I am using <strong>Two languages in this portal Tamil(site language) and English</strong>.</p>
<p>Now I am using <strong>Nova Sans Tamil font for Tamil language font</strong>
and <strong>Roboto font For English</strong></p>
<p>In Headings and Menus I can easily handle this problem using css, but in body of the content I can't do it because <strong>it is collaboration of two language fonts used in the site</strong>.</p>
<p>So the fonts are not looking good in English.</p>
<p>Is there any JavaScript, CSS or any other method to set different font family based on text language?</p>
<p><strong>My need is</strong></p>
<p><strong>If the text is Tamil font then set Nova Sans Tamil<br>
If the text is English font then set Roboto</strong></p>
<p>(Note): I can't use different classes for English font, so don't give this solution. Because I am using English font in thousands of places, it is very hard to change.</p>
| [
{
"answer_id": 305708,
"author": "Ovidiu",
"author_id": 137365,
"author_profile": "https://wordpress.stackexchange.com/users/137365",
"pm_score": 1,
"selected": false,
"text": "<p>Whichever solution you use for language switching, I am sure it sets a meta tag with the language (see case ... | 2018/06/09 | [
"https://wordpress.stackexchange.com/questions/305695",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140788/"
] | I Developed one Newspaper portal in WordPress. I am using **Two languages in this portal Tamil(site language) and English**.
Now I am using **Nova Sans Tamil font for Tamil language font**
and **Roboto font For English**
In Headings and Menus I can easily handle this problem using css, but in body of the content I can't do it because **it is collaboration of two language fonts used in the site**.
So the fonts are not looking good in English.
Is there any JavaScript, CSS or any other method to set different font family based on text language?
**My need is**
**If the text is Tamil font then set Nova Sans Tamil
If the text is English font then set Roboto**
(Note): I can't use different classes for English font, so don't give this solution. Because I am using English font in thousands of places, it is very hard to change. | This question is not about WordPress but about css. Actually there even is a straightforward solution, because css-3 has an attribute called [`unicode-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range), which allows you to load fonts based on the character set. For [Tamil the unicode block](https://en.wikipedia.org/wiki/Tamil_(Unicode_block)) is U+0B02..U+0BCD. So, if you have the english font as a standard you can easily change the font to Tamil whenever appropriate like this:
```
@font-face {
font-family: 'NovaSansTamil';
src: url('novasanstamil.woff') format('woff'); /* full url to font needed */
unicode-range: U+0B02-CD;
}
```
Beware that [browser support is not yet universal](https://caniuse.com/#feat=font-unicode-range) for this feature. |
305,697 | <p>I am using this below code to remove woocommerce sidebar, from cart and single-product page. </p>
<pre><code>function urun_sidebar_kaldir() {
if ( is_product() || is_cart() ) {
remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10 );
}
}
add_action( 'woocommerce_before_main_content', 'urun_sidebar_kaldir' );
</code></pre>
<p>It works in single-product page, but it doesn't work cart page. </p>
<p>I can't remove sidebar in cart page.</p>
<p><strong>//Update</strong></p>
<p>I am not using <strong>woocommerce.php</strong> in theme main folder.</p>
<p>And i have this templates in my theme.</p>
<pre><code>wp-content/themes/{current-theme}/woocommerce/cart/cart.php
</code></pre>
<p>I created custom teplate for cart. And i removed <strong>get_sidebar();</strong> but sidebar is still displaying in cart page.</p>
<pre><code>wp-content/themes/{current-theme}/page-cart.php
wp-content/themes/{current-theme}/page-checkout.php
</code></pre>
| [
{
"answer_id": 305699,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 3,
"selected": true,
"text": "<p>First, most themes have multiple page templates you can choose from.</p>\n\n<p>Please check:</p>\n\n<ol>\n<li>go... | 2018/06/09 | [
"https://wordpress.stackexchange.com/questions/305697",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133897/"
] | I am using this below code to remove woocommerce sidebar, from cart and single-product page.
```
function urun_sidebar_kaldir() {
if ( is_product() || is_cart() ) {
remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10 );
}
}
add_action( 'woocommerce_before_main_content', 'urun_sidebar_kaldir' );
```
It works in single-product page, but it doesn't work cart page.
I can't remove sidebar in cart page.
**//Update**
I am not using **woocommerce.php** in theme main folder.
And i have this templates in my theme.
```
wp-content/themes/{current-theme}/woocommerce/cart/cart.php
```
I created custom teplate for cart. And i removed **get\_sidebar();** but sidebar is still displaying in cart page.
```
wp-content/themes/{current-theme}/page-cart.php
wp-content/themes/{current-theme}/page-checkout.php
``` | First, most themes have multiple page templates you can choose from.
Please check:
1. go to cart page (in wp-admin).
2. See side metabox 'Page Attributes'.
3. There you can set the page template, does it have something like 'full\_width'?
You can also try a different hook, like `wp_head`.
Example:
```
add_action( 'wp_head', 'urun_sidebar_kaldir' );
```
Let me know.
---
After checking the WOO cart template, i can't find a `do_action( 'woocommerce_sidebar' )`.
It does exist in the singe-product.php template.
Are you certain the cart sidebar is generated by WooCommerce?
---
Add a full-width template to your theme:
Read [this](https://premium.wpmudev.org/blog/creating-custom-page-templates-in-wordpress/).
Then follow the steps i mentiod at the beginning of my answer. |
305,700 | <p>I have two post types in my website. one for courses and other for teachers. I want to put a selectable list of teachers post type in courses post type and then show it in course single page and link it to single page of that teacher. how can i do?</p>
<pre><code> function custom_meta_box_markup($object)
{
wp_nonce_field(basename(__FILE__), "meta-box-nonce");
?>
<div>
<select name="meta-box-dropdown">
<?php
$args=array('post_type'=>'mama_ashpaz');
$q=new WP_Query($args);
if($q->have_posts()){
$current=0;
while($q->have_posts()){
$q->the_post();?>
<?php $options[$current]=get_the_title();
$options_id[$current]=get_the_id();
$current++;
}
}wp_reset_postdata();
foreach($options as $key=>$value){
if($value == get_post_meta($object->ID, "meta-box-dropdown", true))
{
?>
<option selected><?php echo $value; ?></option>
<?php
}
else
{
?>
<option><?php echo $value; ?></option>
<?php
}
}
?>
</select>
</div>
<?php
}
function add_custom_meta_box()
{
add_meta_box("demo-meta-box", "مامان آشپز", "custom_meta_box_markup",
"product", "side", "high", null);
}
add_action("add_meta_boxes", "add_custom_meta_box");
function save_custom_meta_box($post_id, $post, $update)
{
if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-
box-nonce"], basename(__FILE__)))
return $post_id;
if(!current_user_can("edit_post", $post_id))
return $post_id;
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
return $post_id;
$slug = "product";
if($slug != $post->post_type)
return $post_id;
$meta_box_dropdown_value = "";
if(isset($_POST["meta-box-dropdown"]))
{
$meta_box_dropdown_value = $_POST["meta-box-dropdown"];
}
update_post_meta($post_id, "meta-box-dropdown",
$meta_box_dropdown_value);
}
add_action("save_post", "save_custom_meta_box", 10, 3);
function add_maman(){?>
<div class="maman-meta"><a href="<?php echo get_the_permalink();?>">
<?php echo get_post_meta( get_the_id(), "meta-box-dropdown", true ) ;?>
</a>
</div>
<?php
}
add_action( 'woocommerce_before_single_product_summary','add_maman' );
</code></pre>
| [
{
"answer_id": 305699,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 3,
"selected": true,
"text": "<p>First, most themes have multiple page templates you can choose from.</p>\n\n<p>Please check:</p>\n\n<ol>\n<li>go... | 2018/06/09 | [
"https://wordpress.stackexchange.com/questions/305700",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145073/"
] | I have two post types in my website. one for courses and other for teachers. I want to put a selectable list of teachers post type in courses post type and then show it in course single page and link it to single page of that teacher. how can i do?
```
function custom_meta_box_markup($object)
{
wp_nonce_field(basename(__FILE__), "meta-box-nonce");
?>
<div>
<select name="meta-box-dropdown">
<?php
$args=array('post_type'=>'mama_ashpaz');
$q=new WP_Query($args);
if($q->have_posts()){
$current=0;
while($q->have_posts()){
$q->the_post();?>
<?php $options[$current]=get_the_title();
$options_id[$current]=get_the_id();
$current++;
}
}wp_reset_postdata();
foreach($options as $key=>$value){
if($value == get_post_meta($object->ID, "meta-box-dropdown", true))
{
?>
<option selected><?php echo $value; ?></option>
<?php
}
else
{
?>
<option><?php echo $value; ?></option>
<?php
}
}
?>
</select>
</div>
<?php
}
function add_custom_meta_box()
{
add_meta_box("demo-meta-box", "مامان آشپز", "custom_meta_box_markup",
"product", "side", "high", null);
}
add_action("add_meta_boxes", "add_custom_meta_box");
function save_custom_meta_box($post_id, $post, $update)
{
if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-
box-nonce"], basename(__FILE__)))
return $post_id;
if(!current_user_can("edit_post", $post_id))
return $post_id;
if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
return $post_id;
$slug = "product";
if($slug != $post->post_type)
return $post_id;
$meta_box_dropdown_value = "";
if(isset($_POST["meta-box-dropdown"]))
{
$meta_box_dropdown_value = $_POST["meta-box-dropdown"];
}
update_post_meta($post_id, "meta-box-dropdown",
$meta_box_dropdown_value);
}
add_action("save_post", "save_custom_meta_box", 10, 3);
function add_maman(){?>
<div class="maman-meta"><a href="<?php echo get_the_permalink();?>">
<?php echo get_post_meta( get_the_id(), "meta-box-dropdown", true ) ;?>
</a>
</div>
<?php
}
add_action( 'woocommerce_before_single_product_summary','add_maman' );
``` | First, most themes have multiple page templates you can choose from.
Please check:
1. go to cart page (in wp-admin).
2. See side metabox 'Page Attributes'.
3. There you can set the page template, does it have something like 'full\_width'?
You can also try a different hook, like `wp_head`.
Example:
```
add_action( 'wp_head', 'urun_sidebar_kaldir' );
```
Let me know.
---
After checking the WOO cart template, i can't find a `do_action( 'woocommerce_sidebar' )`.
It does exist in the singe-product.php template.
Are you certain the cart sidebar is generated by WooCommerce?
---
Add a full-width template to your theme:
Read [this](https://premium.wpmudev.org/blog/creating-custom-page-templates-in-wordpress/).
Then follow the steps i mentiod at the beginning of my answer. |
305,706 | <p>i want to add a prefix to all the blog title by modifying the all ready applied filter .</p>
<p>when i searched i got this:</p>
<pre><code>apply_filters( 'single_post_title', string $post_title, object $post )
</code></pre>
<p>what action do i have to modify this?</p>
<pre><code>add_filter('single_post_title', 'my_title');
function my_title() {}
</code></pre>
<p>i want this done without the javascript ..
any help is really appreciated
thanks </p>
| [
{
"answer_id": 305709,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 2,
"selected": true,
"text": "<p>With the filter <code>single_post_title</code>, you can change the page/post title that is set in the <code><... | 2018/06/09 | [
"https://wordpress.stackexchange.com/questions/305706",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | i want to add a prefix to all the blog title by modifying the all ready applied filter .
when i searched i got this:
```
apply_filters( 'single_post_title', string $post_title, object $post )
```
what action do i have to modify this?
```
add_filter('single_post_title', 'my_title');
function my_title() {}
```
i want this done without the javascript ..
any help is really appreciated
thanks | With the filter `single_post_title`, you can change the page/post title that is set in the `<head><title>Page title</title></head>`.
If you want to change the title that you see in the page header. ( Which i think you want to do).
Use this filter:
```
add_filter('the_title', 'modify_all_titles', 10, 2);
function modify_all_titles($title, $id) {
return 'SOME TEXT BEFORE TITLE | '.$title;
}
```
Place this code in the functions.php (use a child theme).
Regards, Bjorn |
305,716 | <p>My client decided to take it upon himself to change his domain and but when he did that, it corrupted most of the website. I managed to fix most of it but there is one error i cannot fix. When the user clicks on a picture it loads the picture fine but the left,right, and X on top are replaced with a box as seen here <a href="https://i.imgur.com/8wvJkTT.png" rel="nofollow noreferrer">Example</a> . Has anyone encountered this and how did you fix it? Every icon in elementor is displaying this but I want to fix the gallery icons more than anything</p>
<p>Here is the link to the site
<a href="http://thedetailpro.com/boat-yacht-detailing/" rel="nofollow noreferrer">http://thedetailpro.com/boat-yacht-detailing/</a>.</p>
| [
{
"answer_id": 305709,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 2,
"selected": true,
"text": "<p>With the filter <code>single_post_title</code>, you can change the page/post title that is set in the <code><... | 2018/06/09 | [
"https://wordpress.stackexchange.com/questions/305716",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145082/"
] | My client decided to take it upon himself to change his domain and but when he did that, it corrupted most of the website. I managed to fix most of it but there is one error i cannot fix. When the user clicks on a picture it loads the picture fine but the left,right, and X on top are replaced with a box as seen here [Example](https://i.imgur.com/8wvJkTT.png) . Has anyone encountered this and how did you fix it? Every icon in elementor is displaying this but I want to fix the gallery icons more than anything
Here is the link to the site
<http://thedetailpro.com/boat-yacht-detailing/>. | With the filter `single_post_title`, you can change the page/post title that is set in the `<head><title>Page title</title></head>`.
If you want to change the title that you see in the page header. ( Which i think you want to do).
Use this filter:
```
add_filter('the_title', 'modify_all_titles', 10, 2);
function modify_all_titles($title, $id) {
return 'SOME TEXT BEFORE TITLE | '.$title;
}
```
Place this code in the functions.php (use a child theme).
Regards, Bjorn |
305,812 | <p>I am building an football news site, and on my homepage I have a list of the latest articles. Just the titles and date, no featured images etc. Very clean and simple. But I want to add an image from which category it is in front of it.</p>
<p>For example, if it's news from the English football competition, there will be an English flag before the title. In my WordPress article it will be posted in the English category. If it's in the Dutch competition, there will be a Dutch flag etc.</p>
<p>I have an example, made with photoshop. The first 5 articles are how I actually want it, the last are how they are currently. (It's a demo text so don't focus on the text):</p>
<p><a href="https://i.stack.imgur.com/iaZVh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iaZVh.png" alt="enter image description here"></a></p>
<pre><code>Class Block_28_View extends BlockViewAbstract
{
public function set_content_setting_option()
{
$this->options['show_date'] = '';
$this->options['date_format'] = 'default';
$this->options['date_format_custom'] = 'Y/m/d';
$this->options['excerpt_length'] = 20;
}
public function render_block($post, $attr)
{
$date = $attr['show_date'] ? $this->post_meta_2($post) : "";
$output =
"<article " . jnews_post_class("jeg_post jeg_pl_xs_4", $post->ID) . ">
<div class=\"jeg_postblock_content\"><img src="\
<h3 class=\"jeg_post_title\">
<a href=\"" . get_the_permalink($post) . "\">" . get_the_title($post) . "</a>
</h3>
" . $date . "
</div>
</article>";
return $output;
}
public function build_column($results, $attr)
{
$first_block = '';
$ads_position = $this->random_ads_position(sizeof($results));
for ( $i = 0; $i < sizeof($results); $i++ )
{
if ( $i == $ads_position )
{
$first_block .= $this->render_module_ads('jeg_ajax_loaded anim_' . $i);
}
$first_block .= $this->render_block($results[$i], $attr);
}
$show_border = $attr['show_border'] ? 'show_border' : '';
$output =
"<div class=\"jeg_posts {$show_border}\">
<div class=\"jeg_postsmall jeg_load_more_flag\">
{$first_block}
</div>
</div>";
return $output;
}
public function build_column_alt($results, $attr)
{
$first_block = '';
$ads_position = $this->random_ads_position(sizeof($results));
for ( $i = 0; $i < sizeof($results); $i++ )
{
if ( $i == $ads_position )
{
$first_block .= $this->render_module_ads('jeg_ajax_loaded anim_' . $i);
}
$first_block .= $this->render_block($results[$i], $attr);
}
$output = $first_block;
return $output;
}
public function render_output($attr, $column_class)
{
$results = $this->build_query($attr);
$navigation = $this->render_navigation($attr, $results['next'], $results['prev'], $results['total_page']);
if(!empty($results['result'])) {
$content = $this->render_column($results['result'], $attr);
} else {
$content = $this->empty_content();
}
return
"<div class=\"jeg_block_container\">
{$this->get_content_before($attr)}
{$content}
{$this->get_content_after($attr)}
</div>
<div class=\"jeg_block_navigation\">
{$this->get_navigation_before($attr)}
{$navigation}
{$this->get_navigation_after($attr)}
</div>";
}
public function render_column($result, $attr)
{
$content = $this->build_column($result, $attr);
return $content;
}
public function render_column_alt($result, $attr)
{
$content = $this->build_column_alt($result, $attr);
return $content;
}
}
</code></pre>
| [
{
"answer_id": 305709,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 2,
"selected": true,
"text": "<p>With the filter <code>single_post_title</code>, you can change the page/post title that is set in the <code><... | 2018/06/11 | [
"https://wordpress.stackexchange.com/questions/305812",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145136/"
] | I am building an football news site, and on my homepage I have a list of the latest articles. Just the titles and date, no featured images etc. Very clean and simple. But I want to add an image from which category it is in front of it.
For example, if it's news from the English football competition, there will be an English flag before the title. In my WordPress article it will be posted in the English category. If it's in the Dutch competition, there will be a Dutch flag etc.
I have an example, made with photoshop. The first 5 articles are how I actually want it, the last are how they are currently. (It's a demo text so don't focus on the text):
[](https://i.stack.imgur.com/iaZVh.png)
```
Class Block_28_View extends BlockViewAbstract
{
public function set_content_setting_option()
{
$this->options['show_date'] = '';
$this->options['date_format'] = 'default';
$this->options['date_format_custom'] = 'Y/m/d';
$this->options['excerpt_length'] = 20;
}
public function render_block($post, $attr)
{
$date = $attr['show_date'] ? $this->post_meta_2($post) : "";
$output =
"<article " . jnews_post_class("jeg_post jeg_pl_xs_4", $post->ID) . ">
<div class=\"jeg_postblock_content\"><img src="\
<h3 class=\"jeg_post_title\">
<a href=\"" . get_the_permalink($post) . "\">" . get_the_title($post) . "</a>
</h3>
" . $date . "
</div>
</article>";
return $output;
}
public function build_column($results, $attr)
{
$first_block = '';
$ads_position = $this->random_ads_position(sizeof($results));
for ( $i = 0; $i < sizeof($results); $i++ )
{
if ( $i == $ads_position )
{
$first_block .= $this->render_module_ads('jeg_ajax_loaded anim_' . $i);
}
$first_block .= $this->render_block($results[$i], $attr);
}
$show_border = $attr['show_border'] ? 'show_border' : '';
$output =
"<div class=\"jeg_posts {$show_border}\">
<div class=\"jeg_postsmall jeg_load_more_flag\">
{$first_block}
</div>
</div>";
return $output;
}
public function build_column_alt($results, $attr)
{
$first_block = '';
$ads_position = $this->random_ads_position(sizeof($results));
for ( $i = 0; $i < sizeof($results); $i++ )
{
if ( $i == $ads_position )
{
$first_block .= $this->render_module_ads('jeg_ajax_loaded anim_' . $i);
}
$first_block .= $this->render_block($results[$i], $attr);
}
$output = $first_block;
return $output;
}
public function render_output($attr, $column_class)
{
$results = $this->build_query($attr);
$navigation = $this->render_navigation($attr, $results['next'], $results['prev'], $results['total_page']);
if(!empty($results['result'])) {
$content = $this->render_column($results['result'], $attr);
} else {
$content = $this->empty_content();
}
return
"<div class=\"jeg_block_container\">
{$this->get_content_before($attr)}
{$content}
{$this->get_content_after($attr)}
</div>
<div class=\"jeg_block_navigation\">
{$this->get_navigation_before($attr)}
{$navigation}
{$this->get_navigation_after($attr)}
</div>";
}
public function render_column($result, $attr)
{
$content = $this->build_column($result, $attr);
return $content;
}
public function render_column_alt($result, $attr)
{
$content = $this->build_column_alt($result, $attr);
return $content;
}
}
``` | With the filter `single_post_title`, you can change the page/post title that is set in the `<head><title>Page title</title></head>`.
If you want to change the title that you see in the page header. ( Which i think you want to do).
Use this filter:
```
add_filter('the_title', 'modify_all_titles', 10, 2);
function modify_all_titles($title, $id) {
return 'SOME TEXT BEFORE TITLE | '.$title;
}
```
Place this code in the functions.php (use a child theme).
Regards, Bjorn |
305,821 | <p>my .htaccess code </p>
<h1>BEGIN WordPress</h1>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p><a href="https://i.stack.imgur.com/txgmh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/txgmh.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 305709,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 2,
"selected": true,
"text": "<p>With the filter <code>single_post_title</code>, you can change the page/post title that is set in the <code><... | 2018/06/11 | [
"https://wordpress.stackexchange.com/questions/305821",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135085/"
] | my .htaccess code
BEGIN WordPress
===============
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
[](https://i.stack.imgur.com/txgmh.png) | With the filter `single_post_title`, you can change the page/post title that is set in the `<head><title>Page title</title></head>`.
If you want to change the title that you see in the page header. ( Which i think you want to do).
Use this filter:
```
add_filter('the_title', 'modify_all_titles', 10, 2);
function modify_all_titles($title, $id) {
return 'SOME TEXT BEFORE TITLE | '.$title;
}
```
Place this code in the functions.php (use a child theme).
Regards, Bjorn |
305,842 | <p>How to get the value of ACF after clicking update user in User menu.
I have the following code but it's not working:</p>
<pre><code>function get_acf_value ($post_id) {
$v = get_field('field_5b1d13fce338d', $post_id);
echo $v;
}
add_action( 'acf/save_post', 'get_acf_value' );
</code></pre>
| [
{
"answer_id": 305853,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 1,
"selected": false,
"text": "<p>Your code is working but its not going to print to the screen anything because save_post running in ajax. You c... | 2018/06/11 | [
"https://wordpress.stackexchange.com/questions/305842",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131529/"
] | How to get the value of ACF after clicking update user in User menu.
I have the following code but it's not working:
```
function get_acf_value ($post_id) {
$v = get_field('field_5b1d13fce338d', $post_id);
echo $v;
}
add_action( 'acf/save_post', 'get_acf_value' );
``` | Your code is working but its not going to print to the screen anything because save\_post running in ajax. You can debug the action with the `error_log()`.
First in the wp-config.php you need to turn debug and set it to log into file instead of display
```
define('WP_DEBUG', true);
define('WP_DEBUG_DISPLAY', false);
define('WP_DEBUG_LOG', true);
```
It will create you a file in the folder wp-content in the name debug.log
And then you can use `error_log()` to debug like this:
```
function get_acf_value ($post_id) {
$v = get_field('field_5b1d13fce338d', $post_id);
error_log($v);
// Incase it is array you can use print_r
error_log( print_r( $v, true ) );
}
add_action( 'acf/save_post', 'get_acf_value' );
``` |
305,882 | <p>While freshly installed, I cannot access the 'Add new plugins` page whatsoever. It just keep waiting & then redirect me to 404 page of the current theme.</p>
<p>I'm not sure what went wrong as the wordpress is freshly installed. Wordpress version is 4.9.6 & I'm using PHP7 for the host.</p>
<p>I tried solutions suggested for similar issues but cannot get it fixed. I also get this message when I'm at the Installed Plugins page</p>
<p><code>Warning: An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums. (WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.) in /home/tuva9001/public_html/wp-includes/update.php on line 347</code></p>
| [
{
"answer_id": 305853,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 1,
"selected": false,
"text": "<p>Your code is working but its not going to print to the screen anything because save_post running in ajax. You c... | 2018/06/12 | [
"https://wordpress.stackexchange.com/questions/305882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101948/"
] | While freshly installed, I cannot access the 'Add new plugins` page whatsoever. It just keep waiting & then redirect me to 404 page of the current theme.
I'm not sure what went wrong as the wordpress is freshly installed. Wordpress version is 4.9.6 & I'm using PHP7 for the host.
I tried solutions suggested for similar issues but cannot get it fixed. I also get this message when I'm at the Installed Plugins page
`Warning: An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums. (WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.) in /home/tuva9001/public_html/wp-includes/update.php on line 347` | Your code is working but its not going to print to the screen anything because save\_post running in ajax. You can debug the action with the `error_log()`.
First in the wp-config.php you need to turn debug and set it to log into file instead of display
```
define('WP_DEBUG', true);
define('WP_DEBUG_DISPLAY', false);
define('WP_DEBUG_LOG', true);
```
It will create you a file in the folder wp-content in the name debug.log
And then you can use `error_log()` to debug like this:
```
function get_acf_value ($post_id) {
$v = get_field('field_5b1d13fce338d', $post_id);
error_log($v);
// Incase it is array you can use print_r
error_log( print_r( $v, true ) );
}
add_action( 'acf/save_post', 'get_acf_value' );
``` |
305,894 | <p>I am having a heck of a time finding an answer to this solution. I have googled everything I can think of but I can't find anything. I want to load an inline JavaScript tag in the footer of the admin. When I use the admin_footer action, the code is added <em>before</em> the JS tags that are called by the wp_enqueue_script function. I need this script to be called <em>after</em> those scripts. How can I achieve this?</p>
<p>This is what I am using now:</p>
<pre><code><?php add_action('admin_footer', 'gallery_js', PHP_INT_MAX);
function gallery_js(){ ?>
<script>
(function($){
$('#deleteSelected').serviceGallery({
ajaxUrl: '<?php echo JZS_PLUGIN_PATH.'/admin/partials/service-gallery-ajax.php';?>'
});
})(jQuery);
</script>
<?php }
</code></pre>
<p>See this image for a better explanation:
<a href="https://i.stack.imgur.com/zU9BU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zU9BU.jpg" alt="enter image description here"></a>
The image is when using the admin_footer action.</p>
| [
{
"answer_id": 305896,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 0,
"selected": false,
"text": "<p>I did the following test:</p>\n\n<pre><code>add_action('admin_footer', 'admin_footer_test', PHP_INT_MAX);\nfunc... | 2018/06/12 | [
"https://wordpress.stackexchange.com/questions/305894",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86835/"
] | I am having a heck of a time finding an answer to this solution. I have googled everything I can think of but I can't find anything. I want to load an inline JavaScript tag in the footer of the admin. When I use the admin\_footer action, the code is added *before* the JS tags that are called by the wp\_enqueue\_script function. I need this script to be called *after* those scripts. How can I achieve this?
This is what I am using now:
```
<?php add_action('admin_footer', 'gallery_js', PHP_INT_MAX);
function gallery_js(){ ?>
<script>
(function($){
$('#deleteSelected').serviceGallery({
ajaxUrl: '<?php echo JZS_PLUGIN_PATH.'/admin/partials/service-gallery-ajax.php';?>'
});
})(jQuery);
</script>
<?php }
```
See this image for a better explanation:
[](https://i.stack.imgur.com/zU9BU.jpg)
The image is when using the admin\_footer action. | I finally found the answer. I need to use the [admin\_print\_footer\_scripts](https://make.wordpress.org/core/2016/07/15/introducing-admin_print_footer_scripts-hook_suffix-in-4-6/) action. This will add scripts after the scripts that were called with `wp_enqueue_scripts`. |
305,910 | <p>I have a custom post type by the name of the event.</p>
<p>So Created a category page them for them like this →</p>
<pre><code>category-event.php
</code></pre>
<p>Like this →</p>
<pre><code><?php get_header(); ?>
//and then the loop here
<?php get_footer(); ?>
</code></pre>
<p>But the individual category pages are not generating the posts only from those categories, but entirely all posts.</p>
<p>I think something needs to be fixed in the loop?</p>
<h1>Update → the Loop</h1>
<pre><code>$the_query = new WP_Query( array(
'post_type' => 'event',
'posts_per_page' => 10,
'post_status' => 'publish',
) );
?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- the loop -->
<div class="class1">
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="class2">
<div class="class3">
<?php $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
<?php $embed = wp_oembed_get( $url ); ?>
<div class="class4">
<iframe id="class_frame" width="560" height="315" src="https://www.youtube.com/watch"); ?>" allowfullscreen frameborder="0"></iframe>
</div>
</div>
<div class="class6">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</div>
<!-- end of the loop -->
<!-- <?php wp_reset_postdata(); ?> -->
<?php endif; ?>
</code></pre>
| [
{
"answer_id": 305912,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to make use of the template hierarchy. So, according to the information given of your cu... | 2018/06/12 | [
"https://wordpress.stackexchange.com/questions/305910",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
] | I have a custom post type by the name of the event.
So Created a category page them for them like this →
```
category-event.php
```
Like this →
```
<?php get_header(); ?>
//and then the loop here
<?php get_footer(); ?>
```
But the individual category pages are not generating the posts only from those categories, but entirely all posts.
I think something needs to be fixed in the loop?
Update → the Loop
=================
```
$the_query = new WP_Query( array(
'post_type' => 'event',
'posts_per_page' => 10,
'post_status' => 'publish',
) );
?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- the loop -->
<div class="class1">
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="class2">
<div class="class3">
<?php $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
<?php $embed = wp_oembed_get( $url ); ?>
<div class="class4">
<iframe id="class_frame" width="560" height="315" src="https://www.youtube.com/watch"); ?>" allowfullscreen frameborder="0"></iframe>
</div>
</div>
<div class="class6">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</div>
<!-- end of the loop -->
<!-- <?php wp_reset_postdata(); ?> -->
<?php endif; ?>
``` | You may alter the main query before the loop, but it's crucial to reset the main query afterwards. Otherwise you'll probably run into problems elsewhere.
Disclaimer: Doing this is officially discouraged by WordPress [here](https://developer.wordpress.org/reference/functions/query_posts/). However, in my experience it works perfectly to achieve the behaviour you want. Just don't forget to add **wp\_reset\_query();** after closing the loop.
```
<?php query_posts('post_type=event'); ?>
<?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>
<!-- Stuff happening inside the loop -->
<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>
```
**Another approach** (slightly more complicated but without altering the main query) would be:
```
<?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>
<?php $get_category_posts = get_posts( $args ); ?>
<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>
<!-- Stuff happening inside our custom 'loop' -->
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
```
According to the 2nd solution, **your PHP-File should look like this:**
```
<?php get_header(); ?>
<?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>
<?php $get_category_posts = get_posts( $args ); ?>
<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>
<div class="class1">
<div class="class2">
<div class="class3">
<?php print_r( get_post_meta( get_the_ID() ) ); // Just for demo purposes ?>
<?php // $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
<?php // $embed = wp_oembed_get( $url ); ?>
<div class="class4">
<iframe id="class_frame" width="560" height="315" src="https://www.youtube.com/watch" allowfullscreen frameborder="0"></iframe>
</div>
</div>
<div class="class6">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
</div>
</div>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php get_footer(); ?>
```
If this doesn't work it might be that you're working in the wrong template file. Without knowing your project my guess would be that it should be **archive-event.php**
**Update:**
It turned out to be **taxonomy-event.php** in this case. |
305,939 | <p>EDIT: see solution below from @motivast. With his basic setup you can then make whatever changes you'd like to specific auto-scroll actions and relocate whichever specific notices you want. My final solution also includes hooking a blank div within the coupon form and then targeting the coupon notices there, like this:</p>
<pre><code>/* Add div to hook coupon notices to */
add_action ('woocommerce_cart_coupon' , 'coupon_notices_div' , 1 );
function coupon_notices_div() {
echo "";
?>
<div class="cart-coupon-notices"></div>
<?php
}
</code></pre>
<p>With that in your custom plugin php file, you can then use .cart-coupon-notices instead of .cart-collaterals in @motivast's solution. This places the coupon notices immediately below the "apply coupon" button.</p>
<hr>
<p>Original question:</p>
<p>I've found many examples of how to do this for the "added to cart" notice on products/shop pages, but the cart page seems to be altogether different. The notices I want to move more than any others are the coupon notices (i.e. "coupon applied successfully" etc.). Auto-scrolling the customers to the top of the page when they add a coupon is quite annoying for them.</p>
<p>The solution everyone talks about is that you need to just relocate wc_print_notices from the top of the cart page to somewhere else (I want it hooked to woocommerce_before_cart_totals), but no matter what I do the notices are still at the top of the page.</p>
<p>There are several variations of this question on stackexchange, none with any answers that work.</p>
<p>I've tried all the options listed <a href="https://stackoverflow.com/questions/44326937/removing-adding-wc-print-notices-on-cart-page">here</a>, but no luck. </p>
<p>I've tried playing with variations from <a href="https://stackoverflow.com/questions/32583786/how-to-change-position-of-woocommerce-added-to-cart-message">here</a>, also no luck.</p>
<p>I've tried the options from <a href="https://stackoverflow.com/questions/34226268/how-do-i-move-the-woocommerce-error-message-where-i-want">here</a>, and... no luck.</p>
<p>Other variations of the same problem: <a href="https://stackoverflow.com/questions/48176219/need-to-show-woo-commerce-notices-twice-on-cart-page">here</a>, <a href="https://stackoverflow.com/questions/33791072/how-to-change-position-of-woocommerce-error-messages-on-checkout-page/33794083">here</a>, a possible solution that works only with the storefront theme <a href="https://stackoverflow.com/questions/46565865/change-the-position-of-of-woocommerce-notices-in-storefront-theme">here</a>.</p>
<p>Any help would be hugely appreciated!</p>
<p>EDIT: Two threads from elsewhere helping to solve this issue:</p>
<p><a href="https://wordpress.org/support/topic/relocate-coupon-notices-on-cart-page/" rel="nofollow noreferrer">https://wordpress.org/support/topic/relocate-coupon-notices-on-cart-page/</a></p>
<p><a href="https://www.facebook.com/groups/advanced.woocommerce/permalink/2141163449231396/" rel="nofollow noreferrer">https://www.facebook.com/groups/advanced.woocommerce/permalink/2141163449231396/</a> </p>
| [
{
"answer_id": 305912,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to make use of the template hierarchy. So, according to the information given of your cu... | 2018/06/12 | [
"https://wordpress.stackexchange.com/questions/305939",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73388/"
] | EDIT: see solution below from @motivast. With his basic setup you can then make whatever changes you'd like to specific auto-scroll actions and relocate whichever specific notices you want. My final solution also includes hooking a blank div within the coupon form and then targeting the coupon notices there, like this:
```
/* Add div to hook coupon notices to */
add_action ('woocommerce_cart_coupon' , 'coupon_notices_div' , 1 );
function coupon_notices_div() {
echo "";
?>
<div class="cart-coupon-notices"></div>
<?php
}
```
With that in your custom plugin php file, you can then use .cart-coupon-notices instead of .cart-collaterals in @motivast's solution. This places the coupon notices immediately below the "apply coupon" button.
---
Original question:
I've found many examples of how to do this for the "added to cart" notice on products/shop pages, but the cart page seems to be altogether different. The notices I want to move more than any others are the coupon notices (i.e. "coupon applied successfully" etc.). Auto-scrolling the customers to the top of the page when they add a coupon is quite annoying for them.
The solution everyone talks about is that you need to just relocate wc\_print\_notices from the top of the cart page to somewhere else (I want it hooked to woocommerce\_before\_cart\_totals), but no matter what I do the notices are still at the top of the page.
There are several variations of this question on stackexchange, none with any answers that work.
I've tried all the options listed [here](https://stackoverflow.com/questions/44326937/removing-adding-wc-print-notices-on-cart-page), but no luck.
I've tried playing with variations from [here](https://stackoverflow.com/questions/32583786/how-to-change-position-of-woocommerce-added-to-cart-message), also no luck.
I've tried the options from [here](https://stackoverflow.com/questions/34226268/how-do-i-move-the-woocommerce-error-message-where-i-want), and... no luck.
Other variations of the same problem: [here](https://stackoverflow.com/questions/48176219/need-to-show-woo-commerce-notices-twice-on-cart-page), [here](https://stackoverflow.com/questions/33791072/how-to-change-position-of-woocommerce-error-messages-on-checkout-page/33794083), a possible solution that works only with the storefront theme [here](https://stackoverflow.com/questions/46565865/change-the-position-of-of-woocommerce-notices-in-storefront-theme).
Any help would be hugely appreciated!
EDIT: Two threads from elsewhere helping to solve this issue:
<https://wordpress.org/support/topic/relocate-coupon-notices-on-cart-page/>
<https://www.facebook.com/groups/advanced.woocommerce/permalink/2141163449231396/> | You may alter the main query before the loop, but it's crucial to reset the main query afterwards. Otherwise you'll probably run into problems elsewhere.
Disclaimer: Doing this is officially discouraged by WordPress [here](https://developer.wordpress.org/reference/functions/query_posts/). However, in my experience it works perfectly to achieve the behaviour you want. Just don't forget to add **wp\_reset\_query();** after closing the loop.
```
<?php query_posts('post_type=event'); ?>
<?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>
<!-- Stuff happening inside the loop -->
<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>
```
**Another approach** (slightly more complicated but without altering the main query) would be:
```
<?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>
<?php $get_category_posts = get_posts( $args ); ?>
<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>
<!-- Stuff happening inside our custom 'loop' -->
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
```
According to the 2nd solution, **your PHP-File should look like this:**
```
<?php get_header(); ?>
<?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>
<?php $get_category_posts = get_posts( $args ); ?>
<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>
<div class="class1">
<div class="class2">
<div class="class3">
<?php print_r( get_post_meta( get_the_ID() ) ); // Just for demo purposes ?>
<?php // $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
<?php // $embed = wp_oembed_get( $url ); ?>
<div class="class4">
<iframe id="class_frame" width="560" height="315" src="https://www.youtube.com/watch" allowfullscreen frameborder="0"></iframe>
</div>
</div>
<div class="class6">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
</div>
</div>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php get_footer(); ?>
```
If this doesn't work it might be that you're working in the wrong template file. Without knowing your project my guess would be that it should be **archive-event.php**
**Update:**
It turned out to be **taxonomy-event.php** in this case. |
305,951 | <p>Does anyone know how to put code into your theme that will only shop up on WooCommerce pages? I want to add a cart link but don't need it to shop up on the rest of the site. Thanks!</p>
| [
{
"answer_id": 305912,
"author": "user3135691",
"author_id": 59755,
"author_profile": "https://wordpress.stackexchange.com/users/59755",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to make use of the template hierarchy. So, according to the information given of your cu... | 2018/06/12 | [
"https://wordpress.stackexchange.com/questions/305951",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125569/"
] | Does anyone know how to put code into your theme that will only shop up on WooCommerce pages? I want to add a cart link but don't need it to shop up on the rest of the site. Thanks! | You may alter the main query before the loop, but it's crucial to reset the main query afterwards. Otherwise you'll probably run into problems elsewhere.
Disclaimer: Doing this is officially discouraged by WordPress [here](https://developer.wordpress.org/reference/functions/query_posts/). However, in my experience it works perfectly to achieve the behaviour you want. Just don't forget to add **wp\_reset\_query();** after closing the loop.
```
<?php query_posts('post_type=event'); ?>
<?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>
<!-- Stuff happening inside the loop -->
<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>
```
**Another approach** (slightly more complicated but without altering the main query) would be:
```
<?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>
<?php $get_category_posts = get_posts( $args ); ?>
<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>
<!-- Stuff happening inside our custom 'loop' -->
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
```
According to the 2nd solution, **your PHP-File should look like this:**
```
<?php get_header(); ?>
<?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>
<?php $get_category_posts = get_posts( $args ); ?>
<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>
<div class="class1">
<div class="class2">
<div class="class3">
<?php print_r( get_post_meta( get_the_ID() ) ); // Just for demo purposes ?>
<?php // $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
<?php // $embed = wp_oembed_get( $url ); ?>
<div class="class4">
<iframe id="class_frame" width="560" height="315" src="https://www.youtube.com/watch" allowfullscreen frameborder="0"></iframe>
</div>
</div>
<div class="class6">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
</div>
</div>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php get_footer(); ?>
```
If this doesn't work it might be that you're working in the wrong template file. Without knowing your project my guess would be that it should be **archive-event.php**
**Update:**
It turned out to be **taxonomy-event.php** in this case. |
305,976 | <p>So I am trying to edit my Search so it searches only for specific categories. I am adding this code to my <code>functions.php</code> file in child theme:</p>
<pre><code>function searchcategory($query) {
if ($query->is_search) {
$query->set('cat','37');
}
return $query;
}
add_filter('pre_get_posts','searchcategory');
</code></pre>
<p>So this is the issue: For example, when I run this code, my search does not even find anything.</p>
<p>Important notes:
1) First of all, I have created several taxonomies and custom post types with Toolset plugin, and these is ID of one of those taxonomies - I am looking up its ID by hovering cursor over the name of taxonomy. Could this be an issue?
2) When I run this code, which supposes to exclude all pages from search results, I still see some of the pages. It is weird. </p>
<pre><code>function SearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'page');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
</code></pre>
<p>Does anyone know what may cause this issue?</p>
| [
{
"answer_id": 305979,
"author": "tera_789",
"author_id": 144586,
"author_profile": "https://wordpress.stackexchange.com/users/144586",
"pm_score": 0,
"selected": false,
"text": "<p>I solved the issue. I added this same code:</p>\n\n<pre><code>function searchcategory($query) {\nif ($quer... | 2018/06/13 | [
"https://wordpress.stackexchange.com/questions/305976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144586/"
] | So I am trying to edit my Search so it searches only for specific categories. I am adding this code to my `functions.php` file in child theme:
```
function searchcategory($query) {
if ($query->is_search) {
$query->set('cat','37');
}
return $query;
}
add_filter('pre_get_posts','searchcategory');
```
So this is the issue: For example, when I run this code, my search does not even find anything.
Important notes:
1) First of all, I have created several taxonomies and custom post types with Toolset plugin, and these is ID of one of those taxonomies - I am looking up its ID by hovering cursor over the name of taxonomy. Could this be an issue?
2) When I run this code, which supposes to exclude all pages from search results, I still see some of the pages. It is weird.
```
function SearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'page');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
```
Does anyone know what may cause this issue? | This code should work OK, but... There are some problems with it. Let's break it apart and add some comments.
```
function searchcategory($query) {
if ($query->is_search) {
// Checking only for is_search is very risky. It will be set to true
// whenever param "s" is set. So your function will modify any wp_query with s,
// for instance the one in wp-admin... But also any other, even if
// the query isn't querying for posts...
$query->set('cat','37');
// You pass ID of term in here. It's a number. Passing it as string
// is not a problem, but it's another bad practice, because it will
// have to be converted to number.
}
return $query;
// It's an action - you don't have to return anything in it. Your result
// will be ignored.
}
add_filter('pre_get_posts','searchcategory');
// pre_get_posts is and action and not a filter.
// Due to the way actions/filters are implemented,
// you can assign your callback using `add_filter`,
// but it isn't a good practice.
```
So how to write it nicer?
```
function searchcategory($query) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$query->set( 'cat', 37 );
}
}
add_action( 'pre_get_posts', 'searchcategory' );
``` |
306,011 | <p>I need to display New Arrivals in a section of my homepage, I have created a new arrivals category and would like to display the products in this category on a page, I don't want to use the shortcode as I am writing the html & php for this page.</p>
<p>Any help would be appreciated, thanks.</p>
| [
{
"answer_id": 306013,
"author": "Tim",
"author_id": 118534,
"author_profile": "https://wordpress.stackexchange.com/users/118534",
"pm_score": 4,
"selected": true,
"text": "<p>you can still use a shortcode inside of php if you aren't customizing the output. see <a href=\"https://docs.woo... | 2018/06/13 | [
"https://wordpress.stackexchange.com/questions/306011",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145262/"
] | I need to display New Arrivals in a section of my homepage, I have created a new arrivals category and would like to display the products in this category on a page, I don't want to use the shortcode as I am writing the html & php for this page.
Any help would be appreciated, thanks. | you can still use a shortcode inside of php if you aren't customizing the output. see <https://docs.woocommerce.com/document/woocommerce-shortcodes/#scenario-5-specific-categories> and <https://developer.wordpress.org/reference/functions/do_shortcode/>
```
<?php
echo do_shortcode('[products category="new-arrivals"]');
?>
```
Alternatively, If you need to customize the output of the products then just use `wc_get_products` to get a list of products and iterate through it. See <https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query>
```
<?php
$args = array(
'category' => array( 'new-arrivals' ),
);
$products = wc_get_products( $args );
foreach ($products as $product) {
echo $product->get_title() . ' ' . $product->get_price();
}
?>
``` |
306,021 | <p>I need to push js variable into php variable. AJAX url is set via wp_localize_script but it returns ERROR 400 Bad Request. functions.php is looks like </p>
<pre><code>wp_localize_script( 'script-js', 'compareids_ajax', array( 'ajax_url' => admin_url('admin-ajax.php')) );
</code></pre>
<p>custom.js</p>
<pre><code> var compareIDs = $(".table td input:checkbox:checked").map(function(){
return $(this).val();
}).get(); // <----
$('.selected').text(compareIDs);
console.log(compareIDs);
$.ajax({
type: "POST",
url: compareids_ajax.ajax_url,
data: '{ compareIDs : compareIDs }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
},
error: function (errormessage) {
}
});
</code></pre>
<p>and my filter-page.php has</p>
<pre><code> <?php
$compareIDs = array( $_POST['compareIDs'] );
$args02 = array( 'post_type' => 'custom',
'post__in' => $compareIDs );
$loop02 = new WP_Query( $args02 );
while ( $loop02->have_posts() ) : $loop02->the_post();
?>
</code></pre>
| [
{
"answer_id": 306067,
"author": "Bikash Waiba",
"author_id": 121069,
"author_profile": "https://wordpress.stackexchange.com/users/121069",
"pm_score": 2,
"selected": true,
"text": "<p>First you need to to send function name as additional data as</p>\n\n<pre><code> $.ajax({\n typ... | 2018/06/13 | [
"https://wordpress.stackexchange.com/questions/306021",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145268/"
] | I need to push js variable into php variable. AJAX url is set via wp\_localize\_script but it returns ERROR 400 Bad Request. functions.php is looks like
```
wp_localize_script( 'script-js', 'compareids_ajax', array( 'ajax_url' => admin_url('admin-ajax.php')) );
```
custom.js
```
var compareIDs = $(".table td input:checkbox:checked").map(function(){
return $(this).val();
}).get(); // <----
$('.selected').text(compareIDs);
console.log(compareIDs);
$.ajax({
type: "POST",
url: compareids_ajax.ajax_url,
data: '{ compareIDs : compareIDs }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
},
error: function (errormessage) {
}
});
```
and my filter-page.php has
```
<?php
$compareIDs = array( $_POST['compareIDs'] );
$args02 = array( 'post_type' => 'custom',
'post__in' => $compareIDs );
$loop02 = new WP_Query( $args02 );
while ( $loop02->have_posts() ) : $loop02->the_post();
?>
``` | First you need to to send function name as additional data as
```
$.ajax({
type: "POST",
url: compareids_ajax.ajax_url,
data: { // Data object
compareIDs : compareIDs,
action: 'your_ajax_function' // This is required to let WordPress know which function to invoke
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log( msg );
},
error: function (errormessage) {
console.log( errormessage );
}
});
```
In your php file
```
add_action('wp_ajax_nopriv_your_ajax_function','your_ajax_function'); // Ajax Function should be hooked like this for unauthenticated users
add_action('wp_ajax_your_ajax_function','your_ajax_function'); //
function your_ajax_function(){
$comparedIds = $_POST['compareIDs']; // Your data is now available in $_POST
// Do your stuff here
die(); // At the end
}
```
See [wp\_ajax\_(action)](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)) |
306,057 | <p>I am adding a default WordPress Search widget through Elementor on two of my page, page X and page Y. Page X ID = 100, page Y ID = 200. I want the user to be able to search through category 37 when he is on page X, and be able to search through category 24 when he is on page Y. I wrote this code: </p>
<pre><code>function searchcategory($query) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
if ( is_page(100) ) {
$query->set('cat',37);
}
else if ( is_page(200) ) {
$query->set('cat',24);
}
}
}
add_filter('pre_get_posts','searchcategory');
</code></pre>
<p>However, it does not work properly. It returns pages which have different categories and IDs etc. Also, results are same on both page X and page Y. Can anyone help editing the code?</p>
<p>Note: the code below works fine though:</p>
<pre><code>function searchtest($query) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$query->set( 'cat', 39 );
}
}
add_action( 'pre_get_posts', 'searchtest' );
</code></pre>
| [
{
"answer_id": 306064,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>Well, let's try to understand what is your code doing...</p>\n\n<p>In this line:</p>\n\n<pre><code>if... | 2018/06/14 | [
"https://wordpress.stackexchange.com/questions/306057",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144586/"
] | I am adding a default WordPress Search widget through Elementor on two of my page, page X and page Y. Page X ID = 100, page Y ID = 200. I want the user to be able to search through category 37 when he is on page X, and be able to search through category 24 when he is on page Y. I wrote this code:
```
function searchcategory($query) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
if ( is_page(100) ) {
$query->set('cat',37);
}
else if ( is_page(200) ) {
$query->set('cat',24);
}
}
}
add_filter('pre_get_posts','searchcategory');
```
However, it does not work properly. It returns pages which have different categories and IDs etc. Also, results are same on both page X and page Y. Can anyone help editing the code?
Note: the code below works fine though:
```
function searchtest($query) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$query->set( 'cat', 39 );
}
}
add_action( 'pre_get_posts', 'searchtest' );
``` | The answer before mine shows you the problem about `is_search()` in your code.
To solve your problem, you can try to add some datas from your search form. In your WordPress you have a searchform.php, you can edit this file to add a new hidden field or use an ugly filter function like I have do here :
```
// Gives you the category where you want to search with from page ID
add_filter('wpse_306057_search_category_id', 'wpse_306057_search_category_id', 10, 1);
function wpse_306057_search_category_id($id = false) {
switch($id)
{
case 100:
$cat_id = 37;
break;
case 200:
$cat_id = 24;
break;
case 201:
case 202:
case 203:
$cat_id = array(57,99); // You may use multiple cats
break;
default:
$cat_id = false;
break;
}
return $cat_id;
}
// Add input hidden with "from page" for your search form
add_filter('get_search_form', 'wpse_306057_search_category_input', 10, 1);
function wpse_306057_search_category_input($form) {
return str_replace('</form>', '<input type="hidden" name="search_from_page" value="'.get_queried_object_id().'" /></form>', $form);
}
// Add cat to your query
add_filter('pre_get_posts', 'wpse_306057_search_category', 10, 1);
function wpse_306057_search_category($query) {
if(!is_admin()
&& $query->is_main_query()
&& $query->is_search()
&& !empty(@$_GET['search_from_page'])
&& apply_filters('wpse_306057_search_category_id', $_GET['search_from_page']))
{
$query->set('cat', apply_filters('wpse_306057_search_category_id', $_GET['search_from_page']));
}
}
```
I haven't tested the code, but it's a good way to play with what you want to achieve. |
306,058 | <p>How to redirect Old Post URL to new Post URL and keep Old post Comments? is it possible. can any one give me plugin to do this.</p>
| [
{
"answer_id": 306061,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": false,
"text": "<p>I use is <a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">free ... | 2018/06/14 | [
"https://wordpress.stackexchange.com/questions/306058",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124340/"
] | How to redirect Old Post URL to new Post URL and keep Old post Comments? is it possible. can any one give me plugin to do this. | I use is [free redirection](https://wordpress.org/plugins/redirection/) plugin. If you are using Yoast SEO premium, redirection feature is available for you already. You can also use any other plugin if you like. The only thing you need to ensure is, it should be a 301 redirection.
For this example, I’m using Redirection plugin.
Here is the scenario:
```
Already published post with URL: https://WPSutra.com/how-to-add-google-amp-to-wordpress-to-speed-up-your-mobile-site
New URL After editing the post slug: https://WPSutra.com/Google-amp-WordPress
```
Go to Tools > Redirection (or redirection tab of any other plugin that you are using). You can also set redirection using the .htaccess method.
Here you can set the 301 redirect from old post to the new one as shown in below screenshot:
[](https://i.stack.imgur.com/HCSRR.png)
What this would do is, when someone will click on your old URL, they will be automatically redirected to new URL. This would ensure you wouldn’t lose any traffic after changing post slug of the already published post.
Do note that you would lose your social media shares number & that is a very little trade-off you need to make when dealing with editing old post URL. I usually do this for editing my old blog posts or dealing with non-performing blog posts. |
306,110 | <p>I'm completely out of my league with regex stuff. I've seen a lot of examples for putting redirect code into the <code>.htaccess</code> file, but the default examples are mostly for changing away from dates. Everything else says to use the Redirection plugin, which I already use for simple 1 off redirects, but I don't know the regex for a permalink change. We have 743 posts, so I'm not doing those 1-by-1!</p>
<p>Here's the old and new structure:</p>
<p>old: <code>/%post_id%/%postname%</code><br>
new: <code>/%category%/%postname%</code></p>
<p>Any help with what I need to put into the <code>.htaccess</code> file or the redirection plugin for this specific permalink change, would be most appreciated!</p>
| [
{
"answer_id": 306061,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": false,
"text": "<p>I use is <a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">free ... | 2018/06/14 | [
"https://wordpress.stackexchange.com/questions/306110",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19510/"
] | I'm completely out of my league with regex stuff. I've seen a lot of examples for putting redirect code into the `.htaccess` file, but the default examples are mostly for changing away from dates. Everything else says to use the Redirection plugin, which I already use for simple 1 off redirects, but I don't know the regex for a permalink change. We have 743 posts, so I'm not doing those 1-by-1!
Here's the old and new structure:
old: `/%post_id%/%postname%`
new: `/%category%/%postname%`
Any help with what I need to put into the `.htaccess` file or the redirection plugin for this specific permalink change, would be most appreciated! | I use is [free redirection](https://wordpress.org/plugins/redirection/) plugin. If you are using Yoast SEO premium, redirection feature is available for you already. You can also use any other plugin if you like. The only thing you need to ensure is, it should be a 301 redirection.
For this example, I’m using Redirection plugin.
Here is the scenario:
```
Already published post with URL: https://WPSutra.com/how-to-add-google-amp-to-wordpress-to-speed-up-your-mobile-site
New URL After editing the post slug: https://WPSutra.com/Google-amp-WordPress
```
Go to Tools > Redirection (or redirection tab of any other plugin that you are using). You can also set redirection using the .htaccess method.
Here you can set the 301 redirect from old post to the new one as shown in below screenshot:
[](https://i.stack.imgur.com/HCSRR.png)
What this would do is, when someone will click on your old URL, they will be automatically redirected to new URL. This would ensure you wouldn’t lose any traffic after changing post slug of the already published post.
Do note that you would lose your social media shares number & that is a very little trade-off you need to make when dealing with editing old post URL. I usually do this for editing my old blog posts or dealing with non-performing blog posts. |
306,168 | <p><br>I am having a problem accessing my Advanced Custom Fields that I assigned to my post type.</p>
<p><a href="https://i.stack.imgur.com/JuiNY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JuiNY.png" alt="enter image description here"></a></p>
<p>To loop through the posts in my events types I did this:</p>
<pre><code><?php
$slider = get_posts( $slider = g array(
'post_type' => 'event',
'posts_per_page' => - 1
)); ?>
<?php
$count = 0; ?>
<?php
foreach($slider as $slide): ?>
<?php
$title = the_field('event_name'); ?>
<div class="item <?php
echo ($count == 0) ? 'active' : ''; ?>">
<img src="<?php
echo wp_get_attachment_url(get_post_thumbnail_id($slide->ID)) ?>" class="img-responsive yooo"/>
<div class="carousel-caption">
<div class="caption-text">
<hr style="width: 60%;border-bottom: 1px solid #000;margin-top: 0px;margin-bottom: 50px;">
<img src="<?php
bloginfo('stylesheet_directory'); ?>/assets/img/icons/note_icon.svg" onerror="this.src='<?php
bloginfo('stylesheet_directory'); ?>/assets/img/icons/music_note.png'" alt="" class="img-responsive img--center">
<h4><?php
echo get_the_title($ID); ?></h4>
<h4><?php
the_field('event_date'); ?></h4>
<p><?php
the_content(); ?></p>
<hr style="width: 60%;border-bottom: 1px solid #000;margin-bottom: 0px;margin-top: 50px;">
</div>
</div>
</div>
<?php
$count++; ?>
<?php
endforeach; ?>
</code></pre>
<p>I get the featured image from the post but I cant retrieve the content (text), title or my advanced custom fields.</p>
| [
{
"answer_id": 306061,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": false,
"text": "<p>I use is <a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">free ... | 2018/06/15 | [
"https://wordpress.stackexchange.com/questions/306168",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145360/"
] | I am having a problem accessing my Advanced Custom Fields that I assigned to my post type.
[](https://i.stack.imgur.com/JuiNY.png)
To loop through the posts in my events types I did this:
```
<?php
$slider = get_posts( $slider = g array(
'post_type' => 'event',
'posts_per_page' => - 1
)); ?>
<?php
$count = 0; ?>
<?php
foreach($slider as $slide): ?>
<?php
$title = the_field('event_name'); ?>
<div class="item <?php
echo ($count == 0) ? 'active' : ''; ?>">
<img src="<?php
echo wp_get_attachment_url(get_post_thumbnail_id($slide->ID)) ?>" class="img-responsive yooo"/>
<div class="carousel-caption">
<div class="caption-text">
<hr style="width: 60%;border-bottom: 1px solid #000;margin-top: 0px;margin-bottom: 50px;">
<img src="<?php
bloginfo('stylesheet_directory'); ?>/assets/img/icons/note_icon.svg" onerror="this.src='<?php
bloginfo('stylesheet_directory'); ?>/assets/img/icons/music_note.png'" alt="" class="img-responsive img--center">
<h4><?php
echo get_the_title($ID); ?></h4>
<h4><?php
the_field('event_date'); ?></h4>
<p><?php
the_content(); ?></p>
<hr style="width: 60%;border-bottom: 1px solid #000;margin-bottom: 0px;margin-top: 50px;">
</div>
</div>
</div>
<?php
$count++; ?>
<?php
endforeach; ?>
```
I get the featured image from the post but I cant retrieve the content (text), title or my advanced custom fields. | I use is [free redirection](https://wordpress.org/plugins/redirection/) plugin. If you are using Yoast SEO premium, redirection feature is available for you already. You can also use any other plugin if you like. The only thing you need to ensure is, it should be a 301 redirection.
For this example, I’m using Redirection plugin.
Here is the scenario:
```
Already published post with URL: https://WPSutra.com/how-to-add-google-amp-to-wordpress-to-speed-up-your-mobile-site
New URL After editing the post slug: https://WPSutra.com/Google-amp-WordPress
```
Go to Tools > Redirection (or redirection tab of any other plugin that you are using). You can also set redirection using the .htaccess method.
Here you can set the 301 redirect from old post to the new one as shown in below screenshot:
[](https://i.stack.imgur.com/HCSRR.png)
What this would do is, when someone will click on your old URL, they will be automatically redirected to new URL. This would ensure you wouldn’t lose any traffic after changing post slug of the already published post.
Do note that you would lose your social media shares number & that is a very little trade-off you need to make when dealing with editing old post URL. I usually do this for editing my old blog posts or dealing with non-performing blog posts. |
306,178 | <p><strong>Update</strong>
Case closed. I forgot I have a kill function in my functions.php with redirects attachment, search, author, daily archive pages to home. Deleted the part for search and works fine.</p>
<p>Sorry for that, and thank you for your time and help :) </p>
<p>I have a simple search form in wordpress </p>
<pre><code><form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
<label>
<input type="search" class="search-field" placeholder="what are you looking for?" value="" name="s" title="enter search" />
</label>
<input type="submit" class="btn search-submit" value="Search" />
</form>
</code></pre>
<p>After I submit the form it redirects to home page. I was trying to change the action to echo <code>home_url( '/search.php' );</code> but then I get a 404. </p>
<p>I have got the search.php done. The code is </p>
<pre><code> <?php if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php printf( __( 'Search Results for: %s'), '<span>' . get_search_query() . '</span>' ); ?></h1>
</header>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content'); ?>
<?php endwhile; ?>
<?php else : ?>
<p>no results</p>
<?php endif; ?>
</code></pre>
| [
{
"answer_id": 306061,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": false,
"text": "<p>I use is <a href=\"https://wordpress.org/plugins/redirection/\" rel=\"nofollow noreferrer\">free ... | 2018/06/15 | [
"https://wordpress.stackexchange.com/questions/306178",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/143333/"
] | **Update**
Case closed. I forgot I have a kill function in my functions.php with redirects attachment, search, author, daily archive pages to home. Deleted the part for search and works fine.
Sorry for that, and thank you for your time and help :)
I have a simple search form in wordpress
```
<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
<label>
<input type="search" class="search-field" placeholder="what are you looking for?" value="" name="s" title="enter search" />
</label>
<input type="submit" class="btn search-submit" value="Search" />
</form>
```
After I submit the form it redirects to home page. I was trying to change the action to echo `home_url( '/search.php' );` but then I get a 404.
I have got the search.php done. The code is
```
<?php if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php printf( __( 'Search Results for: %s'), '<span>' . get_search_query() . '</span>' ); ?></h1>
</header>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content'); ?>
<?php endwhile; ?>
<?php else : ?>
<p>no results</p>
<?php endif; ?>
``` | I use is [free redirection](https://wordpress.org/plugins/redirection/) plugin. If you are using Yoast SEO premium, redirection feature is available for you already. You can also use any other plugin if you like. The only thing you need to ensure is, it should be a 301 redirection.
For this example, I’m using Redirection plugin.
Here is the scenario:
```
Already published post with URL: https://WPSutra.com/how-to-add-google-amp-to-wordpress-to-speed-up-your-mobile-site
New URL After editing the post slug: https://WPSutra.com/Google-amp-WordPress
```
Go to Tools > Redirection (or redirection tab of any other plugin that you are using). You can also set redirection using the .htaccess method.
Here you can set the 301 redirect from old post to the new one as shown in below screenshot:
[](https://i.stack.imgur.com/HCSRR.png)
What this would do is, when someone will click on your old URL, they will be automatically redirected to new URL. This would ensure you wouldn’t lose any traffic after changing post slug of the already published post.
Do note that you would lose your social media shares number & that is a very little trade-off you need to make when dealing with editing old post URL. I usually do this for editing my old blog posts or dealing with non-performing blog posts. |
306,207 | <p>I am making an plugin, and inside my admin page (Which i add by <code>add_menu_page()</code> function) i call this function <code>pll_the_languages(["raw" => 1]))</code> but its return nothing,on client side its work fine.
I added many languages on Polylang setting page.
How can i get Polylang available languages from an admin page ?</p>
| [
{
"answer_id": 306227,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": true,
"text": "<p>According to <a href=\"https://polylang.wordpress.com/documentation/documentation-for-developers/funct... | 2018/06/15 | [
"https://wordpress.stackexchange.com/questions/306207",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145389/"
] | I am making an plugin, and inside my admin page (Which i add by `add_menu_page()` function) i call this function `pll_the_languages(["raw" => 1]))` but its return nothing,on client side its work fine.
I added many languages on Polylang setting page.
How can i get Polylang available languages from an admin page ? | According to [Polylangs Function Reference](https://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/), `pll_the_languages`
>
> Displays a language switcher.
>
>
>
And most probably it uses some additional CSS/JS to work. If you want to get the list of languages and display them with your custom code, then you can use this function instead:
```
pll_languages_list($args);
```
and it will return the list of languages.
>
> $args is an optional array parameter. Options are:
>
>
> * ‘hide\_empty’ => hides languages with no posts if set to 1 (default: 0)
> * ‘fields’ => returns only that field if set. Possible values are
> ‘slug’, ‘locale’, ‘name’, defaults to ‘slug’
>
>
> |
306,216 | <p>I'm thinking using transients to store form messages to be showed after a form was submited and the page reload.</p>
<p>My question is: if two or more user are using the same form in differents sessions, How can I get the correct transient message to the correct user?</p>
| [
{
"answer_id": 306227,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": true,
"text": "<p>According to <a href=\"https://polylang.wordpress.com/documentation/documentation-for-developers/funct... | 2018/06/15 | [
"https://wordpress.stackexchange.com/questions/306216",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145399/"
] | I'm thinking using transients to store form messages to be showed after a form was submited and the page reload.
My question is: if two or more user are using the same form in differents sessions, How can I get the correct transient message to the correct user? | According to [Polylangs Function Reference](https://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/), `pll_the_languages`
>
> Displays a language switcher.
>
>
>
And most probably it uses some additional CSS/JS to work. If you want to get the list of languages and display them with your custom code, then you can use this function instead:
```
pll_languages_list($args);
```
and it will return the list of languages.
>
> $args is an optional array parameter. Options are:
>
>
> * ‘hide\_empty’ => hides languages with no posts if set to 1 (default: 0)
> * ‘fields’ => returns only that field if set. Possible values are
> ‘slug’, ‘locale’, ‘name’, defaults to ‘slug’
>
>
> |
306,228 | <p>WooCommerce settings are located at <code>wp-admin/admin.php?page=wc-settings</code> and each of the Tabs for its settings is a continuation of the URL query string (ex: <code>wp-admin/admin.php?page=wc-settings&tab=products</code> for Products).</p>
<p>I know how to use the <code>woocommerce_settings_tabs_array</code> hook to manipulate the tab itself, but these Tabs also have sub links called "Sections."</p>
<p>For example, Products has General, Inventory, Downloadable Products and Product Vendors for me since I have a premium plugin.</p>
<p>How do I remove these sections from underneath the tab? Specifically, I want to remove the Product Vendors link that that premium extension added.</p>
| [
{
"answer_id": 306255,
"author": "user141080",
"author_id": 141080,
"author_profile": "https://wordpress.stackexchange.com/users/141080",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/mnN0h.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.i... | 2018/06/16 | [
"https://wordpress.stackexchange.com/questions/306228",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37934/"
] | WooCommerce settings are located at `wp-admin/admin.php?page=wc-settings` and each of the Tabs for its settings is a continuation of the URL query string (ex: `wp-admin/admin.php?page=wc-settings&tab=products` for Products).
I know how to use the `woocommerce_settings_tabs_array` hook to manipulate the tab itself, but these Tabs also have sub links called "Sections."
For example, Products has General, Inventory, Downloadable Products and Product Vendors for me since I have a premium plugin.
How do I remove these sections from underneath the tab? Specifically, I want to remove the Product Vendors link that that premium extension added. | [](https://i.stack.imgur.com/mnN0h.png)
To change this "sub navigation" you could use the WooCommerce filter "[woocommerce\_get\_sections\_products](https://docs.woocommerce.com/document/adding-a-section-to-a-settings-tab/)".
The following example code will remove the sub navigation point "inventory":
```
function change_navi_function($sections)
{
// remove sub navigation point "inventory"
unset($sections['inventory']);
return $sections;
}
add_filter('woocommerce_get_sections_products', 'change_navi_function');
```
[](https://i.stack.imgur.com/Z2Yme.png)
What you have to do now is either to hook your "change\_navi\_function" function after the function from the premium plugin and then remove the "Product Vendors" from the "$sections" array. Or you unhook the function from the premium plugin which use the "woocommerce\_get\_sections\_products" filter. |
306,234 | <p>This is the code:</p>
<pre><code>if ($keys = get_post_custom_keys()) {
foreach ((array) $keys as $key) {
$keyt = trim($key);
if (is_protected_meta($keyt, 'post')) {
continue;
}
$values = array_map('trim',
get_post_custom_values($key));
$value = implode($values, ', ');
echo " key : ".$key;
echo " value : ".$value;
}
}
</code></pre>
<p>The Result:</p>
<pre><code>keyyy : nova_price valueee : $9
</code></pre>
<p>My question: Is there a specific Wordpress function to get the meta value <code>$9</code> using meta key <code>nova price</code>? </p>
<p>I tried using this WP function:</p>
<pre><code>echo" get_post_meta: "; get_post_meta(the_ID(), 'nova_price', true);
</code></pre>
<p>but the result is:</p>
<pre><code>get_post_meta: 1872
</code></pre>
<p>Any help would be greatly appreciated. Many Thanks.</p>
| [
{
"answer_id": 306255,
"author": "user141080",
"author_id": 141080,
"author_profile": "https://wordpress.stackexchange.com/users/141080",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/mnN0h.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.i... | 2018/06/16 | [
"https://wordpress.stackexchange.com/questions/306234",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127706/"
] | This is the code:
```
if ($keys = get_post_custom_keys()) {
foreach ((array) $keys as $key) {
$keyt = trim($key);
if (is_protected_meta($keyt, 'post')) {
continue;
}
$values = array_map('trim',
get_post_custom_values($key));
$value = implode($values, ', ');
echo " key : ".$key;
echo " value : ".$value;
}
}
```
The Result:
```
keyyy : nova_price valueee : $9
```
My question: Is there a specific Wordpress function to get the meta value `$9` using meta key `nova price`?
I tried using this WP function:
```
echo" get_post_meta: "; get_post_meta(the_ID(), 'nova_price', true);
```
but the result is:
```
get_post_meta: 1872
```
Any help would be greatly appreciated. Many Thanks. | [](https://i.stack.imgur.com/mnN0h.png)
To change this "sub navigation" you could use the WooCommerce filter "[woocommerce\_get\_sections\_products](https://docs.woocommerce.com/document/adding-a-section-to-a-settings-tab/)".
The following example code will remove the sub navigation point "inventory":
```
function change_navi_function($sections)
{
// remove sub navigation point "inventory"
unset($sections['inventory']);
return $sections;
}
add_filter('woocommerce_get_sections_products', 'change_navi_function');
```
[](https://i.stack.imgur.com/Z2Yme.png)
What you have to do now is either to hook your "change\_navi\_function" function after the function from the premium plugin and then remove the "Product Vendors" from the "$sections" array. Or you unhook the function from the premium plugin which use the "woocommerce\_get\_sections\_products" filter. |
306,250 | <p>hi i am try this code for display featured image after first paragraph and display image title and alt attribute </p>
<pre><code>add_filter('the_content', function($content)
{
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
$img = '<img src="'.$url.'" alt="" title=""/>';
$content = preg_replace('#(<p>.*?</p>)#','$1'.$img, $content, 1);
return $content;
});
</code></pre>
<p>featured image display correctly but title and alt attribute not show, please tell me anyone whats a problem in this code</p>
| [
{
"answer_id": 306253,
"author": "mayersdesign",
"author_id": 106965,
"author_profile": "https://wordpress.stackexchange.com/users/106965",
"pm_score": 0,
"selected": false,
"text": "<p>You have nothing in the code to display those values, try:</p>\n\n<pre><code>$img = '<img src=\"'.$... | 2018/06/16 | [
"https://wordpress.stackexchange.com/questions/306250",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114504/"
] | hi i am try this code for display featured image after first paragraph and display image title and alt attribute
```
add_filter('the_content', function($content)
{
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
$img = '<img src="'.$url.'" alt="" title=""/>';
$content = preg_replace('#(<p>.*?</p>)#','$1'.$img, $content, 1);
return $content;
});
```
featured image display correctly but title and alt attribute not show, please tell me anyone whats a problem in this code | Maybe following function is what you are looking for.
The important part you are looking for in the code is the line which holds the [pathinfo](https://secure.php.net/manual/en/function.pathinfo.php),
which is php and not WordPress specific.
There are probably several other options but as nobody responded till now I think that this function will help you out till another *(maybe better)* answer is added by someone else.
>
> You could make a backup of the functions.php (found in the theme folder) before you add this function to it.
>
>
>
I have tested it in a sandbox with the WP version 4.9.6 and it should work flawless.
```
/**
* Add content on Alt/Title tags
*
* @link https://wordpress.stackexchange.com/q/306250
* @version Wordpress V4.9.6
*
* Source:
* @see https://codex.wordpress.org/Function_Reference/wp_get_attachment_url
* @see https://secure.php.net/manual/en/function.pathinfo.php
* @see https://secure.php.net/manual/en/function.preg-replace.php
*
* @param [type] $content [description]
* @return [type] [description]
*/
add_filter( 'the_content', 'add_filename_on_img_tags' );
function add_filename_on_img_tags( $content )
{
// get featured image
$url = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
// get filename
$filename = pathinfo( $arr['name'], PATHINFO_FILENAME );
// add content on ALT/TITLE tags
$img = '<img src="' . $url . '" alt="' . $filename . '" title="' . $filename . '"/>';
// add image after first paragraph
$content = preg_replace( '#(<p>.*?</p>)#','$1' . $img, $content, 1 );
return $content;
} // end function
```
In the docblock you find links with information for code as used in the function. |
306,251 | <p>I wish to replace one string in all my WP posts (over one hundred).</p>
<p>There is a "bulk edit" feature, but I do not think it covers this feature.</p>
<p>I can think of downloading the database, open it with an editor and make a replace. In a GUI editor this may fail since the file is so large. If I read up on database structure and MySQL I can probably isolate the variable containing the post texts and only edit that one. It is probably best to use a line editor like SED.</p>
<p>At present I don't use MySQL and SED daily and it will take some time to experiment with and also verify that file is OK.</p>
<p>Is there any quick way to make an edit-replace command over all my WP posts?</p>
<p>(The reason I need to do this is that the latest update of "Insert PHP" plug-in does not allow PHP written straight into the pages, which I have used.)</p>
| [
{
"answer_id": 306253,
"author": "mayersdesign",
"author_id": 106965,
"author_profile": "https://wordpress.stackexchange.com/users/106965",
"pm_score": 0,
"selected": false,
"text": "<p>You have nothing in the code to display those values, try:</p>\n\n<pre><code>$img = '<img src=\"'.$... | 2018/06/16 | [
"https://wordpress.stackexchange.com/questions/306251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144531/"
] | I wish to replace one string in all my WP posts (over one hundred).
There is a "bulk edit" feature, but I do not think it covers this feature.
I can think of downloading the database, open it with an editor and make a replace. In a GUI editor this may fail since the file is so large. If I read up on database structure and MySQL I can probably isolate the variable containing the post texts and only edit that one. It is probably best to use a line editor like SED.
At present I don't use MySQL and SED daily and it will take some time to experiment with and also verify that file is OK.
Is there any quick way to make an edit-replace command over all my WP posts?
(The reason I need to do this is that the latest update of "Insert PHP" plug-in does not allow PHP written straight into the pages, which I have used.) | Maybe following function is what you are looking for.
The important part you are looking for in the code is the line which holds the [pathinfo](https://secure.php.net/manual/en/function.pathinfo.php),
which is php and not WordPress specific.
There are probably several other options but as nobody responded till now I think that this function will help you out till another *(maybe better)* answer is added by someone else.
>
> You could make a backup of the functions.php (found in the theme folder) before you add this function to it.
>
>
>
I have tested it in a sandbox with the WP version 4.9.6 and it should work flawless.
```
/**
* Add content on Alt/Title tags
*
* @link https://wordpress.stackexchange.com/q/306250
* @version Wordpress V4.9.6
*
* Source:
* @see https://codex.wordpress.org/Function_Reference/wp_get_attachment_url
* @see https://secure.php.net/manual/en/function.pathinfo.php
* @see https://secure.php.net/manual/en/function.preg-replace.php
*
* @param [type] $content [description]
* @return [type] [description]
*/
add_filter( 'the_content', 'add_filename_on_img_tags' );
function add_filename_on_img_tags( $content )
{
// get featured image
$url = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
// get filename
$filename = pathinfo( $arr['name'], PATHINFO_FILENAME );
// add content on ALT/TITLE tags
$img = '<img src="' . $url . '" alt="' . $filename . '" title="' . $filename . '"/>';
// add image after first paragraph
$content = preg_replace( '#(<p>.*?</p>)#','$1' . $img, $content, 1 );
return $content;
} // end function
```
In the docblock you find links with information for code as used in the function. |
306,262 | <p>i tried enqueue the bootstap with functions php</p>
<pre><code>wp_enqueue_style('bootstrap4', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css');
wp_enqueue_script( 'boot1','https://code.jquery.com/jquery-3.3.1.slim.min.js');
wp_enqueue_script( 'boot2','https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js');
wp_enqueue_script( 'boot2','https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js');
</code></pre>
<p>css seems to work but none of the js files are working..not sure what i am doing wrong..</p>
<p>please help thank</p>
| [
{
"answer_id": 306263,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>function abc_load_my_scripts() {\n wp_enqueue_script( 'boot1','https://code.jquery... | 2018/06/16 | [
"https://wordpress.stackexchange.com/questions/306262",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | i tried enqueue the bootstap with functions php
```
wp_enqueue_style('bootstrap4', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css');
wp_enqueue_script( 'boot1','https://code.jquery.com/jquery-3.3.1.slim.min.js');
wp_enqueue_script( 'boot2','https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js');
wp_enqueue_script( 'boot2','https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js');
```
css seems to work but none of the js files are working..not sure what i am doing wrong..
please help thank | You can use action hook and enqueue script and style to the site.
```
function my_scripts() {
wp_enqueue_style('bootstrap4', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css');
wp_enqueue_script( 'boot1','https://code.jquery.com/jquery-3.3.1.slim.min.js', array( 'jquery' ),'',true );
wp_enqueue_script( 'boot2','https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js', array( 'jquery' ),'',true );
wp_enqueue_script( 'boot3','https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js', array( 'jquery' ),'',true );
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
```
If you want to add the scripts after jQuery then you can use the jQuery array for dependent and last argument true will include the JS at footer, if you want the js in header, you can remove that. |
306,315 | <p>I am trying to get the billing email of an order in woocommerce v2.5.5
However its giving me this error: </p>
<pre><code>Call to undefined method WC_Order::get_billing_email()
</code></pre>
<p>Here is my order object : print_r($order)</p>
<p><a href="https://i.stack.imgur.com/X3oGL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X3oGL.png" alt="enter image description here"></a></p>
<p>My Code</p>
<pre><code> $order_id = $order->get_order_number();
$customer_email = $order->get_billing_email();
$shipping_country = $order->get_shipping_country();
$order_items = $order->get_items();
</code></pre>
<p>Both get_billing_email and get_shipping_country isn't working.</p>
<p>Condition : I can't upgrade the plugin as the site is really old and i'm 100% sure it'll cost me another 50 to 60 hours to fix everything. Just need a quick fix. </p>
| [
{
"answer_id": 306316,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 3,
"selected": true,
"text": "<p>In WC version 2.5, <code>get</code> and <code>set</code> functions are not available.\nThe paramete... | 2018/06/18 | [
"https://wordpress.stackexchange.com/questions/306315",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45790/"
] | I am trying to get the billing email of an order in woocommerce v2.5.5
However its giving me this error:
```
Call to undefined method WC_Order::get_billing_email()
```
Here is my order object : print\_r($order)
[](https://i.stack.imgur.com/X3oGL.png)
My Code
```
$order_id = $order->get_order_number();
$customer_email = $order->get_billing_email();
$shipping_country = $order->get_shipping_country();
$order_items = $order->get_items();
```
Both get\_billing\_email and get\_shipping\_country isn't working.
Condition : I can't upgrade the plugin as the site is really old and i'm 100% sure it'll cost me another 50 to 60 hours to fix everything. Just need a quick fix. | In WC version 2.5, `get` and `set` functions are not available.
The parameters you want are public. So, you can directly access them:
```
$customer_email = $order->billing_email;
$shipping_country = $order->shipping_country;
```
And so on.
Please check the keys before using them. |
306,346 | <p>I've created a Text widget and put font-awesome icon HTML in editor Text Mode <code><i class="fab fa-facebook"></i></code> but toggling to Visual mode makes the code disappears though I can see it working on Frontend.</p>
| [
{
"answer_id": 306349,
"author": "Harsh",
"author_id": 131853,
"author_profile": "https://wordpress.stackexchange.com/users/131853",
"pm_score": 0,
"selected": false,
"text": "<p>You have used the wrong syntax. </p>\n\n<p>True syntax is <code><i class=\"fa fa-facebook\"></i><... | 2018/06/18 | [
"https://wordpress.stackexchange.com/questions/306346",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142283/"
] | I've created a Text widget and put font-awesome icon HTML in editor Text Mode `<i class="fab fa-facebook"></i>` but toggling to Visual mode makes the code disappears though I can see it working on Frontend. | I think the issue is that WordPress removes empty tags from the editor. Try adding in a non-breaking space - Font Awesome should remove it so you shouldn't see any noticeable difference:
```
<i class="fab fa-facebook"> </i>
``` |
306,432 | <p>I'm looking to edit a custom post type's menu link in the WordPress admin - Is this possible?</p>
<p>For example, currently its</p>
<p><code>/wp-admin/edit.php?post_type=application</code></p>
<p>and I want to update this with</p>
<p><code>/wp-admin/edit.php?s&post_status=all&post_type=application&cat=36&paged=1</code></p>
<p>Thank you for your time</p>
| [
{
"answer_id": 306437,
"author": "Elex",
"author_id": 113687,
"author_profile": "https://wordpress.stackexchange.com/users/113687",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <code>admin_menu</code> hook. You will be able to loop over all menus. </p>\n\n<pre><code>add_... | 2018/06/19 | [
"https://wordpress.stackexchange.com/questions/306432",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145497/"
] | I'm looking to edit a custom post type's menu link in the WordPress admin - Is this possible?
For example, currently its
`/wp-admin/edit.php?post_type=application`
and I want to update this with
`/wp-admin/edit.php?s&post_status=all&post_type=application&cat=36&paged=1`
Thank you for your time | You can use the `admin_menu` hook. You will be able to loop over all menus.
```
add_action( 'admin_menu', 'wpse_306432_edit_post_type_admin_menu', 11);
function wpse_306432_edit_post_type_admin_menu()
{
global $menu;
foreach($menu as $k => $v){
if($v[1] == 'edit_applications') // possibly 'edit_application', I'm not sure
{
$menu[$k][2] = 'edit.php?post_status=all&post_type=application&cat=36&paged=1'; // I modify your query
break;
}
}
}
```
Should work for you :)
Don't hesitate to add a nice :
```
echo '<pre>';
var_dump($menu);
echo '</pre>';
die();
```
After `global $menu` to understand how it works, and change more ! |
306,433 | <p>First sorry for my bad english, i'm french.
I need to make my website GDPR Friendly, so for this I use the plugin 'RGPD' who give me the possibility to check or uncheck multiples types of cookies. This plugin also give some functions to use.</p>
<p>Here is what I try :</p>
<pre><code> if (!is_allowed_cookie('_ga')) {
?>
<script>
function deleteCookie(name) {
document.cookie = name + '=; Path=/; Domain=.youtube.com; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
var arr = ["GPS","APISID","CONSENT","HSID","LOGIN_INFO","PREF","SAPISID","SSID","VISITOR_INFO1_LIVE","YSC"];
var i = 0;
for ( i=0; i< arr.length; i++){
deleteCookie(arr[i],false,-1);
}
</script>
<?php
}
</code></pre>
<p>But no one of the cookies are deleted, or maybe they are, but they came back instantly after.
I also try this method in PHP :</p>
<pre><code> foreach($_COOKIE as $key => $value) {
unset($_COOKIE[$key]);
}
</code></pre>
<p>but nothing too, no one of the cookies was deleted.</p>
<p>So how can I do to delete a cookie ?</p>
<p>Thanks.</p>
| [
{
"answer_id": 306437,
"author": "Elex",
"author_id": 113687,
"author_profile": "https://wordpress.stackexchange.com/users/113687",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <code>admin_menu</code> hook. You will be able to loop over all menus. </p>\n\n<pre><code>add_... | 2018/06/19 | [
"https://wordpress.stackexchange.com/questions/306433",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145309/"
] | First sorry for my bad english, i'm french.
I need to make my website GDPR Friendly, so for this I use the plugin 'RGPD' who give me the possibility to check or uncheck multiples types of cookies. This plugin also give some functions to use.
Here is what I try :
```
if (!is_allowed_cookie('_ga')) {
?>
<script>
function deleteCookie(name) {
document.cookie = name + '=; Path=/; Domain=.youtube.com; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
var arr = ["GPS","APISID","CONSENT","HSID","LOGIN_INFO","PREF","SAPISID","SSID","VISITOR_INFO1_LIVE","YSC"];
var i = 0;
for ( i=0; i< arr.length; i++){
deleteCookie(arr[i],false,-1);
}
</script>
<?php
}
```
But no one of the cookies are deleted, or maybe they are, but they came back instantly after.
I also try this method in PHP :
```
foreach($_COOKIE as $key => $value) {
unset($_COOKIE[$key]);
}
```
but nothing too, no one of the cookies was deleted.
So how can I do to delete a cookie ?
Thanks. | You can use the `admin_menu` hook. You will be able to loop over all menus.
```
add_action( 'admin_menu', 'wpse_306432_edit_post_type_admin_menu', 11);
function wpse_306432_edit_post_type_admin_menu()
{
global $menu;
foreach($menu as $k => $v){
if($v[1] == 'edit_applications') // possibly 'edit_application', I'm not sure
{
$menu[$k][2] = 'edit.php?post_status=all&post_type=application&cat=36&paged=1'; // I modify your query
break;
}
}
}
```
Should work for you :)
Don't hesitate to add a nice :
```
echo '<pre>';
var_dump($menu);
echo '</pre>';
die();
```
After `global $menu` to understand how it works, and change more ! |
306,445 | <p>I am trying to create a custom rewrite rule for a custom post type where</p>
<p><strong>This:</strong></p>
<pre><code>http://test.loc/products/directory/?c=some-value
</code></pre>
<p>Should become <strong>this</strong>:</p>
<pre><code>http://test.loc/products/directory/some-value
</code></pre>
<p><strong>Minimal code:</strong></p>
<pre><code>function create_post_type() {
register_post_type( 'acme_product',
array(
'labels' => array(
'name' => __( 'Products' ),
'singular_name' => __( 'Product' )
),
'show_ui' => false,
'public' => true,
'has_archive' => true,
'rewrite' => array("slug" => "products/directory")
)
);
add_rewrite_rule(
'^products/directory/([A-Za-z0-9-]+)/?$',
'index.php?post_type=acme_product&c=$1',
'top'
);
}
</code></pre>
<p>I also tried like this:</p>
<pre><code>add_rewrite_rule(
'^products/directory/?([^/]*)/?',
'index.php?post_type=acme_product&c=$matches[1]',
'top'
);
</code></pre>
<p>I simply can't get the value of <strong>'c'</strong>. Is there something in the rewrite rule that should be different? I can't seem to get this to work.</p>
<p>By the way I CAN retrieve 'some-value' of 'c' from this:</p>
<pre><code> http://test.loc/index.php?post_type=acme_product&c=some-value
</code></pre>
<p>To retrieve the value in the template I tried both:</p>
<pre><code>get_query_var( 'c' );
</code></pre>
<p>and</p>
<pre><code>$_GET['c'];
</code></pre>
<p>I get nothing back...</p>
| [
{
"answer_id": 306453,
"author": "GRowing",
"author_id": 81897,
"author_profile": "https://wordpress.stackexchange.com/users/81897",
"pm_score": 2,
"selected": false,
"text": "<p><strong>SOLUTION:</strong></p>\n\n<p>I am answering my own question here since no responses were given and I ... | 2018/06/19 | [
"https://wordpress.stackexchange.com/questions/306445",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81897/"
] | I am trying to create a custom rewrite rule for a custom post type where
**This:**
```
http://test.loc/products/directory/?c=some-value
```
Should become **this**:
```
http://test.loc/products/directory/some-value
```
**Minimal code:**
```
function create_post_type() {
register_post_type( 'acme_product',
array(
'labels' => array(
'name' => __( 'Products' ),
'singular_name' => __( 'Product' )
),
'show_ui' => false,
'public' => true,
'has_archive' => true,
'rewrite' => array("slug" => "products/directory")
)
);
add_rewrite_rule(
'^products/directory/([A-Za-z0-9-]+)/?$',
'index.php?post_type=acme_product&c=$1',
'top'
);
}
```
I also tried like this:
```
add_rewrite_rule(
'^products/directory/?([^/]*)/?',
'index.php?post_type=acme_product&c=$matches[1]',
'top'
);
```
I simply can't get the value of **'c'**. Is there something in the rewrite rule that should be different? I can't seem to get this to work.
By the way I CAN retrieve 'some-value' of 'c' from this:
```
http://test.loc/index.php?post_type=acme_product&c=some-value
```
To retrieve the value in the template I tried both:
```
get_query_var( 'c' );
```
and
```
$_GET['c'];
```
I get nothing back... | **SOLUTION:**
I am answering my own question here since no responses were given and I presume this might be helpful to someone and in the mean while I found a solution..
I had to use the second version of 'add\_rewrite\_rule':
```
add_rewrite_rule(
'^products/directory/?([^/]*)/?',
'index.php?post_type=acme_product&c=$matches[1]',
'top'
);
```
I needed to register a query var,, since external query params aren't recognizable to WordPress
```
function 123wp_query_vars( $query_vars ){
$query_vars[] = 'c';
return $query_vars;
}
add_filter( 'query_vars', '123wp_query_vars' );
```
Then retrieve the value in the template using:
```
get_query_var( 'c' );
``` |
306,447 | <p>I hate it, when plugins add their own settings like this:
<a href="https://i.stack.imgur.com/1gh4c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1gh4c.png" alt="WordPress admin 1"></a></p>
<p>It's cluttered and annoying. Can I somehow move them in under 'Settings':</p>
<p><a href="https://i.stack.imgur.com/4hpju.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4hpju.png" alt="WordPress admin 2"></a></p>
<p>I imagined something like, checking if there is a plugin by the given name; and if there is, then remove it from the admin bar, like this (however, this doesn't work):</p>
<pre><code>function custom_menu_page_removing() {
// Neither of these two work (the first is the
// link, the second is the slug
remove_menu_page( 'admin.php?page=themepacific_jp_gallery' );
remove_menu_page( 'tiled-gallery-carousel-without-jetpack' );
}
add_action( 'admin_menu', 'custom_menu_page_removing' );
</code></pre>
<p>I then imagined adding a link to generel settings like this:</p>
<pre><code>function example_admin_menu() {
global $submenu;
$url = home_url() . '/wp-admin/admin.php?page=wpseo_dashboard';
$submenu['options-general.php'][] = array('Yoast', 'manage_options', $url);
}
add_action('admin_menu', 'example_admin_menu');
</code></pre>
<p>But my two problems are these:</p>
<ul>
<li>I can't find the correct <code>remove_menu_page( 'URL' );</code> to remove either Yoast or TP Tiled Gallery. How do I do that? </li>
<li>If I remove the Yoast, - what will then happen to the sub-menu? How do I access that:</li>
</ul>
<p><a href="https://i.stack.imgur.com/4HUCp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4HUCp.png" alt="Yoast sub menu"></a></p>
| [
{
"answer_id": 347000,
"author": "BigG",
"author_id": 174927,
"author_profile": "https://wordpress.stackexchange.com/users/174927",
"pm_score": 0,
"selected": false,
"text": "<p>For Yoast, you can easily hide it, the settings are also in the WP topbar. :)</p>\n\n<p>To hide it, use this c... | 2018/06/19 | [
"https://wordpress.stackexchange.com/questions/306447",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128304/"
] | I hate it, when plugins add their own settings like this:
[](https://i.stack.imgur.com/1gh4c.png)
It's cluttered and annoying. Can I somehow move them in under 'Settings':
[](https://i.stack.imgur.com/4hpju.png)
I imagined something like, checking if there is a plugin by the given name; and if there is, then remove it from the admin bar, like this (however, this doesn't work):
```
function custom_menu_page_removing() {
// Neither of these two work (the first is the
// link, the second is the slug
remove_menu_page( 'admin.php?page=themepacific_jp_gallery' );
remove_menu_page( 'tiled-gallery-carousel-without-jetpack' );
}
add_action( 'admin_menu', 'custom_menu_page_removing' );
```
I then imagined adding a link to generel settings like this:
```
function example_admin_menu() {
global $submenu;
$url = home_url() . '/wp-admin/admin.php?page=wpseo_dashboard';
$submenu['options-general.php'][] = array('Yoast', 'manage_options', $url);
}
add_action('admin_menu', 'example_admin_menu');
```
But my two problems are these:
* I can't find the correct `remove_menu_page( 'URL' );` to remove either Yoast or TP Tiled Gallery. How do I do that?
* If I remove the Yoast, - what will then happen to the sub-menu? How do I access that:
[](https://i.stack.imgur.com/4HUCp.png) | You seem to be making life complicated. Here's the code you need;
```
function menu_shuffle() {
remove_menu_page( 'plugin-page' );
add_submenu_page('options-general.php','Page Title', 'Menu Label','manage_options', 'plugin-page' );
};
add_action( 'admin_menu', 'menu_shuffle' );
```
`plugin-page` can be found by mousing over the existing menu label and getting the part after the `?page=`in this case `?page=plugin-page`
The Wordpress function definition for `add_submenu_page()` <https://developer.wordpress.org/reference/functions/add_submenu_page/> includes a list of all the menu page slugs (and you need the '.php').
so in the example above for Yoast (bless its pointy little head and use Hide SEO Bloat)
```
function menu_shuffle() {
remove_menu_page( 'wpseo_dashboard' );
add_submenu_page('options-general.php','Yoast SE0', 'SEO','manage_options', 'wpseo_dashboard' );
};
add_action( 'admin_menu', 'menu_shuffle' );
``` |
306,458 | <p>I have a form that is on the front end of my site. I'm trying to remove the "Remember me" checkbox but can't get this to work. Here is my form code. </p>
<pre><code><?php
$args = array(
'echo' => true,
'remember' => true,
'redirect' => ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
'form_id' => 'loginform',
'id_username' => 'user_login',
'id_password' => 'user_pass',
'id_remember' => 'rememberme',
'id_submit' => 'wp-submit',
'label_username' => __( 'Username' ),
'label_password' => __( 'Password' ),
'label_remember' => __( 'Remember Me' ),
'label_log_in' => __( 'Log In' ),
'value_username' => '',
'value_remember' => false
);
wp_login_form( $args );
?>
</code></pre>
<p>I have tried this code, but I think this would be for the wp-admin form (and it doesn't work on my form. </p>
<pre><code>add_action('login_head', 'do_not_remember_me');
function do_not_remember_me()
{
echo '<style type="text/css">.forgetmenot { display:none; }</style>';
}
</code></pre>
<p>Any ideas on how to do this properly?</p>
| [
{
"answer_id": 306459,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Look at your generated page code (or use the Inspect Element) to see what CSS class is assigned to the... | 2018/06/19 | [
"https://wordpress.stackexchange.com/questions/306458",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145165/"
] | I have a form that is on the front end of my site. I'm trying to remove the "Remember me" checkbox but can't get this to work. Here is my form code.
```
<?php
$args = array(
'echo' => true,
'remember' => true,
'redirect' => ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
'form_id' => 'loginform',
'id_username' => 'user_login',
'id_password' => 'user_pass',
'id_remember' => 'rememberme',
'id_submit' => 'wp-submit',
'label_username' => __( 'Username' ),
'label_password' => __( 'Password' ),
'label_remember' => __( 'Remember Me' ),
'label_log_in' => __( 'Log In' ),
'value_username' => '',
'value_remember' => false
);
wp_login_form( $args );
?>
```
I have tried this code, but I think this would be for the wp-admin form (and it doesn't work on my form.
```
add_action('login_head', 'do_not_remember_me');
function do_not_remember_me()
{
echo '<style type="text/css">.forgetmenot { display:none; }</style>';
}
```
Any ideas on how to do this properly? | There is a `remember` argument for `wp_login_form()`. Just set it to false:
```
$args = array(
'remember' => false,
);
wp_login_form( $args );
``` |
306,463 | <p>I need help accessing a specific term from a custom taxonomy.</p>
<p>I am getting the terms with</p>
<pre><code> $terms = wp_get_post_terms($post->ID, 'mytax', array("fields" => "all"));
</code></pre>
<p>If I <code>print_r($terms)</code> this is what I get:</p>
<pre><code>Array (
[0] => WP_Term Object (
[term_id] => 30
[name] => Term1
[slug] => term1
[term_group] => 0
[term_taxonomy_id] => 30
[taxonomy] => mytax
[description] =>
[parent] => 0
[count] => 78
[filter] => raw
)
[1] => WP_Term Object (
[term_id] => 32
[name] => Term2
[slug] => term2
[term_group] => 0
[term_taxonomy_id] => 32
[taxonomy] => mytax
[description] =>
[parent] => 30
[count] => 44
[filter] => raw
)
)
</code></pre>
<p>How do I extract the ID for Term1 out of this array? </p>
| [
{
"answer_id": 306459,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Look at your generated page code (or use the Inspect Element) to see what CSS class is assigned to the... | 2018/06/19 | [
"https://wordpress.stackexchange.com/questions/306463",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145115/"
] | I need help accessing a specific term from a custom taxonomy.
I am getting the terms with
```
$terms = wp_get_post_terms($post->ID, 'mytax', array("fields" => "all"));
```
If I `print_r($terms)` this is what I get:
```
Array (
[0] => WP_Term Object (
[term_id] => 30
[name] => Term1
[slug] => term1
[term_group] => 0
[term_taxonomy_id] => 30
[taxonomy] => mytax
[description] =>
[parent] => 0
[count] => 78
[filter] => raw
)
[1] => WP_Term Object (
[term_id] => 32
[name] => Term2
[slug] => term2
[term_group] => 0
[term_taxonomy_id] => 32
[taxonomy] => mytax
[description] =>
[parent] => 30
[count] => 44
[filter] => raw
)
)
```
How do I extract the ID for Term1 out of this array? | There is a `remember` argument for `wp_login_form()`. Just set it to false:
```
$args = array(
'remember' => false,
);
wp_login_form( $args );
``` |
306,500 | <p>im trying to redirect users on specific categry with this hook:</p>
<pre><code>// Show app-data posts only to app users
function user_redirect()
{
if ( is_category( 'app-data' ) ) {
$url = site_url();
wp_redirect( $url );
exit();
}
}
add_action( 'the_post', 'user_redirect' );
</code></pre>
<p>But its not working and i dont know why. it redirect if the user if browsing the category. i want to redirect if the user is browsing the category or a post of that category</p>
| [
{
"answer_id": 306502,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 2,
"selected": false,
"text": "<p>change your hook name <strong>the_post</strong> to <strong>template_redirect</strong></p>\n\n<pre><co... | 2018/06/20 | [
"https://wordpress.stackexchange.com/questions/306500",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51191/"
] | im trying to redirect users on specific categry with this hook:
```
// Show app-data posts only to app users
function user_redirect()
{
if ( is_category( 'app-data' ) ) {
$url = site_url();
wp_redirect( $url );
exit();
}
}
add_action( 'the_post', 'user_redirect' );
```
But its not working and i dont know why. it redirect if the user if browsing the category. i want to redirect if the user is browsing the category or a post of that category | Why it's not working?
---------------------
There is one major problem with your code... You can't redirect after any html content was already sent... Such redirect will be ignored...
So why is your code incorrect? Because of `the_post` hook. This hook is fired up when the object of post is set up. So usually it's in the loop, which is much too late to do redirects...
So how to fix your code?
------------------------
Use another hook.
Here is the [list of available hooks fired up during typical request](https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request).
One of the best hooks for doing redirects ([and commonly used for that](https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect#Performing_a_redirect)) is `template_redirect`. As you can see it's fired up just before getting header, so everything is already set up.
```
function redirect_not_app_users_if_app_data_category() {
if ( (is_category( 'app-data' ) || in_category('app-data'))&& ! is_user_logged_in() ) {
wp_redirect( home_url() );
die;
}
}
add_action( 'template_redirect', 'redirect_not_app_users_if_app_data_category');
``` |
306,513 | <p>I have two product category </p>
<ol>
<li>MULTILINGUAL DIGITAL MARKETING (ID 75)</li>
<li>INTERNATIONAL SALES CHANNELS (ID 107)</li>
</ol>
<p>I want to run some code via if condition for these two category only.</p>
<p>I tried using this code but it didn't worked</p>
<pre><code>if( is_product_category(107 || 75) ) {
$term = get_queried_object();
$parent = $term->parent;
if (!empty($parent)) {
$child_of = $parent;
} else {
$child_of = $term->term_id;
}
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'child_of' => $child_of,
) );
if ($terms) {
foreach ( $terms as $category ) {
$category_id = $category->term_id;
$category_slug = $category->slug;
$category_name = $category->name;
$category_desc = $category->description;
echo '<div class="'.$category_slug.'">';
echo '<h2>'.$category_name.'</h2>';
if ($category_desc) {
echo '<p>'.$category_desc.'</p>';
}
$products_args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category_id,
),
),
);
$products = new WP_Query( $products_args );
if ( $products->have_posts() ) { // only start if we hace some products
// START some normal woocommerce loop
woocommerce_product_loop_start();
if ( wc_get_loop_prop( 'total' ) ) {
while ( $products->have_posts() ) : $products->the_post();
/**
* Hook: woocommerce_shop_loop.
*
* @hooked WC_Structured_Data::generate_product_data() - 10
*/
do_action( 'woocommerce_shop_loop' );
wc_get_template_part( 'content', 'product' );
endwhile; // end of the loop.
}
woocommerce_product_loop_end();
// END the normal woocommerce loop
// Restore original post data, maybe not needed here (in a plugin it might be necessary)
wp_reset_postdata();
}
</code></pre>
| [
{
"answer_id": 306515,
"author": "Bogdan Dragomir",
"author_id": 145601,
"author_profile": "https://wordpress.stackexchange.com/users/145601",
"pm_score": 1,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>if( is_product_category( 'category1-slug' ) || is_product_category( 'categor... | 2018/06/20 | [
"https://wordpress.stackexchange.com/questions/306513",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145599/"
] | I have two product category
1. MULTILINGUAL DIGITAL MARKETING (ID 75)
2. INTERNATIONAL SALES CHANNELS (ID 107)
I want to run some code via if condition for these two category only.
I tried using this code but it didn't worked
```
if( is_product_category(107 || 75) ) {
$term = get_queried_object();
$parent = $term->parent;
if (!empty($parent)) {
$child_of = $parent;
} else {
$child_of = $term->term_id;
}
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'child_of' => $child_of,
) );
if ($terms) {
foreach ( $terms as $category ) {
$category_id = $category->term_id;
$category_slug = $category->slug;
$category_name = $category->name;
$category_desc = $category->description;
echo '<div class="'.$category_slug.'">';
echo '<h2>'.$category_name.'</h2>';
if ($category_desc) {
echo '<p>'.$category_desc.'</p>';
}
$products_args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category_id,
),
),
);
$products = new WP_Query( $products_args );
if ( $products->have_posts() ) { // only start if we hace some products
// START some normal woocommerce loop
woocommerce_product_loop_start();
if ( wc_get_loop_prop( 'total' ) ) {
while ( $products->have_posts() ) : $products->the_post();
/**
* Hook: woocommerce_shop_loop.
*
* @hooked WC_Structured_Data::generate_product_data() - 10
*/
do_action( 'woocommerce_shop_loop' );
wc_get_template_part( 'content', 'product' );
endwhile; // end of the loop.
}
woocommerce_product_loop_end();
// END the normal woocommerce loop
// Restore original post data, maybe not needed here (in a plugin it might be necessary)
wp_reset_postdata();
}
``` | `is_product_category()` is to be used on woocommerce category archive pages only so first make sure that you are on category archive.
instead of category number use category slug name `is_product_category('category-slug')`
no need to run OR(||) condition just use `is_product_category('category-slug1','category-slug2')` to get same output |
306,542 | <p>How would one go about creating a gallery page which is a gallery of galleries - using a specific photo from the subgallery as a cover for the album? </p>
<p>This is what I have so far.</p>
<p>I have a folder on the backend built using WP Media Folder called <code>master</code>. I want the galleries page to list a thumbnail for each folder inside of <code>master</code> and a name of the gallery the thumbnail belongs to. </p>
<p>Here is what I have.</p>
<pre><code>$galleries = get_terms( 'wpmf-gallery-category', [ 'hide_empty' => 0 ]);
foreach ( $galleries as $gal )
{
if ( $gal->name != 'master' )
{
?>
<div id="gallery-id-<? $gal->ID ?>" class="cell medium-3 margin-x text-center" style="border: solid black; ">
<figure class="cell">
<img src="<?= // Get sub-gallery thumbnail ?>" alt="<?= $gal->name?>">
</figure>
<div class="detail">
<span>
<?= $gal->name ?>
</span>
</div>
</div>
<?
}
}
</code></pre>
<p>I guess the question is, how do I access the images by the folder they are in? I don't see how WP Media Folder links to the images. I need to be able to query and get the image srcs from the gallery element id.</p>
| [
{
"answer_id": 306648,
"author": "Dan",
"author_id": 145214,
"author_profile": "https://wordpress.stackexchange.com/users/145214",
"pm_score": 1,
"selected": false,
"text": "<p>I created a custom function for this, but if you want the root folder id, you can use the <code>wp cli</code> a... | 2018/06/20 | [
"https://wordpress.stackexchange.com/questions/306542",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145214/"
] | How would one go about creating a gallery page which is a gallery of galleries - using a specific photo from the subgallery as a cover for the album?
This is what I have so far.
I have a folder on the backend built using WP Media Folder called `master`. I want the galleries page to list a thumbnail for each folder inside of `master` and a name of the gallery the thumbnail belongs to.
Here is what I have.
```
$galleries = get_terms( 'wpmf-gallery-category', [ 'hide_empty' => 0 ]);
foreach ( $galleries as $gal )
{
if ( $gal->name != 'master' )
{
?>
<div id="gallery-id-<? $gal->ID ?>" class="cell medium-3 margin-x text-center" style="border: solid black; ">
<figure class="cell">
<img src="<?= // Get sub-gallery thumbnail ?>" alt="<?= $gal->name?>">
</figure>
<div class="detail">
<span>
<?= $gal->name ?>
</span>
</div>
</div>
<?
}
}
```
I guess the question is, how do I access the images by the folder they are in? I don't see how WP Media Folder links to the images. I need to be able to query and get the image srcs from the gallery element id. | I created a custom function for this, but if you want the root folder id, you can use the `wp cli` and use the command `wp term list wpmf-gallery-category` to show all the gallery folders. Get the term id of the one you want to use as the root and set it to $master\_id
```
/*
get_root_gallery_id();
Custom function that returns the id of folder with parent id == 0
*/
$master_id = get_root_gallery_id( 'master' );
$galleries = get_terms( 'wpmf-gallery-category', [ 'hide_empty' => 0 ]);
// If there is a root folder
if ( $master_id )
{
foreach ( $galleries as $gal )
{
if ( $gal->parent == $master_id )
{
$args = [
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_status' => 'inherit'
'tax_query' => [
[
'taxonomy' => 'wpmf-gallery-category',
'terms' => [ $gal->term_id ],
'field' => 'term_id'
]
]
];
$query = new WP_Query( $args );
if ( $query->have_posts() )
{
while ( $query->have_posts() )
{
$query->the_post();
global $post; // Image as Post Object
}
}
}
}
}
``` |
306,572 | <p>I'd like to customise the recipient of a new order in WooCommerce. According to the documentation and various examples I can do this like so:</p>
<pre><code>function wc_change_admin_new_order_email_recipient( $recipient, $order ) {
global $woocommerce;
//some code
return $recipient;
}
add_filter('woocommerce_email_recipient_new_order', 'wc_change_admin_new_order_email_recipient', 10, 2);
</code></pre>
<p>However I cannot get this filter to trigger on my local development machine, nor can I get the site to send order emails even with this code removed.</p>
<p>I have a working local debugger and the code stops at various points in the wc_email class, however it only gets to the get_recipient function when I change the admin email in the backend.</p>
<p>Here is what I have tried:</p>
<ul>
<li>turned all other plugins off</li>
<li>made sure Wordpress, WooCommerce, Theme is up to date</li>
<li>Some theme files are shown as not up to date, but admin-new-order.php does not show in this list</li>
<li>admin-new-order.php in overrides folder is identical to WooCommerce version, so I have also tried to remove the override completely</li>
<li>Lost password sends me an email on my local system (over the Internet), so email delivery is working</li>
</ul>
<p>Is there a cron job used for delivery of the admin new order email, if so how can I trigger it?</p>
<p>Any other ideas?</p>
| [
{
"answer_id": 311960,
"author": "Gabrielizalo",
"author_id": 70221,
"author_profile": "https://wordpress.stackexchange.com/users/70221",
"pm_score": 2,
"selected": false,
"text": "<p>If you use <strong>W3 Total Cache</strong> verify this solution: <a href=\"https://web.archive.org/web/2... | 2018/06/20 | [
"https://wordpress.stackexchange.com/questions/306572",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80887/"
] | I'd like to customise the recipient of a new order in WooCommerce. According to the documentation and various examples I can do this like so:
```
function wc_change_admin_new_order_email_recipient( $recipient, $order ) {
global $woocommerce;
//some code
return $recipient;
}
add_filter('woocommerce_email_recipient_new_order', 'wc_change_admin_new_order_email_recipient', 10, 2);
```
However I cannot get this filter to trigger on my local development machine, nor can I get the site to send order emails even with this code removed.
I have a working local debugger and the code stops at various points in the wc\_email class, however it only gets to the get\_recipient function when I change the admin email in the backend.
Here is what I have tried:
* turned all other plugins off
* made sure Wordpress, WooCommerce, Theme is up to date
* Some theme files are shown as not up to date, but admin-new-order.php does not show in this list
* admin-new-order.php in overrides folder is identical to WooCommerce version, so I have also tried to remove the override completely
* Lost password sends me an email on my local system (over the Internet), so email delivery is working
Is there a cron job used for delivery of the admin new order email, if so how can I trigger it?
Any other ideas? | If you use **W3 Total Cache** verify this solution: [WordPress Failed to Set Referrer Policy Response Headers – W3 Total Cache](https://web.archive.org/web/20180827171724/https://623lafayette.com/2018/05/02/wordpress-failed-to-set-referrer-policy/) |
306,604 | <p>I want to apply some <code>javascript</code> to my <code>header</code> and want to know what the best way to implement it is.</p>
<p>here is the source that contains the javascript I'm including - <a href="https://codepen.io/kaemak/pen/mHyKa/" rel="noreferrer">https://codepen.io/kaemak/pen/mHyKa/</a></p>
<p>Should I create a new <code>javascript</code> file then add it to the <code>child theme</code>, if so then I'm unsure of what to call the file and will it apply to the head from this location?</p>
| [
{
"answer_id": 306628,
"author": "Swati",
"author_id": 123547,
"author_profile": "https://wordpress.stackexchange.com/users/123547",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, create a new JavaScript file and just call it wherever you want, I would suggest to call it under foote... | 2018/06/21 | [
"https://wordpress.stackexchange.com/questions/306604",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145660/"
] | I want to apply some `javascript` to my `header` and want to know what the best way to implement it is.
here is the source that contains the javascript I'm including - <https://codepen.io/kaemak/pen/mHyKa/>
Should I create a new `javascript` file then add it to the `child theme`, if so then I'm unsure of what to call the file and will it apply to the head from this location? | You should enqueue the script in child theme's functions.php.
for example if name of the js file is custom.js and if you place it under js folder in your child theme, then in functions.php you should add
```
function my_custom_scripts() {
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array( 'jquery' ),'',true );
}
add_action( 'wp_enqueue_scripts', 'my_custom_scripts' );
```
Here `get_stylesheet_directory_uri()` will return the directory of your child theme, then `array( 'jquery' )` would make your js load after jquery, if your script requires js then you should use this else you can remove or you can add the dependent script here, then the last parameter true, is to make your js load at the footer. |
306,642 | <p>I am trying to customize the notification email sent to user that contains the link to set password.</p>
<p>Currently, I have set up a custom user registration and login forms at the urls <code>site.com/register</code> and <code>site.com/login</code> respectively.</p>
<p>After the registration, wordpress is sending email with following link that asks to set a password.</p>
<p><code>site.com/wp-login.php?action=rp&key=XYieERXh3QinbU4VquB2&login=user%40gmail.com</code></p>
<p>I want it replace this url to</p>
<p><code>site.com/login?action=rp&key=XYieERXh3QinbU4VquB2&login=user%40gmail.com</code></p>
<p>I have tried the following code in <code>functions.php</code></p>
<pre><code>add_filter( 'wp_new_user_notification_email', 'my_wp_new_user_notification_email', 10, 3 );
function my_wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname ) {
$message = sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n";
$message .= __('Hello To set your password, visit the following address:') . "\r\n\r\n";
$message .= '<' . network_site_url("login/?key=$key&login=" . rawurlencode($user->user_login), 'login') . ">\r\n\r\n";
$wp_new_user_notification_email['message'] = $message
return $wp_new_user_notification_email;
}
</code></pre>
<p>I think I am missing <code>$key</code> information since the email received has the link like this:</p>
<p><code>site.com/login?action=rp&key=&login=user%40test.com</code></p>
<p>How to fix this?</p>
| [
{
"answer_id": 306730,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 1,
"selected": false,
"text": "<p>You need to be able to assign the generated key to your variable <code>$key</code>, which is curr... | 2018/06/21 | [
"https://wordpress.stackexchange.com/questions/306642",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66151/"
] | I am trying to customize the notification email sent to user that contains the link to set password.
Currently, I have set up a custom user registration and login forms at the urls `site.com/register` and `site.com/login` respectively.
After the registration, wordpress is sending email with following link that asks to set a password.
`site.com/wp-login.php?action=rp&key=XYieERXh3QinbU4VquB2&login=user%40gmail.com`
I want it replace this url to
`site.com/login?action=rp&key=XYieERXh3QinbU4VquB2&login=user%40gmail.com`
I have tried the following code in `functions.php`
```
add_filter( 'wp_new_user_notification_email', 'my_wp_new_user_notification_email', 10, 3 );
function my_wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname ) {
$message = sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n";
$message .= __('Hello To set your password, visit the following address:') . "\r\n\r\n";
$message .= '<' . network_site_url("login/?key=$key&login=" . rawurlencode($user->user_login), 'login') . ">\r\n\r\n";
$wp_new_user_notification_email['message'] = $message
return $wp_new_user_notification_email;
}
```
I think I am missing `$key` information since the email received has the link like this:
`site.com/login?action=rp&key=&login=user%40test.com`
How to fix this? | You need to use the `get_password_reset_key` function [(see reference)](https://developer.wordpress.org/reference/functions/get_password_reset_key/) which will query the database and return the reset password key of the user.
Here's a full working example:
```
add_filter( 'wp_new_user_notification_email', 'custom_wp_new_user_notification_email', 10, 3 );
function custom_wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname ) {
$key = get_password_reset_key( $user );
$message = sprintf(__('Welcome to the Community,')) . "\r\n\r\n";
$message .= 'To set your password, visit the following address:' . "\r\n\r\n";
$message .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user->user_login), 'login') . "\r\n\r\n";
$message .= "After this you can enjoy our website!" . "\r\n\r\n";
$message .= "Kind regards," . "\r\n";
$message .= "Support Office Team" . "\r\n";
$wp_new_user_notification_email['message'] = $message;
$wp_new_user_notification_email['headers'] = 'From: MyName<example@domain.ext>'; // this just changes the sender name and email to whatever you want (instead of the default WordPress <wordpress@domain.ext>
return $wp_new_user_notification_email;
}
``` |
306,685 | <p>I am trying to solve my https redirection from all away.I follow the all solutions form stackexchange. But still in problem so I am writing here.
Problem is that https redirection is working but some url not redirect.
For example .
<a href="http://example.com/contact" rel="nofollow noreferrer">http://example.com/contact</a> not redirect on <a href="http://example.com/contact" rel="nofollow noreferrer">http://example.com/contact</a>.
This is my code .</p>
<pre><code>define( 'WP_CACHE', false );
define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);
define('WP_HOME','https://www.example.com');
define('WP_SITEURL','https://www.example.com');
</code></pre>
<p>Thanks for support .</p>
| [
{
"answer_id": 306687,
"author": "Godwin Alex Ogbonda",
"author_id": 128519,
"author_profile": "https://wordpress.stackexchange.com/users/128519",
"pm_score": -1,
"selected": false,
"text": "<p>You can use <a href=\"https://wordpress.org/plugins/really-simple-ssl/\" rel=\"nofollow norefe... | 2018/06/22 | [
"https://wordpress.stackexchange.com/questions/306685",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145664/"
] | I am trying to solve my https redirection from all away.I follow the all solutions form stackexchange. But still in problem so I am writing here.
Problem is that https redirection is working but some url not redirect.
For example .
<http://example.com/contact> not redirect on <http://example.com/contact>.
This is my code .
```
define( 'WP_CACHE', false );
define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);
define('WP_HOME','https://www.example.com');
define('WP_SITEURL','https://www.example.com');
```
Thanks for support . | Your code redirects the WordPress admin pages to use https (which will work fine), and then sets the site and WordPress addresses (which may auto redirect some pages). Note that FORCE\_SSL\_LOGIN was deprecated in WordPress version 4.0 (<https://codex.wordpress.org/Administration_Over_SSL>)
You can force the whole site to use SSL using .htaccess (note to cover WordPress installs to their own directory, it should be the .htaccess in the same server directory that the Site home would use).
Usually that would be:
```
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
</IfModule>
```
but some hosts require an environment variable:
```
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
</IfModule>
```
If you're using Windows hosting .htaccess won't work, you'll need to use web.config
```
<rule name="HTTPS" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
</rule>
```
Related Considerations
----------------------
I'd recommend you change all links under your control to use https. Within WordPress the <https://en-gb.wordpress.org/plugins/velvet-blues-update-urls/> is very handy for this.
You should consider changing the WordPress URL and the Site URL in the admin instead, and take a look at this good overall guide to migrating WordPress to use https <https://reviewofweb.com/how-to/migrate-wordpress-from-http-to-https/> |
306,695 | <p>I just want to hide the footer from the homepage and the rest of the website footer should remain the same. how can i do that? here is my website <a href="http://texmex-cantina.com/" rel="nofollow noreferrer">http://texmex-cantina.com/</a>
Thanks in advance.</p>
| [
{
"answer_id": 306687,
"author": "Godwin Alex Ogbonda",
"author_id": 128519,
"author_profile": "https://wordpress.stackexchange.com/users/128519",
"pm_score": -1,
"selected": false,
"text": "<p>You can use <a href=\"https://wordpress.org/plugins/really-simple-ssl/\" rel=\"nofollow norefe... | 2018/06/22 | [
"https://wordpress.stackexchange.com/questions/306695",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137945/"
] | I just want to hide the footer from the homepage and the rest of the website footer should remain the same. how can i do that? here is my website <http://texmex-cantina.com/>
Thanks in advance. | Your code redirects the WordPress admin pages to use https (which will work fine), and then sets the site and WordPress addresses (which may auto redirect some pages). Note that FORCE\_SSL\_LOGIN was deprecated in WordPress version 4.0 (<https://codex.wordpress.org/Administration_Over_SSL>)
You can force the whole site to use SSL using .htaccess (note to cover WordPress installs to their own directory, it should be the .htaccess in the same server directory that the Site home would use).
Usually that would be:
```
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
</IfModule>
```
but some hosts require an environment variable:
```
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
</IfModule>
```
If you're using Windows hosting .htaccess won't work, you'll need to use web.config
```
<rule name="HTTPS" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
</rule>
```
Related Considerations
----------------------
I'd recommend you change all links under your control to use https. Within WordPress the <https://en-gb.wordpress.org/plugins/velvet-blues-update-urls/> is very handy for this.
You should consider changing the WordPress URL and the Site URL in the admin instead, and take a look at this good overall guide to migrating WordPress to use https <https://reviewofweb.com/how-to/migrate-wordpress-from-http-to-https/> |