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=\"https://github.com/WordPress/gutenberg/blob/v2.9.2/docs/reference/deprecated.md#310\" rel=\"noreferrer\">release notes</a>).</p>\n\n<p>Specifically <code>wp.blocks.InspectorControls</code> is now <code>wp.editor.InspectorControls</code> - you'll need to change the first line of your code.</p>\n\n<p><em>Note: <code>registerBlockType</code> is still imported from <code>wp.blocks.*</code> iirc.</em></p>\n\n<p>As a side note, I've also found that the <code>focus &&</code> trick no longer required as GB automatically displays the InspectorControls when the block is focused.</p>\n"
},
{
"answer_id": 324094,
"author": "Biskrem Muhammad",
"author_id": 157889,
"author_profile": "https://wordpress.stackexchange.com/users/157889",
"pm_score": 2,
"selected": false,
"text": "<p>I'm going to give you a walk through to the point, because I struggled too :)</p>\n\n<p>First import the <code>InspectorControls</code></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>const { InspectorControls } = wp.editor;\n</code></pre>\n\n<p>then import components such as <code>ColorPalette</code></p>\n\n<pre class=\"lang-php prettyprint-override\"><code>const { ColorPalette } = wp.components;\n</code></pre>\n\n<p>In order to save the state you have to define an attribute:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>attributes: {\n // To storage background colour of the div\n background_color: { \n type: 'string', \n default: 'red', // Default value for newly added block\n }, \n // To storage the complete style of the div that will be 'merged' with the selected colors\n block_style: { \n selector: 'div', // From tag a\n source: 'attribute', // binds an attribute of the tag\n attribute: 'style', // binds style of a: the dynamic colors\n }\n},\n</code></pre>\n\n<p>Then at the <code>edit</code> function... Define the <code>onChangeColorHandler</code> and a variable to hold the changed value in the <strong>JSX</strong>, because of course you can't from the css.</p>\n\n<p>In the <code>return</code> part return an array of two elements <code>[]</code> the <code>Inspector</code> and the rendered <code>div</code> in the editor</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>edit: function( props ) {\n\n var background_color = props.attributes.background_color // To bind button background color\n\n // Style object for the button\n // I created a style in JSX syntax to keep it here for\n // the dynamic changes\n var block_style = props.attributes.block_style // To bind the style of the button\n block_style = {\n backgroundColor: background_color,\n color: '#000',\n padding: '14px 25px',\n fontSize: '16px', \n }\n\n //\n // onChange event functions\n //\n function onChangeBgColor ( content ) {\n props.setAttributes({background_color: content})\n }\n\n // Creates a <p class='wp-block-cgb-block-gtm-audio-block'></p>.\n return [\n <InspectorControls>\n <label class=\"blocks-base-control__label\">background color</label>\n <ColorPalette // Element Tag for Gutenberg standard colour selector\n onChange={onChangeBgColor} // onChange event callback\n />\n </InspectorControls>\n ,\n <div className={ props.className } style={block_style}>\n <p>— Hello from the backend.</p>\n </div>\n ];\n},\n</code></pre>\n\n<p>** FINALLY: ** the save method, just create variable for the style and give the rendered <code>div</code> the JSX style of that value.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>save: function( props ) {\n\n var block_style = {\n backgroundColor: props.attributes.background_color\n }\n return (\n <div style={block_style}>\n <p>— Hello from the frontend.</p>\n </div>\n );\n},\n</code></pre>\n\n<blockquote>\n <p><a href=\"https://gist.github.com/BiskremMuhammad/cf9c4a882e2f373d13602766e1867b60#file-gutenberg-block-development-simple-div-with-background-color-change-from-inspector-js\" rel=\"nofollow noreferrer\">here is a complete gist of the file</a></p>\n</blockquote>\n"
},
{
"answer_id": 336979,
"author": "auco",
"author_id": 167296,
"author_profile": "https://wordpress.stackexchange.com/users/167296",
"pm_score": 0,
"selected": false,
"text": "<p><code>PanelColor</code> has been deprecated, use <code>PanelColorSettings</code> instead:</p>\n\n<pre><code>const {\n PanelColorSettings,\n …\n} = wp.editor;\n\n…\n\nedit: (props) => {\n …\n return (\n …\n <InspectorControls>\n <PanelColorSettings\n title={ 'Background Color' }\n colorSettings={[{\n value: backgroundColor,\n onChange: onChangeBackgroundColor,\n label: __('Background Color')\n }]}\n />\n </InspectorControls>\n …\n</code></pre>\n"
}
]
| 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 WordPress uses in database for dates by default):</p>\n\n<pre><code>// Convert date to MySQL date format before it is stored in database\n$date = date('Y-m-d', 'the_date_value' );\n</code></pre>\n\n<p>Then you can sort by that date field:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'closing_column_orderby' ); \nfunction closing_column_orderby( $query ) { \n if( ! is_admin() ) \n return; \n\n $orderby = $query->get( 'orderby'); \n\n if( 'closing' == $orderby ) { \n $query->set('meta_key','closing');\n $query->set('meta_type','DATE');\n $query->set('orderby','meta_value'); \n } \n} \n</code></pre>\n\n<p>Then, before display, change to the display format you wish.</p>\n\n<pre><code>// Convert from MySQL format to the desired format for display\n// For example, use the date format configured in WordPress settings\n$date = date( get_option('date_format'), 'the_date_value' );\n</code></pre>\n"
},
{
"answer_id": 304560,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>By default meta values will be treated as strings, leading to the result that you get. As you can see from the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">codex on <code>wp_query</code></a> you can force a comparison with different formats by defining a <code>meta_type</code>. Like this:</p>\n\n<pre><code> $query->set('meta_type','DATETIME'); \n</code></pre>\n"
}
]
| 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 WordPress uses in database for dates by default):</p>\n\n<pre><code>// Convert date to MySQL date format before it is stored in database\n$date = date('Y-m-d', 'the_date_value' );\n</code></pre>\n\n<p>Then you can sort by that date field:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'closing_column_orderby' ); \nfunction closing_column_orderby( $query ) { \n if( ! is_admin() ) \n return; \n\n $orderby = $query->get( 'orderby'); \n\n if( 'closing' == $orderby ) { \n $query->set('meta_key','closing');\n $query->set('meta_type','DATE');\n $query->set('orderby','meta_value'); \n } \n} \n</code></pre>\n\n<p>Then, before display, change to the display format you wish.</p>\n\n<pre><code>// Convert from MySQL format to the desired format for display\n// For example, use the date format configured in WordPress settings\n$date = date( get_option('date_format'), 'the_date_value' );\n</code></pre>\n"
},
{
"answer_id": 304560,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>By default meta values will be treated as strings, leading to the result that you get. As you can see from the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">codex on <code>wp_query</code></a> you can force a comparison with different formats by defining a <code>meta_type</code>. Like this:</p>\n\n<pre><code> $query->set('meta_type','DATETIME'); \n</code></pre>\n"
}
]
| 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 try disabling all the plugins?</li>\n<li>Please check the \"Addional CSS\" in the customizer and check if the code is there, or check if there is any Custom CSS plugin installed\nand this is inserted in it. Also check the style.css file in your\ntheme.</li>\n<li>Add additional CSS yourself by adding a code like this and overriding this? Here's the code:<br>\n<code>html {margin-top: 1px !important;}</code></li>\n</ul>\n\n<p>If any of these doesn't fix the issue, please let me know which theme are you using. </p>\n"
},
{
"answer_id": 304576,
"author": "Renz Ramos",
"author_id": 144357,
"author_profile": "https://wordpress.stackexchange.com/users/144357",
"pm_score": 1,
"selected": false,
"text": "<p>If you can't see it in view source code ( ctrl + u ), probably javascript added it.</p>\n\n<p>And also, is this only available when you're logged in? I think it caused by the WordPress admin bar. </p>\n\n<p>Regards,\nRenz</p>\n"
},
{
"answer_id": 304577,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": true,
"text": "<p>The CSS code you're seeing is added by core of WP when admin bar is showing. </p>\n\n<p>The function that outputs it is called <a href=\"https://developer.wordpress.org/reference/functions/_admin_bar_bump_cb/\" rel=\"noreferrer\"><code>_admin_bar_bump_cb()</code></a> and it's called as hook on <code>wp_head</code>.</p>\n\n<p>So how to get rid of it? Just remove this action from that hook:</p>\n\n<pre><code>function remove_admin_bar_bump() {\n remove_action( 'wp_head', '_admin_bar_bump_cb' );\n}\nadd_action('get_header', 'remove_admin_bar_bump');\n</code></pre>\n\n<p>Then you can add it in your CSS and use <code>body.admin-bar</code> as context if you want to add some styles only if the admin bar is visible.</p>\n"
}
]
| 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 widgets for specific <strong>page/post/archive/single/taxonomy</strong> page for <strong>logged-in/unlogged users</strong>. </p>\n\n<p>AH Display Widgets: <a href=\"https://wordpress.org/plugins/ah-display-widgets/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/ah-display-widgets/</a></p>\n\n<p>You simply need to select from drop-down whether to show specific widget to logged-in users or unlogged users.</p>\n\n<p>Hope this helps...!!</p>\n\n<p><a href=\"https://i.stack.imgur.com/FtZCD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FtZCD.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 304594,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 1,
"selected": false,
"text": "<p>Probably simplest, though not always optimal, is to use CSS. In the vast majority of WordPress themes (ones assigning body classes), <code>logged-in</code> and <code>home</code> will be applied to the body tag automatically, when appropriate, and every widget gets a unique ID wherever it's displayed. </p>\n\n<p>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 <code>text-24</code>:</p>\n\n<pre><code>/*CONCEAL text-24 WIDGET FROM LOGGED IN USERS ON HOME PAGE */\n.home.logged-in #text-24 {\n display: none;\n} \n</code></pre>\n\n<p>(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 <code>admin-bar</code> class if I happened to be hiding the Admin Bar already from users below Administrator level.) </p>\n"
}
]
| 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 values.</p>\n\n<p>The problem in here is that <a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow noreferrer\"><code>add_post_meta</code></a> does exactly what it's name is saying - it adds a post meta value. There is 4th arg for that function that's called <code>unique</code>, but it work based on key and not value.</p>\n\n<p>All of that means that you have to do the checking by yourself... So you'll have to get all meta values using <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta</code></a> for that key and check if there already exists a meta with given value...</p>\n\n<p>So how can that look like?</p>\n\n<p>Somewhere in your code is a line looking like this:</p>\n\n<pre><code>add_post_meta( $post_id, $meta_key, $meta_value );\n</code></pre>\n\n<p>Just change it to this:</p>\n\n<pre><code>$existing_pms = get_post_meta( $post_id, $meta_key );\nif ( ! in_array( $meta_value, $existing_pms ) ) {\n add_post_meta( $post_id, $meta_key, $meta_value );\n}\n</code></pre>\n"
},
{
"answer_id": 375178,
"author": "DaveyJake",
"author_id": 51546,
"author_profile": "https://wordpress.stackexchange.com/users/51546",
"pm_score": 0,
"selected": false,
"text": "<p>I know this post is a little outdated but just in case anyone comes across this, I've written a function that checks for any pre-existing metadata attached a given post.</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Check if post has pre-existing metadata.\n *\n * @see metadata_exists()\n *\n * @param int $post_id The post ID.\n * @param string $meta_key The meta key to look for.\n *\n * @return bool True if key is found. False if not.\n */\nfunction wpse304585_post_meta_exists( $post_id, $meta_key ) {\n if ( metadata_exists( 'post', $post_id, $meta_key ) ) {\n return true;\n }\n\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 404956,
"author": "Purple Tentacle",
"author_id": 106593,
"author_profile": "https://wordpress.stackexchange.com/users/106593",
"pm_score": 0,
"selected": false,
"text": "<p>You could always just delete_post_meta first, which will only remove any matching exiting entries, then add_post_meta.</p>\n<pre><code> delete_post_meta($post_id, 'client', 'Andy');\n add_post_meta($post_id, 'client', 'Andy', false);\n</code></pre>\n<p>This will prevent any duplicates and add any new entries as needed.</p>\n"
}
]
| 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 values.</p>\n\n<p>The problem in here is that <a href=\"https://codex.wordpress.org/Function_Reference/add_post_meta\" rel=\"nofollow noreferrer\"><code>add_post_meta</code></a> does exactly what it's name is saying - it adds a post meta value. There is 4th arg for that function that's called <code>unique</code>, but it work based on key and not value.</p>\n\n<p>All of that means that you have to do the checking by yourself... So you'll have to get all meta values using <a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\"><code>get_post_meta</code></a> for that key and check if there already exists a meta with given value...</p>\n\n<p>So how can that look like?</p>\n\n<p>Somewhere in your code is a line looking like this:</p>\n\n<pre><code>add_post_meta( $post_id, $meta_key, $meta_value );\n</code></pre>\n\n<p>Just change it to this:</p>\n\n<pre><code>$existing_pms = get_post_meta( $post_id, $meta_key );\nif ( ! in_array( $meta_value, $existing_pms ) ) {\n add_post_meta( $post_id, $meta_key, $meta_value );\n}\n</code></pre>\n"
},
{
"answer_id": 375178,
"author": "DaveyJake",
"author_id": 51546,
"author_profile": "https://wordpress.stackexchange.com/users/51546",
"pm_score": 0,
"selected": false,
"text": "<p>I know this post is a little outdated but just in case anyone comes across this, I've written a function that checks for any pre-existing metadata attached a given post.</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Check if post has pre-existing metadata.\n *\n * @see metadata_exists()\n *\n * @param int $post_id The post ID.\n * @param string $meta_key The meta key to look for.\n *\n * @return bool True if key is found. False if not.\n */\nfunction wpse304585_post_meta_exists( $post_id, $meta_key ) {\n if ( metadata_exists( 'post', $post_id, $meta_key ) ) {\n return true;\n }\n\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 404956,
"author": "Purple Tentacle",
"author_id": 106593,
"author_profile": "https://wordpress.stackexchange.com/users/106593",
"pm_score": 0,
"selected": false,
"text": "<p>You could always just delete_post_meta first, which will only remove any matching exiting entries, then add_post_meta.</p>\n<pre><code> delete_post_meta($post_id, 'client', 'Andy');\n add_post_meta($post_id, 'client', 'Andy', false);\n</code></pre>\n<p>This will prevent any duplicates and add any new entries as needed.</p>\n"
}
]
| 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 modify the permalink in the URL the easiest thing to do would be to edit the permalink in the edit page of that particular post/page, rather than doing it programmatically.</p>\n\n<p>If this is more complicated, you may want to look at the <a href=\"https://codex.wordpress.org/Function_Reference/WP_Rewrite\" rel=\"nofollow noreferrer\">WP_Rewrite API</a> and create custom logic with that.</p>\n\n<p>Also, you can <a href=\"https://wordpress.stackexchange.com/questions/108642/permalinks-custom-post-type-custom-taxonomy-post#108647\">rewrite the permalink structure</a> in the CPT declaration</p>\n"
},
{
"answer_id": 304972,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<h2>URLs made from CF</h2>\n\n<p>Well, you can do this in many ways... One of them would be to use <code>parse_request</code> filter and modify it's behavior, but it can easily mess something up.</p>\n\n<p>Another way would be to use <code>save_post</code> action and modify the posts <code>post_name</code>, so WordPress will work like normal, but the <code>post_name</code> 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...</p>\n\n<p>So here's the code:</p>\n\n<pre><code>function change_post_name_on_save($post_ID, $post, $update ) {\n global $wpdb;\n\n $post = get_post( $post_ID );\n $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 );\n\n if ( ! in_array( $post->post_status, array( 'publish', 'trash' ) ) ) {\n // no changes for post that is already published or trashed\n $wpdb->update( $wpdb->posts, array( 'post_name' => $cf_post_name ), array( 'ID' => $post_ID ) );\n clean_post_cache( $post_ID );\n } elseif ( 'publish' == $post->post_status ) {\n if ( $post->ID == $post->post_name ) {\n // it was published just now\n $wpdb->update( $wpdb->posts, array( 'post_name' => $cf_post_name ), array( 'ID' => $post_ID ) );\n clean_post_cache( $post_ID );\n }\n }\n}\nadd_action( 'save_post', 'change_post_name_on_save', 20, 3 );\n</code></pre>\n\n<p>It's not the prettiest one, because ACF fields are saved after the post, so you'll have to overwrite the <code>post_name</code> after the post is already saved. But it should work just fine.</p>\n\n<h2>CPTs in root</h2>\n\n<p>And there's the second part of your question: How to make CPTs URLs without CPT slug...</p>\n\n<p>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.</p>\n\n<p>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...</p>\n\n<p>One way to fix this is to register CPT with a slug and then change their links and WPs behavior. Here's the code:</p>\n\n<pre><code>function register_mycpt() {\n $arguments = array(\n 'label' => 'MyCPT',\n 'public' => true,\n 'hierarchical' => false,\n ...\n 'has_archive' => false,\n 'rewrite' => true\n );\n register_post_type('mycpt', $arguments);\n}\nadd_action( 'init', 'register_mycpt' );\n</code></pre>\n\n<p>Now the URLs for these posts will look like these:</p>\n\n<pre><code>http://example.com/mycpt/{post_name}/\n</code></pre>\n\n<p>But we can easily change this using <code>post_type_link</code> filter:</p>\n\n<pre><code>function change_mycpt_post_type_link( $url, $post, $leavename ) {\n if ( 'mycpt' == $post->post_type ) {\n $url = site_url('/') . $post->post_name . '/';\n }\n\n return $url;\n}\nadd_filter( 'post_type_link', 'change_mycpt_post_type_link', 10, 3 );\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>function try_mycpt_before_page_in_parse_request( $wp ) {\n global $wpdb;\n\n if ( is_admin() ) return;\n\n if ( array_key_exists( 'name', $wp->query_vars ) ) {\n $post_name = $wp->query_vars['name'];\n\n $id = $wpdb->get_var( $wpdb->prepare(\n \"SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_name = %s \",\n 'mycpt', $post_name\n ) );\n\n if ( $id ) {\n $wp->query_vars['mycpt'] = $post_name;\n $wp->query_vars['post_type'] = 'mycpt';\n }\n\n }\n}\nadd_action( 'parse_request', 'try_mycpt_before_page_in_parse_request' );\n</code></pre>\n"
}
]
| 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 <[email protected]>
* @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 WordPress Multisite</a> (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,</p>\n\n<ol>\n<li>you modify the domain in your database. I am not aware of any plugins that handle wpms installation till date. However, I use the <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">Interconnect/it search and replace db tool</a>. 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.</li>\n<li>you also need to change the wp-config.php wpms settings,\n<code>\ndefine('DOMAIN_CURRENT_SITE', 'localhost');\ndefine('PATH_CURRENT_SITE', '/local-folder/');\n</code>\nto\n<code>\ndefine('DOMAIN_CURRENT_SITE', 'your-domain.com');\ndefine('PATH_CURRENT_SITE', '/'); //or a sub-folder name is not a root installation.\n</code></li>\n</ol>\n\n<p>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.</p>\n\n<p>[EDIT] In case you have created a fresh installation, then the likely issue is that you have either a problem with your <a href=\"https://codex.wordpress.org/Create_A_Network?#Enabling_the_Network\" rel=\"nofollow noreferrer\">htaccess</a> file or with the site_url/home_url <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">settings</a>. </p>\n\n<p>If you have misconfigured your site_rule/home_url in your dashboard then you need to change it directly in your database. Follow these <a href=\"https://codex.wordpress.org/Changing_The_Site_URL#Changing_the_URL_directly_in_the_database\" rel=\"nofollow noreferrer\">instructions</a>, and assuming from your question that you have installed your WordPress files in the sub-folder <code>/wp</code>, make sure that,</p>\n\n<ol>\n<li>If you want to access your site with: <code>domain.com</code> and your dashboard with <code>domain.com/wp-admin</code>, then</li>\n</ol>\n\n<p><code>\nsiteurl = http://domain.com\nhome = http:/domain.com/wp</code></p>\n\n<ol start=\"2\">\n<li>If you want to access your site with <code>domain.com/wp</code> and your dashboard with <code>domain.com/wp/wp-admin</code> then,</li>\n</ol>\n\n<p><code>\nsiteurl = http://domain.com/wp\nhome = http:/domain.com/wp</code></p>\n\n<p>[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 <a href=\"https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor\" rel=\"nofollow noreferrer\">network tab of the inspector console</a>. This can give you a clue as to where the redirection is being applied.</p>\n"
},
{
"answer_id": 402871,
"author": "nydame",
"author_id": 86502,
"author_profile": "https://wordpress.stackexchange.com/users/86502",
"pm_score": 0,
"selected": false,
"text": "<p>This answer is specific to WordPress Multisite instances set up with Bitnami: .htaccess files may not work as expected. Instead, when I follow these instructions I found on Bitnami docs: <a href=\"https://docs.bitnami.com/aws/apps/wordpress-multisite/administration/use-directories/\" rel=\"nofollow noreferrer\">https://docs.bitnami.com/aws/apps/wordpress-multisite/administration/use-directories/</a> my problem was solved.</p>\n"
}
]
| 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 <[email protected]>
* @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 type</em>:</p>\n\n<pre><code>function mailer_config( PHPMailer $mailer ) {\n if( 'Subject #1' === $mailer->Subject && 'text/html' !== $mailer->ContentType ) {\n $mailer->IsHTML( true );\n }\n}\n</code></pre>\n\n<p>other options would be to e.g. check the <code>$mailer->From</code> or <code>$mailer->FromName</code>, or some other conditions, depending on your setup. </p>\n\n<p>Another approach without <em>PHPMailer</em> dependency, could be to use the <code>wp_mail</code> filter, with the <code>wp_mail_content_type</code> filter.</p>\n"
},
{
"answer_id": 305439,
"author": "Luca Reghellin",
"author_id": 10381,
"author_profile": "https://wordpress.stackexchange.com/users/10381",
"pm_score": 1,
"selected": true,
"text": "<p>Ok, following @birgire suggestions, I finally ended up using <code>wp_mail_content_type</code> filter in conjunction with an hidden field on my form. Php code is this:</p>\n\n<pre><code>add_filter( 'wp_mail_content_type', 'set_mailer_content_type' );\nfunction set_mailer_content_type( $content_type ) {\n if(isset($_POST['ishtmlform'])){ return 'text/html'; } // in-page/form hidden field\n return 'text/plain';\n}\n</code></pre>\n\n<p>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).</p>\n\n<p>Side notes, slightly offtopic:</p>\n\n<ul>\n<li>internally, <code>wp_mail()</code> just sets <code>PhpMailer->isHTML(true)</code> if you set content type == <code>'text/html'</code>. You can find the source in <code>wp-includes/pluggable.php</code></li>\n<li>Keep in mind that if you set <code>'text/html'</code>, 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.</li>\n</ul>\n"
}
]
| 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 hierarchical, all terms if taxonomy is not hierarchical</p>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/es:Function_Reference/get_terms\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/es:Function_Reference/get_terms</a></p>\n\n<p>I think you're finding something like this:</p>\n\n<pre><code>/**\n * Recursively get taxonomy hierarchy\n *\n * @source http://www.daggerhart.com/wordpress-get-taxonomy-hierarchy-including-children/\n * @param string $taxonomy\n * @param int $parent - parent term id\n *\n * @return array\n */\nfunction get_taxonomy_hierarchy( $taxonomy, $parent = 0 ) {\n // only 1 taxonomy\n $taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;\n // get all direct decendents of the $parent\n $terms = get_terms( $taxonomy, array('parent' => $parent) );\n // prepare a new array. these are the children of $parent\n // we'll ultimately copy all the $terms into this new array, but only after they\n // find their own children\n $children = array();\n // go through all the direct decendents of $parent, and gather their children\n foreach( $terms as $term ) {\n // recurse to get the direct decendents of \"this\" term\n $term->children = get_taxonomy_hierarchy( $taxonomy, $term->term_id );\n // add the term to our new array\n $children[ $term->term_id ] = $term;\n }\n // send the results back to the caller\n return $children;\n}\n</code></pre>\n\n<p>It should return all the child from Location</p>\n\n<p>We are agree?</p>\n"
},
{
"answer_id": 305763,
"author": "rassoh",
"author_id": 18713,
"author_profile": "https://wordpress.stackexchange.com/users/18713",
"pm_score": 2,
"selected": false,
"text": "<p>OK, so this is what I came up with:</p>\n\n<pre><code>function get_childless_term_children( $parent_id, $taxonomy ) {\n // get all childless $terms of this $taxonomy\n $terms = get_terms(array(\n 'taxonomy' => $taxonomy,\n 'childless' => true,\n ));\n\n foreach( $terms as $key => $term ) {\n // remove $terms that aren't descendants (= children) of $parent_id\n if( !in_array( $parent_id, get_ancestors( $term->term_id, $taxonomy ) ) ) {\n unset( $terms[$key] );\n }\n }\n return $terms;\n}\n</code></pre>\n\n<p>What this does: Get all childless terms that are children of <code>$parent_id</code>.</p>\n"
}
]
| 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, since the output is somewhat predictable, I would try the following instead of the getCapitalLetters function:</p>\n\n<pre><code>function strip_cruft( $str ) {\n $str = str_replace( '\";s', '', $str );\n $str = str_replace( '\"', '', $str );\n return $str;\n}\n</code></pre>\n\n<p>Part 2 - To output a populated dropdown:</p>\n\n<p>Use the above function and remember to add a value in between the opening and closing tags:</p>\n\n<pre><code><?php foreach($posttype as $post) {\n $post = strip_cruft( $post ); ?>\n <option value=\"<?php echo esc_attr( $post ); ?>\">\n <?php echo esc_html( $post ); ?>\n </option>\n<?php } ?>\n</code></pre>\n\n<p>If you'd like them to be all lowercase, you can use WordPress's <code>sanitize_title</code> function.</p>\n"
},
{
"answer_id": 304787,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>In your original question you had text like this</p>\n\n<pre><code>a:12:{s:3:\"key\";s:19:\"field_57bdd83367bb1\";s:5:\"label\"\n</code></pre>\n\n<p>This is <em>not</em> JSON. This is a PHP serialized Array. This is a representation of a PHP array intended for storage in a database. It is created with the <code>serialize()</code> function. If you try to <code>update_post_meta()</code> or <code>update_option()</code> with an Array value in WordPress then WordPress will serialize the data first. When you use <code>get_post_meta()</code> or <code>get_option()</code> WordPress will <code>unserialize()</code> the data for you.</p>\n\n<p>Your problem here is that you're not retrieving this data with WordPress functions. You're using <code>Mage::helper('wordpress')->getPostType2()</code>, which appears to be a Magento function. If you're using this data in Magento then A. This is the wrong forum, please ask in a Magento forum if you have issues in Magento and B. You need to unserialize the data yourself:</p>\n\n<pre><code>$posttype= Mage::helper('wordpress')->getPostType2();\n$posttype = unserialize($posttype);\necho 'Post type:';\n\necho '<pre>';print_r($posttype);\n</code></pre>\n\n<p>PS: I rolled back your question to the first version, because it was the only version of the question that included information that explained the problem.</p>\n"
}
]
| 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 rule before the wordpress rules. For that it do not make a difference where exactly the page is located on the disk, as long as you write the correct rule.</p>\n\n<p>But for me it just sounds wrong and it is much better to convert the page into a wordpress page template by adding the relevant header and just add it like you add any other wordpress page \"underneath\" your main page, and since you will probably very quickly realize that you will want to be able to use the <code>wp_footer</code> and <code>wp_head</code> hooks, you are most likely to end doing it in any case.</p>\n"
},
{
"answer_id": 304754,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 4,
"selected": true,
"text": "<p>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 <code>.htaccess</code>. 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).</p>\n\n<p>For example, instead of saving your non-WordPress page at <code>/city/pricing/index.php</code>, save it at <code>/non-wordress/city-pricing.php</code> (for example) or <code>/non-wordress/city/pricing/index.php</code> (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).</p>\n\n<p>Then in <code>.htaccess</code> <em>before</em> the WordPress front-controller (ie. <em>before</em> the <code># BEGIN WordPress</code> section) you can do something like:</p>\n\n<pre><code>RewriteRule ^city/pricing/$ /non-wordpress/city-pricing.php [L]\n</code></pre>\n\n<p>This <em>internally rewrites</em> <code>/city/pricing/</code> to <code>/non-wordpress/city-pricing.php</code> - this is entirely hidden from the end user.</p>\n\n<p>But stress, this <em>must</em> go before the WordPress front-controller, otherwise you'll simply get a 404.</p>\n"
}
]
| 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 nothing else matches, wordpress will try to find a page there).</p>\n\n<p>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 ;)</p>\n"
},
{
"answer_id": 305011,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>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.</p>\n\n<p>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...</p>\n\n<p>One way to fix this is to register CPT with a slug and then change their links and WPs behavior. Here's the code:</p>\n\n<pre><code>function register_mycpt() {\n $arguments = array(\n 'label' => 'MyCPT',\n 'public' => true,\n 'hierarchical' => false,\n ...\n 'has_archive' => false,\n 'rewrite' => true\n );\n register_post_type('mycpt', $arguments);\n}\nadd_action( 'init', 'register_mycpt' );\n</code></pre>\n\n<p>Now the URLs for these posts will look like these:</p>\n\n<pre><code>http://example.com/mycpt/{post_name}/\n</code></pre>\n\n<p>But we can easily change this using <code>post_type_link</code> filter:</p>\n\n<pre><code>function change_mycpt_post_type_link( $url, $post, $leavename ) {\n if ( 'mycpt' == $post->post_type ) {\n $url = site_url('/') . $post->post_name . '/';\n }\n\n return $url;\n}\nadd_filter( 'post_type_link', 'change_mycpt_post_type_link', 10, 3 );\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>function try_mycpt_before_page_in_parse_request( $wp ) {\n global $wpdb;\n\n if ( is_admin() ) return;\n\n if ( array_key_exists( 'name', $wp->query_vars ) ) {\n $post_name = $wp->query_vars['name'];\n\n $id = $wpdb->get_var( $wpdb->prepare(\n \"SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_name = %s \",\n 'mycpt', $post_name\n ) );\n\n if ( $id ) {\n $wp->query_vars['mycpt'] = $post_name;\n $wp->query_vars['post_type'] = 'mycpt';\n }\n\n }\n}\nadd_action( 'parse_request', 'try_mycpt_before_page_in_parse_request' );\n</code></pre>\n\n<p>PS. Is it wise to use that code? That's another question. It changes behavior of WP in rather major way, so it can be a little bit tricky. But if there is really a need, you can do this...</p>\n\n<p>Disclaimer: This code will work fine for nonhierarchical CPTs, but you can adapt it to work for hierarchical also...</p>\n"
}
]
| 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 should have <code>wp_head()</code> somewhere between <code><head></head></code>, then you can let WordPress set the title tag by <a href=\"https://codex.wordpress.org/Title_Tag#Adding_Theme_Support\" rel=\"nofollow noreferrer\">adding support for <code>title-tag</code> to your theme</a>:</p>\n\n<pre><code>function wpse_304818_theme_setup() {\n add_theme_support( 'title-tag' );\n}\nadd_action( 'after_setup_theme', 'wpse_304818_theme_setup' );\n</code></pre>\n"
},
{
"answer_id": 304868,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": 0,
"selected": false,
"text": "<p>You need to follow steps to add support for title tag as mentioned in the answer by @Jacob Peattie</p>\n\n<p>If still, you want additional option to add SEO specific title and meta description, you can use Yoast SEO WordPress plugin, which provides additional custom fields to add the page title and meta description.</p>\n\n<p>Yoast SEO: <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wordpress-seo/</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/vNGaX.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vNGaX.jpg\" alt=\"enter image description here\"></a></p>\n"
}
]
| 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 should have <code>wp_head()</code> somewhere between <code><head></head></code>, then you can let WordPress set the title tag by <a href=\"https://codex.wordpress.org/Title_Tag#Adding_Theme_Support\" rel=\"nofollow noreferrer\">adding support for <code>title-tag</code> to your theme</a>:</p>\n\n<pre><code>function wpse_304818_theme_setup() {\n add_theme_support( 'title-tag' );\n}\nadd_action( 'after_setup_theme', 'wpse_304818_theme_setup' );\n</code></pre>\n"
},
{
"answer_id": 304868,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": 0,
"selected": false,
"text": "<p>You need to follow steps to add support for title tag as mentioned in the answer by @Jacob Peattie</p>\n\n<p>If still, you want additional option to add SEO specific title and meta description, you can use Yoast SEO WordPress plugin, which provides additional custom fields to add the page title and meta description.</p>\n\n<p>Yoast SEO: <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wordpress-seo/</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/vNGaX.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vNGaX.jpg\" alt=\"enter image description here\"></a></p>\n"
}
]
| 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_consent_checkbox', 10 );</code></p>\n\n<pre><code>function remove_filters_with_method_name( $hook_name = '', $method_name = '', $priority = 0 ) {\n global $wp_filter;\n // Take only filters on right hook name and priority\n if ( ! isset( $wp_filter[ $hook_name ][ $priority ] ) || ! is_array( $wp_filter[ $hook_name ][ $priority ] ) ) {\n return false;\n }\n // Loop on filters registered\n foreach ( (array) $wp_filter[ $hook_name ][ $priority ] as $unique_id => $filter_array ) {\n // Test if filter is an array ! (always for class/method)\n if ( isset( $filter_array['function'] ) && is_array( $filter_array['function'] ) ) {\n // Test if object is a class and method is equal to param !\n if ( is_object( $filter_array['function'][0] ) && get_class( $filter_array['function'][0] ) && $filter_array['function'][1] == $method_name ) {\n // Test for WordPress >= 4.7 WP_Hook class (https://make.wordpress.org/core/2016/09/08/wp_hook-next-generation-actions-and-filters/)\n if ( is_a( $wp_filter[ $hook_name ], 'WP_Hook' ) ) {\n unset( $wp_filter[ $hook_name ]->callbacks[ $priority ][ $unique_id ] );\n } else {\n unset( $wp_filter[ $hook_name ][ $priority ][ $unique_id ] );\n }\n }\n }\n }\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 304913,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": false,
"text": "<p>To remove an action you need to pass the same callable that was used to add the action in the first place. The difference with your hook, compared to a plain function or static method, is that you have passed a method on a <em>specific instance</em> of your class. Note the use of <code>$this</code>:</p>\n\n<pre><code>add_action( 'woocommerce_after_order_notes', array( $this, 'checkout_consent_checkbox' ) );\n</code></pre>\n\n<p>So when you remove the action you need to pass the <em>same instance</em> the same way:</p>\n\n<pre><code>add_action( 'woocommerce_after_order_notes', array( $that, 'checkout_consent_checkbox' ) );\n</code></pre>\n\n<p>Where <code>$that</code> is a variable containing the same instance of the class. </p>\n\n<p>To do this you need to find that variable. This depends on how the plugin was originally built. <em>If</em> the class was instantiated into a global variable like this:</p>\n\n<pre><code>global $wp_gdpr_wc_controller;\n$wp_gdpr_wc_controller = new Controller_Wc;\n</code></pre>\n\n<p>Then you would remove it like this:</p>\n\n<pre><code>global $wp_gdpr_wc_controller;\nremove_action( 'woocommerce_after_order_notes', array( $wp_gdpr_wc_controller, 'checkout_consent_checkbox' ) );\n</code></pre>\n"
},
{
"answer_id": 412405,
"author": "Flea",
"author_id": 217679,
"author_profile": "https://wordpress.stackexchange.com/users/217679",
"pm_score": 1,
"selected": false,
"text": "<p>In order to improve Alex's answer I've added string comparation with get_class( $filter_array['function'][0]) (also is possible with instance of) because the same method name may be within other classes.</p>\n<p>Here's the function:</p>\n<pre><code>function remove_filters_with_method_and_class_name( $hook_name, $class_name,$method_name, $priority = 0 ) {\n global $wp_filter;\n // Take only filters on right hook name and priority\n if ( ! isset( $wp_filter[ $hook_name ][ $priority ] ) || ! is_array( $wp_filter[ $hook_name ][ $priority ] ) ) {\n return false;\n }\n // Loop on filters registered\n foreach ( (array) $wp_filter[ $hook_name ][ $priority ] as $unique_id => $filter_array ) {\n // Test if filter is an array ! (always for class/method)\n if ( isset( $filter_array['function'] ) && is_array( $filter_array['function']) ) {\n // Test if object is a class and method is equal to param !\n if ( is_object( $filter_array['function'][0] ) && get_class( $filter_array['function'][0] )\n && get_class( $filter_array['function'][0] ) == $class_name && $filter_array['function'][1] == $method_name ) {\n // Test for WordPress >= 4.7 WP_Hook class (https://make.wordpress.org/core/2016/09/08/wp_hook-next-generation-actions-and-filters/)\n if ( is_a( $wp_filter[ $hook_name ], 'WP_Hook' ) ) {\n unset( $wp_filter[ $hook_name ]->callbacks[ $priority ][ $unique_id ] );\n } else {\n unset( $wp_filter[ $hook_name ][ $priority ][ $unique_id ] );\n }\n }\n }\n }\n return false;\n}\n</code></pre>\n<p>And you can call it like this:</p>\n<pre><code>remove_filters_with_method_and_class_name("woocommerce_after_order_notes", "Controller_Wc","checkout_consent_checkbox",10);\n</code></pre>\n"
}
]
| 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 customer dashboard. With the proper hook, you should be able to quickly accomplish your goal.</p>\n\n<p>Your best bet is reviewing the Woocommerce documentation at this <a href=\"https://docs.woocommerce.com/wc-apidocs/hook-docs.html\" rel=\"nofollow noreferrer\">link</a>.</p>\n\n<p>As for WordPress you can get the current user with the <a href=\"https://developer.wordpress.org/reference/functions/get_current_user_id/\" rel=\"nofollow noreferrer\">get_current_user()</a> function.</p>\n"
},
{
"answer_id": 304866,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": 2,
"selected": false,
"text": "<p>WooCommerce doesn't provide any such hook to display User ID on the dashbaord.</p>\n\n<p>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.</p>\n\n<p><a href=\"https://docs.woocommerce.com/document/template-structure/\" rel=\"nofollow noreferrer\">https://docs.woocommerce.com/document/template-structure/</a></p>\n\n<p>You need to copy template <strong>dashboard.php</strong> file from WooCommerce plugin template to <strong>woocommerce/myaccount/</strong> folder in your theme.</p>\n\n<p>You can use a code to display <strong>User ID</strong> anywhere on the dashboard page.</p>\n\n<pre><code><?php echo esc_html( $current_user->ID ); ?>\n</code></pre>\n"
},
{
"answer_id": 304894,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": 0,
"selected": false,
"text": "<p>To display name on Customer New Account email, try adding below code in <strong>customer-new-account.php</strong> email template file. Let me know if this works.</p>\n\n<pre><code><?php $user = get_user_by( 'user_login', $user_login );\nif($user){\n echo $user->ID;\n}?>\n</code></pre>\n"
}
]
| 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 customer dashboard. With the proper hook, you should be able to quickly accomplish your goal.</p>\n\n<p>Your best bet is reviewing the Woocommerce documentation at this <a href=\"https://docs.woocommerce.com/wc-apidocs/hook-docs.html\" rel=\"nofollow noreferrer\">link</a>.</p>\n\n<p>As for WordPress you can get the current user with the <a href=\"https://developer.wordpress.org/reference/functions/get_current_user_id/\" rel=\"nofollow noreferrer\">get_current_user()</a> function.</p>\n"
},
{
"answer_id": 304866,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": 2,
"selected": false,
"text": "<p>WooCommerce doesn't provide any such hook to display User ID on the dashbaord.</p>\n\n<p>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.</p>\n\n<p><a href=\"https://docs.woocommerce.com/document/template-structure/\" rel=\"nofollow noreferrer\">https://docs.woocommerce.com/document/template-structure/</a></p>\n\n<p>You need to copy template <strong>dashboard.php</strong> file from WooCommerce plugin template to <strong>woocommerce/myaccount/</strong> folder in your theme.</p>\n\n<p>You can use a code to display <strong>User ID</strong> anywhere on the dashboard page.</p>\n\n<pre><code><?php echo esc_html( $current_user->ID ); ?>\n</code></pre>\n"
},
{
"answer_id": 304894,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": 0,
"selected": false,
"text": "<p>To display name on Customer New Account email, try adding below code in <strong>customer-new-account.php</strong> email template file. Let me know if this works.</p>\n\n<pre><code><?php $user = get_user_by( 'user_login', $user_login );\nif($user){\n echo $user->ID;\n}?>\n</code></pre>\n"
}
]
| 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. Then I might try to find the plugin. On the other hand, theme with poor code might be the culprit.</p>\n"
},
{
"answer_id": 304891,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Your query looks OK, so I doubt that it will cause any problems. But then... Let's take a look at your loop:</p>\n\n<pre><code>if ($mainPosts->have_posts()) {\n\n while ($mainPosts->have_posts()) {\n $postItemImage = the_post_thumbnail_url();\n ... \n echo \"...\";\n\n }\n}\n</code></pre>\n\n<p>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...</p>\n\n<p>It will be an infinite loop, because there is no <code>$mainPosts->the_post()</code>, so it doesn't \"consume\" posts, so there are always all of them when checking loop condition.</p>\n\n<p>This will work fine:</p>\n\n<pre><code>while ($mainPosts->have_posts()) {\n $mainPosts->the_post();\n $postItemImage = the_post_thumbnail_url();\n ... \n echo \"...\";\n}\n</code></pre>\n"
}
]
| 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. Then I might try to find the plugin. On the other hand, theme with poor code might be the culprit.</p>\n"
},
{
"answer_id": 304891,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Your query looks OK, so I doubt that it will cause any problems. But then... Let's take a look at your loop:</p>\n\n<pre><code>if ($mainPosts->have_posts()) {\n\n while ($mainPosts->have_posts()) {\n $postItemImage = the_post_thumbnail_url();\n ... \n echo \"...\";\n\n }\n}\n</code></pre>\n\n<p>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...</p>\n\n<p>It will be an infinite loop, because there is no <code>$mainPosts->the_post()</code>, so it doesn't \"consume\" posts, so there are always all of them when checking loop condition.</p>\n\n<p>This will work fine:</p>\n\n<pre><code>while ($mainPosts->have_posts()) {\n $mainPosts->the_post();\n $postItemImage = the_post_thumbnail_url();\n ... \n echo \"...\";\n}\n</code></pre>\n"
}
]
| 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.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dqm3G.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Step 2:</strong> Set your column Interval 0, if you don't want padding and margin,\n make sure that you custom drainage width option is Enable.</p>\n\n<p><a href=\"https://i.stack.imgur.com/1c37P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1c37P.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Alternative Solution for Remove Spacing</strong></p>\n\n<p>You can also set custom margins with the spacing option as per mark in the screenshot below.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Jock4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Jock4.png\" alt=\"enter image description here\"></a></p>\n\n<p>I hope this suggestion is helpful for you.</p>\n"
},
{
"answer_id": 304952,
"author": "bravokeyl",
"author_id": 43098,
"author_profile": "https://wordpress.stackexchange.com/users/43098",
"pm_score": 3,
"selected": true,
"text": "<p>Checking the demo, I see that you put <code>padding</code> and <code>margin</code> 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).</p>\n\n<p><a href=\"https://i.stack.imgur.com/7vadW.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7vadW.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 305008,
"author": "GingerHippo",
"author_id": 144628,
"author_profile": "https://wordpress.stackexchange.com/users/144628",
"pm_score": 1,
"selected": false,
"text": "<p>We generally see this when margins and padding are conflicting between rows and columns. An alternative method to solving this problem would be to create negative margins. If you choose to use negative margins, know that Divi will overlap imagery from right to left, choosing right content as dominant.</p>\n\n<p>Additionally, make sure you are customizing desktop, tablet, and mobile separately, and the break points for a sideways tablet fall under desktop margin and padding parameters. I keep an iPad next to me to check breakpoint conflicts, along with my iPhone for mobile, etc., because what you are seeing in the visual builder as the mobile or tablet view is not always accurate.</p>\n\n<p>Hope this helps. We used negative margins on our homepage, towards the middle, because we couldn't get a 2px white space to disappear between images. See for yourself at <a href=\"http://gingerhippo.com\" rel=\"nofollow noreferrer\">GingerHippo</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/Sp91o.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Sp91o.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/AeS0t.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AeS0t.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 305075,
"author": "Lynob",
"author_id": 23780,
"author_profile": "https://wordpress.stackexchange.com/users/23780",
"pm_score": 1,
"selected": false,
"text": "<p>I Created a class on the main blurb element called <code>.projects-gallery</code>, then in Divi themes options I added this CSS</p>\n\n<pre><code> .projects-gallery .et_pb_blurb_container { \n display: none; \n}\n .projects-gallery:hover .et_pb_blurb_container { \n display: block; \n}\n</code></pre>\n\n<p>The reason is, <code>.et_pb_blurb_container</code> is taking space and you cannot hide it because then, project titles won't show. Using the code above, you hide it, then you show it, when someone hovers on a particular project. You need a custom class so you don't mess up the rest of the page.</p>\n\n<p>and if you have them on separate rows like I do and want to remove the margin between the rows, then divi applies <code>line-height:1</code> to <code>body</code>, to remove it</p>\n\n<pre><code>.projects-gallery{\n line-height:0;\n} \n</code></pre>\n\n<p>The result</p>\n\n<p><a href=\"https://i.stack.imgur.com/a9HNT.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/a9HNT.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>and to keep the animation when you hover over the image</p>\n\n<pre><code>.projects-gallery:hover{\n line-height:1;\n}\n</code></pre>\n"
}
]
| 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 when updating the cart. The below works, though it's purely a front end customization. Hope this helps someone else!</p>\n\n<pre><code>function bbloomer_split_product_individual_cart_items( $cart_item_data, $product_id ){\n $unique_cart_item_key = uniqid();\n $cart_item_data['unique_key'] = $unique_cart_item_key;\n return $cart_item_data;\n}\n\nadd_filter( 'woocommerce_add_cart_item_data', 'bbloomer_split_product_individual_cart_items', 10, 2 ); \n\nadd_action( 'woocommerce_after_cart_item_quantity_update', 'limit_cart_item_quantity', 20, 4 );\nfunction limit_cart_item_quantity( $cart_item_key, $quantity, $old_quantity, $cart ){\n\n // Here the quantity limit\n $limit = 1;\n $orders_added = $quantity - $limit;\n\n if( $quantity > $limit ){\n //Set existing line item quantity to the limit of 1\n $cart->cart_contents[ $cart_item_key ]['quantity'] = $limit;\n //get product id of item that was updated\n $product_id = $cart->cart_contents[ $cart_item_key ][ 'product_id' ];\n\n for( $i = 0; $i< $orders_added; $i++ ){\n //iterate over the number of orders you must as with quantity one\n $unique_cart_item_key = uniqid();\n //create unique cart item ID, this is what breaks it out as a separate line item\n $cart_item_data = array();\n //initialize cart_item_data array where the unique_cart_item_key will be stored\n $cart_item_data['unique_key'] = $unique_cart_item_key;\n //set the cart_item_data at unique_key = to the newly created unique_key\n\n //add that shit! this does not take into account variable products\n\n $cart->add_to_cart( $product_id, 1, 0, 0, $cart_item_data );\n\n }\n\n // Add a custom notice\n wc_add_notice( __('We Split out quantities of more than one into invididual line items for tracking purposes, please update quantities as needed'), 'notice' );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 358754,
"author": "froger.me",
"author_id": 130448,
"author_profile": "https://wordpress.stackexchange.com/users/130448",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the solution I found - split done at order save, not at cart level:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'woocommerce_after_order_object_save', array( $this, 'split_order_items' ), 10, 2 );\nfunction split_order_items( $order, $data_store ) {\n $order_items = $order->get_items();\n\n foreach ( $order_items as $item ) {\n\n if ( $item instanceof WC_Order_Item_Product ) {\n $quantity = $item->get_quantity( 'edit' );\n $product = $item->get_product();\n\n if ( $product && 1 < $quantity ) {\n $product = $item->get_product();\n $taxes = $item->get_taxes();\n\n WP_Weixin::log( $order->get_item( $item->get_id() ) );\n\n $order->remove_item( $item->get_id() );\n\n for ( $i = $quantity; $i > 0; $i-- ) {\n $new_item = new WC_Order_Item_Product();\n $new_taxes = array();\n\n if ( ! empty( $taxes ) && is_array( $taxes ) ) {\n foreach ( $taxes as $taxes_key => $tax_values ) {\n $new_tax_values = array();\n\n if ( ! empty( $values ) && is_array( $values ) ) {\n\n foreach ( $values as $tax_key => $tax_value ) {\n $new_tax_values[ $tax_key ] = $tax_value / $quantity;\n }\n }\n\n $new_taxes[ $taxes_key ] = $new_tax_values;\n }\n }\n\n $new_item->set_product( $product );\n $new_item->set_backorder_meta();\n $new_item->set_props(\n array(\n 'quantity' => 1,\n 'subtotal' => $item->get_subtotal( 'edit' ) / $quantity,\n 'total' => $item->get_total( 'edit' ) / $quantity,\n 'subtotal_tax' => $item->get_subtotal_tax( 'edit' ) / $quantity,\n 'total_tax' => $item->get_total_tax( 'edit' ) / $quantity,\n 'taxes' => $new_taxes,\n )\n );\n $order->add_item( $new_item );\n }\n }\n }\n }\n\n remove_action( 'woocommerce_after_order_object_save', array( $this, 'split_order_items' ), 10 );\n $order->save();\n add_action( 'woocommerce_after_order_object_save', array( $this, 'split_order_items' ), 10, 2 );\n}\n</code></pre>\n\n<p>The minor downside is that the order is saved twice (the order items are protected, and they have to be saved in database before they can be accessed), which can be acceptable depending on the cases. This is the only way as far as I could tell after spending a few hours looking at the source code.</p>\n"
},
{
"answer_id": 368242,
"author": "Steven7",
"author_id": 175231,
"author_profile": "https://wordpress.stackexchange.com/users/175231",
"pm_score": 0,
"selected": false,
"text": "<p>I read a lot the previous code, and i fixed this, totally backend costumization, I was in need of something like this, we add serial numbers to each product but we want customers to buy with quantity, hope helps some people,</p>\n<p>add in functions.php of your theme/child-theme or any file included in functions.php</p>\n<p>in last edition, I added support for variation products</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'woocommerce_after_order_object_save', 'split_order_items', 10, 2 );\nfunction split_order_items($order) {\n $order_items = $order->get_items();\n foreach ($order_items as $item) {\n $quantity = $item->get_quantity('edit');\n $product = $item->get_product();\n $included_cats = [24, 25];\n $variable = false;\n if ($product->is_type('variation')) {\n $variation_id = $product->get_id();\n $variable_prod = $product;\n $product = wc_get_product($product->get_parent_id());\n $variable = true;\n }\n $category_id = get_the_terms($product->get_id(), 'product_cat')[0]->term_id;\n if ($product && $quantity > 1 && in_array($category_id, $included_cats)) {\n if ($variable) {\n $init_qty = $quantity;\n $item->set_quantity(1);\n if ($quantity > 1) $item->set_props([\n 'subtotal' => $item->get_subtotal('edit') / ($init_qty ?: $quantity),\n 'total' => $item->get_total('edit') / ($init_qty ?: $quantity),\n 'subtotal_tax' => $item->get_subtotal_tax('edit') / ($init_qty ?: $quantity),\n 'total_tax' => $item->get_total_tax('edit') / ($init_qty ?: $quantity),\n ]);\n if ($quantity == 1) continue;\n $quantity--;\n } else {\n $order->remove_item($item->get_id());\n }\n $taxes = $item->get_taxes();\n for ($i = $quantity; $i > 0; $i--) {\n $new_item = new WC_Order_Item_Product();\n $new_taxes = [];\n if ($variable) {\n $new_item->set_product_id($product->get_id());\n $new_item->set_variation_id($variation_id);\n $new_item->set_variation(is_callable([$variable_prod, 'get_variation_attributes']) ? $variable_prod->get_variation_attributes() : []);\n $new_item->set_name($variable_prod->get_name());\n $new_item->set_tax_class($variable_prod->get_tax_class());\n } else {\n $new_item->set_product($product);\n }\n if (!empty($taxes) && is_array($taxes)) {\n foreach ($taxes as $taxes_key => $tax_values) {\n $new_tax_values = [];\n if (!empty($tax_values) && is_array($tax_values)) {\n foreach ($tax_values as $tax_key => $tax_value) {\n $new_tax_values[$tax_key] = $tax_value / $quantity;\n }\n }\n $new_taxes[$taxes_key] = $new_tax_values;\n }\n }\n $new_item->set_backorder_meta();\n $new_item->set_props([\n 'quantity' => 1,\n 'subtotal' => $item->get_subtotal('edit') / ($variable ? 1 : $quantity),\n 'total' => $item->get_total('edit') / ($variable ? 1 : $quantity),\n 'subtotal_tax' => $item->get_subtotal_tax('edit') / ($variable ? 1 : $quantity),\n 'total_tax' => $item->get_total_tax('edit') / ($variable ? 1 : $quantity),\n 'taxes' => $new_taxes,\n ]);\n $order->add_item($new_item);\n }\n }\n }\n remove_action('woocommerce_after_order_object_save', 'split_order_items', 10);\n $order->save();\n add_action('woocommerce_after_order_object_save', 'split_order_items', 10, 1);\n}\n</code></pre>\n"
}
]
| 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 ID back:</p>\n\n<pre><code>$link = get_sub_field( 'offer_link' );\n$id = url_to_postid( $link['url'] );\n</code></pre>\n\n<p>But if you want a field that will give you an ID of a selected page you should use probably use the Relationship field instead. It'd probably be much more efficient. It also means that if the URL to that post changes your saved data wouldn't cease to work like it would if you were saving the URL.</p>\n"
},
{
"answer_id": 304973,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think that you should use the Link field in your case, if you want to create relation with post object...</p>\n\n<p>It would be much better to use Relation field, if you should be able to select many posts, or just Post Object, if it should be possible to select only one value.</p>\n\n<p>If you go for the Post Object field type, then remember to set its Return Format to Post ID. </p>\n\n<p>This way <code>get_sub_field( 'your-field-name' )</code> will return exactly the ID of selected post.</p>\n\n<p>If you want to display link to this post, you can always use <code>echo get_permalink( get_sub_field( 'your-field-name' ) );</code></p>\n\n<p>So this is your code after modifications (I've used your original name for the field, but it would be nice to change it too, I guess, since it doesn't contain link anymore):</p>\n\n<pre><code><?php \n $post_id = get_sub_field('offer_link');\n if ( $post_id ):\n?>\n<a href=\"#post-<?php echo esc_attr($post_id); ?>\"><?php echo get_post_field( 'post_title', $post_id ); ?></a>\n<?php endif; ?>\n</code></pre>\n"
},
{
"answer_id": 305024,
"author": "Damian",
"author_id": 125792,
"author_profile": "https://wordpress.stackexchange.com/users/125792",
"pm_score": -1,
"selected": false,
"text": "<p>This works form me:</p>\n\n<pre><code><?php \n\n$link = get_sub_field('offer_link');\n$x = $link->ID;\n\nif( $link ): ?>\n<a href=\"#post-<?php echo $x ?>\"><?php echo get_sub_field('offer_link_text'); ?></a>\n<?php endif; ?>\n</code></pre>\n\n<p>and Post Object field.</p>\n\n<p>Thaks for everyone for help :)</p>\n"
},
{
"answer_id": 312405,
"author": "relish27",
"author_id": 85492,
"author_profile": "https://wordpress.stackexchange.com/users/85492",
"pm_score": 1,
"selected": true,
"text": "<p>The <a href=\"https://www.advancedcustomfields.com/resources/page-link/\" rel=\"nofollow noreferrer\">Page Link documentation</a> 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.</p>\n\n<pre><code><?php \n\n// vars\n$post_id = get_field('url', false, false);\n\n// check \nif( $post_id ): ?>\n<a href=\"<?php echo get_the_permalink($post_id); ?>\"><?php echo get_the_title($post_id); ?></a>\n<?php endif; ?>\n</code></pre>\n\n<p>The \"false, false\" parameters allow you to retrieve more details.</p>\n"
},
{
"answer_id": 405999,
"author": "Anadar",
"author_id": 207261,
"author_profile": "https://wordpress.stackexchange.com/users/207261",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone else trying this, if you need to get the post id from a subfield in a repeater you can use the get_sub_field with a false flag for the format:</p>\n<pre><code>if ( have_rows( 'repeater') ):\n while ( have_rows( 'repeater') ):the_row();\n $post_id=get_sub_field( 'item_name', false );\n endwhile;\nendif;\n</code></pre>\n"
}
]
| 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.org/reference/functions/dbdelta/\" rel=\"nofollow noreferrer\"><code>dbDelta()</code></a>. Even better, use something else to run raw queries.</p>\n\n<h2>Explanation</h2>\n\n<p><code>wpdb->query()</code> <a href=\"https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/wp-db.php#L1924\" rel=\"nofollow noreferrer\">uses</a> the <a href=\"http://php.net/manual/en/function.mysql-query.php\" rel=\"nofollow noreferrer\"><code>mysql_query()</code></a> function. From PHP manual:</p>\n\n<blockquote>\n <p>mysql_query() sends a unique query (<strong>multiple queries are not supported</strong>) to the currently active database on the server that's associated with the specified link_identifier.</p>\n</blockquote>\n\n<p>In order for that to work, <code>wpdb</code> would have to use <a href=\"http://php.net/manual/en/mysqli.multi-query.php\" rel=\"nofollow noreferrer\"><code>mysqli_multi_query()</code></a>. But you are dealing with WordPress here: it still runs with the deprecated <code>mysql</code> extension.</p>\n\n<h2>Solution 1</h2>\n\n<p>I imagined that WP would have something to aid with migrations, and apparently it does: <a href=\"https://developer.wordpress.org/reference/functions/dbdelta/\" rel=\"nofollow noreferrer\"><code>dbDelta()</code></a>. This is a 438-line-long monster, so I will save you some time:</p>\n\n<p>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 <code>true</code>. 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 <a href=\"https://codex.wordpress.org/Database_Description#Multisite_Table_Overview\" rel=\"nofollow noreferrer\">global tables</a>. 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. <strong>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</strong>.</p>\n\n<p>If you thought that you can use <a href=\"https://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">IoC</a> and pass the <code>wpdb</code> object to your cool standardized interface implementation, then you're out of luck.</p>\n\n<h2>Solution 2</h2>\n\n<p>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 <code>wpdb</code> (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 <code>dbDelta()</code>, it's probably more reliable to find a way to run raw queries.</p>\n\n<ul>\n<li><code>mysqli_multi_query()</code> is a function of the <code>mysqli</code> (not outdated) extension that can easily run multiple statements at once.</li>\n<li><a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\"><code>PDO</code></a> can run multiple queries in <a href=\"https://phpdelusions.net/pdo#emulation\" rel=\"nofollow noreferrer\">emulation mode</a>.</li>\n</ul>\n"
},
{
"answer_id": 305118,
"author": "Jiwan",
"author_id": 143440,
"author_profile": "https://wordpress.stackexchange.com/users/143440",
"pm_score": 0,
"selected": false,
"text": "<p>Declare your table name in a variable.</p>\n\n<pre>\n$tbl_name = $wpdb->prefix.'your_table_name';\n</pre>\n\n<p>Declare your field names in an array.</p>\n\n<pre>\n$fields = array(\n 'your_field1',\n 'your_field2',\n 'your_field3', \n);\n</pre>\n\n<p>Store form data in some variables.</p>\n\n<pre>\n$data1 = $_POST['your_field1'];\n$data2 = $_POST['your_field2'];\n$data3 = $_POST['your_field3'];\n</pre>\n\n<p>Store form data in a variable as array</p>\n\n<pre>\n$mydata = array( \n 'your_field1' => $data1,\n 'your_field2' => $data2,\n 'your_field3' => $data3, \n) ;\n</pre>\n\n<p>And finally call the insert query.</p>\n\n<pre>\n$wpdb->insert( $tbl_name, $mydata )\n</pre>\n\n<p>You can run the codes in foreach loop for multiple data rows.</p>\n"
},
{
"answer_id": 362839,
"author": "Aurovrata",
"author_id": 52120,
"author_profile": "https://wordpress.stackexchange.com/users/52120",
"pm_score": 1,
"selected": false,
"text": "<p>In your case you are trying to insert multiple rows in your table, so instead of doing 1 insert query for each row, you can insert all your rows using a <a href=\"https://www.tutorialspoint.com/how-to-insert-an-array-of-values-in-a-mysql-table-with-a-single-insert\" rel=\"nofollow noreferrer\">single statement</a>,</p>\n\n<pre><code>$sql = \"INSERT INTO wp_ctt_timetables (name, homework, tod, class, dow, lesson) VALUES ('', '', '', 3, 0, 0), ('', '', '', 3, 0, 1), ('', '', '', 3, 0, 2), ('', '', '', 3, 0, 3), ('', '', '', 3, 0, 4)\"; //... and so on\n$results = $wpdb->query($sql);\n</code></pre>\n\n<p>However, to answer your original question, if each of your queries are different, you can also execute the queries one after the other, </p>\n\n<pre><code>$sql = \"query 1...\";\n$results = $wpdb->query($sql);\n$sql = \"query 2...\";\n$results = $wpdb->query($sql);\n$sql = \"query 3...\";\n$results = $wpdb->query($sql);\n</code></pre>\n\n<p>this even works if you <a href=\"https://stackoverflow.com/a/18247149/3596672\">create a temporary table and use that table in a subsequent query</a>.</p>\n"
}
]
| 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 to an identifiable person who can be directly or indirectly identified in particular by reference to an identifier. This definition provides for a wide range of personal identifiers to constitute personal data, including name, identification number, location data or online identifier, reflecting changes in technology and the way organisations collect information about people.</p>\n\n<h2>What should you do as Dev?</h2>\n\n<p>Ask you self what you data will you store and is it really necessary. If you must store personal data add functions to read this data to send it to a customer (identifiable person) and also a function to remove a data for a customer. If yous tore personal data think also about encoding of the data.</p>\n\n<p>Trade consciously with the data of the customers, the visitors and think about read, remove and encoding. I mean this should think in the right direction to get a solid plugin in the topic of GDPR.</p>\n"
},
{
"answer_id": 305017,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 4,
"selected": true,
"text": "<p>Well, this has little to do with WordPress development as such, even if there is now a <a href=\"https://developer.wordpress.org/reference/functions/the_privacy_policy_link/\" rel=\"nofollow noreferrer\">special privacy function</a>, but since I´ve been writing about online privacy for over 25 years now I´ll gladly answer. Let´s take a <a href=\"https://en.wikipedia.org/wiki/General_Data_Protection_Regulation\" rel=\"nofollow noreferrer\">look at the principles</a>:</p>\n<ol>\n<li><p>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.</p>\n</li>\n<li><p>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.</p>\n</li>\n<li><p>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.</p>\n</li>\n<li><p>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.</p>\n</li>\n<li><p>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.</p>\n</li>\n<li><p>Data protection officer and breaches. Not your responsibility.</p>\n</li>\n</ol>\n<p>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.</p>\n<p><strong>Update</strong>: Sample texts</p>\n<ul>\n<li>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].</li>\n<li>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.</li>\n</ul>\n"
},
{
"answer_id": 306688,
"author": "Maria Filina",
"author_id": 145706,
"author_profile": "https://wordpress.stackexchange.com/users/145706",
"pm_score": 1,
"selected": false,
"text": "<p>According to GDPR rules you need to receive explicit, positive consent from users to collect, process and use their personal data (name, phone number, email address, payment data, etc).</p>\n\n<hr>\n\n<p>So, for web forms you need:</p>\n\n<ul>\n<li>ask for consent of using personal data;</li>\n<li>add double op-in;</li>\n<li>add an acknowledgement check-box at the end of the form.</li>\n</ul>\n\n<hr>\n\n<p>These steps help your plugin to be GDPR compliant. \nAlso, here is a <a href=\"https://qawerk.com/blogs/gdpr-compliance-checklist-outsourcing-companies/\" rel=\"nofollow noreferrer\">GDPR compliance checklist</a> created by the company I work for which you can use in other projects. </p>\n"
},
{
"answer_id": 383252,
"author": "SagarG",
"author_id": 159774,
"author_profile": "https://wordpress.stackexchange.com/users/159774",
"pm_score": 0,
"selected": false,
"text": "<p>GDPR rules in brief:</p>\n<ol>\n<li>Ask for the users' consent</li>\n<li>Save their consent</li>\n<li>Let the users know what data you are saving and why is it necessary before they provide you their consent so that they can decide</li>\n<li>Users' should be able to delete their saved data if they want at any time</li>\n<li>Users' should also be able to download their data before deleting it</li>\n</ol>\n<p>and the most important one..</p>\n<ol start=\"6\">\n<li>Never save their credit card information and also let the users' know about this by mentioning it in a disclaimer</li>\n</ol>\n<p>Hope this helps.</p>\n"
}
]
| 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>$locations = get_theme_mod('nav_menu_locations');\n$locations['primary-menu'] = $term_id_of_menu;\nset_theme_mod( 'nav_menu_locations', $locations );\n</code></pre>\n\n<p>Source: <a href=\"https://stackoverflow.com/a/19637827/7243209\">https://stackoverflow.com/a/19637827/7243209</a></p>\n"
},
{
"answer_id": 305081,
"author": "Kenny Wyland",
"author_id": 112418,
"author_profile": "https://wordpress.stackexchange.com/users/112418",
"pm_score": 3,
"selected": false,
"text": "<p>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 <code>var_export()</code> on the variable being passed in) and saw it was calling <code>set_theme_mod( 'nav_menu_locations', $menu_locations );</code>. I've updated my code to use this and it seems to be working:</p>\n\n<pre><code>$locations = get_theme_mod('nav_menu_locations');\n$locations['primary'] = $menu_id;\nset_theme_mod( 'nav_menu_locations', $locations );\n</code></pre>\n\n<p>One of the things that threw me off when I was trying to figure out how to do this is that the documentation for <code>get_theme_mod()</code> 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. </p>\n"
}
]
| 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 website and all incoming traffic from all over the world. Firewalls monitor your website traffic and blocks many common security threats before they reach your WordPress site.</p>\n\n<p>There are two type of firewall protection available for WP site.\n1) DNS Level Website Firewall\n2) Application Level Firewall </p>\n\n<p>Now let me give brief how are they different from one another.\n<strong>DNS Level Website Firewall</strong> – These firewall route your website traffic through their cloud proxy servers. This allows them to only send genuine traffic to your web server.</p>\n\n<p><strong>Application Level Firewall</strong> – These firewall examine the traffic once it reaches your server but before loading most WordPress scripts. This method is not as efficient as DNS level firewall in reducing the server load.</p>\n\n<p>and finally i recommend using a DNS level firewall because they are exceptionally good at identifying genuine website traffic vs bad requests</p>\n"
},
{
"answer_id": 305111,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 1,
"selected": false,
"text": "<p>There is no \"WordPress Firewall\".</p>\n\n<p>A <a href=\"https://en.wikipedia.org/wiki/Firewall_(computing)\" rel=\"nofollow noreferrer\">firewall</a> acts either on the network or on the host, never on a later stage such as a specific software running on a server. </p>\n\n<p>Everything that claims to be a firewall specific for WordPress is a scam. See the linked Wikipedia article for the details.</p>\n"
}
]
| 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 is hook into the <code>after_switch_theme</code> hook and see if the <code>$old_name</code> is DahTheme. If it is, that means that the current theme isn't DahTheme, so you want to deactivate the plugin.</p>\n\n<pre><code>function wpse_after_switch_theme( $old_name, $old_theme ) {\n if( 'DahTheme' === $old_name ) {\n //* You may or may not need to include wp-admin/includes/plugin.php here\n deactivate_plugins( 'dahplugin/dahplugin.php' );\n }\n}\nadd_action( 'after_switch_theme', 'wpse_after_switch_theme', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 305134,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>This entire approach is backwards. The problem is not deactivating on theme switch, but making sure the plugin isn't available unless the theme it was built for is active.</p>\n\n<p>So, the check should be in the plugin, not the theme</p>\n\n<p>So lets start by figuring out which theme is active, we can do this via <code>wp_get_theme</code> <a href=\"https://developer.wordpress.org/reference/functions/wp_get_theme/\" rel=\"nofollow noreferrer\">documented here</a> </p>\n\n<p>We then Register a hook in our plugin on <code>admin_init</code>:</p>\n\n<pre><code>add_action( 'admin_init', function() {\n $theme = wp_get_theme();\n} );\n</code></pre>\n\n<p>Then, if the theme isn't the intended theme, deactivate:</p>\n\n<pre><code>if ( $theme->headers['name'] !== 'DahTheme' ) {\n deactivate_plugins( plugin_basename( __FILE__ ) );\n}\n</code></pre>\n\n<p>Notice that deactivate_plugins is plural, and it requires an absolute path. Because of the use of <code>__FILE__</code>, this check must be in the main plugin file.</p>\n\n<hr>\n\n<p>Although, this complicates things when switching back to 'DahTheme' as now the plugin is inactive, so it would be better to do the check then return early, so the plugin does nothing, rather than deactivating. This way no customizer options are presented for incompatible themes, and no issues happen when the user previews themes or switches back</p>\n"
},
{
"answer_id": 305934,
"author": "tsquez",
"author_id": 65047,
"author_profile": "https://wordpress.stackexchange.com/users/65047",
"pm_score": 0,
"selected": false,
"text": "<p>I basically solved this issue by using <code>is_plugin_active</code> - before I was loading additional panels and sections with the plugin and when someone chose another theme the <code>customize register</code> created by the plugin was still there was still there and when they went into the new themes customizer, a fatal error was generated.</p>\n\n<p>This corrected the issue.</p>\n"
},
{
"answer_id": 352564,
"author": "Deepak Rajpal",
"author_id": 28526,
"author_profile": "https://wordpress.stackexchange.com/users/28526",
"pm_score": 0,
"selected": false,
"text": "<p>This is not exactly the answer to the asked question. However, this will be helpful for many <strong>who are looking to perform certain action after activation or deactivation of themes</strong>. </p>\n\n<pre><code>// Perform action when your theme is deactivated (actually switched to another)\nadd_action( 'switch_theme', 'action_switch_theme', 10, 1 ); \nfunction action_switch_theme( ) { \n // deactivate your plugin\n}; \n\n// Perform action after your theme is activated (switched from other theme)\nadd_action( 'after_switch_theme', 'action_after_switch_theme', 10, 1 ); \nfunction action_after_switch_theme( ) { \n // activate your plugin\n}; \n</code></pre>\n"
}
]
| 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 string, dynamic or not, to HTML, you\n should also escape it with esc_html and so, even if it's just a string\n being output, you should use esc_html_e?</p>\n</blockquote>\n\n<p>Yes and no. If you want to allow the HTML to be shown in there, then you don’t have to escape it. But if you want to be more secure and be certain that no HTML will be shown, then yes - you can do the escaping.</p>\n\n<p>This “static string” is translated, so it’s not static anymore. Translators can put anything as translation. And even worse - you can use <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext\" rel=\"nofollow noreferrer\"><code>gettext</code></a> filter to modify it, so not only translators, but also any plugin or theme can change that text...</p>\n\n<p>It’s not so important with <code>esc_html</code>, but it starts to be, when you’ll take a look at <code>esc_attr</code> - translators can easily break your site putting wrong characters in string that is printed as HTML attribute.</p>\n"
},
{
"answer_id": 305171,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>You should always escape output. end of sentence, and end of story.</p>\n\n<p>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.</p>\n\n<p>Going down from the theoretical to the practical, it is not true that <code>__</code> 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 <strong>meant</strong> to supply an easy way to override a string to any other string, a string you might have no idea about its content.</p>\n\n<p>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.</p>\n\n<p>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. </p>\n\n<p>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. </p>\n"
},
{
"answer_id": 305705,
"author": "Tim",
"author_id": 48306,
"author_profile": "https://wordpress.stackexchange.com/users/48306",
"pm_score": 2,
"selected": false,
"text": "<p>Your argument appears to be that \"Product\" will always be \"Product\". As others have pointed out, this is not the case because (1) it may print a translation, and (2) it can be altered by filters in your theme or any plugin you have installed.</p>\n\n<p>On the first point: Translator content should not be considered trusted (in my opinion) and so you should ALWAYS (when possible*) escape any localised string. Even if you trust your translators personally, they could innocently enter text that would break your web page if left unescaped.</p>\n\n<p>So to your original question \"Is this a correct usage of esc_html_e?\" </p>\n\n<p><em>Yes it is absolutely correct for both your examples.</em></p>\n\n<p>If you're really worried that <code>esc_html</code> is overkill (presumably you're concerned about performance) you should at least use PHP's native <a href=\"http://php.net/manual/en/function.htmlspecialchars.php\" rel=\"nofollow noreferrer\">htmlspecialchars function</a>. I'll probably get lynched for suggesting that, because it's not best practice from a WordPress perspective. (you'll miss out on various other filters and character set checks).</p>\n\n<hr>\n\n<p>* There is another case worth discussing here:</p>\n\n<p>If the translation is <strong>intended to contain HTML</strong>, like <a href=\"https://translate.wordpress.org/projects/wp/dev/en-gb/default?filters%5Bstatus%5D=either&filters%5Boriginal_id%5D=146&filters%5Btranslation_id%5D=27460185\" rel=\"nofollow noreferrer\">this example</a> then you will often see authors printing unescaped strings. Ideally untrusted HTML should be sanitized before printing, but even the WordPress core does not do this.</p>\n\n<p>Sanitizing HTML carries a bigger overhead than simply escaping it, which possibly explains why even WordPress has examples of unescaped HTML translations. <a href=\"https://github.com/WordPress/twentyseventeen/blob/master/search.php#L19\" rel=\"nofollow noreferrer\">Here's one in twenty seventeen</a>. Presumably the user-provided search query in <code>%s</code> has been sanitized, but the translation hasn't. Open up your favourite PO editor and enter a translation like this:</p>\n\n<pre><code>#: search.php:19\nmsgid \"Search Results for: %s\"\nmsgstr \"Oh dear <script>alert(\\\"HACKED\\\")</script>\"\n</code></pre>\n\n<p>Voila. Script injected into search results page. Try it. This actually works in twentyseventeen.</p>\n\n<p>We can argue all day whether translator content should be trusted. I'd argue that it isn't. A stray, but perfectly innocent <code>\"<\"</code> could break your page.</p>\n"
}
]
| 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>\n\n<p>If you want to check if $embed is empty, just check it:</p>\n\n<pre><code>if ( ! trim($embed) ) {\n // it’s empty\n}\n</code></pre>\n\n<p>If you want to check if the $url is empty:</p>\n\n<pre><code>if ( ! trim($url) ) {\n // it’s empty\n}\n</code></pre>\n"
},
{
"answer_id": 305170,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>The <a href=\"https://codex.wordpress.org/Function_Reference/wp_oembed_get\" rel=\"nofollow noreferrer\"><code>wp_oembed_get()</code> </a> only works for supported oEmbed providers. The return value is also is a URL of false, as mentioned per codex:</p>\n\n<blockquote>\n <p>If $url is a valid url to a supported provider, the function returns\n the embed code provided to it from the oEmbed protocol. Otherwise, it\n will return false.</p>\n</blockquote>\n\n<p>Therefore, is the input is empty, the return value would be false, so you could simply check:</p>\n\n<pre><code>if ( $embed ) {\n // Valid\n}\n</code></pre>\n"
}
]
| 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=\"nofollow noreferrer\"><code>the_content</code></a> <a href=\"https://codex.wordpress.org/Plugin_API/Hooks\" rel=\"nofollow noreferrer\">filter</a>, to literally filter the content into your structure. </p>\n\n<p>Somthing like this</p>\n\n<pre><code><?php\nadd_filter('the_content',function($the_content){\n // find blockquotes\n $regex = '/<blockquote>(.+?)<\\/blockquote>([\\n|$])/i';\n $blockquotes = preg_match_all($regex,$the_content,$matches);\n\n // remove blockquotes\n $main_content = preg_replace($regex,'',$the_content);\n\n // rebuild blockqoutes\n $my_blockquotes = '';\n foreach ($matches[1] as $blockquote) {\n $my_blockquotes .= \"<blockquote>{$blockquote}</blockquote>\";\n }\n\n // rebuild content\n $new_content = '';\n if (!empty($my_blockquotes)) {\n $new_content = \"\n <div class='my-blockquotes'>\n {$my_blockquotes}\n </div>\\n\";\n }\n $new_content .= \"\n <div class='main-content'>\n {$main_content}\n </div>\\n\";\n\n return $new_content;\n});\n</code></pre>\n\n<p>but you'll notice this still might feel a little <em>hacky</em> as you're separating user-supplied content where unexpected user error can still happen. For example: line-breaks may be inconsistent between blockquotes. </p>\n\n<p>You'd be better off creating <a href=\"https://developer.wordpress.org/plugins/metadata/custom-meta-boxes/\" rel=\"nofollow noreferrer\">a custom metabox</a> and/or using <a href=\"https://codex.wordpress.org/Custom_Fields\" rel=\"nofollow noreferrer\">post_meta</a> 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 <code>the_content</code> still, or you can edit your template files of your theme, or hook into another action in your theme.</p>\n"
},
{
"answer_id": 305200,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 0,
"selected": false,
"text": "<p>I did something similar - in my case, I was applying a class directly on any <code>blockquote</code> tags using string replace.</p>\n\n<pre><code><?php\n$content = the_content();\n$content = str_replace( \"<blockquote>\", \"<blockquote class=\\\"quote\\\">\", $content );\necho $content;\n?>\n</code></pre>\n\n<p>Read more about string replace here: <a href=\"http://php.net/manual/en/function.str-replace.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.str-replace.php</a></p>\n"
},
{
"answer_id": 402440,
"author": "Qubical",
"author_id": 108969,
"author_profile": "https://wordpress.stackexchange.com/users/108969",
"pm_score": 0,
"selected": false,
"text": "<p>Came to this answer in my search to "rewrite" blockquotes in the_content and this in turn led me to a different solution using php domdocument functions which I'll post below for any possible help it may provide.</p>\n<pre><code>/**\n * Add tweet link to blockquotes\n */\nfunction my_blockquote_tweets( $the_content ) {\n\n global $wp;\n\n // Parse content\n $document = new DOMDocument();\n $document->loadHTML( $the_content );\n $blockquotes = $document->getElementsByTagName('blockquote');\n\n $svg = file_get_contents( get_stylesheet_directory() . '/resources/images/svg/social-logos/twitter.svg' );\n\n foreach ($blockquotes as $blockquote) {\n\n // Twitter Icon\n $twitter_svg = $document->createDocumentFragment();\n $twitter_svg->appendXML( $svg );\n\n // Icon wrapper\n $twitter_logo_wrapper = $document->createElement('span');\n $twitter_logo_wrapper->setAttribute('class', 'tweet-logo');\n $twitter_logo_wrapper->appendChild( $twitter_svg );\n\n $tweet_text = substr($blockquote->nodeValue, 0, 250);\n\n if( strlen( $tweet_text ) > 250 ) {\n $tweet_text .= ' &#8230;';\n }\n\n $tweet = $document->createElement('a');\n $tweet->setAttribute( 'class', 'tweet-this group' );\n $tweet->setAttribute( 'title', __('Tweet this quote', 'pwa') );\n $tweet->setAttribute( 'href', 'https://twitter.com/intent/tweet?text=' . urlencode( $tweet_text ) . '&url=%0A' . urlencode(home_url( $wp->request )));\n $tweet->setAttribute( 'target', '_blank' );\n\n $tweet->appendChild( $twitter_logo_wrapper );\n\n $tweet_text = $document->createTextNode( __( 'Tweet this' , 'pwa' ) );\n $tweet->appendChild( $tweet_text );\n\n $blockquote->appendChild( $tweet );\n\n }\n\n $the_content = $document->saveHtml();\n\n return $the_content;\n\n\n}\nadd_filter('the_content', 'my_blockquote_tweets', 10, 1);\n</code></pre>\n<p>Hope it help someone.</p>\n"
}
]
| 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\";\n\nupdate_post_meta($post_id, 'category', $features); \n</code></pre>\n\n<p>Is fine, it will only fail if the <code>$post_id</code> is not found.\nI'm assuming you want to save custom categories, not real WP taxonomies.</p>\n\n<p>Do you have the debug log activated? Does it tell you anything?</p>\n\n<hr>\n\n<p><strong>Activate debug log.</strong></p>\n\n<ol>\n<li><p><a href=\"https://nl.wordpress.org/plugins/wp-log-viewer/\" rel=\"nofollow noreferrer\">Download and activate a log viewer.</a></p></li>\n<li><p>Open wp-config.php (located in WP root folder), and change the line:</p>\n\n<p>define( \"WP_DEBUG\", false );</p></li>\n</ol>\n\n<p>into </p>\n\n<pre><code>define( \"WP_DEBUG\", true );// just toggle this line to false to turn off\nif ( WP_DEBUG ) {\n define( \"WP_DEBUG_DISPLAY\", false );\n define( \"WP_DEBUG_LOG\", true );\n @ini_set( \"display_errors\", 0 );\n define( \"SCRIPT_DEBUG\", true );\n}\n</code></pre>\n\n<p>You can now view error logs. Disable logging when you are done!</p>\n\n<hr>\n\n<p><strong>Working with the debug log</strong><br>\nIf (for example) you want to check the <code>$post_id</code> that is being used, you can add the following right below the <code>update_post_meta()</code>:</p>\n\n<pre><code>error_log('The post id is: '.$post_id);\n</code></pre>\n\n<p>To check an array i always use:</p>\n\n<pre><code>error_log('The features array is: <pre>'.print_r($features,true).'</pre>');\n</code></pre>\n\n<hr>\n\n<p>Regards, Bjorn</p>\n"
},
{
"answer_id": 305213,
"author": "Bjorn",
"author_id": 83707,
"author_profile": "https://wordpress.stackexchange.com/users/83707",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, so probably the meta data is saved correctly, now we are going to retrieve it.</p>\n\n<p>I'm not sure where and how you're adding this code, it looks like a metabox?</p>\n\n<p>The checkboxes aren't magicly getting checked, you need to add some logic to it.</p>\n\n<p>First we need to have a closer look how you save the checkbox data.\nWe want to save to the DB which checkboxes are checked.</p>\n\n<p>This array:</p>\n\n<pre><code>$features = array();\n$features[0] = \"star\";\n$features[1] = \"triangle\";\n$features[2] = \"square\";\n</code></pre>\n\n<p>Is not going to tell us which categories are checked.</p>\n\n<p>We want to save the array like this:</p>\n\n<pre><code>$features = array();\n$features['star'] = 1; // checked\n$features['square'] = 0; // not checked\n$features['triangle'] = 1; // checked\n</code></pre>\n\n<hr>\n\n<p>Above the checkbox HTML you need to get the features data (post_meta) from the DB.</p>\n\n<p>Add this above the html:</p>\n\n<pre><code><?php\nglobal $post;\n$features = get_post_meta( $post->ID, 'category', true );\n?>\n</code></pre>\n\n<p>When you want to check a checkbox you need to add the attribute <code>checked=\"checked\"</code> to it.\nWe only want to do this if the features array from the DB is telling us to do so.\nYou can achieve this with this checkbox html:</p>\n\n<pre><code><input type=\"checkbox\" name=\"checkbox_name\" id=\"checkbox_id\" value=\"triangle\" <?php echo (isset($features['triangle']) && $features['triangle']) ? 'checked=\"checked\"' : '' ?> />\n</code></pre>\n\n<p>This:</p>\n\n<pre><code><?php echo (isset($features['triangle']) && $features['triangle']) ? 'checked=\"checked\"' : '' ?>\n</code></pre>\n\n<p>Checks if the array key (triangle) is present in the <code>$features</code> array and if the value is set to 1 (or any positive value). If yes, it outputs <code>checked=\"checked\"</code>, if not, it does nothing.</p>\n\n<p>Regards, Bjorn</p>\n"
},
{
"answer_id": 382578,
"author": "Hermann",
"author_id": 130509,
"author_profile": "https://wordpress.stackexchange.com/users/130509",
"pm_score": 0,
"selected": false,
"text": "<p>Just set the last parameter (<code>$prev</code>) the <code>update_post_meta</code> to false, this enable you to insert new values to the <code>meta_key</code>. You can also check if the value is not already in the array before updating. Something like this.</p>\n<pre><code>// Get post met first\n// false because we want to return all the values \n// saved in the meta key 'category'\n$oldValues = get_post_meta($post_ID, "category", false);\nforeach($features as $feature){\n// Check if value is there, otherwise add it\n if (in_array($feature, $oldValues)){\n continue;\n } esle {\n update_post_meta($post_ID, "category", $feature, false);\n }\n}\n</code></pre>\n"
}
]
| 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 towards the end of <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow noreferrer\"><code>wp_nav_menu</code></a> 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.</li>\n<li>A bit more complicated is replacing the whole generation process of <code>wp_nav_menu</code> with a <a href=\"https://wordpress.stackexchange.com/questions/14037/menu-items-description-custom-walker-for-wp-nav-menu\">custom walker</a> 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.</li>\n<li>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.</li>\n</ol>\n"
},
{
"answer_id": 305248,
"author": "DHL17",
"author_id": 125227,
"author_profile": "https://wordpress.stackexchange.com/users/125227",
"pm_score": 0,
"selected": false,
"text": "<p>This is not proper approach but you can try jQuery like this to achieve desired output:</p>\n\n<pre><code>function add_li_atts_script()\n{\n?>\n<script>\n jQuery(document).ready(function(e) {\n jQuery('#menu-item-276').attr(\"data-id\",\"1\");\n jQuery('#menu-item-276').attr(\"data-slug\",\"home\"); \n });\n</script>\n<?php\n}\nadd_action('wp_head','add_li_atts_script');\n</code></pre>\n\n<p>For every new menu you need to add this 2 lines and need to give every <code>li</code> a new <code>ID</code> by default <code>wp_nav_menu</code> will generate unique <code>ID</code> for every <code>li</code> :</p>\n\n<pre><code>jQuery('#li-id').attr(\"data-id\",\"DESIRED ID\");\njQuery('#li-id').attr(\"data-slug\",\"DESIRED SLUG\");\n</code></pre>\n"
}
]
| 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<p><strong>Overloading Template Compatibility theme files</strong>\nTemplate compatibility also runs a check to see if two directories or folders exist in a theme:</p>\n\n<pre><code>'buddypress'\n'community'\n</code></pre>\n\n<p>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.</p>\n\n<p>Therefore, you can modify any bp theme compatibility template by copying it over from:</p>\n\n<pre><code>/bp-templates/bp-legacy/buddypress/\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>/my-theme/community/ or /my-theme/buddypress/\n</code></pre>\n\n<p>N.B. Inside the subfolder <code>‘community’</code> <strong>you must preserve the path structure/folders</strong> that exist in the BP original /buddypress/ folder so /activity/ must be created to hold index.php or any of the other activity templates.</p>\n\n<p>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.</p>\n\n<p>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.\n * 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.</p>\n\n<p>Source: <a href=\"https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/\" rel=\"nofollow noreferrer\">https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/</a></p>\n"
},
{
"answer_id": 332279,
"author": "Jeremy Muckel",
"author_id": 119050,
"author_profile": "https://wordpress.stackexchange.com/users/119050",
"pm_score": 2,
"selected": false,
"text": "<p>Inside your wordpress theme (hopefully a custom or child theme) create a \"buddypress\" folder.</p>\n\n<p>Then you can override files from the <code>/plugins/buddypress/bp-templates/[buddypress theme]</code> folder. But you must keep the exact same folder structure. It works with bp-nouveau also, I just checked.</p>\n\n<p>For example, if I was using a wordpress theme called \"mytheme\", and I wanted to override or add something to a single member's profile page, I would create <code>mytheme/buddypress/members/single/home.php</code></p>\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<p><strong>Overloading Template Compatibility theme files</strong>\nTemplate compatibility also runs a check to see if two directories or folders exist in a theme:</p>\n\n<pre><code>'buddypress'\n'community'\n</code></pre>\n\n<p>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.</p>\n\n<p>Therefore, you can modify any bp theme compatibility template by copying it over from:</p>\n\n<pre><code>/bp-templates/bp-legacy/buddypress/\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>/my-theme/community/ or /my-theme/buddypress/\n</code></pre>\n\n<p>N.B. Inside the subfolder <code>‘community’</code> <strong>you must preserve the path structure/folders</strong> that exist in the BP original /buddypress/ folder so /activity/ must be created to hold index.php or any of the other activity templates.</p>\n\n<p>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.</p>\n\n<p>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.\n * 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.</p>\n\n<p>Source: <a href=\"https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/\" rel=\"nofollow noreferrer\">https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/</a></p>\n"
},
{
"answer_id": 332279,
"author": "Jeremy Muckel",
"author_id": 119050,
"author_profile": "https://wordpress.stackexchange.com/users/119050",
"pm_score": 2,
"selected": false,
"text": "<p>Inside your wordpress theme (hopefully a custom or child theme) create a \"buddypress\" folder.</p>\n\n<p>Then you can override files from the <code>/plugins/buddypress/bp-templates/[buddypress theme]</code> folder. But you must keep the exact same folder structure. It works with bp-nouveau also, I just checked.</p>\n\n<p>For example, if I was using a wordpress theme called \"mytheme\", and I wanted to override or add something to a single member's profile page, I would create <code>mytheme/buddypress/members/single/home.php</code></p>\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<p><strong>Overloading Template Compatibility theme files</strong>\nTemplate compatibility also runs a check to see if two directories or folders exist in a theme:</p>\n\n<pre><code>'buddypress'\n'community'\n</code></pre>\n\n<p>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.</p>\n\n<p>Therefore, you can modify any bp theme compatibility template by copying it over from:</p>\n\n<pre><code>/bp-templates/bp-legacy/buddypress/\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>/my-theme/community/ or /my-theme/buddypress/\n</code></pre>\n\n<p>N.B. Inside the subfolder <code>‘community’</code> <strong>you must preserve the path structure/folders</strong> that exist in the BP original /buddypress/ folder so /activity/ must be created to hold index.php or any of the other activity templates.</p>\n\n<p>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.</p>\n\n<p>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.\n * 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.</p>\n\n<p>Source: <a href=\"https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/\" rel=\"nofollow noreferrer\">https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/</a></p>\n"
},
{
"answer_id": 332279,
"author": "Jeremy Muckel",
"author_id": 119050,
"author_profile": "https://wordpress.stackexchange.com/users/119050",
"pm_score": 2,
"selected": false,
"text": "<p>Inside your wordpress theme (hopefully a custom or child theme) create a \"buddypress\" folder.</p>\n\n<p>Then you can override files from the <code>/plugins/buddypress/bp-templates/[buddypress theme]</code> folder. But you must keep the exact same folder structure. It works with bp-nouveau also, I just checked.</p>\n\n<p>For example, if I was using a wordpress theme called \"mytheme\", and I wanted to override or add something to a single member's profile page, I would create <code>mytheme/buddypress/members/single/home.php</code></p>\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<p><strong>Overloading Template Compatibility theme files</strong>\nTemplate compatibility also runs a check to see if two directories or folders exist in a theme:</p>\n\n<pre><code>'buddypress'\n'community'\n</code></pre>\n\n<p>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.</p>\n\n<p>Therefore, you can modify any bp theme compatibility template by copying it over from:</p>\n\n<pre><code>/bp-templates/bp-legacy/buddypress/\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>/my-theme/community/ or /my-theme/buddypress/\n</code></pre>\n\n<p>N.B. Inside the subfolder <code>‘community’</code> <strong>you must preserve the path structure/folders</strong> that exist in the BP original /buddypress/ folder so /activity/ must be created to hold index.php or any of the other activity templates.</p>\n\n<p>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.</p>\n\n<p>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.\n * 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.</p>\n\n<p>Source: <a href=\"https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/\" rel=\"nofollow noreferrer\">https://codex.buddypress.org/themes/theme-compatibility-1-7/a-quick-look-at-1-7-theme-compatibility/</a></p>\n"
},
{
"answer_id": 332279,
"author": "Jeremy Muckel",
"author_id": 119050,
"author_profile": "https://wordpress.stackexchange.com/users/119050",
"pm_score": 2,
"selected": false,
"text": "<p>Inside your wordpress theme (hopefully a custom or child theme) create a \"buddypress\" folder.</p>\n\n<p>Then you can override files from the <code>/plugins/buddypress/bp-templates/[buddypress theme]</code> folder. But you must keep the exact same folder structure. It works with bp-nouveau also, I just checked.</p>\n\n<p>For example, if I was using a wordpress theme called \"mytheme\", and I wanted to override or add something to a single member's profile page, I would create <code>mytheme/buddypress/members/single/home.php</code></p>\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>In functions.php of the child theme I've added this to cancel that function : </p>\n\n<pre><code>add_action( 'after_setup_theme', 'remove_featured_images_from_child_theme', 11 ); \nfunction remove_featured_images_from_child_theme() {\n remove_theme_support( 'title-tag' );\n}\n</code></pre>\n\n<p>Then I've added this to header.php : </p>\n\n<pre><code><title><?php wp_title(''); ?></title>\n</code></pre>\n\n<p>With this two snippets of code the wp_title filter works fine.</p>\n\n<p>But I think this is not the right way since WP recommands to use add_theme_support('title-tag'), but I'm disabling it !</p>\n"
},
{
"answer_id": 305548,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": false,
"text": "<p>When adding <code>title-tag</code> support in a theme, the title tag can be filtered by several filters, but not <code>wp_title</code>. The reason is that if the theme supports <code>title-tag</code>, WordPress uses <a href=\"https://developer.wordpress.org/reference/functions/wp_get_document_title/\" rel=\"noreferrer\"><code>wp_get_document_title()</code></a> instead of <a href=\"https://developer.wordpress.org/reference/functions/wp_title/\" rel=\"noreferrer\"><code>wp_title()</code></a>.</p>\n\n<p>For themes with support for <code>title-tag</code> you can use <a href=\"https://developer.wordpress.org/reference/hooks/document_title_parts/\" rel=\"noreferrer\"><code>document_title_parts</code></a>:</p>\n\n<pre><code>add_filter( 'document_title_parts', 'filter_document_title_parts' );\nfunction filter_document_title_parts( $title_parts ) {\n\n $title_parts['title'] = 'The title'; \n $title_parts['tagline'] = 'A tagline';\n $title_parts['site'] = 'My Site';\n\n return $title_parts; \n\n}\n</code></pre>\n\n<p>Or <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_document_title/\" rel=\"noreferrer\"><code>pre_get_document_title</code></a>:</p>\n\n<pre><code>add_filter( 'pre_get_document_title', 'filter_document_title' );\nfunction filter_document_title( $title ) {\n\n $title = 'The title'; \n\n return $title; \n\n}\n</code></pre>\n"
}
]
| 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><code>// if matched...\nremove_filter( 'nav_menu_css_class', 'highlight_base_category', 1, 3 );\n</code></pre>\n"
},
{
"answer_id": 305366,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the answer by Chris J Allen, if you want to remove all filters including those not added by your plugin/theme, you would use <a href=\"https://developer.wordpress.org/reference/func\" rel=\"nofollow noreferrer\"><code>remove_all_filters()</code></a> instead of <code>remove_filter()</code>.</p>\n\n<pre><code>add_filter( 'nav_menu_css_class', 'wpse_nav_menu_css_class', 1, 4 );\nfunction wpse_nav_menu_css_class( $classes, $item, $args, $depth ) {\n //* Do something useful to the nav menu CSS class\n $classes[] = 'highlight';\n\n //* Make sure no other filters modify the classes\n remove_all_filters( 'nav_menu_css_class' );\n return $classes;\n}\n</code></pre>\n"
},
{
"answer_id": 305375,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>Yes, there is such way. All you need to do is to unregister your filter inside it:</p>\n\n<pre><code>function highlight_base_category( $classes, $item, $args ) {\n // most probably you have some if statement here\n if ( /* YOU CONDITION */ ) { \n // your code\n remove_filter( 'nav_menu_css_class', 'highlight_base_category', 1 );\n }\n return $classes;\n}\nadd_filter( 'nav_menu_css_class', 'highlight_base_category', 1, 3 );\n</code></pre>\n"
}
]
| 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_rules = array(\n '(.?.+?)/page/?([0-9]{1,})/?$' => 'index.php?pagename=$matches[1]&paged=$matches[2]',\n 'blog/([^/]+)/?$' => 'index.php?post_type=post&name=$matches[1]',\n 'blog/[^/]+/attachment/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]',\n 'blog/[^/]+/attachment/([^/]+)/trackback/?$' => 'index.php?post_type=post&attachment=$matches[1]&tb=1',\n 'blog/[^/]+/attachment/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',\n 'blog/[^/]+/attachment/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',\n 'blog/[^/]+/attachment/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&attachment=$matches[1]&cpage=$matches[2]', \n 'blog/[^/]+/attachment/([^/]+)/embed/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',\n 'blog/[^/]+/embed/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',\n 'blog/([^/]+)/embed/?$' => 'index.php?post_type=post&name=$matches[1]&embed=true',\n 'blog/[^/]+/([^/]+)/embed/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',\n 'blog/([^/]+)/trackback/?$' => 'index.php?post_type=post&name=$matches[1]&tb=1',\n 'blog/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&name=$matches[1]&feed=$matches[2]',\n 'blog/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&name=$matches[1]&feed=$matches[2]',\n 'blog/page/([0-9]{1,})/?$' => 'index.php?post_type=post&paged=$matches[1]',\n 'blog/[^/]+/page/?([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&paged=$matches[2]',\n 'blog/([^/]+)/page/?([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&paged=$matches[2]',\n 'blog/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&cpage=$matches[2]',\n 'blog/([^/]+)(/[0-9]+)?/?$' => 'index.php?post_type=post&name=$matches[1]&page=$matches[2]',\n 'blog/[^/]+/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]',\n 'blog/[^/]+/([^/]+)/trackback/?$' => 'index.php?post_type=post&attachment=$matches[1]&tb=1',\n 'blog/[^/]+/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',\n 'blog/[^/]+/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',\n 'blog/[^/]+/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&attachment=$matches[1]&cpage=$matches[2]',\n );\n $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;\n }\n add_action( 'generate_rewrite_rules', 'generate_rewrite_rules' );\n\n function update_post_link( $post_link, $id = 0 ) {\n $post = get_post( $id );\n if( is_object( $post ) && $post->post_type == 'post' ) {\n return home_url( '/blog/' . $post->post_name );\n }\n return $post_link;\n }\n add_filter( 'post_link', 'update_post_link', 1, 3 );\n</code></pre>\n"
},
{
"answer_id": 359523,
"author": "Harshal Solanki",
"author_id": 183393,
"author_profile": "https://wordpress.stackexchange.com/users/183393",
"pm_score": 0,
"selected": false,
"text": "<pre class=\"lang-php prettyprint-override\"><code>//Place code in function.php \nadd_action('init', 'my_new_default_post_type', 1); \nfunction my_new_default_post_type() \n{ \n register_post_type('post', array(\n // 'labels' => $labels, \n 'public' => true, \n //'show_in_admin_bar' => true,\n '_builtin' => false, \n '_edit_link' => 'post.php?post=%d', \n 'capability_type' => 'post', \n 'map_meta_cap' => true, \n 'hierarchical' => false, \n 'rewrite' => array('slug' => 'resources/blog'), // Add your slug here \n 'query_var' => false, \n 'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats'),\n )); \n /* If you add above code in function.php, Your blog pagination is stopped to working, You need to add rewrite rule using "Debug This" Plugin under Query >> Rewrite Section & modify your rewrite_rule. */ \n add_rewrite_rule('(.?.+?)/page/?([0-9]{1,})/?$', 'index.php?pagename=resources/blog&paged=$matches[1]', 'top');\n}\n\n</code></pre>\n"
},
{
"answer_id": 359526,
"author": "Zeth",
"author_id": 128304,
"author_profile": "https://wordpress.stackexchange.com/users/128304",
"pm_score": 2,
"selected": false,
"text": "<p>I found the answer <a href=\"https://wordpress.stackexchange.com/a/230313/128304\">here</a>. Remember to pop in there and give it a like. </p>\n\n<p>I'll post it here, for people in a rush.</p>\n\n<hr>\n\n<p>Put this into the <code>functions.php</code>-file:</p>\n\n<pre><code>function wp1482371_custom_post_type_args( $args, $post_type ) {\n if ( $post_type == \"post\" ) {\n $args['rewrite'] = array(\n 'slug' => 'blog'\n );\n }\n\n return $args;\n}\nadd_filter( 'register_post_type_args', 'wp1482371_custom_post_type_args', 20, 2 );\n</code></pre>\n\n<p>(Tested and works). </p>\n\n<p><em>Remember!!</em></p>\n\n<p><strong>Remember A)</strong> Remember to update your permalinks afterwards (by going into <strong>Settings</strong> >> <strong>Permalinks</strong> >> <strong>Click 'Save Changes'</strong> ).</p>\n\n<p><strong>Remember B)</strong> If you get wierd results, then try opening an incognito-window and see if it words there. WordPress has a feature that redirects to '<a href=\"http://biostall.com/prevent-wordpress-redirecting-to-nearest-matching-url/\" rel=\"nofollow noreferrer\">Nearest Matching URL</a>', that can seem confusing, when playing around with permalinks.</p>\n\n<hr>\n\n<p>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). </p>\n"
}
]
| 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\">\n <input type=\"hidden\" name=\"page\" value=\"<?php echo $_REQUEST['page'] ?>\" />\n <?php\n $this->customers_obj->prepare_items();\n $this->customers_obj->search_box('Search', 'search');\n $this->customers_obj->display(); ?>\n</form>\n</code></pre>\n"
},
{
"answer_id": 374405,
"author": "Rohit Sharma",
"author_id": 148561,
"author_profile": "https://wordpress.stackexchange.com/users/148561",
"pm_score": 1,
"selected": false,
"text": "<p>I have achieved this by cloning the pagination function of WP List Table and added search variable in url. Following is the code for same.</p>\n<p>protected function pagination( $which ) {\nif ( empty( $this->_pagination_args ) ) {\nreturn;\n}</p>\n<pre><code> $total_items = $this->_pagination_args['total_items'];\n $total_pages = $this->_pagination_args['total_pages'];\n $infinite_scroll = false;\n\n if ( isset( $this->_pagination_args['infinite_scroll'] ) ) {\n $infinite_scroll = $this->_pagination_args['infinite_scroll'];\n }\n\n if ( 'top' === $which && $total_pages > 1 ) {\n $this->screen->render_screen_reader_content( 'heading_pagination' );\n }\n\n $output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items ), number_format_i18n( $total_items ) ) . '</span>';\n\n $current = $this->get_pagenum();\n $removable_query_args = wp_removable_query_args();\n\n $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );\n\n $current_url = remove_query_arg( $removable_query_args, $current_url );\n\n if( isset($_REQUEST['s'] ) ){\n $current_url = add_query_arg( 's', $_REQUEST['s'], $current_url );\n }\n\n $page_links = array();\n\n $total_pages_before = '<span class="paging-input">';\n $total_pages_after = '</span></span>';\n\n $disable_first = $disable_last = $disable_prev = $disable_next = false;\n\n if ( $current == 1 ) {\n $disable_first = true;\n $disable_prev = true;\n }\n if ( $current == 2 ) {\n $disable_first = true;\n }\n if ( $current == $total_pages ) {\n $disable_last = true;\n $disable_next = true;\n }\n if ( $current == $total_pages - 1 ) {\n $disable_last = true;\n }\n\n if ( $disable_first ) {\n $page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">&laquo;</span>';\n } else {\n $page_links[] = sprintf(\n "<a class='first-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",\n esc_url( remove_query_arg( 'paged', $current_url ) ),\n __( 'First page' ),\n '&laquo;'\n );\n }\n\n if ( $disable_prev ) {\n $page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">&lsaquo;</span>';\n } else {\n $page_links[] = sprintf(\n "<a class='prev-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",\n esc_url( add_query_arg( 'paged', max( 1, $current - 1 ), $current_url ) ),\n __( 'Previous page' ),\n '&lsaquo;'\n );\n }\n\n if ( 'bottom' === $which ) {\n $html_current_page = $current;\n $total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';\n } else {\n $html_current_page = sprintf(\n "%s<input class='current-page' id='current-page-selector' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",\n '<label for="current-page-selector" class="screen-reader-text">' . __( 'Current Page' ) . '</label>',\n $current,\n strlen( $total_pages )\n );\n }\n $html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );\n $page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging' ), $html_current_page, $html_total_pages ) . $total_pages_after;\n\n if ( $disable_next ) {\n $page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">&rsaquo;</span>';\n } else {\n $page_links[] = sprintf(\n "<a class='next-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",\n esc_url( add_query_arg( 'paged', min( $total_pages, $current + 1 ), $current_url ) ),\n __( 'Next page' ),\n '&rsaquo;'\n );\n }\n\n if ( $disable_last ) {\n $page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">&raquo;</span>';\n } else {\n $page_links[] = sprintf(\n "<a class='last-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",\n esc_url( add_query_arg( 'paged', $total_pages, $current_url ) ),\n __( 'Last page' ),\n '&raquo;'\n );\n }\n\n $pagination_links_class = 'pagination-links';\n if ( ! empty( $infinite_scroll ) ) {\n $pagination_links_class .= ' hide-if-js';\n }\n $output .= "\\n<span class='$pagination_links_class'>" . join( "\\n", $page_links ) . '</span>';\n\n if ( $total_pages ) {\n $page_class = $total_pages < 2 ? ' one-page' : '';\n } else {\n $page_class = ' no-pages';\n }\n\n $this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";\n echo $this->_pagination;\n}\n</code></pre>\n"
}
]
| 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>Changing text that is going to be translated is not. Try using a plugin such as <a href=\"https://wordpress.org/plugins/loco-translate/\" rel=\"nofollow noreferrer\">Loco translate</a>, you should be able to overwrite that message with it.</p>\n"
},
{
"answer_id": 305430,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": false,
"text": "<p>There is a filter you can use, but it is well hidden. Take a look at the <a href=\"https://developer.wordpress.org/reference/functions/__/\" rel=\"nofollow noreferrer\">WordPress function <code>__</code></a>. As you can see it calls another function, <a href=\"https://developer.wordpress.org/reference/functions/translate/\" rel=\"nofollow noreferrer\"><code>translate</code></a>. And there it is, a filter called <code>gettext</code>. You can use it to intercept any (translated) text that is run through <code>__</code>.</p>\n\n<p>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:</p>\n\n<pre><code>add_filter ('gettext','wpse305425_change_string',10,3);\nfunction wpse305425_change_string ($translation, $text, $domain) {\n if ($text == 'I consent to ...') $translation = 'your text';\n return $translation;\n }\n</code></pre>\n"
}
]
| 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>Changing text that is going to be translated is not. Try using a plugin such as <a href=\"https://wordpress.org/plugins/loco-translate/\" rel=\"nofollow noreferrer\">Loco translate</a>, you should be able to overwrite that message with it.</p>\n"
},
{
"answer_id": 305430,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": false,
"text": "<p>There is a filter you can use, but it is well hidden. Take a look at the <a href=\"https://developer.wordpress.org/reference/functions/__/\" rel=\"nofollow noreferrer\">WordPress function <code>__</code></a>. As you can see it calls another function, <a href=\"https://developer.wordpress.org/reference/functions/translate/\" rel=\"nofollow noreferrer\"><code>translate</code></a>. And there it is, a filter called <code>gettext</code>. You can use it to intercept any (translated) text that is run through <code>__</code>.</p>\n\n<p>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:</p>\n\n<pre><code>add_filter ('gettext','wpse305425_change_string',10,3);\nfunction wpse305425_change_string ($translation, $text, $domain) {\n if ($text == 'I consent to ...') $translation = 'your text';\n return $translation;\n }\n</code></pre>\n"
}
]
| 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 custom_query_vars( $vars ) {\n $vars[] = 'earnings';\n return $vars;\n}\nadd_filter( 'query_vars', 'custom_query_vars', 0 );\n</code></pre>\n"
},
{
"answer_id": 380084,
"author": "peroks",
"author_id": 199168,
"author_profile": "https://wordpress.stackexchange.com/users/199168",
"pm_score": 1,
"selected": false,
"text": "<p>Try adding this code to your add_action 'init' function.</p>\n<pre><code>// Let WooCommerce add a new custom endpoint "earnings" for you\nadd_filter( 'woocommerce_get_query_vars', function( $vars ) {\n $vars['earnings'] = 'earnings';\n return $vars;\n} );\n\n// Add "earnings" to the WooCommerce account menu\nadd_filter( 'woocommerce_account_menu_items', function( $items ) {\n $items['earnings'] = __( 'My earnings', 'your-text-domain' );\n return $items;\n} );\n\n// Display your custom title on the new endpoint page\n// Pattern: woocommerce_endpoint_{$your_endpoint}_title\nadd_filter( 'woocommerce_endpoint_earnings_title', function( $title ) {\n return __( 'My earnings', 'your-text-domain' );\n} );\n\n// Display your custom content on the new endpoint page\n// Pattern: woocommerce_account_{$your_endpoint}_endpoint\nadd_action( 'woocommerce_account_earnings_endpoint', function() {\n echo __( 'Hello World', 'your-text-domain' );\n} );\n\n// Only for testing, REMOVE afterwards!\nflush_rewrite_rules();\n</code></pre>\n"
}
]
| 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://example.com/index.php/...../posts</code></p>\n\n<p>It's the problem of your server. Your server doesn't support that because you're may using <code>Lightpd</code> server.</p>\n\n<p>You can edit <code>rewrite_once</code> in lightpd.conf if it's lightpd server.\nAlso, if your server support htaccess you can add this line to rewrite url.</p>\n\n<pre><code>\"^(.+)/?$\" => \"/index.php/$1\"\n</code></pre>\n\n<p>This is for lightpd and this regex you can use for htaccess.</p>\n\n<p><strong>Update:</strong> As you've said your server support htaccess, use this code in your htaccess</p>\n\n<pre><code>Options +FollowSymLinks\nRewriteEngine On\nRewriteBase /\nRewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\\ /index.php\nRewriteRule ^index.php$ http://example.com/ [R=301,L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</code></pre>\n"
},
{
"answer_id": 305499,
"author": "maheshwaghmare",
"author_id": 52167,
"author_profile": "https://wordpress.stackexchange.com/users/52167",
"pm_score": 2,
"selected": false,
"text": "<p>You need to set the permalink structure of your website.</p>\n\n<ol>\n<li>Goto <strong>Settings > Permalink</strong>.</li>\n<li>Remove <code>index.php</code> from the <em>Custom Structure</em>.</li>\n<li>Click on <code>Save Changes</code>.</li>\n</ol>\n\n<p>It re-generate your permalink structure. And you'll be able to access the posts with <code>http://example.com/index.php/wp-json/wp/v2/posts</code></p>\n\n<p><strong>Updated:</strong></p>\n\n<p><code>.htaccess</code> code like below:</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /dev.fresh/\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /dev.fresh/index.php [L]\n</IfModule>\n\n# END WordPress\n</code></pre>\n\n<p><strong>Note: Change <code>dev.fresh</code> with your own domain.</strong></p>\n"
}
]
| 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.tinymce.com/communityQuestion?id=90661000000IiyjAAC\" rel=\"nofollow noreferrer\">https://community.tinymce.com/communityQuestion?id=90661000000IiyjAAC</a></p>\n\n<p>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.</p>\n"
},
{
"answer_id": 333265,
"author": "Chris",
"author_id": 164302,
"author_profile": "https://wordpress.stackexchange.com/users/164302",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar issue</p>\n\n<p>let doNotRemoveFormat = false;</p>\n\n<pre><code>tinymce.init({\nstyle_formats: [\n {title: 'Footer - 11px', inline: 'span', classes: 'admin-footer'},\n {title: 'Standard - 14px', inline: 'span'},\n {title: 'Heading 1 - 19px', inline: 'span', classes: 'admin-heading-1'}, \n {title: 'Heading 2 - 22px', inline: 'span', classes: 'admin-heading-2'} \n ],\nsetup: function (ed) {\n ed.on('ExecCommand', function checkListNodes (evt) {\nif (cmd === 'mceToggleFormat') {\n if(!doNotRemoveFormat) { \n let val = 'runThis|' + evt.value;\n this.execCommand('RemoveFormat', false, val);\n } else {\n doNotRemoveFormat = false;\n }\n} else if (cmd === 'RemoveFormat') {\n let value = evt.value.split(\"|\");\n if(value[0] === 'runThis') {\n doNotRemoveFormat = true;\n this.execCommand('mceToggleFormat', false, value[1])\n }\n});\n</code></pre>\n"
},
{
"answer_id": 381020,
"author": "vivalavendredi",
"author_id": 199949,
"author_profile": "https://wordpress.stackexchange.com/users/199949",
"pm_score": 2,
"selected": false,
"text": "<p>You CAN overwrite the old classes.</p>\n<p>Instead of:</p>\n<pre><code>'classes' => 'lead'\n</code></pre>\n<p>Use this:</p>\n<pre><code>'attributes' => array('class' => 'lead')\n</code></pre>\n"
}
]
| 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 take id of the post as parameter.\n<a href=\"https://codex.wordpress.org/Function_Reference/get_the_content\" rel=\"nofollow noreferrer\">here is the ref</a></p>\n\n<p>Second, in the loop, you are using has_post_thumbnail without parameter. In that case, you must use the_post() method, because it actually change the global post variable in the loop.</p>\n"
},
{
"answer_id": 305531,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Function <a href=\"https://codex.wordpress.org/Function_Reference/get_the_content\" rel=\"nofollow noreferrer\"><code>get_the_content</code></a> doesn't take <code>post_ID</code> as param. It has 2 params:</p>\n\n<ul>\n<li><code>$more_link_text</code> - (string) (optional) Content for when there is\nmore text.</li>\n<li><code>$stripteaser</code> - (boolean) (optional) Strip teaser content\nbefore the more text.</li>\n</ul>\n\n<p>So you can't use it as in your code <code>get_the_content( $p->ID );</code> - this will get content of current post and use <code>$p->ID</code> as more link text.</p>\n\n<p>So how to get the content of any post based on post ID?</p>\n\n<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/get_post_field\" rel=\"nofollow noreferrer\"><code>get_post_field</code></a> function:</p>\n\n<pre><code>echo apply_filters( 'the_content', get_post_field( 'post_content', $p->ID ) );\n</code></pre>\n"
}
]
| 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 is simply no code of your own in that sample that can be/is worth testing, therefor there isn't much to unit test.</p>\n\n<p>Lets look at the details. <code>add_filter</code> is integration with core code, <code>remove_filter</code> is integration with core code and <code>header</code> is integration with PHP core. If you remove all of those lines you are left with zero code.</p>\n\n<p>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.</p>\n\n<p>What you need here is an integration test, set a wordpress instance with your code, send an api request and inspect the result.</p>\n"
},
{
"answer_id": 412231,
"author": "Lotus",
"author_id": 37062,
"author_profile": "https://wordpress.stackexchange.com/users/37062",
"pm_score": 0,
"selected": false,
"text": "<p>If what you're indeed trying to do is to verify that the WordPress Core continues to behave correctly after future upgrades and that your hooked method is triggered and that the headers are thus set on the response, then I have a suggestion.</p>\n<p>First, you're going to want to make sure you've some way of debugging this application. I suggest breakpoints, but it looks like you're partial to print statements. Either works, but if you use print statements, then be sure to print some dummy data to verify that you can tell the difference between an empty variable or a misconfigured logging level.</p>\n<p>Given a debugging method, there's a few places to hook into. First, make sure that your "rest_api_init" hooked function is in fact being called. Print at the start of it and verify you see your message. Assuming you do, then the rabbit hole goes on.</p>\n<p>In my version of WordPress, line 494 of <code>class-wp-rest-server.php</code> has your <code>rest_pre_serve_request</code> filter being triggered. Debug that you're in fact triggering that line with your test invocation -- you should be able to print before, then see your attached function fire, and then also print after.</p>\n<p>Assuming you're hitting that line, and that your attached function is triggered, note that the rest (haha no pun intended) of that core method does not include any calls to <code>$this->send_headers(...)</code> so I assume at this point your <code>headers(...)</code> call (being core PHP code) should be working.</p>\n<p>If not, note that just above on line 474 we see <code>$headers = $result->get_headers();</code> so looking up the docs for <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_response/\" rel=\"nofollow noreferrer\">WP_Rest_Response</a> we see it extends <a href=\"https://developer.wordpress.org/reference/classes/wp_http_response/__construct/\" rel=\"nofollow noreferrer\">WP_HTTP_Response</a> which has the ability to set headers in the constructor and also directly with <a href=\"https://developer.wordpress.org/reference/classes/wp_http_response/set_headers/\" rel=\"nofollow noreferrer\">set_headers</a>. From here, you can create a middleware for your responses which set the headers for you, in a worst-case scenario.</p>\n<p>Further digging into the core file can help you understand why your <code>headers(...)</code> calls as-is do not work.</p>\n"
}
]
| 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 within your <em>wp-config.php</em> 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 ). </p>\n\n<p>My suggestion to resolving your issue is this:</p>\n\n<p>1) Open your <em>wp-config.php</em> file <br>\n2) Look for a line of code similar to the one below </p>\n\n<pre><code>define('WP_SITEURL','http://www.example.com');\n</code></pre>\n\n<p>3) delete it</p>\n\n<p>That's it! You should now be able to edit the \"Wordpress Address (URL)\" from the admin page.</p>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php</a></p>\n"
},
{
"answer_id": 306517,
"author": "Mel",
"author_id": 116916,
"author_profile": "https://wordpress.stackexchange.com/users/116916",
"pm_score": 0,
"selected": false,
"text": "<p>Oh my god, call me noob of the month... ;)</p>\n\n<p>The problem was in fact a small line of code at the bottom of the wp-config.php which I always use in my WP webs to change the content folder's name.</p>\n\n<p>I changed it and now it works.</p>\n"
}
]
| 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 within your <em>wp-config.php</em> 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 ). </p>\n\n<p>My suggestion to resolving your issue is this:</p>\n\n<p>1) Open your <em>wp-config.php</em> file <br>\n2) Look for a line of code similar to the one below </p>\n\n<pre><code>define('WP_SITEURL','http://www.example.com');\n</code></pre>\n\n<p>3) delete it</p>\n\n<p>That's it! You should now be able to edit the \"Wordpress Address (URL)\" from the admin page.</p>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Changing_The_Site_URL#Edit_wp-config.php</a></p>\n"
},
{
"answer_id": 306517,
"author": "Mel",
"author_id": 116916,
"author_profile": "https://wordpress.stackexchange.com/users/116916",
"pm_score": 0,
"selected": false,
"text": "<p>Oh my god, call me noob of the month... ;)</p>\n\n<p>The problem was in fact a small line of code at the bottom of the wp-config.php which I always use in my WP webs to change the content folder's name.</p>\n\n<p>I changed it and now it works.</p>\n"
}
]
| 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 admin side, it sounds like you want one language in the backend and another on the frontend. </p>\n\n<p>You might want to check out <a href=\"http://www.wpbeginner.com/beginners-guide/how-to-easily-create-a-multilingual-wordpress-site/\" rel=\"nofollow noreferrer\">WPBeginner's article on multi-language WordPress</a>.</p>\n\n<p>If <em>all</em> you are changing is the date language, and you are comfortable editing template, then you can <a href=\"https://stackoverflow.com/questions/4975854/translating-php-date-for-multilingual-site\">alter the date displays alone using PHP</a>. </p>\n"
},
{
"answer_id": 357192,
"author": "gardelin",
"author_id": 107666,
"author_profile": "https://wordpress.stackexchange.com/users/107666",
"pm_score": 0,
"selected": false,
"text": "<p>You can change the global site language under Settings > General, but then edit your user account to set the admin language to whatever you want for your user account. For more info reference <a href=\"https://wptavern.com/wordpress-4-7-to-introduce-user-specific-language-setting-for-the-admin\" rel=\"nofollow noreferrer\">https://wptavern.com/wordpress-4-7-to-introduce-user-specific-language-setting-for-the-admin</a></p>\n"
}
]
| 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/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a></p>\n\n<p>With this tool you can replace strings in the database.</p>\n\n<p>Upload srdb to the root and extract (example.com/srdb/_all_files).</p>\n\n<p>Then go to <a href=\"http://example.com/srdb\" rel=\"nofollow noreferrer\">http://example.com/srdb</a>.</p>\n\n<p>You should do the following replace.</p>\n\n<p>Search: example.com/wordpress<br>\nReplace by: example.com</p>\n\n<p><strong>NOTE:</strong><br>ALWAYS MAKE A FULL DATABASE BACK-UP WHEN YOU USE THIS TOOL! USE ON YOUR OWN RISK.</p>\n\n<p><strong>NOTE 2:</strong><br>\nDO NOT FORGET TO COMPLETELY REMOVE IT WHEN YOU'RE DONE!</p>\n"
},
{
"answer_id": 305806,
"author": "adam",
"author_id": 51444,
"author_profile": "https://wordpress.stackexchange.com/users/51444",
"pm_score": -1,
"selected": false,
"text": "<p>i think i have problem sorted...i forgot to alter the index.php file from</p>\n\n<p>require( dirname( <strong>FILE</strong> ) . '/wp-blog-header.php' );</p>\n\n<p>to read </p>\n\n<p>require( dirname( <strong>FILE</strong> ) . '/wordpress/wp-blog-header.php' );</p>\n"
}
]
| 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_template_part/\" rel=\"nofollow noreferrer\"><code>get_template_part()</code></a>. You can pass variables to template parts via <a href=\"https://developer.wordpress.org/reference/functions/set_query_var/\" rel=\"nofollow noreferrer\"><code>set_query_var()</code></a>.</p>\n"
},
{
"answer_id": 305636,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress allows you to chop up template files into chunks that then can be included into the main template using <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\"><code>get_template_part</code></a>. So you could isolate your template for the ACF-field in a separate file and call that from any other template.</p>\n\n<p>Beware that it is not directly possible to pass variables from the main template to the template part, though <a href=\"https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part\">there are bypasses</a>.</p>\n"
},
{
"answer_id": 305640,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>And to add to previous answers, you can not only use <code>get_template_part</code>, but also use it's second param and combine it with ACFs <code>get_row_layout</code>.</p>\n\n<p>So let's say that somewhere in your template is:</p>\n\n<pre><code><?php while ( have_posts() ) : the_post(); ?>\n<article>\n ... SOME CODE\n\n <?php while ( have_rows( 'YOUR_FIELD_NAME' ) ) : the_row(); ?>\n ... HERE SHOULD GO THE CODE FOR ACF FIELD\n <?php endwhile; ?>\n\n ... SOME OTHER CODE\n</article>\n<?php endwhile; ?>\n</code></pre>\n\n<p>You can change it to:</p>\n\n<pre><code><?php while ( have_posts() ) : the_post(); ?>\n<article>\n ... SOME CODE\n\n <?php\n while ( have_rows( 'YOUR_FIELD_NAME' ) ) :\n the_row();\n get_template_part( 'block', get_row_layout() );\n\n endwhile;\n ?>\n\n ... SOME OTHER CODE\n</article>\n<?php endwhile; ?>\n</code></pre>\n\n<p>Then you can create your custom templates named: <code>block.php</code> (it will be used as fallback), <code>block-layout_1.php</code> (it will be used for layout called \"layout_1\", and so on.</p>\n"
}
]
| 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_template_part/\" rel=\"nofollow noreferrer\"><code>get_template_part()</code></a>. You can pass variables to template parts via <a href=\"https://developer.wordpress.org/reference/functions/set_query_var/\" rel=\"nofollow noreferrer\"><code>set_query_var()</code></a>.</p>\n"
},
{
"answer_id": 305636,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress allows you to chop up template files into chunks that then can be included into the main template using <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\"><code>get_template_part</code></a>. So you could isolate your template for the ACF-field in a separate file and call that from any other template.</p>\n\n<p>Beware that it is not directly possible to pass variables from the main template to the template part, though <a href=\"https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part\">there are bypasses</a>.</p>\n"
},
{
"answer_id": 305640,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>And to add to previous answers, you can not only use <code>get_template_part</code>, but also use it's second param and combine it with ACFs <code>get_row_layout</code>.</p>\n\n<p>So let's say that somewhere in your template is:</p>\n\n<pre><code><?php while ( have_posts() ) : the_post(); ?>\n<article>\n ... SOME CODE\n\n <?php while ( have_rows( 'YOUR_FIELD_NAME' ) ) : the_row(); ?>\n ... HERE SHOULD GO THE CODE FOR ACF FIELD\n <?php endwhile; ?>\n\n ... SOME OTHER CODE\n</article>\n<?php endwhile; ?>\n</code></pre>\n\n<p>You can change it to:</p>\n\n<pre><code><?php while ( have_posts() ) : the_post(); ?>\n<article>\n ... SOME CODE\n\n <?php\n while ( have_rows( 'YOUR_FIELD_NAME' ) ) :\n the_row();\n get_template_part( 'block', get_row_layout() );\n\n endwhile;\n ?>\n\n ... SOME OTHER CODE\n</article>\n<?php endwhile; ?>\n</code></pre>\n\n<p>Then you can create your custom templates named: <code>block.php</code> (it will be used as fallback), <code>block-layout_1.php</code> (it will be used for layout called \"layout_1\", and so on.</p>\n"
}
]
| 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 Subscription plugin.</p>\n\n<p>It feels wrong to duplicate an order, can't you just connect it somewhere, and where you want, collect the data from the original order when you need it?</p>\n\n<p>I can see what you're missing.</p>\n\n<p>When you do <code>$order->get_items()</code>, it collects all the products in that order, this does not include all (product) item meta data.</p>\n\n<p>For that you have to add something like this:</p>\n\n<pre><code>foreach ( $order->get_items() as $item_id => $item ) {\n\n // get item_meta\n $from_order_item_meta_data = wc_get_order_item_meta( $item_id, '_set_correct_meta_key_here', true );\n\n // save item meta data\n wc_update_order_item_meta($to_order_item_id, '_set_correct_meta_key_here', $from_order_item_meta_data);\n}\n</code></pre>\n\n<p>You cannot use this directly in your function, the example above is just to show you the methods <code>wc_get_order_item_meta()</code> & <code>wc_update_order_item_meta()</code>;</p>\n\n<p>Regards, Bjorn</p>\n"
},
{
"answer_id": 336353,
"author": "Scotty G",
"author_id": 166793,
"author_profile": "https://wordpress.stackexchange.com/users/166793",
"pm_score": 1,
"selected": false,
"text": "<p>Just change the <code>$item_id</code> to <code>$to_order_item_id</code> and you don't even have to touch the <code>order_item_meta</code> since it is still associated with the proper <code>$item_id</code>. So your <code>foreach</code> from above would be ...</p>\n\n<pre><code>foreach($order->get_items() as $item_id=>$item) {\n wc_update_order_item($item_id, array('order_id'=>$to_order_item_id));\n}\n</code></pre>\n\n<p>Then you could even calculate the new totals of both orders after by using ...</p>\n\n<pre><code>$original_order = new WC_Order($original_order_id);\n$original_order->calculate_totals();\n$order = new WC_Order($to_order_item_id);\n$order->calculate_totals();\n</code></pre>\n\n<p>I also discovered sometimes woocommerce will not let you change the <code>order item</code> data so I ended up doing the same as above but with a <code>straight to the database</code> update instead ...</p>\n\n<pre><code>global $wpdb;\n$table = 'wp_woocommerce_order_items';\n$data = array('order_id'=>$to_order_item_id);\nforeach($order->get_items() as $item_id=>$item) {\n $where = array('order_item_id'=>$item_id);\n $updated = $wpdb->update($table, $data, $where);\n if($updated === false) {\n echo 'sorry dawg, there was an error';\n }\n else {\n echo 'you got the soup!';\n }\n}\n</code></pre>\n"
}
]
| 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 1) or adds a class to the html or body tag (see case 2).</p>\n\n<p><strong>Case 1</strong></p>\n\n<p>If you have a meta or any other identifiable tag that holds the language value, but it is not a wrapper for your content, simply add a javascript code that watches for changes on that tag and simply add a class to the body based on what value the meta or whichever tag has.</p>\n\n<p>Example based on meta tag:</p>\n\n<p><code><meta name=\"language\" content=\"english\"></code></p>\n\n<p>JS Code:</p>\n\n<pre><code>jQuery(document).ready(function(){\n let newLang = jQuery('meta[name=\"language\"]').attr('content');\n jQuery('body').removeClass('otherlanguage english').addClass(newLang); \\\\i am removing both language classes to make sure they are not added twice\n});\n</code></pre>\n\n<p>Now check case 2 because that step comes next.</p>\n\n<p><strong>Case 2</strong></p>\n\n<p>Then in your CSS simply target</p>\n\n<pre><code>body.english p {\n font-family: whatever;\n}\n</code></pre>\n"
},
{
"answer_id": 305712,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>This question is not about WordPress but about css. Actually there even is a straightforward solution, because css-3 has an attribute called <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range\" rel=\"nofollow noreferrer\"><code>unicode-range</code></a>, which allows you to load fonts based on the character set. For <a href=\"https://en.wikipedia.org/wiki/Tamil_(Unicode_block)\" rel=\"nofollow noreferrer\">Tamil the unicode block</a> 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:</p>\n\n<pre><code>@font-face { \n font-family: 'NovaSansTamil';\n src: url('novasanstamil.woff') format('woff'); /* full url to font needed */\n unicode-range: U+0B02-CD;\n }\n</code></pre>\n\n<p>Beware that <a href=\"https://caniuse.com/#feat=font-unicode-range\" rel=\"nofollow noreferrer\">browser support is not yet universal</a> for this feature.</p>\n"
},
{
"answer_id": 341260,
"author": "mb0742",
"author_id": 170524,
"author_profile": "https://wordpress.stackexchange.com/users/170524",
"pm_score": 0,
"selected": false,
"text": "<p>Incase anybody runs across this question in the future the easiest method (that I have found) is to simply grab your text elements, use regex to identify the character set and then add the element class as necessary. </p>\n\n<pre><code>var textElements = document.querySelectorAll(\".content\");\nfor (var i = 0; i < textElements.length; i++) {\n if (textElements[i].innerHTML.match(/[\\u0B80-\\u0BFF]/)) {\n textElements[i].className += \" tamil\";\n }\n}\n</code></pre>\n\n<p></p>\n\n<pre><code>.content {\n font-family: \"Nova Sans\";\n}\n.tamil {\n font-family: whatever;\n}\n</code></pre>\n\n<p><a href=\"http://kourge.net/projects/regexp-unicode-block\" rel=\"nofollow noreferrer\">http://kourge.net/projects/regexp-unicode-block</a> (Choose the block range relevant to your lang).</p>\n"
}
]
| 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 to cart page (in wp-admin).</li>\n<li>See side metabox 'Page Attributes'.</li>\n<li>There you can set the page template, does it have something like 'full_width'?</li>\n</ol>\n\n<p>You can also try a different hook, like <code>wp_head</code>.</p>\n\n<p>Example:<br></p>\n\n<pre><code>add_action( 'wp_head', 'urun_sidebar_kaldir' );\n</code></pre>\n\n<p>Let me know.</p>\n\n<hr>\n\n<p>After checking the WOO cart template, i can't find a <code>do_action( 'woocommerce_sidebar' )</code>.\nIt does exist in the singe-product.php template.</p>\n\n<p>Are you certain the cart sidebar is generated by WooCommerce?</p>\n\n<hr>\n\n<p>Add a full-width template to your theme:</p>\n\n<p>Read <a href=\"https://premium.wpmudev.org/blog/creating-custom-page-templates-in-wordpress/\" rel=\"nofollow noreferrer\">this</a>.</p>\n\n<p>Then follow the steps i mentiod at the beginning of my answer.</p>\n"
},
{
"answer_id": 398352,
"author": "ratoli",
"author_id": 215056,
"author_profile": "https://wordpress.stackexchange.com/users/215056",
"pm_score": 0,
"selected": false,
"text": "<p>For me it works with the following code, but I'm not sure if this is really viable and future proof.</p>\n<pre><code>function woo_remove_sidebar() { \n if( ! is_product() or\n ! is_cart() or\n ! is_checkout() or\n ! is_account_page() )\n {\n remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10 );\n }\n}\nadd_filter( 'is_active_sidebar', 'woo_remove_sidebar' );\n</code></pre>\n"
}
]
| 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 to cart page (in wp-admin).</li>\n<li>See side metabox 'Page Attributes'.</li>\n<li>There you can set the page template, does it have something like 'full_width'?</li>\n</ol>\n\n<p>You can also try a different hook, like <code>wp_head</code>.</p>\n\n<p>Example:<br></p>\n\n<pre><code>add_action( 'wp_head', 'urun_sidebar_kaldir' );\n</code></pre>\n\n<p>Let me know.</p>\n\n<hr>\n\n<p>After checking the WOO cart template, i can't find a <code>do_action( 'woocommerce_sidebar' )</code>.\nIt does exist in the singe-product.php template.</p>\n\n<p>Are you certain the cart sidebar is generated by WooCommerce?</p>\n\n<hr>\n\n<p>Add a full-width template to your theme:</p>\n\n<p>Read <a href=\"https://premium.wpmudev.org/blog/creating-custom-page-templates-in-wordpress/\" rel=\"nofollow noreferrer\">this</a>.</p>\n\n<p>Then follow the steps i mentiod at the beginning of my answer.</p>\n"
},
{
"answer_id": 398352,
"author": "ratoli",
"author_id": 215056,
"author_profile": "https://wordpress.stackexchange.com/users/215056",
"pm_score": 0,
"selected": false,
"text": "<p>For me it works with the following code, but I'm not sure if this is really viable and future proof.</p>\n<pre><code>function woo_remove_sidebar() { \n if( ! is_product() or\n ! is_cart() or\n ! is_checkout() or\n ! is_account_page() )\n {\n remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10 );\n }\n}\nadd_filter( 'is_active_sidebar', 'woo_remove_sidebar' );\n</code></pre>\n"
}
]
| 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><head><title>Page title</title></head></code>.</p>\n\n<p>If you want to change the title that you see in the page header. ( Which i think you want to do).</p>\n\n<p>Use this filter:</p>\n\n<pre><code>add_filter('the_title', 'modify_all_titles', 10, 2);\n\nfunction modify_all_titles($title, $id) {\n return 'SOME TEXT BEFORE TITLE | '.$title;\n}\n</code></pre>\n\n<p>Place this code in the functions.php (use a child theme).</p>\n\n<p>Regards, Bjorn</p>\n"
},
{
"answer_id": 305710,
"author": "Ovidiu",
"author_id": 137365,
"author_profile": "https://wordpress.stackexchange.com/users/137365",
"pm_score": 0,
"selected": false,
"text": "<p>If you are referring to the wp_title function called in the title tag in the head part of the header.</p>\n\n<pre><code>function wpdocs_filter_wp_title( $title, $sep ) {\n global $paged, $page;\n\n if ( is_feed() )\n return $title;\n\n // Add the site name.\n $title .= get_bloginfo( 'name' );\n\n // Add whatever else you want\n $title .= $sep . 'whatever other information';\n\n return $title;\n}\nadd_filter( 'wp_title', 'wpdocs_filter_wp_title', 10, 2 );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_title/\" rel=\"nofollow noreferrer\">Here is the documentation</a></p>\n"
}
]
| 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><head><title>Page title</title></head></code>.</p>\n\n<p>If you want to change the title that you see in the page header. ( Which i think you want to do).</p>\n\n<p>Use this filter:</p>\n\n<pre><code>add_filter('the_title', 'modify_all_titles', 10, 2);\n\nfunction modify_all_titles($title, $id) {\n return 'SOME TEXT BEFORE TITLE | '.$title;\n}\n</code></pre>\n\n<p>Place this code in the functions.php (use a child theme).</p>\n\n<p>Regards, Bjorn</p>\n"
},
{
"answer_id": 305710,
"author": "Ovidiu",
"author_id": 137365,
"author_profile": "https://wordpress.stackexchange.com/users/137365",
"pm_score": 0,
"selected": false,
"text": "<p>If you are referring to the wp_title function called in the title tag in the head part of the header.</p>\n\n<pre><code>function wpdocs_filter_wp_title( $title, $sep ) {\n global $paged, $page;\n\n if ( is_feed() )\n return $title;\n\n // Add the site name.\n $title .= get_bloginfo( 'name' );\n\n // Add whatever else you want\n $title .= $sep . 'whatever other information';\n\n return $title;\n}\nadd_filter( 'wp_title', 'wpdocs_filter_wp_title', 10, 2 );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_title/\" rel=\"nofollow noreferrer\">Here is the documentation</a></p>\n"
}
]
| 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><head><title>Page title</title></head></code>.</p>\n\n<p>If you want to change the title that you see in the page header. ( Which i think you want to do).</p>\n\n<p>Use this filter:</p>\n\n<pre><code>add_filter('the_title', 'modify_all_titles', 10, 2);\n\nfunction modify_all_titles($title, $id) {\n return 'SOME TEXT BEFORE TITLE | '.$title;\n}\n</code></pre>\n\n<p>Place this code in the functions.php (use a child theme).</p>\n\n<p>Regards, Bjorn</p>\n"
},
{
"answer_id": 305710,
"author": "Ovidiu",
"author_id": 137365,
"author_profile": "https://wordpress.stackexchange.com/users/137365",
"pm_score": 0,
"selected": false,
"text": "<p>If you are referring to the wp_title function called in the title tag in the head part of the header.</p>\n\n<pre><code>function wpdocs_filter_wp_title( $title, $sep ) {\n global $paged, $page;\n\n if ( is_feed() )\n return $title;\n\n // Add the site name.\n $title .= get_bloginfo( 'name' );\n\n // Add whatever else you want\n $title .= $sep . 'whatever other information';\n\n return $title;\n}\nadd_filter( 'wp_title', 'wpdocs_filter_wp_title', 10, 2 );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_title/\" rel=\"nofollow noreferrer\">Here is the documentation</a></p>\n"
}
]
| 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><head><title>Page title</title></head></code>.</p>\n\n<p>If you want to change the title that you see in the page header. ( Which i think you want to do).</p>\n\n<p>Use this filter:</p>\n\n<pre><code>add_filter('the_title', 'modify_all_titles', 10, 2);\n\nfunction modify_all_titles($title, $id) {\n return 'SOME TEXT BEFORE TITLE | '.$title;\n}\n</code></pre>\n\n<p>Place this code in the functions.php (use a child theme).</p>\n\n<p>Regards, Bjorn</p>\n"
},
{
"answer_id": 305710,
"author": "Ovidiu",
"author_id": 137365,
"author_profile": "https://wordpress.stackexchange.com/users/137365",
"pm_score": 0,
"selected": false,
"text": "<p>If you are referring to the wp_title function called in the title tag in the head part of the header.</p>\n\n<pre><code>function wpdocs_filter_wp_title( $title, $sep ) {\n global $paged, $page;\n\n if ( is_feed() )\n return $title;\n\n // Add the site name.\n $title .= get_bloginfo( 'name' );\n\n // Add whatever else you want\n $title .= $sep . 'whatever other information';\n\n return $title;\n}\nadd_filter( 'wp_title', 'wpdocs_filter_wp_title', 10, 2 );\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/hooks/wp_title/\" rel=\"nofollow noreferrer\">Here is the documentation</a></p>\n"
}
]
| 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 can debug the action with the <code>error_log()</code>.</p>\n\n<p>First in the wp-config.php you need to turn debug and set it to log into file instead of display</p>\n\n<pre><code>define('WP_DEBUG', true);\ndefine('WP_DEBUG_DISPLAY', false);\ndefine('WP_DEBUG_LOG', true);\n</code></pre>\n\n<p>It will create you a file in the folder wp-content in the name debug.log</p>\n\n<p>And then you can use <code>error_log()</code> to debug like this:</p>\n\n<pre><code>function get_acf_value ($post_id) {\n $v = get_field('field_5b1d13fce338d', $post_id);\n error_log($v);\n // Incase it is array you can use print_r\n error_log( print_r( $v, true ) );\n}\nadd_action( 'acf/save_post', 'get_acf_value' );\n</code></pre>\n"
},
{
"answer_id": 305855,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>As Shibi already stated, echoing the value during <code>save_post</code> or <code>acf/save_post</code> doesn't make much sense, since you won't see much of your output. But I don't think echoing it is the thing you want to do with this value. I'm guessing it's just some way of debugging?</p>\n\n<p>But, there is one more problem with your code. Most probably it will return previous value for given field. Why? ACF doc <a href=\"https://www.advancedcustomfields.com/resources/acf-save_post/\" rel=\"nofollow noreferrer\">offers some explanation</a>.</p>\n\n<blockquote>\n <p>This filter allows you to hook in before or after the data has been\n saved. It is important to note that the get_field() function will\n return different values at these times (previous value / new value).</p>\n</blockquote>\n\n<p>So if you'll use priority less than 10, you will get previous value for given field.</p>\n\n<pre><code>function get_acf_value ($post_id) {\n $v = get_field('field_5b1d13fce338d', $post_id);\n // $v contains old value of field 'field_5b1d13fce338d'\n echo $v;\n}\nadd_action( 'acf/save_post', 'get_acf_value', 1 ); // <- priority is 1\n</code></pre>\n\n<p>And if you'll use priority greater than 10, you will get new value for that field.</p>\n\n<pre><code>function get_acf_value ($post_id) {\n $v = get_field('field_5b1d13fce338d', $post_id);\n // $v contains new value of field 'field_5b1d13fce338d'\n echo $v;\n}\nadd_action( 'acf/save_post', 'get_acf_value', 20 ); // <- priority is 20\n</code></pre>\n\n<p>Using it with priority equal to 10 is a little bit risky - most probably it will get you old or new value, depending on when your hook is assigned.</p>\n"
},
{
"answer_id": 378123,
"author": "Konrad Gałęzowski",
"author_id": 178067,
"author_profile": "https://wordpress.stackexchange.com/users/178067",
"pm_score": 0,
"selected": false,
"text": "<p>Hardcoding fields IDs is considered generally bad idea, because it will work only if you export and import your fields, and you're hardcoding ACF's implementation details into your code. Much less volatile solution is to use field's name.</p>\n<p>Let's say your field name is <code>is_allowed_to_make_reviews</code>. You can use the code below to hook when field is saved and do anything you need with it's value.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function update_is_allowed_to_make_reviews($user_id)\n{\n if (is_admin() === false) { // if you want it to work only in wp_admin\n return;\n }\n\n if ($_POST['_acf_screen'] !== 'user') { // to not fire it on other screens\n return;\n }\n\n $value = get_field('is_allowed_to_make_reviews', $user_id);\n\n echo $value;\n}\n\nadd_action('acf/save_post', 'update_is_allowed_to_make_reviews', 100);\n</code></pre>\n"
}
]
| 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 can debug the action with the <code>error_log()</code>.</p>\n\n<p>First in the wp-config.php you need to turn debug and set it to log into file instead of display</p>\n\n<pre><code>define('WP_DEBUG', true);\ndefine('WP_DEBUG_DISPLAY', false);\ndefine('WP_DEBUG_LOG', true);\n</code></pre>\n\n<p>It will create you a file in the folder wp-content in the name debug.log</p>\n\n<p>And then you can use <code>error_log()</code> to debug like this:</p>\n\n<pre><code>function get_acf_value ($post_id) {\n $v = get_field('field_5b1d13fce338d', $post_id);\n error_log($v);\n // Incase it is array you can use print_r\n error_log( print_r( $v, true ) );\n}\nadd_action( 'acf/save_post', 'get_acf_value' );\n</code></pre>\n"
},
{
"answer_id": 305855,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>As Shibi already stated, echoing the value during <code>save_post</code> or <code>acf/save_post</code> doesn't make much sense, since you won't see much of your output. But I don't think echoing it is the thing you want to do with this value. I'm guessing it's just some way of debugging?</p>\n\n<p>But, there is one more problem with your code. Most probably it will return previous value for given field. Why? ACF doc <a href=\"https://www.advancedcustomfields.com/resources/acf-save_post/\" rel=\"nofollow noreferrer\">offers some explanation</a>.</p>\n\n<blockquote>\n <p>This filter allows you to hook in before or after the data has been\n saved. It is important to note that the get_field() function will\n return different values at these times (previous value / new value).</p>\n</blockquote>\n\n<p>So if you'll use priority less than 10, you will get previous value for given field.</p>\n\n<pre><code>function get_acf_value ($post_id) {\n $v = get_field('field_5b1d13fce338d', $post_id);\n // $v contains old value of field 'field_5b1d13fce338d'\n echo $v;\n}\nadd_action( 'acf/save_post', 'get_acf_value', 1 ); // <- priority is 1\n</code></pre>\n\n<p>And if you'll use priority greater than 10, you will get new value for that field.</p>\n\n<pre><code>function get_acf_value ($post_id) {\n $v = get_field('field_5b1d13fce338d', $post_id);\n // $v contains new value of field 'field_5b1d13fce338d'\n echo $v;\n}\nadd_action( 'acf/save_post', 'get_acf_value', 20 ); // <- priority is 20\n</code></pre>\n\n<p>Using it with priority equal to 10 is a little bit risky - most probably it will get you old or new value, depending on when your hook is assigned.</p>\n"
},
{
"answer_id": 378123,
"author": "Konrad Gałęzowski",
"author_id": 178067,
"author_profile": "https://wordpress.stackexchange.com/users/178067",
"pm_score": 0,
"selected": false,
"text": "<p>Hardcoding fields IDs is considered generally bad idea, because it will work only if you export and import your fields, and you're hardcoding ACF's implementation details into your code. Much less volatile solution is to use field's name.</p>\n<p>Let's say your field name is <code>is_allowed_to_make_reviews</code>. You can use the code below to hook when field is saved and do anything you need with it's value.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function update_is_allowed_to_make_reviews($user_id)\n{\n if (is_admin() === false) { // if you want it to work only in wp_admin\n return;\n }\n\n if ($_POST['_acf_screen'] !== 'user') { // to not fire it on other screens\n return;\n }\n\n $value = get_field('is_allowed_to_make_reviews', $user_id);\n\n echo $value;\n}\n\nadd_action('acf/save_post', 'update_is_allowed_to_make_reviews', 100);\n</code></pre>\n"
}
]
| 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);\nfunction admin_footer_test() {\n ?>\n <!--\n ADMIN_FOOTER\n -->\n <?php\n}\n\nadd_action('admin_enqueue_scripts', 'admin_enqueue_scripts_test', PHP_INT_MAX);\nfunction admin_enqueue_scripts_test() {\n wp_enqueue_script( 'sq_general_js', get_stylesheet_directory_uri() . '/js/test.js', array('jquery'), '', true );\n}\n\nadd_action( 'admin_print_scripts', 'admin_print_scripts_test', PHP_INT_MAX );\nfunction admin_print_scripts_test() {\n wp_enqueue_script( 'projects_portrait_slider', get_stylesheet_directory_uri() . '/js/test.js', array('jquery'), '', true );\n}\n</code></pre>\n\n<p><code>admin_footer</code> is always above the script enqueue's. With <code>admin_print_scripts</code> you can get below <code>admin_enqueue_scripts</code>.</p>\n\n<p>Regards, Bjorn</p>\n"
},
{
"answer_id": 305897,
"author": "ShoeLace1291",
"author_id": 86835,
"author_profile": "https://wordpress.stackexchange.com/users/86835",
"pm_score": 3,
"selected": true,
"text": "<p>I finally found the answer. I need to use the <a href=\"https://make.wordpress.org/core/2016/07/15/introducing-admin_print_footer_scripts-hook_suffix-in-4-6/\" rel=\"nofollow noreferrer\">admin_print_footer_scripts</a> action. This will add scripts after the scripts that were called with <code>wp_enqueue_scripts</code>.</p>\n"
}
]
| 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 custom post type, the name of the category template should be: category-event.php</p>\n\n<p>Sure, you also need to have the right query in place (in your \"category-event.php\" file) in order to get the correct posts.</p>\n\n<pre><code>// Custom Query for CPT 'tires'\n$custom_arguments = array(\n 'post_type' => 'event',\n 'posts_per_page' => '36',\n 'taxonomy' => 'your-event-categories',\n 'orderby'=> 'name',\n 'order'=> 'ASC'\n);\n$loop = new WP_Query($custom_arguments);\n\n$html = '';\n// Build your HTML output\n$html .= '<div class=\"event-archive\">';\n while ($loop->have_posts() ) : $loop->the_post();\n $html .= Your HTML Markup to display the content\n $html .= '<div class=\"gridbox\">';\n\n endwhile;\n ....\n wp_reset_query();\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 305914,
"author": "Nico",
"author_id": 128522,
"author_profile": "https://wordpress.stackexchange.com/users/128522",
"pm_score": 2,
"selected": true,
"text": "<p>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.</p>\n\n<p>Disclaimer: Doing this is officially discouraged by WordPress <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">here</a>. However, in my experience it works perfectly to achieve the behaviour you want. Just don't forget to add <strong>wp_reset_query();</strong> after closing the loop.</p>\n\n<pre><code><?php query_posts('post_type=event'); ?>\n <?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>\n\n <!-- Stuff happening inside the loop -->\n\n <?php endwhile; endif; ?>\n<?php wp_reset_query(); ?>\n</code></pre>\n\n<p><strong>Another approach</strong> (slightly more complicated but without altering the main query) would be:</p>\n\n<pre><code><?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>\n<?php $get_category_posts = get_posts( $args ); ?>\n<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>\n\n <!-- Stuff happening inside our custom 'loop' -->\n\n<?php endforeach; ?>\n<?php wp_reset_postdata(); ?>\n</code></pre>\n\n<p>According to the 2nd solution, <strong>your PHP-File should look like this:</strong></p>\n\n<pre><code><?php get_header(); ?>\n\n<?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>\n<?php $get_category_posts = get_posts( $args ); ?>\n<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>\n\n <div class=\"class1\">\n <div class=\"class2\">\n <div class=\"class3\">\n\n <?php print_r( get_post_meta( get_the_ID() ) ); // Just for demo purposes ?>\n\n <?php // $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>\n <?php // $embed = wp_oembed_get( $url ); ?>\n\n <div class=\"class4\">\n <iframe id=\"class_frame\" width=\"560\" height=\"315\" src=\"https://www.youtube.com/watch\" allowfullscreen frameborder=\"0\"></iframe>\n </div>\n </div>\n <div class=\"class6\">\n <h1><?php the_title(); ?></h1>\n <p><?php the_content(); ?></p>\n </div>\n </div>\n </div>\n\n<?php endforeach; ?>\n<?php wp_reset_postdata(); ?>\n\n<?php get_footer(); ?>\n</code></pre>\n\n<p>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 <strong>archive-event.php</strong></p>\n\n<p><strong>Update:</strong></p>\n\n<p>It turned out to be <strong>taxonomy-event.php</strong> in this case.</p>\n"
},
{
"answer_id": 305923,
"author": "honk31",
"author_id": 10994,
"author_profile": "https://wordpress.stackexchange.com/users/10994",
"pm_score": 2,
"selected": false,
"text": "<p>The problem of yours is, you run your own query, and make no use of the main <code>$wp_query</code>. try to use that one:</p>\n\n<pre><code><?php\nif ( have_posts() ) :\n while ( have_posts() ) : the_post();\n //whatever \n endwhile;\nendif;\n</code></pre>\n\n<p>and NOT</p>\n\n<pre><code>$the_query->have_posts()\n</code></pre>\n"
}
]
| 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 custom post type, the name of the category template should be: category-event.php</p>\n\n<p>Sure, you also need to have the right query in place (in your \"category-event.php\" file) in order to get the correct posts.</p>\n\n<pre><code>// Custom Query for CPT 'tires'\n$custom_arguments = array(\n 'post_type' => 'event',\n 'posts_per_page' => '36',\n 'taxonomy' => 'your-event-categories',\n 'orderby'=> 'name',\n 'order'=> 'ASC'\n);\n$loop = new WP_Query($custom_arguments);\n\n$html = '';\n// Build your HTML output\n$html .= '<div class=\"event-archive\">';\n while ($loop->have_posts() ) : $loop->the_post();\n $html .= Your HTML Markup to display the content\n $html .= '<div class=\"gridbox\">';\n\n endwhile;\n ....\n wp_reset_query();\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 305914,
"author": "Nico",
"author_id": 128522,
"author_profile": "https://wordpress.stackexchange.com/users/128522",
"pm_score": 2,
"selected": true,
"text": "<p>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.</p>\n\n<p>Disclaimer: Doing this is officially discouraged by WordPress <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">here</a>. However, in my experience it works perfectly to achieve the behaviour you want. Just don't forget to add <strong>wp_reset_query();</strong> after closing the loop.</p>\n\n<pre><code><?php query_posts('post_type=event'); ?>\n <?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>\n\n <!-- Stuff happening inside the loop -->\n\n <?php endwhile; endif; ?>\n<?php wp_reset_query(); ?>\n</code></pre>\n\n<p><strong>Another approach</strong> (slightly more complicated but without altering the main query) would be:</p>\n\n<pre><code><?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>\n<?php $get_category_posts = get_posts( $args ); ?>\n<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>\n\n <!-- Stuff happening inside our custom 'loop' -->\n\n<?php endforeach; ?>\n<?php wp_reset_postdata(); ?>\n</code></pre>\n\n<p>According to the 2nd solution, <strong>your PHP-File should look like this:</strong></p>\n\n<pre><code><?php get_header(); ?>\n\n<?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>\n<?php $get_category_posts = get_posts( $args ); ?>\n<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>\n\n <div class=\"class1\">\n <div class=\"class2\">\n <div class=\"class3\">\n\n <?php print_r( get_post_meta( get_the_ID() ) ); // Just for demo purposes ?>\n\n <?php // $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>\n <?php // $embed = wp_oembed_get( $url ); ?>\n\n <div class=\"class4\">\n <iframe id=\"class_frame\" width=\"560\" height=\"315\" src=\"https://www.youtube.com/watch\" allowfullscreen frameborder=\"0\"></iframe>\n </div>\n </div>\n <div class=\"class6\">\n <h1><?php the_title(); ?></h1>\n <p><?php the_content(); ?></p>\n </div>\n </div>\n </div>\n\n<?php endforeach; ?>\n<?php wp_reset_postdata(); ?>\n\n<?php get_footer(); ?>\n</code></pre>\n\n<p>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 <strong>archive-event.php</strong></p>\n\n<p><strong>Update:</strong></p>\n\n<p>It turned out to be <strong>taxonomy-event.php</strong> in this case.</p>\n"
},
{
"answer_id": 305923,
"author": "honk31",
"author_id": 10994,
"author_profile": "https://wordpress.stackexchange.com/users/10994",
"pm_score": 2,
"selected": false,
"text": "<p>The problem of yours is, you run your own query, and make no use of the main <code>$wp_query</code>. try to use that one:</p>\n\n<pre><code><?php\nif ( have_posts() ) :\n while ( have_posts() ) : the_post();\n //whatever \n endwhile;\nendif;\n</code></pre>\n\n<p>and NOT</p>\n\n<pre><code>$the_query->have_posts()\n</code></pre>\n"
}
]
| 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 custom post type, the name of the category template should be: category-event.php</p>\n\n<p>Sure, you also need to have the right query in place (in your \"category-event.php\" file) in order to get the correct posts.</p>\n\n<pre><code>// Custom Query for CPT 'tires'\n$custom_arguments = array(\n 'post_type' => 'event',\n 'posts_per_page' => '36',\n 'taxonomy' => 'your-event-categories',\n 'orderby'=> 'name',\n 'order'=> 'ASC'\n);\n$loop = new WP_Query($custom_arguments);\n\n$html = '';\n// Build your HTML output\n$html .= '<div class=\"event-archive\">';\n while ($loop->have_posts() ) : $loop->the_post();\n $html .= Your HTML Markup to display the content\n $html .= '<div class=\"gridbox\">';\n\n endwhile;\n ....\n wp_reset_query();\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 305914,
"author": "Nico",
"author_id": 128522,
"author_profile": "https://wordpress.stackexchange.com/users/128522",
"pm_score": 2,
"selected": true,
"text": "<p>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.</p>\n\n<p>Disclaimer: Doing this is officially discouraged by WordPress <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">here</a>. However, in my experience it works perfectly to achieve the behaviour you want. Just don't forget to add <strong>wp_reset_query();</strong> after closing the loop.</p>\n\n<pre><code><?php query_posts('post_type=event'); ?>\n <?php if ( have_posts() ): while ( have_posts() ): the_post(); ?>\n\n <!-- Stuff happening inside the loop -->\n\n <?php endwhile; endif; ?>\n<?php wp_reset_query(); ?>\n</code></pre>\n\n<p><strong>Another approach</strong> (slightly more complicated but without altering the main query) would be:</p>\n\n<pre><code><?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>\n<?php $get_category_posts = get_posts( $args ); ?>\n<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>\n\n <!-- Stuff happening inside our custom 'loop' -->\n\n<?php endforeach; ?>\n<?php wp_reset_postdata(); ?>\n</code></pre>\n\n<p>According to the 2nd solution, <strong>your PHP-File should look like this:</strong></p>\n\n<pre><code><?php get_header(); ?>\n\n<?php $args = array( 'posts_per_page' => 10, 'post_type' => 'event', 'post_status' => 'publish' ); ?>\n<?php $get_category_posts = get_posts( $args ); ?>\n<?php foreach ( $get_category_posts as $post ) : setup_postdata( $post ); ?>\n\n <div class=\"class1\">\n <div class=\"class2\">\n <div class=\"class3\">\n\n <?php print_r( get_post_meta( get_the_ID() ) ); // Just for demo purposes ?>\n\n <?php // $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>\n <?php // $embed = wp_oembed_get( $url ); ?>\n\n <div class=\"class4\">\n <iframe id=\"class_frame\" width=\"560\" height=\"315\" src=\"https://www.youtube.com/watch\" allowfullscreen frameborder=\"0\"></iframe>\n </div>\n </div>\n <div class=\"class6\">\n <h1><?php the_title(); ?></h1>\n <p><?php the_content(); ?></p>\n </div>\n </div>\n </div>\n\n<?php endforeach; ?>\n<?php wp_reset_postdata(); ?>\n\n<?php get_footer(); ?>\n</code></pre>\n\n<p>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 <strong>archive-event.php</strong></p>\n\n<p><strong>Update:</strong></p>\n\n<p>It turned out to be <strong>taxonomy-event.php</strong> in this case.</p>\n"
},
{
"answer_id": 305923,
"author": "honk31",
"author_id": 10994,
"author_profile": "https://wordpress.stackexchange.com/users/10994",
"pm_score": 2,
"selected": false,
"text": "<p>The problem of yours is, you run your own query, and make no use of the main <code>$wp_query</code>. try to use that one:</p>\n\n<pre><code><?php\nif ( have_posts() ) :\n while ( have_posts() ) : the_post();\n //whatever \n endwhile;\nendif;\n</code></pre>\n\n<p>and NOT</p>\n\n<pre><code>$the_query->have_posts()\n</code></pre>\n"
}
]
| 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 ($query->is_search) {\n$query->set('cat','37');\n}\nreturn $query;\n}\nadd_filter('pre_get_posts','searchcategory');\n</code></pre>\n\n<p>The problem was with Toolset plugin. For some reason, it was messing up the search results based on categories/taxonomies. Whatever it was, the code above works fine with original WordPress categories.</p>\n"
},
{
"answer_id": 305984,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>This code should work OK, but... There are some problems with it. Let's break it apart and add some comments.</p>\n\n<pre><code>function searchcategory($query) {\n if ($query->is_search) {\n // Checking only for is_search is very risky. It will be set to true\n // whenever param \"s\" is set. So your function will modify any wp_query with s,\n // for instance the one in wp-admin... But also any other, even if\n // the query isn't querying for posts...\n\n $query->set('cat','37');\n // You pass ID of term in here. It's a number. Passing it as string\n // is not a problem, but it's another bad practice, because it will\n // have to be converted to number.\n }\n return $query;\n\n // It's an action - you don't have to return anything in it. Your result \n // will be ignored.\n}\nadd_filter('pre_get_posts','searchcategory');\n\n// pre_get_posts is and action and not a filter.\n// Due to the way actions/filters are implemented,\n// you can assign your callback using `add_filter`,\n// but it isn't a good practice.\n</code></pre>\n\n<p>So how to write it nicer?</p>\n\n<pre><code>function searchcategory($query) {\n if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {\n $query->set( 'cat', 37 );\n }\n}\nadd_action( 'pre_get_posts', 'searchcategory' );\n</code></pre>\n"
}
]
| 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.woocommerce.com/document/woocommerce-shortcodes/#scenario-5-specific-categories\" rel=\"noreferrer\">https://docs.woocommerce.com/document/woocommerce-shortcodes/#scenario-5-specific-categories</a> and <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/do_shortcode/</a></p>\n\n<pre><code><?php\necho do_shortcode('[products category=\"new-arrivals\"]');\n?> \n</code></pre>\n\n<p>Alternatively, If you need to customize the output of the products then just use <code>wc_get_products</code> to get a list of products and iterate through it. See <a href=\"https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query\" rel=\"noreferrer\">https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query</a> </p>\n\n<pre><code><?php\n$args = array(\n 'category' => array( 'new-arrivals' ),\n);\n$products = wc_get_products( $args );\nforeach ($products as $product) {\n echo $product->get_title() . ' ' . $product->get_price();\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 331701,
"author": "Debbie Kurth",
"author_id": 119560,
"author_profile": "https://wordpress.stackexchange.com/users/119560",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming woocommerce plugin is in place:</p>\n\n<pre><code> if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) \n {\n $args = array('category' => array( 'Your category name' ), );\n $products = wc_get_products( $args );\n foreach ($products as $product) \n {\n DebugLog('Title: '. $product->get_name() . ' Price: ' . $product->get_price()) ;\n }\n }\n</code></pre>\n\n<p>$product->get_title(), does not always seem to display the product name.</p>\n"
}
]
| 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 type: \"POST\",\n url: compareids_ajax.ajax_url,\n data: { // Data object\n compareIDs : compareIDs,\n action: 'your_ajax_function' // This is required to let WordPress know which function to invoke\n },\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function (msg) {\n console.log( msg );\n },\n error: function (errormessage) {\n console.log( errormessage );\n }\n });\n</code></pre>\n\n<p>In your php file</p>\n\n<pre><code> add_action('wp_ajax_nopriv_your_ajax_function','your_ajax_function'); // Ajax Function should be hooked like this for unauthenticated users\n add_action('wp_ajax_your_ajax_function','your_ajax_function'); // \n\n function your_ajax_function(){\n\n $comparedIds = $_POST['compareIDs']; // Your data is now available in $_POST \n // Do your stuff here\n\n die(); // At the end \n\n }\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">wp_ajax_(action)</a></p>\n"
},
{
"answer_id": 306123,
"author": "Deyan Veselinov",
"author_id": 145268,
"author_profile": "https://wordpress.stackexchange.com/users/145268",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you. I actually did that but it seems there is no connection to the admin-ajax.php Its always 400 Bad request. Even if I just test it with the functions.php</p>\n\n<pre><code> add_action('wp_ajax_my_action', 'my_action');\n\n function my_action(){\n\n echo 'My action';\n\n }\n\n\n then enter http://my-website.com/wp-admin/admin-ajax.php?action=my_action\n</code></pre>\n\n<p>the browser displays 0</p>\n"
}
]
| 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 ( ! is_admin() && $query->is_main_query() && $query->is_search() ) { \n</code></pre>\n\n<p>you check if you're not in admin area, if the query is the main query for the current page and if the current page is a search page.</p>\n\n<p>And here:</p>\n\n<pre><code>if ( is_page(100) ) {\n</code></pre>\n\n<p>you check if the current page is page with ID 100.</p>\n\n<p>So what's the problem? These conditions won't be satisfied both... It's either a page or a search results page...</p>\n"
},
{
"answer_id": 306116,
"author": "Elex",
"author_id": 113687,
"author_profile": "https://wordpress.stackexchange.com/users/113687",
"pm_score": 1,
"selected": false,
"text": "<p>The answer before mine shows you the problem about <code>is_search()</code> in your code. </p>\n\n<p>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 :</p>\n\n<pre><code>// Gives you the category where you want to search with from page ID\nadd_filter('wpse_306057_search_category_id', 'wpse_306057_search_category_id', 10, 1);\nfunction wpse_306057_search_category_id($id = false) {\n switch($id)\n {\n case 100:\n $cat_id = 37;\n break;\n\n case 200:\n $cat_id = 24;\n break;\n\n\n case 201:\n case 202:\n case 203:\n $cat_id = array(57,99); // You may use multiple cats\n break;\n\n\n default:\n $cat_id = false;\n break;\n }\n return $cat_id;\n}\n\n// Add input hidden with \"from page\" for your search form\nadd_filter('get_search_form', 'wpse_306057_search_category_input', 10, 1);\nfunction wpse_306057_search_category_input($form) {\n return str_replace('</form>', '<input type=\"hidden\" name=\"search_from_page\" value=\"'.get_queried_object_id().'\" /></form>', $form);\n}\n\n// Add cat to your query\nadd_filter('pre_get_posts', 'wpse_306057_search_category', 10, 1);\nfunction wpse_306057_search_category($query) {\n if(!is_admin()\n && $query->is_main_query()\n && $query->is_search()\n && !empty(@$_GET['search_from_page'])\n && apply_filters('wpse_306057_search_category_id', $_GET['search_from_page']))\n {\n $query->set('cat', apply_filters('wpse_306057_search_category_id', $_GET['search_from_page']));\n }\n}\n</code></pre>\n\n<p>I haven't tested the code, but it's a good way to play with what you want to achieve.</p>\n"
}
]
| 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 redirection</a> 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.</p>\n\n<p>For this example, I’m using Redirection plugin.</p>\n\n<p>Here is the scenario:</p>\n\n<pre><code>Already published post with URL: https://WPSutra.com/how-to-add-google-amp-to-wordpress-to-speed-up-your-mobile-site\nNew URL After editing the post slug: https://WPSutra.com/Google-amp-WordPress\n</code></pre>\n\n<p>Go to Tools > Redirection (or redirection tab of any other plugin that you are using). You can also set redirection using the .htaccess method.</p>\n\n<p>Here you can set the 301 redirect from old post to the new one as shown in below screenshot:\n<a href=\"https://i.stack.imgur.com/HCSRR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HCSRR.png\" alt=\"enter image description here\"></a></p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 359837,
"author": "Harshal Solanki",
"author_id": 183393,
"author_profile": "https://wordpress.stackexchange.com/users/183393",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n/* If your Old Website Blog indexed on google crawling site & you want to replace your URL with New One,\nHere, I describe whole process. */\n// Redirected Single Blog Posts using \"template_redirect\" function without use of \"301 Redirection\" plugin\n/* Redirected Blog detailed page URL like : \n\"HOMEURL/test-abc\" to \"HOMEURL/resources/blog/test-abc\" */\n\n/* Start Template Redirection Only For Single Blog Posts */\nadd_action('template_redirect', 'redirect_single_post_func');\n\nfunction redirect_single_post_func() {\n if (is_singular('post')) {\n global $post;\n global $wp;\n $resource_ID = 'Your Page/Posts ID'; //specify id here\n $resource_post = get_post($resource_ID);\n $resource_slug = $resource_post->post_name;\n\n $blog_ID = 'Your Page/Posts ID'; //specify id here\n $blog_post = get_post($blog_ID);\n $blog_slug = $blog_post->post_name;\n\n\n $url = $wp->request;\n if (strstr($url, $resource_slug) && strstr($url, $blog_slug)) {\n return true;\n } else {\n $post_slug = $post->post_name;\n $new_slug = home_url() . \"/resources/blog/\" . $post_slug;\n wp_redirect($new_slug);\n }\n exit;\n }\n}\n?>\n</code></pre>\n"
}
]
| 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 redirection</a> 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.</p>\n\n<p>For this example, I’m using Redirection plugin.</p>\n\n<p>Here is the scenario:</p>\n\n<pre><code>Already published post with URL: https://WPSutra.com/how-to-add-google-amp-to-wordpress-to-speed-up-your-mobile-site\nNew URL After editing the post slug: https://WPSutra.com/Google-amp-WordPress\n</code></pre>\n\n<p>Go to Tools > Redirection (or redirection tab of any other plugin that you are using). You can also set redirection using the .htaccess method.</p>\n\n<p>Here you can set the 301 redirect from old post to the new one as shown in below screenshot:\n<a href=\"https://i.stack.imgur.com/HCSRR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HCSRR.png\" alt=\"enter image description here\"></a></p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 359837,
"author": "Harshal Solanki",
"author_id": 183393,
"author_profile": "https://wordpress.stackexchange.com/users/183393",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n/* If your Old Website Blog indexed on google crawling site & you want to replace your URL with New One,\nHere, I describe whole process. */\n// Redirected Single Blog Posts using \"template_redirect\" function without use of \"301 Redirection\" plugin\n/* Redirected Blog detailed page URL like : \n\"HOMEURL/test-abc\" to \"HOMEURL/resources/blog/test-abc\" */\n\n/* Start Template Redirection Only For Single Blog Posts */\nadd_action('template_redirect', 'redirect_single_post_func');\n\nfunction redirect_single_post_func() {\n if (is_singular('post')) {\n global $post;\n global $wp;\n $resource_ID = 'Your Page/Posts ID'; //specify id here\n $resource_post = get_post($resource_ID);\n $resource_slug = $resource_post->post_name;\n\n $blog_ID = 'Your Page/Posts ID'; //specify id here\n $blog_post = get_post($blog_ID);\n $blog_slug = $blog_post->post_name;\n\n\n $url = $wp->request;\n if (strstr($url, $resource_slug) && strstr($url, $blog_slug)) {\n return true;\n } else {\n $post_slug = $post->post_name;\n $new_slug = home_url() . \"/resources/blog/\" . $post_slug;\n wp_redirect($new_slug);\n }\n exit;\n }\n}\n?>\n</code></pre>\n"
}
]
| 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 redirection</a> 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.</p>\n\n<p>For this example, I’m using Redirection plugin.</p>\n\n<p>Here is the scenario:</p>\n\n<pre><code>Already published post with URL: https://WPSutra.com/how-to-add-google-amp-to-wordpress-to-speed-up-your-mobile-site\nNew URL After editing the post slug: https://WPSutra.com/Google-amp-WordPress\n</code></pre>\n\n<p>Go to Tools > Redirection (or redirection tab of any other plugin that you are using). You can also set redirection using the .htaccess method.</p>\n\n<p>Here you can set the 301 redirect from old post to the new one as shown in below screenshot:\n<a href=\"https://i.stack.imgur.com/HCSRR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HCSRR.png\" alt=\"enter image description here\"></a></p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 359837,
"author": "Harshal Solanki",
"author_id": 183393,
"author_profile": "https://wordpress.stackexchange.com/users/183393",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n/* If your Old Website Blog indexed on google crawling site & you want to replace your URL with New One,\nHere, I describe whole process. */\n// Redirected Single Blog Posts using \"template_redirect\" function without use of \"301 Redirection\" plugin\n/* Redirected Blog detailed page URL like : \n\"HOMEURL/test-abc\" to \"HOMEURL/resources/blog/test-abc\" */\n\n/* Start Template Redirection Only For Single Blog Posts */\nadd_action('template_redirect', 'redirect_single_post_func');\n\nfunction redirect_single_post_func() {\n if (is_singular('post')) {\n global $post;\n global $wp;\n $resource_ID = 'Your Page/Posts ID'; //specify id here\n $resource_post = get_post($resource_ID);\n $resource_slug = $resource_post->post_name;\n\n $blog_ID = 'Your Page/Posts ID'; //specify id here\n $blog_post = get_post($blog_ID);\n $blog_slug = $blog_post->post_name;\n\n\n $url = $wp->request;\n if (strstr($url, $resource_slug) && strstr($url, $blog_slug)) {\n return true;\n } else {\n $post_slug = $post->post_name;\n $new_slug = home_url() . \"/resources/blog/\" . $post_slug;\n wp_redirect($new_slug);\n }\n exit;\n }\n}\n?>\n</code></pre>\n"
}
]
| 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 redirection</a> 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.</p>\n\n<p>For this example, I’m using Redirection plugin.</p>\n\n<p>Here is the scenario:</p>\n\n<pre><code>Already published post with URL: https://WPSutra.com/how-to-add-google-amp-to-wordpress-to-speed-up-your-mobile-site\nNew URL After editing the post slug: https://WPSutra.com/Google-amp-WordPress\n</code></pre>\n\n<p>Go to Tools > Redirection (or redirection tab of any other plugin that you are using). You can also set redirection using the .htaccess method.</p>\n\n<p>Here you can set the 301 redirect from old post to the new one as shown in below screenshot:\n<a href=\"https://i.stack.imgur.com/HCSRR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HCSRR.png\" alt=\"enter image description here\"></a></p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 359837,
"author": "Harshal Solanki",
"author_id": 183393,
"author_profile": "https://wordpress.stackexchange.com/users/183393",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\n/* If your Old Website Blog indexed on google crawling site & you want to replace your URL with New One,\nHere, I describe whole process. */\n// Redirected Single Blog Posts using \"template_redirect\" function without use of \"301 Redirection\" plugin\n/* Redirected Blog detailed page URL like : \n\"HOMEURL/test-abc\" to \"HOMEURL/resources/blog/test-abc\" */\n\n/* Start Template Redirection Only For Single Blog Posts */\nadd_action('template_redirect', 'redirect_single_post_func');\n\nfunction redirect_single_post_func() {\n if (is_singular('post')) {\n global $post;\n global $wp;\n $resource_ID = 'Your Page/Posts ID'; //specify id here\n $resource_post = get_post($resource_ID);\n $resource_slug = $resource_post->post_name;\n\n $blog_ID = 'Your Page/Posts ID'; //specify id here\n $blog_post = get_post($blog_ID);\n $blog_slug = $blog_post->post_name;\n\n\n $url = $wp->request;\n if (strstr($url, $resource_slug) && strstr($url, $blog_slug)) {\n return true;\n } else {\n $post_slug = $post->post_name;\n $new_slug = home_url() . \"/resources/blog/\" . $post_slug;\n wp_redirect($new_slug);\n }\n exit;\n }\n}\n?>\n</code></pre>\n"
}
]
| 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/functions-reference/\" rel=\"noreferrer\">Polylangs Function Reference</a>, <code>pll_the_languages</code></p>\n\n<blockquote>\n <p>Displays a language switcher.</p>\n</blockquote>\n\n<p>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:</p>\n\n<pre><code>pll_languages_list($args);\n</code></pre>\n\n<p>and it will return the list of languages.</p>\n\n<blockquote>\n <p>$args is an optional array parameter. Options are:</p>\n \n <ul>\n <li>‘hide_empty’ => hides languages with no posts if set to 1 (default: 0)</li>\n <li>‘fields’ => returns only that field if set. Possible values are\n ‘slug’, ‘locale’, ‘name’, defaults to ‘slug’</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 339659,
"author": "Libla",
"author_id": 169460,
"author_profile": "https://wordpress.stackexchange.com/users/169460",
"pm_score": 2,
"selected": false,
"text": "<p>Polylang offers the function <code>pll_languages_list()</code> but note this will return only one type of value <code>slug</code>.</p>\n\n<p>You can use <code>get_terms</code> to query all languages with the name and slug included.</p>\n\n<pre><code>get_terms( 'term_language', [ 'hide_empty' => false ] );\n</code></pre>\n"
},
{
"answer_id": 384013,
"author": "MuturiAlex",
"author_id": 168074,
"author_profile": "https://wordpress.stackexchange.com/users/168074",
"pm_score": 2,
"selected": false,
"text": "<p>You can get an array with the language details using the following call:</p>\n<pre><code>if (function_exists('pll_languages_list')) {\n return pll_languages_list(array('fields' => array()));\n}\n</code></pre>\n<p>The result is an array which you can play with to your liking...</p>\n<pre><code>{\nterm_id: 19,\nname: "English",\nslug: "en",\nterm_group: 0,\nterm_taxonomy_id: 19,\ntaxonomy: "language",\ndescription: "en_US",\nparent: 0,\ncount: 149,\ntl_term_id: 20,\ntl_term_taxonomy_id: 20,\ntl_count: 35,\nlocale: "en_US",\nis_rtl: 0,\nw3c: "en-US",\nfacebook: "en_US",\nflag_url: "http://***********.one/wp-content/plugins/polylang/flags/us.png",\nflag: "<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHzSURBVHjaYkxOP8IAB//+Mfz7w8Dwi4HhP5CcJb/n/7evb16/APL/gRFQDiAAw3JuAgAIBEDQ/iswEERjGzBQLEru97ll0g0+3HvqMn1SpqlqGsZMsZsIe0SICA5gt5a/AGIEarCPtFh+6N/ffwxA9OvP/7//QYwff/6fZahmePeB4dNHhi+fGb59Y4zyvHHmCEAAAW3YDzQYaJJ93a+vX79aVf58//69fvEPlpIfnz59+vDhw7t37968efP3b/SXL59OnjwIEEAsDP+YgY53b2b89++/awvLn98MDi2cVxl+/vl6mituCtBghi9f/v/48e/XL86krj9XzwEEEENy8g6gu22rfn78+NGs5Ofr16+ZC58+fvyYwX8rxOxXr169fPny+fPn1//93bJlBUAAsQADZMEBxj9/GBxb2P/9+S/R8u3vzxuyaX8ZHv3j8/YGms3w8ycQARmi2eE37t4ACCDGR4/uSkrKAS35B3TT////wADOgLOBIaXIyjBlwxKAAGKRXjCB0SOEaeu+/y9fMnz4AHQxCP348R/o+l+//sMZQBNLEvif3AcIIMZbty7Ly6t9ZmXl+fXj/38GoHH/UcGfP79//BBiYHjy9+8/oUkNAAHEwt1V/vI/KBY/QSISFqM/GBg+MzB8A6PfYC5EFiDAABqgW776MP0rAAAAAElFTkSuQmCC" title="English" alt="English" width="16" height="11" style="width: 16px; height: 11px;" />",\nhome_url: "http://**********.one/en/front-page-2/",\nsearch_url: "http://*********.one/en/",\nhost: null,\nmo_id: "1716",\npage_on_front: 2560,\npage_for_posts: 499,\nfilter: "raw",\nflag_code: "us"\n},\n</code></pre>\n"
}
]
| 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/functions-reference/\" rel=\"noreferrer\">Polylangs Function Reference</a>, <code>pll_the_languages</code></p>\n\n<blockquote>\n <p>Displays a language switcher.</p>\n</blockquote>\n\n<p>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:</p>\n\n<pre><code>pll_languages_list($args);\n</code></pre>\n\n<p>and it will return the list of languages.</p>\n\n<blockquote>\n <p>$args is an optional array parameter. Options are:</p>\n \n <ul>\n <li>‘hide_empty’ => hides languages with no posts if set to 1 (default: 0)</li>\n <li>‘fields’ => returns only that field if set. Possible values are\n ‘slug’, ‘locale’, ‘name’, defaults to ‘slug’</li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 339659,
"author": "Libla",
"author_id": 169460,
"author_profile": "https://wordpress.stackexchange.com/users/169460",
"pm_score": 2,
"selected": false,
"text": "<p>Polylang offers the function <code>pll_languages_list()</code> but note this will return only one type of value <code>slug</code>.</p>\n\n<p>You can use <code>get_terms</code> to query all languages with the name and slug included.</p>\n\n<pre><code>get_terms( 'term_language', [ 'hide_empty' => false ] );\n</code></pre>\n"
},
{
"answer_id": 384013,
"author": "MuturiAlex",
"author_id": 168074,
"author_profile": "https://wordpress.stackexchange.com/users/168074",
"pm_score": 2,
"selected": false,
"text": "<p>You can get an array with the language details using the following call:</p>\n<pre><code>if (function_exists('pll_languages_list')) {\n return pll_languages_list(array('fields' => array()));\n}\n</code></pre>\n<p>The result is an array which you can play with to your liking...</p>\n<pre><code>{\nterm_id: 19,\nname: "English",\nslug: "en",\nterm_group: 0,\nterm_taxonomy_id: 19,\ntaxonomy: "language",\ndescription: "en_US",\nparent: 0,\ncount: 149,\ntl_term_id: 20,\ntl_term_taxonomy_id: 20,\ntl_count: 35,\nlocale: "en_US",\nis_rtl: 0,\nw3c: "en-US",\nfacebook: "en_US",\nflag_url: "http://***********.one/wp-content/plugins/polylang/flags/us.png",\nflag: "<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAALCAIAAAD5gJpuAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAHzSURBVHjaYkxOP8IAB//+Mfz7w8Dwi4HhP5CcJb/n/7evb16/APL/gRFQDiAAw3JuAgAIBEDQ/iswEERjGzBQLEru97ll0g0+3HvqMn1SpqlqGsZMsZsIe0SICA5gt5a/AGIEarCPtFh+6N/ffwxA9OvP/7//QYwff/6fZahmePeB4dNHhi+fGb59Y4zyvHHmCEAAAW3YDzQYaJJ93a+vX79aVf58//69fvEPlpIfnz59+vDhw7t37968efP3b/SXL59OnjwIEEAsDP+YgY53b2b89++/awvLn98MDi2cVxl+/vl6mituCtBghi9f/v/48e/XL86krj9XzwEEEENy8g6gu22rfn78+NGs5Ofr16+ZC58+fvyYwX8rxOxXr169fPny+fPn1//93bJlBUAAsQADZMEBxj9/GBxb2P/9+S/R8u3vzxuyaX8ZHv3j8/YGms3w8ycQARmi2eE37t4ACCDGR4/uSkrKAS35B3TT////wADOgLOBIaXIyjBlwxKAAGKRXjCB0SOEaeu+/y9fMnz4AHQxCP348R/o+l+//sMZQBNLEvif3AcIIMZbty7Ly6t9ZmXl+fXj/38GoHH/UcGfP79//BBiYHjy9+8/oUkNAAHEwt1V/vI/KBY/QSISFqM/GBg+MzB8A6PfYC5EFiDAABqgW776MP0rAAAAAElFTkSuQmCC" title="English" alt="English" width="16" height="11" style="width: 16px; height: 11px;" />",\nhome_url: "http://**********.one/en/front-page-2/",\nsearch_url: "http://*********.one/en/",\nhost: null,\nmo_id: "1716",\npage_on_front: 2560,\npage_for_posts: 499,\nfilter: "raw",\nflag_code: "us"\n},\n</code></pre>\n"
}
]
| 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.imgur.com/mnN0h.png\" alt=\"WooCommerce settings with product tab\"></a></p>\n\n<p>To change this \"sub navigation\" you could use the WooCommerce filter \"<a href=\"https://docs.woocommerce.com/document/adding-a-section-to-a-settings-tab/\" rel=\"nofollow noreferrer\">woocommerce_get_sections_products</a>\". </p>\n\n<p>The following example code will remove the sub navigation point \"inventory\":</p>\n\n<pre><code>function change_navi_function($sections)\n{\n // remove sub navigation point \"inventory\"\n unset($sections['inventory']);\n\n return $sections;\n}\n\nadd_filter('woocommerce_get_sections_products', 'change_navi_function');\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/Z2Yme.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z2Yme.png\" alt=\"WooCommerce settings with product tab without the subnavigation point inventory \"></a></p>\n\n<p>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.</p>\n"
},
{
"answer_id": 348956,
"author": "Eli King",
"author_id": 161534,
"author_profile": "https://wordpress.stackexchange.com/users/161534",
"pm_score": -1,
"selected": false,
"text": "<p>you can find the file in \n<code>~/wp-content/plugins/woocommerce/includes/admin/views/html-admin-settings.php</code></p>\n\n<pre><code>foreach ( $tabs as $slug => $label ) {\n echo '<a href=\"' . esc_html( admin_url( 'admin.php?page=wc-settings&tab=' . esc_attr( $slug ) ) ) . '\" class=\"nav-tab ' . ( $current_tab === $slug ? 'nav-tab-active' : '' ) . '\">' . esc_html( $label ) . '</a>';\n}\n</code></pre>\n\n<p>and edit <code>html-admin-settings.php</code> add code </p>\n\n<pre><code>foreach ( $tabs as $slug => $label ) {\n if( $slug != \"Product\"){\n echo '<a href=\"' . esc_html( admin_url( 'admin.php?page=wc-settings&tab=' . esc_attr( $slug ) ) ) . '\" class=\"nav-tab ' . ( $current_tab === $slug ? 'nav-tab-active' : '' ) . '\">' . esc_html( $label ) . '</a>';\n } \n}\n</code></pre>\n"
}
]
| 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.imgur.com/mnN0h.png\" alt=\"WooCommerce settings with product tab\"></a></p>\n\n<p>To change this \"sub navigation\" you could use the WooCommerce filter \"<a href=\"https://docs.woocommerce.com/document/adding-a-section-to-a-settings-tab/\" rel=\"nofollow noreferrer\">woocommerce_get_sections_products</a>\". </p>\n\n<p>The following example code will remove the sub navigation point \"inventory\":</p>\n\n<pre><code>function change_navi_function($sections)\n{\n // remove sub navigation point \"inventory\"\n unset($sections['inventory']);\n\n return $sections;\n}\n\nadd_filter('woocommerce_get_sections_products', 'change_navi_function');\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/Z2Yme.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z2Yme.png\" alt=\"WooCommerce settings with product tab without the subnavigation point inventory \"></a></p>\n\n<p>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.</p>\n"
},
{
"answer_id": 348956,
"author": "Eli King",
"author_id": 161534,
"author_profile": "https://wordpress.stackexchange.com/users/161534",
"pm_score": -1,
"selected": false,
"text": "<p>you can find the file in \n<code>~/wp-content/plugins/woocommerce/includes/admin/views/html-admin-settings.php</code></p>\n\n<pre><code>foreach ( $tabs as $slug => $label ) {\n echo '<a href=\"' . esc_html( admin_url( 'admin.php?page=wc-settings&tab=' . esc_attr( $slug ) ) ) . '\" class=\"nav-tab ' . ( $current_tab === $slug ? 'nav-tab-active' : '' ) . '\">' . esc_html( $label ) . '</a>';\n}\n</code></pre>\n\n<p>and edit <code>html-admin-settings.php</code> add code </p>\n\n<pre><code>foreach ( $tabs as $slug => $label ) {\n if( $slug != \"Product\"){\n echo '<a href=\"' . esc_html( admin_url( 'admin.php?page=wc-settings&tab=' . esc_attr( $slug ) ) ) . '\" class=\"nav-tab ' . ( $current_tab === $slug ? 'nav-tab-active' : '' ) . '\">' . esc_html( $label ) . '</a>';\n } \n}\n</code></pre>\n"
}
]
| 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=\"'.$url.'\" alt=\"'.get_the_title().'\" title=\"'.get_the_title().'\"/>';\n</code></pre>\n"
},
{
"answer_id": 306310,
"author": "Charles",
"author_id": 15605,
"author_profile": "https://wordpress.stackexchange.com/users/15605",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe following function is what you are looking for.<br />\nThe important part you are looking for in the code is the line which holds the <a href=\"https://secure.php.net/manual/en/function.pathinfo.php\" rel=\"nofollow noreferrer\">pathinfo</a>,<br />\nwhich is php and not WordPress specific.</p>\n\n<p>There are probably several other options but as nobody responded till now I think that this function will help you out till another <em>(maybe better)</em> answer is added by someone else.</p>\n\n<blockquote>\n <p>You could make a backup of the functions.php (found in the theme folder) before you add this function to it.</p>\n</blockquote>\n\n<p>I have tested it in a sandbox with the WP version 4.9.6 and it should work flawless.</p>\n\n<pre><code>/**\n * Add content on Alt/Title tags\n * \n * @link https://wordpress.stackexchange.com/q/306250\n * @version Wordpress V4.9.6 \n * \n * Source:\n * @see https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\n * @see https://secure.php.net/manual/en/function.pathinfo.php\n * @see https://secure.php.net/manual/en/function.preg-replace.php\n * \n * @param [type] $content [description]\n * @return [type] [description]\n */\nadd_filter( 'the_content', 'add_filename_on_img_tags' );\nfunction add_filename_on_img_tags( $content )\n{\n // get featured image\n $url = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );\n // get filename\n $filename = pathinfo( $arr['name'], PATHINFO_FILENAME );\n // add content on ALT/TITLE tags\n $img = '<img src=\"' . $url . '\" alt=\"' . $filename . '\" title=\"' . $filename . '\"/>';\n // add image after first paragraph\n $content = preg_replace( '#(<p>.*?</p>)#','$1' . $img, $content, 1 );\n\n return $content;\n\n} // end function\n</code></pre>\n\n<p>In the docblock you find links with information for code as used in the function.</p>\n"
},
{
"answer_id": 349401,
"author": "cesur",
"author_id": 175983,
"author_profile": "https://wordpress.stackexchange.com/users/175983",
"pm_score": -1,
"selected": false,
"text": "<p>You can use this as well.</p>\n\n<pre><code>the_post_thumbnail( 'large', array( 'title' => get_the_title(get_post_thumbnail_id()),'alt' => get_the_post_thumbnail_caption() ) );\n</code></pre>\n"
}
]
| 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=\"'.$url.'\" alt=\"'.get_the_title().'\" title=\"'.get_the_title().'\"/>';\n</code></pre>\n"
},
{
"answer_id": 306310,
"author": "Charles",
"author_id": 15605,
"author_profile": "https://wordpress.stackexchange.com/users/15605",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe following function is what you are looking for.<br />\nThe important part you are looking for in the code is the line which holds the <a href=\"https://secure.php.net/manual/en/function.pathinfo.php\" rel=\"nofollow noreferrer\">pathinfo</a>,<br />\nwhich is php and not WordPress specific.</p>\n\n<p>There are probably several other options but as nobody responded till now I think that this function will help you out till another <em>(maybe better)</em> answer is added by someone else.</p>\n\n<blockquote>\n <p>You could make a backup of the functions.php (found in the theme folder) before you add this function to it.</p>\n</blockquote>\n\n<p>I have tested it in a sandbox with the WP version 4.9.6 and it should work flawless.</p>\n\n<pre><code>/**\n * Add content on Alt/Title tags\n * \n * @link https://wordpress.stackexchange.com/q/306250\n * @version Wordpress V4.9.6 \n * \n * Source:\n * @see https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\n * @see https://secure.php.net/manual/en/function.pathinfo.php\n * @see https://secure.php.net/manual/en/function.preg-replace.php\n * \n * @param [type] $content [description]\n * @return [type] [description]\n */\nadd_filter( 'the_content', 'add_filename_on_img_tags' );\nfunction add_filename_on_img_tags( $content )\n{\n // get featured image\n $url = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );\n // get filename\n $filename = pathinfo( $arr['name'], PATHINFO_FILENAME );\n // add content on ALT/TITLE tags\n $img = '<img src=\"' . $url . '\" alt=\"' . $filename . '\" title=\"' . $filename . '\"/>';\n // add image after first paragraph\n $content = preg_replace( '#(<p>.*?</p>)#','$1' . $img, $content, 1 );\n\n return $content;\n\n} // end function\n</code></pre>\n\n<p>In the docblock you find links with information for code as used in the function.</p>\n"
},
{
"answer_id": 349401,
"author": "cesur",
"author_id": 175983,
"author_profile": "https://wordpress.stackexchange.com/users/175983",
"pm_score": -1,
"selected": false,
"text": "<p>You can use this as well.</p>\n\n<pre><code>the_post_thumbnail( 'large', array( 'title' => get_the_title(get_post_thumbnail_id()),'alt' => get_the_post_thumbnail_caption() ) );\n</code></pre>\n"
}
]
| 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.com/jquery-3.3.1.slim.min.js', array('jquery'));\n wp_enqueue_script( 'boot2','https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js', array('jquery'));\n wp_enqueue_script( 'boot3','https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js', array('jquery'));\n}\nadd_action( 'wp_enqueue_scripts', 'abc_load_my_scripts', 999);\n</code></pre>\n\n<p>With the last argument <code>array('jquery')</code> you're telling WP to include the script AFTER jQuery. Note that every script must use a different handle (first parameter).</p>\n\n<p>More info <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>When you check the <code><head></code>, are you certain the scripts aren't loaded?</p>\n\n<p>Regards, Bjorn</p>\n"
},
{
"answer_id": 306264,
"author": "Akshat",
"author_id": 114978,
"author_profile": "https://wordpress.stackexchange.com/users/114978",
"pm_score": 4,
"selected": true,
"text": "<p>You can use action hook and enqueue script and style to the site.</p>\n\n<pre><code>function my_scripts() {\n wp_enqueue_style('bootstrap4', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css');\n wp_enqueue_script( 'boot1','https://code.jquery.com/jquery-3.3.1.slim.min.js', array( 'jquery' ),'',true );\n wp_enqueue_script( 'boot2','https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js', array( 'jquery' ),'',true );\n wp_enqueue_script( 'boot3','https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js', array( 'jquery' ),'',true );\n}\nadd_action( 'wp_enqueue_scripts', 'my_scripts' );\n</code></pre>\n\n<p>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.</p>\n"
}
]
| 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 parameters you want are public. So, you can directly access them:</p>\n\n<pre><code> $customer_email = $order->billing_email;\n $shipping_country = $order->shipping_country;\n</code></pre>\n\n<p>And so on.</p>\n\n<p>Please check the keys before using them.</p>\n"
},
{
"answer_id": 393807,
"author": "Andrew",
"author_id": 182920,
"author_profile": "https://wordpress.stackexchange.com/users/182920",
"pm_score": 0,
"selected": false,
"text": "<p>Newer WooCommerce versions doesn't allow direct access and you'd need to use:</p>\n<p><code>$customer_email = $order->get_billing_email();</code></p>\n"
}
]
| 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></code>.<br />\nAlso verify that you have added font-awesome in your theme and function file.</p>\n"
},
{
"answer_id": 306387,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 3,
"selected": true,
"text": "<p>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:</p>\n\n<pre><code><i class=\"fab fa-facebook\">&nbsp;</i>\n</code></pre>\n"
},
{
"answer_id": 326978,
"author": "ASJorg",
"author_id": 29115,
"author_profile": "https://wordpress.stackexchange.com/users/29115",
"pm_score": 0,
"selected": false,
"text": "<p>@Harsh - The original poster was using the syntax from Font Awesome 5, where different prefixes are used based on whether it is a brand (fab prefix), solid (fas prefix), regular (far prefix) and light (fal prefix). </p>\n\n<p>Also, I found that the <code>\"&nbsp;\"</code> did resolve disappearing icon the issue for me. </p>\n"
}
]
| 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_action( 'admin_menu', 'wpse_306432_edit_post_type_admin_menu', 11);\nfunction wpse_306432_edit_post_type_admin_menu()\n{\n global $menu;\n\n foreach($menu as $k => $v){\n if($v[1] == 'edit_applications') // possibly 'edit_application', I'm not sure\n {\n $menu[$k][2] = 'edit.php?post_status=all&post_type=application&cat=36&paged=1'; // I modify your query\n break;\n }\n }\n}\n</code></pre>\n\n<p>Should work for you :)</p>\n\n<p>Don't hesitate to add a nice :</p>\n\n<pre><code>echo '<pre>';\nvar_dump($menu);\necho '</pre>';\ndie();\n</code></pre>\n\n<p>After <code>global $menu</code> to understand how it works, and change more !</p>\n"
},
{
"answer_id": 306438,
"author": "venomphil",
"author_id": 145497,
"author_profile": "https://wordpress.stackexchange.com/users/145497",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for your answer :) That looks like a better solution that what i've come up with!</p>\n\n<p>I've added javascript to the admin and updated the link that way</p>\n\n<pre><code>function custom_admin_js() {\n$url = get_bloginfo('template_directory') . '/library/js/wp-admin-XXX.js';\nif( current_user_can( 'XX' ) ){ \n echo '\"<script type=\"text/javascript\" src=\"'. $url . '\"></script>'\";\n}; } add_action('admin_footer', 'custom_admin_js');\n</code></pre>\n"
}
]
| 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_action( 'admin_menu', 'wpse_306432_edit_post_type_admin_menu', 11);\nfunction wpse_306432_edit_post_type_admin_menu()\n{\n global $menu;\n\n foreach($menu as $k => $v){\n if($v[1] == 'edit_applications') // possibly 'edit_application', I'm not sure\n {\n $menu[$k][2] = 'edit.php?post_status=all&post_type=application&cat=36&paged=1'; // I modify your query\n break;\n }\n }\n}\n</code></pre>\n\n<p>Should work for you :)</p>\n\n<p>Don't hesitate to add a nice :</p>\n\n<pre><code>echo '<pre>';\nvar_dump($menu);\necho '</pre>';\ndie();\n</code></pre>\n\n<p>After <code>global $menu</code> to understand how it works, and change more !</p>\n"
},
{
"answer_id": 306438,
"author": "venomphil",
"author_id": 145497,
"author_profile": "https://wordpress.stackexchange.com/users/145497",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for your answer :) That looks like a better solution that what i've come up with!</p>\n\n<p>I've added javascript to the admin and updated the link that way</p>\n\n<pre><code>function custom_admin_js() {\n$url = get_bloginfo('template_directory') . '/library/js/wp-admin-XXX.js';\nif( current_user_can( 'XX' ) ){ \n echo '\"<script type=\"text/javascript\" src=\"'. $url . '\"></script>'\";\n}; } add_action('admin_footer', 'custom_admin_js');\n</code></pre>\n"
}
]
| 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 presume this might be helpful to someone and in the mean while I found a solution..</p>\n\n<p>I had to use the second version of 'add_rewrite_rule':</p>\n\n<pre><code>add_rewrite_rule( \n '^products/directory/?([^/]*)/?',\n 'index.php?post_type=acme_product&c=$matches[1]',\n 'top'\n);\n</code></pre>\n\n<p>I needed to register a query var,, since external query params aren't recognizable to WordPress</p>\n\n<pre><code>function 123wp_query_vars( $query_vars ){\n $query_vars[] = 'c';\n return $query_vars;\n}\nadd_filter( 'query_vars', '123wp_query_vars' );\n</code></pre>\n\n<p>Then retrieve the value in the template using:</p>\n\n<pre><code>get_query_var( 'c' );\n</code></pre>\n"
},
{
"answer_id": 385724,
"author": "Felipe Fernandes Rosa",
"author_id": 203964,
"author_profile": "https://wordpress.stackexchange.com/users/203964",
"pm_score": 0,
"selected": false,
"text": "<p>If you just want a redirect with regex, use Yoast SEO and select Redirects and choose option Regex.</p>\n<p>For a url go from <code>http://example.com/products/?c=some-value</code> to <code>http://example.com/products/some-value</code> use this regex expression and paste on Yoast redirect regex page:</p>\n<blockquote>\n<p><strong>Type:</strong> 301 Moved Permanently<br />\n<strong>Regex Expression:</strong> products/?c=/?([^/]*)/?<br />\n<strong>URL:</strong> products/$1</p>\n</blockquote>\n<p>I hope it helps another people who wants to redirect not just <strong>add and rewrite_rule</strong></p>\n<p>Best,</p>\n"
}
]
| 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 code :</p>\n\n<pre><code>function mte_custom_menu_page_removing() { \nremove_menu_page( 'wpseo_dashboard' ); //Yoast\n</code></pre>\n\n<p>I am also interested to know how to move all other plugins in the settings submenu.</p>\n\n<p><a href=\"https://codetheworld.info/2016/11/deplacer-le-menu-dune-extension-wordpress-dans-un-sous-menu/\" rel=\"nofollow noreferrer\">-> Maybe an other solution here</a></p>\n"
},
{
"answer_id": 358377,
"author": "Chris Pink",
"author_id": 57686,
"author_profile": "https://wordpress.stackexchange.com/users/57686",
"pm_score": 3,
"selected": true,
"text": "<p>You seem to be making life complicated. Here's the code you need;</p>\n\n<pre><code>function menu_shuffle() {\n remove_menu_page( 'plugin-page' );\n add_submenu_page('options-general.php','Page Title', 'Menu Label','manage_options', 'plugin-page' );\n};\n\nadd_action( 'admin_menu', 'menu_shuffle' );\n</code></pre>\n\n<p><code>plugin-page</code> can be found by mousing over the existing menu label and getting the part after the <code>?page=</code>in this case <code>?page=plugin-page</code></p>\n\n<p>The Wordpress function definition for <code>add_submenu_page()</code> <a href=\"https://developer.wordpress.org/reference/functions/add_submenu_page/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_submenu_page/</a> includes a list of all the menu page slugs (and you need the '.php').</p>\n\n<p>so in the example above for Yoast (bless its pointy little head and use Hide SEO Bloat)</p>\n\n<pre><code>function menu_shuffle() {\n remove_menu_page( 'wpseo_dashboard' );\n add_submenu_page('options-general.php','Yoast SE0', 'SEO','manage_options', 'wpseo_dashboard' );\n};\n\nadd_action( 'admin_menu', 'menu_shuffle' );\n</code></pre>\n"
}
]
| 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 area you want to block. Then add that CSS code to your Additional CSS in your theme.</p>\n\n<p>If the CSS class is 'rememberme', then </p>\n\n<pre><code>.rememberme {display:none !important;}\n</code></pre>\n\n<p>in the Additional CSS of your theme (via the Customizer) should work to hide that block.</p>\n\n<p><strong>Added</strong></p>\n\n<p>You might look into the login_form_defaults filter, as in </p>\n\n<pre><code>add_filter('login_form_defaults', $args);\n</code></pre>\n\n<p>Using your $args. This is supposed to set the default arguments for the <code>wp_login_form()</code> function.</p>\n\n<p>...and the class used by wp_login_form is <code>login-remember</code> about line 470 in the <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.6/src/wp-includes/general-template.php#L0\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/4.9.6/src/wp-includes/general-template.php#L0</a> core code. (Looking at the core code is always helpful...)</p>\n\n<p>** <strong>Added</strong> **</p>\n\n<p>Well, the above code is not correct. According to the docs, this should work:</p>\n\n<pre><code> add_filter( 'login_form_defaults', 'wp_disable_remember_me',10,1);\n\nfunction wp_disable_remember_me($args ) {\n\n $args['value_remember'] = false;\n $args['remember']= false;\nreturn $args;\n}\n</code></pre>\n\n<p>....but it doesn't. Not sure why; have tested it with several sites/themes.</p>\n\n<p>So perhaps the CSS 'hide' solution is the only choice.</p>\n"
},
{
"answer_id": 306746,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 2,
"selected": false,
"text": "<p>There is a <code>remember</code> argument for <code>wp_login_form()</code>. Just set it to false:</p>\n\n<pre><code>$args = array(\n 'remember' => false,\n);\n\nwp_login_form( $args );\n</code></pre>\n"
}
]
| 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 area you want to block. Then add that CSS code to your Additional CSS in your theme.</p>\n\n<p>If the CSS class is 'rememberme', then </p>\n\n<pre><code>.rememberme {display:none !important;}\n</code></pre>\n\n<p>in the Additional CSS of your theme (via the Customizer) should work to hide that block.</p>\n\n<p><strong>Added</strong></p>\n\n<p>You might look into the login_form_defaults filter, as in </p>\n\n<pre><code>add_filter('login_form_defaults', $args);\n</code></pre>\n\n<p>Using your $args. This is supposed to set the default arguments for the <code>wp_login_form()</code> function.</p>\n\n<p>...and the class used by wp_login_form is <code>login-remember</code> about line 470 in the <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.6/src/wp-includes/general-template.php#L0\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/4.9.6/src/wp-includes/general-template.php#L0</a> core code. (Looking at the core code is always helpful...)</p>\n\n<p>** <strong>Added</strong> **</p>\n\n<p>Well, the above code is not correct. According to the docs, this should work:</p>\n\n<pre><code> add_filter( 'login_form_defaults', 'wp_disable_remember_me',10,1);\n\nfunction wp_disable_remember_me($args ) {\n\n $args['value_remember'] = false;\n $args['remember']= false;\nreturn $args;\n}\n</code></pre>\n\n<p>....but it doesn't. Not sure why; have tested it with several sites/themes.</p>\n\n<p>So perhaps the CSS 'hide' solution is the only choice.</p>\n"
},
{
"answer_id": 306746,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 2,
"selected": false,
"text": "<p>There is a <code>remember</code> argument for <code>wp_login_form()</code>. Just set it to false:</p>\n\n<pre><code>$args = array(\n 'remember' => false,\n);\n\nwp_login_form( $args );\n</code></pre>\n"
}
]
| 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><code>add_action( 'template_redirect', 'wpse_restrict_catgorey');\nfunction wpse_restrict_catgorey(){\n\n if( ! is_user_logged_in() && is_category( 'app-data' ) ) {\n wp_redirect( home_url() );\n exit;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 306503,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<h2>Why it's not working?</h2>\n\n<p>There is one major problem with your code... You can't redirect after any html content was already sent... Such redirect will be ignored...</p>\n\n<p>So why is your code incorrect? Because of <code>the_post</code> 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...</p>\n\n<h2>So how to fix your code?</h2>\n\n<p>Use another hook. </p>\n\n<p>Here is the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">list of available hooks fired up during typical request</a>.</p>\n\n<p>One of the best hooks for doing redirects (<a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect#Performing_a_redirect\" rel=\"nofollow noreferrer\">and commonly used for that</a>) is <code>template_redirect</code>. As you can see it's fired up just before getting header, so everything is already set up.</p>\n\n<pre><code>function redirect_not_app_users_if_app_data_category() {\n if ( (is_category( 'app-data' ) || in_category('app-data'))&& ! is_user_logged_in() ) {\n wp_redirect( home_url() );\n die;\n }\n}\nadd_action( 'template_redirect', 'redirect_not_app_users_if_app_data_category');\n</code></pre>\n"
}
]
| 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( 'category2-slug' ) ) {\n //...\n}\n</code></pre>\n"
},
{
"answer_id": 306516,
"author": "Shamsur Rahman",
"author_id": 92258,
"author_profile": "https://wordpress.stackexchange.com/users/92258",
"pm_score": 4,
"selected": true,
"text": "<p><code>is_product_category()</code> is to be used on woocommerce category archive pages only so first make sure that you are on category archive.</p>\n\n<p>instead of category number use category slug name <code>is_product_category('category-slug')</code></p>\n\n<p>no need to run OR(||) condition just use <code>is_product_category('category-slug1','category-slug2')</code> to get same output</p>\n"
},
{
"answer_id": 360383,
"author": "blift",
"author_id": 184075,
"author_profile": "https://wordpress.stackexchange.com/users/184075",
"pm_score": 0,
"selected": false,
"text": "<p>For a few categories, you should use slugs in array when you use is_product_category() function. Below example. Tested and works.</p>\n\n<pre><code>if( is_product_category( array('category1-slug', 'category2-slug' )) )\n</code></pre>\n"
}
]
| 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> and use the command <code>wp term list wpmf-gallery-category</code> 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</p>\n\n<pre><code>/*\n get_root_gallery_id();\n Custom function that returns the id of folder with parent id == 0\n*/\n$master_id = get_root_gallery_id( 'master' );\n$galleries = get_terms( 'wpmf-gallery-category', [ 'hide_empty' => 0 ]);\n\n // If there is a root folder\n if ( $master_id )\n {\n foreach ( $galleries as $gal )\n {\n if ( $gal->parent == $master_id )\n {\n $args = [\n 'post_type' => 'attachment',\n 'posts_per_page' => -1,\n 'post_status' => 'inherit'\n\n 'tax_query' => [\n [\n 'taxonomy' => 'wpmf-gallery-category',\n 'terms' => [ $gal->term_id ],\n 'field' => 'term_id'\n ]\n ]\n ];\n\n $query = new WP_Query( $args );\n\n if ( $query->have_posts() )\n {\n while ( $query->have_posts() )\n {\n\n $query->the_post();\n\n global $post; // Image as Post Object\n }\n }\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 306812,
"author": "Lisa Baird",
"author_id": 145764,
"author_profile": "https://wordpress.stackexchange.com/users/145764",
"pm_score": 0,
"selected": false,
"text": "<p>We use 2 plugins to accomplish this without programming, the bonus being we don't have to worry about updating the code every 3 months...downside is obvious... MLA Library (Media Library Assistant I think is the actual name) and Content Views Pro by PT Guy. I can't remember if the free let's you filter media. </p>\n"
}
]
| 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/20180827171724/https://623lafayette.com/2018/05/02/wordpress-failed-to-set-referrer-policy/\" rel=\"nofollow noreferrer\">WordPress Failed to Set Referrer Policy Response Headers – W3 Total Cache</a></p>\n"
},
{
"answer_id": 311971,
"author": "Jorge Casariego",
"author_id": 137650,
"author_profile": "https://wordpress.stackexchange.com/users/137650",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Chris</strong> did you try the solution from the <a href=\"https://wordpress.org/support/topic/failed-to-set-referrer-policy-error/\" rel=\"nofollow noreferrer\">WordPress Forum</a>?</p>\n\n<p>According to some users, this can solve the problem. Go into your <strong>.htaccess</strong> file and change the following:</p>\n\n<blockquote>\n <p>Header set Referrer-Policy \"\"</p>\n</blockquote>\n\n<p>to</p>\n\n<blockquote>\n <p>Header set Referrer-Policy \"origin\"</p>\n</blockquote>\n"
}
]
| 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 footer that's the best way to call js files. \nYou can add below code to your footer:</p>\n\n<pre><code><script src=\"<?php echo get_template_directory_uri(); ?>/filename.js\"></script>\n</code></pre>\n"
},
{
"answer_id": 306639,
"author": "Akshat",
"author_id": 114978,
"author_profile": "https://wordpress.stackexchange.com/users/114978",
"pm_score": 5,
"selected": false,
"text": "<p>You should enqueue the script in child theme's functions.php.\nfor 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</p>\n\n<pre><code>function my_custom_scripts() {\n wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array( 'jquery' ),'',true );\n}\nadd_action( 'wp_enqueue_scripts', 'my_custom_scripts' );\n</code></pre>\n\n<p>Here <code>get_stylesheet_directory_uri()</code> will return the directory of your child theme, then <code>array( 'jquery' )</code> 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.</p>\n"
}
]
| 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 currently undefined.</p>\n\n<p>You could work around this by attaching another function to the <code>retrieve_password_key</code> action, which fires just after WordPress generates the key. From its name I would think it exists just for this purpose.</p>\n\n<pre><code>function wpse306642_stash_key( $user_login, $key ) {\n global $wpse306642_new_user_key;\n $wpse306642_new_user_key = $key;\n}\n\nadd_action( 'retrieve_password_key', 'wpse306642_stash_key', 10, 2 );\n</code></pre>\n\n<p>Then replace <code>$key</code> in your function with <code>$wpse306642_new_user_key</code>, declaring it as global at the start of the function.</p>\n\n<p>Using a global just for this does feel a little hacky, but it should work.</p>\n"
},
{
"answer_id": 317496,
"author": "Dimitris Siakavelis",
"author_id": 143359,
"author_profile": "https://wordpress.stackexchange.com/users/143359",
"pm_score": 2,
"selected": false,
"text": "<p>You need to use the <code>get_password_reset_key</code> function <a href=\"https://developer.wordpress.org/reference/functions/get_password_reset_key/\" rel=\"nofollow noreferrer\">(see reference)</a> which will query the database and return the reset password key of the user.</p>\n\n<p>Here's a full working example:</p>\n\n<pre><code>add_filter( 'wp_new_user_notification_email', 'custom_wp_new_user_notification_email', 10, 3 );\n\nfunction custom_wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname ) {\n $key = get_password_reset_key( $user );\n $message = sprintf(__('Welcome to the Community,')) . \"\\r\\n\\r\\n\";\n $message .= 'To set your password, visit the following address:' . \"\\r\\n\\r\\n\";\n $message .= network_site_url(\"wp-login.php?action=rp&key=$key&login=\" . rawurlencode($user->user_login), 'login') . \"\\r\\n\\r\\n\";\n $message .= \"After this you can enjoy our website!\" . \"\\r\\n\\r\\n\";\n $message .= \"Kind regards,\" . \"\\r\\n\";\n $message .= \"Support Office Team\" . \"\\r\\n\";\n $wp_new_user_notification_email['message'] = $message;\n\n $wp_new_user_notification_email['headers'] = 'From: MyName<[email protected]>'; // this just changes the sender name and email to whatever you want (instead of the default WordPress <[email protected]>\n\n return $wp_new_user_notification_email;\n}\n</code></pre>\n"
}
]
| 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<[email protected]>'; // this just changes the sender name and email to whatever you want (instead of the default WordPress <[email protected]>
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 noreferrer\">Really simple SSL plugin</a>. Or Htaccess code can fix this.</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^www.example.com [NC,OR]\nRewriteCond %{HTTP_HOST} ^example.com [NC]\nRewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]\n</code></pre>\n"
},
{
"answer_id": 306696,
"author": "itinerant",
"author_id": 33455,
"author_profile": "https://wordpress.stackexchange.com/users/33455",
"pm_score": 2,
"selected": false,
"text": "<p>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 (<a href=\"https://codex.wordpress.org/Administration_Over_SSL\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Administration_Over_SSL</a>)</p>\n\n<p>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).</p>\n\n<p>Usually that would be:</p>\n\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteCond %{HTTPS} !=on\n RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]\n</IfModule>\n</code></pre>\n\n<p>but some hosts require an environment variable:</p>\n\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteCond %{ENV:HTTPS} !=on\n RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]\n</IfModule>\n</code></pre>\n\n<p>If you're using Windows hosting .htaccess won't work, you'll need to use web.config</p>\n\n<pre><code><rule name=\"HTTPS\" patternSyntax=\"Wildcard\" stopProcessing=\"true\">\n <match url=\"*\" />\n <conditions>\n <add input=\"{HTTPS}\" pattern=\"off\" />\n </conditions>\n <action type=\"Redirect\" url=\"https://{HTTP_HOST}{REQUEST_URI}\" redirectType=\"Found\" />\n</rule>\n</code></pre>\n\n<h2>Related Considerations</h2>\n\n<p>I'd recommend you change all links under your control to use https. Within WordPress the <a href=\"https://en-gb.wordpress.org/plugins/velvet-blues-update-urls/\" rel=\"nofollow noreferrer\">https://en-gb.wordpress.org/plugins/velvet-blues-update-urls/</a> is very handy for this.</p>\n\n<p>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 <a href=\"https://reviewofweb.com/how-to/migrate-wordpress-from-http-to-https/\" rel=\"nofollow noreferrer\">https://reviewofweb.com/how-to/migrate-wordpress-from-http-to-https/</a></p>\n"
}
]
| 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 noreferrer\">Really simple SSL plugin</a>. Or Htaccess code can fix this.</p>\n\n<pre><code>RewriteCond %{HTTP_HOST} ^www.example.com [NC,OR]\nRewriteCond %{HTTP_HOST} ^example.com [NC]\nRewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]\n</code></pre>\n"
},
{
"answer_id": 306696,
"author": "itinerant",
"author_id": 33455,
"author_profile": "https://wordpress.stackexchange.com/users/33455",
"pm_score": 2,
"selected": false,
"text": "<p>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 (<a href=\"https://codex.wordpress.org/Administration_Over_SSL\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Administration_Over_SSL</a>)</p>\n\n<p>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).</p>\n\n<p>Usually that would be:</p>\n\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteCond %{HTTPS} !=on\n RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]\n</IfModule>\n</code></pre>\n\n<p>but some hosts require an environment variable:</p>\n\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteCond %{ENV:HTTPS} !=on\n RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]\n</IfModule>\n</code></pre>\n\n<p>If you're using Windows hosting .htaccess won't work, you'll need to use web.config</p>\n\n<pre><code><rule name=\"HTTPS\" patternSyntax=\"Wildcard\" stopProcessing=\"true\">\n <match url=\"*\" />\n <conditions>\n <add input=\"{HTTPS}\" pattern=\"off\" />\n </conditions>\n <action type=\"Redirect\" url=\"https://{HTTP_HOST}{REQUEST_URI}\" redirectType=\"Found\" />\n</rule>\n</code></pre>\n\n<h2>Related Considerations</h2>\n\n<p>I'd recommend you change all links under your control to use https. Within WordPress the <a href=\"https://en-gb.wordpress.org/plugins/velvet-blues-update-urls/\" rel=\"nofollow noreferrer\">https://en-gb.wordpress.org/plugins/velvet-blues-update-urls/</a> is very handy for this.</p>\n\n<p>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 <a href=\"https://reviewofweb.com/how-to/migrate-wordpress-from-http-to-https/\" rel=\"nofollow noreferrer\">https://reviewofweb.com/how-to/migrate-wordpress-from-http-to-https/</a></p>\n"
}
]
| 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/> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.