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 |
|---|---|---|---|---|---|---|
306,726 | <p>I apologize in advance if this is wrong place to ask my question (mods: please move it to appropriate place)</p>
<hr>
<p>I'm seeing following message in my wordpress logs:</p>
<blockquote>
<p>PHP Warning: include(): Unable to allocate memory for pool.</p>
</blockquote>
<p>and/or</p>
<blockquote>
<p>PHP Warning: Unknown: Unable to allocate memory for pool. in Unknown
on line 0</p>
</blockquote>
<p><code>php -v</code>:</p>
<pre><code># php -v
PHP 5.3.3 (cli) (built: Nov 7 2016 11:21:30)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
#
</code></pre>
<p><code>memory_limit</code> and/or <code>apc.shm_size</code> set to <code>128M</code>:</p>
<pre><code># grep ^memory_limit ./php.ini
memory_limit = 128M
# grep ^apc.shm_size ./php.d/apc.ini
apc.shm_size=128M
#
</code></pre>
<hr>
<p>I've tried setting <code>memory_limit</code> to <code>-1</code> and/or <code>512M</code> for test, yet same results (message above).</p>
<p>Please advise.</p>
| [
{
"answer_id": 306735,
"author": "Edward Caissie",
"author_id": 1952,
"author_profile": "https://wordpress.stackexchange.com/users/1952",
"pm_score": 1,
"selected": false,
"text": "<p>Does this topic help (it appears to be referencing the items you are looking at currently) <a href=\"htt... | 2018/06/22 | [
"https://wordpress.stackexchange.com/questions/306726",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3255/"
] | I apologize in advance if this is wrong place to ask my question (mods: please move it to appropriate place)
---
I'm seeing following message in my wordpress logs:
>
> PHP Warning: include(): Unable to allocate memory for pool.
>
>
>
and/or
>
> PHP Warning: Unknown: Unable to allocate memory for pool. in Unknown
> on line 0
>
>
>
`php -v`:
```
# php -v
PHP 5.3.3 (cli) (built: Nov 7 2016 11:21:30)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
#
```
`memory_limit` and/or `apc.shm_size` set to `128M`:
```
# grep ^memory_limit ./php.ini
memory_limit = 128M
# grep ^apc.shm_size ./php.d/apc.ini
apc.shm_size=128M
#
```
---
I've tried setting `memory_limit` to `-1` and/or `512M` for test, yet same results (message above).
Please advise. | Does this topic help (it appears to be referencing the items you are looking at currently) <https://stackoverflow.com/questions/3723316/what-is-causing-unable-to-allocate-memory-for-pool-in-php> ? |
306,752 | <p>I'm hoping someone who knows more than me about PHP and WordPress can help me out with this issue. I have a custom post type with posts I am displaying using the following code:</p>
<pre><code><?php $args = array( 'post_type' => 'upcoming_event', 'posts_per_page' => 3 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="upcomingevents">';
echo '<h4>';
the_title();
echo '</h4>';
echo '<div class="upcomingeventimage">';
the_post_thumbnail('medium');
echo '</div>';
echo '<div class="upcoming-event-entry-content">';
the_content();
echo '</div>';
echo '</div>';
endwhile;
wp_reset_postdata();
?>
</code></pre>
<p>While this works fine in a php file, I'm trying to also make it easily accessible via shortcode. I made the shortcode, and the shortcode works, but every time I place it on a page/post and click "update" or "publish" it sends me to a page with this content printed on it (and only this content printed on it)... But it still saves it, and it still displays fine on the page I saved it on. I know I'm missing something, but I'm so novice at PHP that I don't know what it is.</p>
<p>Here's my shortcode:</p>
<pre><code>// Shortcode for Upcoming Events
function upcoming_events_shortcode() {
$args = array( 'post_type' => 'upcoming_event', 'posts_per_page' => 3 );
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="upcomingevents">';
echo '<h4>';
the_title();
echo '</h4>';
echo '<div class="upcomingeventimage">';
the_post_thumbnail('medium');
echo '</div>';
echo '<div class="upcoming-event-entry-content">';
the_content();
echo '</div>';
echo '</div>';
endwhile;
wp_reset_postdata();
}
add_shortcode('upcoming-events', 'upcoming_events_shortcode');
</code></pre>
<p>Thanks for any help! I'm learning as I go with this and usually I can Google my way out of most things, not this one though. Scratching my head on it.</p>
| [
{
"answer_id": 306735,
"author": "Edward Caissie",
"author_id": 1952,
"author_profile": "https://wordpress.stackexchange.com/users/1952",
"pm_score": 1,
"selected": false,
"text": "<p>Does this topic help (it appears to be referencing the items you are looking at currently) <a href=\"htt... | 2018/06/22 | [
"https://wordpress.stackexchange.com/questions/306752",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145742/"
] | I'm hoping someone who knows more than me about PHP and WordPress can help me out with this issue. I have a custom post type with posts I am displaying using the following code:
```
<?php $args = array( 'post_type' => 'upcoming_event', 'posts_per_page' => 3 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="upcomingevents">';
echo '<h4>';
the_title();
echo '</h4>';
echo '<div class="upcomingeventimage">';
the_post_thumbnail('medium');
echo '</div>';
echo '<div class="upcoming-event-entry-content">';
the_content();
echo '</div>';
echo '</div>';
endwhile;
wp_reset_postdata();
?>
```
While this works fine in a php file, I'm trying to also make it easily accessible via shortcode. I made the shortcode, and the shortcode works, but every time I place it on a page/post and click "update" or "publish" it sends me to a page with this content printed on it (and only this content printed on it)... But it still saves it, and it still displays fine on the page I saved it on. I know I'm missing something, but I'm so novice at PHP that I don't know what it is.
Here's my shortcode:
```
// Shortcode for Upcoming Events
function upcoming_events_shortcode() {
$args = array( 'post_type' => 'upcoming_event', 'posts_per_page' => 3 );
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
echo '<div class="upcomingevents">';
echo '<h4>';
the_title();
echo '</h4>';
echo '<div class="upcomingeventimage">';
the_post_thumbnail('medium');
echo '</div>';
echo '<div class="upcoming-event-entry-content">';
the_content();
echo '</div>';
echo '</div>';
endwhile;
wp_reset_postdata();
}
add_shortcode('upcoming-events', 'upcoming_events_shortcode');
```
Thanks for any help! I'm learning as I go with this and usually I can Google my way out of most things, not this one though. Scratching my head on it. | Does this topic help (it appears to be referencing the items you are looking at currently) <https://stackoverflow.com/questions/3723316/what-is-causing-unable-to-allocate-memory-for-pool-in-php> ? |
306,756 | <p>I noticed recently that when uploading files larger than 7mb to a Wordpress site that I developed, I get an HTTP Error. I've checked some of my PHP variables, and have verified that <code>memory_limit</code> is set to 256M and both <code>post_max_size</code> and <code>upload_max_filesize</code> are set to 128M. After reading <a href="https://wordpress.stackexchange.com/questions/51592/http-error-when-uploading-images">this thread</a>, I tried installing the Default to GD plugin that uses GD as the default WP_Image_Editor class.</p>
<p>After installing the plugin, I'm not having the issue anymore. That said, I'm curious if there's a way to fix this issue with the newer WP_Image_Editor class?</p>
<p>I've also noticed that when I get the HTTP error, I can look at the files attached to the post I added the file to and see that the file is actually there and was successfully uploaded. However, Wordpress seems to have issues displaying it in the Media browser.</p>
<p>I also noticed that if I upload multiple large images over 7mb, I will see the most recent image as the first item in the media library. If I delete that image, I'll see the next most recently uploaded image. For some reason Wordpress is only able to show the most recent image and the thumbnail seems to be broken. However if you navigate to the uploaded file's URI, you can see that the file uploaded successfully.</p>
<p>Does anyone have an idea what's going on with this and is this a known error in Wordpress that's being addressed? Thanks!</p>
| [
{
"answer_id": 306761,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 2,
"selected": false,
"text": "<p>I sometimes get this exact same issue and set of symptoms.</p>\n\n<p>It's caused by the image bei... | 2018/06/22 | [
"https://wordpress.stackexchange.com/questions/306756",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47939/"
] | I noticed recently that when uploading files larger than 7mb to a Wordpress site that I developed, I get an HTTP Error. I've checked some of my PHP variables, and have verified that `memory_limit` is set to 256M and both `post_max_size` and `upload_max_filesize` are set to 128M. After reading [this thread](https://wordpress.stackexchange.com/questions/51592/http-error-when-uploading-images), I tried installing the Default to GD plugin that uses GD as the default WP\_Image\_Editor class.
After installing the plugin, I'm not having the issue anymore. That said, I'm curious if there's a way to fix this issue with the newer WP\_Image\_Editor class?
I've also noticed that when I get the HTTP error, I can look at the files attached to the post I added the file to and see that the file is actually there and was successfully uploaded. However, Wordpress seems to have issues displaying it in the Media browser.
I also noticed that if I upload multiple large images over 7mb, I will see the most recent image as the first item in the media library. If I delete that image, I'll see the next most recently uploaded image. For some reason Wordpress is only able to show the most recent image and the thumbnail seems to be broken. However if you navigate to the uploaded file's URI, you can see that the file uploaded successfully.
Does anyone have an idea what's going on with this and is this a known error in Wordpress that's being addressed? Thanks! | I sometimes get this exact same issue and set of symptoms.
It's caused by the image being too large for the memory available. Not the file size as that has compressed data, but the actual width x height x colourdepth.
You can see the full size image because it uploaded fine. You have trouble in the media browser because WP ran out of memory while scaling and cropping the image and so there is no version available for the media browser thumbnail.
I've always found that allocating much more memory to the process fixes it. Or use smaller images (dimensions, not file size).
WordPress will use the higher of WP\_MAX\_MEMORY\_LIMIT and your PHP memory limit, so as long as your hosting allows the easiest thing to do is to set WP\_MAX\_MEMORY\_LIMIT in your wp-config.php:
```
define( 'WP_MAX_MEMORY_LIMIT', '257M' ); // you choose how much
```
The default is 256M for image handling anyway, so if you have problems resizing images it'll need to be something higher than 256M.
As long as your host allows PHP to increase the memory using `@ini_set` then this will work. |
306,784 | <p><a href="https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet" rel="nofollow noreferrer">WordPress documentation</a> says to enqueue parent stylesheet in child theme:</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
$parent_style = 'parent-style';
// Why enqueue parent style again? The child theme works perfectly without this line
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
</code></pre>
<p>But parent theme stylesheet is already enqueued in parent theme, what's the point to enqueue it again in child theme?</p>
| [
{
"answer_id": 306761,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 2,
"selected": false,
"text": "<p>I sometimes get this exact same issue and set of symptoms.</p>\n\n<p>It's caused by the image bei... | 2018/06/23 | [
"https://wordpress.stackexchange.com/questions/306784",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2426/"
] | [WordPress documentation](https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet) says to enqueue parent stylesheet in child theme:
```
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
$parent_style = 'parent-style';
// Why enqueue parent style again? The child theme works perfectly without this line
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
```
But parent theme stylesheet is already enqueued in parent theme, what's the point to enqueue it again in child theme? | I sometimes get this exact same issue and set of symptoms.
It's caused by the image being too large for the memory available. Not the file size as that has compressed data, but the actual width x height x colourdepth.
You can see the full size image because it uploaded fine. You have trouble in the media browser because WP ran out of memory while scaling and cropping the image and so there is no version available for the media browser thumbnail.
I've always found that allocating much more memory to the process fixes it. Or use smaller images (dimensions, not file size).
WordPress will use the higher of WP\_MAX\_MEMORY\_LIMIT and your PHP memory limit, so as long as your hosting allows the easiest thing to do is to set WP\_MAX\_MEMORY\_LIMIT in your wp-config.php:
```
define( 'WP_MAX_MEMORY_LIMIT', '257M' ); // you choose how much
```
The default is 256M for image handling anyway, so if you have problems resizing images it'll need to be something higher than 256M.
As long as your host allows PHP to increase the memory using `@ini_set` then this will work. |
306,816 | <p>I'm using Contact Form 7 and Flamingo to create a consultant registration form on my Wordpress site. By my client request, every submission need to have a registration code (reg_code) which is a combination of submission date and a random number to make it unique.</p>
<p>So I added an hidden input field to my CF7 code with the id "reg_code". On my first try, I used JS to generate a "reg_code" variable right after users visit my site and set the hidden field value to the generated "reg_code" variable. The "reg_code" was saved to CF7 submission successfully but in some cases, when a user didn't submit the form at the first visit time but after a few days, the date part in his "reg_code" would not be correct because that code was generated at his first visit time and cached in the browser.</p>
<p>To avoid this issue, I decided to move the "reg_code" generation function from JS to PHP and the procedure would be like this:</p>
<ol>
<li>Submit button clicked</li>
<li>Use AJAX to call a PHP function which returns a reg_code</li>
<li>Set the hidden field "reg_code" in CF7 value to the returned result</li>
<li>Really perform CF7 submission which saves all CF7 fields to Flamingo</li>
</ol>
<p>This is my JS to trigger the AJAX call before CF7 submit event:</p>
<pre><code>$('.wpcf7-form').on('submit', function (e) {
$.ajax({
type: "post",
dataType: "json",
url: js_object.ajax_url,
data: {
action: "custom_reg_code",
},
success: function (response) {
if (response.success) {
$('#reg_code').val(response.data)
}
else {
console.log('Something wrong')
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('fail: ' + textStatus, errorThrown);
},
complete: function() {
}
})
})
</code></pre>
<p>My result: It works only some times. Only some submissions have "reg_code" value, some others have empty "reg_code".</p>
<p>As my guess, the CF7 submit event won't wait for AJAX call to be complete. I tried to add <strong>e.preventDefault()</strong> to the code above to stop the default CF7 submit but no success then. I also tried the CF7 eventListener "wpcf7submit" but still no luck.</p>
<p>Finally, the question is: Is there any way to pause the default CF7 submit event to modify an input field value, then continue the submission process ?</p>
<p>Thank you very much</p>
| [
{
"answer_id": 306819,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": true,
"text": "<p>You could save your AJAX pain and go about this in a different way by placing a hidden field withi... | 2018/06/23 | [
"https://wordpress.stackexchange.com/questions/306816",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70137/"
] | I'm using Contact Form 7 and Flamingo to create a consultant registration form on my Wordpress site. By my client request, every submission need to have a registration code (reg\_code) which is a combination of submission date and a random number to make it unique.
So I added an hidden input field to my CF7 code with the id "reg\_code". On my first try, I used JS to generate a "reg\_code" variable right after users visit my site and set the hidden field value to the generated "reg\_code" variable. The "reg\_code" was saved to CF7 submission successfully but in some cases, when a user didn't submit the form at the first visit time but after a few days, the date part in his "reg\_code" would not be correct because that code was generated at his first visit time and cached in the browser.
To avoid this issue, I decided to move the "reg\_code" generation function from JS to PHP and the procedure would be like this:
1. Submit button clicked
2. Use AJAX to call a PHP function which returns a reg\_code
3. Set the hidden field "reg\_code" in CF7 value to the returned result
4. Really perform CF7 submission which saves all CF7 fields to Flamingo
This is my JS to trigger the AJAX call before CF7 submit event:
```
$('.wpcf7-form').on('submit', function (e) {
$.ajax({
type: "post",
dataType: "json",
url: js_object.ajax_url,
data: {
action: "custom_reg_code",
},
success: function (response) {
if (response.success) {
$('#reg_code').val(response.data)
}
else {
console.log('Something wrong')
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('fail: ' + textStatus, errorThrown);
},
complete: function() {
}
})
})
```
My result: It works only some times. Only some submissions have "reg\_code" value, some others have empty "reg\_code".
As my guess, the CF7 submit event won't wait for AJAX call to be complete. I tried to add **e.preventDefault()** to the code above to stop the default CF7 submit but no success then. I also tried the CF7 eventListener "wpcf7submit" but still no luck.
Finally, the question is: Is there any way to pause the default CF7 submit event to modify an input field value, then continue the submission process ?
Thank you very much | You could save your AJAX pain and go about this in a different way by placing a hidden field within your form in PHP.
Method 1, with the aid of a plugin
==================================
I generally use the Contact Form 7 Dynamic Text Extension plugin as an easy route to creating custom CF7 tags, which still needs a little coding. You could also go the extra distance and just code your own CF7 tags, but I haven't tried that yet, but I might as an edit to this answer.
With this plugin in place you can put tags into your CF7 form like this:
```
[dynamichidden custom-reg-code “CF7_custom_reg_code”]
```
And in the email pane of CF7's admin page you'd insert [custom-reg-code].
To get it working, just make yourself a matching shortcode to generate your string:
```
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);
}
function wpse306816_CF7_custom_reg_code() {
return date("Ymd") . generateRandomString();
}
add_shortcode('CF7_custom_reg_code', 'wpse306816_CF7_custom_reg_code');
```
Hat-tip to <https://stackoverflow.com/a/13212994/6347850> for the random number generation.
Now you will have a hidden field in your form made up of the current date and a random number that you can use in your form's sent email or save in Flamingo just like any other CF7 field.
Method 2, without the aid of a plugin
=====================================
And a little research has shown that it's even easier to just write your own CF7 tag and not bother with the plugin.
To create a CF7 tag `[serial]`, you register it using `wpcf7_add_form_tag()` on the `wpcf7_init` action hook, passing the name of the tag and the name of a callback function to handle it:
```
add_action( 'wpcf7_init', 'wpse306816_CF7_add_custom_tag' );
function wpse306816_CF7_add_custom_tag() {
wpcf7_add_form_tag(
'serial',
'wpse306816_CF7_handle_custom_tag' );
}
```
And for your case, the callback simply needs to return the serial string value:
```
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);
}
function wpse306816_CF7_handle_custom_tag( $tag ) {
return date("Ymd") . generateRandomString();
}
``` |
306,859 | <p>I want my WordPress homepage to display post by popularity. Like it automatically bring the post to top which have been visited by most visitors and same in ascending order.
Any help will be appreciated.</p>
| [
{
"answer_id": 306819,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 3,
"selected": true,
"text": "<p>You could save your AJAX pain and go about this in a different way by placing a hidden field withi... | 2018/06/24 | [
"https://wordpress.stackexchange.com/questions/306859",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145800/"
] | I want my WordPress homepage to display post by popularity. Like it automatically bring the post to top which have been visited by most visitors and same in ascending order.
Any help will be appreciated. | You could save your AJAX pain and go about this in a different way by placing a hidden field within your form in PHP.
Method 1, with the aid of a plugin
==================================
I generally use the Contact Form 7 Dynamic Text Extension plugin as an easy route to creating custom CF7 tags, which still needs a little coding. You could also go the extra distance and just code your own CF7 tags, but I haven't tried that yet, but I might as an edit to this answer.
With this plugin in place you can put tags into your CF7 form like this:
```
[dynamichidden custom-reg-code “CF7_custom_reg_code”]
```
And in the email pane of CF7's admin page you'd insert [custom-reg-code].
To get it working, just make yourself a matching shortcode to generate your string:
```
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);
}
function wpse306816_CF7_custom_reg_code() {
return date("Ymd") . generateRandomString();
}
add_shortcode('CF7_custom_reg_code', 'wpse306816_CF7_custom_reg_code');
```
Hat-tip to <https://stackoverflow.com/a/13212994/6347850> for the random number generation.
Now you will have a hidden field in your form made up of the current date and a random number that you can use in your form's sent email or save in Flamingo just like any other CF7 field.
Method 2, without the aid of a plugin
=====================================
And a little research has shown that it's even easier to just write your own CF7 tag and not bother with the plugin.
To create a CF7 tag `[serial]`, you register it using `wpcf7_add_form_tag()` on the `wpcf7_init` action hook, passing the name of the tag and the name of a callback function to handle it:
```
add_action( 'wpcf7_init', 'wpse306816_CF7_add_custom_tag' );
function wpse306816_CF7_add_custom_tag() {
wpcf7_add_form_tag(
'serial',
'wpse306816_CF7_handle_custom_tag' );
}
```
And for your case, the callback simply needs to return the serial string value:
```
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);
}
function wpse306816_CF7_handle_custom_tag( $tag ) {
return date("Ymd") . generateRandomString();
}
``` |
306,868 | <p>I'm new to wordpress and am trying to develop my first own theme. The thing is: the front page must be static, with no display of posts. But I need a blog section and am trying to do it by creating a custom page template that calls the last 10 posts.</p>
<p>How would I do that using the loop? Please, help me! Thank you all in advance!</p>
| [
{
"answer_id": 306879,
"author": "Andy Macaulay-Brook",
"author_id": 94267,
"author_profile": "https://wordpress.stackexchange.com/users/94267",
"pm_score": 0,
"selected": false,
"text": "<p>If you create a page template with your own query, you are throwing away all the work WordPress d... | 2018/06/25 | [
"https://wordpress.stackexchange.com/questions/306868",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145809/"
] | I'm new to wordpress and am trying to develop my first own theme. The thing is: the front page must be static, with no display of posts. But I need a blog section and am trying to do it by creating a custom page template that calls the last 10 posts.
How would I do that using the loop? Please, help me! Thank you all in advance! | By default WordPress displays your content in a blog format on the homepage.
Using Default Static and Blog Page Settings in WordPress.
WordPress comes with built-in support for creating a custom home page (static front page), and a separate page for blog posts. To use this method, you need to create two new WordPress pages.
The first page is going to be your custom home page.
Next you need to create another page for your blog posts. You can title this page as Blog. A lot of WordPress themes come with different templates, and it is possible that your theme may have a template to be used for blog page. However, if there is no template available in your theme, then you can simply choose default. Don’t forget to disable the comments and trackbacks option on this page as well.
Now we need to get WordPress to use these pages accordingly. To do that go to Setttings » Reading and under the Front page displays option choose A static page. Below that choose the page to be used as the front page and the page for your blog posts. Save your changes, and load your site to review changes.
---
And If you want to create a custom Template that calls the latest 10 posts, You can use the following step (Note - You can use your own HTML for the required layout) -
**Step 1: Page template**
*Create a blank page template named “page-blog.php” and include the following code:*
```
<?php
/*
Template Name: Blog
*/
?>
<?php get_header(); ?>
<div id="content">
<?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?>
<?php if( have_posts() ): ?>
<?php while( have_posts() ): the_post(); ?>
<div id="post-<?php get_the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( array(200,220) ); ?></a>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<span class="meta"><?php author_profile_avatar_link(48); ?> <strong><?php the_time('F jS, Y'); ?></strong> / <strong><?php the_author_link(); ?></strong> / <span class="comments"><?php comments_popup_link(__('0 comments','example'),__('1 comment','example'),__('% comments','example')); ?></span></span>
<?php the_excerpt(__('Continue reading »','example')); ?>
</div><!-- /#post-<?php get_the_ID(); ?> -->
<?php endwhile; ?>
<div class="navigation">
<span class="newer"><?php previous_posts_link(__('« Newer','example')) ?></span> <span class="older"><?php next_posts_link(__('Older »','example')) ?></span>
</div><!-- /.navigation -->
<?php else: ?>
<div id="post-404" class="noposts">
<p><?php _e('None found.','example'); ?></p>
</div><!-- /#post-404 -->
<?php endif; wp_reset_query(); ?>
</div><!-- /#content -->
<?php get_footer(); ?>
```
*Instead of showing 5 posts, you can set posts\_per\_page=10 or whatever works best.*
Note also that the HTML used in this example is rudimentary to keep things simple. You'll probably need to make a few changes to the markup to synchronize with your theme design.
**Step 2: Add New Page**
Once page-blog.php is complete and uploaded to the server, log in to the WP Admin and visit the Add New Page screen. There, create a new page named "Blog" (or whatever you want), and set its Template as "Blog" from the "Page Attributes" panel.
Done!
Now visit the Blog page after publishing and you should see the custom WP\_Query loop working: your latest blog posts will be displayed on the page. |
306,873 | <p>I'm trying to upload files with dwg extension to media but when I do that I get an error telling me that uploading files with this extension is not allowed. I tried to upload them via ftp but I cannot see them in my panel afterwards. I've looked for a solution online and tried adding this to my <code>functions.php</code>:</p>
<pre><code>function custom_upload_mimes ( $existing_mimes=array() ) {
$existing_mimes[‘dwg’] = ‘application/dwg’;
return $existing_mimes;
}
add_filter(‘upload_mimes’,’custom_upload_mimes’);
</code></pre>
<p>But it didn't change anything. Is there any other way to bypass this file restriction? </p>
| [
{
"answer_id": 306874,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Your code should work just fine. The only problem in there is that you’ve set incorrect mime type, I g... | 2018/06/25 | [
"https://wordpress.stackexchange.com/questions/306873",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145150/"
] | I'm trying to upload files with dwg extension to media but when I do that I get an error telling me that uploading files with this extension is not allowed. I tried to upload them via ftp but I cannot see them in my panel afterwards. I've looked for a solution online and tried adding this to my `functions.php`:
```
function custom_upload_mimes ( $existing_mimes=array() ) {
$existing_mimes[‘dwg’] = ‘application/dwg’;
return $existing_mimes;
}
add_filter(‘upload_mimes’,’custom_upload_mimes’);
```
But it didn't change anything. Is there any other way to bypass this file restriction? | Your code should work just fine. The only problem in there is that you’ve set incorrect mime type, I guess...
It should be `image/vnd.dwg`.
So this one should work:
```
function custom_upload_mimes ( $existing_mimes=array() ) {
$existing_mimes['dwg'] = 'image/vnd.dwg';
return $existing_mimes;
}
add_filter('upload_mimes', 'custom_upload_mimes');
``` |
306,887 | <p>I am trying to create custom post & post tags with following code</p>
<pre><code>function cptportfolioPost_init() {
register_post_type( 'portfolio',
array(
'labels' => array(
'name' => __( 'Portfolio' ),
'singular_name' => __( 'Portfolio' )
),
'public' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-calendar-alt',
'taxonomies' => array('post_tag'),
'supports' => array(
'title',
'editor',
'excerpt',
'revisions',
'thumbnail',
'author',
'page-attributes',
)
)
);
}
add_action( 'init', 'cptportfolioPost_init' );
</code></pre>
<p>get tags on the post page with this code </p>
<pre><code><?php $tags = get_tags();
$html = '<div class="post-tags-wrap">';
foreach ( $tags as $tag ) {
$tag_link = get_tag_link( $tag->term_id );
$html .= "<a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}'>";
$html .= "{$tag->name}</a>";
}
$html .= '</div>';
echo $html;?>
</code></pre>
<p>in dashboard my custom post has a tags option, in frontend on post page selected tags also displayed but when I click tags link, tags page doesn't display custom post related to that tag only display WordPress default post related to that tag
So how can I get my custom post on the tags page </p>
| [
{
"answer_id": 306874,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Your code should work just fine. The only problem in there is that you’ve set incorrect mime type, I g... | 2018/06/25 | [
"https://wordpress.stackexchange.com/questions/306887",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102143/"
] | I am trying to create custom post & post tags with following code
```
function cptportfolioPost_init() {
register_post_type( 'portfolio',
array(
'labels' => array(
'name' => __( 'Portfolio' ),
'singular_name' => __( 'Portfolio' )
),
'public' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-calendar-alt',
'taxonomies' => array('post_tag'),
'supports' => array(
'title',
'editor',
'excerpt',
'revisions',
'thumbnail',
'author',
'page-attributes',
)
)
);
}
add_action( 'init', 'cptportfolioPost_init' );
```
get tags on the post page with this code
```
<?php $tags = get_tags();
$html = '<div class="post-tags-wrap">';
foreach ( $tags as $tag ) {
$tag_link = get_tag_link( $tag->term_id );
$html .= "<a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}'>";
$html .= "{$tag->name}</a>";
}
$html .= '</div>';
echo $html;?>
```
in dashboard my custom post has a tags option, in frontend on post page selected tags also displayed but when I click tags link, tags page doesn't display custom post related to that tag only display WordPress default post related to that tag
So how can I get my custom post on the tags page | Your code should work just fine. The only problem in there is that you’ve set incorrect mime type, I guess...
It should be `image/vnd.dwg`.
So this one should work:
```
function custom_upload_mimes ( $existing_mimes=array() ) {
$existing_mimes['dwg'] = 'image/vnd.dwg';
return $existing_mimes;
}
add_filter('upload_mimes', 'custom_upload_mimes');
``` |
306,904 | <p>I occasionally want to reset my WordPress installation back to default--both the database and files. What is the most efficient way to do so? </p>
<p>I know there are viable plugins to reset the database. But are there automated methods to reset the files to default as well? Or do I need to simply delete everything and re-upload all the WordPress files?</p>
| [
{
"answer_id": 306922,
"author": "Benjamin Atkin",
"author_id": 8567,
"author_profile": "https://wordpress.stackexchange.com/users/8567",
"pm_score": 0,
"selected": false,
"text": "<p>You can use git and a script:</p>\n\n<pre><code>#!/bin/bash\n# check out a revision\ngit checkout master... | 2018/06/25 | [
"https://wordpress.stackexchange.com/questions/306904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51204/"
] | I occasionally want to reset my WordPress installation back to default--both the database and files. What is the most efficient way to do so?
I know there are viable plugins to reset the database. But are there automated methods to reset the files to default as well? Or do I need to simply delete everything and re-upload all the WordPress files? | If you only want to *empty* the site of its *content* (*posts*, *comments*, *terms*, and *meta*) then there's a [wp-cli](https://developer.wordpress.org/cli/commands/site/empty/) command for that:
```
$ wp site empty
```
Use the the `--uploads` parameter to delete all files in the uploads folder and `--yes` to skip the conformation.
**Warning: Remember to backup before testing!**
See [the wp-cli docs](https://developer.wordpress.org/cli/commands/site/empty/) for more information: |
306,990 | <p>I just want to setup SMTP for a specific instance of <code>wp_mail()</code>. </p>
<p>I have tested plugins like "Easy WP SMTP" and also checked how to set up SMTP manually but all <strong>these apply to the entire site</strong> and then every email from the site is sent through the SMTP account.</p>
<p>I don't want to send any other emails like newsletters or comment approval emails through the same SMTP account.</p>
| [
{
"answer_id": 318826,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 2,
"selected": false,
"text": "<p>The following is a way to handle your question. It is in two parts. First, you would create your connect... | 2018/06/26 | [
"https://wordpress.stackexchange.com/questions/306990",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101689/"
] | I just want to setup SMTP for a specific instance of `wp_mail()`.
I have tested plugins like "Easy WP SMTP" and also checked how to set up SMTP manually but all **these apply to the entire site** and then every email from the site is sent through the SMTP account.
I don't want to send any other emails like newsletters or comment approval emails through the same SMTP account. | The following is a way to handle your question. It is in two parts. First, you would create your connection as constants to be used later. The best way to do this is in wp-config.php. (You mentioned that you're doing this in a custom plugin. If that's something that is to be portable, then you may want to change this to saving setting in the db instead.) Second, you'll apply a function hooked to the phpmailer that WP uses. In that function you can define your criteria in which you'd use the SMTP connection instead of the default.
You can set up your SMTP credentials and server connection info in wp-config.php as constants as follows:
```
/*
* Set the following constants in wp-config.php
* These should be added somewhere BEFORE the
* constant ABSPATH is defined.
*/
define( 'SMTP_USER', 'user@example.com' ); // Username to use for SMTP authentication
define( 'SMTP_PASS', 'smtp password' ); // Password to use for SMTP authentication
define( 'SMTP_HOST', 'smtp.example.com' ); // The hostname of the mail server
define( 'SMTP_FROM', 'website@example.com' ); // SMTP From email address
define( 'SMTP_NAME', 'e.g Website Name' ); // SMTP From name
define( 'SMTP_PORT', '25' ); // SMTP port number - likely to be 25, 465 or 587
define( 'SMTP_SECURE', 'tls' ); // Encryption system to use - ssl or tls
define( 'SMTP_AUTH', true ); // Use SMTP authentication (true|false)
define( 'SMTP_DEBUG', 0 ); // for debugging purposes only set to 1 or 2
```
Once you've added that to your wp-config.php file, you have constants that you can use to connect and send any email via SMTP. You can do this by hooking to the phpmailer\_init action and using that to set up connection criteria using the constants you defined above.
In your specific case, you would want to add some conditional logic in the function to identify the condition in which you want to send via SMTP. Set up your conditional so that only your criteria uses the SMTP connection for the phpmailer, and all others would use whatever is already being used.
Since we don't know what that is from your OP, I've represented it here with a generic `true === $some_criteria`:
```
add_action( 'phpmailer_init', 'send_smtp_email' );
function send_smtp_email( $phpmailer ) {
if ( true === $some_criteria ) {
if ( ! is_object( $phpmailer ) ) {
$phpmailer = (object) $phpmailer;
}
$phpmailer->Mailer = 'smtp';
$phpmailer->Host = SMTP_HOST;
$phpmailer->SMTPAuth = SMTP_AUTH;
$phpmailer->Port = SMTP_PORT;
$phpmailer->Username = SMTP_USER;
$phpmailer->Password = SMTP_PASS;
$phpmailer->SMTPSecure = SMTP_SECURE;
$phpmailer->From = SMTP_FROM;
$phpmailer->FromName = SMTP_NAME;
}
// any other case would not change the sending server
}
```
This concept is from the following gist on github:
<https://gist.github.com/butlerblog/c5c5eae5ace5bdaefb5d>
General instructions on it here:
<http://b.utler.co/Y3> |
307,003 | <p>I need to put link with image at the end of post page.
What I am looking for is that at the end of each new post, I need to have small image with link that opens in a new window. How to do that?
Thanks.</p>
| [
{
"answer_id": 318826,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 2,
"selected": false,
"text": "<p>The following is a way to handle your question. It is in two parts. First, you would create your connect... | 2018/06/26 | [
"https://wordpress.stackexchange.com/questions/307003",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145893/"
] | I need to put link with image at the end of post page.
What I am looking for is that at the end of each new post, I need to have small image with link that opens in a new window. How to do that?
Thanks. | The following is a way to handle your question. It is in two parts. First, you would create your connection as constants to be used later. The best way to do this is in wp-config.php. (You mentioned that you're doing this in a custom plugin. If that's something that is to be portable, then you may want to change this to saving setting in the db instead.) Second, you'll apply a function hooked to the phpmailer that WP uses. In that function you can define your criteria in which you'd use the SMTP connection instead of the default.
You can set up your SMTP credentials and server connection info in wp-config.php as constants as follows:
```
/*
* Set the following constants in wp-config.php
* These should be added somewhere BEFORE the
* constant ABSPATH is defined.
*/
define( 'SMTP_USER', 'user@example.com' ); // Username to use for SMTP authentication
define( 'SMTP_PASS', 'smtp password' ); // Password to use for SMTP authentication
define( 'SMTP_HOST', 'smtp.example.com' ); // The hostname of the mail server
define( 'SMTP_FROM', 'website@example.com' ); // SMTP From email address
define( 'SMTP_NAME', 'e.g Website Name' ); // SMTP From name
define( 'SMTP_PORT', '25' ); // SMTP port number - likely to be 25, 465 or 587
define( 'SMTP_SECURE', 'tls' ); // Encryption system to use - ssl or tls
define( 'SMTP_AUTH', true ); // Use SMTP authentication (true|false)
define( 'SMTP_DEBUG', 0 ); // for debugging purposes only set to 1 or 2
```
Once you've added that to your wp-config.php file, you have constants that you can use to connect and send any email via SMTP. You can do this by hooking to the phpmailer\_init action and using that to set up connection criteria using the constants you defined above.
In your specific case, you would want to add some conditional logic in the function to identify the condition in which you want to send via SMTP. Set up your conditional so that only your criteria uses the SMTP connection for the phpmailer, and all others would use whatever is already being used.
Since we don't know what that is from your OP, I've represented it here with a generic `true === $some_criteria`:
```
add_action( 'phpmailer_init', 'send_smtp_email' );
function send_smtp_email( $phpmailer ) {
if ( true === $some_criteria ) {
if ( ! is_object( $phpmailer ) ) {
$phpmailer = (object) $phpmailer;
}
$phpmailer->Mailer = 'smtp';
$phpmailer->Host = SMTP_HOST;
$phpmailer->SMTPAuth = SMTP_AUTH;
$phpmailer->Port = SMTP_PORT;
$phpmailer->Username = SMTP_USER;
$phpmailer->Password = SMTP_PASS;
$phpmailer->SMTPSecure = SMTP_SECURE;
$phpmailer->From = SMTP_FROM;
$phpmailer->FromName = SMTP_NAME;
}
// any other case would not change the sending server
}
```
This concept is from the following gist on github:
<https://gist.github.com/butlerblog/c5c5eae5ace5bdaefb5d>
General instructions on it here:
<http://b.utler.co/Y3> |
307,018 | <p>I am a newbe in wordpress theme development. Can anyone tell me where I should implement the code for any ajax functionalities(say a voting system for posts)? should I write it on a separate plugin or as a custom code in functions.php please do explain your reason, thanks.</p>
| [
{
"answer_id": 307022,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>Use REST API endpoint instead!</p>\n\n<p>Lets register an endpoint at <code>/wp-json/tomjn/v1/test</code>, t... | 2018/06/26 | [
"https://wordpress.stackexchange.com/questions/307018",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145902/"
] | I am a newbe in wordpress theme development. Can anyone tell me where I should implement the code for any ajax functionalities(say a voting system for posts)? should I write it on a separate plugin or as a custom code in functions.php please do explain your reason, thanks. | Use REST API endpoint instead!
Lets register an endpoint at `/wp-json/tomjn/v1/test`, that calls `tomjn_rest_test()` when you hit it:
```
add_action( 'rest_api_init', function () {
register_rest_route( 'tomjn/v1', '/test/', array(
'methods' => 'GET',
'callback' => 'tomjn_rest_test'
) );
} );
```
Now lets add the `tomjn_rest_test` function:
```
function tomjn_rest_test( $request ) {
return "moomins";
}
```
Now when we visit tomjn.com/wp-json/tomjn/v1/test we get:
[](https://i.stack.imgur.com/fpAf1.png)
Now we can grab it on the frontend:
```
<script>
jQuery.ajax({
url: <?php echo wp_json_encode( esc_url_raw( rest_url( 'tomjn/v1/test' ) ) ); ?>
}).done(function( data ) {
// do something
jQuery( '#tomsword' ).text( data );
});
</script>
```
That code looks for a `<div id="tomsword">` and sets the contents to whatever the endpoint returned.
### But Where Do I Put The Code? Theme or Plugin?
You can register you endpoints in a plugin or theme, just remember:
* themes determine how your site looks
* plugins determine what you site can do
**Voting sounds like functionality, not decoration, and should go in a plugin.**
If you put it in a theme, then that functionality is forever trapped in that theme unless a developer manually extracts it. Any voting data is unavailable as soon as the user changes the theme |
307,040 | <p>Is it possible / how can I get all posts from all sites on a multisite installation using the REST API? On the front page of the primary site, I want to display recent posts from <em>all</em> the sites; e.g., mysite.com shows recent posts from mysite.com/site1, myite.com/site2, etc., merged together (possibly with some filtering). I know how to do this with PHP; I want to see if I can do it using the REST API.</p>
<p>Josh Pollock @ torquemag has proposed this solution:
<a href="https://torquemag.io/2016/07/combine-wordpress-sites-rest-api/" rel="nofollow noreferrer">https://torquemag.io/2016/07/combine-wordpress-sites-rest-api/</a></p>
<p>Josh's example envisions combining posts from 2 completely different sites, and so I'm wondering if there is another way to do this within a single multisite install. I haven't done much with custom endpoints til now and wondering if a custom endpoint could accomplish this as well.</p>
<p>Also curious about any potential performance issues involved.</p>
| [
{
"answer_id": 307045,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, there is a way to do that. It's a bit complex for here; you have to loop through all sites (after... | 2018/06/26 | [
"https://wordpress.stackexchange.com/questions/307040",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124357/"
] | Is it possible / how can I get all posts from all sites on a multisite installation using the REST API? On the front page of the primary site, I want to display recent posts from *all* the sites; e.g., mysite.com shows recent posts from mysite.com/site1, myite.com/site2, etc., merged together (possibly with some filtering). I know how to do this with PHP; I want to see if I can do it using the REST API.
Josh Pollock @ torquemag has proposed this solution:
<https://torquemag.io/2016/07/combine-wordpress-sites-rest-api/>
Josh's example envisions combining posts from 2 completely different sites, and so I'm wondering if there is another way to do this within a single multisite install. I haven't done much with custom endpoints til now and wondering if a custom endpoint could accomplish this as well.
Also curious about any potential performance issues involved. | Here's a REST API recipe for **latest post per site on a multi-site**, for relatively few sites:
* Use `get_sites()`,
* loop over sites and switch to each site,
* query latest post on each site,
* collect data,
* order data by *utime*,
* serve data
**Example REST Routes**
```
https://example.com/wp-json/wpse/v1/latest-post-per-site
https://example.com/wp-json/wpse/v1/latest-post-per-site?number=10
https://example.com/wp-json/wpse/v1/latest-post-per-site?debug
```
**Example Plugin**
Here's a demo plugin implementing the above recipe (needs testing):
```
<?php
/**
* Plugin Name: WPSE-307040: Rest API - Latest Post Per Site
* Description: Rest API - latest post per site (multisite).
* Plugin URI: https://wordpress.stackexchange.com/a/307051/26350
* Author: birgire
* Version: 1.0.0
*/
namespace WPSE\RestAPI\LatestPostPerSite;
/**
* Register Rest Route
*/
add_action( 'rest_api_init', function() {
register_rest_route(
'wpse/v1',
'/latest-post-per-site/',
[
'methods' => 'GET',
'callback' => __NAMESPACE__.'\rest_results'
]
);
} );
/**
* Rest Results
*/
function rest_results( $request ) {
$parameters = $request->get_query_params();
// Default 10 items
$number = isset( $parameters['number'] ) ? (int) $parameters['number'] : 10;
// Max 30 items
if( $number > 30 ) {
$number = 30;
}
$items = [];
$i = 0;
$blogs = get_sites( [
'orderby' => 'last_updated',
'order' => 'DESC',
'number' => (int) $number
] );
foreach ( $blogs as $blog ) {
switch_to_blog( $blog->blog_id );
// Site info
$details = get_blog_details( $blog->blog_id );
$items[$i]['sitename'] = esc_html( $details->blogname );
$items[$i]['siteid'] = (int) $blog->blog_id;
$items[$i]['homeurl'] = esc_url( $details->home );
// Latest post
$args = [
'orderby' => 'post_date',
'order' => 'DESC',
'posts_per_page' => 1,
'post_type' => 'post',
'post_status' => 'publish',
'ignore_sticky_posts' => true,
'no_found_rows' => true,
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
];
$query = new \WP_Query( $args );
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
// Title
$items[$i]['title'] = esc_html( get_the_title( get_the_ID() ) );
// Date
$items[$i]['date'] = esc_html( get_the_date( 'Y-m-d H:i:s', get_the_ID() ) );
// Unix time
$items[$i]['utime'] = esc_html( get_the_date( 'U', get_the_ID() ) );
// Excerpt
$items[$i]['excerpt'] = esc_html( wp_trim_words( strip_shortcodes( get_the_content() ), 50 ) );
// Permalink
$items[$i]['url'] = esc_url( get_permalink( get_the_ID() ) );
}
wp_reset_postdata();
}
$i++;
restore_current_blog();
// Sort by utime.
$items = wp_list_sort( $items, 'utime', 'DESC' );
$data = [
'success' => true,
'count' => count( $items ),
'items' => $items,
];
// Debug for super admins.
if( isset( $parameters['debug'] ) && current_user_can( 'manage_networks' ) ) {
$data['qrs'] = get_num_queries();
$data['sec'] = timer_stop(0);
}
return $data;
}
```
For larger number of sites, I would instead consider hooking into the *create/update/delete* for *post/meta/taxonomy/term* on each site, to sync and collect site wide data to a dedicated data site in the multi-site network.
Hope it helps! |
307,088 | <p>Im trying to get this simple condition tag to work . Im having no luck</p>
<pre><code>// If we are logged in, and NOT an admin and NOT on specific page...
if ( is_user_logged_in() & !is_admin() ) & !is_page('account') ) {
</code></pre>
| [
{
"answer_id": 307089,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>Count the brackets, you've got an extra one:</p>\n\n<pre><code>// ↓... | 2018/06/27 | [
"https://wordpress.stackexchange.com/questions/307088",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108508/"
] | Im trying to get this simple condition tag to work . Im having no luck
```
// If we are logged in, and NOT an admin and NOT on specific page...
if ( is_user_logged_in() & !is_admin() ) & !is_page('account') ) {
``` | ```
if(strpos($_SERVER['REQUEST_URI'], '/account/') === FALSE AND strpos($_SERVER['REQUEST_URI'], '/wp-admin/') === FALSE AND ! is_user_logged_in() === FALSE) {
``` |
307,105 | <p>I have the following website: <a href="https://www.bibaboegifts.be" rel="nofollow noreferrer">www.bibaboegifts.be</a>.</p>
<ul>
<li>When giving in the URL <a href="https://www.bibaboegifts.be" rel="nofollow noreferrer">https://www.bibaboegifts.be</a>, the CSS is loaded. </li>
<li>However, when giving in the URL <a href="https://bibaboegifts.be" rel="nofollow noreferrer">https://bibaboegifts.be</a> (<strong>without the www. part</strong>), the CSS is not loaded. Only the content is displayed, but my lay-out is not applied.</li>
</ul>
<p>Any idea why this is the case & how this can be resolved? </p>
| [
{
"answer_id": 307089,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>Count the brackets, you've got an extra one:</p>\n\n<pre><code>// ↓... | 2018/06/27 | [
"https://wordpress.stackexchange.com/questions/307105",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129008/"
] | I have the following website: [www.bibaboegifts.be](https://www.bibaboegifts.be).
* When giving in the URL <https://www.bibaboegifts.be>, the CSS is loaded.
* However, when giving in the URL <https://bibaboegifts.be> (**without the www. part**), the CSS is not loaded. Only the content is displayed, but my lay-out is not applied.
Any idea why this is the case & how this can be resolved? | ```
if(strpos($_SERVER['REQUEST_URI'], '/account/') === FALSE AND strpos($_SERVER['REQUEST_URI'], '/wp-admin/') === FALSE AND ! is_user_logged_in() === FALSE) {
``` |
307,109 | <p>I have a custom page template defined and working properly.
On this specific page, I want to list a lot of links, and paginate them, to display 100 links per page.</p>
<p>Here is the code in my template file, working exactly like I want</p>
<pre><code><div class="container">
<ul class="row listing-items">
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$custom_args = array(
'post_type' => 'page',
'posts_per_page' => 90,
'paged' => $paged,
'order' => 'ASC',
'orderby' => 'title',
'post__not_in' => array('6','6371','9522','5038','6380','9521','6385','9276','4159','4087','4085','4082'),
'post_parent__in' => array('13', '154', '127', '162', '123', '167', '159', '121','18675','18676','18677','18678','18679','18680','18681','18682','18683','18684','18685','18687','18688','18689','18690','18691','18692','18693','18695','18696','18697','18699','18700','18701','18702','18703','18704','18694','18709','18705','18710','18706','18707','18718','18719','18720','18721','18722','18723','18724','18725','18726','18711','18727','18728','18729','18730','18731','18732','18716','18733','18734','18712','18735','18736','18737','18738','18739','18740','18741','18742','18743','18744','18745','18746','18717','18747','18686','18708','18748','18713','18749','18750','18751','18714','18752','18698','18753','18754','18755','18757','18758','18759','18760','18715','18761','18762','18756'),
);
$wp_query = new WP_Query( $custom_args );
if ( $wp_query->have_posts() ) {
while ( $wp_query->have_posts() ) : $wp_query->the_post();
echo '<li class="listing-item col-12 col-sm-12 col-md-12 col-lg-6 col-xl-6">';
echo '<a href="'.get_the_permalink().'">Voiture '.get_the_title().'</a></li>';
endwhile;
wp_reset_postdata();
}
?>
</ul>
</code></pre>
<p></p>
<p>Now, for SEO purposes, I want to add in my header rel Next and Prev, so Google understand the pagination and can understand which page is the current one, and which page is next and prev. </p>
<p>Here is my code in functions.php</p>
<pre><code>function rel_next_prev() {
global $paged;
if ( get_previous_posts_link() ) {
echo '<link rel="prev" href="'.get_pagenum_link( $paged - 1 ).'" />';
}
if ( get_next_posts_link() ) {
echo '<link rel="next" href="'.get_pagenum_link( $paged + 1 ).'" />';
}
}
add_action( 'wp_head', 'rel_next_prev' );
</code></pre>
<p>Unfortunately, this is partially working. I always get the Rel Prev link in the header, but is not currently based on the query I did.
Let me explain:</p>
<p>When my query is set, I have 19 pages, under this format:</p>
<pre><code>http://localhost:3000/villes/page/2/
</code></pre>
<p>So If I change the URL to be (404)</p>
<pre><code> http://localhost:3000/villes/page/222/
</code></pre>
<p>I still get rel Prev with 221 in the header.</p>
<p><em>So to resume:</em></p>
<p><strong>How do I properly set rel next/prev in the header based on the current query I'm doing?</strong></p>
<p>Thanks!</p>
| [
{
"answer_id": 307182,
"author": "yofisim",
"author_id": 98907,
"author_profile": "https://wordpress.stackexchange.com/users/98907",
"pm_score": 3,
"selected": true,
"text": "<p>After a huge night overthinking this, and thanks to Joost de Valk (Yoast SEO plugin author), I found the solut... | 2018/06/27 | [
"https://wordpress.stackexchange.com/questions/307109",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98907/"
] | I have a custom page template defined and working properly.
On this specific page, I want to list a lot of links, and paginate them, to display 100 links per page.
Here is the code in my template file, working exactly like I want
```
<div class="container">
<ul class="row listing-items">
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$custom_args = array(
'post_type' => 'page',
'posts_per_page' => 90,
'paged' => $paged,
'order' => 'ASC',
'orderby' => 'title',
'post__not_in' => array('6','6371','9522','5038','6380','9521','6385','9276','4159','4087','4085','4082'),
'post_parent__in' => array('13', '154', '127', '162', '123', '167', '159', '121','18675','18676','18677','18678','18679','18680','18681','18682','18683','18684','18685','18687','18688','18689','18690','18691','18692','18693','18695','18696','18697','18699','18700','18701','18702','18703','18704','18694','18709','18705','18710','18706','18707','18718','18719','18720','18721','18722','18723','18724','18725','18726','18711','18727','18728','18729','18730','18731','18732','18716','18733','18734','18712','18735','18736','18737','18738','18739','18740','18741','18742','18743','18744','18745','18746','18717','18747','18686','18708','18748','18713','18749','18750','18751','18714','18752','18698','18753','18754','18755','18757','18758','18759','18760','18715','18761','18762','18756'),
);
$wp_query = new WP_Query( $custom_args );
if ( $wp_query->have_posts() ) {
while ( $wp_query->have_posts() ) : $wp_query->the_post();
echo '<li class="listing-item col-12 col-sm-12 col-md-12 col-lg-6 col-xl-6">';
echo '<a href="'.get_the_permalink().'">Voiture '.get_the_title().'</a></li>';
endwhile;
wp_reset_postdata();
}
?>
</ul>
```
Now, for SEO purposes, I want to add in my header rel Next and Prev, so Google understand the pagination and can understand which page is the current one, and which page is next and prev.
Here is my code in functions.php
```
function rel_next_prev() {
global $paged;
if ( get_previous_posts_link() ) {
echo '<link rel="prev" href="'.get_pagenum_link( $paged - 1 ).'" />';
}
if ( get_next_posts_link() ) {
echo '<link rel="next" href="'.get_pagenum_link( $paged + 1 ).'" />';
}
}
add_action( 'wp_head', 'rel_next_prev' );
```
Unfortunately, this is partially working. I always get the Rel Prev link in the header, but is not currently based on the query I did.
Let me explain:
When my query is set, I have 19 pages, under this format:
```
http://localhost:3000/villes/page/2/
```
So If I change the URL to be (404)
```
http://localhost:3000/villes/page/222/
```
I still get rel Prev with 221 in the header.
*So to resume:*
**How do I properly set rel next/prev in the header based on the current query I'm doing?**
Thanks! | After a huge night overthinking this, and thanks to Joost de Valk (Yoast SEO plugin author), I found the solution.
As per this thread: <https://github.com/Yoast/wordpress-seo/issues/437> , what I want to achieve the way I do, **is undoable, or at least, a very bad practice.**
If you want your custom query to have the default pagination and rel next prev in the header, you need to call it before `get_header();`
THEORIC SOLUTION
================
To make your custom query work with default WP and Yoast functions, you need to:
1. Put your query **BEFORE** `get_header();`
2. Be sure your query has the default name provided by WP, which is `$wp_query`
3. That being said, you will need to create a specific page template for your query, so you can set your query before getting the header.
PRACTIC SOLUTION
================
For the previous code I had, which was working with `get_template_part();`.
1. Create a custom page-template, refering to the page ID or the page slug. More on this here: <https://developer.wordpress.org/themes/template-files-section/page-template-files/>
2. Set your custom query before the `get_header();` function.
3. Be sure to re-adapt your code, so it displays the way you want.
Here is my code, which is working as expected. **Be sure to keep the** `rel_next_prev();` **function I placed in my functions.php**
Final Result:
```
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$custom_args = array(
'post_type' => 'page',
'posts_per_page' => 90,
'paged' => $paged,
'order' => 'ASC',
'orderby' => 'title',
'post__not_in' => array('6','6371','9522','5038','6380','9521','6385','9276','4159','4087','4085','4082'),
'post_parent__in' => array('13', '154', '127', '162', '123', '167', '159', '121','18675','18676','18677','18678','18679','18680','18681','18682','18683','18684','18685','18687','18688','18689','18690','18691','18692','18693','18695','18696','18697','18699','18700','18701','18702','18703','18704','18694','18709','18705','18710','18706','18707','18718','18719','18720','18721','18722','18723','18724','18725','18726','18711','18727','18728','18729','18730','18731','18732','18716','18733','18734','18712','18735','18736','18737','18738','18739','18740','18741','18742','18743','18744','18745','18746','18717','18747','18686','18708','18748','18713','18749','18750','18751','18714','18752','18698','18753','18754','18755','18757','18758','18759','18760','18715','18761','18762','18756'),
);
$wp_query = new WP_Query( $custom_args );
get_header();
get_template_part('template-parts/headers/header', 'listing');
?>
<div class="container">
<ul class="row listing-items">
<?php
if ( $wp_query->have_posts() ) {
while ( $wp_query->have_posts() ) :
$wp_query->the_post();
?>
<li class="listing-item col-12 col-sm-12 col-md-12 col-lg-6 col-xl-6">
<a href="<?php get_the_permalink(); ?>">Serrurier <?php the_title();?></a></li>
<?php
endwhile;
wp_reset_postdata(); // reset the query
}
?>
</ul>
<div class="row pagination">
<?php $paginationArgs = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%/',
'total' => $wp_query->max_num_pages,
'current' => $paged,
'show_all' => true,
'end_size' => 1,
'mid_size' => 1,
'prev_next' => True,
'prev_text' => __('«'),
'next_text' => __('»'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
?>
<div class="col-12 heading">
<span>Page <?php echo $paged; ?> sur <?php echo $wp_query->max_num_pages; ?></span>
</div>
<div class="col-12 items">
<?php echo paginate_links($paginationArgs); ?>
</div>
</div>
</div>
<?php
get_footer();
?>
``` |
307,113 | <p>I have disabled the author pages on my WordPress blog using the Yoast SEO plugin, but I saw that when I click the author name, it just redirects me to the homepage. Can I change the URL myblog.com/author/me directly to myblog.com, without a 301 redirect? Thanks!</p>
| [
{
"answer_id": 307114,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": false,
"text": "<p>Disabling the author pages is a 'good thing'. A 'bad actor' can enumerate your users, or even get your... | 2018/06/27 | [
"https://wordpress.stackexchange.com/questions/307113",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145970/"
] | I have disabled the author pages on my WordPress blog using the Yoast SEO plugin, but I saw that when I click the author name, it just redirects me to the homepage. Can I change the URL myblog.com/author/me directly to myblog.com, without a 301 redirect? Thanks! | Disabling the author pages is a 'good thing'. A 'bad actor' can enumerate your users, or even get your admin user (which is user id 1) with a simple query on any page. So redirecting author requests is a good idea - and a good security measure. (As is never having a user called 'admin', especially if it has admin privileges.)
For instance, an attacker could use the xmlprc.prg page to post multiple requests to any page. They could look through x number of author id's and get a list of the login names of all the user ids. Then use that list to try to get into the admin pages.
I suspect that the Yoast plugin is redirecting author requests. The code to redirect author requests to the home page will look like this:
```
function wp_redirect_if_author_query() {
$is_author_set = get_query_var( 'author', '' );
if ( $is_author_set != '' && !is_admin()) {
wp_redirect( home_url(), 301 ); // send them somewhere else
exit;
}
}
add_action( 'template_redirect', 'wp_redirect_if_author_query' );
```
Put a variation of this code (with the redirect you want to have) in your Child Theme's functions.php file. Or in a simple plugin. (I have a customized personal plugin where I do all sorts of standard settings, including those related to security.) You might need to give a higher priority to the add\_action (the optional third parameter, which defaults to 10) to override what the Yoast plugin is doing. |
307,155 | <p>I could use another set of eyes on this one...its been a little bit of time since I last created a Wordpress theme. I can't figure out what I'm doing wrong here.</p>
<p>I created a custom post type (journal) and set up a loop on a custom template, which I set on the homepage.<br>
I then have single-journal.php template for the individual post types.<br>
The Journal CPT posts show up fine in my home page template, the url/permalink looks correct on inspection. However, when I click through on any of them (I have three at the moment), they all show the content of the latest post. The url/permalink comes up correct in the url bar too, but the content is wrong.
Heres some code:
This is the loop on the home page template:</p>
<pre><code><div class="post-slider">
<?php $args = array('post_type' => 'journal',
'posts_per_page' => -1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC');
$loop = new WP_Query($args);
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) :
$loop->the_post(); ?>
<div class="post-card">
<div class="post-card-inner">
<?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>
<a href="<?php the_permalink(); ?>"
rel="bookmark"
title="Permanent Link to <?php the_title_attribute(); ?>">
<p><?php the_title(); ?></p>
</a>
</div>
</div>
<?php
// End the loop.
endwhile;
else:
?>
<h1>No posts here!</h1>
<?php endif;
wp_reset_postdata(); ?>
</div>
</code></pre>
<p>This is the loop from single-journal.php:</p>
<pre><code> <?php $args = array('post_type' => 'journal',
'showposts' => 1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC');
$loop = new WP_Query($args);
if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<!--- Add authorname taxonomy -->
<?php the_terms( $post->ID, 'authorname', 'Author: ', ', ', ' ' ); ?>
<hr/>
<nav class="nav-single">
<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentytwelve' ); ?></h3>
<span class="nav-previous"><?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '&larr;', 'Previous post link', 'twentytwelve' ) . '</span> %title' ); ?></span>
<span class="nav-next"><?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '&rarr;', 'Next post link', 'twentytwelve' ) . '</span>' ); ?></span>
</nav><!-- .nav-single -->
<?php comments_template( '', true ); ?>
<?php endwhile; endif; wp_reset_postdata();// end of the loop. ?>
</code></pre>
<p>This is the custom post type:</p>
<pre><code>/*
** Journal Entry
**
*/
function journal_entry() {
// creating (registering) the custom type
register_post_type( 'journal',
array(
'labels' => array(
'name' => __( 'Journal Entry' ),
'singular_name' => __( 'Journal Entry' ),
'add_new' => __( 'Add New Journal Entry' ),
'add_new_item' => __( 'Add New Journal Entry' ),
'edit_item' => __( 'Edit Journal Entry' ),
'new_item' => __( 'Add New Journal Entry' ),
'view_item' => __( 'View Journal Entry' ),
'search_items' => __( 'Search Journal Entry' ),
'not_found' => __( 'No Journal Entry found' ),
'not_found_in_trash' => __( 'No Journal Entry found in trash' ),
'menu_name' => _x( 'Journal Entry', 'journal' ),
),
//'taxonomies' => array('category'),
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields' ),
'capability_type' => 'post',
'rewrite' => array("slug" => "journal"), // Permalinks format
'has_archive' => true,
'query_var' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-book-alt', /* the icon for the custom post type menu */
//'register_meta_box_cb' => 'add_team_members_metaboxes'
//'yarpp_support' => true
)
); /* end of register post type */
/* this adds your post categories to your custom post type */
//register_taxonomy_for_object_type( 'category', 'stories' );
/* this adds your post tags to your custom post type */
//register_taxonomy_for_object_type( 'post_tag', 'custom_post_faq' );
}
add_action( 'init', 'journal_entry');
function journal_taxonomy() {
register_taxonomy(
'journal_categories', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
'journal', //post type name
array(
'hierarchical' => true,
'label' => 'Custom Categories', //Display name
'query_var' => true,
'rewrite' => array(
'slug' => 'journal-categories', // This controls the base slug that will display before each term
'with_front' => false // Don't display the category base before
)
)
);
}
add_action( 'init', 'journal_taxonomy');
</code></pre>
| [
{
"answer_id": 307157,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>The Main Query already contains the correct post, but you are creating a new query and asking for a single post or... | 2018/06/28 | [
"https://wordpress.stackexchange.com/questions/307155",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64900/"
] | I could use another set of eyes on this one...its been a little bit of time since I last created a Wordpress theme. I can't figure out what I'm doing wrong here.
I created a custom post type (journal) and set up a loop on a custom template, which I set on the homepage.
I then have single-journal.php template for the individual post types.
The Journal CPT posts show up fine in my home page template, the url/permalink looks correct on inspection. However, when I click through on any of them (I have three at the moment), they all show the content of the latest post. The url/permalink comes up correct in the url bar too, but the content is wrong.
Heres some code:
This is the loop on the home page template:
```
<div class="post-slider">
<?php $args = array('post_type' => 'journal',
'posts_per_page' => -1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC');
$loop = new WP_Query($args);
if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) :
$loop->the_post(); ?>
<div class="post-card">
<div class="post-card-inner">
<?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>
<a href="<?php the_permalink(); ?>"
rel="bookmark"
title="Permanent Link to <?php the_title_attribute(); ?>">
<p><?php the_title(); ?></p>
</a>
</div>
</div>
<?php
// End the loop.
endwhile;
else:
?>
<h1>No posts here!</h1>
<?php endif;
wp_reset_postdata(); ?>
</div>
```
This is the loop from single-journal.php:
```
<?php $args = array('post_type' => 'journal',
'showposts' => 1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC');
$loop = new WP_Query($args);
if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<!--- Add authorname taxonomy -->
<?php the_terms( $post->ID, 'authorname', 'Author: ', ', ', ' ' ); ?>
<hr/>
<nav class="nav-single">
<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentytwelve' ); ?></h3>
<span class="nav-previous"><?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '←', 'Previous post link', 'twentytwelve' ) . '</span> %title' ); ?></span>
<span class="nav-next"><?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '→', 'Next post link', 'twentytwelve' ) . '</span>' ); ?></span>
</nav><!-- .nav-single -->
<?php comments_template( '', true ); ?>
<?php endwhile; endif; wp_reset_postdata();// end of the loop. ?>
```
This is the custom post type:
```
/*
** Journal Entry
**
*/
function journal_entry() {
// creating (registering) the custom type
register_post_type( 'journal',
array(
'labels' => array(
'name' => __( 'Journal Entry' ),
'singular_name' => __( 'Journal Entry' ),
'add_new' => __( 'Add New Journal Entry' ),
'add_new_item' => __( 'Add New Journal Entry' ),
'edit_item' => __( 'Edit Journal Entry' ),
'new_item' => __( 'Add New Journal Entry' ),
'view_item' => __( 'View Journal Entry' ),
'search_items' => __( 'Search Journal Entry' ),
'not_found' => __( 'No Journal Entry found' ),
'not_found_in_trash' => __( 'No Journal Entry found in trash' ),
'menu_name' => _x( 'Journal Entry', 'journal' ),
),
//'taxonomies' => array('category'),
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields' ),
'capability_type' => 'post',
'rewrite' => array("slug" => "journal"), // Permalinks format
'has_archive' => true,
'query_var' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-book-alt', /* the icon for the custom post type menu */
//'register_meta_box_cb' => 'add_team_members_metaboxes'
//'yarpp_support' => true
)
); /* end of register post type */
/* this adds your post categories to your custom post type */
//register_taxonomy_for_object_type( 'category', 'stories' );
/* this adds your post tags to your custom post type */
//register_taxonomy_for_object_type( 'post_tag', 'custom_post_faq' );
}
add_action( 'init', 'journal_entry');
function journal_taxonomy() {
register_taxonomy(
'journal_categories', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
'journal', //post type name
array(
'hierarchical' => true,
'label' => 'Custom Categories', //Display name
'query_var' => true,
'rewrite' => array(
'slug' => 'journal-categories', // This controls the base slug that will display before each term
'with_front' => false // Don't display the category base before
)
)
);
}
add_action( 'init', 'journal_taxonomy');
``` | You shouldn't be using custom queries in these templates. The main query (using `have_posts();`, `the_post();` etc. without `$loop`) is already set up with the correct posts for these templates.
Look at the custom query you're using on the single template:
```
$args = array('post_type' => 'journal',
'showposts' => 1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC');
$loop = new WP_Query($args);
```
That's a query for the latest journal post. So of that's what you're going to see when you use `$loop->the_post()`. Also, `showposts` is deprecated. Use `posts_per_page` instead.
So this:
```
if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?>
```
Needs to be:
```
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
``` |
307,159 | <p>I am setting up non-for-profit domestic violence support website and struggle to find a way to create active category parent and it children links in pages sidebar.</p>
<p>What is the ideal solution to dynamically display category parent and it's children?</p>
| [
{
"answer_id": 307157,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>The Main Query already contains the correct post, but you are creating a new query and asking for a single post or... | 2018/06/28 | [
"https://wordpress.stackexchange.com/questions/307159",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145989/"
] | I am setting up non-for-profit domestic violence support website and struggle to find a way to create active category parent and it children links in pages sidebar.
What is the ideal solution to dynamically display category parent and it's children? | You shouldn't be using custom queries in these templates. The main query (using `have_posts();`, `the_post();` etc. without `$loop`) is already set up with the correct posts for these templates.
Look at the custom query you're using on the single template:
```
$args = array('post_type' => 'journal',
'showposts' => 1,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC');
$loop = new WP_Query($args);
```
That's a query for the latest journal post. So of that's what you're going to see when you use `$loop->the_post()`. Also, `showposts` is deprecated. Use `posts_per_page` instead.
So this:
```
if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?>
```
Needs to be:
```
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
``` |
307,209 | <p>First of all, I tried searching and working on this, but couldn't create the logic or method to do this.</p>
<p>I'm trying to display <code>users</code> and <code>custom post type</code> content together into a single <code>loop</code>. I can get the value of <code>custom post type</code> using <code>WP_Query</code> and <code>users</code> using <code>WP_USER_Query</code>. and I can display them simultaneously. But then the posts and users won't be mixed in the order of date.</p>
<p>I'm not sure if I can achieve this via custom <code>query</code>. My knowledge and experience is limited on this part. </p>
<p>Can anyone help me put in the right direction about how I can achieve this?</p>
<hr>
<p>// Edit and Update</p>
<p>Thank you all for your comment, I believe I gave the half of the idea of what I really need and how I'm trying to achieve it. So I'll begin with the idea/scenario.</p>
<p>General Idea: </p>
<ol>
<li>I have Custom post type, let's call it "assignment" and "projects".</li>
<li>I have users on the site, let's call them "teacher" and "student".</li>
<li>multiple teachers can assign "assignment" and "projects" to multiple students.</li>
<li>Now, I have a "Directory" page, on which I wish to display all (teacher, student, assignments, and projects).</li>
<li>On the frontend, I wish to display each cpt entry and users in thumbnail view like the 4x4 grid.</li>
</ol>
<p>Now, I have create a page-template called <code>directory.php</code> and used the following loop to display only cpt <code>assignment</code> and <code>projects</code>.</p>
<pre><code>$args = array(
'post_type' => array('assigment', 'project'),
'post_status' => 'publish',
'order' => 'ASC'
);
$query = new WP_query( $args );
</code></pre>
<p>and looped it like this</p>
<pre><code><?php if ( $query->have_posts() ) : ?>
<?php
while ( $query->have_posts() ) :
$query->the_post();
get_template_part( 'template-parts/content', get_post_type() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
wp_reset_postdata();
?>
</code></pre>
<p>the code is working, but please focus on the syntax error if any. now the part of users. I wrote it like this.</p>
<pre><code>$user = new WP_User_Query(array('role'=> 'teacher'));
if (!empty($user)) {
foreach ($user as $teacher) {
echo $teacher->first_name;
}
}
</code></pre>
<p>you get the basic idea of how I can use the users. </p>
<p><strong>The main Question</strong></p>
<p>How can I merge Users within the post loop, so users and posts display in a grid of 4x4 and order by timestamps?</p>
<p>For example, we have the following with the date of creation.</p>
<p>Teach A ( 10 Jun, 2018 )
Teach B ( 12 Jun, 2018 )
Stud C ( 15 Jun, 2018 )
Assign 1 ( 16 Jun, 2018 )
Assign 2 ( 18 Jun, 2018 )
Stud D ( 20 Jun, 2018 )
Proj 1 ( 22 Jun, 2018 )</p>
<p>and then I display in the 4x4 grid like this.</p>
<p>Teach A Teach B Stud C Assign 1
Assign 2 Stud D Proj 1</p>
<p>Please let me know if it's still confusing. </p>
| [
{
"answer_id": 307518,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>You can not merge two different queries when the returned type is an object, because they have different met... | 2018/06/28 | [
"https://wordpress.stackexchange.com/questions/307209",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110899/"
] | First of all, I tried searching and working on this, but couldn't create the logic or method to do this.
I'm trying to display `users` and `custom post type` content together into a single `loop`. I can get the value of `custom post type` using `WP_Query` and `users` using `WP_USER_Query`. and I can display them simultaneously. But then the posts and users won't be mixed in the order of date.
I'm not sure if I can achieve this via custom `query`. My knowledge and experience is limited on this part.
Can anyone help me put in the right direction about how I can achieve this?
---
// Edit and Update
Thank you all for your comment, I believe I gave the half of the idea of what I really need and how I'm trying to achieve it. So I'll begin with the idea/scenario.
General Idea:
1. I have Custom post type, let's call it "assignment" and "projects".
2. I have users on the site, let's call them "teacher" and "student".
3. multiple teachers can assign "assignment" and "projects" to multiple students.
4. Now, I have a "Directory" page, on which I wish to display all (teacher, student, assignments, and projects).
5. On the frontend, I wish to display each cpt entry and users in thumbnail view like the 4x4 grid.
Now, I have create a page-template called `directory.php` and used the following loop to display only cpt `assignment` and `projects`.
```
$args = array(
'post_type' => array('assigment', 'project'),
'post_status' => 'publish',
'order' => 'ASC'
);
$query = new WP_query( $args );
```
and looped it like this
```
<?php if ( $query->have_posts() ) : ?>
<?php
while ( $query->have_posts() ) :
$query->the_post();
get_template_part( 'template-parts/content', get_post_type() );
endwhile;
the_posts_navigation();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
wp_reset_postdata();
?>
```
the code is working, but please focus on the syntax error if any. now the part of users. I wrote it like this.
```
$user = new WP_User_Query(array('role'=> 'teacher'));
if (!empty($user)) {
foreach ($user as $teacher) {
echo $teacher->first_name;
}
}
```
you get the basic idea of how I can use the users.
**The main Question**
How can I merge Users within the post loop, so users and posts display in a grid of 4x4 and order by timestamps?
For example, we have the following with the date of creation.
Teach A ( 10 Jun, 2018 )
Teach B ( 12 Jun, 2018 )
Stud C ( 15 Jun, 2018 )
Assign 1 ( 16 Jun, 2018 )
Assign 2 ( 18 Jun, 2018 )
Stud D ( 20 Jun, 2018 )
Proj 1 ( 22 Jun, 2018 )
and then I display in the 4x4 grid like this.
Teach A Teach B Stud C Assign 1
Assign 2 Stud D Proj 1
Please let me know if it's still confusing. | You can not merge two different queries when the returned type is an object, because they have different methods and properties. Instead, you can get them as an array. Then you can merge them and compare the dates. For this, I'm going to use `get_posts()` over `WP_Query()`, and `get_users()` over `WP_User_Query()` to achieve this.
The code itself should be self explanatory.
```
// Get a list of users
$users = get_users ();
// Get an array of posts. Don't forget to set the args
$posts = get_posts();
// Let's merge these two
$users_posts = array_merge( $users, $posts );
// Now, let's sort both of them based on
// their dates. a user object holds the date
// as `user_registered`, while a post object
// holds the date as `post_date`. We use the
// usort() function to do so.
usort( $users_posts, "sort_users_and_posts" );
// Function to sort the array
function sort_users_and_posts( $a, $b ){
// Here's the tricky part. We need to get the
// date based on the object type, and then compare them.
// Get the date for first element
if( $a instanceof WP_User ){
$first_element_date = strtotime ( $a->user_registered );
} else {
$first_element_date = strtotime ( $a->post_date );
}
// Get the date for second element
if( $b instanceof WP_User ){
$second_element_date = strtotime ( $b->user_registered );
} else {
$second_element_date = strtotime ( $b->post_date );
}
// Now let's compare the dates
// If the dates are the same
if ( $first_element_date == $second_element_date ) return 0;
// If one is bigger than the other
return ( $first_element_date < $second_element_date ) ? -1 : 1;
}
// Now, we run a foreach loop and output the date.
// We need to check again whether the object is an
// instance of WP_Post or WP_User
foreach ( $users_posts as $object ) {
if( $object instanceof WP_Post ){
// This is a post
} else {
// This is a user
}
}
``` |
307,239 | <p>Just starting to play with Gutenberg block development, and I am building a very simple button (yes I know buttons are already included, but this block will have lots of settings and classes not included in the core block).</p>
<p>Seem's pretty strait forward, but when I save the block and reload, I get a validation error and the "This block appears to have been modified externally" message.</p>
<pre><code>registerBlockType('franklin/button', {
title: 'Button',
keywords: ['button' ],
icon: 'admin-links',
category: 'layout',
attributes: {
text: {
source: 'text',
selector: '.button-text'
},
},
edit({attributes, setAttributes }) {
return (
<div class="guttenberg-usa-button">
<button class="usa-button">
<PlainText
onChange={ content => setAttributes({ text: content }) }
value={ attributes.text }
placeholder="Your button text"
className="button-text"
/>
</button>
</div>
);
},
save({attributes}) {
return (
<button class="usa-button">
{ attributes.text }
</button>
);
}
});
</code></pre>
<p>So in the editor, I'll add my block, modify the (button) text, save, and reload where I get the This block appears to have been modified externally" message.</p>
<p>Console shows the following error</p>
<pre><code>Expected:
<button class="usa-button" class="wp-block-franklin-button"></button>
Actual:
<button class="usa-button" class="wp-block-franklin-button">testest</button>
</code></pre>
<p>I must be missing some fundamental concept or something, but I thought the save() function determines what gets displayed on the frontend which btw, looks as expected.</p>
| [
{
"answer_id": 307518,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p>You can not merge two different queries when the returned type is an object, because they have different met... | 2018/06/28 | [
"https://wordpress.stackexchange.com/questions/307239",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19536/"
] | Just starting to play with Gutenberg block development, and I am building a very simple button (yes I know buttons are already included, but this block will have lots of settings and classes not included in the core block).
Seem's pretty strait forward, but when I save the block and reload, I get a validation error and the "This block appears to have been modified externally" message.
```
registerBlockType('franklin/button', {
title: 'Button',
keywords: ['button' ],
icon: 'admin-links',
category: 'layout',
attributes: {
text: {
source: 'text',
selector: '.button-text'
},
},
edit({attributes, setAttributes }) {
return (
<div class="guttenberg-usa-button">
<button class="usa-button">
<PlainText
onChange={ content => setAttributes({ text: content }) }
value={ attributes.text }
placeholder="Your button text"
className="button-text"
/>
</button>
</div>
);
},
save({attributes}) {
return (
<button class="usa-button">
{ attributes.text }
</button>
);
}
});
```
So in the editor, I'll add my block, modify the (button) text, save, and reload where I get the This block appears to have been modified externally" message.
Console shows the following error
```
Expected:
<button class="usa-button" class="wp-block-franklin-button"></button>
Actual:
<button class="usa-button" class="wp-block-franklin-button">testest</button>
```
I must be missing some fundamental concept or something, but I thought the save() function determines what gets displayed on the frontend which btw, looks as expected. | You can not merge two different queries when the returned type is an object, because they have different methods and properties. Instead, you can get them as an array. Then you can merge them and compare the dates. For this, I'm going to use `get_posts()` over `WP_Query()`, and `get_users()` over `WP_User_Query()` to achieve this.
The code itself should be self explanatory.
```
// Get a list of users
$users = get_users ();
// Get an array of posts. Don't forget to set the args
$posts = get_posts();
// Let's merge these two
$users_posts = array_merge( $users, $posts );
// Now, let's sort both of them based on
// their dates. a user object holds the date
// as `user_registered`, while a post object
// holds the date as `post_date`. We use the
// usort() function to do so.
usort( $users_posts, "sort_users_and_posts" );
// Function to sort the array
function sort_users_and_posts( $a, $b ){
// Here's the tricky part. We need to get the
// date based on the object type, and then compare them.
// Get the date for first element
if( $a instanceof WP_User ){
$first_element_date = strtotime ( $a->user_registered );
} else {
$first_element_date = strtotime ( $a->post_date );
}
// Get the date for second element
if( $b instanceof WP_User ){
$second_element_date = strtotime ( $b->user_registered );
} else {
$second_element_date = strtotime ( $b->post_date );
}
// Now let's compare the dates
// If the dates are the same
if ( $first_element_date == $second_element_date ) return 0;
// If one is bigger than the other
return ( $first_element_date < $second_element_date ) ? -1 : 1;
}
// Now, we run a foreach loop and output the date.
// We need to check again whether the object is an
// instance of WP_Post or WP_User
foreach ( $users_posts as $object ) {
if( $object instanceof WP_Post ){
// This is a post
} else {
// This is a user
}
}
``` |
307,259 | <p>I've just checked a double click on my form that inserts new user meta, which actually inserted it twice! The problem is, I actually need the values to be non-unique so I can insert multiple times. </p>
<p>My aim is simple, to capture post the data from the form into the <code>user_meta</code>table only once from the form, but it seems to insert twice, three times... As many times as I click the submit button.</p>
<p>I've tried this Javascript:</p>
<pre><code>var wasSubmitted = false;
function checkBeforeSubmit(){
if(!wasSubmitted) {
wasSubmitted = true;
return wasSubmitted;
}
return false;
}
</code></pre>
<p>And nothing happened, I'm wondering, how do I do this with PHP? Or even a bit of Javascript that will actually work.</p>
<p>Ideally, I don't want to use jQuery, I prefer simple JS.</p>
| [
{
"answer_id": 307264,
"author": "Otto",
"author_id": 2232,
"author_profile": "https://wordpress.stackexchange.com/users/2232",
"pm_score": 2,
"selected": false,
"text": "<p>Dunno if you looked at add_user_meta, but it takes an optional fourth parameter.</p>\n\n<pre><code>function add_us... | 2018/06/28 | [
"https://wordpress.stackexchange.com/questions/307259",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146035/"
] | I've just checked a double click on my form that inserts new user meta, which actually inserted it twice! The problem is, I actually need the values to be non-unique so I can insert multiple times.
My aim is simple, to capture post the data from the form into the `user_meta`table only once from the form, but it seems to insert twice, three times... As many times as I click the submit button.
I've tried this Javascript:
```
var wasSubmitted = false;
function checkBeforeSubmit(){
if(!wasSubmitted) {
wasSubmitted = true;
return wasSubmitted;
}
return false;
}
```
And nothing happened, I'm wondering, how do I do this with PHP? Or even a bit of Javascript that will actually work.
Ideally, I don't want to use jQuery, I prefer simple JS. | Dunno if you looked at add\_user\_meta, but it takes an optional fourth parameter.
```
function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false )
```
Send "true" to the $unique value and it won't insert it twice.
<https://developer.wordpress.org/reference/functions/add_user_meta/> |
307,307 | <ul>
<li>I'm using Advanced Custom Fields.</li>
<li>I have a registered <code>bookitall_roomstype</code> custom post type. </li>
<li>I have a registered <code>bookitall_bookings</code> as another custom post type.</li>
<li>In the bookitall_bookings there is a field called
<code>bookitall_roomstype</code> that is stored as a <code>pagelink</code> (acf "type"). (This
looks like a permalink to the actual roomtype (It's NOT stored as a
title/name)</li>
</ul>
<p>I'm setting up certain columns (and their values) to be shown. Now I want the roomtype's name to be shown. I'm doing like below...</p>
<p><strong>This is a snippet of my code. This snippet retrieves the NAME <code>roomtype_name</code> of the pagelink-type <code>bookitall_roomstype</code></strong>:</p>
<pre><code>$allfields_currentpost = get_fields();
$args = array(
'posts_per_page' => -1,
'offset' => 0,
'orderby' => 'ID',
'order' => 'ASC',
'post_type' => 'bookitall_roomtypes'
);
$roomtypes = get_posts( $args );
$pagelink = get_field('bookitall_roomstype'); //pagelink acf type
$roomtypes_slugs = array();
foreach ( $roomtypes as $r ) {
$roomtypes_slugs[] = get_permalink( $r->ID);
}
$arrkey = (array_search($pagelink, $roomtypes_slugs));
$roomtype_name = '';
if ( $arrkey !== false ) {
$roomtype_name = $roomtypes[$arrkey]->post_title;
}
</code></pre>
<p><strong><em>The above do actually work</em></strong> (I put it here if someone have the same issue and I also <strong>want to know if there is a better/simpler way of achieving above?</strong> (getting the roomtype's name from current post)</p>
<p>I've tried to use <code>url to postid( $pagelink )</code> and <code>get_page_by_path( $pagelink )</code> but those only returns 0 (which means no object is returned). If a post had been returned I could use <code>$post->post_title</code>.</p>
<p>UPDATE:
<strong>New code</strong> (thanks to @Milo !!!):</p>
<pre><code>$allfields_currentpost = get_fields(false, false);
$roomtype_id = $allfields_currentpost['bookitall_roomstype'];
$roomtype_name = get_the_title($roomtype_id);
</code></pre>
<p>(I'm jusing the other field values from the current post as well, therefore I'm using <code>get_fields()</code> instead of <code>get_field()</code>)</p>
| [
{
"answer_id": 307319,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>You shouldn't need to get all <code>bookitall_roomstype</code> in lines 2-9 of your code. You really only... | 2018/06/29 | [
"https://wordpress.stackexchange.com/questions/307307",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38848/"
] | * I'm using Advanced Custom Fields.
* I have a registered `bookitall_roomstype` custom post type.
* I have a registered `bookitall_bookings` as another custom post type.
* In the bookitall\_bookings there is a field called
`bookitall_roomstype` that is stored as a `pagelink` (acf "type"). (This
looks like a permalink to the actual roomtype (It's NOT stored as a
title/name)
I'm setting up certain columns (and their values) to be shown. Now I want the roomtype's name to be shown. I'm doing like below...
**This is a snippet of my code. This snippet retrieves the NAME `roomtype_name` of the pagelink-type `bookitall_roomstype`**:
```
$allfields_currentpost = get_fields();
$args = array(
'posts_per_page' => -1,
'offset' => 0,
'orderby' => 'ID',
'order' => 'ASC',
'post_type' => 'bookitall_roomtypes'
);
$roomtypes = get_posts( $args );
$pagelink = get_field('bookitall_roomstype'); //pagelink acf type
$roomtypes_slugs = array();
foreach ( $roomtypes as $r ) {
$roomtypes_slugs[] = get_permalink( $r->ID);
}
$arrkey = (array_search($pagelink, $roomtypes_slugs));
$roomtype_name = '';
if ( $arrkey !== false ) {
$roomtype_name = $roomtypes[$arrkey]->post_title;
}
```
***The above do actually work*** (I put it here if someone have the same issue and I also **want to know if there is a better/simpler way of achieving above?** (getting the roomtype's name from current post)
I've tried to use `url to postid( $pagelink )` and `get_page_by_path( $pagelink )` but those only returns 0 (which means no object is returned). If a post had been returned I could use `$post->post_title`.
UPDATE:
**New code** (thanks to @Milo !!!):
```
$allfields_currentpost = get_fields(false, false);
$roomtype_id = $allfields_currentpost['bookitall_roomstype'];
$roomtype_name = get_the_title($roomtype_id);
```
(I'm jusing the other field values from the current post as well, therefore I'm using `get_fields()` instead of `get_field()`) | [The page link field](https://www.advancedcustomfields.com/resources/page-link/) actually stores the post ID, which gets formatted internally by the `get_field` function on output. The 3rd argument for `get_field` lets you disable that output formatting so you just get the ID back, which you can then use to get title and permalink for that post:
```
$post_id = get_field( 'bookitall_roomstype', false, false );
if( $post_id ):
echo get_the_permalink( $post_id );
echo get_the_title( $post_id );
endif;
``` |
307,310 | <p>We recently implemented a stock quote system, where a user can enter a stock symbol and it will return all sorts of financial values.</p>
<p>I have a template made up that displays the financial widgets, and when a user enters a ticker symbol it runs some JS with the callback url being my template. In this example, it is something like this.</p>
<p><a href="https://www.stocktrades.ca/quote/?qm_symbol=AAPL" rel="nofollow noreferrer">https://www.stocktrades.ca/quote/?qm_symbol=AAPL</a></p>
<p>What my issue is, is the title is currently blank. When a user inputs a symbol, the page title in the browser is simply “Quote -” Instead, I want it to be “Quote – XXXX” with XXXX being the stock ticker they entered.</p>
<p>What is the easiest way to go about this? I know it’s probably really simple, but I am stumped</p>
| [
{
"answer_id": 307319,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>You shouldn't need to get all <code>bookitall_roomstype</code> in lines 2-9 of your code. You really only... | 2018/06/29 | [
"https://wordpress.stackexchange.com/questions/307310",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146068/"
] | We recently implemented a stock quote system, where a user can enter a stock symbol and it will return all sorts of financial values.
I have a template made up that displays the financial widgets, and when a user enters a ticker symbol it runs some JS with the callback url being my template. In this example, it is something like this.
<https://www.stocktrades.ca/quote/?qm_symbol=AAPL>
What my issue is, is the title is currently blank. When a user inputs a symbol, the page title in the browser is simply “Quote -” Instead, I want it to be “Quote – XXXX” with XXXX being the stock ticker they entered.
What is the easiest way to go about this? I know it’s probably really simple, but I am stumped | [The page link field](https://www.advancedcustomfields.com/resources/page-link/) actually stores the post ID, which gets formatted internally by the `get_field` function on output. The 3rd argument for `get_field` lets you disable that output formatting so you just get the ID back, which you can then use to get title and permalink for that post:
```
$post_id = get_field( 'bookitall_roomstype', false, false );
if( $post_id ):
echo get_the_permalink( $post_id );
echo get_the_title( $post_id );
endif;
``` |
307,345 | <p>The following <em>works</em> but isn't up to snuff with <a href="https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards" rel="nofollow noreferrer">PHP Code Sniffer WordPress coding standards</a> </p>
<pre><code><?php esc_html_e( ADDRESS, 'wprig' ); ?>
</code></pre>
<p>Linter yells at me with:</p>
<blockquote>
<p>[WordPress.WP.I18n.NonSingularStringLiteralText] The $text arg must be a single string literal, not "ADDRESS". </p>
</blockquote>
<p>The following, for aforementioned error, also don't work:</p>
<pre><code><?php esc_html_e( (string)ADDRESS, 'wprig' ); ?>
<?php esc_html_e( strval(ADDRESS), 'wprig' ); ?>
<?php esc_attr_e( ADDRESS, 'wprig' ); ?>
</code></pre>
<p>I know <a href="https://vip.wordpress.com/2014/06/20/the-importance-of-escaping-all-the-things/" rel="nofollow noreferrer">constants can be exploited</a> so it is needed. Any way to make this work besides <code>//phpcs:ignore</code>, or is this not good practice and I should redo my use of constants?</p>
| [
{
"answer_id": 307349,
"author": "Otto",
"author_id": 2232,
"author_profile": "https://wordpress.stackexchange.com/users/2232",
"pm_score": 5,
"selected": true,
"text": "<p>You cannot use constants or anything other than actual strings with translation functions.</p>\n\n<p>This is becaus... | 2018/06/29 | [
"https://wordpress.stackexchange.com/questions/307345",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132362/"
] | The following *works* but isn't up to snuff with [PHP Code Sniffer WordPress coding standards](https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards)
```
<?php esc_html_e( ADDRESS, 'wprig' ); ?>
```
Linter yells at me with:
>
> [WordPress.WP.I18n.NonSingularStringLiteralText] The $text arg must be a single string literal, not "ADDRESS".
>
>
>
The following, for aforementioned error, also don't work:
```
<?php esc_html_e( (string)ADDRESS, 'wprig' ); ?>
<?php esc_html_e( strval(ADDRESS), 'wprig' ); ?>
<?php esc_attr_e( ADDRESS, 'wprig' ); ?>
```
I know [constants can be exploited](https://vip.wordpress.com/2014/06/20/the-importance-of-escaping-all-the-things/) so it is needed. Any way to make this work besides `//phpcs:ignore`, or is this not good practice and I should redo my use of constants? | You cannot use constants or anything other than actual strings with translation functions.
This is because the code that reads your code, and produces the translatable strings does not actually *run* your code, it is *reading* your code.
Here is a more detailed post on the topic:
<http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/>
But the short version is this:
This is wrong:
```
<?php esc_html_e( ADDRESS, 'wprig' ); ?>
```
Nothing will make that right except this:
```
<?php esc_html_e( 'Actual String here', 'wprig' ); ?>
``` |
307,362 | <p>You know how all these websites send out links to their new users for them to verify their Email address? I'm trying to set up something like this but after some research I still haven't found a good explanation on how to implement this.</p>
<p>I'm open for plugin recommendations, however most of the plugins I found have a ton of other features that I don't really need.</p>
<p>Without using a plugin, how would I go about adding this to my code?</p>
<p>My approach would be to add a 'Email not verified' attribute to the user meta after signup and send out an email with some kind of verification key to the user. How can I verify if the user actually clicked on that link though?</p>
<p>Thanks for any advice</p>
| [
{
"answer_id": 307367,
"author": "Akshat",
"author_id": 114978,
"author_profile": "https://wordpress.stackexchange.com/users/114978",
"pm_score": 5,
"selected": true,
"text": "<p>You can use <code>user_register</code> hook</p>\n\n<pre><code>add_action( 'user_register', 'my_registration',... | 2018/06/30 | [
"https://wordpress.stackexchange.com/questions/307362",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145115/"
] | You know how all these websites send out links to their new users for them to verify their Email address? I'm trying to set up something like this but after some research I still haven't found a good explanation on how to implement this.
I'm open for plugin recommendations, however most of the plugins I found have a ton of other features that I don't really need.
Without using a plugin, how would I go about adding this to my code?
My approach would be to add a 'Email not verified' attribute to the user meta after signup and send out an email with some kind of verification key to the user. How can I verify if the user actually clicked on that link though?
Thanks for any advice | You can use `user_register` hook
```
add_action( 'user_register', 'my_registration', 10, 2 );
function my_registration( $user_id ) {
// get user data
$user_info = get_userdata($user_id);
// create md5 code to verify later
$code = md5(time());
// make it into a code to send it to user via email
$string = array('id'=>$user_id, 'code'=>$code);
// create the activation code and activation status
update_user_meta($user_id, 'account_activated', 0);
update_user_meta($user_id, 'activation_code', $code);
// create the url
$url = get_site_url(). '/my-account/?act=' .base64_encode( serialize($string));
// basically we will edit here to make this nicer
$html = 'Please click the following links <br/><br/> <a href="'.$url.'">'.$url.'</a>';
// send an email out to user
wp_mail( $user_info->user_email, __('Email Subject','text-domain') , $html);
}
```
You can check for `$_GET['act']` and then activate if that's a valid key by updating the meta value `account_activated`. You can use `wp_authenticate_user` hook to verify activation status every time when user tries to login.
Snippet to validate:
```
add_action( 'init', 'verify_user_code' );
function verify_user_code(){
if(isset($_GET['act'])){
$data = unserialize(base64_decode($_GET['act']));
$code = get_user_meta($data['id'], 'activation_code', true);
// verify whether the code given is the same as ours
if($code == $data['code']){
// update the user meta
update_user_meta($data['id'], 'is_activated', 1);
wc_add_notice( __( '<strong>Success:</strong> Your account has been activated! ', 'text-domain' ) );
}
}
}
``` |
307,416 | <p>How can I enable shortcodes on a custom post type that doesn't use <code>the_content()</code> or <code>get_the_content()</code>?
In the template file it uses</p>
<pre><code><?php echo nl2br( $post->post_content ); ?>
</code></pre>
<p>to get the content from the backend like any other post or page would.
I have tried using</p>
<pre><code><?php echo do_shortcode(get_post_field('post_content', $postid)); ?>
</code></pre>
<p>which works but the shortcode itself is still displaying for example:</p>
<pre><code>[gallery columns="4" link="file" ids="1,2,3,4"]
</code></pre>
<p>displays above the gallery photos.</p>
| [
{
"answer_id": 307446,
"author": "Mammaltron",
"author_id": 88160,
"author_profile": "https://wordpress.stackexchange.com/users/88160",
"pm_score": -1,
"selected": false,
"text": "<p>Use <code>apply_filters()</code> to let WordPress process the shortcodes in your content. </p>\n\n<p><cod... | 2018/07/01 | [
"https://wordpress.stackexchange.com/questions/307416",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86094/"
] | How can I enable shortcodes on a custom post type that doesn't use `the_content()` or `get_the_content()`?
In the template file it uses
```
<?php echo nl2br( $post->post_content ); ?>
```
to get the content from the backend like any other post or page would.
I have tried using
```
<?php echo do_shortcode(get_post_field('post_content', $postid)); ?>
```
which works but the shortcode itself is still displaying for example:
```
[gallery columns="4" link="file" ids="1,2,3,4"]
```
displays above the gallery photos. | For my particular situation the answer was to replace `<?php echo nl2br( $post->post_content ); ?>` with `<?php echo $content; ?>` which allowed all shortcodes to work as expected. |
307,484 | <p>I am trying to build a plugin, in the plugin I want the admin to be able to send data to database and let the user view the data in the front end, but I am still having problems with sending data to database</p>
<p>I am trying to validate this code to keep it safe from injection
This is my code </p>
<pre><code><?php
if (!empty($_POST)) {
global $wpdb;
$table = wp_save;
$data = array(
'name' => $_POST['yourname'],
'chord' => $_POST['number']
);
$format = array(
'%s',
'%s'
);
$success=$wpdb->insert( $table, $data,
$format );
if($success){
echo 'data has been save' ;
}
} else {
?>
<form method="post">
<input type="text" name="yourname">
<textarea name="number"></textarea>
<input type="submit">
</form>
<?php
}
?>
</code></pre>
| [
{
"answer_id": 307487,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$table = wp_save;\n</code></pre>\n\n<p>This is setting <code>$table</code> to a PHP <a href=\"h... | 2018/07/02 | [
"https://wordpress.stackexchange.com/questions/307484",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146214/"
] | I am trying to build a plugin, in the plugin I want the admin to be able to send data to database and let the user view the data in the front end, but I am still having problems with sending data to database
I am trying to validate this code to keep it safe from injection
This is my code
```
<?php
if (!empty($_POST)) {
global $wpdb;
$table = wp_save;
$data = array(
'name' => $_POST['yourname'],
'chord' => $_POST['number']
);
$format = array(
'%s',
'%s'
);
$success=$wpdb->insert( $table, $data,
$format );
if($success){
echo 'data has been save' ;
}
} else {
?>
<form method="post">
<input type="text" name="yourname">
<textarea name="number"></textarea>
<input type="submit">
</form>
<?php
}
?>
``` | ```
$table = wp_save;
```
This is setting `$table` to a PHP [constant](http://php.net/manual/en/language.constants.php) `wp_save`. If I had to guess I'd say you don't actually have a constant by that name, and just meant to set the table name to `wp_save`. To do that you need to put the table name between quotes, so that it's a [String](http://php.net/manual/en/language.types.string.php):
```
$table = 'wp_save';
```
However, given that WordPress users can change the `wp_` prefix in the database to whatever they like, you should use `$wpdb->prefix` to use the correct prefix as set by the user:
```
$table = $wpdb->prefix . 'save';
```
Before diving in too deep on building a plugin though, I'd suggest brushing up on the basics of PHP so that you know the difference between the different types of values, like Strings and Constants. Ultimately everything you're going to be doing in the back-end is PHP, and the fundamentals don't differ just because it's WordPress. |
307,521 | <p>I have registered a widget in order to allow users to filter posts by category or write something in the search box, the problem is that my 'blog' page is 'home.php' because it is a single-page-site (in index.php I am loading all the content), when I pick up a category or click on search button it redirects to index.php, instead of remaining in home.php.</p>
<p>How can I change that behaviour?</p>
| [
{
"answer_id": 307487,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$table = wp_save;\n</code></pre>\n\n<p>This is setting <code>$table</code> to a PHP <a href=\"h... | 2018/07/02 | [
"https://wordpress.stackexchange.com/questions/307521",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137882/"
] | I have registered a widget in order to allow users to filter posts by category or write something in the search box, the problem is that my 'blog' page is 'home.php' because it is a single-page-site (in index.php I am loading all the content), when I pick up a category or click on search button it redirects to index.php, instead of remaining in home.php.
How can I change that behaviour? | ```
$table = wp_save;
```
This is setting `$table` to a PHP [constant](http://php.net/manual/en/language.constants.php) `wp_save`. If I had to guess I'd say you don't actually have a constant by that name, and just meant to set the table name to `wp_save`. To do that you need to put the table name between quotes, so that it's a [String](http://php.net/manual/en/language.types.string.php):
```
$table = 'wp_save';
```
However, given that WordPress users can change the `wp_` prefix in the database to whatever they like, you should use `$wpdb->prefix` to use the correct prefix as set by the user:
```
$table = $wpdb->prefix . 'save';
```
Before diving in too deep on building a plugin though, I'd suggest brushing up on the basics of PHP so that you know the difference between the different types of values, like Strings and Constants. Ultimately everything you're going to be doing in the back-end is PHP, and the fundamentals don't differ just because it's WordPress. |
307,539 | <p>Is is safe to edit language files from wp-content/languages/plugins/woocommerce-ro_RO.mo(.po) ? I'm asking this because I don't want them to be overriden on plugin update. Sorry if dumb question.</p>
| [
{
"answer_id": 307487,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$table = wp_save;\n</code></pre>\n\n<p>This is setting <code>$table</code> to a PHP <a href=\"h... | 2018/07/02 | [
"https://wordpress.stackexchange.com/questions/307539",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115614/"
] | Is is safe to edit language files from wp-content/languages/plugins/woocommerce-ro\_RO.mo(.po) ? I'm asking this because I don't want them to be overriden on plugin update. Sorry if dumb question. | ```
$table = wp_save;
```
This is setting `$table` to a PHP [constant](http://php.net/manual/en/language.constants.php) `wp_save`. If I had to guess I'd say you don't actually have a constant by that name, and just meant to set the table name to `wp_save`. To do that you need to put the table name between quotes, so that it's a [String](http://php.net/manual/en/language.types.string.php):
```
$table = 'wp_save';
```
However, given that WordPress users can change the `wp_` prefix in the database to whatever they like, you should use `$wpdb->prefix` to use the correct prefix as set by the user:
```
$table = $wpdb->prefix . 'save';
```
Before diving in too deep on building a plugin though, I'd suggest brushing up on the basics of PHP so that you know the difference between the different types of values, like Strings and Constants. Ultimately everything you're going to be doing in the back-end is PHP, and the fundamentals don't differ just because it's WordPress. |
307,542 | <p>It can be sometimes bothersome when, in the Discussion (Comments) dashboard, where the admin can see a list of comments, moving the mouse over a link will cause a preview of that link. Sometimes the preview gets in the way of looking at the comment. This is especially true with spam comments.</p>
<p>And I am also concerned that a link to a page/site that had some 'bad' code would cause a compromise of my site. </p>
<p>Is there a way to disable this 'feature'? Not sure where it is coming from.</p>
| [
{
"answer_id": 338830,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>This is still happening in WP5.2.1. You can verify it by looking at your spam messages (via the Admin,... | 2018/07/02 | [
"https://wordpress.stackexchange.com/questions/307542",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29416/"
] | It can be sometimes bothersome when, in the Discussion (Comments) dashboard, where the admin can see a list of comments, moving the mouse over a link will cause a preview of that link. Sometimes the preview gets in the way of looking at the comment. This is especially true with spam comments.
And I am also concerned that a link to a page/site that had some 'bad' code would cause a compromise of my site.
Is there a way to disable this 'feature'? Not sure where it is coming from. | [Since version 4.1.6](https://wordpress.org/support/topic/how-to-disable-mshots-service/#post-12939728), Akismet has a filter which [allows you to disable these "mShots"](https://wordpress.org/support/topic/how-to-disable-mshots-service/#post-12944077) (the site preview popups):
```
<?php
function disable_akismet_mshots( $value ) {
return false;
}
add_filter( 'akismet_enable_mshots', 'disable_akismet_mshots' );
``` |
307,580 | <p>I'm working on a Plugin for the WordPress Customizer and need to call a function when the previewer has loaded. Is there an event or an other method that tells me the preview is loaded?</p>
<p>If have tried:</p>
<pre><code>jQuery(window).load (function() { // Customizer loaded...
wp.customize.previewer.bind( 'refresh', function() { // doesn't seem to work ?!
alert ('Previewer has loaded');
}
}
</code></pre>
<p>I've also tried <code>wp.customizer.bind('refresh', function (){</code></p>
<p>Is there no event that gets fired when the preview is loaded? The refresh event gets fired when the previewer gets refreshed.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 307901,
"author": "Milli",
"author_id": 146281,
"author_profile": "https://wordpress.stackexchange.com/users/146281",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't found an Customizer API event for when the preview has loaded. Here is a solution with the on load ... | 2018/07/03 | [
"https://wordpress.stackexchange.com/questions/307580",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146281/"
] | I'm working on a Plugin for the WordPress Customizer and need to call a function when the previewer has loaded. Is there an event or an other method that tells me the preview is loaded?
If have tried:
```
jQuery(window).load (function() { // Customizer loaded...
wp.customize.previewer.bind( 'refresh', function() { // doesn't seem to work ?!
alert ('Previewer has loaded');
}
}
```
I've also tried `wp.customizer.bind('refresh', function (){`
Is there no event that gets fired when the preview is loaded? The refresh event gets fired when the previewer gets refreshed.
Any ideas? | Yes, this is the way to detect when the preview has loaded:
```
wp.customize.bind( 'ready', function() {
wp.customize.previewer.bind( 'ready', function( message ) {
console.info( 'Preview is loaded' );
} );
} );
```
This JS code should be enqueued at the `customize_controls_enqueue_scripts` action with `customize-controls` script as its dependency. |
307,591 | <p>I want to use a fallback image if no featured image is set. I'm using the following code, but the image is not shown...</p>
<pre><code><?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?>
<?php the_post_thumbnail( array(334, 259) ); // Declare pixel size you need inside the array ?>
<?php else : // No thumbnail? Showing default is better UX than no image. ?>
<img src="/wp/wp-content/themes/klicknet-theme/images/testbild.png"
alt="testbild" width="334" height="259" title="Bild: <?php the_title(); ?>">
<?php endif; ?>
</code></pre>
<p>Any ideas why?</p>
| [
{
"answer_id": 307621,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Your code looks OK and it should work just fine. But there are some things you can (and you should) f... | 2018/07/03 | [
"https://wordpress.stackexchange.com/questions/307591",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82174/"
] | I want to use a fallback image if no featured image is set. I'm using the following code, but the image is not shown...
```
<?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?>
<?php the_post_thumbnail( array(334, 259) ); // Declare pixel size you need inside the array ?>
<?php else : // No thumbnail? Showing default is better UX than no image. ?>
<img src="/wp/wp-content/themes/klicknet-theme/images/testbild.png"
alt="testbild" width="334" height="259" title="Bild: <?php the_title(); ?>">
<?php endif; ?>
```
Any ideas why? | Your code looks OK and it should work just fine. But there are some things you can (and you should) fix.
1. You don't use absolute URL for your fallback image
-----------------------------------------------------
You pass `/wp/wp-content/themes/klicknet-theme/images/testbild.png` as src of your image. It would be much better and more secure if you'd use WP functions in there. For example like so:
```
<img src="<?php bloginfo('template_url'); ?>/images/testbild.png">
```
2. You don't escape the title properly
--------------------------------------
In your fallback image you use `the_title()` in title attribute. But you don't escape it as an attribute. If the title contains `"` character, it will break your HTML. Another problem is that the title can contain HTML tags, and they will be printed in your attribute.
If you want to use title as attribute, you should use [`the_title_attribute`](https://codex.wordpress.org/Function_Reference/the_title_attribute) function instead. So the fixed version of that line can look something like this:
```
<img src="<?php bloginfo('template_url'); ?>/images/testbild.png" alt="testbild" width="334" height="259" title="<?php the_title_attribute( array( 'before' => 'Bild: ', 'after' => '' ) ); ?>">
``` |
307,636 | <p>When i try to install a website that i got as an duplicator archive i get the following error at the very last step of the installation:</p>
<p><a href="https://i.stack.imgur.com/oIbB7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oIbB7.jpg" alt="enter image description here"></a>
I am using the latest version of xampp on my local machine which has 16GB of DDR4. These are the relevant values in my PHP.INI</p>
<pre><code>memory_limit=1024M
max_execution_time=300
post_max_size=32M
</code></pre>
| [
{
"answer_id": 307605,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": false,
"text": "<p>You can't add additional \"folders\" in the post editing screen. You would need to change your permalink ... | 2018/07/04 | [
"https://wordpress.stackexchange.com/questions/307636",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122013/"
] | When i try to install a website that i got as an duplicator archive i get the following error at the very last step of the installation:
[](https://i.stack.imgur.com/oIbB7.jpg)
I am using the latest version of xampp on my local machine which has 16GB of DDR4. These are the relevant values in my PHP.INI
```
memory_limit=1024M
max_execution_time=300
post_max_size=32M
``` | You can't add additional "folders" in the post editing screen. You would need to change your permalink structure, so that Posts include the Category in the URL. In Settings > Permalinks, choose "Custom Structure" and paste
`/%category%/%postname%/`
Keep in mind this will change all your Post URLs, so you'll need to add redirects. Also keep in mind small tweaks to permalinks like this don't often give you a big SEO boost so depending on how many posts you would need to redirect, it may be worth investing more effort into optimizing the on-page content rather than changing permalinks. |
307,640 | <p>Created my first custom theme from scratch and I'm trying to do a listing of all posts with the same tag.</p>
<p>In <code>tag.php</code> I display all posts with that specific tag via a <code>WP_Query</code> and I'm trying to implement the pagination for that listing (using <code>paginate_links()</code>). Page links seem to be outputted correctly. Also the first page looks good.</p>
<p>What I don't understand is that when I go on to the next tag page (or to any of the page links outputted from my <code>tag.php</code> template e.g. <code>http://127.0.0.1/wp_site/tag/test_tag/page/2/</code>) the content from <code>index.php</code> is being displayed.</p>
<p>What am I actually missing for displaying the subsequent tag pages correctly?</p>
<h2><code>tag.php</code> template CODE:</h2>
<pre><code><?php get_header(); ?>
<div class="">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php if (have_posts()) : ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<h1 class="entry-title">Other entries related to &#39;<?php single_tag_title(); ?>&#39;</h1>
</header><!-- .entry-header -->
<div class="entry-content"></div><!-- .entry-content -->
</article><!-- #post-## -->
<div>
<?php while (have_posts()) : the_post(); ?>
<?php
$tagId = get_queried_object()->term_id;
$postType = get_post_type();
?>
<?php endwhile; ?>
<?php
$htmlOutput = '';
/* the 'terms' ID is the testimonial category parent id */
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = [
'post_type' => 'testimonials-widget',
'tag_id' => $tagId,
'posts_per_page' => 3,
'paged' => $paged,
'tax_query' => [
[
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => '8',
]
],
];
$post_query = new WP_Query($args);
$contentHtml = '';
if($post_query->have_posts() ) {
$posts = $post_query->posts;
foreach($posts as $post) {
// generate html output
}
}
wp_reset_postdata();
echo $contentHtml;
?>
</div>
<div class="mainContentWrapperCls">
<?php
echo paginate_links( array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $post_query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'type' => 'plain',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => sprintf( '<i></i> %1$s', __( '&lt;&lt; Previous page', 'text-domain' ) ),
'next_text' => sprintf( '%1$s <i></i>', __( 'Next page &gt;&gt;', 'text-domain' ) ),
'add_args' => false,
'add_fragment' => '',
) );
?>
</div>
<?php else : ?>
<h1>No posts were found.</h1>
<?php endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
</div><!-- .wrap -->
<?php get_footer(); ?>
</code></pre>
<blockquote>
<p><em><strong>Note:</strong></em> I created a new query with <code>WP_Query</code> in <code>tag.php</code>. The reason why I did this is because I didn't know how to generate the type of pagination I needed (<code><Prev 1 2 3 Next></code> style) via <code>paginate_links()</code>, with the main query.</p>
</blockquote>
<h2>Theme <code>functions.php</code> CODE:</h2>
<pre><code><?php
function myCustomThemeScriptEnqueue() {
// Theme stylesheet, js
wp_enqueue_style('myCustomTheme-style', get_stylesheet_uri(), array(), '1.0.0', 'all');
}
function myCustomThemeThemeSetup() {
add_theme_support('menus');
add_post_type_support( 'page', 'excerpt' );
}
function nllTagFilter($query) {
if ($query->is_main_query()) {
if ($query->is_tag) {
$post_types = get_post_types();
$query->set('post_type', $post_types);
}
}
}
add_action('pre_get_posts','nllTagFilter');
add_action('wp_enqueue_scripts', 'myCustomThemeScriptEnqueue');
add_action('init', 'myCustomThemeThemeSetup');
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 150, 150 );
?>
</code></pre>
<p>This is my theme's file-structure so far:</p>
<p><a href="https://i.stack.imgur.com/PzHKj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PzHKj.png" alt="custom theme file structure" /></a></p>
| [
{
"answer_id": 307663,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": true,
"text": "<h2>Overall CODE issues:</h2>\n\n<p>Your CODE is so wrong in so many ways that I shouldn't even attempt to addres... | 2018/07/04 | [
"https://wordpress.stackexchange.com/questions/307640",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133712/"
] | Created my first custom theme from scratch and I'm trying to do a listing of all posts with the same tag.
In `tag.php` I display all posts with that specific tag via a `WP_Query` and I'm trying to implement the pagination for that listing (using `paginate_links()`). Page links seem to be outputted correctly. Also the first page looks good.
What I don't understand is that when I go on to the next tag page (or to any of the page links outputted from my `tag.php` template e.g. `http://127.0.0.1/wp_site/tag/test_tag/page/2/`) the content from `index.php` is being displayed.
What am I actually missing for displaying the subsequent tag pages correctly?
`tag.php` template CODE:
------------------------
```
<?php get_header(); ?>
<div class="">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php if (have_posts()) : ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<h1 class="entry-title">Other entries related to '<?php single_tag_title(); ?>'</h1>
</header><!-- .entry-header -->
<div class="entry-content"></div><!-- .entry-content -->
</article><!-- #post-## -->
<div>
<?php while (have_posts()) : the_post(); ?>
<?php
$tagId = get_queried_object()->term_id;
$postType = get_post_type();
?>
<?php endwhile; ?>
<?php
$htmlOutput = '';
/* the 'terms' ID is the testimonial category parent id */
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = [
'post_type' => 'testimonials-widget',
'tag_id' => $tagId,
'posts_per_page' => 3,
'paged' => $paged,
'tax_query' => [
[
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => '8',
]
],
];
$post_query = new WP_Query($args);
$contentHtml = '';
if($post_query->have_posts() ) {
$posts = $post_query->posts;
foreach($posts as $post) {
// generate html output
}
}
wp_reset_postdata();
echo $contentHtml;
?>
</div>
<div class="mainContentWrapperCls">
<?php
echo paginate_links( array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $post_query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'type' => 'plain',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => sprintf( '<i></i> %1$s', __( '<< Previous page', 'text-domain' ) ),
'next_text' => sprintf( '%1$s <i></i>', __( 'Next page >>', 'text-domain' ) ),
'add_args' => false,
'add_fragment' => '',
) );
?>
</div>
<?php else : ?>
<h1>No posts were found.</h1>
<?php endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
</div><!-- .wrap -->
<?php get_footer(); ?>
```
>
> ***Note:*** I created a new query with `WP_Query` in `tag.php`. The reason why I did this is because I didn't know how to generate the type of pagination I needed (`<Prev 1 2 3 Next>` style) via `paginate_links()`, with the main query.
>
>
>
Theme `functions.php` CODE:
---------------------------
```
<?php
function myCustomThemeScriptEnqueue() {
// Theme stylesheet, js
wp_enqueue_style('myCustomTheme-style', get_stylesheet_uri(), array(), '1.0.0', 'all');
}
function myCustomThemeThemeSetup() {
add_theme_support('menus');
add_post_type_support( 'page', 'excerpt' );
}
function nllTagFilter($query) {
if ($query->is_main_query()) {
if ($query->is_tag) {
$post_types = get_post_types();
$query->set('post_type', $post_types);
}
}
}
add_action('pre_get_posts','nllTagFilter');
add_action('wp_enqueue_scripts', 'myCustomThemeScriptEnqueue');
add_action('init', 'myCustomThemeThemeSetup');
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 150, 150 );
?>
```
This is my theme's file-structure so far:
[](https://i.stack.imgur.com/PzHKj.png) | Overall CODE issues:
--------------------
Your CODE is so wrong in so many ways that I shouldn't even attempt to address them here. I suggest you study [Official WordPress Theme Handbook](https://developer.wordpress.org/themes/) properly before doing these sort of customizations.
For the sake of the context, I'm ignoring other issues within your CODE and touching only the issues below:
1. Why `index.php` template is being loaded?
--------------------------------------------
First of all, you are getting wrong pagination from your erroneous CODE (check the explanation below). So apart from the first tag page, all the other tag pages are nonexistent (i.e. you need to add more posts to the tag to get more tag pages).
Secondly, According to WordPress Template loading rules, `404.php` template should be loaded for those non-existing tag pages (as you probably know, in HTTP, 404 is the **Page Not Found Error CODE**). However, since you don't have a `404.php` template in your theme, `index.php` template is being loaded, as it is the **ultimate fallback template** in a WordPress theme.
Now, if you create a `404.php` template, then you'll see that it'll be loaded instead of `index.php` for those non-existing tag pages.
Study [WordPress Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) properly for a better understanding of how different templates are loaded for different content.
2. Fixing the wrong pagination:
-------------------------------
As I said above, you're getting nonexistent tag page numbers within your pagination. To remove those nonexistent page numbers from the pagination, you need to delete the
```
'total' => $post_query->max_num_pages
```
line from the `paginate_links` function call in `tag.php` template file.
The reason is:
1. `$post_query` is your custom query, not the main query that should determine the number of pages the tag archive has. You even used `wp_reset_postdata()` before `paginate_links` function call, so no reason to use that variable here.
2. The `total` parameter of the `paginate_links` function by default gets the value of the main WP\_Query's `max_num_pages` property. So deleting it will automatically provide the correct value for the pagination from the main WP\_Query object.
3. Pagination without new `WP_Query`:
-------------------------------------
In the comments you said:
>
> The reason why I did this is because I didn't know how to generate the type of pagination I needed (`<Prev 1 2 3 Next>` style) via `paginate_links()`, with the main query.
>
>
>
Well, you don't need a completely new `WP_Query` just for a different pagination style. In fact, the `paginate_links()` function don't need the main `WP_Query` object at all!
So all you need for your desired pagination style is:
```
echo paginate_links( array(
'end_size' => 2,
'mid_size' => 1,
'prev_text' => __( '<< Previous page', 'text-domain' ),
'next_text' => __( 'Next page >>', 'text-domain' )
) );
```
All the other values are being collected by default (including the main `WP_Query` object)! So you can remove your new `WP_Query` object in the `tag.php` template entirely. Check the [`paginate_links` documentation](https://developer.wordpress.org/reference/functions/paginate_links/).
Having said that, there can be only one more thing you may want (judging from your comments):
4. Control the number of posts per tag page:
--------------------------------------------
You don't need a new `WP_Query` for this either. This can be easily achieved from the following CODE in `functions.php`:
```
function tag_post_per_page_filter( $query ) {
if ( $query->is_main_query() ) {
if ( $query->is_tag ) {
$query->set( 'posts_per_page', 3 );
}
}
}
add_action('pre_get_posts','tag_post_per_page_filter');
```
Basically it sets the `posts_per_page` to `3` in the main `WP_Query` object for the tag pages. That's all. |
307,650 | <p>The default menu classes in WordPress are pretty useful. But one problem that i stumble over from time to time is with categories as subitems in menus. For example the following menu structure:</p>
<ul>
<li>Page 1</li>
<li>Page 2
<ul>
<li>Category 1</li>
</ul></li>
<li>Page 3</li>
</ul>
<p>So when <code>Category 1</code> is active <code>Page 2</code> gets <code>.current-menu-ancestor</code> which is fine … but as soon as a post of <code>Category 1</code> is viewed <code>Page 2</code> has no specific classes … But <code>Category 1</code> has <code>.current-menu-ancestor</code> as expected.</p>
<p><strong>So finally here's the question: How do i assign a class for these <code>.current-post-ancestor</code> parents?</strong></p>
<p>I'm searching for a PHP solution. Javascript/jQuery is pretty clear … here is a jQuery solution for better understanding what i want to do (And for those who have the same problem and are happy with a JS solution):</p>
<pre><code>jQuery( 'li.current-post-ancestor' ).parents( 'li.menu-item' ).addClass( 'current-menu-ancestor' );
</code></pre>
| [
{
"answer_id": 307656,
"author": "mcgoo",
"author_id": 146340,
"author_profile": "https://wordpress.stackexchange.com/users/146340",
"pm_score": 0,
"selected": false,
"text": "<p>You could use <a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow noreferrer\">http... | 2018/07/04 | [
"https://wordpress.stackexchange.com/questions/307650",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52227/"
] | The default menu classes in WordPress are pretty useful. But one problem that i stumble over from time to time is with categories as subitems in menus. For example the following menu structure:
* Page 1
* Page 2
+ Category 1
* Page 3
So when `Category 1` is active `Page 2` gets `.current-menu-ancestor` which is fine … but as soon as a post of `Category 1` is viewed `Page 2` has no specific classes … But `Category 1` has `.current-menu-ancestor` as expected.
**So finally here's the question: How do i assign a class for these `.current-post-ancestor` parents?**
I'm searching for a PHP solution. Javascript/jQuery is pretty clear … here is a jQuery solution for better understanding what i want to do (And for those who have the same problem and are happy with a JS solution):
```
jQuery( 'li.current-post-ancestor' ).parents( 'li.menu-item' ).addClass( 'current-menu-ancestor' );
``` | This is probably what you are looking for ..
```
add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );
function add_menu_parent_class( $items ) {
$parents = array();
foreach ( $items as $item ) {
if ( in_array('current-post-ancestor', $item->classes) ) {
$parents[] = $item->menu_item_parent;
}
}
foreach ( $items as $item ) {
if ( in_array( $item->ID, $parents ) ) {
$item->classes[] = 'current-menu-ancestor';
}
}
return $items;
}
```
It will add a class to **current post ancestor** menu item parent. I have tried this in my theme and it is working perfectly. |
307,699 | <p>I've been trying to solve this myself for hours but I can't figure out where I am going wrong.</p>
<p>I have a custom registration form on my website and I would like to add a checkbox for users to sign up for the newsletter.</p>
<p>I went through the <a href="https://beta.docs.mailpoet.com/article/195-add-subscribers-through-your-own-form-or-plugin" rel="nofollow noreferrer">Mailpoet Docs</a> and tried everything that they describe there but something is not working for me. </p>
<p>The user is being signed up successfully but never gets added to my mainling list. Here's my code</p>
<pre><code>function newsletterSignUp(){
$subscriber_data = array(
'email' => sanitize_text_field($_POST['email']),
'first_name' => sanitize_text_field($_POST['first_name']),
'last_name' => sanitize_text_field($_POST['last_name'])
);
$list = \MailPoet\API\API::MP('v1')->getLists()[0][id];
//Returns the ID of the list that I want to assign subscribers to
try {
$subscriber = \MailPoet\API\API::MP('v1')->addSubscriber($subscriber_data, $list, $options);
} catch(Exception $exception) {
// return $exception->getMessage();
}
}
</code></pre>
<p>I am calling this function like this:</p>
<pre><code>if(isset($_POST['submit'])){
// Some other code to sign up the user
if(isset($_POST['subscribe'])){ //The name of my checkbox input
newsletterSignUp();
}
}
</code></pre>
<p>Any help will be greatly appreciated!!</p>
| [
{
"answer_id": 307656,
"author": "mcgoo",
"author_id": 146340,
"author_profile": "https://wordpress.stackexchange.com/users/146340",
"pm_score": 0,
"selected": false,
"text": "<p>You could use <a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow noreferrer\">http... | 2018/07/04 | [
"https://wordpress.stackexchange.com/questions/307699",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145115/"
] | I've been trying to solve this myself for hours but I can't figure out where I am going wrong.
I have a custom registration form on my website and I would like to add a checkbox for users to sign up for the newsletter.
I went through the [Mailpoet Docs](https://beta.docs.mailpoet.com/article/195-add-subscribers-through-your-own-form-or-plugin) and tried everything that they describe there but something is not working for me.
The user is being signed up successfully but never gets added to my mainling list. Here's my code
```
function newsletterSignUp(){
$subscriber_data = array(
'email' => sanitize_text_field($_POST['email']),
'first_name' => sanitize_text_field($_POST['first_name']),
'last_name' => sanitize_text_field($_POST['last_name'])
);
$list = \MailPoet\API\API::MP('v1')->getLists()[0][id];
//Returns the ID of the list that I want to assign subscribers to
try {
$subscriber = \MailPoet\API\API::MP('v1')->addSubscriber($subscriber_data, $list, $options);
} catch(Exception $exception) {
// return $exception->getMessage();
}
}
```
I am calling this function like this:
```
if(isset($_POST['submit'])){
// Some other code to sign up the user
if(isset($_POST['subscribe'])){ //The name of my checkbox input
newsletterSignUp();
}
}
```
Any help will be greatly appreciated!! | This is probably what you are looking for ..
```
add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );
function add_menu_parent_class( $items ) {
$parents = array();
foreach ( $items as $item ) {
if ( in_array('current-post-ancestor', $item->classes) ) {
$parents[] = $item->menu_item_parent;
}
}
foreach ( $items as $item ) {
if ( in_array( $item->ID, $parents ) ) {
$item->classes[] = 'current-menu-ancestor';
}
}
return $items;
}
```
It will add a class to **current post ancestor** menu item parent. I have tried this in my theme and it is working perfectly. |
307,713 | <p>I have a custom post type <code>mycpt</code> and I'm trying to allow for a variable to be appended onto the end of the URL right after the post name slug, like this:</p>
<pre><code>www.site.com/mycpt/the-name-of-my-post/var-value-here/
</code></pre>
<p>I've been searching around, and the only examples I can find don't use the post name/slug in the URL, but rather taxonomies, so I'm not sure what the correct way to do it is. Here is what I'm trying now, but it's treating the URL with the variable as a separate page type (it's loading a default template rather than the template my custom post type uses).</p>
<pre><code>add_action( 'init', function() {
add_rewrite_tag( '%my_var%', '([^/]*)' );
add_rewrite_rule( '^mycpt/(.*)/([^/]*)/?', 'index.php?post_type=mycpt&my_var=$matches[1]', 'top' );
}, 10, 0 );
</code></pre>
<p>I also tried changing <code>$matches[1]</code> to <code>$matches[2]</code> since I thought maybe the wildcard for the post name/slug was the first match, but that didn't work either.</p>
<p>Can anybody see what I'm doing wrong here?</p>
| [
{
"answer_id": 307715,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>As a temporary solution you can try using free plugin : <a href=\"https://wordpress.org/plugins/custom-post-type-... | 2018/07/04 | [
"https://wordpress.stackexchange.com/questions/307713",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63238/"
] | I have a custom post type `mycpt` and I'm trying to allow for a variable to be appended onto the end of the URL right after the post name slug, like this:
```
www.site.com/mycpt/the-name-of-my-post/var-value-here/
```
I've been searching around, and the only examples I can find don't use the post name/slug in the URL, but rather taxonomies, so I'm not sure what the correct way to do it is. Here is what I'm trying now, but it's treating the URL with the variable as a separate page type (it's loading a default template rather than the template my custom post type uses).
```
add_action( 'init', function() {
add_rewrite_tag( '%my_var%', '([^/]*)' );
add_rewrite_rule( '^mycpt/(.*)/([^/]*)/?', 'index.php?post_type=mycpt&my_var=$matches[1]', 'top' );
}, 10, 0 );
```
I also tried changing `$matches[1]` to `$matches[2]` since I thought maybe the wildcard for the post name/slug was the first match, but that didn't work either.
Can anybody see what I'm doing wrong here? | Here's a complete working example that adds a post type, with extra rule to capture an additional parameter:
```
function wpd_post_type_and_rule() {
register_post_type( 'mycpt',
array(
'labels' => array(
'name' => __( 'mycpt' ),
),
'public' => true,
'rewrite' => array( 'slug' => 'mycpt' ),
)
);
add_rewrite_tag( '%mycpt_var%', '([^/]*)' );
add_rewrite_rule(
'^mycpt/([^/]*)/([^/]*)/?$',
'index.php?mycpt=$matches[1]&mycpt_var=$matches[2]',
'top'
);
}
add_action( 'init', 'wpd_post_type_and_rule' );
```
After adding this and flushing rewrite rules, you'll have both
```
www.site.com/mycpt/the-name-of-my-post/
```
and
```
www.site.com/mycpt/the-name-of-my-post/var-value-here/
```
You can get the value of `mycpt_var` in the template with:
```
echo get_query_var( 'mycpt_var' );
``` |
307,783 | <p>I built a page with Elementor, and I want to use it as my home page. When I use a static home page with my theme, it still gets wrapped with the header, footer, and content container, which I don't want in this case.</p>
<p>I've built a simple <code>front-page.php</code> template to try to just output the contents of this page.</p>
<pre><code><!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js no-svg">
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php
$page = get_page_by_path( 'home' );
$content = apply_filters('the_content', $page->post_content);
echo $content;
get_footer();
?>
</body>
<?php wp_footer(); ?>
</code></pre>
<p>This works to output the <em>content</em>, but I don't get the styles and my posts widgets are MIA. How can I modify this template to also get the styles and so that all the widgets will be present?</p>
| [
{
"answer_id": 370754,
"author": "Maduka Jayalath",
"author_id": 110601,
"author_profile": "https://wordpress.stackexchange.com/users/110601",
"pm_score": 3,
"selected": false,
"text": "<p>Here is the way,</p>\n<pre><code>$contentElementor = "";\n\nif (class_exists("\\\\El... | 2018/07/05 | [
"https://wordpress.stackexchange.com/questions/307783",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31649/"
] | I built a page with Elementor, and I want to use it as my home page. When I use a static home page with my theme, it still gets wrapped with the header, footer, and content container, which I don't want in this case.
I've built a simple `front-page.php` template to try to just output the contents of this page.
```
<!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js no-svg">
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php
$page = get_page_by_path( 'home' );
$content = apply_filters('the_content', $page->post_content);
echo $content;
get_footer();
?>
</body>
<?php wp_footer(); ?>
```
This works to output the *content*, but I don't get the styles and my posts widgets are MIA. How can I modify this template to also get the styles and so that all the widgets will be present? | Here is the way,
```
$contentElementor = "";
if (class_exists("\\Elementor\\Plugin")) {
$post_ID = 124;
$pluginElementor = \Elementor\Plugin::instance();
$contentElementor = $pluginElementor->frontend->get_builder_content($post_ID);
}
echo $contentElementor;
``` |
307,794 | <p>I have the following problem when I am validating a field with the Advanced Custom Fields plugin in wordpress. What happens is that the field is validated correctly but the error appears on a new page instead of going out on the same page above the field to which I am validating. The code to validate is the following:</p>
<pre><code>function validate_fields_contact()
{
add_filter('acf/validate_value/name=phone_contact', 'validate_phone_number', 10, 4);
}
function validate_phone_number($valid, $value, $field, $input)
{
if (!$valid) {
return $valid;
}
if(!preg_match("/^\+XX(\s|\d){8,12}$/", $value)) {
return __('Incorrect Format.');
}
return true;
}
</code></pre>
<p><strong>It should be like that:</strong> </p>
<p><a href="https://i.stack.imgur.com/1r7Bm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1r7Bm.png" alt="enter image description here"></a></p>
<p><strong>This is what happens</strong></p>
<p><a href="https://i.stack.imgur.com/0Po9Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Po9Y.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 319945,
"author": "Kostiantyn Petlia",
"author_id": 104932,
"author_profile": "https://wordpress.stackexchange.com/users/104932",
"pm_score": 3,
"selected": true,
"text": "<p>I did have the same issue. And I wasted enough time for the answer.</p>\n\n<p>At first be sure tha... | 2018/07/05 | [
"https://wordpress.stackexchange.com/questions/307794",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144662/"
] | I have the following problem when I am validating a field with the Advanced Custom Fields plugin in wordpress. What happens is that the field is validated correctly but the error appears on a new page instead of going out on the same page above the field to which I am validating. The code to validate is the following:
```
function validate_fields_contact()
{
add_filter('acf/validate_value/name=phone_contact', 'validate_phone_number', 10, 4);
}
function validate_phone_number($valid, $value, $field, $input)
{
if (!$valid) {
return $valid;
}
if(!preg_match("/^\+XX(\s|\d){8,12}$/", $value)) {
return __('Incorrect Format.');
}
return true;
}
```
**It should be like that:**
[](https://i.stack.imgur.com/1r7Bm.png)
**This is what happens**
[](https://i.stack.imgur.com/0Po9Y.png) | I did have the same issue. And I wasted enough time for the answer.
At first be sure that:
The ajax request isn't failed and happens. So, check:
1. Is acf\_form\_head() before get\_header() and run before any html is output?
2. Does your theme contain call to wp\_head()?
3. Does your theme contain call to wp\_foot()?
4. Are your deferring the loading of JavaScript or otherwise altering the way that JavaScript is loaded on the page?
(Look at [this ACF support topic](https://support.advancedcustomfields.com/forums/topic/my-acf_form-is-saving-to-the-database-but-not-showing-up-in-the-admin-panel-unde/) too. If you use acf\_form() for creating new user look at [this topic](https://support.advancedcustomfields.com/forums/topic/create-new-user-with-acf_form/)).
But in my case the root was is\_admin() in this line into the 'acf/validate\_value' hook:
```
if ( ! $valid || is_admin() ) { return $valid; }
```
**Because is\_admin() returns 'true' by AJAX requests**. As a result, the validate function didn't work.
Hope it will helpfully for somebody. |
307,795 | <p>I’m looking to add Instagram to my follow buttons, and on the settings pages it tells me:</p>
<p>You can setup Instagram, YouTube, Snapchat, and other buttons in an AddToAny Follow widget.</p>
<p>Add the “AddToAny Follow” widget in Customize or Widgets.</p>
<p>But in the AddToAny Follow Widget i’ve got linkedin, twitter and facebook. No trace of instagram, that is what I’m trying to add. (<a href="https://imgur.com/a/FEXOQYI" rel="nofollow noreferrer">https://imgur.com/a/FEXOQYI</a>)</p>
<p>What am I not understanding here?</p>
| [
{
"answer_id": 319945,
"author": "Kostiantyn Petlia",
"author_id": 104932,
"author_profile": "https://wordpress.stackexchange.com/users/104932",
"pm_score": 3,
"selected": true,
"text": "<p>I did have the same issue. And I wasted enough time for the answer.</p>\n\n<p>At first be sure tha... | 2018/07/05 | [
"https://wordpress.stackexchange.com/questions/307795",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8895/"
] | I’m looking to add Instagram to my follow buttons, and on the settings pages it tells me:
You can setup Instagram, YouTube, Snapchat, and other buttons in an AddToAny Follow widget.
Add the “AddToAny Follow” widget in Customize or Widgets.
But in the AddToAny Follow Widget i’ve got linkedin, twitter and facebook. No trace of instagram, that is what I’m trying to add. (<https://imgur.com/a/FEXOQYI>)
What am I not understanding here? | I did have the same issue. And I wasted enough time for the answer.
At first be sure that:
The ajax request isn't failed and happens. So, check:
1. Is acf\_form\_head() before get\_header() and run before any html is output?
2. Does your theme contain call to wp\_head()?
3. Does your theme contain call to wp\_foot()?
4. Are your deferring the loading of JavaScript or otherwise altering the way that JavaScript is loaded on the page?
(Look at [this ACF support topic](https://support.advancedcustomfields.com/forums/topic/my-acf_form-is-saving-to-the-database-but-not-showing-up-in-the-admin-panel-unde/) too. If you use acf\_form() for creating new user look at [this topic](https://support.advancedcustomfields.com/forums/topic/create-new-user-with-acf_form/)).
But in my case the root was is\_admin() in this line into the 'acf/validate\_value' hook:
```
if ( ! $valid || is_admin() ) { return $valid; }
```
**Because is\_admin() returns 'true' by AJAX requests**. As a result, the validate function didn't work.
Hope it will helpfully for somebody. |
307,916 | <p>I've just installed a fresh install of WordPress and before doing anything else I've tried to setup a multisite, which I would like to do with subdirectories. </p>
<p>But when I click on Network Setup I get the notification: </p>
<blockquote>
<p>Because your installation is not new, the sites in your WordPress
network must use sub-domains. The main site in a sub-directory
installation will need to use a modified permalink structure,
potentially breaking existing links.</p>
</blockquote>
<p>Can anyone tell me what I'm doing wrong, or what I need to change to allow subdirectories?</p>
| [
{
"answer_id": 307955,
"author": "Robert Gres",
"author_id": 146551,
"author_profile": "https://wordpress.stackexchange.com/users/146551",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://premium.wpmudev.org/forums/topic/enabling-network-because-your-install-is-not-new-the... | 2018/07/07 | [
"https://wordpress.stackexchange.com/questions/307916",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59568/"
] | I've just installed a fresh install of WordPress and before doing anything else I've tried to setup a multisite, which I would like to do with subdirectories.
But when I click on Network Setup I get the notification:
>
> Because your installation is not new, the sites in your WordPress
> network must use sub-domains. The main site in a sub-directory
> installation will need to use a modified permalink structure,
> potentially breaking existing links.
>
>
>
Can anyone tell me what I'm doing wrong, or what I need to change to allow subdirectories? | You don't need to do anything just past this code in your activated theme's `functions.php`
```
add_filter( 'allow_subdirectory_install', '__return_true' );
``` |
307,920 | <p>I want to remove tag, category classes from Post Titles of my WordPress blog. On the frontend, Wordpress generates extra classes for every single article title.</p>
<p>For Example, <a href="https://examsmate.in/indian-army-preparation-tips/" rel="nofollow noreferrer">this article</a>, has these article title classes "category-tips-guides" "tag-indian-army" as displayed in the following image:</p>
<p><a href="https://i.stack.imgur.com/J2Aqi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J2Aqi.png" alt="enter image description here"></a></p>
<p>I have tried the following snippet to remove some extra classes (<a href="https://wordpress.stackexchange.com/questions/302055/remove-classes-from-post-class?rq=1">shared on this page</a>) and it works:</p>
<pre><code>function lsmwp_remove_postclasses($classes, $class, $post_id) {
$classes = array_diff( $classes, array(
'hentry',
'type-' . get_post_type($post_id),
'status-' . get_post_status($post_id),
) );
return $classes;
add_filter('post_class', 'lsmwp_remove_postclasses', 10, 3);
</code></pre>
<p>But the issue with this code is that it doesn't remove any Tag, Category classes as I want.</p>
<p><strong>Some References to post_class:</strong></p>
<ol>
<li><a href="https://codex.wordpress.org/Function_Reference/post_class" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/post_class</a></li>
<li><a href="https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/post-template.php#L0" rel="nofollow noreferrer">https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/post-template.php#L0</a></li>
</ol>
| [
{
"answer_id": 307955,
"author": "Robert Gres",
"author_id": 146551,
"author_profile": "https://wordpress.stackexchange.com/users/146551",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://premium.wpmudev.org/forums/topic/enabling-network-because-your-install-is-not-new-the... | 2018/07/07 | [
"https://wordpress.stackexchange.com/questions/307920",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146528/"
] | I want to remove tag, category classes from Post Titles of my WordPress blog. On the frontend, Wordpress generates extra classes for every single article title.
For Example, [this article](https://examsmate.in/indian-army-preparation-tips/), has these article title classes "category-tips-guides" "tag-indian-army" as displayed in the following image:
[](https://i.stack.imgur.com/J2Aqi.png)
I have tried the following snippet to remove some extra classes ([shared on this page](https://wordpress.stackexchange.com/questions/302055/remove-classes-from-post-class?rq=1)) and it works:
```
function lsmwp_remove_postclasses($classes, $class, $post_id) {
$classes = array_diff( $classes, array(
'hentry',
'type-' . get_post_type($post_id),
'status-' . get_post_status($post_id),
) );
return $classes;
add_filter('post_class', 'lsmwp_remove_postclasses', 10, 3);
```
But the issue with this code is that it doesn't remove any Tag, Category classes as I want.
**Some References to post\_class:**
1. <https://codex.wordpress.org/Function_Reference/post_class>
2. <https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/post-template.php#L0> | You don't need to do anything just past this code in your activated theme's `functions.php`
```
add_filter( 'allow_subdirectory_install', '__return_true' );
``` |
307,930 | <p>Problem:</p>
<ul>
<li>I need to associate to every PostType a Company(done with Taxonomy, taxonomy is a huge list of Companies)</li>
<li>A company can be a Producer or a Developer</li>
<li>I need to Select a Producer on the PostType</li>
<li>I need to Select a Developer on the PostType</li>
</ul>
<p>As you understand you can have the same Company as Developer and Producer</p>
<p><strong>Solution ?</strong></p>
<p>Unfortunately i find myself like a fish out of water. Wordpress is the perfect CMS for this Job but for this task, ehmmm, i dont know :/
According my background i can associate a Company to a Post Type (Company will be the Taxonomy). But after ? How to do an intermediate Association (every Company can be a Developer, Publisher or Both) ?</p>
<p>P.S I Dont need meta fields (i need to insert at least 2000 companies if not more than that, custom fields will slow down hard i think the queries if i start to search a developer who has done x PostType)</p>
<p>Thanks in advance to each of you for your time, I do not owe you a beer, I owe you a ticket for the World Cup final if you give me a hand, I'm banging my head against the wall two days for that ...... :/ :D</p>
| [
{
"answer_id": 307955,
"author": "Robert Gres",
"author_id": 146551,
"author_profile": "https://wordpress.stackexchange.com/users/146551",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://premium.wpmudev.org/forums/topic/enabling-network-because-your-install-is-not-new-the... | 2018/07/07 | [
"https://wordpress.stackexchange.com/questions/307930",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146538/"
] | Problem:
* I need to associate to every PostType a Company(done with Taxonomy, taxonomy is a huge list of Companies)
* A company can be a Producer or a Developer
* I need to Select a Producer on the PostType
* I need to Select a Developer on the PostType
As you understand you can have the same Company as Developer and Producer
**Solution ?**
Unfortunately i find myself like a fish out of water. Wordpress is the perfect CMS for this Job but for this task, ehmmm, i dont know :/
According my background i can associate a Company to a Post Type (Company will be the Taxonomy). But after ? How to do an intermediate Association (every Company can be a Developer, Publisher or Both) ?
P.S I Dont need meta fields (i need to insert at least 2000 companies if not more than that, custom fields will slow down hard i think the queries if i start to search a developer who has done x PostType)
Thanks in advance to each of you for your time, I do not owe you a beer, I owe you a ticket for the World Cup final if you give me a hand, I'm banging my head against the wall two days for that ...... :/ :D | You don't need to do anything just past this code in your activated theme's `functions.php`
```
add_filter( 'allow_subdirectory_install', '__return_true' );
``` |
307,970 | <p>I am making my theme.
I am using wp_editor in front-end to submit post. </p>
<p>I submit through wp_editor in the specific page, and this being displayed in single.php.
At single.php I am using </p>
<pre><code><?php the_content(); ?>
</code></pre>
<p>The problem is when I put enter-key (like br tag) in a post that is several blank row, these blank rows are disappeared. All contents are shown without blank row. so it looks not cool. </p>
<p>My first language is not English, so I am not sure that my expression is good to explain my intention. </p>
<p>I mean, I want like this (A). but the content shows like (B). There's no blank rows.. </p>
<p>(A)
My name is mike. Hi. <br>
Hahaha. you look nice.<br><br></p>
<p>And what is you name?<br><br></p>
<p>(B)
My name is mike. Hi. <br>
Hahaha. you look nice.<br>
And what is you name?<br><br></p>
<p>Can someone have any idea?</p>
<p>Thank you.</p>
| [
{
"answer_id": 307955,
"author": "Robert Gres",
"author_id": 146551,
"author_profile": "https://wordpress.stackexchange.com/users/146551",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://premium.wpmudev.org/forums/topic/enabling-network-because-your-install-is-not-new-the... | 2018/07/08 | [
"https://wordpress.stackexchange.com/questions/307970",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133185/"
] | I am making my theme.
I am using wp\_editor in front-end to submit post.
I submit through wp\_editor in the specific page, and this being displayed in single.php.
At single.php I am using
```
<?php the_content(); ?>
```
The problem is when I put enter-key (like br tag) in a post that is several blank row, these blank rows are disappeared. All contents are shown without blank row. so it looks not cool.
My first language is not English, so I am not sure that my expression is good to explain my intention.
I mean, I want like this (A). but the content shows like (B). There's no blank rows..
(A)
My name is mike. Hi.
Hahaha. you look nice.
And what is you name?
(B)
My name is mike. Hi.
Hahaha. you look nice.
And what is you name?
Can someone have any idea?
Thank you. | You don't need to do anything just past this code in your activated theme's `functions.php`
```
add_filter( 'allow_subdirectory_install', '__return_true' );
``` |
308,021 | <p>I'm trying to add a class to list blocks (<code>core/list</code>) in Gutenberg. Unfortunately, it looks like because some blocks like lists and paragraphs don't have the standard default class name of <code>wp-block-{name}</code> they can't be renamed using the <a href="https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/#blocks-getblockdefaultclassname" rel="noreferrer"><code>blocks.getBlockDefaultClassName</code></a> filter.</p>
<p>To get around that, I've used the <code>blocks.getSaveContent.extraProps</code> filter, which seems to enable me to add a class to ALL the blocks that don't already have classes. Code below is how I got that working. It's adding <code>added-class-name</code> to blocks likes lists and paragraphs and so on. </p>
<pre><code>function addBlockClassName( className ) {
return Object.assign( className, { class: 'added-class-name' } );
}
wp.hooks.addFilter(
'blocks.getSaveContent.extraProps',
'gdt-guten-plugin/add-block-class-name',
addBlockClassName
);
</code></pre>
<p>And I'm enqueuing it like so:</p>
<pre><code>function gdt_blocks_class_rename() {
wp_enqueue_script(
'gdt-plugin-blacklist-blocks',
get_stylesheet_directory_uri() . '/dist/guten-addons.js',
array( 'wp-blocks' )
);
}
add_action( 'enqueue_block_editor_assets', 'gdt_blocks_class_rename' );
</code></pre>
<p>However, what I want to be able to do is add a class to <em>ONLY</em> list blocks? Can that be done at all?</p>
| [
{
"answer_id": 308044,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 4,
"selected": false,
"text": "<p>You have second and third arguments with this hook you can use the second to get the block type.</p>\n\n<p><a h... | 2018/07/09 | [
"https://wordpress.stackexchange.com/questions/308021",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17461/"
] | I'm trying to add a class to list blocks (`core/list`) in Gutenberg. Unfortunately, it looks like because some blocks like lists and paragraphs don't have the standard default class name of `wp-block-{name}` they can't be renamed using the [`blocks.getBlockDefaultClassName`](https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/#blocks-getblockdefaultclassname) filter.
To get around that, I've used the `blocks.getSaveContent.extraProps` filter, which seems to enable me to add a class to ALL the blocks that don't already have classes. Code below is how I got that working. It's adding `added-class-name` to blocks likes lists and paragraphs and so on.
```
function addBlockClassName( className ) {
return Object.assign( className, { class: 'added-class-name' } );
}
wp.hooks.addFilter(
'blocks.getSaveContent.extraProps',
'gdt-guten-plugin/add-block-class-name',
addBlockClassName
);
```
And I'm enqueuing it like so:
```
function gdt_blocks_class_rename() {
wp_enqueue_script(
'gdt-plugin-blacklist-blocks',
get_stylesheet_directory_uri() . '/dist/guten-addons.js',
array( 'wp-blocks' )
);
}
add_action( 'enqueue_block_editor_assets', 'gdt_blocks_class_rename' );
```
However, what I want to be able to do is add a class to *ONLY* list blocks? Can that be done at all? | There are issues in the answer marked as correct. It will break the alignment class functionality, and is not actually adding to the classList, instead it is overriding it. And you will only be able to use that one solution for your whole theme.
Instead you can use "registerBlockStyle()" to add a style variation to the list block, and set "isDefault" to true for it to use that class/style but still be able to skip using it, or add a multiple variations if you want.
the wp.domReady() makes sure that it loads when it should and applies the changes
```
wp.domReady( () => {
wp.blocks.registerBlockStyle( 'core/list', {
name: 'custom-list-style',
label: 'Custom list style',
isDefault: true
} );
} );
``` |
308,029 | <p>I want my user pay before every post publishing. I searched for some hooks that triggers before a post publishes, but all these hooks run after a post is successfully published and i don't want this.
pre_post_update, publish_post, save_post and wp_insert_post are the available hooks.
If there is not an action that runs before publishing post, how can i prevent publishing post is user don't pay when he wants to publish the post ?</p>
<p><strong>Edit</strong>: Now i'm using this code for checking if a post is publishing, but this function is not working, i'm using this function in a custom plugin. </p>
<pre><code>function af_check_payment( $new_status, $old_status, $post ) {
if ( $new_status == 'publish' && $old_status != 'publish' && $post->post_type == 'barbershop' ) {
wp_transition_post_status( 'pending', $old_status, $post );
echo 'At least i know its publishing';
}
}
add_action( 'transition_post_status', 'af_check_payment', 10, 3 );
</code></pre>
<p>This function does not echo or change any post status. </p>
| [
{
"answer_id": 308044,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 4,
"selected": false,
"text": "<p>You have second and third arguments with this hook you can use the second to get the block type.</p>\n\n<p><a h... | 2018/07/09 | [
"https://wordpress.stackexchange.com/questions/308029",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136480/"
] | I want my user pay before every post publishing. I searched for some hooks that triggers before a post publishes, but all these hooks run after a post is successfully published and i don't want this.
pre\_post\_update, publish\_post, save\_post and wp\_insert\_post are the available hooks.
If there is not an action that runs before publishing post, how can i prevent publishing post is user don't pay when he wants to publish the post ?
**Edit**: Now i'm using this code for checking if a post is publishing, but this function is not working, i'm using this function in a custom plugin.
```
function af_check_payment( $new_status, $old_status, $post ) {
if ( $new_status == 'publish' && $old_status != 'publish' && $post->post_type == 'barbershop' ) {
wp_transition_post_status( 'pending', $old_status, $post );
echo 'At least i know its publishing';
}
}
add_action( 'transition_post_status', 'af_check_payment', 10, 3 );
```
This function does not echo or change any post status. | There are issues in the answer marked as correct. It will break the alignment class functionality, and is not actually adding to the classList, instead it is overriding it. And you will only be able to use that one solution for your whole theme.
Instead you can use "registerBlockStyle()" to add a style variation to the list block, and set "isDefault" to true for it to use that class/style but still be able to skip using it, or add a multiple variations if you want.
the wp.domReady() makes sure that it loads when it should and applies the changes
```
wp.domReady( () => {
wp.blocks.registerBlockStyle( 'core/list', {
name: 'custom-list-style',
label: 'Custom list style',
isDefault: true
} );
} );
``` |
308,126 | <p>I am wondering whether it is possible to automatically add a class to a series of links based on the link text.</p>
<p>The scenario is as follows:</p>
<p>I am displaying a list of links on a page in Wordpress that link to other posts - in this case a custom post type for a schedule. The posts all have time based names, i.e. '12:23' '12:53' '13:23' and so on.</p>
<p>This generates a list of links like this:</p>
<pre><code><a href="departuretime/1223">12:23</a>
<a href="departuretime/1253">12:53</a>
<a href="departuretime/1323">13:23</a>
</code></pre>
<p>Where each link links to a full custom post associated to display that schedule.</p>
<p>I would like to format these links based on the current time and to do this I need the class to be automatically generated based on the link text.</p>
<pre><code><a class='1223' href="departuretime/1223">12:23</a>
<a class='1253' href="departuretime/1253">12:53</a>
<a class='1323' href="departuretime/1323">13:23</a>
</code></pre>
<p>Any help with this would be appreciated.</p>
| [
{
"answer_id": 308128,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>If you just want to do this for styling reasons it's not necessary to add a class, you can style based ... | 2018/07/10 | [
"https://wordpress.stackexchange.com/questions/308126",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146666/"
] | I am wondering whether it is possible to automatically add a class to a series of links based on the link text.
The scenario is as follows:
I am displaying a list of links on a page in Wordpress that link to other posts - in this case a custom post type for a schedule. The posts all have time based names, i.e. '12:23' '12:53' '13:23' and so on.
This generates a list of links like this:
```
<a href="departuretime/1223">12:23</a>
<a href="departuretime/1253">12:53</a>
<a href="departuretime/1323">13:23</a>
```
Where each link links to a full custom post associated to display that schedule.
I would like to format these links based on the current time and to do this I need the class to be automatically generated based on the link text.
```
<a class='1223' href="departuretime/1223">12:23</a>
<a class='1253' href="departuretime/1253">12:53</a>
<a class='1323' href="departuretime/1323">13:23</a>
```
Any help with this would be appreciated. | If I understand it correctly you want a visual indicator for departures relevant on the current time.
One solution will be using Javascript and provide a way for the element to be identified as passed or active schedule time.
**HTML**
```
<div id="myElement">
<a href="https://myawesomenewsite.com/departuretime/1253">1253</a>
<a href="https://myawesomenewsite.com/departuretime/1255">1255</a>
<a href="https://myawesomenewsite.com/departuretime/0955">0955</a>
<a href="https://myawesomenewsite.com/departuretime/2213">2213</a>
</div>
```
**JAVASCRIPT**
```
// find elements
var rootElements = $("#myElement a");
rootElements.each(function(index, item){
var url = item.href,
arr_split = url.split("/"),
arr_index = arr_split.length-1,
departureTime = arr_split[arr_index],
date = new Date(),
myTime = date.getHours()+''+date.getMinutes();
//add your class like this
item.classList.add(myTime);
//but you can also spice it up a bit
if(departureTime>myTime){
item.classList.add("you_have_time");
}else{
item.classList.add("you_dont_have_time");
}
});
```
**CSS**
```
.you_have_time{
color:green;
}
.you_dont_have_time{
color:red;
}
```
And ofcourse the [jsfiddle](https://jsfiddle.net/pq4Lxug6/1/) |
308,150 | <p>I want to create an Autocomplete function in WordPress. I want a search field from where <strong>username</strong> can be searched. I am using following JQuery UI. </p>
<pre><code><label>Users</label>
<input type="text" name="user_name" id="user-name" />
<?php
$get_arr_user = array('John', 'Rogers', 'Paul', 'Amanda', 'Peter');
?>
<script>
jQuery(document).ready(function($) {
var availableTags = <?php echo json_encode($get_arr_user); ?>;
$( "#user-name" ).autocomplete({
source: availableTags
});
});
</script>
</code></pre>
<p>My problem is that I am not able to get the list of <strong>Usernames</strong> in this format - <code>array('John', 'Rogers', 'Paul', 'Amanda', 'Peter');</code> How do I get that?</p>
| [
{
"answer_id": 308153,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow noreferrer\"><code>get_u... | 2018/07/10 | [
"https://wordpress.stackexchange.com/questions/308150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124069/"
] | I want to create an Autocomplete function in WordPress. I want a search field from where **username** can be searched. I am using following JQuery UI.
```
<label>Users</label>
<input type="text" name="user_name" id="user-name" />
<?php
$get_arr_user = array('John', 'Rogers', 'Paul', 'Amanda', 'Peter');
?>
<script>
jQuery(document).ready(function($) {
var availableTags = <?php echo json_encode($get_arr_user); ?>;
$( "#user-name" ).autocomplete({
source: availableTags
});
});
</script>
```
My problem is that I am not able to get the list of **Usernames** in this format - `array('John', 'Rogers', 'Paul', 'Amanda', 'Peter');` How do I get that? | The other answers are correct, but it's possible to achive the same thing with less code using [`wp_list_pluck()`](https://codex.wordpress.org/Function_Reference/wp_list_pluck):
```
$users = get_users();
$user_names = wp_list_pluck( $users, 'display_name' );
```
`wp_list_pluck()` used that way will get the `display_name` field of all the users in an array without needing to do a loop. |
308,162 | <p>I am using bootstrap to layout a simple webpage. I have also add some css (<code>@media (min-width: 1920px) {..}</code>) media queries which I use for different resolutions</p>
<p>Now I hope WP has a hook which checks the media resolution so I can trim with more characters/words.</p>
<pre><code><?php echo wp_trim_words(get_the_content(), 40, '...'); ?>
</code></pre>
<p>vs</p>
<pre><code> <?php echo wp_trim_words(get_the_content(), 70, '...'); ?>
</code></pre>
<p>In short, how can I output different text length based on browser resolutions?</p>
| [
{
"answer_id": 308165,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 0,
"selected": false,
"text": "<p>One way to find out if a specific function has hooks is to look it up on the <a href=\"https://developer.wo... | 2018/07/10 | [
"https://wordpress.stackexchange.com/questions/308162",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9936/"
] | I am using bootstrap to layout a simple webpage. I have also add some css (`@media (min-width: 1920px) {..}`) media queries which I use for different resolutions
Now I hope WP has a hook which checks the media resolution so I can trim with more characters/words.
```
<?php echo wp_trim_words(get_the_content(), 40, '...'); ?>
```
vs
```
<?php echo wp_trim_words(get_the_content(), 70, '...'); ?>
```
In short, how can I output different text length based on browser resolutions? | Browser resolution is set on the user end. Actually, the window may even be resized after the page has been loaded. Css media queries will deal with that on the user end.
So, when the page is generated on the server side, the user window size is unknown and you cannot determine how many words to serve at that point. It has to be done on the user end.
The easiest approach would be to include the longest excerpt and wrap the last 30 words in `<span>` tags, which you hide using css on smaller screens.
A more complicated approach would be to detect screen size using jquery and then call the [rest api](https://developer.wordpress.org/rest-api/) to retrieve the relevant excerpt. |
308,164 | <p>How to remove elementor from wordpress admin menu. I have tried below option but it didnt work.</p>
<pre><code>add_action( 'admin_menu', 'my_remove_menu_pages' );
function my_remove_menu_pages() {
remove_menu_page( 'edit.php?post_type=elementor_library' );
//Elementor
};
</code></pre>
| [
{
"answer_id": 308176,
"author": "Amit Jugran",
"author_id": 135161,
"author_profile": "https://wordpress.stackexchange.com/users/135161",
"pm_score": 0,
"selected": false,
"text": "<p>I have been able to do it using <code>'admin_init'</code> action. The correct code is below</p>\n\n<pre... | 2018/07/10 | [
"https://wordpress.stackexchange.com/questions/308164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135161/"
] | How to remove elementor from wordpress admin menu. I have tried below option but it didnt work.
```
add_action( 'admin_menu', 'my_remove_menu_pages' );
function my_remove_menu_pages() {
remove_menu_page( 'edit.php?post_type=elementor_library' );
//Elementor
};
``` | This would work for editors. You can swap the role in and out depending on which role you are trying to target (e.g., `editor`, `subscriber`, etc.). This would go in `functions.php` of your child theme.
```
function remove_menus(){
// get current login user's role
$roles = wp_get_current_user()->roles;
// test role
if( !in_array('editor',$roles)){
return;
}
//remove menu from site backend.
remove_menu_page( 'edit.php?post_type=elementor_library' ); // Elementor Templates
remove_menu_page( 'elementor' ); // Elementor
}
add_action( 'admin_menu', 'remove_menus' , 100 );
``` |
308,236 | <p>Is there any way to change the order of filters for e.g. the_content before they are applied? What I currently have is the following ideas:</p>
<pre><code>/**
* Print all filters for some hook.
*/
function print_filters_for( $hook = '' ) {
global $wp_filter;
if( empty( $hook ) || !isset( $wp_filter[$hook] ) )
return;
print '<pre>';
print_r( $wp_filter[$hook] );
print '</pre>';
}
add_action('template_redirect','print_filters');
function print_filters() {
print_r(print_filters_for('the_content'));die;
}
</code></pre>
<p>This gives me the filters, but I can not think of any comfortable way to change their priorities.</p>
<pre><code>add_filter( 'the_content', 'my_content_filter_priority_reorder', 0 );
function my_content_filter_priority_reorder($the_content) {
// reorder filter priorities
return $the_content;
}
</code></pre>
<p>Has anybody already had this problem and knows how to possibly change this?</p>
| [
{
"answer_id": 308242,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>If you know the existing callback and priority you can just remove the filters and then add again at a d... | 2018/07/11 | [
"https://wordpress.stackexchange.com/questions/308236",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12035/"
] | Is there any way to change the order of filters for e.g. the\_content before they are applied? What I currently have is the following ideas:
```
/**
* Print all filters for some hook.
*/
function print_filters_for( $hook = '' ) {
global $wp_filter;
if( empty( $hook ) || !isset( $wp_filter[$hook] ) )
return;
print '<pre>';
print_r( $wp_filter[$hook] );
print '</pre>';
}
add_action('template_redirect','print_filters');
function print_filters() {
print_r(print_filters_for('the_content'));die;
}
```
This gives me the filters, but I can not think of any comfortable way to change their priorities.
```
add_filter( 'the_content', 'my_content_filter_priority_reorder', 0 );
function my_content_filter_priority_reorder($the_content) {
// reorder filter priorities
return $the_content;
}
```
Has anybody already had this problem and knows how to possibly change this? | If you know the existing callback and priority you can just remove the filters and then add again at a different priority:
```
remove_filter( 'the_content', 'convert_smilies', 20 );
add_filter( 'the_content', 'convert_smilies', 30 );
remove_filter( 'the_content', 'capital_P_dangit', 11 );
add_filter( 'the_content', 'capital_P_dangit', 20 );
``` |
308,271 | <p>There is a site with WordPress installed and a theme selected. I have created an HTML page for the site, but it wasn't looking well with the theme. So, I want to put the page on the site without any theme, and just the way I wrote the code, without disabling the theme from any other pages.</p>
<p>Is there an easy way to do it without messing with the theme? And if there isn't, then I am willing to modify theme files, but how should I go about it? </p>
| [
{
"answer_id": 308272,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 4,
"selected": true,
"text": "<p>There is, in fact, a way to do it without messing with the theme, let's say your WordPress is on <code>pub... | 2018/07/11 | [
"https://wordpress.stackexchange.com/questions/308271",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146759/"
] | There is a site with WordPress installed and a theme selected. I have created an HTML page for the site, but it wasn't looking well with the theme. So, I want to put the page on the site without any theme, and just the way I wrote the code, without disabling the theme from any other pages.
Is there an easy way to do it without messing with the theme? And if there isn't, then I am willing to modify theme files, but how should I go about it? | There is, in fact, a way to do it without messing with the theme, let's say your WordPress is on `public_html/your_site`, now you want to create an HTML page that is on `your_site.com/mypage`, so instead of creating a page or post called `mypage` on your WordPress dashboard you are going to create a **mypage.html** and upload it to `public_html/your_site`, in case you want to get rid of the .html you can simply hide it from your **.htaccess** doing something like:
```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]
```
Keep in mind any tracking code you have on your WordPress, for example, Google Analytics, if you are using things like that you will have to add those codes to your HTML page as well. |
308,291 | <p>I discovered after much painful debugging that requests to the the WP HTTP API (in this case, though <code>wp_remote_request()</code>) always ended up as <code>GET</code> method after being redirected, even if the method was something else in the initial request (in my case <code>PURGE</code> as used by the <a href="https://wordpress.org/plugins/varnish-http-purge/" rel="nofollow noreferrer">Varnish HTTP Purge plugin</a>)</p>
<p>Normally this would apply to <code>POST</code> requests, where redirecting to a <code>GET</code> request of the same URL means completely obliterating the data being sent with the <code>POST</code>. In my case, using <code>PURGE</code> the outcome was that Apache was loading the actual URLs I was trying to purge, which wasn't what I wanted. </p>
<p>The point being: Pretty much never will you want this to happen. Whatever method you use to send a request, you surely want that method to be used in the end. This behavior is confusing and annoying and will probably be experienced as inexplicable bugginess for most users (in my case, the bug took me years to track down, and had been slowing down my local dev site where I don't have Varnish installed). </p>
<p>I'm posting this question so I can answer it myself in hopes people find it using Google in the future. The point is to be <strong>aware</strong> of this behavior so that if it is happening to you you can just find a way around it. </p>
| [
{
"answer_id": 308292,
"author": "jerclarke",
"author_id": 175,
"author_profile": "https://wordpress.stackexchange.com/users/175",
"pm_score": 1,
"selected": true,
"text": "<p>It turns out that as part of <code>class-request->parse_response()</code>, where redirections are handled for... | 2018/07/11 | [
"https://wordpress.stackexchange.com/questions/308291",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/175/"
] | I discovered after much painful debugging that requests to the the WP HTTP API (in this case, though `wp_remote_request()`) always ended up as `GET` method after being redirected, even if the method was something else in the initial request (in my case `PURGE` as used by the [Varnish HTTP Purge plugin](https://wordpress.org/plugins/varnish-http-purge/))
Normally this would apply to `POST` requests, where redirecting to a `GET` request of the same URL means completely obliterating the data being sent with the `POST`. In my case, using `PURGE` the outcome was that Apache was loading the actual URLs I was trying to purge, which wasn't what I wanted.
The point being: Pretty much never will you want this to happen. Whatever method you use to send a request, you surely want that method to be used in the end. This behavior is confusing and annoying and will probably be experienced as inexplicable bugginess for most users (in my case, the bug took me years to track down, and had been slowing down my local dev site where I don't have Varnish installed).
I'm posting this question so I can answer it myself in hopes people find it using Google in the future. The point is to be **aware** of this behavior so that if it is happening to you you can just find a way around it. | It turns out that as part of `class-request->parse_response()`, where redirections are handled for the various higher-level request functions (this is where it does the recursive requests for each subsequent hop) there's a weird hook thing that ends up running `WP_Http->browser_redirect_compatibility()` on the redirected request.
`browser_redirect_compatibility()` is pretty simple:
```
public static function browser_redirect_compatibility( $location, $headers, $data, &$options, $original ) {
// Browser compat
if ( $original->status_code === 302 ) {
$options['type'] = Requests::GET;
}
}
```
Basically, it just obliterates the method you chose as soon as theres a 302 redirection, replacing it with `GET`. They seem to assume they are converting a `POST` request, but as is clear from reading it, this will apply to ANY method other than `GET` which ends up being a 302.
Notably though, this **DOESN'T** have any effect on 301 redirects, and seems to be related to an underlying crappiness of 302 as an error. You can read more about 302 and it's problems in [this previous question about a similar problem with `POST` requests getting converted to GET and losing their data](
[Temporary redirect prevents getting $\_POST array](https://wordpress.stackexchange.com/questions/87515/temporary-redirect-prevents-getting-post-array/87528#87528))
Affects Apache but not Nginx?
-----------------------------
This seems relevant: My local dev environment uses MAMP and the sites is hosted through Apache, and this insane problem is triggered.
Our live site uses a Nginx->Varnish->Nginx setup, where for whatever reason, the same redirects were never `302` at all, but instead were `301` and thus worked correctly (they stayed as `PURGE` at the redirected location, which was the `https` version of the URL, rather than the `http` version).
So my recommendtaions to anyone having this problem:
----------------------------------------------------
* Switch to Nginx completely as it seems to not use 302 for such redirects. Apache sux.
* Look for sources of 302 errors and reconfigure your server to use 301 instead
* Look for ways to avoid triggering redirects in the first place! (in our case, making sure the URLs were already `https` to start is an obvious improvement and will make our logs cleaner) |
308,301 | <p>I am creating a plugin that generates a theme, and so I want to have a checkbox at the end of the theme generation process that gives the possibility to activate the freshly created theme without having to do it manually.
Is there any function that can do that?</p>
| [
{
"answer_id": 308302,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 1,
"selected": false,
"text": "<p>The only thing that comes to my mind is to do it from the database, so basically after you check the chec... | 2018/07/11 | [
"https://wordpress.stackexchange.com/questions/308301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146776/"
] | I am creating a plugin that generates a theme, and so I want to have a checkbox at the end of the theme generation process that gives the possibility to activate the freshly created theme without having to do it manually.
Is there any function that can do that? | Of course there’s a function for that ([Codex](https://codex.wordpress.org/Function_Reference/switch_theme)):
```
switch_theme( $stylesheet )
```
It:
>
> Switches current theme to new template and stylesheet names. Accepts
> one argument: $stylesheet of the theme. ($stylesheet is the name of
> your folder slug. It's the same value that you'd use for a child
> theme, something like `twentythirteen`.) It also accepts an additional
> function signature of two arguments: $template then $stylesheet. This
> is for backwards compatibility.
>
>
>
And why is that any better? WordPress uses filters and actions for many things. For example, when you switch the theme, the unused widgets will get saved, so you can restore them in new sidebars... All of that won’t be done, if you switch the theme directly in DB. |
308,361 | <p>I have a running site (Site A).</p>
<p>I want to re-write the site fully to improve everything but, when I'm finished, I don't want to have to get everyone to sign up to the new site.</p>
<p>I wondered if I could create an entirely new site on a different domain (Site B) with a clean install of Wordpress - and then when I'm finished developing the site copy over the following tables from Site A to Site B:
wp_options
wp_users
wp_usermeta</p>
<p>And would all my existing users then have full access to Site B (the new site) ?</p>
<p>Or is there more to it than this?</p>
<p>Thanks</p>
| [
{
"answer_id": 308302,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 1,
"selected": false,
"text": "<p>The only thing that comes to my mind is to do it from the database, so basically after you check the chec... | 2018/07/12 | [
"https://wordpress.stackexchange.com/questions/308361",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39292/"
] | I have a running site (Site A).
I want to re-write the site fully to improve everything but, when I'm finished, I don't want to have to get everyone to sign up to the new site.
I wondered if I could create an entirely new site on a different domain (Site B) with a clean install of Wordpress - and then when I'm finished developing the site copy over the following tables from Site A to Site B:
wp\_options
wp\_users
wp\_usermeta
And would all my existing users then have full access to Site B (the new site) ?
Or is there more to it than this?
Thanks | Of course there’s a function for that ([Codex](https://codex.wordpress.org/Function_Reference/switch_theme)):
```
switch_theme( $stylesheet )
```
It:
>
> Switches current theme to new template and stylesheet names. Accepts
> one argument: $stylesheet of the theme. ($stylesheet is the name of
> your folder slug. It's the same value that you'd use for a child
> theme, something like `twentythirteen`.) It also accepts an additional
> function signature of two arguments: $template then $stylesheet. This
> is for backwards compatibility.
>
>
>
And why is that any better? WordPress uses filters and actions for many things. For example, when you switch the theme, the unused widgets will get saved, so you can restore them in new sidebars... All of that won’t be done, if you switch the theme directly in DB. |
308,433 | <p>I am creating a comparison table and the issue is in while loop i am not able to put the <code>"tr"</code> in proper place. I need layout like this</p>
<pre><code><table>
<tr>
<td>post title 1</td>
<td>post title 2</td>
<td>post title 3</td>
</tr>
<tr>
<td>post content 1</td>
<td>post content 2</td>
<td>post content 3</td>
</tr>
<tr>
<td>post author 1</td>
<td>post author 2</td>
<td>post author 3</td>
</tr>
</table>
</code></pre>
<p>How can i achieve that it's seems like no option see my code below</p>
<pre><code><div class="acadp">
<table>
<tr>
<?php while( $acadp_query->have_posts() ) : $acadp_query->the_post(); ?>
<td><?php the_title(); ?></td>
<td><?php the_content(); ?></td>
<td><?php the_author(); ?></td>
<?php endwhile; ?>
<tr>
</table>
</div>
<?php wp_reset_postdata(); ?>
</code></pre>
| [
{
"answer_id": 308434,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>You need 3 separate loops. One for each row, with each post creating a new column:</p>\n\n<pre><code>&l... | 2018/07/13 | [
"https://wordpress.stackexchange.com/questions/308433",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128610/"
] | I am creating a comparison table and the issue is in while loop i am not able to put the `"tr"` in proper place. I need layout like this
```
<table>
<tr>
<td>post title 1</td>
<td>post title 2</td>
<td>post title 3</td>
</tr>
<tr>
<td>post content 1</td>
<td>post content 2</td>
<td>post content 3</td>
</tr>
<tr>
<td>post author 1</td>
<td>post author 2</td>
<td>post author 3</td>
</tr>
</table>
```
How can i achieve that it's seems like no option see my code below
```
<div class="acadp">
<table>
<tr>
<?php while( $acadp_query->have_posts() ) : $acadp_query->the_post(); ?>
<td><?php the_title(); ?></td>
<td><?php the_content(); ?></td>
<td><?php the_author(); ?></td>
<?php endwhile; ?>
<tr>
</table>
</div>
<?php wp_reset_postdata(); ?>
``` | ```
<div class="acadp">
<?php
$compare =[];
while( $acadp_query->have_posts() ) {
$acadp_query->the_post(); $post_meta = get_post_meta( $post->ID );
$category = wp_get_object_terms( $post->ID, 'acadp_categories' );
$compare['Title'][] = get_the_title();
$compare['Manufacturer'][] = $category[0]->name;
$compare['Image'][] = get_the_acadp_listing_thumbnail($post_meta);
if( count( $fields ) ){
foreach( $fields as $field ) {
$value = $post_meta[ $field->ID ][0];
$compare[$field->post_title][] = $value;
}
}
$compare['URL'][] = "<a href='".get_the_permalink()."' class='btn btn-primary'>View Details</a>";
}
?>
<table class="table table-bordered">
<?php foreach ($compare as $feature => $value): ?>
<tr>
<th><?php echo $feature; ?></th>
<td><?php echo implode("</td><td>",$value); ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<!-- end of the loop -->
<!-- Use reset postdata to restore orginal query -->
<?php wp_reset_postdata(); ?>
``` |
308,439 | <p>My version variable doesn't seem to be being applied within my enqueue functions (snippet below).</p>
<pre><code>//version number
$version = '1.0.0';
function frontend_styles($version) {
wp_enqueue_style(
'frontend_styles', //reference
get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source
array(), //dependenices
$version, //version number
'all' //media type ('all', 'screen', 'handheld', 'print')
);
}
</code></pre>
<p>Is there a way of setting a global version number that could be applied to all styles?</p>
<p>EDIT:
Below is the actual source code.</p>
<pre><code>//version number
$version = '1.0.0';
//remove jquery scripts
function remove_jquery() {
wp_deregister_script('jquery');
wp_deregister_script('jquery-core');
wp_deregister_script('jquery-migrate');
}
//remove embed scripts
function remove_embed() {
wp_deregister_script('wp-embed');
}
//site styles
function frontend_styles() {
global $version;
wp_enqueue_style(
'frontend_styles', //reference
get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source
array(), //dependenices
$version, //version number
'all' //media type ('all', 'screen', 'handheld', 'print')
);
}
//admin_styles
function backend_styles() {
global $version;
wp_enqueue_style(
'backend_styles', //reference
get_stylesheet_directory_uri() . '/assets/css/admin.min.css', //source
array(), //dependenices
$version, //version number
'all' //media type ('all', 'screen', 'handheld', 'print')
);
}
//site scripts
function frontend_scripts() {
global $version;
wp_enqueue_script(
'frontend_scripts', //reference
get_stylesheet_directory_uri() . '/assets/js/app.min.js', //source
array(), //dependencies
$version, //version number
true //load in footer
);
//pass sylsheet uri to javascript variable in app.js
$translation_array = array(
'get_stylesheet_directory_uri' => get_stylesheet_directory_uri() . '/',
'home_url' => home_url('/')
);
wp_localize_script('frontend_scripts', 'php', $translation_array);
}
//admin scripts
function backend_scripts() {
global $version;
wp_enqueue_script(
'backend_scripts', //reference
get_stylesheet_directory_uri() . '/assets/js/admin.min.js', //source
array(), //dependencies
$version, //version number
true //load in footer
);
}
</code></pre>
| [
{
"answer_id": 308440,
"author": "Florian",
"author_id": 52583,
"author_profile": "https://wordpress.stackexchange.com/users/52583",
"pm_score": 1,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>// global theme version\n$version = '1.0.0';\n\nfunction frontend_styles() {\n\n ... | 2018/07/13 | [
"https://wordpress.stackexchange.com/questions/308439",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/141411/"
] | My version variable doesn't seem to be being applied within my enqueue functions (snippet below).
```
//version number
$version = '1.0.0';
function frontend_styles($version) {
wp_enqueue_style(
'frontend_styles', //reference
get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source
array(), //dependenices
$version, //version number
'all' //media type ('all', 'screen', 'handheld', 'print')
);
}
```
Is there a way of setting a global version number that could be applied to all styles?
EDIT:
Below is the actual source code.
```
//version number
$version = '1.0.0';
//remove jquery scripts
function remove_jquery() {
wp_deregister_script('jquery');
wp_deregister_script('jquery-core');
wp_deregister_script('jquery-migrate');
}
//remove embed scripts
function remove_embed() {
wp_deregister_script('wp-embed');
}
//site styles
function frontend_styles() {
global $version;
wp_enqueue_style(
'frontend_styles', //reference
get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source
array(), //dependenices
$version, //version number
'all' //media type ('all', 'screen', 'handheld', 'print')
);
}
//admin_styles
function backend_styles() {
global $version;
wp_enqueue_style(
'backend_styles', //reference
get_stylesheet_directory_uri() . '/assets/css/admin.min.css', //source
array(), //dependenices
$version, //version number
'all' //media type ('all', 'screen', 'handheld', 'print')
);
}
//site scripts
function frontend_scripts() {
global $version;
wp_enqueue_script(
'frontend_scripts', //reference
get_stylesheet_directory_uri() . '/assets/js/app.min.js', //source
array(), //dependencies
$version, //version number
true //load in footer
);
//pass sylsheet uri to javascript variable in app.js
$translation_array = array(
'get_stylesheet_directory_uri' => get_stylesheet_directory_uri() . '/',
'home_url' => home_url('/')
);
wp_localize_script('frontend_scripts', 'php', $translation_array);
}
//admin scripts
function backend_scripts() {
global $version;
wp_enqueue_script(
'backend_scripts', //reference
get_stylesheet_directory_uri() . '/assets/js/admin.min.js', //source
array(), //dependencies
$version, //version number
true //load in footer
);
}
``` | Try this
```
// global theme version
$version = '1.0.0';
function frontend_styles() {
global $version;
wp_enqueue_style(
'frontend_styles', //reference
get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source
array(), //dependenices
$version, //version number
'all' //media type ('all', 'screen', 'handheld', 'print')
);
}
``` |
308,444 | <p>I have been searching for theme developing info but all that are related to this subject are talking about a custom page at <code>page.php</code>.</p>
<p>What I am trying to achieve is different. The scenario is that I have to create a page where the content is hard-coded, so I can have more creative freedom on the design. That is to say, I don't want to have it generated through adding pages from the CMS, since there are more restrictions to it.</p>
<p>Can I create a new static <code>.php</code> (a <code>page.php</code> with specific content), and linked to it from menu nav bar? It is similar to making a static home page, but not a "home" page.</p>
| [
{
"answer_id": 308440,
"author": "Florian",
"author_id": 52583,
"author_profile": "https://wordpress.stackexchange.com/users/52583",
"pm_score": 1,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>// global theme version\n$version = '1.0.0';\n\nfunction frontend_styles() {\n\n ... | 2018/07/13 | [
"https://wordpress.stackexchange.com/questions/308444",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146878/"
] | I have been searching for theme developing info but all that are related to this subject are talking about a custom page at `page.php`.
What I am trying to achieve is different. The scenario is that I have to create a page where the content is hard-coded, so I can have more creative freedom on the design. That is to say, I don't want to have it generated through adding pages from the CMS, since there are more restrictions to it.
Can I create a new static `.php` (a `page.php` with specific content), and linked to it from menu nav bar? It is similar to making a static home page, but not a "home" page. | Try this
```
// global theme version
$version = '1.0.0';
function frontend_styles() {
global $version;
wp_enqueue_style(
'frontend_styles', //reference
get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source
array(), //dependenices
$version, //version number
'all' //media type ('all', 'screen', 'handheld', 'print')
);
}
``` |
308,457 | <p>I am currently using Wordpress and I have a problem. I'm trying to develop a code that shows an image or another image based on the value of the custom field</p>
<p>In each product, for example, I have a variable called store_1 or store_2 apart from the main stock of the product.</p>
<p>What I want to do is a custom function for wordpress in the custom fields of the product in which it shows one image or another depending on the total amount of the value that custom field has. In the following code that I provide, it is for the wordpress stock itself, where it shows 3 images depending on the amount that there is.</p>
<p>For example, if there are more than five, it shows an image in green, if there are less than five, it shows an image in orange and if there is 0 or less than zero it shows an image in red.</p>
<p>This same code, I would like to customize it in each of those variables that I will embed in the product.</p>
<pre><code>add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2);
</code></pre>
<p>function wcs_custom_get_availability( $availability, $_product ) {
global $product;</p>
<pre><code>// Stock greater than 5 or enough stock
if ( $_product->is_in_stock() ) {
$availability['availability'] = __('<img src="https://myweb.com/images/fullstock.png">','woocommerce');
}
// Low stock < 5
if ( $_product->is_in_stock() && $product->get_stock_quantity() <= 5 ) {
$availability['availability'] = sprintf( __('<img src="https://myweb.com/images/lowstock.png">', 'woocommerce'), $product->get_stock_quantity());
}
// No stock
if ( ! $_product->is_in_stock() ) {
$availability['availability'] = __('<img src="https://myweb.com/images/notock.png">', 'woocommerce');
}
return $availability;
</code></pre>
<p>}</p>
<p>And this is my problem, I do not know what code should be developed in the functions file of my wordpress but customized for that variable.</p>
<p>Thank you I await your response</p>
| [
{
"answer_id": 308440,
"author": "Florian",
"author_id": 52583,
"author_profile": "https://wordpress.stackexchange.com/users/52583",
"pm_score": 1,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>// global theme version\n$version = '1.0.0';\n\nfunction frontend_styles() {\n\n ... | 2018/07/13 | [
"https://wordpress.stackexchange.com/questions/308457",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146891/"
] | I am currently using Wordpress and I have a problem. I'm trying to develop a code that shows an image or another image based on the value of the custom field
In each product, for example, I have a variable called store\_1 or store\_2 apart from the main stock of the product.
What I want to do is a custom function for wordpress in the custom fields of the product in which it shows one image or another depending on the total amount of the value that custom field has. In the following code that I provide, it is for the wordpress stock itself, where it shows 3 images depending on the amount that there is.
For example, if there are more than five, it shows an image in green, if there are less than five, it shows an image in orange and if there is 0 or less than zero it shows an image in red.
This same code, I would like to customize it in each of those variables that I will embed in the product.
```
add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2);
```
function wcs\_custom\_get\_availability( $availability, $\_product ) {
global $product;
```
// Stock greater than 5 or enough stock
if ( $_product->is_in_stock() ) {
$availability['availability'] = __('<img src="https://myweb.com/images/fullstock.png">','woocommerce');
}
// Low stock < 5
if ( $_product->is_in_stock() && $product->get_stock_quantity() <= 5 ) {
$availability['availability'] = sprintf( __('<img src="https://myweb.com/images/lowstock.png">', 'woocommerce'), $product->get_stock_quantity());
}
// No stock
if ( ! $_product->is_in_stock() ) {
$availability['availability'] = __('<img src="https://myweb.com/images/notock.png">', 'woocommerce');
}
return $availability;
```
}
And this is my problem, I do not know what code should be developed in the functions file of my wordpress but customized for that variable.
Thank you I await your response | Try this
```
// global theme version
$version = '1.0.0';
function frontend_styles() {
global $version;
wp_enqueue_style(
'frontend_styles', //reference
get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source
array(), //dependenices
$version, //version number
'all' //media type ('all', 'screen', 'handheld', 'print')
);
}
``` |
308,466 | <p>I'm seeing a weird problem where if someone searches "Test Search" it's returning fine, but if someone searches "Test Search " it's returning some weird posts that don't seem relevant.</p>
<p>How do I go about trimming white space from beginning and end of a search term?</p>
| [
{
"answer_id": 308474,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>In WordPress search terms are <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter\" ... | 2018/07/13 | [
"https://wordpress.stackexchange.com/questions/308466",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75134/"
] | I'm seeing a weird problem where if someone searches "Test Search" it's returning fine, but if someone searches "Test Search " it's returning some weird posts that don't seem relevant.
How do I go about trimming white space from beginning and end of a search term? | I came across the same problem.
In my opinion, this should be the default search behavior in WP.
The solution is to filter the array of parsed query variables.
See the documentation [here](https://developer.wordpress.org/reference/hooks/request/).
Add this to the `functions.php` file in your theme directory.
```
add_filter('request', function ($query_vars) {
if (!is_admin() && !empty($query_vars['s'])) {
$query_vars['s'] = trim($query_vars['s']);
}
return $query_vars;
});
``` |
308,470 | <p>I'm fairly new to wordpress and the content management system. I've been following a couple of tutorials to get started. I've been searching for specifically how to include a date picker in the add new custom post type. </p>
<p><a href="https://i.stack.imgur.com/sCISj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sCISj.png" alt="My Events Custom Post Type"></a></p>
<p>I want to add an extra field in here for the user to select a date to specify when the event will take place. I don't want the user to manually type out the date through text but want to use a date picker, whether it be a normal html5 datepicker or a jquery one.</p>
<p>The code i used to generate this is within the functions.php, I understand that this is probably not the best place to put all my code but i'm currently just experimenting for now but can't seem to find a solution to my problem.</p>
<pre><code> /*
Custom post types
*/
function awesome_custom_post_type ()
{
$labels = array(
'name' => 'Events',
'singular_name' => 'Event',
'add_new' => 'Add Event',
'all_items' => 'All Events',
'add_new_item' => 'Add Event',
'edit_item' => 'Edit Event',
'new_item' => 'New Event',
'view_item' => 'View Event',
'search_item_label' => 'Search Events',
'not_found' => 'No Events Found',
'not_found_in_trash' => 'No Events Found in Trash',
'parent_item_colon' => 'Parent Event'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'publicly_queryable' => false,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => true,
'supports' => array(
'title',
'editor',
'thumbnail',
),
'menu_icon' => 'dashicons-calendar-alt',
'menu_position' => 5,
'excluse_from_search' => true
);
register_post_type( 'awesome_events', $args );
}
add_action( 'init', 'awesome_custom_post_type' );
</code></pre>
<p>Thanks in advance.</p>
| [
{
"answer_id": 308475,
"author": "sunil",
"author_id": 56910,
"author_profile": "https://wordpress.stackexchange.com/users/56910",
"pm_score": 1,
"selected": false,
"text": "<p>@vemuez</p>\n\n<p>you need to enqueue js and css files to admin_print_script and admin_print_style</p>\n\n<p>he... | 2018/07/13 | [
"https://wordpress.stackexchange.com/questions/308470",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146895/"
] | I'm fairly new to wordpress and the content management system. I've been following a couple of tutorials to get started. I've been searching for specifically how to include a date picker in the add new custom post type.
[](https://i.stack.imgur.com/sCISj.png)
I want to add an extra field in here for the user to select a date to specify when the event will take place. I don't want the user to manually type out the date through text but want to use a date picker, whether it be a normal html5 datepicker or a jquery one.
The code i used to generate this is within the functions.php, I understand that this is probably not the best place to put all my code but i'm currently just experimenting for now but can't seem to find a solution to my problem.
```
/*
Custom post types
*/
function awesome_custom_post_type ()
{
$labels = array(
'name' => 'Events',
'singular_name' => 'Event',
'add_new' => 'Add Event',
'all_items' => 'All Events',
'add_new_item' => 'Add Event',
'edit_item' => 'Edit Event',
'new_item' => 'New Event',
'view_item' => 'View Event',
'search_item_label' => 'Search Events',
'not_found' => 'No Events Found',
'not_found_in_trash' => 'No Events Found in Trash',
'parent_item_colon' => 'Parent Event'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'publicly_queryable' => false,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => true,
'supports' => array(
'title',
'editor',
'thumbnail',
),
'menu_icon' => 'dashicons-calendar-alt',
'menu_position' => 5,
'excluse_from_search' => true
);
register_post_type( 'awesome_events', $args );
}
add_action( 'init', 'awesome_custom_post_type' );
```
Thanks in advance. | With the help of sunil's answer I figured out exactly what I needed to do.
I went and downloaded the free version of Metabox at <https://wordpress.org/plugins/meta-box/>
Once I downloaded it, I've placed it in `child-theme/external/meta-box`and referenced it from `child-theme/inc/events-custom-post-type.php`.
`events-custom-post-type.php` looks like this.
```
require_once(get_stylesheet_directory() . '/external/meta-box/meta-box.php');
function custom_events ()
{
$labels = array(
'name' => 'Events',
'singular_name' => 'Event',
'add_new' => 'Add Event',
'all_items' => 'All Events',
'add_new_item' => 'Add Event',
'edit_item' => 'Edit Event',
'new_item' => 'New Event',
'view_item' => 'View Event',
'search_item_label' => 'Search Events',
'not_found' => 'No Events Found',
'not_found_in_trash' => 'No Events Found in Trash',
'parent_item_colon' => 'Parent Event'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'publicly_queryable' => false,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => true,
'supports' => array(
'title',
'editor',
),
'menu_icon' => 'dashicons-calendar-alt',
'menu_position' => 5,
'exclude_from_search' => true
);
register_post_type( 'custom_events_post_type', $args );
}
function prefix_register_meta_boxes_events( $meta_boxes ) {
$prefix = 'custom_event_';
$meta_boxes[] = array(
'id' => $prefix . 'details',
'title' => 'Event details',
'post_types' => 'custom_events_post_type',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => 'Event date',
'desc' => 'Select event date',
'id' => $prefix . 'date',
'type' => 'date',
),
array (
'name' => 'Event location',
'desc' => 'Location of the event',
'id' => $prefix . 'location',
'type' => 'text'
)
)
);
return $meta_boxes;
}
add_action( 'init', 'custom_events' );
add_filter( 'rwmb_meta_boxes', 'prefix_register_meta_boxes_events' );
```
The `custom_events` function sets up the custom post type while the `prefix_register_meta_boxes_events` function sets up the custom field date picker.
You just have to make sure that in `prefix_register_meta_boxes_events` function, where it says `post_types` to add what your own custom post type is registered as.
After that, I just referenced this file in `child-theme/functions.php` like so.
```
require get_stylesheet_directory() . '/inc/events-custom-post-type.php';
``` |
308,497 | <p>How can I copy the default styling for the admin and tell wordpress to use custom style instead of the default? Basically I want to change the colour and font without having to use !important syntax to force Wordpress to use it. </p>
| [
{
"answer_id": 308567,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": 1,
"selected": false,
"text": "<p>Enqueue custom admin CSS file (custom-admin.css) in your WordPress backend using below function:</p>\... | 2018/07/13 | [
"https://wordpress.stackexchange.com/questions/308497",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146914/"
] | How can I copy the default styling for the admin and tell wordpress to use custom style instead of the default? Basically I want to change the colour and font without having to use !important syntax to force Wordpress to use it. | As noted by @Fusion, this has changed beginning with version 5. In order to override admin styles for 5.\*, you need a hook in `functions.php`, something like this:
```php
function custom_admin() {
$url = get_settings('siteurl');
$url = $url . '/wp-content/themes/my-theme/wp-admin.css';
echo '<link rel="stylesheet" type="text/css" href="' . $url . '" />';
}
add_action('admin_head', 'custom_admin')
```
Sources:
[Wordpress Codex](https://codex.wordpress.org/Creating_Admin_Themes)
[isitwp Snippet](https://www.isitwp.com/custom-admin-css/)
Please note the the **isitwp Snippet** erroneously mixes html entitites with angle brackets. You should use angle brackets not entitieis. |
308,505 | <p>What is the best approach to changing admin menu labels? As part of my first step in modifying the admin area, I would like to know how I can change <strong>WooCommerce</strong> label to <strong>Shop</strong>? </p>
| [
{
"answer_id": 308506,
"author": "Castiblanco",
"author_id": 44370,
"author_profile": "https://wordpress.stackexchange.com/users/44370",
"pm_score": 3,
"selected": true,
"text": "<p>In order to change the menu labels you will have to go to add this code into your <code>functions.php</cod... | 2018/07/14 | [
"https://wordpress.stackexchange.com/questions/308505",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146914/"
] | What is the best approach to changing admin menu labels? As part of my first step in modifying the admin area, I would like to know how I can change **WooCommerce** label to **Shop**? | In order to change the menu labels you will have to go to add this code into your `functions.php`:
```
add_filter( 'gettext', 'change_woocommerce_text' );
function change_woocommerce_text( $translated )
{
$translated = str_replace( 'WooCommerce', 'Store', $translated );
return $translated;
}
```
Tested. |
308,509 | <p>In the <code>register_post_status</code>, I've already disabled
<code>show_in_admin_all_list</code> & <code>show_in_admin_status_list</code> for my custom status <code>my_hidden_status</code></p>
<p>However, from the query log the post_status <code>my_hidden_status</code> is still not being filtered out (when loading edit.php)</p>
<p>e.g.</p>
<pre><code>SELECT post_status, COUNT( * ) AS num_posts FROM st_posts WHERE
post_type = 'my_cpt' GROUP BY post_status;
</code></pre>
<p>The post_status I wanted to filter is actually over 90% of my CPT, so
if the query is rewritten as</p>
<pre><code>SELECT post_status, COUNT( * ) AS num_posts FROM st_posts WHERE
post_type = 'my_cpt' AND post_status != 'my_hidden_status' GROUP BY
post_status;
</code></pre>
<p>It can greatly improve performance.</p>
<p>Is this a bug?</p>
| [
{
"answer_id": 308731,
"author": "SeventhSteel",
"author_id": 17276,
"author_profile": "https://wordpress.stackexchange.com/users/17276",
"pm_score": 1,
"selected": false,
"text": "<p>Is it a bug? It's doing a little more work than it has to, but it's not resulting in any unexpected outp... | 2018/07/14 | [
"https://wordpress.stackexchange.com/questions/308509",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16037/"
] | In the `register_post_status`, I've already disabled
`show_in_admin_all_list` & `show_in_admin_status_list` for my custom status `my_hidden_status`
However, from the query log the post\_status `my_hidden_status` is still not being filtered out (when loading edit.php)
e.g.
```
SELECT post_status, COUNT( * ) AS num_posts FROM st_posts WHERE
post_type = 'my_cpt' GROUP BY post_status;
```
The post\_status I wanted to filter is actually over 90% of my CPT, so
if the query is rewritten as
```
SELECT post_status, COUNT( * ) AS num_posts FROM st_posts WHERE
post_type = 'my_cpt' AND post_status != 'my_hidden_status' GROUP BY
post_status;
```
It can greatly improve performance.
Is this a bug? | >
> ***TL;DR:*** It's not a bug (*as we generally understand it*), rather it's a feature that was **never fully implemented** in WordPress.
>
>
>
---
Status of `register_post_status()`
----------------------------------
`register_post_status()` function was never fully implemented in WordPress. If you check WordPress [Codex entry for register\_post\_status() function](https://codex.wordpress.org/Function_Reference/register_post_status), you'll see it's clearly mentioned in a notice:
>
> **NOTICE:**
>
>
> This function does NOT add the registered post status to the admin panel. This functionality is **pending future development**. Please refer to [Trac Ticket #12706](https://core.trac.wordpress.org/ticket/12706) . Consider the action hook [post\_submitbox\_misc\_actions](http://core.trac.wordpress.org/browser/tags/3.5.1/wp-admin/includes/meta-boxes.php#L183) for adding this parameter.
>
>
>
Also, if you visit the [Related Ticket](https://core.trac.wordpress.org/ticket/12706), you'll see that the discussion to implement it fully is going on for over 8 years now (starting from March 2010)! However, since WordPress is open source community driven software & there weren't a lot of volunteers willing to work on this feature, it's still pending proper implementation.
The [Trac Ticket #12706](https://core.trac.wordpress.org/ticket/12706) states the following in the description:
>
> A developer should be able to register a custom post status using **register\_post\_status()**. The admin UI (including post submit box and quick edit) **should reflect this new custom post status**. Furthermore, there are many hard-coded references to 'draft' and 'pending' statuses in core that should properly use the post status API.
>
>
> **All existing arguments to register\_post\_status() should be fully implemented**, should also support per-post-type arguments. As things get implemented across core, there will likely be a need for supporting capabilities and bits of API.
>
>
>
Now if you look at the WordPress core CODE, you'll see that this description is still valid. That means:
* The admin UI (including post submit box and quick edit) **doesn't reflect custom post status**. Check [this part of the CODE](https://github.com/WordPress/WordPress/blob/cd4c960a6c17e683bcc76f1efaadcb272955bb83/wp-admin/includes/meta-boxes.php#L91-L113) in core:
```
<?php _e( 'Status:' ); ?> <span id="post-status-display">
<?php
switch ( $post->post_status ) {
case 'private':
_e( 'Privately Published' );
break;
case 'publish':
_e( 'Published' );
break;
case 'future':
_e( 'Scheduled' );
break;
case 'pending':
_e( 'Pending Review' );
break;
case 'draft':
case 'auto-draft':
_e( 'Draft' );
break;
}
?>
</span>
```
The CODE contains **no action / filter hook for any custom post status** or for any modification whatsoever. So the only logical way at the moment is to use some JavaScript to alter the UI implementation until this feature is implemented in WordPress core.
* All existing arguments to ***register\_post\_status()* is not yet fully implemented** & hence may look buggy.
* And a lot more discussion & work is needed for the full implementation of the Post Status API.
What to do about this Lack of Feature or Bug?
---------------------------------------------
Call it a lack of feature or call it a bug, the fact remains: there's a lot more work that needs to be done to complete the Post Status API.
So if this is too important for you, it's better to join in the discussion in the Support Ticket mentioned above to expedite the development process.
Although the entire development process will need a lot of voluntary work, you can still comment on it about the argument `show_in_admin_all_list` not affecting the query, so that at least this part of the anomaly can be improved earlier than the rest of the Status API.
What to do until core doesn't implement the features properly?
--------------------------------------------------------------
As it is now, `show_in_admin_all_list` argument only affects the `All(*)` status header part of the All Posts Listing, for example:
[](https://i.stack.imgur.com/VqQXA.png)
**Image-1:** All Posts Listing Status Header (All Posts Selected)
However, it doesn't affect the posts that appear in the list (although it should).
To make sure that posts with your custom status `my_hidden_status` doesn't appear in the list as well, you need to set the `public` argument to `false`.
This will make the `register_post_status()` function call look like the following:
```
register_post_status( 'my_hidden_status', array(
'label' => _x( 'My Hidden Status', 'post' ),
'public' => false,
'show_in_admin_all_list' => false,
'show_in_admin_status_list' => false,
'label_count' => _n_noop( 'My Hidden Status <span class="count">(%s)</span>', 'My Hidden Status <span class="count">(%s)</span>' )
) );
```
This will show the correct count in `All(*)` status header and also remove the posts with `my_hidden_status` from the `All Posts` or `All {custom_post_type}` listing.
Of course, this will essentially make posts with `my_hidden_status` inaccessible from WordPress Admin Panel. If that was the intent, then fine, otherwise, you may use the `show_in_admin_status_list` to show the posts with `my_hidden_status` in a separate listing header:
```
register_post_status( 'my_hidden_status', array(
'label' => _x( 'My Hidden Status', 'post' ),
'public' => false,
'show_in_admin_all_list' => false,
'show_in_admin_status_list' => true,
'label_count' => _n_noop( 'My Hidden Status <span class="count">(%s)</span>', 'My Hidden Status <span class="count">(%s)</span>' )
) );
```
This will show the Post Lists with the status `my_hidden_status` in a separate header like the following:
[](https://i.stack.imgur.com/EF0wV.png)
**Image-2:** All Posts Listing Status Header (Custom Status Selected)
DB Query Optimization Issue:
----------------------------
The related DB Query comes from `wp_count_posts()` function in `wp-includes/post.php` file. If you take a look at the [related CODE](https://github.com/WordPress/WordPress/blob/c9dce0606b0d7e6f494d4abe7b193ac046a322cd/wp-includes/post.php#L2457-L2467), you'll see that the arguments from `register_post_status()` function are not implemented there. Also, there's no way to filter or extend this part of the core CODE either:
```
$query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
if ( 'readable' == $perm && is_user_logged_in() ) {
$post_type_object = get_post_type_object( $type );
if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
$query .= $wpdb->prepare(
" AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
get_current_user_id()
);
}
}
$query .= ' GROUP BY post_status';
```
Unless both `show_in_admin_all_list` and `show_in_admin_status_list` are set to `false` for a particular status, related posts shouldn't be removed from the query anyway. Otherwise WordPress will not be able to generate the proper `status header` (as shown in image-2).
However, in the case where both `show_in_admin_all_list` and `show_in_admin_status_list` are set to `false`, WordPress doesn't need the count information for that custom status. So logically in this case you'll have a little query performance improvement with `AND post_status != 'my_hidden_status'` part, if you have a large number of posts (like Millions) and most of your posts (as you said 90%) are from that custom status.
Still, there are two reasons why core may not update this part of the CODE even though there may be a little performance gain in your particular case:
1. **WordPress Database uses an index named `type_status_date`** that indexes `wp-posts` table entries based on `post_type`, `post_status`, `post_date` and `ID` fields. **So queries are fast enough even without the `AND post_status != 'my_hidden_status'` part**.
I've tested with 15K+ posts and it only takes a few milliseconds. Check [this MySQL Document](https://dev.mysql.com/doc/refman/8.0/en/group-by-optimization.html) for more information on GROUP BY Optimization with index. With some tweaks to MySQL index, you may even get better results without even changing WP Core. For example, adding another index with `post_type` and `post_status` column may give you a few milliseconds gain.
2. Even though adding `AND post_status != 'my_hidden_status'` may make the query faster (merely by milliseconds) in your particular case, WordPress still may not update it, because WordPress will have to **consider the possibility where a hidden custom status has only a few posts**. In those cases, adding `AND post_status != 'my_hidden_status'` will actually make the query results a bit slower (only by a few milliseconds).
So considering everything, WordPress may or may not update the query with `AND post_status != 'my_hidden_status'` when both `show_in_admin_all_list` and `show_in_admin_status_list` are set to `false` for a custom status. However, in my opinion, at least making the related query filterable will improve the flexibility for the developers. |
308,517 | <p>I have following foreach loop code...</p>
<pre><code><?php
$usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" );
foreach ( $usernames as $username )
{
echo $username->user_name;
}
?>
</code></pre>
<p>When I use <code>echo $username->user_name;</code> it displays all the usernames from the <code>user_name</code> column of database. I want to display only the first username from the list. How to do... Pl help... Thanks...</p>
| [
{
"answer_id": 308519,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$usernames = $wpdb->get_results( \"SELECT user_name FROM wpxa_project_members WHERE projec... | 2018/07/14 | [
"https://wordpress.stackexchange.com/questions/308517",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124069/"
] | I have following foreach loop code...
```
<?php
$usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" );
foreach ( $usernames as $username )
{
echo $username->user_name;
}
?>
```
When I use `echo $username->user_name;` it displays all the usernames from the `user_name` column of database. I want to display only the first username from the list. How to do... Pl help... Thanks... | I have found the solution... Here it is...
```
<?php
$usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" );
foreach ( $usernames as $username )
{
$member_username[] = $username->user_name;
}
echo $member_username[0];
?>
```
Hope it may help other users. |
308,520 | <p>I want to hide the navigation menu on a particular page. I know how to find the page id, but I am clueless about how to find the rest of the stuff, it would be great if someone could look into my blog's css from the link - idkwhereto.com</p>
<p>Thanks.</p>
| [
{
"answer_id": 308519,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$usernames = $wpdb->get_results( \"SELECT user_name FROM wpxa_project_members WHERE projec... | 2018/07/14 | [
"https://wordpress.stackexchange.com/questions/308520",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146922/"
] | I want to hide the navigation menu on a particular page. I know how to find the page id, but I am clueless about how to find the rest of the stuff, it would be great if someone could look into my blog's css from the link - idkwhereto.com
Thanks. | I have found the solution... Here it is...
```
<?php
$usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" );
foreach ( $usernames as $username )
{
$member_username[] = $username->user_name;
}
echo $member_username[0];
?>
```
Hope it may help other users. |
308,532 | <p>For some reason, I have to unpublish certain posts every time wordpress loads.
This is my code: </p>
<pre><code>function af_change_post_status() {
$notpayed_posts = new WP_Query( array(
'meta_key' => '_payment',
'meta_value' => '0'
) );
foreach ($notpayed_posts as $notpayed_post) {
wp_transition_post_status( 'draft', $notpayed_post->post_status, $notpayed_post);
}
}
add_action( 'init', 'af_change_post_status' );
</code></pre>
<p>The query is correct and it's returning the posts I want, but the <code>wp_transition_post_status</code> function is not working and I don't know why? </p>
| [
{
"answer_id": 308533,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>It's pretty simple error. You use <code>WP_Query</code> to get posts, but then you try to use that <c... | 2018/07/14 | [
"https://wordpress.stackexchange.com/questions/308532",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136480/"
] | For some reason, I have to unpublish certain posts every time wordpress loads.
This is my code:
```
function af_change_post_status() {
$notpayed_posts = new WP_Query( array(
'meta_key' => '_payment',
'meta_value' => '0'
) );
foreach ($notpayed_posts as $notpayed_post) {
wp_transition_post_status( 'draft', $notpayed_post->post_status, $notpayed_post);
}
}
add_action( 'init', 'af_change_post_status' );
```
The query is correct and it's returning the posts I want, but the `wp_transition_post_status` function is not working and I don't know why? | >
> This function contains do\_action() calls for post status transition
> action hooks. The order of the words in the function name might be
> confusing – **it does not change the status of posts, it only calls
> actions that can be hooked into by plugin developers.**
>
>
>
<https://codex.wordpress.org/Function_Reference/wp_transition_post_status>
What you want is `wp_update_post`, you're also using `WP_Query` incorrectly:
```
$notpayed\_posts = new WP\_Query( array(
'meta\_key' => '\_payment',
'meta\_value' => '0'
) );
```
while ($notpayed_posts->have_posts()) {
$notpayed_posts->the_post();
wp_update_post( array(
'ID' => get_the_ID(),
'post_status' => 'draft'
));
}
wp_reset_postdata();
```
Also, keep in mind that your query is an expensive/very slow post meta query, post meta isn't built for searching or queries where you're looking for posts. Consider a taxonomy term.
You also do nothing to change the meta afterwards, so if there are 10 posts that match, then every page load will try to update 10 posts, even if they've already been updated! Either change the meta value with `update_post_meta` or check the post status in the query, e.g.
```
$notpayed_posts = new WP_Query( array(
'post_status' => 'publish',
'meta_key' => '_payment',
'meta_value' => '0'
) );
```
Additionally, use a cron job, don't do it on every page load by using the `init` hook, it's very bad for performance and incompatible with page caching |
308,542 | <p>Hi i'm just begining with wordpress so any help would be appreciated. I trying to get this working but the response data is undefined because of the 400 error. I've tried everything. Here's my code.</p>
<pre><code>function simokydesigns_translate_scripts() {
wp_enqueue_script('customjquery', get_template_directory_uri()
.'/js/customjquery.js', array('jquery'));
wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin-
ajax.php' ) );
}
add_action( 'wp_enqueue_scripts', 'simokydesigns_translate_scripts' );
function get_ajax_sidebar(){
get_sidebar();
}
add_action('wp_ajax_get_ajax_sidebar', 'get_ajax_sidebar');
add_action('wp_ajax_nopriv_get_ajax_sidebar', 'get_ajax_sidebar');
//js/customjquery.js
(function($) {
$.ajax({
type: 'POST', // use $_POST method to submit data
dataType: "html",
url: ajaxurl,
data: {
'action': 'get_ajax_sidebar',
},
success:function(data) {
alert('Got this from the server: ' + data);
//$( '#widget-top' ).html( data );
},
error: function (data) {
console.log('error' + data);
}
});
/*$( '#widget-top').append( "<?php echo get_sidebar();?>" );*/
})( jQuery );
</code></pre>
| [
{
"answer_id": 308544,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>This line break here:</p>\n\n<pre><code>wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admi... | 2018/07/14 | [
"https://wordpress.stackexchange.com/questions/308542",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146939/"
] | Hi i'm just begining with wordpress so any help would be appreciated. I trying to get this working but the response data is undefined because of the 400 error. I've tried everything. Here's my code.
```
function simokydesigns_translate_scripts() {
wp_enqueue_script('customjquery', get_template_directory_uri()
.'/js/customjquery.js', array('jquery'));
wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin-
ajax.php' ) );
}
add_action( 'wp_enqueue_scripts', 'simokydesigns_translate_scripts' );
function get_ajax_sidebar(){
get_sidebar();
}
add_action('wp_ajax_get_ajax_sidebar', 'get_ajax_sidebar');
add_action('wp_ajax_nopriv_get_ajax_sidebar', 'get_ajax_sidebar');
//js/customjquery.js
(function($) {
$.ajax({
type: 'POST', // use $_POST method to submit data
dataType: "html",
url: ajaxurl,
data: {
'action': 'get_ajax_sidebar',
},
success:function(data) {
alert('Got this from the server: ' + data);
//$( '#widget-top' ).html( data );
},
error: function (data) {
console.log('error' + data);
}
});
/*$( '#widget-top').append( "<?php echo get_sidebar();?>" );*/
})( jQuery );
``` | You have two problems
in PHP you need change this
is bad:
```
wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin-
ajax.php' ) );
```
change to:
```
wp_localize_script( 'customjquery', 'my_custom_vars', ['ajax_url' => admin_url('admin-ajax.php')] );
```
and your javascript need this changes
is bad:
```
$.ajax({
type: 'POST', // use $_POST method to submit data
dataType: "html",
url: ajaxurl,
```
change to:
```
$.ajax({
type: 'POST', // use $_POST method to submit data
dataType: "html",
url: my_custom_vars.ajax_url,
``` |
308,552 | <p>I am trying to get product attribute slug. I have used below code but it display name. </p>
<pre><code>echo $_product->get_attribute( 'pa_color' );
</code></pre>
<p>I am working on woocommerce/cart/cart.php file in theme folder.</p>
<p>Also I checked this is coming in anchor url of product image in cart page but not getting it</p>
<p><strong>anchor url</strong>: <a href="https://example.com/productos/sweatshirt/?attribute_pa_color=aa2757&attribute_pa_talla=m" rel="nofollow noreferrer">https://example.com/productos/sweatshirt/?attribute_pa_color=aa2757&attribute_pa_talla=m</a></p>
<p>I am working on this from today morning but I have not get success. Please guide. </p>
<p><a href="https://i.stack.imgur.com/b63TS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b63TS.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 308556,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$att=$_product->get_attribute('pa_color');\n\n$values = wc_get_product_terms( $product->... | 2018/07/14 | [
"https://wordpress.stackexchange.com/questions/308552",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145656/"
] | I am trying to get product attribute slug. I have used below code but it display name.
```
echo $_product->get_attribute( 'pa_color' );
```
I am working on woocommerce/cart/cart.php file in theme folder.
Also I checked this is coming in anchor url of product image in cart page but not getting it
**anchor url**: <https://example.com/productos/sweatshirt/?attribute_pa_color=aa2757&attribute_pa_talla=m>
I am working on this from today morning but I have not get success. Please guide.
[](https://i.stack.imgur.com/b63TS.png) | I got this....
To get slug use:
```
$attributes = $_product->get_attributes();
$pa_color = $attributes["pa_color"];
```
Thanks to all for helping me. |
308,580 | <p>I want to know how to change the login label such as Username or Email Address to Username within the wp-login.php?</p>
| [
{
"answer_id": 308583,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": -1,
"selected": false,
"text": "<p>@William : although your solution may work, it's not the proper way (which is why you got a downvote)... | 2018/07/14 | [
"https://wordpress.stackexchange.com/questions/308580",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146914/"
] | I want to know how to change the login label such as Username or Email Address to Username within the wp-login.php? | All of these strings/labels are passed through translation functions, so you can use [`gettext`](https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext) filter to modify them.
```
function change_labels( $translated_text, $text, $domain ) {
if ( 'Username' === $text ) {
$translated_text = 'Username new label';
}
return $translated_text;
}
function register_change_label_filter() {
add_filter( 'gettext', 'change_labels', 20, 3 );
}
add_action( 'login_head', 'register_change_labels_filter' );
// this way our filter will work only on wp-login and not everywhere on site...
``` |
308,591 | <p>I have added custom field in woocommerce Products>General Tab. But I am not getting those custom fields value in response using following link:- <a href="http://yoursite.com/wp-json/wc/v2/products/" rel="nofollow noreferrer">http://yoursite.com/wp-json/wc/v2/products/</a></p>
<p>My Code:-</p>
<pre><code>//Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
//Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">' ;
//Purchasing Cost
woocommerce_wp_text_input(
array(
'id' => 'purchasing_cost',
'placeholder' => 'Purchasing Cost',
'label' => __('Purchasing Cost', 'woocommerce'),
'type' => 'text',
'show_in_rest' => true,
'rest_base' => 'products',
'rest_controller_class' => 'WP_REST_Products_Controller',
)
);
//OverHead
woocommerce_wp_text_input(
array(
'id' => 'overhead',
'placeholder' => 'Overhead',
'label' => __('Overhead', 'woocommerce'),
'type' => 'text',
'show_in_rest' => true,
'rest_base' => 'products',
'rest_controller_class' => 'WP_REST_Products_Controller',
)
);
echo '</div>';
}
//To Save data
function woo_add_custom_general_fields_save($post_id) {
//Purchasing Cost
$woocommerce_purchasing_cost_field = $_POST['purchasing_cost'];
if (!empty($woocommerce_purchasing_cost_field))
update_post_meta($post_id, 'purchasing_cost', esc_attr($woocommerce_purchasing_cost_field));
//OverHead
$woocommerce_overhead_field = $_POST['overhead'];
if (!empty($woocommerce_overhead_field))
update_post_meta($post_id, 'overhead', esc_attr($woocommerce_overhead_field));
}
</code></pre>
<p>Thanks in Advance.</p>
| [
{
"answer_id": 308608,
"author": "Andrea Somovigo",
"author_id": 64435,
"author_profile": "https://wordpress.stackexchange.com/users/64435",
"pm_score": 2,
"selected": false,
"text": "<p>You should ad the custom field to product API response, try this\n (untested)</p>\n\n<pre><code>add_f... | 2018/07/15 | [
"https://wordpress.stackexchange.com/questions/308591",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146897/"
] | I have added custom field in woocommerce Products>General Tab. But I am not getting those custom fields value in response using following link:- <http://yoursite.com/wp-json/wc/v2/products/>
My Code:-
```
//Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
//Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">' ;
//Purchasing Cost
woocommerce_wp_text_input(
array(
'id' => 'purchasing_cost',
'placeholder' => 'Purchasing Cost',
'label' => __('Purchasing Cost', 'woocommerce'),
'type' => 'text',
'show_in_rest' => true,
'rest_base' => 'products',
'rest_controller_class' => 'WP_REST_Products_Controller',
)
);
//OverHead
woocommerce_wp_text_input(
array(
'id' => 'overhead',
'placeholder' => 'Overhead',
'label' => __('Overhead', 'woocommerce'),
'type' => 'text',
'show_in_rest' => true,
'rest_base' => 'products',
'rest_controller_class' => 'WP_REST_Products_Controller',
)
);
echo '</div>';
}
//To Save data
function woo_add_custom_general_fields_save($post_id) {
//Purchasing Cost
$woocommerce_purchasing_cost_field = $_POST['purchasing_cost'];
if (!empty($woocommerce_purchasing_cost_field))
update_post_meta($post_id, 'purchasing_cost', esc_attr($woocommerce_purchasing_cost_field));
//OverHead
$woocommerce_overhead_field = $_POST['overhead'];
if (!empty($woocommerce_overhead_field))
update_post_meta($post_id, 'overhead', esc_attr($woocommerce_overhead_field));
}
```
Thanks in Advance. | You should ad the custom field to product API response, try this
(untested)
```
add_filter( 'woocommerce_rest_prepare_product', 'custom_products_api_data', 90, 2 );
function custom_products_api_data( $response, $post ) {
// retrieve a custom field and add it to API response
$response->data['purchasing_cost'] = get_post_meta( $post->ID, 'purchasing_cost', true );
return $response;
}
``` |
308,611 | <p>I am using <code>save_post</code> for a function to send an email when a post is updated by a user. This is firing twice and I am aware this is due to the post revisions and autosaves. </p>
<p>I have tried to prevent this from happening by wrapping my <code>wp_mail</code> within a conditional statement but this still fires twice. What adjustments do I need to make to ensure this only fires once when a user updates the post? </p>
<pre><code>function updated_search_notification($post_id)
{
$post_type = get_post_type($post_id);
if ($post_type === 'utility-search') {
if ((wp_is_post_revision($post_id)) || (wp_is_post_autosave($post_id))) {
// post is autosave
} else {
// Message Variables
$siteurl = get_option('siteurl');
$post_url = '' . $siteurl . '/wp-admin/post.php?post=' . $post_id . '&action=edit';
$new_search_name = '';
//$new_search_email = get_option( 'new_search_email' );
$new_search_email = '[email]';
$utility_search_customer = '';
$subject = 'Your search has been updated';
// Message Contents
$message = "[Message Contents]";
// Send Email
wp_mail($new_search_email, $subject, $message);
}
}
}
add_action('save_post', 'updated_search_notification', 10, 3);
</code></pre>
| [
{
"answer_id": 308612,
"author": "Atlas_Gondal",
"author_id": 132879,
"author_profile": "https://wordpress.stackexchange.com/users/132879",
"pm_score": 0,
"selected": false,
"text": "<p>Try this piece of code inside your function:</p>\n\n<pre><code>if ( defined( 'DOING_AUTOSAVE' ) &&... | 2018/07/15 | [
"https://wordpress.stackexchange.com/questions/308611",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64567/"
] | I am using `save_post` for a function to send an email when a post is updated by a user. This is firing twice and I am aware this is due to the post revisions and autosaves.
I have tried to prevent this from happening by wrapping my `wp_mail` within a conditional statement but this still fires twice. What adjustments do I need to make to ensure this only fires once when a user updates the post?
```
function updated_search_notification($post_id)
{
$post_type = get_post_type($post_id);
if ($post_type === 'utility-search') {
if ((wp_is_post_revision($post_id)) || (wp_is_post_autosave($post_id))) {
// post is autosave
} else {
// Message Variables
$siteurl = get_option('siteurl');
$post_url = '' . $siteurl . '/wp-admin/post.php?post=' . $post_id . '&action=edit';
$new_search_name = '';
//$new_search_email = get_option( 'new_search_email' );
$new_search_email = '[email]';
$utility_search_customer = '';
$subject = 'Your search has been updated';
// Message Contents
$message = "[Message Contents]";
// Send Email
wp_mail($new_search_email, $subject, $message);
}
}
}
add_action('save_post', 'updated_search_notification', 10, 3);
``` | First, you can use this hook to target only one custom type:
<https://developer.wordpress.org/reference/hooks/save_post_post-post_type/>
This hook (and `save_post`) is called the first time when you click on "new ..." and then the hook is called with `$update = FALSE`.
Then to send e-mail only when the object is updated, you can test `$update` like this:
```
const UTILITY_SEARCH_POST_TYPE = "utility-search";
add_action("save_post_" . UTILITY_SEARCH_POST_TYPE, function ($post_ID, $post, $update) {
if (wp_is_post_autosave($post_ID)) {
return;
}
if (!$update) { // if new object
return;
}
// preparing e-mail
...
// sending e-mail
wp_mail(...);
}, 10, 3);
``` |
308,656 | <p>I am using WP_Query to loop a Custom Field, Custom Post Type that shows 6 Menu Icons across 6 horizontal fields. The icons do not show on the page. </p>
<p>My query code is:</p>
<pre><code><?php $loop = new WP_Query( array( 'post_type' => 'course_feature', 'orderby', => 'post_id', 'order' => 'ASC')); ?>
</code></pre>
<p>code to show loop:</p>
<pre><code><?php while( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="col-sm-2">
<i class=<?php the_field('course_feature_icon'); ?>"</i>
</div>
<?php endwhile; ?>
</code></pre>
| [
{
"answer_id": 308657,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>There's a missing opening quote and closing bracket on this line:</p>\n\n<pre><code><i class=<?ph... | 2018/07/16 | [
"https://wordpress.stackexchange.com/questions/308656",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146589/"
] | I am using WP\_Query to loop a Custom Field, Custom Post Type that shows 6 Menu Icons across 6 horizontal fields. The icons do not show on the page.
My query code is:
```
<?php $loop = new WP_Query( array( 'post_type' => 'course_feature', 'orderby', => 'post_id', 'order' => 'ASC')); ?>
```
code to show loop:
```
<?php while( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="col-sm-2">
<i class=<?php the_field('course_feature_icon'); ?>"</i>
</div>
<?php endwhile; ?>
``` | There's a missing opening quote and closing bracket on this line:
```
<i class=<?php the_field('course_feature_icon'); ?>"</i>
```
Needs to be:
```
<i class="<?php the_field('course_feature_icon'); ?>"></i>
```
That's all that's wrong with your code. It should then work assuming:
1. You have a custom field, `course_feature_icon`, whose value is a valid CSS class.
2. You have the necessary CSS to add an icon based on that class.
One last suggestion though. For safety you should [escape](https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/) the field value before outputting it as a class:
```
<i class="<?php echo esc_attr( get_field('course_feature_icon') ); ?>"></i>
``` |
308,661 | <p>How can I change the menu icon (coming from external plugins, like WooCommerce) in wp-admin area with custom icon? (The menu-item is actually <code>post-type</code>, so there should be some <code>register_post_type</code> command i think).</p>
| [
{
"answer_id": 308665,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>to add a custom image, you can use this code. the original image is set with CSS then you have to add custom CSS ... | 2018/07/16 | [
"https://wordpress.stackexchange.com/questions/308661",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146914/"
] | How can I change the menu icon (coming from external plugins, like WooCommerce) in wp-admin area with custom icon? (The menu-item is actually `post-type`, so there should be some `register_post_type` command i think). | WooCommerce styles the icon via this CSS file: `woocommerce/assets/css/menu.css`, and here's the corresponding code (*pretty-printed* or actually, I copied it from [`woocommerce/assets/css/menu.scss`](https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/assets/css/menu.scss#L17)):
```
#adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before {
font-family: 'WooCommerce' !important;
content: '\e03d';
}
```
So you can change the `font-family` and the `content` (and other) properties to suit your custom icon.
---
Below is an example of customizing the icon by changing it to use a `background-image`:
```
// We hook to the `admin_enqueue_scripts` action with a priority of `11`, where
// at this point, the default CSS file should have been loaded. But you can or
// should add the CSS rule to your custom CSS file; just make sure it's loaded
// *after* the default CSS file.
add_action( 'admin_enqueue_scripts', function(){
$css = <<<EOT
#adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before {
content: ' ';
background: url('https://png.icons8.com/dusk/2x/e-commerce.png') no-repeat center;
background-size: contain;
}
EOT;
wp_add_inline_style( 'woocommerce_admin_menu_styles', $css );
}, 11 );
```
Note: The `menu.css` file is registered and queued in [`WC_Admin_Assets::admin_styles()`](https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/includes/admin/class-wc-admin-assets.php#L28) with the handle/name of `woocommerce_admin_menu_styles`. |
308,695 | <p>I have Used the function <code>dynamic_sidebar('sidebarId')</code> in the <code>sidebar.php</code> file.</p>
<p>and all the functionality of the sidebar is Working succsessfully </p>
<p>My Question is How To Change the Html of the sidebar widgets and add some classes in widget items To fit My Design ?</p>
<p><a href="https://i.stack.imgur.com/Ka4ki.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ka4ki.png" alt="enter image description here"></a>
Thank You in advance</p>
| [
{
"answer_id": 308665,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>to add a custom image, you can use this code. the original image is set with CSS then you have to add custom CSS ... | 2018/07/16 | [
"https://wordpress.stackexchange.com/questions/308695",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142085/"
] | I have Used the function `dynamic_sidebar('sidebarId')` in the `sidebar.php` file.
and all the functionality of the sidebar is Working succsessfully
My Question is How To Change the Html of the sidebar widgets and add some classes in widget items To fit My Design ?
[](https://i.stack.imgur.com/Ka4ki.png)
Thank You in advance | WooCommerce styles the icon via this CSS file: `woocommerce/assets/css/menu.css`, and here's the corresponding code (*pretty-printed* or actually, I copied it from [`woocommerce/assets/css/menu.scss`](https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/assets/css/menu.scss#L17)):
```
#adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before {
font-family: 'WooCommerce' !important;
content: '\e03d';
}
```
So you can change the `font-family` and the `content` (and other) properties to suit your custom icon.
---
Below is an example of customizing the icon by changing it to use a `background-image`:
```
// We hook to the `admin_enqueue_scripts` action with a priority of `11`, where
// at this point, the default CSS file should have been loaded. But you can or
// should add the CSS rule to your custom CSS file; just make sure it's loaded
// *after* the default CSS file.
add_action( 'admin_enqueue_scripts', function(){
$css = <<<EOT
#adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before {
content: ' ';
background: url('https://png.icons8.com/dusk/2x/e-commerce.png') no-repeat center;
background-size: contain;
}
EOT;
wp_add_inline_style( 'woocommerce_admin_menu_styles', $css );
}, 11 );
```
Note: The `menu.css` file is registered and queued in [`WC_Admin_Assets::admin_styles()`](https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/includes/admin/class-wc-admin-assets.php#L28) with the handle/name of `woocommerce_admin_menu_styles`. |
308,700 | <p>My parent theme calls a function:</p>
<pre><code>function get_nav_markup() {
ob_start();
?>
<nav class="navbar navbar-toggleable-md navbar-inverse site-navbar" role="navigation">
<div class="container">
<?php if ( is_home() ): ?>
<h1 class="navbar-brand mb-0">
<?php echo get_sitename_formatted(); ?>
</h1>
<?php else: ?>
<a href="<?php echo bloginfo( 'url' ); ?>" class="navbar-brand">
<?php echo get_sitename_formatted(); ?>
</a>
<?php endif; ?>
<button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#header-menu" aria-controls="header-menu" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<?php
wp_nav_menu( array(
'theme_location' => 'header-menu',
'depth' => 2,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'header-menu',
'menu_class' => 'nav navbar-nav ml-md-auto',
) );
?>
</div>
</nav>
<?php
return ob_get_clean();
}
</code></pre>
<p>and then later uses it like so:</p>
<pre><code>function get_header_markup() {
global $post;
echo get_nav_markup( $post );
$videos = get_header_videos( $post );
$images = get_header_images( $post );
if ( $videos || $images ) {
echo get_header_media_markup( $post, $videos, $images );
}
else {
echo get_header_default_markup( $post );
}
}
</code></pre>
<p>Is there anyway that I can overwrite get_nav_markup or at least append additional information immediately after it in my child theme? </p>
<p>Given the way the parent theme function written I don't think I can. But I really need to be able to add some additional DIVs and PHP right after the /nav</p>
| [
{
"answer_id": 308702,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>No, it doesn't appear to be possible. At least not directly. You can replace functions in parent themes... | 2018/07/16 | [
"https://wordpress.stackexchange.com/questions/308700",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146418/"
] | My parent theme calls a function:
```
function get_nav_markup() {
ob_start();
?>
<nav class="navbar navbar-toggleable-md navbar-inverse site-navbar" role="navigation">
<div class="container">
<?php if ( is_home() ): ?>
<h1 class="navbar-brand mb-0">
<?php echo get_sitename_formatted(); ?>
</h1>
<?php else: ?>
<a href="<?php echo bloginfo( 'url' ); ?>" class="navbar-brand">
<?php echo get_sitename_formatted(); ?>
</a>
<?php endif; ?>
<button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#header-menu" aria-controls="header-menu" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<?php
wp_nav_menu( array(
'theme_location' => 'header-menu',
'depth' => 2,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'header-menu',
'menu_class' => 'nav navbar-nav ml-md-auto',
) );
?>
</div>
</nav>
<?php
return ob_get_clean();
}
```
and then later uses it like so:
```
function get_header_markup() {
global $post;
echo get_nav_markup( $post );
$videos = get_header_videos( $post );
$images = get_header_images( $post );
if ( $videos || $images ) {
echo get_header_media_markup( $post, $videos, $images );
}
else {
echo get_header_default_markup( $post );
}
}
```
Is there anyway that I can overwrite get\_nav\_markup or at least append additional information immediately after it in my child theme?
Given the way the parent theme function written I don't think I can. But I really need to be able to add some additional DIVs and PHP right after the /nav | Ok so here is what I have decided given the situation.
1. I have copied the header.php file into my child theme.
2. I have changed the line in the header file from get\_header\_markup(); to get\_header\_markup\_updated();
3. I have then created a new function in my child themes function.php file called get\_header\_markup\_updated.
4. I started the function off my copying the existing one from the parent theme, but then added the code I needed... where I needed it.
The result now looks like:
```
function get_header_markup_updated() {
global $post;
echo get_nav_markup( $post ); ?>
<div class="breadcrumbnav">
<!-- Inserted all my other code here -->
</div>
<?php
$videos = get_header_videos( $post );
$images = get_header_images( $post );
if ( $videos || $images ) {
echo get_header_media_markup( $post, $videos, $images );
}
else {
echo get_header_default_markup( $post );
}
}
?>
```
This seems to be working just fine. Hopefully this will also be the least obtrusive going forward. |
308,730 | <p>I'm trying to build functionality (using the Advanced Custom Fields plugin) to list information in a page template for all custom post types ('Product') that have specified taxonomies.</p>
<p>This is my current stable code, which queries the Products, but only based on the taxonomy terms I hard-code:</p>
<pre><code>$posts = get_posts(array(
'posts_per_page' => 10,
'post_type' => 'company_product',
'tax_query' => array(
array(
'taxonomy' => 'taxonomy',
'field' => 'slug',
'terms' => 'product1'
),
));
</code></pre>
<p>I've used ACF to set up functionality in the backend to select multiple taxonomies (via a repeater field) that I want to apply to the query, so that the admin can modify which Products are returned based on which taxonomies they have.</p>
<p>I tried this:</p>
<pre><code>$posts = get_posts(array(
'posts_per_page' => 10,
'post_type' => 'company_product',
'tax_query' => array(
if( have_rows('category_taxonomies') ):
while ( have_rows('category_taxonomies') ) : the_row();
array(
'taxonomy' => 'taxonomy',
'field' => 'slug',
'terms' => the_sub_field('category_taxonomy')
),
endwhile;
endif;
));
</code></pre>
<p>But received this error: <code>Parse error: syntax error, unexpected 'if' (T_IF), expecting ')' in</code>...</p>
<p>As you can see, I'm trying to add an array to the tax_query for each taxonomy that's selected in the backend, but trying to put the if/while functions inside the array itself causes an error.</p>
<p>I assumed the above method wouldn't work, but PHP isn't my expertise so I'm not sure where to go from here. Any help is appreciated.</p>
| [
{
"answer_id": 308738,
"author": "Paul Elrich",
"author_id": 146435,
"author_profile": "https://wordpress.stackexchange.com/users/146435",
"pm_score": -1,
"selected": false,
"text": "<p>If conditions don't run inside of arrays, so you will need to write separate arrays for each condition... | 2018/07/16 | [
"https://wordpress.stackexchange.com/questions/308730",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115332/"
] | I'm trying to build functionality (using the Advanced Custom Fields plugin) to list information in a page template for all custom post types ('Product') that have specified taxonomies.
This is my current stable code, which queries the Products, but only based on the taxonomy terms I hard-code:
```
$posts = get_posts(array(
'posts_per_page' => 10,
'post_type' => 'company_product',
'tax_query' => array(
array(
'taxonomy' => 'taxonomy',
'field' => 'slug',
'terms' => 'product1'
),
));
```
I've used ACF to set up functionality in the backend to select multiple taxonomies (via a repeater field) that I want to apply to the query, so that the admin can modify which Products are returned based on which taxonomies they have.
I tried this:
```
$posts = get_posts(array(
'posts_per_page' => 10,
'post_type' => 'company_product',
'tax_query' => array(
if( have_rows('category_taxonomies') ):
while ( have_rows('category_taxonomies') ) : the_row();
array(
'taxonomy' => 'taxonomy',
'field' => 'slug',
'terms' => the_sub_field('category_taxonomy')
),
endwhile;
endif;
));
```
But received this error: `Parse error: syntax error, unexpected 'if' (T_IF), expecting ')' in`...
As you can see, I'm trying to add an array to the tax\_query for each taxonomy that's selected in the backend, but trying to put the if/while functions inside the array itself causes an error.
I assumed the above method wouldn't work, but PHP isn't my expertise so I'm not sure where to go from here. Any help is appreciated. | OK, I have no idea how and why your code should work... It has nothing in common with correct PHP syntax... But it's pretty good pseudo-code, so I think I can guess, what you wanted to achieve...
```
$tax_query = array();
if ( have_rows('category_taxonomies') ) {
while ( have_rows('category_taxonomies') ) {
the_row();
$tax_query[] = array(
'taxonomy' => 'taxonomy', // <- you should put real taxonomy name in here
'field' => 'slug',
'terms' => get_sub_field('category_taxonomy')
);
}
}
$posts = get_posts( array(
'posts_per_page' => 10,
'post_type' => 'company_product',
'tax_query' => $tax_query
));
``` |
308,759 | <p>I wanted to combine multiple categories in one Menu item</p>
<p>I checked this dicussion, someone said:</p>
<blockquote>
<p>You'd have to make a custom link for that.</p>
<p>Make your URL <a href="http://www.example.com/?cat=(id-white),(id-rabbit)" rel="nofollow noreferrer">http://www.example.com/?cat=(id-white),(id-rabbit)</a></p>
</blockquote>
<p>Below is my link but can't show the correct categories. ID is correct.</p>
<p><a href="http://example.com/?cat=(id-32),(id-33)" rel="nofollow noreferrer">http://example.com/?cat=(id-32),(id-33)</a></p>
| [
{
"answer_id": 308770,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": false,
"text": "<p>You misunderstood the quote, the URL needs to be</p>\n\n<pre><code>http://example.com/?cat=32,33\n</code></pre... | 2018/07/17 | [
"https://wordpress.stackexchange.com/questions/308759",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135792/"
] | I wanted to combine multiple categories in one Menu item
I checked this dicussion, someone said:
>
> You'd have to make a custom link for that.
>
>
> Make your URL <http://www.example.com/?cat=(id-white),(id-rabbit)>
>
>
>
Below is my link but can't show the correct categories. ID is correct.
<http://example.com/?cat=(id-32),(id-33)> | You misunderstood the quote, the URL needs to be
```
http://example.com/?cat=32,33
```
I just tested it and it seems to work. However, the title was only one of the categories' name, there might be other problems with this solution. |
308,837 | <p>I want the custom fields for PDF file upload on admin side for the post where i can select any PDF file for the any posts using custom code or any type of plugins.</p>
<p>can you recommend me please by which my problem can be solved ?</p>
<pre><code><?php
$array=array('posts_per_page'=>2, 'post_type'=>'post');
$mypost=get_posts($array);
//print_r($mypost);
foreach($mypost as $values)
{
//print_r($mypost);
echo "<p>" .$values->post_title."</p>";
echo "<p>" .$values->post_content."</p>";
echo "<p>" .get_the_post_thumbnail($values->ID, 'thumbnail', array( 'class' => 'thumbnail text-center' ))."</p>";
echo '<p>' . date_i18n('d F Y', strtotime($values->post_date)) .'</p> ';
//$ca = get_the_category($values->ID);
//print_r($ca);
//echo $ca[0]->name;
$pdf_file = get_field('pdf');
print_r($pdf_file);
if( $file ) {
echo '<a href="'.$pdf_file.'">Download File</a>';
}
}
?>
</code></pre>
| [
{
"answer_id": 308839,
"author": "dhirenpatel22",
"author_id": 124380,
"author_profile": "https://wordpress.stackexchange.com/users/124380",
"pm_score": 3,
"selected": true,
"text": "<p>Follow below steps to create custom PDF upload field in custom post type:</p>\n\n<ol>\n<li>Install <a ... | 2018/07/17 | [
"https://wordpress.stackexchange.com/questions/308837",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144155/"
] | I want the custom fields for PDF file upload on admin side for the post where i can select any PDF file for the any posts using custom code or any type of plugins.
can you recommend me please by which my problem can be solved ?
```
<?php
$array=array('posts_per_page'=>2, 'post_type'=>'post');
$mypost=get_posts($array);
//print_r($mypost);
foreach($mypost as $values)
{
//print_r($mypost);
echo "<p>" .$values->post_title."</p>";
echo "<p>" .$values->post_content."</p>";
echo "<p>" .get_the_post_thumbnail($values->ID, 'thumbnail', array( 'class' => 'thumbnail text-center' ))."</p>";
echo '<p>' . date_i18n('d F Y', strtotime($values->post_date)) .'</p> ';
//$ca = get_the_category($values->ID);
//print_r($ca);
//echo $ca[0]->name;
$pdf_file = get_field('pdf');
print_r($pdf_file);
if( $file ) {
echo '<a href="'.$pdf_file.'">Download File</a>';
}
}
?>
``` | Follow below steps to create custom PDF upload field in custom post type:
1. Install [Advance Custom Field](https://wordpress.org/plugins/advanced-custom-fields/) from wordpress.org
2. Go to **Custom Fields** and click on **Add New** button.
3. Follow instructions in below screenshot to add the custom field to upload PDF file.
[](https://i.stack.imgur.com/t63t9.jpg)
4. Use below code to display content on post type template.
```
$pdf_file = get_field('pdf_upload');
if( $file ) {
echo '<a href="'.$pdf_file.'">Download File</a>';
}
```
Reference Documentation: <https://www.advancedcustomfields.com/resources/file/>
Hope this helps..!! |
308,854 | <p>To start I've been searching through several questions and documentation pieces but it seems with WordPress' <code>v2</code> many of the old questions are no longer valid. What I am trying to do is get all posts or a singular post from a category in Postman instead of the common returned 10 posts without having to modify the API in functions.php.</p>
<h2>tldr</h2>
<p>I started with referencing the <a href="https://developer.wordpress.org/rest-api/" rel="noreferrer">REST API Handbook</a> and reviewing the <a href="https://developer.wordpress.org/rest-api/reference/posts/#schema" rel="noreferrer">schema</a> I saw <code>categories</code> and I can return the 10 latest categories using:</p>
<pre><code>http://foobar.com/wp-json/wp/v2/posts/categories_name=hello
</code></pre>
<p>referencing the <a href="https://developer.wordpress.org/rest-api/reference/posts/#arguments" rel="noreferrer">arguments</a> I see <code>per_page</code> so I tried:</p>
<pre><code>http://foobar.com/wp-json/wp/v2/posts/categories_name=hello?per_page=1
</code></pre>
<p>and it returns 10 posts from the category <code>hello</code> so I modified and tried:</p>
<pre><code>http://foobar.com/wp-json/wp/v2/posts/categories_name=hello&per_page=1
</code></pre>
<p>and I get an error returned:</p>
<blockquote>
<p>{
"code": "rest_invalid_param",
"message": "Invalid parameter(s): per_page",
"data": {
"status": 400,
"params": {
"per_page": "per_page is not of type integer."
}
} }</p>
</blockquote>
<p>Searching through Google I <a href="https://stackoverflow.com/questions/20158417/how-to-retrieve-a-list-of-categories-tag-in-wordpress-rest-api">see How to retrieve a list of categories/ tag in Wordpress REST API</a> but the answers are based on <code>v1</code>.</p>
<p>Trying <a href="https://stackoverflow.com/questions/29171854/wordpress-api-json-return-limit">Wordpress API JSON return limit</a> I use:</p>
<pre><code>http://foobar.com/wp-json/wp/v2/posts/?per_page=1
</code></pre>
<p>and I get a singular post so I modified my attempt to:</p>
<pre><code>http://foobar.com/wp-json/wp/v2/posts/?per_page=1$categories_name=hello
</code></pre>
<p>It ignores the category type and returns the latest post. Reading <a href="https://wordpress.stackexchange.com/questions/274890/get-more-than-10-posts-in-a-specific-category-with-the-wordpress-api">Get more than 10 posts in a specific category with the WordPress API</a> I pulled the ID of a category (4) after using:</p>
<pre><code>http://foobar.com/wp-json/wp/v2/categories
</code></pre>
<p>then coded:</p>
<pre><code>http://foobar.com/wp-json/wp/v2/posts/?categories=4&per_page=1
</code></pre>
<p>and I get:</p>
<blockquote>
<p>{
"code": "rest_invalid_param",
"message": "Invalid parameter(s): per_page",
"data": {
"status": 400,
"params": {
"per_page": "per_page is not of type integer."
}
} }</p>
</blockquote>
<p>I thought I might be able to use <code>-1</code> similar to the development of a theme but I get an error.</p>
<p>Other references I read are:</p>
<ul>
<li><a href="https://wordpress.stackexchange.com/questions/222547/wp-rest-api-retrieve-content-from-page">WP REST API - Retrieve content from page</a></li>
<li><a href="http://v2.wp-api.org/reference/categories/" rel="noreferrer">WP REST API Category</a></li>
<li><p>Found this <a href="https://github.com/WP-API/WP-API/issues/2949" rel="noreferrer">Since filter has been removed, how to get posts by category slug with same schema as v2/posts?</a> after reading <a href="https://stackoverflow.com/questions/38944843/search-post-by-categories-wordpress-wp-api">Search post by categories Wordpress WP-API</a></p></li>
<li><p><a href="https://wordpress.stackexchange.com/questions/40839/how-to-get-all-posts-related-to-particular-category-name">How to get all posts related to particular category name?</a></p></li>
</ul>
<p>After reviewing the documentation on <a href="https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters" rel="noreferrer">Pagination</a> it seems to only work with the <code>post</code> and not any <code>category</code>. I can only get more than 10 posts if I use <code>/wp-json/wp/v2/posts?per_page=20</code>, too.</p>
<h2>Question</h2>
<p>When calling a site's WP API how can I control the <code>per_page</code> return of a category wether it be 1 post or all posts?</p>
| [
{
"answer_id": 308869,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>Pretty much all the URLs you are using are invalid in some way:</p>\n\n<pre><code>http://foobar.com/wp-... | 2018/07/17 | [
"https://wordpress.stackexchange.com/questions/308854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25271/"
] | To start I've been searching through several questions and documentation pieces but it seems with WordPress' `v2` many of the old questions are no longer valid. What I am trying to do is get all posts or a singular post from a category in Postman instead of the common returned 10 posts without having to modify the API in functions.php.
tldr
----
I started with referencing the [REST API Handbook](https://developer.wordpress.org/rest-api/) and reviewing the [schema](https://developer.wordpress.org/rest-api/reference/posts/#schema) I saw `categories` and I can return the 10 latest categories using:
```
http://foobar.com/wp-json/wp/v2/posts/categories_name=hello
```
referencing the [arguments](https://developer.wordpress.org/rest-api/reference/posts/#arguments) I see `per_page` so I tried:
```
http://foobar.com/wp-json/wp/v2/posts/categories_name=hello?per_page=1
```
and it returns 10 posts from the category `hello` so I modified and tried:
```
http://foobar.com/wp-json/wp/v2/posts/categories_name=hello&per_page=1
```
and I get an error returned:
>
> {
> "code": "rest\_invalid\_param",
> "message": "Invalid parameter(s): per\_page",
> "data": {
> "status": 400,
> "params": {
> "per\_page": "per\_page is not of type integer."
> }
> } }
>
>
>
Searching through Google I [see How to retrieve a list of categories/ tag in Wordpress REST API](https://stackoverflow.com/questions/20158417/how-to-retrieve-a-list-of-categories-tag-in-wordpress-rest-api) but the answers are based on `v1`.
Trying [Wordpress API JSON return limit](https://stackoverflow.com/questions/29171854/wordpress-api-json-return-limit) I use:
```
http://foobar.com/wp-json/wp/v2/posts/?per_page=1
```
and I get a singular post so I modified my attempt to:
```
http://foobar.com/wp-json/wp/v2/posts/?per_page=1$categories_name=hello
```
It ignores the category type and returns the latest post. Reading [Get more than 10 posts in a specific category with the WordPress API](https://wordpress.stackexchange.com/questions/274890/get-more-than-10-posts-in-a-specific-category-with-the-wordpress-api) I pulled the ID of a category (4) after using:
```
http://foobar.com/wp-json/wp/v2/categories
```
then coded:
```
http://foobar.com/wp-json/wp/v2/posts/?categories=4&per_page=1
```
and I get:
>
> {
> "code": "rest\_invalid\_param",
> "message": "Invalid parameter(s): per\_page",
> "data": {
> "status": 400,
> "params": {
> "per\_page": "per\_page is not of type integer."
> }
> } }
>
>
>
I thought I might be able to use `-1` similar to the development of a theme but I get an error.
Other references I read are:
* [WP REST API - Retrieve content from page](https://wordpress.stackexchange.com/questions/222547/wp-rest-api-retrieve-content-from-page)
* [WP REST API Category](http://v2.wp-api.org/reference/categories/)
* Found this [Since filter has been removed, how to get posts by category slug with same schema as v2/posts?](https://github.com/WP-API/WP-API/issues/2949) after reading [Search post by categories Wordpress WP-API](https://stackoverflow.com/questions/38944843/search-post-by-categories-wordpress-wp-api)
* [How to get all posts related to particular category name?](https://wordpress.stackexchange.com/questions/40839/how-to-get-all-posts-related-to-particular-category-name)
After reviewing the documentation on [Pagination](https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters) it seems to only work with the `post` and not any `category`. I can only get more than 10 posts if I use `/wp-json/wp/v2/posts?per_page=20`, too.
Question
--------
When calling a site's WP API how can I control the `per_page` return of a category wether it be 1 post or all posts? | After a few hours trying different permutations of how to get a return on categories I found my answer. To establish the listing of categories associated with `post` use:
```
/wp-json/wp/v2/categories/
```
I needed a particular category and the `id` of that category was `4` and the slug was called `foobar`.
To get 1 post associated with the category `foobar` I had to use:
```
/wp-json/wp/v2/posts?categories=4&per_page=1
```
To get 100 posts associated with the category `foobar` I used:
```
/wp-json/wp/v2/posts?categories=4&per_page=100
```
and as I found out and it was also mentioned in the [answer](https://wordpress.stackexchange.com/a/308869/25271) my logic of using `-1` was incorrect, you can only use 1 to 100. As it was discussed in the comment on what to do if there are more than 100 posts, well you can call the page using `offset` and I found that under the documentation [Pagination](https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters):
```
/wp-json/wp/v2/posts?categories=4&offset=10&per_page=1
```
so to get more than 100 you'd to build a loop in whatever language you wanted and push it to a file. To assist with the looping under `/wp-json/wp/v2/categories/` and when you reference the category you can reference the total count under `count` which is below the `id`. |
308,876 | <p>My wordpress site dj.pyromusic.cn is based in China, on a chinese server. Somewhere in the theme, or the site, it is making a request to youtube which is obviously blocked here, causing the load time to be over 300 seconds before it times out.</p>
<p>Here is a screenshot of the inspection:</p>
<p><a href="https://i.stack.imgur.com/gbwB0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gbwB0.png" alt="enter image description here"></a></p>
<p>Any ideas how I can block this request? </p>
| [
{
"answer_id": 308877,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 1,
"selected": false,
"text": "<p>The Youtube is called by a script named \"jquery.st.youtube.js\" which is located in your themes fold... | 2018/07/18 | [
"https://wordpress.stackexchange.com/questions/308876",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147123/"
] | My wordpress site dj.pyromusic.cn is based in China, on a chinese server. Somewhere in the theme, or the site, it is making a request to youtube which is obviously blocked here, causing the load time to be over 300 seconds before it times out.
Here is a screenshot of the inspection:
[](https://i.stack.imgur.com/gbwB0.png)
Any ideas how I can block this request? | The Youtube is called by a script named "jquery.st.youtube.js" which is located in your themes folder. You seem to use a premium theme named "Wunder" which effectively means you can do one of two things:
1) You can edit the themes files directly, search for the enqueuing of the script jquery.st.youtube.js (most likely within the functions.php of the theme, but maybe somewhere else) and remove the line/turn the line into a comment. CAUTION: Do not do this if you plan to install updates to this theme. Whenever you update your theme, the changes you made are gone, so i would advise against this way. However, if the support cycle is over, you don't plan to update the theme and need a quick dirty fix RITE NAO, it is a possibility.
2) You create a child theme (<https://codex.wordpress.org/Child_Themes>) of your premium theme. After that, find the handle which is used for enqueueing the "jquery.st.youtube.js"-Script. In the functions.php of your child-theme, you hook into the wp\_enqueue\_scripts action with a big priority like 1000 and use wp\_dequeue\_script to remove it from the action.
Example:
The function in your premium theme where the scripts are enqueued MAY look like this:
```
add_action( 'wp_enqueue_scripts', 'wunder_enqueue_scripts' );
function wunder_enqueue_scripts(){
wp_enqueue_script('wunder-youtube',"jquery.st.youtube.js",array('jquery'),"",true);
..... (more scripts)
}
```
In your child-themes functions.php, you can now insert a function to dequeue the script like this:
```
add_action( 'wp_enqueue_scripts', 'remove_that_darn_youtube_scripts',1000 );
function remove_that_darn_youtube_scripts(){
wp_dequeue_script('wunder-youtube');
}
```
If you don't understand what any of these functions do, then you can read up on [wp\_enqueue\_script](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) and [wp\_dequeue\_script](https://codex.wordpress.org/Function_Reference/wp_dequeue_script) in the wordpress codex (or you get someone to code for you ;) )
While this is way more effort, i would suggest that you take route 2, as it is the "correct" way to do these things. Of Course, after you have built that child theme, you have to activate it for the changes to work.
Last but not least: DON'T DO THIS ON LIVE! Get yourself a backup of the site, and do the changes on local/a subsite/some other webspace and TEST IT before you put it on the live site! |
308,909 | <p>I have access to a single Linux/Apache server where I'm trying to deploy WordPress. For purposes of this error, I've tested it with the default twentyseventeen theme and all plugins disabled.</p>
<p>When I go to any wp-admin page, logged in as an administrator, most of the icons from the left navigation are missing, checked checkboxes have no checks (for example), and the browser console fills with JavaScript errors.</p>
<p>For example, on the dashboard page, none of the icons are visible and the error console reads like this:</p>
<pre><code>Uncaught TypeError: a.widget is not a function
at load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&ver=4.9.7:300
at load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&ver=4.9.7:300
at load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&ver=4.9.7:300
</code></pre>
<p>When I look in the network tab in the browser (I've looked in Chrome, Safari, and Firefox, and the host has looked as well), all requests return a 200 status. It does not seem like any requests are being blocked, at least.</p>
<p>If I add <code>SCRIPT_DEBUG=true</code> to the wp-config.php file, all these errors stop and the interface displays as it normally does.</p>
<p>I've been unable to reproduce this issue locally, and my host appears to be unable to tell me what is wrong (although they do see it). What can I tell them to look into, and/or what can I look into?</p>
<p>Update: to be more clear, my suspicion is that this could be a permissions issue on the server. Perhaps the server is unable to concatenate the files as WordPress expects. But the host has been unable to find anything to this effect, and I'm not knowledgeable enough about Linux/file permissions to know what to tell them to look for, or if that is even what is happening.</p>
| [
{
"answer_id": 308916,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 1,
"selected": false,
"text": "<p>Do you load own javascripts into the admin? If i recall correctly, if SCRIPT_DEBUG is set to true, th... | 2018/07/18 | [
"https://wordpress.stackexchange.com/questions/308909",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/41356/"
] | I have access to a single Linux/Apache server where I'm trying to deploy WordPress. For purposes of this error, I've tested it with the default twentyseventeen theme and all plugins disabled.
When I go to any wp-admin page, logged in as an administrator, most of the icons from the left navigation are missing, checked checkboxes have no checks (for example), and the browser console fills with JavaScript errors.
For example, on the dashboard page, none of the icons are visible and the error console reads like this:
```
Uncaught TypeError: a.widget is not a function
at load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&ver=4.9.7:300
at load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&ver=4.9.7:300
at load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&ver=4.9.7:300
```
When I look in the network tab in the browser (I've looked in Chrome, Safari, and Firefox, and the host has looked as well), all requests return a 200 status. It does not seem like any requests are being blocked, at least.
If I add `SCRIPT_DEBUG=true` to the wp-config.php file, all these errors stop and the interface displays as it normally does.
I've been unable to reproduce this issue locally, and my host appears to be unable to tell me what is wrong (although they do see it). What can I tell them to look into, and/or what can I look into?
Update: to be more clear, my suspicion is that this could be a permissions issue on the server. Perhaps the server is unable to concatenate the files as WordPress expects. But the host has been unable to find anything to this effect, and I'm not knowledgeable enough about Linux/file permissions to know what to tell them to look for, or if that is even what is happening. | Do you load own javascripts into the admin? If i recall correctly, if SCRIPT\_DEBUG is set to true, the javascripts are not concenated, but loaded seperately. So if a custom javascript doesn't play well being concenated, this can lead to the whole concenated javascript being corrupt and not being run correctly.
Try removing the added javascripts one by one and check if that changes anything. |
308,933 | <p>I try this:</p>
<pre><code><?php
function get_ct($id){
$ct = apply_filters('the_content', get_post_field('post_content', $id));
return $ct;
}
$arr = array('post_content' => get_ct(126));
echo json_encode($arr);
?>
</code></pre>
<p>but the post_content 's values ist null any suggestion? thanks</p>
| [
{
"answer_id": 308916,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 1,
"selected": false,
"text": "<p>Do you load own javascripts into the admin? If i recall correctly, if SCRIPT_DEBUG is set to true, th... | 2018/07/18 | [
"https://wordpress.stackexchange.com/questions/308933",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147160/"
] | I try this:
```
<?php
function get_ct($id){
$ct = apply_filters('the_content', get_post_field('post_content', $id));
return $ct;
}
$arr = array('post_content' => get_ct(126));
echo json_encode($arr);
?>
```
but the post\_content 's values ist null any suggestion? thanks | Do you load own javascripts into the admin? If i recall correctly, if SCRIPT\_DEBUG is set to true, the javascripts are not concenated, but loaded seperately. So if a custom javascript doesn't play well being concenated, this can lead to the whole concenated javascript being corrupt and not being run correctly.
Try removing the added javascripts one by one and check if that changes anything. |
308,941 | <p>In August, GDPR requires all websites to have a cookie notification on every page. I am creating a custom post type plugin - but I'm having one problem. The content from the custom post type page isn't being pulled in - it's pulling in the content from the page it is on. If I click on the permalink of the notice page - the content displays exactly as I want it. My guess is, because the plugin is on every page "the_content();" pull in the content from the page they are on. I need to know how to work around this.</p>
<p>Here is the code.</p>
<p>THE PLUGIN CODE:</p>
<pre><code><?php
/**
* Plugin Name: GDPR Cookie Notice
* Description: Adds a Pop-up notice bar on the bottom of the page for GDPR notifications
**/
defined( 'ABSPATH' ) or die( 'You Shall Not Pass!' );
function gdpr_create_post_type(){
$labels = array(
'name' => 'GDPR Notice', // => seperator for associative array key => value
'singular_name' => 'GDPR Notice',
'add_new' => 'Add New',
'add_new_item' => 'Add New GDPR Notice',
'edit_item' => 'Edit GDPR Notice',
'new_item' => 'New GDPR Notice',
'view_item' => 'View GDPR Notices',
'search_items' => 'Search GDPR Notices',
'not_found' => 'No GDPR Notices Found',
'not_found_in_trash' => 'No GDPR Notices Found in Trash'
);
$args = array(
'labels' => $labels,
'has_archive' => false, // these will be used in pages
'public' => true,
'hierarchical' => true, // behave like a page
'rewrite' => array(
'with_front' => false,
'slug' => 'gdpr-notice'
),
'menu_icon' => 'dashicons-id-alt',
'supports' => array(
'title',
'author',
'editor',
'custom-fields',
'page-attributes'
)
);
register_post_type('gdpr', $args);
}
add_action('init', 'gdpr_create_post_type');
</code></pre>
<p>?></p>
<p>THE HEADER.PHP FILE WHERE THE SINGLE PAGE TEMPLATE IS PULLED IN:</p>
<pre><code><header>
... main navigation code ...
</header>
<?php get_template_part('single', 'gdpr'); ?>
</code></pre>
<p>THE SINGLE-GDPR.PHP FILE:</p>
<pre><code><?php
/*
The file for the GDPR Cookie Notice post type, registered via a plugin
*/
?>
<div class="cookie-bar">
<section class="section float-me me-floated">
<div class="container">
<div class="row text-center">
<!-- I've added both editor and custom field filters to see if I can get even one to work -->
<?php if ( have_posts()) :
while ( have_posts()) : the_post();
the_content();
endwhile;
endif; ?>
<?php if ( have_posts()) :
while ( have_posts()) : the_post();
echo get_post_meta($post->ID, 'notice', true);
endwhile;
endif; ?>
</div>
</div>
</section>
</div>
</code></pre>
<p>WP ADMIN - GDPR Notice custom post type page</p>
<p>I'm trying two options – just to see if I can get one to work</p>
<p>WP Editor:
Read our privacy policy to learn more about how we use cookies.</p>
<p>Custom Field:
Name: notice
Value: Read our privacy policy to learn more about how we use cookies.</p>
<p>Thanks for any help you can give.</p>
| [
{
"answer_id": 308916,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 1,
"selected": false,
"text": "<p>Do you load own javascripts into the admin? If i recall correctly, if SCRIPT_DEBUG is set to true, th... | 2018/07/18 | [
"https://wordpress.stackexchange.com/questions/308941",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145059/"
] | In August, GDPR requires all websites to have a cookie notification on every page. I am creating a custom post type plugin - but I'm having one problem. The content from the custom post type page isn't being pulled in - it's pulling in the content from the page it is on. If I click on the permalink of the notice page - the content displays exactly as I want it. My guess is, because the plugin is on every page "the\_content();" pull in the content from the page they are on. I need to know how to work around this.
Here is the code.
THE PLUGIN CODE:
```
<?php
/**
* Plugin Name: GDPR Cookie Notice
* Description: Adds a Pop-up notice bar on the bottom of the page for GDPR notifications
**/
defined( 'ABSPATH' ) or die( 'You Shall Not Pass!' );
function gdpr_create_post_type(){
$labels = array(
'name' => 'GDPR Notice', // => seperator for associative array key => value
'singular_name' => 'GDPR Notice',
'add_new' => 'Add New',
'add_new_item' => 'Add New GDPR Notice',
'edit_item' => 'Edit GDPR Notice',
'new_item' => 'New GDPR Notice',
'view_item' => 'View GDPR Notices',
'search_items' => 'Search GDPR Notices',
'not_found' => 'No GDPR Notices Found',
'not_found_in_trash' => 'No GDPR Notices Found in Trash'
);
$args = array(
'labels' => $labels,
'has_archive' => false, // these will be used in pages
'public' => true,
'hierarchical' => true, // behave like a page
'rewrite' => array(
'with_front' => false,
'slug' => 'gdpr-notice'
),
'menu_icon' => 'dashicons-id-alt',
'supports' => array(
'title',
'author',
'editor',
'custom-fields',
'page-attributes'
)
);
register_post_type('gdpr', $args);
}
add_action('init', 'gdpr_create_post_type');
```
?>
THE HEADER.PHP FILE WHERE THE SINGLE PAGE TEMPLATE IS PULLED IN:
```
<header>
... main navigation code ...
</header>
<?php get_template_part('single', 'gdpr'); ?>
```
THE SINGLE-GDPR.PHP FILE:
```
<?php
/*
The file for the GDPR Cookie Notice post type, registered via a plugin
*/
?>
<div class="cookie-bar">
<section class="section float-me me-floated">
<div class="container">
<div class="row text-center">
<!-- I've added both editor and custom field filters to see if I can get even one to work -->
<?php if ( have_posts()) :
while ( have_posts()) : the_post();
the_content();
endwhile;
endif; ?>
<?php if ( have_posts()) :
while ( have_posts()) : the_post();
echo get_post_meta($post->ID, 'notice', true);
endwhile;
endif; ?>
</div>
</div>
</section>
</div>
```
WP ADMIN - GDPR Notice custom post type page
I'm trying two options – just to see if I can get one to work
WP Editor:
Read our privacy policy to learn more about how we use cookies.
Custom Field:
Name: notice
Value: Read our privacy policy to learn more about how we use cookies.
Thanks for any help you can give. | Do you load own javascripts into the admin? If i recall correctly, if SCRIPT\_DEBUG is set to true, the javascripts are not concenated, but loaded seperately. So if a custom javascript doesn't play well being concenated, this can lead to the whole concenated javascript being corrupt and not being run correctly.
Try removing the added javascripts one by one and check if that changes anything. |
308,950 | <p>I have a question about <a href="https://codex.wordpress.org/Post_Types#Custom_Post_Types" rel="nofollow noreferrer">this</a> documentation.</p>
<p>Why would I register a Custom Post Type in the init function as the docs suggest? Is this only if I am not using a plugin?</p>
<p>As I understand it, <a href="https://codex.wordpress.org/Plugin_API/Action_Reference/init" rel="nofollow noreferrer">init runs every-time WordPress runs/is-loaded</a> by the user. Doesn't this mean the site is needlessly re-registering a new post type on every visit? Why not (if building a plugin) register the post type in <code>require_once plugin_dir_path( __FILE__ )</code> just when the plugin activates?</p>
<p>Wouldn't that also speed up the site? Or am I interpreting <code>init()</code> wrong? Surely the custom post type persists in the database somewhere so doesn't have to be called on every <code>init()</code>?</p>
<p>Here is the Custom Post Type example from the docs, using <code>init()</code>:</p>
<pre><code>function create_post_type() {
register_post_type( 'acme_product',
array(
'labels' => array(
'name' => __( 'Products' ),
'singular_name' => __( 'Product' )
),
'public' => true,
'has_archive' => true,
)
);
}
add_action( 'init', 'create_post_type' );
</code></pre>
| [
{
"answer_id": 308951,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 3,
"selected": true,
"text": "<p><code>register_post_type</code> function should be executed every time a WP request is made. De... | 2018/07/18 | [
"https://wordpress.stackexchange.com/questions/308950",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77764/"
] | I have a question about [this](https://codex.wordpress.org/Post_Types#Custom_Post_Types) documentation.
Why would I register a Custom Post Type in the init function as the docs suggest? Is this only if I am not using a plugin?
As I understand it, [init runs every-time WordPress runs/is-loaded](https://codex.wordpress.org/Plugin_API/Action_Reference/init) by the user. Doesn't this mean the site is needlessly re-registering a new post type on every visit? Why not (if building a plugin) register the post type in `require_once plugin_dir_path( __FILE__ )` just when the plugin activates?
Wouldn't that also speed up the site? Or am I interpreting `init()` wrong? Surely the custom post type persists in the database somewhere so doesn't have to be called on every `init()`?
Here is the Custom Post Type example from the docs, using `init()`:
```
function create_post_type() {
register_post_type( 'acme_product',
array(
'labels' => array(
'name' => __( 'Products' ),
'singular_name' => __( 'Product' )
),
'public' => true,
'has_archive' => true,
)
);
}
add_action( 'init', 'create_post_type' );
``` | `register_post_type` function should be executed every time a WP request is made. Default post types don't have this requirement. You can use your code as is, in MU plugin. Just create a `.PHP` file with this code, and place it in `mu-plugins` sub-folder of `wp-content`. You don't need to provide any standard plugin headers. |
308,953 | <p>I am converting a static website made with Bootstrap in WordPress.
Here is my bootstrap multilevel navigation menu code: </p>
<pre><code><section class="menuBar">
<nav class="navbar navbar-expand-lg navbar-light" data-toggle="sticky-onscroll">
<div class="container">
<button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#mainNavbar" aria-controls="mainNavbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse" id="mainNavbar" style="">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Commercial Appliances</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item dropdown-toggle" href="#">Refrigeration</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Refrigerators</a></li>
<li><a class="dropdown-item" href="#">Freezers</a></li>
<li><a class="dropdown-item" href="#">Walk-in Coolers/Refrigerators</a></li>
<li><a class="dropdown-item" href="#">Walk-in Freezers</a></li>
<li><a class="dropdown-item" href="#">Commercial Freezers</a></li>
<li><a class="dropdown-item" href="#">Commercial Refrigerators</a></li>
<li><a class="dropdown-item" href="#">Salad Bars</a></li>
<li><a class="dropdown-item" href="#">Sandwich Coolers</a></li>
<li><a class="dropdown-item" href="#">Wine Coolers</a></li>
<li><a class="dropdown-item" href="#">Ice Machines</a></li>
<li><a class="dropdown-item" href="#">Beer Coolers</a></li>
<li><a class="dropdown-item" href="#">Kegerators</a></li>
<li><a class="dropdown-item" href="#">Flower Coolers</a></li>
<li><a class="dropdown-item" href="#">Remote Condensers</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Cooking Equipment</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Commercial Ovens</a></li>
<li><a class="dropdown-item" href="#">Stoves/Ranges</a></li>
<li><a class="dropdown-item" href="#">Cooktops</a></li>
<li><a class="dropdown-item" href="#">Convection Ovens</a></li>
<li><a class="dropdown-item" href="#">Salamander Ovens/Broilers</a></li>
<li><a class="dropdown-item" href="#">Double Ovens</a></li>
<li><a class="dropdown-item" href="#">Grills</a></li>
<li><a class="dropdown-item" href="#">Wall Ovens</a></li>
</ul>
</li>
<li><a class="dropdown-item" href="#">Microwaves</a></li>
<li><a class="dropdown-item dropdown-toggle" href="#">Griddles</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Hot Plates</a></li>
<li><a class="dropdown-item" href="#">Wok Ranges</a></li>
<li><a class="dropdown-item" href="#">Warmers</a></li>
<li><a class="dropdown-item" href="#">Deep Fryers</a></li>
<li><a class="dropdown-item" href="#">Steam Table</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Ice Machines / Ice Makers</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Countertop</a></li>
<li><a class="dropdown-item" href="#">Remote condenser</a></li>
<li><a class="dropdown-item" href="#">Modular</a></li>
<li><a class="dropdown-item" href="#">Under counter</a></li>
<li><a class="dropdown-item" href="#">Water filters</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Commercial Dishwashers</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Door Type</a></li>
<li><a class="dropdown-item" href="#">Conveyor Type</a></li>
<li><a class="dropdown-item" href="#">Under counter</a></li>
<li><a class="dropdown-item" href="#">Glasswasher</a></li>
<li><a class="dropdown-item" href="#">High Temperature Dishwashers</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Commercial Laundry</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Washers</a></li>
<li><a class="dropdown-item" href="#">Tumble Dryers (Gas/Electric)</a></li>
<li><a class="dropdown-item" href="#">Coin-operated Washer / Dryer</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Ventilation / Exhaust</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Commercial Kitchen Hoods</a></li>
<li><a class="dropdown-item" href="#">Exhaust Fans</a></li>
<li><a class="dropdown-item" href="#">Direct Drive Fans</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Water Heaters</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Electric / Gas Tankless Heaters</a></li>
<li><a class="dropdown-item" href="#">Electric / Gas Tank Heaters</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Garbage Disposals</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Food Wasters</a></li>
</ul>
</li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Residential Appliances</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Refrigerators / Freezers</a></li>
<li><a class="dropdown-item" href="#">Wine Cooler</a></li>
<li><a class="dropdown-item" href="#">Ice Makers</a></li>
<li><a class="dropdown-item" href="#">Washer Machine</a></li>
<li><a class="dropdown-item" href="#">Gas / Electric Dryer</a></li>
<li><a class="dropdown-item" href="#">Wall Ovens</a></li>
<li><a class="dropdown-item" href="#">Double Ovens</a></li>
<li><a class="dropdown-item" href="#">Ranges</a></li>
<li><a class="dropdown-item" href="#">Cooktops</a></li>
<li><a class="dropdown-item" href="#">Microwaves</a></li>
<li><a class="dropdown-item" href="#">Dishwasher</a></li>
<li><a class="dropdown-item" href="#">Garbage Disposal</a></li>
<li><a class="dropdown-item" href="#">Vent Hood</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">HVAC</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Split system </a></li>
<li><a class="dropdown-item" href="#">Minisplit Ductless systems</a></li>
<li><a class="dropdown-item" href="#">Packaged System</a></li>
<li><a class="dropdown-item" href="#">Gas / Electric Furnace</a></li>
<li><a class="dropdown-item" href="#">Heat Pumps</a></li>
<li><a class="dropdown-item" href="#">Evaporator Coils</a></li>
<li><a class="dropdown-item" href="#">Thermostat</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Installation</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item dropdown-toggle" href="#">Refrigeration Equipment</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Walk-in Cooler Installation</a></li>
<li><a class="dropdown-item" href="#">Ice Machine</a></li>
</ul>
</li>
<li><a class="dropdown-item" href="#">Cooking Equipment</a></li>
<li><a class="dropdown-item" href="#">Commercial Dishwashers</a></li>
<li><a class="dropdown-item dropdown-toggle" href="#">Commercial Laundry</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Washers</a></li>
<li><a class="dropdown-item" href="#">Dryers</a></li>
</ul>
</li>
<li><a class="dropdown-item" href="#">HVAC</a></li>
<li><a class="dropdown-item" href="#">Ventilation / Exhaust</a></li>
<li><a class="dropdown-item" href="#">Water Heaters</a></li>
<li><a class="dropdown-item" href="#">Garbage Disposals</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link" href="maintenance-programs.php">Maintenance Programs</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.php">Contact Us</a>
</li>
</ul>
</div>
<a class="btn btn-red" href="#">Book Now</a>
</div>
</nav>
</section>
</code></pre>
<p>And it's working fine for me:
<a href="https://i.stack.imgur.com/UCVhR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UCVhR.jpg" alt="enter image description here"></a></p>
<p>But to in WordPress, I have used WP_Bootstrap_Navwalker() for the navigation menu. I have put depth => 3 but it's not showing multi level menu as expected. Here is my code: </p>
<pre><code><?php
wp_nav_menu( array(
'theme_location' => 'primary',
'depth' => 3,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'mainNavbar',
'menu_class' => 'navbar-nav',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker()
) );
?>
</code></pre>
<p>But it's just working for dropdown only. It's not showing submenu of submenu. How can I fix this problem? </p>
<p><a href="https://i.stack.imgur.com/ZuNdV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZuNdV.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 308957,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Here some thing interesting for you</p>\n\n<p><strong>STEP 1</strong>\nadd a script to header like below ( it's al... | 2018/07/18 | [
"https://wordpress.stackexchange.com/questions/308953",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137372/"
] | I am converting a static website made with Bootstrap in WordPress.
Here is my bootstrap multilevel navigation menu code:
```
<section class="menuBar">
<nav class="navbar navbar-expand-lg navbar-light" data-toggle="sticky-onscroll">
<div class="container">
<button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#mainNavbar" aria-controls="mainNavbar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse" id="mainNavbar" style="">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Commercial Appliances</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item dropdown-toggle" href="#">Refrigeration</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Refrigerators</a></li>
<li><a class="dropdown-item" href="#">Freezers</a></li>
<li><a class="dropdown-item" href="#">Walk-in Coolers/Refrigerators</a></li>
<li><a class="dropdown-item" href="#">Walk-in Freezers</a></li>
<li><a class="dropdown-item" href="#">Commercial Freezers</a></li>
<li><a class="dropdown-item" href="#">Commercial Refrigerators</a></li>
<li><a class="dropdown-item" href="#">Salad Bars</a></li>
<li><a class="dropdown-item" href="#">Sandwich Coolers</a></li>
<li><a class="dropdown-item" href="#">Wine Coolers</a></li>
<li><a class="dropdown-item" href="#">Ice Machines</a></li>
<li><a class="dropdown-item" href="#">Beer Coolers</a></li>
<li><a class="dropdown-item" href="#">Kegerators</a></li>
<li><a class="dropdown-item" href="#">Flower Coolers</a></li>
<li><a class="dropdown-item" href="#">Remote Condensers</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Cooking Equipment</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Commercial Ovens</a></li>
<li><a class="dropdown-item" href="#">Stoves/Ranges</a></li>
<li><a class="dropdown-item" href="#">Cooktops</a></li>
<li><a class="dropdown-item" href="#">Convection Ovens</a></li>
<li><a class="dropdown-item" href="#">Salamander Ovens/Broilers</a></li>
<li><a class="dropdown-item" href="#">Double Ovens</a></li>
<li><a class="dropdown-item" href="#">Grills</a></li>
<li><a class="dropdown-item" href="#">Wall Ovens</a></li>
</ul>
</li>
<li><a class="dropdown-item" href="#">Microwaves</a></li>
<li><a class="dropdown-item dropdown-toggle" href="#">Griddles</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Hot Plates</a></li>
<li><a class="dropdown-item" href="#">Wok Ranges</a></li>
<li><a class="dropdown-item" href="#">Warmers</a></li>
<li><a class="dropdown-item" href="#">Deep Fryers</a></li>
<li><a class="dropdown-item" href="#">Steam Table</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Ice Machines / Ice Makers</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Countertop</a></li>
<li><a class="dropdown-item" href="#">Remote condenser</a></li>
<li><a class="dropdown-item" href="#">Modular</a></li>
<li><a class="dropdown-item" href="#">Under counter</a></li>
<li><a class="dropdown-item" href="#">Water filters</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Commercial Dishwashers</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Door Type</a></li>
<li><a class="dropdown-item" href="#">Conveyor Type</a></li>
<li><a class="dropdown-item" href="#">Under counter</a></li>
<li><a class="dropdown-item" href="#">Glasswasher</a></li>
<li><a class="dropdown-item" href="#">High Temperature Dishwashers</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Commercial Laundry</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Washers</a></li>
<li><a class="dropdown-item" href="#">Tumble Dryers (Gas/Electric)</a></li>
<li><a class="dropdown-item" href="#">Coin-operated Washer / Dryer</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Ventilation / Exhaust</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Commercial Kitchen Hoods</a></li>
<li><a class="dropdown-item" href="#">Exhaust Fans</a></li>
<li><a class="dropdown-item" href="#">Direct Drive Fans</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Water Heaters</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Electric / Gas Tankless Heaters</a></li>
<li><a class="dropdown-item" href="#">Electric / Gas Tank Heaters</a></li>
</ul>
</li>
<li><a class="dropdown-item dropdown-toggle" href="#">Garbage Disposals</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Food Wasters</a></li>
</ul>
</li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Residential Appliances</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Refrigerators / Freezers</a></li>
<li><a class="dropdown-item" href="#">Wine Cooler</a></li>
<li><a class="dropdown-item" href="#">Ice Makers</a></li>
<li><a class="dropdown-item" href="#">Washer Machine</a></li>
<li><a class="dropdown-item" href="#">Gas / Electric Dryer</a></li>
<li><a class="dropdown-item" href="#">Wall Ovens</a></li>
<li><a class="dropdown-item" href="#">Double Ovens</a></li>
<li><a class="dropdown-item" href="#">Ranges</a></li>
<li><a class="dropdown-item" href="#">Cooktops</a></li>
<li><a class="dropdown-item" href="#">Microwaves</a></li>
<li><a class="dropdown-item" href="#">Dishwasher</a></li>
<li><a class="dropdown-item" href="#">Garbage Disposal</a></li>
<li><a class="dropdown-item" href="#">Vent Hood</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">HVAC</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Split system </a></li>
<li><a class="dropdown-item" href="#">Minisplit Ductless systems</a></li>
<li><a class="dropdown-item" href="#">Packaged System</a></li>
<li><a class="dropdown-item" href="#">Gas / Electric Furnace</a></li>
<li><a class="dropdown-item" href="#">Heat Pumps</a></li>
<li><a class="dropdown-item" href="#">Evaporator Coils</a></li>
<li><a class="dropdown-item" href="#">Thermostat</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Installation</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item dropdown-toggle" href="#">Refrigeration Equipment</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Walk-in Cooler Installation</a></li>
<li><a class="dropdown-item" href="#">Ice Machine</a></li>
</ul>
</li>
<li><a class="dropdown-item" href="#">Cooking Equipment</a></li>
<li><a class="dropdown-item" href="#">Commercial Dishwashers</a></li>
<li><a class="dropdown-item dropdown-toggle" href="#">Commercial Laundry</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Washers</a></li>
<li><a class="dropdown-item" href="#">Dryers</a></li>
</ul>
</li>
<li><a class="dropdown-item" href="#">HVAC</a></li>
<li><a class="dropdown-item" href="#">Ventilation / Exhaust</a></li>
<li><a class="dropdown-item" href="#">Water Heaters</a></li>
<li><a class="dropdown-item" href="#">Garbage Disposals</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link" href="maintenance-programs.php">Maintenance Programs</a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact.php">Contact Us</a>
</li>
</ul>
</div>
<a class="btn btn-red" href="#">Book Now</a>
</div>
</nav>
</section>
```
And it's working fine for me:
[](https://i.stack.imgur.com/UCVhR.jpg)
But to in WordPress, I have used WP\_Bootstrap\_Navwalker() for the navigation menu. I have put depth => 3 but it's not showing multi level menu as expected. Here is my code:
```
<?php
wp_nav_menu( array(
'theme_location' => 'primary',
'depth' => 3,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'mainNavbar',
'menu_class' => 'navbar-nav',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker()
) );
?>
```
But it's just working for dropdown only. It's not showing submenu of submenu. How can I fix this problem?
[](https://i.stack.imgur.com/ZuNdV.jpg) | Here some thing interesting for you
**STEP 1**
add a script to header like below ( it's always better go for the enqueue method . i need some one to help me with properly adding the below script in WordPress way .jquery should run before the second script>
```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {
if (!$(this).next().hasClass('show')) {
$(this).parents('.dropdown-menu').first().find('.show').removeClass("show");
}
var $subMenu = $(this).next(".dropdown-menu");
$subMenu.toggleClass('show');
$(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {
$('.dropdown-submenu .show').removeClass("show");
});
return false;
});
});
</script>
```
**STEP 2**
Add the css like below :
```
.dropdown-submenu {
position: relative;
}
.dropdown-submenu a::after {
transform: rotate(-90deg);
position: absolute;
right: 6px;
top: .8em;
}
.dropdown-submenu .dropdown-menu {
top: 0;
left: 100%;
margin-left: .1rem;
margin-right: .1rem;
}
/* to show the arrow */
.dropdown-submenu a::after {
transform: rotate(-90deg);
position: absolute;
right: 6px;
top: .8em;
}
.dropdown-toggle a::after{
transform: rotate(-90deg);
position: absolute;
right: 6px;
top: .8em;
}
```
**STEP 3**
Now go inside the walker class :
search for `&& 0 === $depth` and remove it. Also make sure that
`'depth' => 3`
Now it should start showing the 3rd level menu . some additional css might be required.
This is being added up in header :
```
wp_nav_menu( array(
'theme_location' => 'primary',
'depth' => 3,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bs-example-navbar-collapse-1',
'menu_class' => 'nav navbar-nav',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker(),
) );
``` |
308,959 | <p>I have a blog. My computer crashed months ago, my username is <code>admin</code> I have tried to recover my password but as it is lost create a new one, they sent a huge long address password will not let me copy and I just do not know what to do. I have recently paid for hosting the site again and can't use my dashboard.</p>
| [
{
"answer_id": 308957,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Here some thing interesting for you</p>\n\n<p><strong>STEP 1</strong>\nadd a script to header like below ( it's al... | 2018/07/19 | [
"https://wordpress.stackexchange.com/questions/308959",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147180/"
] | I have a blog. My computer crashed months ago, my username is `admin` I have tried to recover my password but as it is lost create a new one, they sent a huge long address password will not let me copy and I just do not know what to do. I have recently paid for hosting the site again and can't use my dashboard. | Here some thing interesting for you
**STEP 1**
add a script to header like below ( it's always better go for the enqueue method . i need some one to help me with properly adding the below script in WordPress way .jquery should run before the second script>
```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {
if (!$(this).next().hasClass('show')) {
$(this).parents('.dropdown-menu').first().find('.show').removeClass("show");
}
var $subMenu = $(this).next(".dropdown-menu");
$subMenu.toggleClass('show');
$(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {
$('.dropdown-submenu .show').removeClass("show");
});
return false;
});
});
</script>
```
**STEP 2**
Add the css like below :
```
.dropdown-submenu {
position: relative;
}
.dropdown-submenu a::after {
transform: rotate(-90deg);
position: absolute;
right: 6px;
top: .8em;
}
.dropdown-submenu .dropdown-menu {
top: 0;
left: 100%;
margin-left: .1rem;
margin-right: .1rem;
}
/* to show the arrow */
.dropdown-submenu a::after {
transform: rotate(-90deg);
position: absolute;
right: 6px;
top: .8em;
}
.dropdown-toggle a::after{
transform: rotate(-90deg);
position: absolute;
right: 6px;
top: .8em;
}
```
**STEP 3**
Now go inside the walker class :
search for `&& 0 === $depth` and remove it. Also make sure that
`'depth' => 3`
Now it should start showing the 3rd level menu . some additional css might be required.
This is being added up in header :
```
wp_nav_menu( array(
'theme_location' => 'primary',
'depth' => 3,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bs-example-navbar-collapse-1',
'menu_class' => 'nav navbar-nav',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker(),
) );
``` |
308,970 | <p>I have a widget located at <code>/child-theme/includes/custom-widget.php</code>.</p>
<p>How do I call <code>register_widget</code> and reference that widget?</p>
<p>I've tried something like the following inside <code>functions.php</code>:</p>
<pre><code>function SER_register_widgets() {
register_widget( 'includes/custom-widget.php' );
}
add_action( 'widgets_init', 'SER_register_widgets' );
</code></pre>
<p>but this does not work.</p>
<p>Help appreciated.</p>
| [
{
"answer_id": 308972,
"author": "maverick",
"author_id": 132953,
"author_profile": "https://wordpress.stackexchange.com/users/132953",
"pm_score": 3,
"selected": true,
"text": "<p>include that file in your functions.php file like </p>\n\n<p><code>require_once('includes/custom-widgets.ph... | 2018/07/19 | [
"https://wordpress.stackexchange.com/questions/308970",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147186/"
] | I have a widget located at `/child-theme/includes/custom-widget.php`.
How do I call `register_widget` and reference that widget?
I've tried something like the following inside `functions.php`:
```
function SER_register_widgets() {
register_widget( 'includes/custom-widget.php' );
}
add_action( 'widgets_init', 'SER_register_widgets' );
```
but this does not work.
Help appreciated. | include that file in your functions.php file like
`require_once('includes/custom-widgets.php');`
then you can call `add_action()` hook, in your case
`add_action('widgets_init', 'SER_register_widgets'); .`
the idea is to make that function ( ser\_register\_widgets ) visible in current php file ( functions.php file in this case ) |
308,994 | <p>I need to show the post featured image at the desired position on my theme template. At the same time, I need its width to be 300px and the height- adaptive.</p>
<p>What code should I add to my template?</p>
| [
{
"answer_id": 308995,
"author": "Guillermo Carone",
"author_id": 76897,
"author_profile": "https://wordpress.stackexchange.com/users/76897",
"pm_score": 0,
"selected": false,
"text": "<p>f you want the width of the image to be fixed and the height to change you should look into creating... | 2018/07/19 | [
"https://wordpress.stackexchange.com/questions/308994",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145504/"
] | I need to show the post featured image at the desired position on my theme template. At the same time, I need its width to be 300px and the height- adaptive.
What code should I add to my template? | You can create custom size image with [`add_image_size()`](https://developer.wordpress.org/reference/functions/add_image_size/) in the functions.php
```
function add_custom_size_images() {
// Add image size width 300 with unlimited height.
add_image_size( 'featured-image-300', 300 );
}
add_action( 'after_setup_theme', 'add_custom_size_images' );
```
And in the template to get the size that you created with [`the_post_thumbnail()`](https://developer.wordpress.org/reference/functions/the_post_thumbnail/)
```
the_post_thumbnail( 'featured-image-300' );
```
**Notice:** If you want it to work with the old images that you uploaded already you need to regenarate the thumbnails. There are some plugins for this.
Plugin for example <https://wordpress.org/plugins/regenerate-thumbnails/> |
309,007 | <p>I have set up a custom post type, which user can edit from the frontend. I'm using <code>wp_delete_post()</code> to allow users to delete a post they created. It works, but the posts get deleted instead of being moved to trash.<p>I have tried moving a post to the bin via the backend and it works like you would expect it, the post is moved to the Bin. So I'm not sure why the <code>wp_delete_post</code> doesn't work the same way, but permanently removes the post instead.</p> <p>According to the WordPress Codex, the second parameter of the <code>wp_delete_post()</code> function is a boolean, which, if set to false, should move the post to trash, not permanently delete it. The second parameter is set to false by default, so this is my code: <p><code>wp_delete_post( $race->ID );</code></p><p>I'm aware that I can use the <code>wp_trash_post()</code> function instead (which is actually what I'm using now, since the <code>wp_delete_post</code>, doesn't do what I want it to do), but I would like to find out why the <code>wp_delete_post()</code> function doesn't work correctly.</p></p>
| [
{
"answer_id": 309013,
"author": "Hồ Trọng Linh Ân",
"author_id": 141631,
"author_profile": "https://wordpress.stackexchange.com/users/141631",
"pm_score": 4,
"selected": true,
"text": "<p>Following the line of code</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.9/src... | 2018/07/19 | [
"https://wordpress.stackexchange.com/questions/309007",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136877/"
] | I have set up a custom post type, which user can edit from the frontend. I'm using `wp_delete_post()` to allow users to delete a post they created. It works, but the posts get deleted instead of being moved to trash.I have tried moving a post to the bin via the backend and it works like you would expect it, the post is moved to the Bin. So I'm not sure why the `wp_delete_post` doesn't work the same way, but permanently removes the post instead.
According to the WordPress Codex, the second parameter of the `wp_delete_post()` function is a boolean, which, if set to false, should move the post to trash, not permanently delete it. The second parameter is set to false by default, so this is my code: `wp_delete_post( $race->ID );`
I'm aware that I can use the `wp_trash_post()` function instead (which is actually what I'm using now, since the `wp_delete_post`, doesn't do what I want it to do), but I would like to find out why the `wp_delete_post()` function doesn't work correctly. | Following the line of code
<https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/post.php#L2467>
```
if ( ! $force_delete && ( 'post' === $post->post_type || 'page' === $post->post_type ) && 'trash' !== get_post_status( $postid ) && EMPTY_TRASH_DAYS ) {
return wp_trash_post( $postid );
}
```
the $force\_delete just work with 'post' and 'page', it not work with custom post type |
309,008 | <p>I would like to do the following:</p>
<p>Registered users in my wordpress application can receive messages. They can choose to receive messages in the following ways:</p>
<ul>
<li>The Wordpress application (Inbox system)</li>
<li>SMS message</li>
<li>Email</li>
</ul>
<p>I would like to use the <a href="https://nl.wordpress.org/plugins/front-end-pm/" rel="nofollow noreferrer">Front End PM plugin</a> to send messages in portal. For the sms messages I would use the <a href="https://nl.wordpress.org/plugins/wp-twilio-core/" rel="nofollow noreferrer">Twilio plugin</a>. </p>
<p>So when they sent a message (functionality by Front end PM plugin) I would like to call another function in the Twilio plugin to send an SMS.</p>
<p>What's the proper way to do this? I don't think editing the function in the Front End PM plugin is the correct way to do this? How should it be done?</p>
| [
{
"answer_id": 309383,
"author": "Deleyna",
"author_id": 147443,
"author_profile": "https://wordpress.stackexchange.com/users/147443",
"pm_score": 0,
"selected": false,
"text": "<p>Disclaimer: I'm a relatively new developer and don't know those plugins so my suggestions are general.</p>\... | 2018/07/19 | [
"https://wordpress.stackexchange.com/questions/309008",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65180/"
] | I would like to do the following:
Registered users in my wordpress application can receive messages. They can choose to receive messages in the following ways:
* The Wordpress application (Inbox system)
* SMS message
* Email
I would like to use the [Front End PM plugin](https://nl.wordpress.org/plugins/front-end-pm/) to send messages in portal. For the sms messages I would use the [Twilio plugin](https://nl.wordpress.org/plugins/wp-twilio-core/).
So when they sent a message (functionality by Front end PM plugin) I would like to call another function in the Twilio plugin to send an SMS.
What's the proper way to do this? I don't think editing the function in the Front End PM plugin is the correct way to do this? How should it be done? | Levi Dulstein has a lot of righ, but in my opinion Front-end-pm uses two hooks to send messages:
* fep\_save\_message (from back-end)
* fep\_action\_message\_after\_send (from front-end)
Before sending a email few things are checked, like publishig or sending status (includes/class-fep-emails.php):
```
function save_send_email( $postid, $post ) {
if ( ! $post instanceof WP_Post ) {
$post = get_post( $postid );
}
if ( 'publish' != $post->post_status ){
return;
}
if ( get_post_meta( $postid, '_fep_email_sent', true ) ){
return;
}
$this->send_email( $postid, $post );
}
```
So, for test try add something like this to your plugin or theme:
```
function send_sms( $postid, $post ) {
if ( ! $post instanceof WP_Post ) {
$post = get_post( $postid );
}
if ( 'publish' != $post->post_status ){
return;
}
if ( get_post_meta( $postid, '_fep_email_sent', true ) ){
return;
}
// use Twilio plugin function twl_send_sms
if( function_exists('twl_send_sms') ) {
$participants = fep_get_participants( $postid );
// check if recipients exists, for each get the phone number,
// send message and mark sms as sent (or save sms send time)
$args = array(
'message' => $post->post_title, // or $post->post_content
);
foreach ($participants as $participant) {
// get usermeta with phone number for $participant ID
$args['number_to'] = '098765';
twl_send_sms( $args );
}
}
}
add_action( 'fep_save_message', 'send_sms', 99, 2 ); //sending from back-end
add_action( 'fep_action_message_after_send , 'send_sms', 99, 2 ); //front-end
```
Sorry for my english. I hope you understand what I want to say. |
309,043 | <p>I have all terms in English and I am creating/duplicating the same ones for German language by using foreach on english terms and this way i create all terms for German language. </p>
<p>The problem is when i need to assign an German term to its English version.</p>
<p>I tried the trick with TRID like this: </p>
<pre><code>$trid = $sitepress->get_element_trid($englist_term_id, "taxonomy_name");
$sitepress->set_element_language_details($new_term_id, "taxonomy_name", $trid, $lang_code, $sitepress->get_default_language());
</code></pre>
<p>The problem is that $trid does not take any value (The first line of the above code)</p>
<p>Probably there is some other way to accomplish this!</p>
| [
{
"answer_id": 309046,
"author": "Agon Xheladini",
"author_id": 86433,
"author_profile": "https://wordpress.stackexchange.com/users/86433",
"pm_score": 1,
"selected": false,
"text": "<p>Ok I found the solution. </p>\n\n<p>Actually taxonomy name on icl_translation table is stored with pre... | 2018/07/19 | [
"https://wordpress.stackexchange.com/questions/309043",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86433/"
] | I have all terms in English and I am creating/duplicating the same ones for German language by using foreach on english terms and this way i create all terms for German language.
The problem is when i need to assign an German term to its English version.
I tried the trick with TRID like this:
```
$trid = $sitepress->get_element_trid($englist_term_id, "taxonomy_name");
$sitepress->set_element_language_details($new_term_id, "taxonomy_name", $trid, $lang_code, $sitepress->get_default_language());
```
The problem is that $trid does not take any value (The first line of the above code)
Probably there is some other way to accomplish this! | Ok I found the solution.
Actually taxonomy name on icl\_translation table is stored with prefix called "tax\_" which means taxonomy. The above code would work like this:
```
$trid = $sitepress->get_element_trid($englist_term_id, "tax_taxonomy_name");
$sitepress->set_element_language_details($new_term_id, "tax_taxonomy_name", $trid, $lang_code, $sitepress->get_default_language());
```
The difference is tax\_ prefix.
Cheers! |
309,065 | <p><strong>Background</strong></p>
<p>I am using the theme Rookie from Sportpress.</p>
<p>I created a child theme.</p>
<p>Translation files are existing, especially german in my case.</p>
<p>Wordpress is set to german language.</p>
<p><strong>The Problem</strong></p>
<p>Translation is working fine everywhere except on themes provided templates like the search results page content or pagination.</p>
<p>Affected are the SRP title, nothing found page title and nothing found page content. They just stay in default english language.
Pagination is affected too.</p>
<p>The search form in the content of a nothing found page is translated fine. I guess because it's Wordpress default template.</p>
<p><strong>Code</strong></p>
<p>here some affected code lines from the parent theme.</p>
<p>Search Title</p>
<pre><code><h1 class="page-title entry-title"><?php printf( __( 'Search Results for: %s', 'rookie' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
</code></pre>
<p>Nothing Found title:</p>
<pre><code><h1 class="page-title"><?php _e( 'Nothing Found', 'rookie' ); ?></h1>
</code></pre>
<p>Nothing found text:</p>
<pre><code><p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'rookie' ); ?></p>
</code></pre>
<p>Pagination:</p>
<pre><code><?php if ( get_next_posts_link() ) : ?>
<div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts', 'rookie' ) ); ?></div>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&rarr;</span>', 'rookie' ) ); ?></div>
<?php endif; ?>
</code></pre>
<p><strong>Findings</strong></p>
<p>I checked that the .mo entry for german is existing with the Loco translate plugin.</p>
<p>I replaced the Search Result Title <code>Search Results for: %s</code> with the Category Title <code>Category: %s</code>, which gets translated on a category page (because category archive title is provided from Wordpress), but also not on the SRP!</p>
<p><em>What could be a reason for this behaviour?</em></p>
<p><strong>Workaround</strong></p>
<p>the parent theme is loading the domain via
<code>load_theme_textdomain( 'rookie', get_template_directory() . '/languages' );</code> and points to right location where all translation files (.pot, de_DE.po and de_DE.mo) are existing.</p>
<p>I copied the relevant .po and .mo files over to wp-content/languages/themes/ directory and things are working now.</p>
<p><em>But is this the real best solution?</em></p>
| [
{
"answer_id": 309077,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": -1,
"selected": false,
"text": "<p>Putting files in <code>wp-content/languages/themes/</code> is not a good idea because on the next update, the fi... | 2018/07/20 | [
"https://wordpress.stackexchange.com/questions/309065",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136930/"
] | **Background**
I am using the theme Rookie from Sportpress.
I created a child theme.
Translation files are existing, especially german in my case.
Wordpress is set to german language.
**The Problem**
Translation is working fine everywhere except on themes provided templates like the search results page content or pagination.
Affected are the SRP title, nothing found page title and nothing found page content. They just stay in default english language.
Pagination is affected too.
The search form in the content of a nothing found page is translated fine. I guess because it's Wordpress default template.
**Code**
here some affected code lines from the parent theme.
Search Title
```
<h1 class="page-title entry-title"><?php printf( __( 'Search Results for: %s', 'rookie' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
```
Nothing Found title:
```
<h1 class="page-title"><?php _e( 'Nothing Found', 'rookie' ); ?></h1>
```
Nothing found text:
```
<p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'rookie' ); ?></p>
```
Pagination:
```
<?php if ( get_next_posts_link() ) : ?>
<div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">←</span> Older posts', 'rookie' ) ); ?></div>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>', 'rookie' ) ); ?></div>
<?php endif; ?>
```
**Findings**
I checked that the .mo entry for german is existing with the Loco translate plugin.
I replaced the Search Result Title `Search Results for: %s` with the Category Title `Category: %s`, which gets translated on a category page (because category archive title is provided from Wordpress), but also not on the SRP!
*What could be a reason for this behaviour?*
**Workaround**
the parent theme is loading the domain via
`load_theme_textdomain( 'rookie', get_template_directory() . '/languages' );` and points to right location where all translation files (.pot, de\_DE.po and de\_DE.mo) are existing.
I copied the relevant .po and .mo files over to wp-content/languages/themes/ directory and things are working now.
*But is this the real best solution?* | I downloaded the free Rookie parent theme and have no problem displaying translations of "Search Results for: %s" on a successful search results screen.
This works in the WordPress languages folder at `wp-content/languages/themes/rookie-de_DE.mo` as well as Loco Translate's custom directory. It works there if the files are named correctly because the parent theme correctly loads the "rookie" text domain using "load\_theme\_textdomain".
Are your files named correctly under the WordPress languages directory? Unlike the de\_DE.mo file inside the theme folder, the system location requires the prefix so files should be named rookie-de\_DE.mo |
309,106 | <p>I have following piece of code, which inserts usernames and other details of users in the database. After inserting the usernames I want to email them using <code>wp_mail();</code>. I am unable to do so. How can I do this?</p>
<pre><code>$member_details->user_login = array_map( 'sanitize_text_field', $_POST['user_login'] );
$member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] );
$member_details->status = array_map( 'sanitize_text_field', $_POST['status'] );
$member_details_encode = wp_json_encode( $member_details );
global $wpdb;
$member_result = $wpdb->insert( 'wpxa_project_members',
array(
'project_id' => $_SESSION['project_id'],
'author_id' => $post_author,
'member_details' => $member_details_encode
),
array(
'%d',
'%d',
'%s'
)
);
</code></pre>
| [
{
"answer_id": 309144,
"author": "LearntoExcel",
"author_id": 97108,
"author_profile": "https://wordpress.stackexchange.com/users/97108",
"pm_score": -1,
"selected": false,
"text": "<p>Let us see what code you are trying. Assuming that the hook you have bound that function to is firing,... | 2018/07/20 | [
"https://wordpress.stackexchange.com/questions/309106",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124069/"
] | I have following piece of code, which inserts usernames and other details of users in the database. After inserting the usernames I want to email them using `wp_mail();`. I am unable to do so. How can I do this?
```
$member_details->user_login = array_map( 'sanitize_text_field', $_POST['user_login'] );
$member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] );
$member_details->status = array_map( 'sanitize_text_field', $_POST['status'] );
$member_details_encode = wp_json_encode( $member_details );
global $wpdb;
$member_result = $wpdb->insert( 'wpxa_project_members',
array(
'project_id' => $_SESSION['project_id'],
'author_id' => $post_author,
'member_details' => $member_details_encode
),
array(
'%d',
'%d',
'%s'
)
);
``` | Assuming that `$member_details->user_login` is already a user in the `wp_users` table, then you could use the following to get their email address:
`$user = get_user_by( $member_details->user_login, 'login' );`
From there, you have the user's email address and can use `wp_mail()` to email them:
```
$subject = "My email subject";
$message = "My message body...";
wp_mail( $user->user_email, $subject, $message );
``` |
309,151 | <p>I use the following code to change the title of WordPress <strong>posts</strong> and <strong>pages</strong>. But it changes nav menu item titles too, which I want to avoid.</p>
<p>I want to change the title of posts and pages in: <strong>home page</strong>, all <strong>archive pages</strong> and all <strong>widgets</strong> (recent posts widget, random post widget, etc.) </p>
<p>There are similar questions in both Stack Overflow and WP Stack Exchange suggesting to use <code>in_the_loop()</code> function. Unfortunately, it doesn't work for me, because if I place it, it also affects the sidebar widgets.</p>
<p>That means, if I use <code>in_the_loop()</code> function, <code>the_title</code> filter does not affect <code>recent posts widget</code>, <code>random post widget</code> etc.</p>
<p>So how can I apply <code>the_title</code> filter for just <code>post</code> and <code>page</code> titles, but not menu titles?</p>
<pre><code>function pppp_title_update( $title, $id = null ) {
if ( ! is_admin() ) {
if(is_singular(array('post','page')) || is_archive() || is_home()){
if(in_the_loop()){
$current_post_id = get_the_ID();
$new_titile = get_post_meta($current_post_id, 'pp_new_title',true);
return $new_titile;
}
}
}
return $title;
}
add_filter( 'the_title', 'pppp_title_update', 10, 2 );
</code></pre>
| [
{
"answer_id": 309154,
"author": "anmari",
"author_id": 3569,
"author_profile": "https://wordpress.stackexchange.com/users/3569",
"pm_score": -1,
"selected": false,
"text": "<p>If you have the post object (get_the_ID(); or $post->ID; are essentially the same) See <a href=\"https://stac... | 2018/07/21 | [
"https://wordpress.stackexchange.com/questions/309151",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106350/"
] | I use the following code to change the title of WordPress **posts** and **pages**. But it changes nav menu item titles too, which I want to avoid.
I want to change the title of posts and pages in: **home page**, all **archive pages** and all **widgets** (recent posts widget, random post widget, etc.)
There are similar questions in both Stack Overflow and WP Stack Exchange suggesting to use `in_the_loop()` function. Unfortunately, it doesn't work for me, because if I place it, it also affects the sidebar widgets.
That means, if I use `in_the_loop()` function, `the_title` filter does not affect `recent posts widget`, `random post widget` etc.
So how can I apply `the_title` filter for just `post` and `page` titles, but not menu titles?
```
function pppp_title_update( $title, $id = null ) {
if ( ! is_admin() ) {
if(is_singular(array('post','page')) || is_archive() || is_home()){
if(in_the_loop()){
$current_post_id = get_the_ID();
$new_titile = get_post_meta($current_post_id, 'pp_new_title',true);
return $new_titile;
}
}
}
return $title;
}
add_filter( 'the_title', 'pppp_title_update', 10, 2 );
``` | Problem Description:
--------------------
Let me rephrase the question first. You want to:
1. Set new title to all `post` and `page` type from a meta field.
2. You want this to happen everywhere (home page, single page, widgets etc.)
3. However, you don't want this title change to happen if the title is on the Navigation Menu.
Solution:
---------
Before I give you the CODE, let me explain a few points first (based on your CODE):
How to change titles of all posts and pages:
--------------------------------------------
You already know the use of `the_title` filter. However, if you want to target all `post` and `page` type titles (but not custom post types), then your condition:
```
is_singular(array('post','page')) || is_archive() || is_home()
```
will not work. For example, it'll change custom post type on an archive page or the home page as well. This condition doesn't check if the title we are filtering is a `page` or `post` type. Instead, it checks if the page itself is either singular (`post` or `page`) or it's an archive (category, tag etc.) page or the home page. So custom post types in these pages also gets affected. Additionally, if there is a widget in a custom post type (singular) page, then by this logic, `page` or `post` titles in that widget will not be affected there.
To fix that, we need a different check, like:
```
$post = get_post( $id );
if ( $post instanceof WP_Post && ( $post->post_type == 'post' || $post->post_type == 'page' ) )
```
Why Navigation Menu title is also changed & how to stop it:
-----------------------------------------------------------
WordPress applies `the_title` filter twice on the navigation menu items' title (if the menu items correspond to existing posts or pages).
1. First as the corresponding post or page title. This happens in the `wp_setup_nav_menu_item()` function of `wp-includes/nav-menu.php` file.
2. Then as the Menu item title itself. This happens in the `Walker_Nav_Menu` class.
For your requirement, we need to stop the `the_title` filter both the times.
Fortunately, WordPress has two filters: `pre_wp_nav_menu` fires before filtering menu titles and `wp_nav_menu_items` fires after filtering menu titles. So we can use these two filters to first remove the `the_title` filter for nav menu item titles and then add the `the_title` filter back again for other titles.
CODE
----
You may use the following CODE in the theme's `functions.php` file or as a separate plugin:
```
function wpse309151_title_update( $title, $id = null ) {
if ( ! is_admin() && ! is_null( $id ) ) {
$post = get_post( $id );
if ( $post instanceof WP_Post && ( $post->post_type == 'post' || $post->post_type == 'page' ) ) {
$new_titile = get_post_meta( $id, 'pp_new_title', true );
if( ! empty( $new_titile ) ) {
return $new_titile;
}
}
}
return $title;
}
add_filter( 'the_title', 'wpse309151_title_update', 10, 2 );
function wpse309151_remove_title_filter_nav_menu( $nav_menu, $args ) {
// we are working with menu, so remove the title filter
remove_filter( 'the_title', 'wpse309151_title_update', 10, 2 );
return $nav_menu;
}
// this filter fires just before the nav menu item creation process
add_filter( 'pre_wp_nav_menu', 'wpse309151_remove_title_filter_nav_menu', 10, 2 );
function wpse309151_add_title_filter_non_menu( $items, $args ) {
// we are done working with menu, so add the title filter back
add_filter( 'the_title', 'wpse309151_title_update', 10, 2 );
return $items;
}
// this filter fires after nav menu item creation is done
add_filter( 'wp_nav_menu_items', 'wpse309151_add_title_filter_non_menu', 10, 2 );
``` |
309,177 | <p>I have a query as shown below:</p>
<pre><code><?php
$query = new WP_Query( $wpplnum );
while( $query->have_posts() ): $query->the_post();
?>
<div class="carousel-item col-md-4 active">
<div class="card">
<img class="card-img-top img-fluid" src="http://placehold.it/800x600/f44242/fff" alt="Card image cap">
<div class="card-body">
<h4 class="card-title">Card 1</h4>
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
</div>
</code></pre>
<p>I want to add the <code>active</code> class only to the first loop item:</p>
<p><strong><code>class="carousel-item col-md-4 active"</code></strong></p>
<p>the remaining loop items will be without the <code>active</code> class:</p>
<p><strong><code>class="carousel-item col-md-4"</code></strong></p>
| [
{
"answer_id": 309180,
"author": "user141080",
"author_id": 141080,
"author_profile": "https://wordpress.stackexchange.com/users/141080",
"pm_score": 0,
"selected": false,
"text": "<p>Do you mean something like the following?</p>\n\n<pre><code>$query = new WP_Query($wpplnum);\n\n$first =... | 2018/07/21 | [
"https://wordpress.stackexchange.com/questions/309177",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I have a query as shown below:
```
<?php
$query = new WP_Query( $wpplnum );
while( $query->have_posts() ): $query->the_post();
?>
<div class="carousel-item col-md-4 active">
<div class="card">
<img class="card-img-top img-fluid" src="http://placehold.it/800x600/f44242/fff" alt="Card image cap">
<div class="card-body">
<h4 class="card-title">Card 1</h4>
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
</div>
```
I want to add the `active` class only to the first loop item:
**`class="carousel-item col-md-4 active"`**
the remaining loop items will be without the `active` class:
**`class="carousel-item col-md-4"`** | **I'd use the `current_post` property of the `WP_Query` class instance**, which in your case is the `$query`. So here I check if `$query->current_post` is greater than or equals to `1`:
```
<div class="carousel-item col-md-4 <?php echo $query->current_post >= 1 ? '' : 'active'; ?>">
```
Resource: <https://codex.wordpress.org/Class_Reference/WP_Query#Properties> |
309,185 | <p>so I am still quite new to wordpress development so don't rage and I am sorry if I did something really stupid.</p>
<p>So I am having trouble with my CSS, for some reason it's not affecting the widget content output, which can be seen in the movieposterdisplay-class file. What I am trying to do is make the outputted youtube video auto size to fit the container using CSS. What I want to know is why the CSS isn't affecting the HTML code and a solution to fix it. Thanks in advance for any help.</p>
<p>movieposterdisplayfile</p>
<pre><code>require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay-
scripts.php');
require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay-
class.php');
function register_movieposterdisplay(){
register_widget('Movie_Poster_Display_Widget');
}
add_action('widgets_init', 'register_movieposterdisplay');
</code></pre>
<p>movieposterdisplay-scripts file</p>
<pre><code><?php
function mpd_add_scripts(){
wp_enqueue_style('mpd-main-style', plugins_url().'/movieposterdisplay/css/style.css');
wp_enqueue_script('mpd-main-style', plugins_url().'/movieposterdisplay/js/main.js');
}
add_action('wp_enqueue_scripts', 'mpd_add_scripts');
</code></pre>
<p>movieposterdisplay-class file (file contains the widget output)</p>
<pre><code><?php
class Movie_Poster_Display_Widget extends WP_Widget {
function __construct() {
parent::__construct(
'movieposterdisplay_widget', // Base ID
esc_html__( 'Movie Widget', 'mpd_domain' ), // Name
array( 'description' => esc_html__( 'Displays Movie/TV posters, overviews and trailers.', 'mpd_domain' ), )
);
}
public function widget( $args, $instance) {
echo $args['before_widget'];
$trailer_key ="http://www.youtube.com/embed/" .$this->display_trailer($instance, $first_movie_result)."?enablejsapi=1";
?>
<div class="youtubeplayer">
<iframe
id="player" type="text/html"
src="<?php echo $trailer_key;?>"
frameborder="0" allowfullscreen="allowfullscreen">
</iframe>
</div>
<?php
echo $args['after_widget'];
}
</code></pre>
<p>style.css</p>
<pre><code>.youtubeplayer {
position: relative;
padding-bottom: 75%;
padding-top: 25px;
height: 0;
border: 5px solid red;
}
.youtubeplayer iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</code></pre>
| [
{
"answer_id": 309189,
"author": "Shubham Vijay",
"author_id": 28586,
"author_profile": "https://wordpress.stackexchange.com/users/28586",
"pm_score": -1,
"selected": false,
"text": "<p>Fortunately, it’s fairly easy to find and diagnose the problem. Go to any page on your site and, in Ch... | 2018/07/21 | [
"https://wordpress.stackexchange.com/questions/309185",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147303/"
] | so I am still quite new to wordpress development so don't rage and I am sorry if I did something really stupid.
So I am having trouble with my CSS, for some reason it's not affecting the widget content output, which can be seen in the movieposterdisplay-class file. What I am trying to do is make the outputted youtube video auto size to fit the container using CSS. What I want to know is why the CSS isn't affecting the HTML code and a solution to fix it. Thanks in advance for any help.
movieposterdisplayfile
```
require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay-
scripts.php');
require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay-
class.php');
function register_movieposterdisplay(){
register_widget('Movie_Poster_Display_Widget');
}
add_action('widgets_init', 'register_movieposterdisplay');
```
movieposterdisplay-scripts file
```
<?php
function mpd_add_scripts(){
wp_enqueue_style('mpd-main-style', plugins_url().'/movieposterdisplay/css/style.css');
wp_enqueue_script('mpd-main-style', plugins_url().'/movieposterdisplay/js/main.js');
}
add_action('wp_enqueue_scripts', 'mpd_add_scripts');
```
movieposterdisplay-class file (file contains the widget output)
```
<?php
class Movie_Poster_Display_Widget extends WP_Widget {
function __construct() {
parent::__construct(
'movieposterdisplay_widget', // Base ID
esc_html__( 'Movie Widget', 'mpd_domain' ), // Name
array( 'description' => esc_html__( 'Displays Movie/TV posters, overviews and trailers.', 'mpd_domain' ), )
);
}
public function widget( $args, $instance) {
echo $args['before_widget'];
$trailer_key ="http://www.youtube.com/embed/" .$this->display_trailer($instance, $first_movie_result)."?enablejsapi=1";
?>
<div class="youtubeplayer">
<iframe
id="player" type="text/html"
src="<?php echo $trailer_key;?>"
frameborder="0" allowfullscreen="allowfullscreen">
</iframe>
</div>
<?php
echo $args['after_widget'];
}
```
style.css
```
.youtubeplayer {
position: relative;
padding-bottom: 75%;
padding-top: 25px;
height: 0;
border: 5px solid red;
}
.youtubeplayer iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
``` | The problem was due to an incorrect file path in the movieposterdisplay-scripts file. Whilst the file loaded correctly in the main php file
`require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay- class.php');`
as it already assigned the correct plugin folder name. It did not enqueue correctly as the code was `wp_enqueue_style('mpd-main-style', plugins_url().'/movieposterdisplay/css/style.css');` and I had previously changed the folder name.
Hence I thought it was loading correctly and running fine, however it was only loading correctly. |
309,190 | <p>Wordpress Category Archive permalinks set up with %category% include the full category tree. I want to see only the leaf category in the URL, not the full tree.</p>
<p>Example:</p>
<pre><code>Wordpress Category: recipes > baking > bread
current permalink for archive: domain.com/recipes/baking/bread
desired permalink: domain.com/bread
</code></pre>
<p>I've been searching the web without any idea how to hook or filter this change into my wordpress code, so any ideas and help is highly welcome. thanks Jan</p>
| [
{
"answer_id": 309189,
"author": "Shubham Vijay",
"author_id": 28586,
"author_profile": "https://wordpress.stackexchange.com/users/28586",
"pm_score": -1,
"selected": false,
"text": "<p>Fortunately, it’s fairly easy to find and diagnose the problem. Go to any page on your site and, in Ch... | 2018/07/21 | [
"https://wordpress.stackexchange.com/questions/309190",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147308/"
] | Wordpress Category Archive permalinks set up with %category% include the full category tree. I want to see only the leaf category in the URL, not the full tree.
Example:
```
Wordpress Category: recipes > baking > bread
current permalink for archive: domain.com/recipes/baking/bread
desired permalink: domain.com/bread
```
I've been searching the web without any idea how to hook or filter this change into my wordpress code, so any ideas and help is highly welcome. thanks Jan | The problem was due to an incorrect file path in the movieposterdisplay-scripts file. Whilst the file loaded correctly in the main php file
`require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay- class.php');`
as it already assigned the correct plugin folder name. It did not enqueue correctly as the code was `wp_enqueue_style('mpd-main-style', plugins_url().'/movieposterdisplay/css/style.css');` and I had previously changed the folder name.
Hence I thought it was loading correctly and running fine, however it was only loading correctly. |