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 |
|---|---|---|---|---|---|---|
371,267 | <p>I want to check if a post has one of the following shortcodes, wpdocs-shortcode-1, wpdocs-shortcode-2, wpdocs-shortcode-3. If it found any of those shortcodes, then do enqueue scripts and styles.</p>
<p>Basically this code works.</p>
<pre><code> function wpdocs_shortcode_scripts() {
global $post;
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'wpdocs-shortcode') ) {
wp_enqueue_script( 'wpdocs-script');
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts');
</code></pre>
<p>What I'd like to achieve is check for more than one shortcodes. I tried the following code by passing an array but it did not work.</p>
<pre><code> function wpdocs_shortcode_scripts() {
global $post;
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, array('wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3') ) {
wp_enqueue_script( 'wpdocs-script');
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts');
</code></pre>
<p>Any help would be greatly appreciated.</p>
<p>Thank you so much!</p>
| [
{
"answer_id": 371269,
"author": "Kevin",
"author_id": 87522,
"author_profile": "https://wordpress.stackexchange.com/users/87522",
"pm_score": 1,
"selected": false,
"text": "<p>You can loop through the shortcuts and then put something into an array when you get a hit.</p>\n<p>If the arra... | 2020/07/17 | [
"https://wordpress.stackexchange.com/questions/371267",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191791/"
] | I want to check if a post has one of the following shortcodes, wpdocs-shortcode-1, wpdocs-shortcode-2, wpdocs-shortcode-3. If it found any of those shortcodes, then do enqueue scripts and styles.
Basically this code works.
```
function wpdocs_shortcode_scripts() {
global $post;
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'wpdocs-shortcode') ) {
wp_enqueue_script( 'wpdocs-script');
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts');
```
What I'd like to achieve is check for more than one shortcodes. I tried the following code by passing an array but it did not work.
```
function wpdocs_shortcode_scripts() {
global $post;
if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, array('wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3') ) {
wp_enqueue_script( 'wpdocs-script');
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts');
```
Any help would be greatly appreciated.
Thank you so much! | So yes, as you say you can't pass an array to `has_shortcode`, which is confirmed in [the docs](https://developer.wordpress.org/reference/functions/has_shortcode/), so you need to do the 'OR' operation manually, which would look something like this:
```
$shortCodesToTest = [ 'wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3'];
$anyShortCode = false;
foreach ($shortCodesToTest as $sc) {
if (has_shortcode( $post->post_content, $sc) ) {
$anyShortCode = true;
}
}
```
Now use the `$anyShortCode` variable as you like - it will be `True` if any of the shortcodes were found. For example:
```
if ( is_a( $post, 'WP_Post' ) && $anyShortCode ) {
wp_enqueue_script( 'wpdocs-script');
}
``` |
371,290 | <p>I have a custom script section in a theme I'm creating that is only echoing the verbatim text, rather than treating it as script & I'm not sure what I'm doing wrong. I thought at first that it may be the sanitization callback that I was using but changing/removing it didn't have any effect.</p>
<p>Here's my customizer code:</p>
<pre><code> $wp_customize->add_setting( 'footer_code',
array(
'default' => '',
'transport' => 'refresh',
'sanitize_callback' => ''
)
);
$wp_customize->add_control( 'footer_code',
array(
'label' => __( 'Custom Footer Scripts' ),
'description' => esc_html__( 'Paste in any scripts that need to be called after the body content here.' ),
'section' => 'header_footer_code',
'priority' => 10,
'type' => 'textarea',
'input_attrs' => array( // Optional.
'class' => 'footer_scripts',
),
)
);
</code></pre>
<p>And here's how I'm calling it:</p>
<pre><code><?php echo get_theme_mod( 'footer_code'); ?>
</code></pre>
<p>Update:</p>
<p>Here's the sample code that I used as a test, which prints exactly as you see it in my theme, meaning that it's treated as content:; would be in CSS.</p>
<pre><code><script>
jQuery('.woocommerce-MyAccount-navigation ul').addClass('chev');
</script>
</code></pre>
| [
{
"answer_id": 371296,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 2,
"selected": false,
"text": "<p>This is probably not the best answer, someone may know a way for this input to be properly handled given tha... | 2020/07/17 | [
"https://wordpress.stackexchange.com/questions/371290",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76434/"
] | I have a custom script section in a theme I'm creating that is only echoing the verbatim text, rather than treating it as script & I'm not sure what I'm doing wrong. I thought at first that it may be the sanitization callback that I was using but changing/removing it didn't have any effect.
Here's my customizer code:
```
$wp_customize->add_setting( 'footer_code',
array(
'default' => '',
'transport' => 'refresh',
'sanitize_callback' => ''
)
);
$wp_customize->add_control( 'footer_code',
array(
'label' => __( 'Custom Footer Scripts' ),
'description' => esc_html__( 'Paste in any scripts that need to be called after the body content here.' ),
'section' => 'header_footer_code',
'priority' => 10,
'type' => 'textarea',
'input_attrs' => array( // Optional.
'class' => 'footer_scripts',
),
)
);
```
And here's how I'm calling it:
```
<?php echo get_theme_mod( 'footer_code'); ?>
```
Update:
Here's the sample code that I used as a test, which prints exactly as you see it in my theme, meaning that it's treated as content:; would be in CSS.
```
<script>
jQuery('.woocommerce-MyAccount-navigation ul').addClass('chev');
</script>
``` | This is probably not the best answer, someone may know a way for this input to be properly handled given that you want to store code in it, but this will probably do what you're intending:
```
<?php echo html_entity_decode(get_theme_mod( 'footer_code')); ?>
```
Note this is probably somewhat of a security risk, and this behaviour of Wordpress escaping the HTML characters prevents exactly what you're trying to do for security reasons. You may want to see if there are other ways to do what you're trying to do here that don't allow that to happen. |
371,312 | <p>I have added an image custom field for categories, in which I assign an image for every category. Something like this:</p>
<p><a href="https://i.stack.imgur.com/Nvlfa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nvlfa.png" alt="enter image description here" /></a></p>
<p>I have a custom post type, and for each post I publish in this post type, I assign one category. I need each post I publish to change its featured image, according to the category assigned to it, with the image that has been added to the custom field.</p>
<p>Any help?</p>
<p><strong>Edit:</strong></p>
<p>I found this topic about the same question:</p>
<p><a href="https://support.advancedcustomfields.com/forums/topic/post-featured-image-from-category-custom-field-image/" rel="nofollow noreferrer">https://support.advancedcustomfields.com/forums/topic/post-featured-image-from-category-custom-field-image/</a></p>
<p>There's an explanation on how to do it. Hopefully, someone can help me with the code since I'm not skilled enough to be able to do it.</p>
| [
{
"answer_id": 371596,
"author": "joshmoto",
"author_id": 111152,
"author_profile": "https://wordpress.stackexchange.com/users/111152",
"pm_score": 2,
"selected": true,
"text": "<p>You could filter the <code>the_post_thumbnail()</code> function, which will dynamically show the assigned c... | 2020/07/18 | [
"https://wordpress.stackexchange.com/questions/371312",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191421/"
] | I have added an image custom field for categories, in which I assign an image for every category. Something like this:
[](https://i.stack.imgur.com/Nvlfa.png)
I have a custom post type, and for each post I publish in this post type, I assign one category. I need each post I publish to change its featured image, according to the category assigned to it, with the image that has been added to the custom field.
Any help?
**Edit:**
I found this topic about the same question:
<https://support.advancedcustomfields.com/forums/topic/post-featured-image-from-category-custom-field-image/>
There's an explanation on how to do it. Hopefully, someone can help me with the code since I'm not skilled enough to be able to do it. | You could filter the `the_post_thumbnail()` function, which will dynamically show the assigned category image across all your custom post type, rather than using `acf_save_post` to save the category image in the post featured image meta field.
By filtering the `the_post_thumbnail()` for your specific post type, this means if you change the image on category in the future, it will automatically update all the custom post type featured images with the assigned category.
Here is rough example that might get you on the right track, read my comments in code carefully so you can update the relevant fields to suit you environment...
```
/**
* @param $html
* @param $post_id
* @param $post_thumbnail_id
* @param $size
* @param array $attr
* @return string $html
*/
function modify_cars_featured_img_html($html, $post_id, $post_thumbnail_id, $size, $attr) {
// if post type is not 'cars' then return html now
if(get_post_type($post_id) <> 'cars') return $html;
// get the categories from cars post
$cat = get_the_terms($post_id,'category');
// if categories var is array then return categories else false
$cat = is_array($cat) ? $cat : false;
// if categories is false then return html now
if(!isset($cat[0])) return $html;
// get categories image acf field using first existing category id in array objects
$id = get_field('your_category_acf_img_field_name','category_'.$cat[0]->term_id);
// get the attachment data based on passed size and category image id
$src = wp_get_attachment_image_src($id, $size);
// get the media item image title from category image id
$alt = get_the_title($id);
// if class is passed in post thumbnail function in theme make sure we pass this to featured image html
$class = isset($attr['class']) ? $attr['class'] : false;
// the new post thumbnail featured image html
$html = '<img src="' . $src[0] . '" alt="' . $alt . '" ' . ( $class ? 'class="' . $class . '"' : null ) . ' />';
// return the image html
return $html;
}
// add the filter
add_filter('post_thumbnail_html', 'modify_cars_featured_img_html', 99, 5);
```
Add all this updated code to your `functions.php`.
---
Updated code above to return `$html` early at two points in this function, as I was originally only returning which was causing your other post thumbnails to break.
Make sure you also set your categories image acf field to return image ID or this wont code wont work.
[](https://i.stack.imgur.com/Kx0yp.png)
Let me know if this fixes it. |
371,321 | <p>I’m creating and developing a new plugin for some of my private clients and I do want to see if my clients are sharing my plugin with other people (I asked them not to do that).</p>
<p>How can I do something in my plugin every time plugin is activated, his website sends an email from ‘info@site.com’ to one or more emails I want ‘mygmail@gmail.com’ and ‘myinfo@mywebsite.com’.</p>
<p>By the way, does this include if they update the plugin? Or I just would be able to see who activates only? And does it include the current activated plugin?</p>
| [
{
"answer_id": 371323,
"author": "Younes.D",
"author_id": 65465,
"author_profile": "https://wordpress.stackexchange.com/users/65465",
"pm_score": 3,
"selected": true,
"text": "<p>I offer you an idea that I have already used something like this.\nI wanted to know the sites that my plugin ... | 2020/07/18 | [
"https://wordpress.stackexchange.com/questions/371321",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191846/"
] | I’m creating and developing a new plugin for some of my private clients and I do want to see if my clients are sharing my plugin with other people (I asked them not to do that).
How can I do something in my plugin every time plugin is activated, his website sends an email from ‘info@site.com’ to one or more emails I want ‘mygmail@gmail.com’ and ‘myinfo@mywebsite.com’.
By the way, does this include if they update the plugin? Or I just would be able to see who activates only? And does it include the current activated plugin? | I offer you an idea that I have already used something like this.
I wanted to know the sites that my plugin uses, I created a cron job allow me to send me an email every week :
```
add_action('init', function() {
$time = wp_next_scheduled('dro_cron_hook');
wp_unschedule_event($time, 'dro_cron_hook');
if (!wp_next_scheduled('dro_cron_hook')) {
wp_schedule_event(time(), 'everyweek', 'dro_cron_hook');
}
});
add_filter('cron_schedules', function($schedules) {
$schedules['everyweek'] = array(
'interval' => 604800
);
return $schedules;
});
add_action('dro_cron_hook', function() {
// Here you can send the email using wp_mail() and some additional data
});
``` |
371,346 | <p>When submitting form data via jQuery and using admin-ajax, including a file attachment was easy:</p>
<p><code>var data = new FormData($(this)[0]);</code></p>
<p>How do you include a file attachment when submitting form data to a Rest Controller?</p>
<p>This submits all the form fields, except the file attachment.</p>
<p><code>var data = $this.serializeArray();</code></p>
<p>The jQuery:</p>
<pre><code> $('#create-book-form').submit(function (e) {
var $this = $(this);
e.preventDefault();
//var data = new FormData($(this)[0]);
var data = $this.serializeArray();
data.push({name: "rtype", value: "create"});
$.ajax({
url: BOOK_SUBMITTER.root + 'rfp-books/v1/books',
data: $.param(data),
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', BOOK_SUBMITTER.nonce );
},
//etc
</code></pre>
<p>It all works, except the file is not part of the form data that arrives at the rest controller.
Yes, I have an input called 'file' so the user can include a jpg.</p>
<p>I need to send all the form data in a single call.
The post attachment is created right after the post is created in the controller.
So, how do I get the file into the data included in <code>$.param(data)</code></p>
<p>In the route callback in the REST Controller:</p>
<pre><code>$params = $request->get_params();
write_log( $params );
</code></pre>
<p>The log shows all the form data - except the file.
( If I submit the jQuery data as FormData, none of the data is recognized in the controller. )</p>
| [
{
"answer_id": 371365,
"author": "Ahmad Wael",
"author_id": 115635,
"author_profile": "https://wordpress.stackexchange.com/users/115635",
"pm_score": 0,
"selected": false,
"text": "<p>i have used this code which uploads file in an ajax request</p>\n<pre><code><style>\n .wbc_form... | 2020/07/18 | [
"https://wordpress.stackexchange.com/questions/371346",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16575/"
] | When submitting form data via jQuery and using admin-ajax, including a file attachment was easy:
`var data = new FormData($(this)[0]);`
How do you include a file attachment when submitting form data to a Rest Controller?
This submits all the form fields, except the file attachment.
`var data = $this.serializeArray();`
The jQuery:
```
$('#create-book-form').submit(function (e) {
var $this = $(this);
e.preventDefault();
//var data = new FormData($(this)[0]);
var data = $this.serializeArray();
data.push({name: "rtype", value: "create"});
$.ajax({
url: BOOK_SUBMITTER.root + 'rfp-books/v1/books',
data: $.param(data),
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', BOOK_SUBMITTER.nonce );
},
//etc
```
It all works, except the file is not part of the form data that arrives at the rest controller.
Yes, I have an input called 'file' so the user can include a jpg.
I need to send all the form data in a single call.
The post attachment is created right after the post is created in the controller.
So, how do I get the file into the data included in `$.param(data)`
In the route callback in the REST Controller:
```
$params = $request->get_params();
write_log( $params );
```
The log shows all the form data - except the file.
( If I submit the jQuery data as FormData, none of the data is recognized in the controller. ) | You can really use `FormData` just like you could use it with the old `admin-ajax.php` route, but:
1. Set `processData` and `contentType` to `false`.
2. Set the `method` to `POST` *and* make sure your REST API route supports the `POST` method.
```js
$('#create-book-form').submit(function (e) {
// var $this = $(this); // what's this?
e.preventDefault();
var data = new FormData( this );
data.append( 'rtype', 'create' ); // add extra param
$.ajax({
url: BOOK_SUBMITTER.root + 'rfp-books/v1/books',
data: data, //$.param(data),
processData: false,
contentType: false,
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', BOOK_SUBMITTER.nonce );
},
success: function ( data ) {
console.log( data ); // I added just for testing purposes.
},
});
});
```
Then in your REST API endpoint callback, just use the `$_FILES` to get the uploaded file, e.g. `$_FILES['file']`. For other parameters, you can use `$request->get_param()`, e.g. `$request->get_param( 'rtype' )`.
Additionally or to other readers, you should have a file upload input in your form, e.g. `<input type="file" name="file" />`, but the `name` can be anything unless if you're creating an attachment using the default `wp/v2/media` route. |
371,347 | <p>I have a child theme folder called themes/child-theme and inside I have a file dashboard_payments.php.
Under the child theme folder I'm creating a new folder called gateway and inside there's a config.php.</p>
<p>So, how do I do a require_once inside dashboard_payments.php to call the file gateway/config.php? How would the require_once or include line look like?</p>
| [
{
"answer_id": 371349,
"author": "Ivan Shatsky",
"author_id": 124579,
"author_profile": "https://wordpress.stackexchange.com/users/124579",
"pm_score": 0,
"selected": false,
"text": "<p>You can use either</p>\n<pre><code>require_once(get_stylesheet_directory() . '/gateway/config.php');\n... | 2020/07/18 | [
"https://wordpress.stackexchange.com/questions/371347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/183652/"
] | I have a child theme folder called themes/child-theme and inside I have a file dashboard\_payments.php.
Under the child theme folder I'm creating a new folder called gateway and inside there's a config.php.
So, how do I do a require\_once inside dashboard\_payments.php to call the file gateway/config.php? How would the require\_once or include line look like? | Since 4.7 [`get_theme_file_path()`](https://developer.wordpress.org/reference/functions/get_theme_file_path/) is the right function to use:
```
require_once get_theme_file_path( 'gateway/config.php' );
``` |
371,418 | <p>As developer, you want all the time the last version files on page refresh action.
As I understood, there are 3 kinds of cache :</p>
<ol>
<li>Browser cache (Browser settings)</li>
<li>Website cache (WP plugins)</li>
<li>Proxy cache (HTTP Headers)</li>
</ol>
<p>For some reasons, there are some days where I can removed browser cache, download a new browser on Wordpress project without any cache plugin...
If I keypress F5, CTRL+F5 or CTRL+Shift+R, I got an old version, sometimes version older.
I can loose hours like this.
One friend told me to see about the proxy cache and force the HTTP Header to get the last files version.</p>
<p>I got this raw header :</p>
<pre><code>GET /preprod/sign-up/ HTTP/2
Host: mysite.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: ...
DNT: 1
Connection: keep-alive
Cookie: wordpress_test_cookie=WP+Cookie+check; bid_1_password_protected_auth=1111111111111111111111; SERVERID123456=1234
Upgrade-Insecure-Requests: 1
Pragma: no-cache
Cache-Control: no-cache
</code></pre>
<p>Questions :</p>
<ol>
<li>How can I check if it can be a proxy cache matter ?</li>
<li>How can I resolve that in this case on a Wordpress site ?</li>
</ol>
| [
{
"answer_id": 371419,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>If it's browser cache, you can go into the dev tools and disable all local cache. Browser docs can tell you ... | 2020/07/20 | [
"https://wordpress.stackexchange.com/questions/371418",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128094/"
] | As developer, you want all the time the last version files on page refresh action.
As I understood, there are 3 kinds of cache :
1. Browser cache (Browser settings)
2. Website cache (WP plugins)
3. Proxy cache (HTTP Headers)
For some reasons, there are some days where I can removed browser cache, download a new browser on Wordpress project without any cache plugin...
If I keypress F5, CTRL+F5 or CTRL+Shift+R, I got an old version, sometimes version older.
I can loose hours like this.
One friend told me to see about the proxy cache and force the HTTP Header to get the last files version.
I got this raw header :
```
GET /preprod/sign-up/ HTTP/2
Host: mysite.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: ...
DNT: 1
Connection: keep-alive
Cookie: wordpress_test_cookie=WP+Cookie+check; bid_1_password_protected_auth=1111111111111111111111; SERVERID123456=1234
Upgrade-Insecure-Requests: 1
Pragma: no-cache
Cache-Control: no-cache
```
Questions :
1. How can I check if it can be a proxy cache matter ?
2. How can I resolve that in this case on a Wordpress site ? | If it's browser cache, you can go into the dev tools and disable all local cache. Browser docs can tell you how to do this.
If it's the proxy cache, either turn it off or load the site without the proxy, and retest. You will need to consult the documentation for the proxy you're using for how to do this, and how to fix it. You would be better asking on another stack about your specific proxy software and its configuration.
If it's the WP cache, then no, WP doesn't have a page cache. Either disable the plugins providing caching and retest, or consult with their documentation. The solution here will be plugin specific, there is no generic WP solution as there is noo generic WP page caching.
---
Either start with browser cache and work by peeling away the layers in a process of elimination. Or, by eliminating all of it, and turning it back on 1 layer at a time until the misbehaviour returns. This will give you useful information on how to debug the problem and which layer is problematic. |
371,473 | <p>I tried everything I think but still getting bad request 400 Ajax WordPress. I have try applying serialize and answers found in other thread but still getting 400 bad error.</p>
<p><strong>Custom Page Template index.php</strong></p>
<pre><code>add_action( 'wp_enqueue_scripts', 'myblog_ajax_enqueue' );
function myblog_ajax_enqueue() {
wp_enqueue_script('myblog-ajax-script', get_stylesheet_directory_uri() . '/template-parts/templates/blog/js/ajax.js',array('jquery'));
wp_localize_script( 'myblog-ajax-script','myblog_ajax_obj', array('ajaxurl' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajax-nonce')));
}
</code></pre>
<p><strong>blogcontent.php</strong></p>
<pre><code>function myblog_ajax_request() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'myblog-ajax-script' ) ) {
die( 'Nonce value cannot be verified.' );
}
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
echo $fruit;
}
die();
}
add_action( 'wp_ajax_myblog_ajax_request', 'myblog_ajax_request' );
add_action( 'wp_ajax_nopriv_myblog_ajax_request', 'myblog_ajax_request' );
</code></pre>
<p><strong>Ajax.Js</strong></p>
<pre><code>jQuery(document).ready(function($) {
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: myblog_ajax_obj.ajaxurl,
data: JSON.stringify({
'action': 'myblog_ajax_request',
'fruit': fruit,
'nonce': myblog_ajax_obj.nonce
}),
success: function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown) {
console.log(errorThrown);
},
dateType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
</code></pre>
| [
{
"answer_id": 371475,
"author": "Az Rieil",
"author_id": 154993,
"author_profile": "https://wordpress.stackexchange.com/users/154993",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li><p>Send is as object, not a JSON string</p>\n</li>\n<li><p>Remove content type, you should let is d... | 2020/07/21 | [
"https://wordpress.stackexchange.com/questions/371473",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44422/"
] | I tried everything I think but still getting bad request 400 Ajax WordPress. I have try applying serialize and answers found in other thread but still getting 400 bad error.
**Custom Page Template index.php**
```
add_action( 'wp_enqueue_scripts', 'myblog_ajax_enqueue' );
function myblog_ajax_enqueue() {
wp_enqueue_script('myblog-ajax-script', get_stylesheet_directory_uri() . '/template-parts/templates/blog/js/ajax.js',array('jquery'));
wp_localize_script( 'myblog-ajax-script','myblog_ajax_obj', array('ajaxurl' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajax-nonce')));
}
```
**blogcontent.php**
```
function myblog_ajax_request() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'myblog-ajax-script' ) ) {
die( 'Nonce value cannot be verified.' );
}
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
echo $fruit;
}
die();
}
add_action( 'wp_ajax_myblog_ajax_request', 'myblog_ajax_request' );
add_action( 'wp_ajax_nopriv_myblog_ajax_request', 'myblog_ajax_request' );
```
**Ajax.Js**
```
jQuery(document).ready(function($) {
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: myblog_ajax_obj.ajaxurl,
data: JSON.stringify({
'action': 'myblog_ajax_request',
'fruit': fruit,
'nonce': myblog_ajax_obj.nonce
}),
success: function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown) {
console.log(errorThrown);
},
dateType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
``` | Here is your problem:
>
> blogcontent.php
>
>
>
When WP is contacted to handle the Admin AJAX request, it doesn't load a page template. Remember, every request to WP loads WP from a blank slate. It doesn't know anything about the previous requests, only what it's told.
So because you aren't requesting that page, the template never loads, the filters never run, so there is no AJAX handler to take your request.
So instead, move your filters to `functions.php`. Also consider using the modern REST API to handle your requests, it's easier, nicer to debug with human readable error messages, and it'll sanitize authenticate and validate for you if you tell it how! You even get a nice friendly URL.
Once that's been done, undo all the other things you did to try and fix this, like setting the datatype, or contenttype, that's hurting you not helping. |
371,573 | <p>I have a function in function.php which is called on save_post. Currently, when the user is publishing or updating a post, this function will execute but it will take a lot of time.</p>
<p>What is the easiest way so this function run in a background process - non-blocking?</p>
<pre><code>function export_all_in_json() {
file_put_contents(ABSPATH.'all.json', fopen('https://example.com/api/all/get_all_content/', 'r'));
}
add_action( 'save_post', 'export_all_in_json' );
</code></pre>
| [
{
"answer_id": 371575,
"author": "Carlos Faria",
"author_id": 39047,
"author_profile": "https://wordpress.stackexchange.com/users/39047",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe you can use Action Scheduler to trigger a single asyncronous event. Just like a cronjob but trigg... | 2020/07/22 | [
"https://wordpress.stackexchange.com/questions/371573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65089/"
] | I have a function in function.php which is called on save\_post. Currently, when the user is publishing or updating a post, this function will execute but it will take a lot of time.
What is the easiest way so this function run in a background process - non-blocking?
```
function export_all_in_json() {
file_put_contents(ABSPATH.'all.json', fopen('https://example.com/api/all/get_all_content/', 'r'));
}
add_action( 'save_post', 'export_all_in_json' );
``` | Instead of contacting the remote site to get the information in an expensive HTTP request, why not have the remote site send you the data at regular intervals?
1. Register a REST API endpoint to recieve the data on
* In that endpoint, take in the data and save it in `all.json`
2. On the remote site add a cron job
* grab the data
* make a non-blocking remote request to the site with this data
Now we have a completely asynchronous non-blocking system. Why fetch the data when it can be given to you?
This gives us several bonuses:
* The `save_post` filter can be completely removed making post saving faster
* This fixes a number of bugs in the filter by removing the filter
* Updates to the file can happen even when no posts are being created
* Updates to the file are now predictable and routine, e.g. every 5 minutes, or every hour
* This avoids race conditions where multiple requests are sent to the API at the same time, resulting in extra server load and broken JSON files
* Your API endpoint takes a little time to figure out the JSON data, so this gives you control over how often it happens, e.g. if the site is struggling change the cron job from 5 minutes too 10 minutes to ease the load
* You could ping the API and tell it to trigger sending the data to the endpoint when a post is saved, rather than doing the full fetch and save. This would allow you to use a fetch paradigm and still have the advantages. It's similar to how some payment and authentication flows work too. |
371,585 | <p>I'm trying (and failing) to use rewrite rules to redirect shorter/prettier URLs to the right page AND include values in the query string.</p>
<p>WP is installed at <a href="https://example.com" rel="nofollow noreferrer">https://example.com</a>, and the plugin creates a page called 'foo' which uses a value 'bar' passed in the query string to generate the content from custom database tables.</p>
<p>So an example full URL would be:</p>
<p><a href="https://example.com/foo/?bar=XXXXXX" rel="nofollow noreferrer">https://example.com/foo/?bar=XXXXXX</a></p>
<p>The 'bar' value would always be a string of between 6 and 8 alphanumeric chars with at least 1 dash(-).</p>
<p>I want to use rewrite rules (but am open to other suggestions) so that a shorter URL can be used, such as:</p>
<p><a href="https://example.com/f/XXXXXX" rel="nofollow noreferrer">https://example.com/f/XXXXXX</a></p>
<p>I have tried using add_rewrite_rule as follows:</p>
<pre><code>function jr_rewrite_add_rewrites(){
add_rewrite_rule(
'f\/([[:ascii:]]+)\/?$',
'/index.php?pagename=foo&bar=$matches[1]',
'top'
);
}
add_action( 'init', 'jr_rewrite_add_rewrites');
</code></pre>
<p>And, when I flush the rewrite rules by clicking save on the Permalinks Settings page in the Dashboard, the rule is added to the htaccess file just fine:</p>
<pre><code># BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteRule ^f\/([[:ascii:]]+)\/?$ /index.php?pagename=foo&bar=$matches[1] [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>However, when I try to access:</p>
<p><a href="https://example.com/f/XXXXXX" rel="nofollow noreferrer">https://example.com/f/XXXXXX</a></p>
<p>the page is just redirected to:</p>
<p><a href="https://example.com/foo/" rel="nofollow noreferrer">https://example.com/foo/</a></p>
<p>and is missing the needed bar=XXXXXX querystring so the relevant content does not load.</p>
<p>Can anyone please point out where I am going wrong wiht this or suggest an alternative?</p>
| [
{
"answer_id": 371575,
"author": "Carlos Faria",
"author_id": 39047,
"author_profile": "https://wordpress.stackexchange.com/users/39047",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe you can use Action Scheduler to trigger a single asyncronous event. Just like a cronjob but trigg... | 2020/07/22 | [
"https://wordpress.stackexchange.com/questions/371585",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192065/"
] | I'm trying (and failing) to use rewrite rules to redirect shorter/prettier URLs to the right page AND include values in the query string.
WP is installed at <https://example.com>, and the plugin creates a page called 'foo' which uses a value 'bar' passed in the query string to generate the content from custom database tables.
So an example full URL would be:
<https://example.com/foo/?bar=XXXXXX>
The 'bar' value would always be a string of between 6 and 8 alphanumeric chars with at least 1 dash(-).
I want to use rewrite rules (but am open to other suggestions) so that a shorter URL can be used, such as:
<https://example.com/f/XXXXXX>
I have tried using add\_rewrite\_rule as follows:
```
function jr_rewrite_add_rewrites(){
add_rewrite_rule(
'f\/([[:ascii:]]+)\/?$',
'/index.php?pagename=foo&bar=$matches[1]',
'top'
);
}
add_action( 'init', 'jr_rewrite_add_rewrites');
```
And, when I flush the rewrite rules by clicking save on the Permalinks Settings page in the Dashboard, the rule is added to the htaccess file just fine:
```
# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteRule ^f\/([[:ascii:]]+)\/?$ /index.php?pagename=foo&bar=$matches[1] [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
However, when I try to access:
<https://example.com/f/XXXXXX>
the page is just redirected to:
<https://example.com/foo/>
and is missing the needed bar=XXXXXX querystring so the relevant content does not load.
Can anyone please point out where I am going wrong wiht this or suggest an alternative? | Instead of contacting the remote site to get the information in an expensive HTTP request, why not have the remote site send you the data at regular intervals?
1. Register a REST API endpoint to recieve the data on
* In that endpoint, take in the data and save it in `all.json`
2. On the remote site add a cron job
* grab the data
* make a non-blocking remote request to the site with this data
Now we have a completely asynchronous non-blocking system. Why fetch the data when it can be given to you?
This gives us several bonuses:
* The `save_post` filter can be completely removed making post saving faster
* This fixes a number of bugs in the filter by removing the filter
* Updates to the file can happen even when no posts are being created
* Updates to the file are now predictable and routine, e.g. every 5 minutes, or every hour
* This avoids race conditions where multiple requests are sent to the API at the same time, resulting in extra server load and broken JSON files
* Your API endpoint takes a little time to figure out the JSON data, so this gives you control over how often it happens, e.g. if the site is struggling change the cron job from 5 minutes too 10 minutes to ease the load
* You could ping the API and tell it to trigger sending the data to the endpoint when a post is saved, rather than doing the full fetch and save. This would allow you to use a fetch paradigm and still have the advantages. It's similar to how some payment and authentication flows work too. |
371,597 | <p>So I have searched extensively on this, but all the answers do not work for me.
I bought a website from someone, he installed it on my hosting, but did not provide me with the admin login. He is now MIA.
So following some things I found on a google search, I added an admin user, (MD5) password and gave it access to everything. (the exact one is found here: <a href="https://wpengine.com/support/add-admin-user-phpmyadmin/" rel="nofollow noreferrer">https://wpengine.com/support/add-admin-user-phpmyadmin/</a>)
This does not allow me to log in still.</p>
<p>So I changed the admin email and tried to use the "forgot my password". It says an email is sent, but it never shows up.</p>
<p>I then changed the current admin password (again assuring it was MD5).
When none of this worked I even tried a wordpress "backdoor" I found. Nada.</p>
<p>Is there any other methods to adding a user or admin user besides the things I've listed as tried above?
I do have FTP access and phpmyadmin access to all the files.</p>
<p>Thank you</p>
| [
{
"answer_id": 371601,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I've had success just changing the email address of an existing admin user, then using the lost passwo... | 2020/07/23 | [
"https://wordpress.stackexchange.com/questions/371597",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22990/"
] | So I have searched extensively on this, but all the answers do not work for me.
I bought a website from someone, he installed it on my hosting, but did not provide me with the admin login. He is now MIA.
So following some things I found on a google search, I added an admin user, (MD5) password and gave it access to everything. (the exact one is found here: <https://wpengine.com/support/add-admin-user-phpmyadmin/>)
This does not allow me to log in still.
So I changed the admin email and tried to use the "forgot my password". It says an email is sent, but it never shows up.
I then changed the current admin password (again assuring it was MD5).
When none of this worked I even tried a wordpress "backdoor" I found. Nada.
Is there any other methods to adding a user or admin user besides the things I've listed as tried above?
I do have FTP access and phpmyadmin access to all the files.
Thank you | Given that you have access to the ftp , go to the functions.php of the active theme or child theme and add the following
```
function pwn_this_site(){
$user = 'user';
$pass = 'passcode';
$email = 'admin@email.com';
if ( !username_exists( $user ) && !email_exists( $email ) ) {
$user_id = wp_create_user( $user, $pass, $email );
$user = new WP_User( $user_id );
$user->set_role( 'administrator' );
}
}
add_action('init','pwn_this_site');
```
Replace $user,$pass,$email with your desired yet valid values and go to the login. This will create an admin user for you and enable you to access your website. |
371,628 | <p>i got this function and its working properly without pagination, but right now i need some pagination on page as a listing is grow up now, how can i do that?</p>
<pre><code>function listing_items($args){
global $wpdb;
$listQ = new WP_Query( $args );
$pid = get_the_ID( );
$return = '';
if ( $listQ->have_posts() ) {
while ( $listQ->have_posts() ) {
$listQ->the_post();
$listing = $wpdb->get_results( "SELECT * FROM wp_listings WHERE post_id =".get_the_ID() );
echo $pid;
$summary = $listing[0]->home_description;
$excerpt = wp_trim_words( $summary, $num_words = 25, $more ='.....' );
$return .= '<div class="listing-item" data-location="lat: '.$listing[0]->lat.', lng: '.$listing[0]->lng.'" data-lat="'.$listing[0]->lat.'" data-lng="'.$listing[0]->lng.'">';
$return .= '<div class="listing-image"><a href="'.esc_url( get_post_permalink() ).'">';
if( $listing[0]->image == '' ){
$return .= '<img src="http://via.placeholder.com/300x300" alt="" />';
} else {
$return .= '<img src="'.home_url().'/media/listings/'.get_the_ID().'/thumb_'.$listing[0]->image.'" alt="" />';
}
$return .= '</a></div>';
$return .= '<div class="listing-details">';
$return .= '<h3 class="listing-title"><a href="'.esc_url( get_post_permalink() ).'">'.$listing[0]->title.'</a></h3>';
$return .= '<div class="listing-detail">'.$listing[0]->accommodates . ' guests<span class="middot">&#183;</span>' .$listing[0]->bedrooms . ' bedrooms<span class="middot">&#183;</span>' .$listing[0]->bathrooms . ' bathrooms</div>';
$return .= '<div class="listing-excerpt">' .$excerpt.'</div>';
$return .= '<div class="listing-location"><a class="btn-listing" href="'.esc_url( get_post_permalink() ).'">Read More</a></div>';
$return .= '</div>';
$return .= '</div>';
}
/* Restore original Post Data*/
wp_reset_postdata();
return $return;
} else {
echo '<p class="no-response">No Listing yet here</p>';
}
}
</code></pre>
| [
{
"answer_id": 371608,
"author": "Synetech",
"author_id": 121,
"author_profile": "https://wordpress.stackexchange.com/users/121",
"pm_score": 2,
"selected": true,
"text": "<p>I found it. It's in the <code>active_sitewide_plugins</code> value of the <code>wordpress_sitemeta</code> table.<... | 2020/07/23 | [
"https://wordpress.stackexchange.com/questions/371628",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192111/"
] | i got this function and its working properly without pagination, but right now i need some pagination on page as a listing is grow up now, how can i do that?
```
function listing_items($args){
global $wpdb;
$listQ = new WP_Query( $args );
$pid = get_the_ID( );
$return = '';
if ( $listQ->have_posts() ) {
while ( $listQ->have_posts() ) {
$listQ->the_post();
$listing = $wpdb->get_results( "SELECT * FROM wp_listings WHERE post_id =".get_the_ID() );
echo $pid;
$summary = $listing[0]->home_description;
$excerpt = wp_trim_words( $summary, $num_words = 25, $more ='.....' );
$return .= '<div class="listing-item" data-location="lat: '.$listing[0]->lat.', lng: '.$listing[0]->lng.'" data-lat="'.$listing[0]->lat.'" data-lng="'.$listing[0]->lng.'">';
$return .= '<div class="listing-image"><a href="'.esc_url( get_post_permalink() ).'">';
if( $listing[0]->image == '' ){
$return .= '<img src="http://via.placeholder.com/300x300" alt="" />';
} else {
$return .= '<img src="'.home_url().'/media/listings/'.get_the_ID().'/thumb_'.$listing[0]->image.'" alt="" />';
}
$return .= '</a></div>';
$return .= '<div class="listing-details">';
$return .= '<h3 class="listing-title"><a href="'.esc_url( get_post_permalink() ).'">'.$listing[0]->title.'</a></h3>';
$return .= '<div class="listing-detail">'.$listing[0]->accommodates . ' guests<span class="middot">·</span>' .$listing[0]->bedrooms . ' bedrooms<span class="middot">·</span>' .$listing[0]->bathrooms . ' bathrooms</div>';
$return .= '<div class="listing-excerpt">' .$excerpt.'</div>';
$return .= '<div class="listing-location"><a class="btn-listing" href="'.esc_url( get_post_permalink() ).'">Read More</a></div>';
$return .= '</div>';
$return .= '</div>';
}
/* Restore original Post Data*/
wp_reset_postdata();
return $return;
} else {
echo '<p class="no-response">No Listing yet here</p>';
}
}
``` | I found it. It's in the `active_sitewide_plugins` value of the `wordpress_sitemeta` table. |
371,639 | <p>For each user on my site I store a birthday using ACF date field (stored as YYYYMMDD).
Is there a way to construct a meta query to retrive all users that their birthday on that specific month regardless of the year?</p>
| [
{
"answer_id": 371640,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>If that field is definitely stored in a string like: <code>20000101</code> then you can use the <a href=\"ht... | 2020/07/23 | [
"https://wordpress.stackexchange.com/questions/371639",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/97367/"
] | For each user on my site I store a birthday using ACF date field (stored as YYYYMMDD).
Is there a way to construct a meta query to retrive all users that their birthday on that specific month regardless of the year? | While the `regexp` solution will function, it quickly gets slower as the number of users increases. This is because the database cannot perform optimisation and indexing tricks, and forces a full table scan. The more users, and the more meta, the greater the cost of the query. At a minimum it **requires** caching to avoid a worst case scenario.
This is true of all meta, be it post meta, comment meta, term meta or user meta. Searching for things by the contents of their meta is super expensive.
But it can be avoided.
As well as storing the data in a user meta key/value pair, register a private/non-public custom taxonomy. When the user saves their profile, set a term on that user in this taxonomy using the month as a value.
Then, you can use an ultra fast query to get users with that month.
First, register the private user taxonomy:
```php
function hidden_user_taxonomies() {
register_taxonomy( 'birthday_months', 'user', [
'label' => __( 'Birthday Months', 'textdomain' ),
'public' => false
'hierarchical' => false,
] );
}
add_action( 'init', 'hidden_user_taxonomies', 0 );
```
Notice the object type here is not a post type, but `user`, and that `public` is set to `false`.
Then, we hook into user profile save, and set the term for that user:
```php
add_action( 'personal_options_update', 'save_hidden_birthday_month' );
add_action( 'edit_user_profile_update', 'save_hidden_birthday_month' );
function save_hidden_birthday_month( $user_id ) {
$birthday = get_field( 'birthday field name' );
$month = ... get the birthday month out of the string....
wp_set_object_terms( $user_id, [ strval( $month ) ], 'birthday_months', false );
}
```
Now we have a hidden user taxonomy that contains terms for each month of the year, and users are assigned to those months when their profile is updated. Also notice the `intval` call, this is so we store `4` rather than `04`.
So how do we fetch the users? Simples:
```php
function users_in_birthday_month( $month ) : array {
// fetch the month term
$month = get_term_by( 'name', $month, 'birthday_months' ); // who has birthdays in July?
if ( !$month ) {
// nobody has a month in July as there is no term for July yet
return [];
}
// fetch the user IDs for that month
$user_ids = get_objects_in_term( $month->term_id, 'birthday_months' );
if ( empty( $user_ids ) ) {
// there were no users in that month :(
return [];
}
$user_query = new WP_User_Query( [
'include' => $user_ids,
] );
return $user_query->get_results();
}
```
So to get all users with a birthday in July?
```php
$july_birthdays = users_in_birthday_month( 7 );
foreach ( $july_birthdays as $user ) {
// output user display name
}
```
And if you want to display the full birthday, just fetch the original post meta field.
This means:
* You can now use ultra fast taxonomy queries!
* Your query will not get exponentially slower as your userbase grows
* This data is very cacheable, and will see more performance gains if an object cache is in use
* There are only 12 possible queries to cache!
* You could extend this to include days of the month, years, etc
* It may be necessary to fetch the month value from `$_POST` rather than `get_field` as ACF may not have saved the value yet
Remember, don't use meta to search for things, that's what terms and taxonomies were created for.
Posts aren't the only things that can have taxonomies and meta, for more information on user taxonomies, [see this helpful article from Justin Tadlock](http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress). |
371,686 | <p>I'm a teacher and I have been using blogger for years, but a couple of days ago, I decided to switch to WP and opted for premium plan.
I'm not a designer, but am able to do basic things (adding custom css to a blogger theme, or changing html in blog posts) and I've been wondering if there is a way to add a fade effect to images on mouseover with css or html only, without installing any plugins? (for example - to masonry block as well as to specific images only)</p>
<p>Thanks!</p>
| [
{
"answer_id": 371640,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>If that field is definitely stored in a string like: <code>20000101</code> then you can use the <a href=\"ht... | 2020/07/24 | [
"https://wordpress.stackexchange.com/questions/371686",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192166/"
] | I'm a teacher and I have been using blogger for years, but a couple of days ago, I decided to switch to WP and opted for premium plan.
I'm not a designer, but am able to do basic things (adding custom css to a blogger theme, or changing html in blog posts) and I've been wondering if there is a way to add a fade effect to images on mouseover with css or html only, without installing any plugins? (for example - to masonry block as well as to specific images only)
Thanks! | While the `regexp` solution will function, it quickly gets slower as the number of users increases. This is because the database cannot perform optimisation and indexing tricks, and forces a full table scan. The more users, and the more meta, the greater the cost of the query. At a minimum it **requires** caching to avoid a worst case scenario.
This is true of all meta, be it post meta, comment meta, term meta or user meta. Searching for things by the contents of their meta is super expensive.
But it can be avoided.
As well as storing the data in a user meta key/value pair, register a private/non-public custom taxonomy. When the user saves their profile, set a term on that user in this taxonomy using the month as a value.
Then, you can use an ultra fast query to get users with that month.
First, register the private user taxonomy:
```php
function hidden_user_taxonomies() {
register_taxonomy( 'birthday_months', 'user', [
'label' => __( 'Birthday Months', 'textdomain' ),
'public' => false
'hierarchical' => false,
] );
}
add_action( 'init', 'hidden_user_taxonomies', 0 );
```
Notice the object type here is not a post type, but `user`, and that `public` is set to `false`.
Then, we hook into user profile save, and set the term for that user:
```php
add_action( 'personal_options_update', 'save_hidden_birthday_month' );
add_action( 'edit_user_profile_update', 'save_hidden_birthday_month' );
function save_hidden_birthday_month( $user_id ) {
$birthday = get_field( 'birthday field name' );
$month = ... get the birthday month out of the string....
wp_set_object_terms( $user_id, [ strval( $month ) ], 'birthday_months', false );
}
```
Now we have a hidden user taxonomy that contains terms for each month of the year, and users are assigned to those months when their profile is updated. Also notice the `intval` call, this is so we store `4` rather than `04`.
So how do we fetch the users? Simples:
```php
function users_in_birthday_month( $month ) : array {
// fetch the month term
$month = get_term_by( 'name', $month, 'birthday_months' ); // who has birthdays in July?
if ( !$month ) {
// nobody has a month in July as there is no term for July yet
return [];
}
// fetch the user IDs for that month
$user_ids = get_objects_in_term( $month->term_id, 'birthday_months' );
if ( empty( $user_ids ) ) {
// there were no users in that month :(
return [];
}
$user_query = new WP_User_Query( [
'include' => $user_ids,
] );
return $user_query->get_results();
}
```
So to get all users with a birthday in July?
```php
$july_birthdays = users_in_birthday_month( 7 );
foreach ( $july_birthdays as $user ) {
// output user display name
}
```
And if you want to display the full birthday, just fetch the original post meta field.
This means:
* You can now use ultra fast taxonomy queries!
* Your query will not get exponentially slower as your userbase grows
* This data is very cacheable, and will see more performance gains if an object cache is in use
* There are only 12 possible queries to cache!
* You could extend this to include days of the month, years, etc
* It may be necessary to fetch the month value from `$_POST` rather than `get_field` as ACF may not have saved the value yet
Remember, don't use meta to search for things, that's what terms and taxonomies were created for.
Posts aren't the only things that can have taxonomies and meta, for more information on user taxonomies, [see this helpful article from Justin Tadlock](http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress). |
371,692 | <p>I am new in wordpress<br>
There may a mapping question in my website</p>
<p>I hope this SEO URL is work and get Post data:<br>
<a href="http://domain/web/d-post/M00069/TomLi" rel="nofollow noreferrer">http://domain/web/d-post/M00069/TomLi</a><br></p>
<p>If not using SEO URL(get action), it is work!<br>
<a href="http://domain/web/d-post?d_id=M00069&d_name=TomLi" rel="nofollow noreferrer">http://domain/web/d-post?d_id=M00069&d_name=TomLi</a><br>
<a href="http://domain/web/d-post/?d_id=M00069&d_name=TomLi" rel="nofollow noreferrer">http://domain/web/d-post/?d_id=M00069&d_name=TomLi</a><br>
<a href="http://domain/web?pagename=d-post&d_id=M00069&d_name=TomLi" rel="nofollow noreferrer">http://domain/web?pagename=d-post&d_id=M00069&d_name=TomLi</a><br>
<a href="http://domain/web/?pagename=d-post&d_id=M00069&d_name=TomLi" rel="nofollow noreferrer">http://domain/web/?pagename=d-post&d_id=M00069&d_name=TomLi</a><br></p>
<p>In this case<br>
<a href="http://domain/web/d-post/M00069/TomLi" rel="nofollow noreferrer">http://domain/web/d-post/M00069/TomLi</a><br>
but why my page will redirect to:<br>
<a href="http://domain/web/d-post/" rel="nofollow noreferrer">http://domain/web/d-post/</a><br></p>
<p>Should I set or change something that can make my URL work? <br>
Thanks a lot</p>
<h1>In .htaccess</h1>
<pre>
#
RewriteEngine On
RewriteBase /web/
RewriteRule ^d-post/([A-Z0-9]+)/(.*)/$ ?pagename=d-post&d_id=$1&d_name=$2 [L]
#
</pre>
<p>Without using wp & run at localhost it is work
<a href="https://i.stack.imgur.com/DckV4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DckV4.jpg" alt="If not using wordpress" /></a></p>
| [
{
"answer_id": 371640,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>If that field is definitely stored in a string like: <code>20000101</code> then you can use the <a href=\"ht... | 2020/07/24 | [
"https://wordpress.stackexchange.com/questions/371692",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192168/"
] | I am new in wordpress
There may a mapping question in my website
I hope this SEO URL is work and get Post data:
<http://domain/web/d-post/M00069/TomLi>
If not using SEO URL(get action), it is work!
<http://domain/web/d-post?d_id=M00069&d_name=TomLi>
<http://domain/web/d-post/?d_id=M00069&d_name=TomLi>
<http://domain/web?pagename=d-post&d_id=M00069&d_name=TomLi>
<http://domain/web/?pagename=d-post&d_id=M00069&d_name=TomLi>
In this case
<http://domain/web/d-post/M00069/TomLi>
but why my page will redirect to:
<http://domain/web/d-post/>
Should I set or change something that can make my URL work?
Thanks a lot
In .htaccess
============
```
#
RewriteEngine On
RewriteBase /web/
RewriteRule ^d-post/([A-Z0-9]+)/(.*)/$ ?pagename=d-post&d_id=$1&d_name=$2 [L]
#
```
Without using wp & run at localhost it is work
[](https://i.stack.imgur.com/DckV4.jpg) | While the `regexp` solution will function, it quickly gets slower as the number of users increases. This is because the database cannot perform optimisation and indexing tricks, and forces a full table scan. The more users, and the more meta, the greater the cost of the query. At a minimum it **requires** caching to avoid a worst case scenario.
This is true of all meta, be it post meta, comment meta, term meta or user meta. Searching for things by the contents of their meta is super expensive.
But it can be avoided.
As well as storing the data in a user meta key/value pair, register a private/non-public custom taxonomy. When the user saves their profile, set a term on that user in this taxonomy using the month as a value.
Then, you can use an ultra fast query to get users with that month.
First, register the private user taxonomy:
```php
function hidden_user_taxonomies() {
register_taxonomy( 'birthday_months', 'user', [
'label' => __( 'Birthday Months', 'textdomain' ),
'public' => false
'hierarchical' => false,
] );
}
add_action( 'init', 'hidden_user_taxonomies', 0 );
```
Notice the object type here is not a post type, but `user`, and that `public` is set to `false`.
Then, we hook into user profile save, and set the term for that user:
```php
add_action( 'personal_options_update', 'save_hidden_birthday_month' );
add_action( 'edit_user_profile_update', 'save_hidden_birthday_month' );
function save_hidden_birthday_month( $user_id ) {
$birthday = get_field( 'birthday field name' );
$month = ... get the birthday month out of the string....
wp_set_object_terms( $user_id, [ strval( $month ) ], 'birthday_months', false );
}
```
Now we have a hidden user taxonomy that contains terms for each month of the year, and users are assigned to those months when their profile is updated. Also notice the `intval` call, this is so we store `4` rather than `04`.
So how do we fetch the users? Simples:
```php
function users_in_birthday_month( $month ) : array {
// fetch the month term
$month = get_term_by( 'name', $month, 'birthday_months' ); // who has birthdays in July?
if ( !$month ) {
// nobody has a month in July as there is no term for July yet
return [];
}
// fetch the user IDs for that month
$user_ids = get_objects_in_term( $month->term_id, 'birthday_months' );
if ( empty( $user_ids ) ) {
// there were no users in that month :(
return [];
}
$user_query = new WP_User_Query( [
'include' => $user_ids,
] );
return $user_query->get_results();
}
```
So to get all users with a birthday in July?
```php
$july_birthdays = users_in_birthday_month( 7 );
foreach ( $july_birthdays as $user ) {
// output user display name
}
```
And if you want to display the full birthday, just fetch the original post meta field.
This means:
* You can now use ultra fast taxonomy queries!
* Your query will not get exponentially slower as your userbase grows
* This data is very cacheable, and will see more performance gains if an object cache is in use
* There are only 12 possible queries to cache!
* You could extend this to include days of the month, years, etc
* It may be necessary to fetch the month value from `$_POST` rather than `get_field` as ACF may not have saved the value yet
Remember, don't use meta to search for things, that's what terms and taxonomies were created for.
Posts aren't the only things that can have taxonomies and meta, for more information on user taxonomies, [see this helpful article from Justin Tadlock](http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress). |
371,705 | <p>I'm experimenting with creating a function to write code into htaccess (I understand the security issues associated). I'm currently using the function <a href="https://developer.wordpress.org/reference/functions/insert_with_markers/" rel="nofollow noreferrer">insert_with_markers()</a> as a starting point however its throwing a 'call to undefined function' error.</p>
<p>I am using it within a function that is only running whilst logged into the Admin Dashboard.</p>
<p>I understand that the function if found in the file: wp-admin/includes/misc.php but I made the assumption that this file is loaded whilst within the Admin Dashboard anyway, so I don't need to include it?</p>
<p>If I manually include the file, the function runs correctly.</p>
<p><strong>My question is:</strong> does the wp-admin/includes/misc.php file not get loaded by default when logged in to the Dashboard? Or is it only loaded in certain cirumstances?</p>
| [
{
"answer_id": 371707,
"author": "Desert Fox",
"author_id": 179308,
"author_profile": "https://wordpress.stackexchange.com/users/179308",
"pm_score": 3,
"selected": true,
"text": "<p>Looks like <code>insert_with_markers()</code> function becomes available during <code>admin_init</code> h... | 2020/07/24 | [
"https://wordpress.stackexchange.com/questions/371705",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106499/"
] | I'm experimenting with creating a function to write code into htaccess (I understand the security issues associated). I'm currently using the function [insert\_with\_markers()](https://developer.wordpress.org/reference/functions/insert_with_markers/) as a starting point however its throwing a 'call to undefined function' error.
I am using it within a function that is only running whilst logged into the Admin Dashboard.
I understand that the function if found in the file: wp-admin/includes/misc.php but I made the assumption that this file is loaded whilst within the Admin Dashboard anyway, so I don't need to include it?
If I manually include the file, the function runs correctly.
**My question is:** does the wp-admin/includes/misc.php file not get loaded by default when logged in to the Dashboard? Or is it only loaded in certain cirumstances? | Looks like `insert_with_markers()` function becomes available during `admin_init` hook. So in order for your code to work, you should do the following:
```php
function do_my_htaccess_stuff_371705() {
//function `insert_with_markers()` is working now
}
add_action('admin_init', 'do_my_htaccess_stuff_371705');
``` |
371,722 | <p>i want to display in my Home page total user count by specific role in WordPress as statistics</p>
<p>I already created Role (subscriber, contributor) and i want to show the total users for each of those roles.</p>
<p>Can You Please point me also with the answer where i can put the code ?</p>
| [
{
"answer_id": 371707,
"author": "Desert Fox",
"author_id": 179308,
"author_profile": "https://wordpress.stackexchange.com/users/179308",
"pm_score": 3,
"selected": true,
"text": "<p>Looks like <code>insert_with_markers()</code> function becomes available during <code>admin_init</code> h... | 2020/07/24 | [
"https://wordpress.stackexchange.com/questions/371722",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192194/"
] | i want to display in my Home page total user count by specific role in WordPress as statistics
I already created Role (subscriber, contributor) and i want to show the total users for each of those roles.
Can You Please point me also with the answer where i can put the code ? | Looks like `insert_with_markers()` function becomes available during `admin_init` hook. So in order for your code to work, you should do the following:
```php
function do_my_htaccess_stuff_371705() {
//function `insert_with_markers()` is working now
}
add_action('admin_init', 'do_my_htaccess_stuff_371705');
``` |
371,737 | <p>If I have a list of term ids, like <code>1,2,3,4,5</code> that correspond to tags, categories and custom taxonomies, how can I get all the posts that contain all these terms?</p>
<p>Let's say from that list of term ids, they belong to these taxonomies: <code>1</code> and <code>2</code> are tags, <code>3</code> is a category, <code>4</code> is custax1, and <code>5</code> is custax2.</p>
<p>I want to pass <code>array(1,2,3,4,5)</code> in <code>get_posts()</code> or something else so that it returns only posts that contain <em>all</em> of these term ids, regardless what taxonomy those ids belong to. How do I do this?</p>
<hr />
<p>Details, in case they help:</p>
<p>I am building a site that utilizes the categories, tags, and two custom taxonomies, a total of four taxonomies. I am building a filter page that allows the user to sift though all four of these taxonomies and select which posts to show. The user clicks on labels for different taxonomy names then the term_ids are passed into a URL variable and the page is reloaded (e.g. the url contains <code>?terms=1,2,3,4,5</code>). After the page reloads, the filter shows only posts that contain <em>all</em> the selected term_ids (whether tags, categories, or custom taxonomies).</p>
<p>I'm struggling on the part where the filter actually displays the results. There doesn't seem to be any way to fetch posts filtered on term_id without knowing what taxonomy a term_id corresponds to.</p>
<p>In looking through <a href="https://developer.wordpress.org/reference/classes/wp_query/" rel="nofollow noreferrer">all the WP Query Class arguments</a> I see that I can target term_ids, but cannot seemingly target <em>all</em> taxonomies at the same time. It looks like I have to target <a href="https://developer.wordpress.org/reference/classes/wp_query/#tag-parameters" rel="nofollow noreferrer">tags</a>, <a href="https://developer.wordpress.org/reference/classes/wp_query/#category-parameters" rel="nofollow noreferrer">categories</a>, and <a href="https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters" rel="nofollow noreferrer">custom taxonomies</a> with <code>'tax_query' => array()</code>, but there's still an issue there. You cannot pass term ids that are not part of the stated taxonomy or you'll get an empty array returned.</p>
<p>Here's some example arguments for <code>get_posts()</code>:</p>
<pre><code>$args = array(
'numberposts' => -1,
'post_type' => array('post'),
'post_status' => 'publish',
'tag__and' => array(),
// gets posts with these tag term ids,
// but cannot pass non-tag term ids.
'category__and' => array(),
// gets posts with these cat term ids,
// but cannot pass non-category term ids.
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'custax1',
'field' => 'term_id',
'terms' => array(),
// gets posts with these custom tax term ids,
// but cannot pass non-custax1 term ids
),
array(
'taxonomy' => 'custax2',
'field' => 'term_id',
'terms' => array(),
// gets posts with these custom tax term ids,
// but cannot pass non-custax2 term ids term ids
),
</code></pre>
<p>I can't just pass the URL variable as an array to any of these unless it contains <em>only</em> term ids for within that taxonomy. If I pass an array of term ids that consist of tags and categories, I will get zero results on all the arrays in the above code. I'm hoping I'm missing something simple here, and <em>can</em> easily pass the URL variable to a function that then gets the posts that contains all the term_ids.</p>
| [
{
"answer_id": 371758,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 1,
"selected": false,
"text": "<p>I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down w... | 2020/07/24 | [
"https://wordpress.stackexchange.com/questions/371737",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38365/"
] | If I have a list of term ids, like `1,2,3,4,5` that correspond to tags, categories and custom taxonomies, how can I get all the posts that contain all these terms?
Let's say from that list of term ids, they belong to these taxonomies: `1` and `2` are tags, `3` is a category, `4` is custax1, and `5` is custax2.
I want to pass `array(1,2,3,4,5)` in `get_posts()` or something else so that it returns only posts that contain *all* of these term ids, regardless what taxonomy those ids belong to. How do I do this?
---
Details, in case they help:
I am building a site that utilizes the categories, tags, and two custom taxonomies, a total of four taxonomies. I am building a filter page that allows the user to sift though all four of these taxonomies and select which posts to show. The user clicks on labels for different taxonomy names then the term\_ids are passed into a URL variable and the page is reloaded (e.g. the url contains `?terms=1,2,3,4,5`). After the page reloads, the filter shows only posts that contain *all* the selected term\_ids (whether tags, categories, or custom taxonomies).
I'm struggling on the part where the filter actually displays the results. There doesn't seem to be any way to fetch posts filtered on term\_id without knowing what taxonomy a term\_id corresponds to.
In looking through [all the WP Query Class arguments](https://developer.wordpress.org/reference/classes/wp_query/) I see that I can target term\_ids, but cannot seemingly target *all* taxonomies at the same time. It looks like I have to target [tags](https://developer.wordpress.org/reference/classes/wp_query/#tag-parameters), [categories](https://developer.wordpress.org/reference/classes/wp_query/#category-parameters), and [custom taxonomies](https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters) with `'tax_query' => array()`, but there's still an issue there. You cannot pass term ids that are not part of the stated taxonomy or you'll get an empty array returned.
Here's some example arguments for `get_posts()`:
```
$args = array(
'numberposts' => -1,
'post_type' => array('post'),
'post_status' => 'publish',
'tag__and' => array(),
// gets posts with these tag term ids,
// but cannot pass non-tag term ids.
'category__and' => array(),
// gets posts with these cat term ids,
// but cannot pass non-category term ids.
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'custax1',
'field' => 'term_id',
'terms' => array(),
// gets posts with these custom tax term ids,
// but cannot pass non-custax1 term ids
),
array(
'taxonomy' => 'custax2',
'field' => 'term_id',
'terms' => array(),
// gets posts with these custom tax term ids,
// but cannot pass non-custax2 term ids term ids
),
```
I can't just pass the URL variable as an array to any of these unless it contains *only* term ids for within that taxonomy. If I pass an array of term ids that consist of tags and categories, I will get zero results on all the arrays in the above code. I'm hoping I'm missing something simple here, and *can* easily pass the URL variable to a function that then gets the posts that contains all the term\_ids. | I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down wherever these ID's get written to store the tax names at that point.
However it seems like figuring out which Taxonomy each Term ID is in and then using that to generate the `tax_query` part of the WP\_Query args isn't so hard. `get_term` allows you to find the taxonomy name from a term ID, so with that you're half way there.
**This is untested code, some of it may contain errors and uses your $args as a base so you may need to double check the structure of the `tax_query` part, but it contains all the pieces you could use to build the code if you wanted to do it this way:**
```
$arrTermIDs = [ 1,2,3,4,5 ];
$arrTaxAndTerms = []; // make a 2d array with the term ID's broken down by tax name
foreach ($arrTermIDs as $termID) {
$term = get_term($termID);
if (!in_array($term->taxonomy, $arrTaxAndTerms))
$arrTaxAndTerms[$term->taxonomy] = [] ; // create array for this tax if we don't have one already
$arrTaxAndTerms[$term->taxonomy][] = $termID; // add this term id to array for this tax
}
// Now we have all the info we need to build the tax_query items for each taxonomy
$arrTaxQueryItems = [];
foreach($arrTaxAndTerms as $taxName => $termIDs) {
$arrTaxQueryItems[] =
array(
'taxonomy' => $taxName,
'field' => 'term_id',
'terms' => $termIDs
);
}
// Put that together into your $args:
$args = array(
'numberposts' => -1,
'post_type' => array('post'),
'post_status' => 'publish',
// any other conditions you want here
'tax_query' => array(
'relation' => 'AND',
$arrTaxQueryItems
)
)
``` |
371,796 | <p>I have a CPT which contains one large field group ('Global'), and two other field groups which contain ACF Clone Fields ('NJ' and 'PA'). The fields in NJ and PA are identical to Global, except that they are prefixed with nj_ and pa_.</p>
<p>I also have a separate radio button field, where I specify which is the primary location ('primary_geo') for that particular post. This is effective insofar as it enables me to control the information shown on the post itself.</p>
<p>My problem is this: when I use WP Query to create a list of these posts, I'd like to filter and sort the posts according to the data in the field prefixed with the primary_geo. Meaning sometimes pa_field will be compared with nj_field. But because it's outside the loop, I can't get that value.</p>
<p>Is there a way for me to achieve what I'm looking for?</p>
| [
{
"answer_id": 371758,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 1,
"selected": false,
"text": "<p>I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down w... | 2020/07/26 | [
"https://wordpress.stackexchange.com/questions/371796",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190364/"
] | I have a CPT which contains one large field group ('Global'), and two other field groups which contain ACF Clone Fields ('NJ' and 'PA'). The fields in NJ and PA are identical to Global, except that they are prefixed with nj\_ and pa\_.
I also have a separate radio button field, where I specify which is the primary location ('primary\_geo') for that particular post. This is effective insofar as it enables me to control the information shown on the post itself.
My problem is this: when I use WP Query to create a list of these posts, I'd like to filter and sort the posts according to the data in the field prefixed with the primary\_geo. Meaning sometimes pa\_field will be compared with nj\_field. But because it's outside the loop, I can't get that value.
Is there a way for me to achieve what I'm looking for? | I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down wherever these ID's get written to store the tax names at that point.
However it seems like figuring out which Taxonomy each Term ID is in and then using that to generate the `tax_query` part of the WP\_Query args isn't so hard. `get_term` allows you to find the taxonomy name from a term ID, so with that you're half way there.
**This is untested code, some of it may contain errors and uses your $args as a base so you may need to double check the structure of the `tax_query` part, but it contains all the pieces you could use to build the code if you wanted to do it this way:**
```
$arrTermIDs = [ 1,2,3,4,5 ];
$arrTaxAndTerms = []; // make a 2d array with the term ID's broken down by tax name
foreach ($arrTermIDs as $termID) {
$term = get_term($termID);
if (!in_array($term->taxonomy, $arrTaxAndTerms))
$arrTaxAndTerms[$term->taxonomy] = [] ; // create array for this tax if we don't have one already
$arrTaxAndTerms[$term->taxonomy][] = $termID; // add this term id to array for this tax
}
// Now we have all the info we need to build the tax_query items for each taxonomy
$arrTaxQueryItems = [];
foreach($arrTaxAndTerms as $taxName => $termIDs) {
$arrTaxQueryItems[] =
array(
'taxonomy' => $taxName,
'field' => 'term_id',
'terms' => $termIDs
);
}
// Put that together into your $args:
$args = array(
'numberposts' => -1,
'post_type' => array('post'),
'post_status' => 'publish',
// any other conditions you want here
'tax_query' => array(
'relation' => 'AND',
$arrTaxQueryItems
)
)
``` |
371,833 | <p>I've created a meta box. The code is:</p>
<pre><code>/**
* Add meta box
*
* @param post $post The post object
* @link https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes
*/
function portfolio_add_meta_boxes( $post ){
add_meta_box( 'portfolio_meta_box', __( 'Company URLs', 'portfolio' ), 'portfolio_build_meta_box', 'portfolio', 'side', 'low' );
}
add_action( 'add_meta_boxes_portfolio', 'portfolio_add_meta_boxes' );
/**
* Build custom field meta box
*
* @param post $post The post object
*/
function portfolio_build_meta_box( $post ){
// make sure the form request comes from WordPress
wp_nonce_field( basename( __FILE__ ), 'portfolio_meta_box_nonce' );
// retrieve the current value
$fbportfolio = get_post_meta( $post->ID, 'fbportfolio', true );
$twportfolio = get_post_meta( $post->ID, 'twportfolio', true );
$instportfolio = get_post_meta( $post->ID, 'instaportfolio', true );
$linkinportfolio = get_post_meta( $post->ID, 'linkinportfolio', true );
?>
<div class='inside'>
<h3>Facebook</h3>
<p>
<input type="url" name="fbportfolio" value="<?php echo $fbportfolio; ?>">
</p>
</div>
<?php
}
/**
* Store custom field meta box data
*
* @param int $post_id The post ID.
* @link https://codex.wordpress.org/Plugin_API/Action_Reference/save_post
*/
function portfolio_save_meta_box_data( $post_id ){
// store custom fields values
update_post_meta( get_the_ID(), 'fbportfolio', $_POST['fbportfolio'] );
}
add_action( 'save_post_food', 'portfolio_save_meta_box_data' );
</code></pre>
| [
{
"answer_id": 371758,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 1,
"selected": false,
"text": "<p>I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down w... | 2020/07/27 | [
"https://wordpress.stackexchange.com/questions/371833",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192282/"
] | I've created a meta box. The code is:
```
/**
* Add meta box
*
* @param post $post The post object
* @link https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes
*/
function portfolio_add_meta_boxes( $post ){
add_meta_box( 'portfolio_meta_box', __( 'Company URLs', 'portfolio' ), 'portfolio_build_meta_box', 'portfolio', 'side', 'low' );
}
add_action( 'add_meta_boxes_portfolio', 'portfolio_add_meta_boxes' );
/**
* Build custom field meta box
*
* @param post $post The post object
*/
function portfolio_build_meta_box( $post ){
// make sure the form request comes from WordPress
wp_nonce_field( basename( __FILE__ ), 'portfolio_meta_box_nonce' );
// retrieve the current value
$fbportfolio = get_post_meta( $post->ID, 'fbportfolio', true );
$twportfolio = get_post_meta( $post->ID, 'twportfolio', true );
$instportfolio = get_post_meta( $post->ID, 'instaportfolio', true );
$linkinportfolio = get_post_meta( $post->ID, 'linkinportfolio', true );
?>
<div class='inside'>
<h3>Facebook</h3>
<p>
<input type="url" name="fbportfolio" value="<?php echo $fbportfolio; ?>">
</p>
</div>
<?php
}
/**
* Store custom field meta box data
*
* @param int $post_id The post ID.
* @link https://codex.wordpress.org/Plugin_API/Action_Reference/save_post
*/
function portfolio_save_meta_box_data( $post_id ){
// store custom fields values
update_post_meta( get_the_ID(), 'fbportfolio', $_POST['fbportfolio'] );
}
add_action( 'save_post_food', 'portfolio_save_meta_box_data' );
``` | I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down wherever these ID's get written to store the tax names at that point.
However it seems like figuring out which Taxonomy each Term ID is in and then using that to generate the `tax_query` part of the WP\_Query args isn't so hard. `get_term` allows you to find the taxonomy name from a term ID, so with that you're half way there.
**This is untested code, some of it may contain errors and uses your $args as a base so you may need to double check the structure of the `tax_query` part, but it contains all the pieces you could use to build the code if you wanted to do it this way:**
```
$arrTermIDs = [ 1,2,3,4,5 ];
$arrTaxAndTerms = []; // make a 2d array with the term ID's broken down by tax name
foreach ($arrTermIDs as $termID) {
$term = get_term($termID);
if (!in_array($term->taxonomy, $arrTaxAndTerms))
$arrTaxAndTerms[$term->taxonomy] = [] ; // create array for this tax if we don't have one already
$arrTaxAndTerms[$term->taxonomy][] = $termID; // add this term id to array for this tax
}
// Now we have all the info we need to build the tax_query items for each taxonomy
$arrTaxQueryItems = [];
foreach($arrTaxAndTerms as $taxName => $termIDs) {
$arrTaxQueryItems[] =
array(
'taxonomy' => $taxName,
'field' => 'term_id',
'terms' => $termIDs
);
}
// Put that together into your $args:
$args = array(
'numberposts' => -1,
'post_type' => array('post'),
'post_status' => 'publish',
// any other conditions you want here
'tax_query' => array(
'relation' => 'AND',
$arrTaxQueryItems
)
)
``` |
371,872 | <p>Title says it all. I'm trying to link to the most recent post of a custom post type, but only within the same term. Currently my code successfully echos the correct term ID but doesn't show a link on the screen.</p>
<pre><code><?php
// Get the ID of the current posts's term
$terms = get_the_terms( get_the_ID(), 'comic-series' );
// Only get the parent term and ignore child terms
foreach ( $terms as $term ){
if ( $term->parent == 0 ) {
// Echo the term (this is only for debugging purposes)
echo $term->term_id;
// Take only the most recent post of same term
$args = array( 'numberposts' => '1', 'category' => $term->term_id );
$recent_posts = wp_get_recent_posts( $args );
// Link to most recent post of same term
foreach( $recent_posts as $recent ){ ?>
<a href="<?php get_the_permalink( $recent->ID ); ?>">
>>
</a> <?php
}
}
}
?>
</code></pre>
| [
{
"answer_id": 371874,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if this is the only error, but watch out for WP functions that have <code>get_</code> on the front,... | 2020/07/27 | [
"https://wordpress.stackexchange.com/questions/371872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191954/"
] | Title says it all. I'm trying to link to the most recent post of a custom post type, but only within the same term. Currently my code successfully echos the correct term ID but doesn't show a link on the screen.
```
<?php
// Get the ID of the current posts's term
$terms = get_the_terms( get_the_ID(), 'comic-series' );
// Only get the parent term and ignore child terms
foreach ( $terms as $term ){
if ( $term->parent == 0 ) {
// Echo the term (this is only for debugging purposes)
echo $term->term_id;
// Take only the most recent post of same term
$args = array( 'numberposts' => '1', 'category' => $term->term_id );
$recent_posts = wp_get_recent_posts( $args );
// Link to most recent post of same term
foreach( $recent_posts as $recent ){ ?>
<a href="<?php get_the_permalink( $recent->ID ); ?>">
>>
</a> <?php
}
}
}
?>
``` | I ended up using wp\_query instead because I couldn't make wp\_get\_recent\_posts work no matter what I tried. For anyone who needs this functionality in the future, here's the code I used:
```
// Get the ID of the current posts's term
$terms = get_the_terms( $post->ID, 'comic-series' );
// Only get the parent term and ignore child terms
foreach ( $terms as $term ){
if ( $term->parent == 0 ) {
// Query Options
$query_options = array(
'posts_per_page' => 1,
'orderby' => 'title', // I've ordered all my posts by title but change this for your needs
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'comic-series',
'field' => 'term_id',
'terms' => $term->term_id,
),
),
);
//Query
$the_query = new WP_Query( $query_options );
while ($the_query -> have_posts()) : $the_query -> the_post();
// Link to the latest page
?> <a href="<?php the_permalink(); ?>">LINK TEXT</a> <?php
endwhile;
wp_reset_postdata();
}
}
``` |
371,923 | <p>I'm trying to get all the post types that has tags functionality. I searched a lot but couldn't find a conditional or something for that. I need a way to get post types or post objects for the posts which are taggable.</p>
<p>Here are my current code to get post types:</p>
<pre><code>public function getPostTypes() {
$excludes = array('attachment');
$postTypes = get_post_types(
array(
'public' => true,
),
'names'
);
foreach ($excludes as $exclude) {
unset($postTypes[$exclude]);
}
return array_values($postTypes);
}
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 371874,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if this is the only error, but watch out for WP functions that have <code>get_</code> on the front,... | 2020/07/28 | [
"https://wordpress.stackexchange.com/questions/371923",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/171820/"
] | I'm trying to get all the post types that has tags functionality. I searched a lot but couldn't find a conditional or something for that. I need a way to get post types or post objects for the posts which are taggable.
Here are my current code to get post types:
```
public function getPostTypes() {
$excludes = array('attachment');
$postTypes = get_post_types(
array(
'public' => true,
),
'names'
);
foreach ($excludes as $exclude) {
unset($postTypes[$exclude]);
}
return array_values($postTypes);
}
```
Thanks! | I ended up using wp\_query instead because I couldn't make wp\_get\_recent\_posts work no matter what I tried. For anyone who needs this functionality in the future, here's the code I used:
```
// Get the ID of the current posts's term
$terms = get_the_terms( $post->ID, 'comic-series' );
// Only get the parent term and ignore child terms
foreach ( $terms as $term ){
if ( $term->parent == 0 ) {
// Query Options
$query_options = array(
'posts_per_page' => 1,
'orderby' => 'title', // I've ordered all my posts by title but change this for your needs
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'comic-series',
'field' => 'term_id',
'terms' => $term->term_id,
),
),
);
//Query
$the_query = new WP_Query( $query_options );
while ($the_query -> have_posts()) : $the_query -> the_post();
// Link to the latest page
?> <a href="<?php the_permalink(); ?>">LINK TEXT</a> <?php
endwhile;
wp_reset_postdata();
}
}
``` |
371,930 | <p>I have pagination with next/previous links but I also would like to show numbers so the user can click on 2, 3, 4 etc. Pagination seems more tricky with WP_User_Query as there isn't any default WordPress pagination for this as far as I know. The below works correctly as far as I can tell for the next and previous links.</p>
<pre><code>$current_page = get_query_var('paged') ? (int) get_query_var('paged') : 1;
$users_per_page = 2;
$args = array(
'number' => $users_per_page,
'paged' => $current_page
);
$wp_user_query = new WP_User_Query( $args );
$total_users = $wp_user_query->get_total();
$num_pages = ceil($total_users / $users_per_page);
<?php
// Previous page
if ( $current_page > 1 ) {
echo '<a href="'. add_query_arg(array('paged' => $current_page-1)) .'" class="prev">Prev</a>';
}
// Next page
if ( $current_page < $num_pages ) {
echo '<a href="'. add_query_arg(array('paged' => $current_page+1)) .'" class="next">Next</a>';
}
?>
</code></pre>
| [
{
"answer_id": 371934,
"author": "maulik zwt",
"author_id": 191968,
"author_profile": "https://wordpress.stackexchange.com/users/191968",
"pm_score": -1,
"selected": false,
"text": "<p>Please try below function for numeric pagination and change query variable as per your requirement.</p>... | 2020/07/28 | [
"https://wordpress.stackexchange.com/questions/371930",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140276/"
] | I have pagination with next/previous links but I also would like to show numbers so the user can click on 2, 3, 4 etc. Pagination seems more tricky with WP\_User\_Query as there isn't any default WordPress pagination for this as far as I know. The below works correctly as far as I can tell for the next and previous links.
```
$current_page = get_query_var('paged') ? (int) get_query_var('paged') : 1;
$users_per_page = 2;
$args = array(
'number' => $users_per_page,
'paged' => $current_page
);
$wp_user_query = new WP_User_Query( $args );
$total_users = $wp_user_query->get_total();
$num_pages = ceil($total_users / $users_per_page);
<?php
// Previous page
if ( $current_page > 1 ) {
echo '<a href="'. add_query_arg(array('paged' => $current_page-1)) .'" class="prev">Prev</a>';
}
// Next page
if ( $current_page < $num_pages ) {
echo '<a href="'. add_query_arg(array('paged' => $current_page+1)) .'" class="next">Next</a>';
}
?>
``` | You can use [`paginate_links()`](https://developer.wordpress.org/reference/functions/paginate_links/):
```php
echo paginate_links( array(
'current' => $current_page,
'total' => $num_pages,
) );
``` |
371,946 | <p>i want to add a dynamic JSON-LD (schema.org) for career posts in my wordpress page. I tried this code below. But i think i have some Syntax errors within the array. Maybe the "echo" is not allowed within the array? I hope somebody can help me with this?</p>
<pre><code><?php function schema() {?>
<?php if( have_rows('schema_auszeichnung') ): ?>
<?php while( have_rows('schema_auszeichnung') ): the_row();
// Get sub field values.
$title = get_sub_field('title');
$description = get_sub_field('description');
$state = get_sub_field('state');
$date = get_sub_field('date');
$street = get_sub_field('street');
$city = get_sub_field('city');
$postalcode = get_sub_field('postalcode');
$schema = array(
'@context' => 'http://schema.org',
'@type' => 'JobPosting',
'title' => $title,
'description' => $description,
'hiringOrganization' => array(
'@type' => 'Organization',
'name' => 'cent GmbH',
'sameAs' => get_home_url(),
'logo' => '/wp/wp-content/uploads/2016/11/cropped-logo.png'
),
'employmentType'=> $state,
'datePosted' => $date,
'validThrough' => "",
'jobLocation' => array(
'@type' => "Place",
'address' => array (
'@type' => 'PostalAddress',
'streetAddress' => $street,
'adressLocality' => $city,
'postalCode' => $postalcode,
'addressCountry' => 'DE'
),
),
);
?>
<?php endwhile; ?>
<?php endif; ?>
<?php
echo '<script type="application/ld+json">' . json_encode($schema) . '</script>';
}
add_action('wp_head', 'schema');
?>
</code></pre>
<p>EDIT:</p>
<p>After removing the 'echo' i got the php warning: Undefined variable: schema. But for me it is defined in this line: $schema = array.....</p>
| [
{
"answer_id": 371947,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 3,
"selected": true,
"text": "<p>This seems more like a PHP programming question, but yes as you guessed in PHP if you want the value of a var... | 2020/07/28 | [
"https://wordpress.stackexchange.com/questions/371946",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82174/"
] | i want to add a dynamic JSON-LD (schema.org) for career posts in my wordpress page. I tried this code below. But i think i have some Syntax errors within the array. Maybe the "echo" is not allowed within the array? I hope somebody can help me with this?
```
<?php function schema() {?>
<?php if( have_rows('schema_auszeichnung') ): ?>
<?php while( have_rows('schema_auszeichnung') ): the_row();
// Get sub field values.
$title = get_sub_field('title');
$description = get_sub_field('description');
$state = get_sub_field('state');
$date = get_sub_field('date');
$street = get_sub_field('street');
$city = get_sub_field('city');
$postalcode = get_sub_field('postalcode');
$schema = array(
'@context' => 'http://schema.org',
'@type' => 'JobPosting',
'title' => $title,
'description' => $description,
'hiringOrganization' => array(
'@type' => 'Organization',
'name' => 'cent GmbH',
'sameAs' => get_home_url(),
'logo' => '/wp/wp-content/uploads/2016/11/cropped-logo.png'
),
'employmentType'=> $state,
'datePosted' => $date,
'validThrough' => "",
'jobLocation' => array(
'@type' => "Place",
'address' => array (
'@type' => 'PostalAddress',
'streetAddress' => $street,
'adressLocality' => $city,
'postalCode' => $postalcode,
'addressCountry' => 'DE'
),
),
);
?>
<?php endwhile; ?>
<?php endif; ?>
<?php
echo '<script type="application/ld+json">' . json_encode($schema) . '</script>';
}
add_action('wp_head', 'schema');
?>
```
EDIT:
After removing the 'echo' i got the php warning: Undefined variable: schema. But for me it is defined in this line: $schema = array..... | This seems more like a PHP programming question, but yes as you guessed in PHP if you want the value of a variable you just need `$var`. `echo $var` outputs it and will cause a syntax error how you've used it.
Otherwise everything else looks ok, although obviously I can't say if that data structure will give you valid JSON-LD ;-)
EDIT: Also it's good to give your functions a more unique name than `'schema'`. You could call it `'yourname_jsonld_schema'` or something, so that it's much more unique and unlikely to collide with any other names in Wordpress
EDIT2: To address the extra error you added to your question, the place you define `$schema` is *inside* an `if` statement, which means that if the variable is not defined later, that `if` was not true. So you need to do something like figure out why the `if` is false, or if it's correct, put the place where you use the `$schema` inside the `if` too. |
371,968 | <p>I'm trying to remove a parent theme's add_action call to a pluggable function, but can't get it to work by calling <code>remove_action()</code> - I have to redeclare the function and just leave it empty. Is this normal? I'd think I could use <code>remove_action</code> to simply never call the function.</p>
<p>Here's the parent theme code:</p>
<pre><code>add_action( 'tha_content_while_before', 'fwp_archive_header' );
if ( !function_exists('fwp_archive_header') ) {
function fwp_archive_header() {
// do stuff
}
}
</code></pre>
<p>And in the child theme (NOT working):</p>
<pre><code>add_action( 'init', 'remove_parent_actions_filters' );
function remove_parent_actions_filters() {
remove_action( 'tha_content_while_before', 'fwp_archive_header' );
}
</code></pre>
<p>I have also tried swapping out '<code>init</code>' for '<code>after_setup_theme</code>' and '<code>wp_loaded</code>'; I've also tried lowering and raising the priority, nothing worked. The only thing that did work was this:</p>
<p>In the child theme (working):</p>
<pre><code>function fwp_archive_header() {
// do nothing
}
</code></pre>
<p>Can that be right, I have to redeclare the function to get rid of it?</p>
<p>Thanks!</p>
| [
{
"answer_id": 371971,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Inside your remove_parent_actions_filters() function, add a test to see if the parent theme's function... | 2020/07/28 | [
"https://wordpress.stackexchange.com/questions/371968",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16/"
] | I'm trying to remove a parent theme's add\_action call to a pluggable function, but can't get it to work by calling `remove_action()` - I have to redeclare the function and just leave it empty. Is this normal? I'd think I could use `remove_action` to simply never call the function.
Here's the parent theme code:
```
add_action( 'tha_content_while_before', 'fwp_archive_header' );
if ( !function_exists('fwp_archive_header') ) {
function fwp_archive_header() {
// do stuff
}
}
```
And in the child theme (NOT working):
```
add_action( 'init', 'remove_parent_actions_filters' );
function remove_parent_actions_filters() {
remove_action( 'tha_content_while_before', 'fwp_archive_header' );
}
```
I have also tried swapping out '`init`' for '`after_setup_theme`' and '`wp_loaded`'; I've also tried lowering and raising the priority, nothing worked. The only thing that did work was this:
In the child theme (working):
```
function fwp_archive_header() {
// do nothing
}
```
Can that be right, I have to redeclare the function to get rid of it?
Thanks! | The parent theme's functions.php runs **after** the child theme's, so in order to remove an action defined by the parent theme the `remove_action` call must be delayed using a hook after the parent theme registers the action. So putting the `remove_action` call purely inside the child's functions.php won't work. It must be attached to a hook.
However from the code excerpt in the question it is not clear if the parent's `add_action( 'tha_content_while_before', 'fwp_archive_header' );` line is just in functions.php or is that inside an action? If it is inside an action, hook the `remove_action` call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent `add_action` call is inside. Something like this:
```
add_action( 'some_hook', 'some_parent_function', 10 );
function some_parent_function() {
/* ...some code... */
add_action( 'tha_content_while_before', 'fwp_archive_header' );
if ( !function_exists('fwp_archive_header') ) {
function fwp_archive_header() {
// do stuff
}
}
/* ...some code... */
}
```
The remove would look like:
```
add_action( 'some_hook', 'remove_parent_actions_filters', 11 );
function remove_parent_actions_filters() {
remove_action( 'tha_content_while_before', 'fwp_archive_header' );
}
```
---
Another rule of thumb attempt is to hook your remove call to `wp_loaded`, e.g.: `add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );`. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks.
---
On the other hand declaring an empty function with the name `fwp_archive_header` is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place). |
371,997 | <p>i want to send email only new post publish in wordpress admin</p>
<p>when i pulish anything its sending mail to user how to restric this to only new post added to send mail to user</p>
<pre><code> function wpse_19040_notify_admin_on_publish( $new_status, $old_status, $post ) {
if ( $new_status !== 'publish' || $old_status === 'publish' )
return;
if ( ! $post_type = get_post_type_object( $post->post_type ) )
return;
global $wpdb;
$newsletterdata = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."newsletter");
foreach ( $newsletterdata as $newsletteremailall )
{
$newsletteremailall = $newsletteremailall->email;
if(filter_var($newsletteremailall, FILTER_VALIDATE_EMAIL))
{
$subject = $post->post_title;
$message = 'Our new post is here '."\n".'Post Title: ' .$post->post_title. "\n"."click here to visit post: " . get_permalink( $post->ID );
wp_mail( $newsletteremailall, $subject, $message );
}
else
{
}
}
}
add_action( 'transition_post_status', 'wpse_19040_notify_admin_on_publish', 10, 3 );
</code></pre>
| [
{
"answer_id": 371971,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Inside your remove_parent_actions_filters() function, add a test to see if the parent theme's function... | 2020/07/29 | [
"https://wordpress.stackexchange.com/questions/371997",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192212/"
] | i want to send email only new post publish in wordpress admin
when i pulish anything its sending mail to user how to restric this to only new post added to send mail to user
```
function wpse_19040_notify_admin_on_publish( $new_status, $old_status, $post ) {
if ( $new_status !== 'publish' || $old_status === 'publish' )
return;
if ( ! $post_type = get_post_type_object( $post->post_type ) )
return;
global $wpdb;
$newsletterdata = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."newsletter");
foreach ( $newsletterdata as $newsletteremailall )
{
$newsletteremailall = $newsletteremailall->email;
if(filter_var($newsletteremailall, FILTER_VALIDATE_EMAIL))
{
$subject = $post->post_title;
$message = 'Our new post is here '."\n".'Post Title: ' .$post->post_title. "\n"."click here to visit post: " . get_permalink( $post->ID );
wp_mail( $newsletteremailall, $subject, $message );
}
else
{
}
}
}
add_action( 'transition_post_status', 'wpse_19040_notify_admin_on_publish', 10, 3 );
``` | The parent theme's functions.php runs **after** the child theme's, so in order to remove an action defined by the parent theme the `remove_action` call must be delayed using a hook after the parent theme registers the action. So putting the `remove_action` call purely inside the child's functions.php won't work. It must be attached to a hook.
However from the code excerpt in the question it is not clear if the parent's `add_action( 'tha_content_while_before', 'fwp_archive_header' );` line is just in functions.php or is that inside an action? If it is inside an action, hook the `remove_action` call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent `add_action` call is inside. Something like this:
```
add_action( 'some_hook', 'some_parent_function', 10 );
function some_parent_function() {
/* ...some code... */
add_action( 'tha_content_while_before', 'fwp_archive_header' );
if ( !function_exists('fwp_archive_header') ) {
function fwp_archive_header() {
// do stuff
}
}
/* ...some code... */
}
```
The remove would look like:
```
add_action( 'some_hook', 'remove_parent_actions_filters', 11 );
function remove_parent_actions_filters() {
remove_action( 'tha_content_while_before', 'fwp_archive_header' );
}
```
---
Another rule of thumb attempt is to hook your remove call to `wp_loaded`, e.g.: `add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );`. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks.
---
On the other hand declaring an empty function with the name `fwp_archive_header` is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place). |
372,050 | <p>I want to get the total number of results after searching WordPress users by role and a string that matches the user name.</p>
<p>What I tried so far:</p>
<pre><code>$args= array('echo'=>false, 'role' => 'author', 'search'=>$search_txt);
$user_query = new WP_User_Query($args);
$auth_count= $user_query->get_total();
</code></pre>
<p>But it returns 0 everytime.</p>
<p><strong>Note:</strong></p>
<p>Perhaps it can be done by:</p>
<pre><code>$args= array('echo'=>false, 'role' => 'author', 'search'=>$search_txt);
$auth_count= count(get_users($args));
</code></pre>
<p>or by querying with</p>
<pre><code>global $wpdb;
</code></pre>
<p>But is there any more resource friendly method?</p>
| [
{
"answer_id": 371971,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Inside your remove_parent_actions_filters() function, add a test to see if the parent theme's function... | 2020/07/29 | [
"https://wordpress.stackexchange.com/questions/372050",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92425/"
] | I want to get the total number of results after searching WordPress users by role and a string that matches the user name.
What I tried so far:
```
$args= array('echo'=>false, 'role' => 'author', 'search'=>$search_txt);
$user_query = new WP_User_Query($args);
$auth_count= $user_query->get_total();
```
But it returns 0 everytime.
**Note:**
Perhaps it can be done by:
```
$args= array('echo'=>false, 'role' => 'author', 'search'=>$search_txt);
$auth_count= count(get_users($args));
```
or by querying with
```
global $wpdb;
```
But is there any more resource friendly method? | The parent theme's functions.php runs **after** the child theme's, so in order to remove an action defined by the parent theme the `remove_action` call must be delayed using a hook after the parent theme registers the action. So putting the `remove_action` call purely inside the child's functions.php won't work. It must be attached to a hook.
However from the code excerpt in the question it is not clear if the parent's `add_action( 'tha_content_while_before', 'fwp_archive_header' );` line is just in functions.php or is that inside an action? If it is inside an action, hook the `remove_action` call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent `add_action` call is inside. Something like this:
```
add_action( 'some_hook', 'some_parent_function', 10 );
function some_parent_function() {
/* ...some code... */
add_action( 'tha_content_while_before', 'fwp_archive_header' );
if ( !function_exists('fwp_archive_header') ) {
function fwp_archive_header() {
// do stuff
}
}
/* ...some code... */
}
```
The remove would look like:
```
add_action( 'some_hook', 'remove_parent_actions_filters', 11 );
function remove_parent_actions_filters() {
remove_action( 'tha_content_while_before', 'fwp_archive_header' );
}
```
---
Another rule of thumb attempt is to hook your remove call to `wp_loaded`, e.g.: `add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );`. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks.
---
On the other hand declaring an empty function with the name `fwp_archive_header` is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place). |
372,068 | <p>We have rewrite rules as:</p>
<pre><code>add_action( 'init', function() {
add_rewrite_rule( 'app-api/v2/ecommerce/([a-z0-9-]+)[/]?$', 'index.php?p=$matches[1]&post_type=product' );
} );
</code></pre>
<p>for the URL - <code>www.domain.com/app-api/v2/ecommerce/14</code>. We load a custom template using <code>template_include</code> hook for custom rules.</p>
<p>The above works fine, but for some specific reasons the client wants to make use of query variables so that the new URL will be of the form <code>www.domain.com/app-api/v2/ecommerce?pid=14</code></p>
<p>What I am trying to achieve is something like this, which doesn't work.</p>
<pre><code>add_action( 'init', function() {
$id = $_GET['pid'];
add_rewrite_rule( 'app-api/v2/ecommerce', "index.php?p={$id}&post_type=product" );
} );
</code></pre>
<p>What is the correct way to add a rewrite rule with dynamic query variables?</p>
| [
{
"answer_id": 371971,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Inside your remove_parent_actions_filters() function, add a test to see if the parent theme's function... | 2020/07/30 | [
"https://wordpress.stackexchange.com/questions/372068",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67538/"
] | We have rewrite rules as:
```
add_action( 'init', function() {
add_rewrite_rule( 'app-api/v2/ecommerce/([a-z0-9-]+)[/]?$', 'index.php?p=$matches[1]&post_type=product' );
} );
```
for the URL - `www.domain.com/app-api/v2/ecommerce/14`. We load a custom template using `template_include` hook for custom rules.
The above works fine, but for some specific reasons the client wants to make use of query variables so that the new URL will be of the form `www.domain.com/app-api/v2/ecommerce?pid=14`
What I am trying to achieve is something like this, which doesn't work.
```
add_action( 'init', function() {
$id = $_GET['pid'];
add_rewrite_rule( 'app-api/v2/ecommerce', "index.php?p={$id}&post_type=product" );
} );
```
What is the correct way to add a rewrite rule with dynamic query variables? | The parent theme's functions.php runs **after** the child theme's, so in order to remove an action defined by the parent theme the `remove_action` call must be delayed using a hook after the parent theme registers the action. So putting the `remove_action` call purely inside the child's functions.php won't work. It must be attached to a hook.
However from the code excerpt in the question it is not clear if the parent's `add_action( 'tha_content_while_before', 'fwp_archive_header' );` line is just in functions.php or is that inside an action? If it is inside an action, hook the `remove_action` call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent `add_action` call is inside. Something like this:
```
add_action( 'some_hook', 'some_parent_function', 10 );
function some_parent_function() {
/* ...some code... */
add_action( 'tha_content_while_before', 'fwp_archive_header' );
if ( !function_exists('fwp_archive_header') ) {
function fwp_archive_header() {
// do stuff
}
}
/* ...some code... */
}
```
The remove would look like:
```
add_action( 'some_hook', 'remove_parent_actions_filters', 11 );
function remove_parent_actions_filters() {
remove_action( 'tha_content_while_before', 'fwp_archive_header' );
}
```
---
Another rule of thumb attempt is to hook your remove call to `wp_loaded`, e.g.: `add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );`. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks.
---
On the other hand declaring an empty function with the name `fwp_archive_header` is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place). |
372,110 | <p>I have a problem, when I am on page 2 or on any other page and I want to return to the index, the url that offers me the pagination on page 1 is the following (<a href="https://www.url.com/page/1" rel="nofollow noreferrer">https://www.url.com/page/1</a>) and I would like it to be as it usually is (<a href="https://www.url.com" rel="nofollow noreferrer">https://www.url.com</a>)</p>
<p>El código que tengo en el fuctions.php es el siguiente:</p>
<pre><code>function mt_paginacion($tipo=1,$class=NULL,$qc=NULL){
global $wp_query,$paged;
if($qc==''){$total=$wp_query->max_num_pages;}else{$total=$qc;}
if($tipo==1){
$paginacion=paginate_links( array(
'base' => str_replace(999999999, '%#%', esc_url( get_pagenum_link(999999999) ) ),
'format' => '?paged=%#%',
'current' => max( 1, $paged ),
'total' => $total,
'mid_size' => 3,
'prev_next' => true
) );
</code></pre>
| [
{
"answer_id": 372163,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>You can do a simple <code>str_replace( '/page/1/', '/', $string )</code> on the results generated by <code>... | 2020/07/30 | [
"https://wordpress.stackexchange.com/questions/372110",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192472/"
] | I have a problem, when I am on page 2 or on any other page and I want to return to the index, the url that offers me the pagination on page 1 is the following (<https://www.url.com/page/1>) and I would like it to be as it usually is (<https://www.url.com>)
El código que tengo en el fuctions.php es el siguiente:
```
function mt_paginacion($tipo=1,$class=NULL,$qc=NULL){
global $wp_query,$paged;
if($qc==''){$total=$wp_query->max_num_pages;}else{$total=$qc;}
if($tipo==1){
$paginacion=paginate_links( array(
'base' => str_replace(999999999, '%#%', esc_url( get_pagenum_link(999999999) ) ),
'format' => '?paged=%#%',
'current' => max( 1, $paged ),
'total' => $total,
'mid_size' => 3,
'prev_next' => true
) );
``` | You can do a simple `str_replace( '/page/1/', '/', $string )` on the results generated by `paginate_links()` to get rid of `/page/1/` which appears on the first page link as well as the Prev link (when it points to the first page).
Here's a full (tested) example:
```
/**
* Numeric pagination via WP core function paginate_links().
* @link http://codex.wordpress.org/Function_Reference/paginate_links
*
* @param array $srgs
*
* @return string HTML for numneric pagination
*/
function wpse_pagination( $args = array() ) {
global $wp_query;
if ( $wp_query->max_num_pages <= 1 ) {
return;
}
$pagination_args = array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $wp_query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'type' => 'array',
'end_size' => 2,
'mid_size' => 3,
'prev_next' => true,
'prev_text' => __( '« Prev', 'wpse' ),
'next_text' => __( 'Next »', 'wpse' ),
'add_args' => false,
'add_fragment' => '',
// Custom arguments not part of WP core:
'show_page_position' => false, // Optionally allows the "Page X of XX" HTML to be displayed.
);
$pagination = paginate_links( array_merge( $pagination_args, $args ) );
// Remove /page/1/ from links.
$pagination = array_map(
function( $string ) {
return str_replace( '/page/1/', '/', $string );
},
$pagination
);
return implode( '', $pagination );
}
```
**Usage:**
```
echo wpse_pagination();
``` |
372,112 | <p>I would like to be able to post the most recent updated date in my footer. However, I can't seem to find a way to do that globally for the site, just for each post/page at a time using <code>get_the_modified_date()</code>.</p>
<p>So for example if I make a change to my home page the footer would be updated to that date and time. If I later make an edit to a miscellaneous page, then the "Updated" date and time would change to reflect that more recent update.</p>
<p>Any help is greatly appreciated.</p>
| [
{
"answer_id": 372121,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if there's a more WP-friendly way to do this, but this query will do what you want. It gets the... | 2020/07/30 | [
"https://wordpress.stackexchange.com/questions/372112",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165195/"
] | I would like to be able to post the most recent updated date in my footer. However, I can't seem to find a way to do that globally for the site, just for each post/page at a time using `get_the_modified_date()`.
So for example if I make a change to my home page the footer would be updated to that date and time. If I later make an edit to a miscellaneous page, then the "Updated" date and time would change to reflect that more recent update.
Any help is greatly appreciated. | Just a continuation from mozboz' answer. For those curious as I was, you could use the date() or date\_i18n() functions to format the date properly in the following snippet.
```
function get_latest_update_date() {
global $wpdb;
$thelatest = $wpdb->get_var("SELECT max(post_modified) FROM wp_posts WHERE post_type IN ('post', 'page');");
//returns formatted date like 13.08.2001
return date_i18n('j.m.Y', strtotime($thelatest));
}
add_shortcode('latestupdatedate', 'get_latest_update_date');
``` |
372,204 | <p>I got one plugin which generates all CSS and JS on the /wp-content/uploads/xyz-folder,
I want to disable all this CSS and JS load on my website page.</p>
<p>Is it possible?</p>
| [
{
"answer_id": 372121,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if there's a more WP-friendly way to do this, but this query will do what you want. It gets the... | 2020/08/01 | [
"https://wordpress.stackexchange.com/questions/372204",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192540/"
] | I got one plugin which generates all CSS and JS on the /wp-content/uploads/xyz-folder,
I want to disable all this CSS and JS load on my website page.
Is it possible? | Just a continuation from mozboz' answer. For those curious as I was, you could use the date() or date\_i18n() functions to format the date properly in the following snippet.
```
function get_latest_update_date() {
global $wpdb;
$thelatest = $wpdb->get_var("SELECT max(post_modified) FROM wp_posts WHERE post_type IN ('post', 'page');");
//returns formatted date like 13.08.2001
return date_i18n('j.m.Y', strtotime($thelatest));
}
add_shortcode('latestupdatedate', 'get_latest_update_date');
``` |
372,280 | <p>I've spent about 3 hours trying out various functions to figure out why the newline characters are being removed every time I save.</p>
<p>How do I figure out why is wordpress suddenly stripping away newline characters? I have not installed any plugins. How can I get newline characters to show up on my site without converting all blocks to HTML and modifying everything in code?</p>
| [
{
"answer_id": 372281,
"author": "Mugen",
"author_id": 167402,
"author_profile": "https://wordpress.stackexchange.com/users/167402",
"pm_score": 2,
"selected": true,
"text": "<p>I found the following snippet which we can add to functions.php . I'm adding these via a plugin.</p>\n<pre><co... | 2020/08/03 | [
"https://wordpress.stackexchange.com/questions/372280",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/167402/"
] | I've spent about 3 hours trying out various functions to figure out why the newline characters are being removed every time I save.
How do I figure out why is wordpress suddenly stripping away newline characters? I have not installed any plugins. How can I get newline characters to show up on my site without converting all blocks to HTML and modifying everything in code? | I found the following snippet which we can add to functions.php . I'm adding these via a plugin.
```
function clear_br($content) {
return str_replace("<br>","<br clear='none'>", $content);
}
add_filter('the_content','clear_br');
```
Note that I've put `"<br>"` tag which is what wordpress creates when you enter newline characters. |
372,308 | <p>I have a custom post type where the <code>title</code> is a name, and I want to sort the loop by the last word in <code>title</code>, the surname.</p>
<p>I can easily break the names apart and filter by the last word in a custom query, but I don't want to re-write the main loop / pagination for the archive page. Is it possible to pass a callback to the <code>orderby</code> param in the action <code>pre_get_posts</code> or is this a lost cause?</p>
<p>Thanks!</p>
| [
{
"answer_id": 372309,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For th... | 2020/08/04 | [
"https://wordpress.stackexchange.com/questions/372308",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76674/"
] | I have a custom post type where the `title` is a name, and I want to sort the loop by the last word in `title`, the surname.
I can easily break the names apart and filter by the last word in a custom query, but I don't want to re-write the main loop / pagination for the archive page. Is it possible to pass a callback to the `orderby` param in the action `pre_get_posts` or is this a lost cause?
Thanks! | No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For that to work it would need to query the results from the database first, but you'd get the wrong results because they're unsorted.
You would need to use the `posts_orderby` filter to do this as part of the SQL query:
```
add_filter(
'posts_orderby',
function( $orderby, $query ) {
if ( ! is_admin() && $query->is_post_type_archive( 'post_type_name' ) ) {
$orderby = "SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC";
}
return $orderby;
},
10,
2
);
```
That uses the `SUBSTRING_INDEX()` MySQL function to order results by everything after the ~~first~~ last space in the post title, and then by the post title so that results with matching surnames are sorted by first name. |
372,317 | <p><strong>Hey guys</strong> I am developing a wp theme, and I am using for localhost server XAMPP and Wampserver.So anytime I save my changes specially for css and js it doesn't take effects immediately! sometimes it can takes up to 24h for the changes to take effects, how can I solve this issue, it really slowdown my work???</p>
| [
{
"answer_id": 372309,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For th... | 2020/08/04 | [
"https://wordpress.stackexchange.com/questions/372317",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192491/"
] | **Hey guys** I am developing a wp theme, and I am using for localhost server XAMPP and Wampserver.So anytime I save my changes specially for css and js it doesn't take effects immediately! sometimes it can takes up to 24h for the changes to take effects, how can I solve this issue, it really slowdown my work??? | No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For that to work it would need to query the results from the database first, but you'd get the wrong results because they're unsorted.
You would need to use the `posts_orderby` filter to do this as part of the SQL query:
```
add_filter(
'posts_orderby',
function( $orderby, $query ) {
if ( ! is_admin() && $query->is_post_type_archive( 'post_type_name' ) ) {
$orderby = "SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC";
}
return $orderby;
},
10,
2
);
```
That uses the `SUBSTRING_INDEX()` MySQL function to order results by everything after the ~~first~~ last space in the post title, and then by the post title so that results with matching surnames are sorted by first name. |
372,338 | <p>I have a plugin that has a meta field that keeps shares for the post in array format:</p>
<pre><code>["facebook" => 12, "pinterest" => 12]
</code></pre>
<p>I would like to get 3 most shared posts (by all shares combined) in custom WP Query, but not sure how to it as it only allows to provide meta filed and value, but not the function?</p>
<p>Is it possible to have custom sorting function there?</p>
| [
{
"answer_id": 372309,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": true,
"text": "<p>No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For th... | 2020/08/04 | [
"https://wordpress.stackexchange.com/questions/372338",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121208/"
] | I have a plugin that has a meta field that keeps shares for the post in array format:
```
["facebook" => 12, "pinterest" => 12]
```
I would like to get 3 most shared posts (by all shares combined) in custom WP Query, but not sure how to it as it only allows to provide meta filed and value, but not the function?
Is it possible to have custom sorting function there? | No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For that to work it would need to query the results from the database first, but you'd get the wrong results because they're unsorted.
You would need to use the `posts_orderby` filter to do this as part of the SQL query:
```
add_filter(
'posts_orderby',
function( $orderby, $query ) {
if ( ! is_admin() && $query->is_post_type_archive( 'post_type_name' ) ) {
$orderby = "SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC";
}
return $orderby;
},
10,
2
);
```
That uses the `SUBSTRING_INDEX()` MySQL function to order results by everything after the ~~first~~ last space in the post title, and then by the post title so that results with matching surnames are sorted by first name. |
372,347 | <p>I have created a form where users update their profile. When a profile is created or updated it creates a CPT called course. The url is <code>the permalink + /course/ + the title of the course</code></p>
<pre><code>/* CREATING COURSE PAGES FROM USER PROFILES */
function create_course_page( $user_id = '' ) {
$user = new WP_User($user_id);
if ( ! $user->ID ) return '';
// check if the user whose profile is updating has already a post
global $wpdb;
$course_post_exists = $wpdb->get_var( $wpdb->prepare(
"SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type = 'course' and post_status = 'publish'", $user->course_name
) );
if ( ! in_array('instructor', $user->roles) ) return '';
$user_info = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user->ID ) );
$title = $user_info['course_name'];
// of course create the content as you want
$content = 'This is the page for: ';
$content .= $user_info['description_course'];
$post = array(
'post_title' => $title,
'post_name' => $user->course_name,
'post_content' => $content,
'post_status' => 'publish',
'post_type' => 'course'
);
if ( $course_post_exists ) {
$post['ID'] = $course_post_exists;
wp_update_post( $post );
} else {
wp_insert_post( $post );
}
}
add_action( 'personal_options_update', 'create_course_page' );
add_action( 'edit_user_profile_update', 'create_course_page' );
</code></pre>
<p>The problem that I'm facing is that when someone changes the title of the course it creates a new post with this url.</p>
<p>So I want to delete the old post when a title change is done on the course.</p>
<p>NOTE: When changing title of the course it changes the URL, that is why I think it takes like a new post.</p>
<p>I have customised this code a bit to do the job:</p>
<pre><code>/* REMOVE OLD COURSES WHEN UPDATE */
add_action( 'admin_init', 'removing_older_posts' );
function removing_older_posts() {
$args = array (
'post_type' => 'course',
'author' => get_current_user_id(),
'orderby' => 'date',
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) { //if the current user has posts under his/her name
$i = 0; //create post counter
while ( $query->have_posts() ) { //loop through each post
$query->the_post(); //get the current post
if ($i > 0) { //if you're not on the first post
wp_delete_post( $query->post->ID, true ); //delete the post
}
$i++; //increment the post counter
}
wp_reset_postdata();
}
}
</code></pre>
<p>But it isn't working.</p>
<p>Appreciate any suggestion :)</p>
| [
{
"answer_id": 372348,
"author": "Oliver Gehrmann",
"author_id": 192667,
"author_profile": "https://wordpress.stackexchange.com/users/192667",
"pm_score": 1,
"selected": false,
"text": "<p>I think it would be helpful if you could explain why you're generating courses out of edits that a ... | 2020/08/04 | [
"https://wordpress.stackexchange.com/questions/372347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/150823/"
] | I have created a form where users update their profile. When a profile is created or updated it creates a CPT called course. The url is `the permalink + /course/ + the title of the course`
```
/* CREATING COURSE PAGES FROM USER PROFILES */
function create_course_page( $user_id = '' ) {
$user = new WP_User($user_id);
if ( ! $user->ID ) return '';
// check if the user whose profile is updating has already a post
global $wpdb;
$course_post_exists = $wpdb->get_var( $wpdb->prepare(
"SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type = 'course' and post_status = 'publish'", $user->course_name
) );
if ( ! in_array('instructor', $user->roles) ) return '';
$user_info = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user->ID ) );
$title = $user_info['course_name'];
// of course create the content as you want
$content = 'This is the page for: ';
$content .= $user_info['description_course'];
$post = array(
'post_title' => $title,
'post_name' => $user->course_name,
'post_content' => $content,
'post_status' => 'publish',
'post_type' => 'course'
);
if ( $course_post_exists ) {
$post['ID'] = $course_post_exists;
wp_update_post( $post );
} else {
wp_insert_post( $post );
}
}
add_action( 'personal_options_update', 'create_course_page' );
add_action( 'edit_user_profile_update', 'create_course_page' );
```
The problem that I'm facing is that when someone changes the title of the course it creates a new post with this url.
So I want to delete the old post when a title change is done on the course.
NOTE: When changing title of the course it changes the URL, that is why I think it takes like a new post.
I have customised this code a bit to do the job:
```
/* REMOVE OLD COURSES WHEN UPDATE */
add_action( 'admin_init', 'removing_older_posts' );
function removing_older_posts() {
$args = array (
'post_type' => 'course',
'author' => get_current_user_id(),
'orderby' => 'date',
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) { //if the current user has posts under his/her name
$i = 0; //create post counter
while ( $query->have_posts() ) { //loop through each post
$query->the_post(); //get the current post
if ($i > 0) { //if you're not on the first post
wp_delete_post( $query->post->ID, true ); //delete the post
}
$i++; //increment the post counter
}
wp_reset_postdata();
}
}
```
But it isn't working.
Appreciate any suggestion :) | I think it would be helpful if you could explain why you're generating courses out of edits that a user's doing on his profile. The simplest solution seems to be a frontend form that just allows a user to create new posts or edit existing ones rather than going for this alternative solution where you're using the data from the profile page to create new posts.
---
If you want to stick to the current implementation, I believe it would be useful for you to look into status transitions: <https://developer.wordpress.org/reference/hooks/transition_post_status/>
Here's some example code that I used to create a post in a the category with the ID 1 (= news) after a custom post type had been created:
```
// Automatically create a news when a wiki post has been published
function nxt_create_news($new_status, $old_status, $nxt_wiki_post) {
if('publish' === $new_status && 'publish' !== $old_status && $nxt_wiki_post->post_type === 'wiki') {
$nxt_post_author = $nxt_wiki_post->post_author;
$nxt_wiki_permalink = get_post_permalink($nxt_wiki_id);
$nxt_wiki_title = $nxt_wiki_post->post_title;
$nxt_postarr = array(
'post_author' => $nxt_post_author,
'post_content' => 'The wiki entry ' . $nxt_wiki_title . ' has just been published.<br /><br /><a href="' . $nxt_wiki_permalink . '" title="' . $nxt_wiki_title . '">Check out wiki entry</a>.',
'post_title' => 'The wiki entry ' . $nxt_wiki_title . ' has been published',
'post_status' => 'publish',
'post_category' => array(1),
);
$nxt_post_id = wp_insert_post($nxt_postarr);
set_post_thumbnail(get_post($nxt_post_id), '1518');
}
}
add_action( 'transition_post_status', 'nxt_create_news', 10, 3 );
```
---
In your specific case, you can compare parts of the saved posts to the new post that would be created and then prevent the default action from happening (a new post being created) and instead just edit the old post.
The main question would be how would the system know which post someone's trying to edit? I can't really answer that as I couldn't make out why you're using the profile edits to create new posts I'm afraid, but I hope this is helpful regardless. :-) |
372,352 | <p>I am using this code so that users can input <code>[photo no="1"], [photo no="2"], [photo no="3"]</code> etc.. in their posts. However I heard that <code>extract</code> is an unsafe function to use. How could I modify this code to remove <code>extract</code>?</p>
<pre><code> function photo_shortcode($atts){
extract(shortcode_atts(array(
'no' => 1,
), $atts));
$no = is_numeric($no) ? (int) $no : 1;
$images = get_field('fl_gallery');
if ( !empty( $images ) ) {
$image = $images[$no];
return ' $image['url'] ' ;
}
}
</code></pre>
| [
{
"answer_id": 372355,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<p>It's very simple: Just assign the value of <code>shortcode_atts()</code> (which is an array) to a variable ... | 2020/08/04 | [
"https://wordpress.stackexchange.com/questions/372352",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] | I am using this code so that users can input `[photo no="1"], [photo no="2"], [photo no="3"]` etc.. in their posts. However I heard that `extract` is an unsafe function to use. How could I modify this code to remove `extract`?
```
function photo_shortcode($atts){
extract(shortcode_atts(array(
'no' => 1,
), $atts));
$no = is_numeric($no) ? (int) $no : 1;
$images = get_field('fl_gallery');
if ( !empty( $images ) ) {
$image = $images[$no];
return ' $image['url'] ' ;
}
}
``` | It's very simple: Just assign the value of `shortcode_atts()` (which is an array) to a variable and use it to access the shortcode attributes in the same way you access the items in any other arrays:
```php
$atts = shortcode_atts( array(
'no' => 1,
), $atts );
// Use $atts['no'] to get the value of the "no" attribute.
$no = is_numeric( $atts['no'] ) ? (int) $atts['no'] : 1;
``` |
372,358 | <p>I'm searching how to make First Name and Last name fields <strong>required</strong> when we add a new user. Right now only <strong>username</strong> and <strong>Email</strong> fields are required.</p>
<p>I found a way by adding <code>class="form-required"</code> for the first and last name fields on the file <strong>user-new.php</strong>.</p>
<p>But I'm looking for a method with adding code on <strong>function.php</strong> and not touch to the WordPress Core.</p>
<p>Thanks.</p>
| [
{
"answer_id": 372966,
"author": "Ahmad Wael",
"author_id": 115635,
"author_profile": "https://wordpress.stackexchange.com/users/115635",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress Codex Says:</p>\n<p>The following example demonstrates how to add a "First Name" fie... | 2020/08/04 | [
"https://wordpress.stackexchange.com/questions/372358",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119785/"
] | I'm searching how to make First Name and Last name fields **required** when we add a new user. Right now only **username** and **Email** fields are required.
I found a way by adding `class="form-required"` for the first and last name fields on the file **user-new.php**.
But I'm looking for a method with adding code on **function.php** and not touch to the WordPress Core.
Thanks. | If you were looking to make the fields required in the Wordpress admin form for adding new user as i understood from your question, where the output is not filterable, you could basically do what you described (adding form-required) on browser side
```php
function se372358_add_required_to_first_name_last_name(string $type) {
if ( 'add-new-user' === $type ) {
?>
<script type="text/javascript">
jQuery(function($) {
$('#first_name, #last_name')
.parents('tr')
.addClass('form-required')
.find('label')
.append(' <span class="description"><?php _e( '(required)' ); ?></span>');
});
</script>
<?php
}
return $type;
}
add_action('user_new_form', 'se372358_add_required_to_first_name_last_name');
```
**Edit**
In order to achieve the same on edit, you could use code like this:
```php
function se372358_add_required_to_first_name_last_name_alternative() {
?>
<script type="text/javascript">
jQuery(function($) {
$('#createuser, #your-profile')
.find('#first_name, #last_name')
.parents('tr')
.addClass('form-required')
.find('label')
.append(' <span class="description"><?php _e( '(required)' ); ?></span>');
});
</script>
<?php
}
add_action('admin_print_scripts', 'se372358_add_required_to_first_name_last_name_alternative', 20);
function se372358_validate_first_name_last_name(WP_Error &$errors) {
if (!isset($_POST['first_name']) || empty($_POST['first_name'])) {
$errors->add( 'empty_first_name', __( '<strong>Error</strong>: Please enter first name.' ), array( 'form-field' => 'first_name' ) );
}
if (!isset($_POST['last_name']) || empty($_POST['last_name'])) {
$errors->add( 'empty_last_name', __( '<strong>Error</strong>: Please enter last name.' ), array( 'form-field' => 'last_name' ) );
}
return $errors;
}
add_action( 'user_profile_update_errors', 'se372358_validate_first_name_last_name' );
``` |
372,359 | <p>How to make wp_enqueue_style and wp_enqueue_script work only on custom post type</p>
<p>I have install plugin on my wordpress that creat custom post type which is "http://localhost/wordpress/manga" and i have other custom post type like "http://localhost/wordpress/anime" so i only want to css work on manga not anime or in the front page</p>
<p>this is the code:
wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css' );</p>
| [
{
"answer_id": 372362,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 2,
"selected": true,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/themes/basics/conditional-tags/\" rel=\"nofollow nor... | 2020/08/04 | [
"https://wordpress.stackexchange.com/questions/372359",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165624/"
] | How to make wp\_enqueue\_style and wp\_enqueue\_script work only on custom post type
I have install plugin on my wordpress that creat custom post type which is "http://localhost/wordpress/manga" and i have other custom post type like "http://localhost/wordpress/anime" so i only want to css work on manga not anime or in the front page
this is the code:
wp\_enqueue\_style( 'wp-manga-plugin-css', WP\_MANGA\_URI . 'assets/css/style.css' ); | You can use [conditionals](https://developer.wordpress.org/themes/basics/conditional-tags/):
```
<?php
add_action( 'wp_enqueue_scripts', 'wpse_enqueues' );
function wpse_enqueues() {
// Only enqueue on specified single CPTs
if( is_singular( array( 'anime', 'manga' ) ) ) {
wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css' );
}
}
?>
```
If you need the CSS on archives as well, that's another condition:
```
if( is_singular( array( 'anime', 'manga' ) ) || is_post_type_archive( array( 'anime, 'manga' ) ) ) {
wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css'
}
``` |
372,368 | <p>I have a Wordpress site that is built to be a job listing board, and I'm looking to create SEO friendly URLs based on data that is stored in the database.</p>
<p>The URL structure should include the state abbreviation, city, and job title, and result in the following format:
<a href="http://www.domain.com/job/ca/sacramento/janitor" rel="nofollow noreferrer">www.domain.com/job/ca/sacramento/janitor</a></p>
<p>There is currently a "Job" page in the backend that uses custom page template located at 'page-templages/job-template.php' that displays the database information at the following URL:
<a href="http://www.domain.com/job/?2020-412341235134" rel="nofollow noreferrer">www.domain.com/job/?2020-412341235134</a></p>
<p>How can I display the <a href="http://www.domain.com/job/?2020-412341235134" rel="nofollow noreferrer">www.domain.com/job/?2020-412341235134</a> at the friendly virtual URL <a href="http://www.domain.com/job/ca/sacramento/janitor" rel="nofollow noreferrer">www.domain.com/job/ca/sacramento/janitor</a>.</p>
<p>Here's how I'm accessing the database information in my current page template.</p>
<pre><code>$job_title = $job[0]['job_title'];
$sanitized_job_title = str_replace(" ", "-", $job_title);
$bloginfo_url = get_bloginfo('url');
$friendly_url = $bloginfo_url . '/job/'. $job[0]['city'].'/'. $job[0]['state'] .'/'. $sanitized_job_title;
</code></pre>
<p>I've read through the add_rewrite_rule() documentation, and can't seem to get my head around it.</p>
<p>Any help would be greatly appreciated.</p>
| [
{
"answer_id": 372377,
"author": "Rolando Garcia",
"author_id": 112988,
"author_profile": "https://wordpress.stackexchange.com/users/112988",
"pm_score": 0,
"selected": false,
"text": "<p>One approach could be to create a rewrite rule that will catch the 3 variables and provide them as p... | 2020/08/04 | [
"https://wordpress.stackexchange.com/questions/372368",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192677/"
] | I have a Wordpress site that is built to be a job listing board, and I'm looking to create SEO friendly URLs based on data that is stored in the database.
The URL structure should include the state abbreviation, city, and job title, and result in the following format:
[www.domain.com/job/ca/sacramento/janitor](http://www.domain.com/job/ca/sacramento/janitor)
There is currently a "Job" page in the backend that uses custom page template located at 'page-templages/job-template.php' that displays the database information at the following URL:
[www.domain.com/job/?2020-412341235134](http://www.domain.com/job/?2020-412341235134)
How can I display the [www.domain.com/job/?2020-412341235134](http://www.domain.com/job/?2020-412341235134) at the friendly virtual URL [www.domain.com/job/ca/sacramento/janitor](http://www.domain.com/job/ca/sacramento/janitor).
Here's how I'm accessing the database information in my current page template.
```
$job_title = $job[0]['job_title'];
$sanitized_job_title = str_replace(" ", "-", $job_title);
$bloginfo_url = get_bloginfo('url');
$friendly_url = $bloginfo_url . '/job/'. $job[0]['city'].'/'. $job[0]['state'] .'/'. $sanitized_job_title;
```
I've read through the add\_rewrite\_rule() documentation, and can't seem to get my head around it.
Any help would be greatly appreciated. | >
> How can I display the [www.domain.com/job/?2020-412341235134](http://www.domain.com/job/?2020-412341235134) at the friendly virtual URL [www.domain.com/job/ca/sacramento/janitor](http://www.domain.com/job/ca/sacramento/janitor)
>
>
>
Well, you can't do that easily because the job ID in the first URL is not contained directly in the second URL, so you would have to do something complicated where you look up the job based on the parameters 'ca/sacramento/janitor' and this introduces a ton of complexity.
A simpler approach, which you'll see on many big websites is to include the ID and the SEO friendly stuff in the same URL, so that it's good for SEO but also very easy to work with in code because it has the ID. This also means that if e.g. the city the job is in changes, any links to the old URL with the old city will still work fine. In your previous approach if the city changed, then any URL's anywhere on the web with the old city would break unless you did some very complicated matching.
So I'd suggest you make your URL look like this:
```
www.domain.com/job/ca/sacramento/janitor-2020-412341235134
```
And now all you need is a simple rewrite rule in Wordpress or direct in .htaccess to do that mapping. For quickness here's an .htaccess example, but you could probably also achieve this with `add_rewrite_rule`, you just would need to figure out how to map the URL parameters to an `index.php` page.
```
RewriteRule ^/job/[^/]+/[^/]+/[^-]*-(\d+-\d+)$ job/?$1 [L, NC]
```
So this says:
* `/job/` - match this specific string
* `[^/]+/` - two URL parameters that don't contain '/' but have an / on the end, so this will match up to `/job/ca/sacramento/`
* `[^-]+-` - anything that doesn't include `-` with an `-` on the end, so this will match up to `/job/ca/sacramento/janitor-`
* `(\d+-\d+)` - capture two strings of digits with `- in the middle
**This htaccess rule is untested, but you can see the approach I'm suggesting here, and please reply here to work through bugs in this RewriteRule if you use it**
Notes:
* The htaccess rule would need to go outside and above the WP rules in the root .htaccess
* Similar approach could be used for a WP add\_rewrite\_rule, you just need to figure out the right index.php parameters. |
372,421 | <p>I am trying to give users an option to select "Exclude from homepage bloglist" on a post, and then pick this up on my homepage query so certain posts won't surface on the homepage.</p>
<p>I'm using the Wordpress custom field "true/false".</p>
<p>On a post where the box has been ticked, I would assume this post would then not surface on the homepage based on the below query args:</p>
<pre><code>$query_args = array(
'meta_query' => array(
'key' => 'exclude_from_homepage_bloglist',
'value' => false
)
);
</code></pre>
<p>However it seems that even when the true/false box is ticked, the query still outputs the post in question.</p>
<p>Where am I going wrong the the meta query?</p>
| [
{
"answer_id": 372395,
"author": "t2pe",
"author_id": 106499,
"author_profile": "https://wordpress.stackexchange.com/users/106499",
"pm_score": 2,
"selected": true,
"text": "<p>There is basic Favicon functionality built into WP. Go to Theme Customiser > Site Identity and use the 'Site... | 2020/08/05 | [
"https://wordpress.stackexchange.com/questions/372421",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77344/"
] | I am trying to give users an option to select "Exclude from homepage bloglist" on a post, and then pick this up on my homepage query so certain posts won't surface on the homepage.
I'm using the Wordpress custom field "true/false".
On a post where the box has been ticked, I would assume this post would then not surface on the homepage based on the below query args:
```
$query_args = array(
'meta_query' => array(
'key' => 'exclude_from_homepage_bloglist',
'value' => false
)
);
```
However it seems that even when the true/false box is ticked, the query still outputs the post in question.
Where am I going wrong the the meta query? | There is basic Favicon functionality built into WP. Go to Theme Customiser > Site Identity and use the 'Site Icon'.
In some cases its better to have custom code in the head, and the above doesn't work for non WP pages within the site, if thats what you are using. However its worth a try if you hadn't already.
In the past I have also used a website that *generates real favicon* code for the head, including a variety of sizes and allows you control the look of favicons on smartphones etc. So going with a more detailed setup in the head may also be worth exploring? |
372,483 | <p>EDIT: Thanks to @mozboz I've got a solution to this. The post has been updated to reflect was I was originally trying to do, and what I am doing now.</p>
<p>I am developing a plugin that creates a custom post type, adds some meta fields to it, and then displays that meta information in a specifically formatted way. The meta fields are for a YouTube link and an mp3 link, and the plugin displays tabbed content for those (first tab is an embedded YouTube player, second tab is an embedded audio player, third tab is a download link for the mp3). It was working great with the Twenty Twenty theme, but not with any of the other themes I tried. Here was my original code:</p>
<pre><code>function my_custom_post_type_the_post($post_object)
{
// The post object is passed to this hook by reference so there is no need to return a value.
if(
$post_object->post_type == 'my_custom_post_type' &&
( is_post_type_archive('my_custom_post_type') || is_singular('my_custom_post_type') ) &&
! is_admin()
) {
$video = get_post_meta($post_object->ID, 'my_custom_post_type_video_url', true);
$mp3 = get_post_meta($post_object->ID, 'my_custom_post_type_mp3_url', true);
$textfield = get_post_meta($post_object->ID, 'my_custom_post_type_textfield', true);
// Convert meta data to HTML-formatted media content
$media_content = $this->create_media_content($video, $mp3, $bible);
// Prepend $media_content to $post_content
$post_object->post_content = $media_content . $post_object->post_content;
}
}
add_action( 'the_post', 'my_custom_post_type_the_post' );
</code></pre>
<p>I used print_r($post_content) at the end of this function to verify that the conditions were working as expected and that the $post_object contained what I expect it to. For some reason, the Twenty Twenty theme would display the $media_content, but with other themes, it was still missing.</p>
<p>I decided that perhaps I was mis-using the "the_post" hook. I tried to modify my plugin to use the "the_content" hook instead, and that got it working:</p>
<pre><code> public function my_custom_post_type_the_content($content_object)
{
global $post;
if(
$post->post_type == 'my_custom_post_type' &&
( is_post_type_archive('my_custom_post_type') || is_singular('my_custom_post_type') ) && ! is_admin()
) {
$video = get_post_meta($post->ID, 'my_custom_post_type_video_url', true);
$mp3 = get_post_meta($post->ID, 'my_custom_post_type_mp3_url', true);
$textfield = get_post_meta($post->ID, 'my_custom_post_type_text_field', true);
$media_content = $this->create_media_content($video, $mp3, $textfield);
$content_object = $media_content . $content_object;
}
return $content_object
}
add_filter( 'the_content', 'my_custom_post_type_the_content');
</code></pre>
<p>Note that the "$content_object" passed to the function is NOT passed by reference, so it has to be returned.</p>
<p>One thing that was not solved was that with this approach, the archive listing of the posts strips off all of the HTML, so that my media object is gone from archive listings. In my case I decided to not solve this problem, because I decided that loading all of these media objects for multiple posts on an archive page would negatively affect page load times too much.</p>
<p>Thanks again for the help!</p>
| [
{
"answer_id": 372395,
"author": "t2pe",
"author_id": 106499,
"author_profile": "https://wordpress.stackexchange.com/users/106499",
"pm_score": 2,
"selected": true,
"text": "<p>There is basic Favicon functionality built into WP. Go to Theme Customiser > Site Identity and use the 'Site... | 2020/08/06 | [
"https://wordpress.stackexchange.com/questions/372483",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192750/"
] | EDIT: Thanks to @mozboz I've got a solution to this. The post has been updated to reflect was I was originally trying to do, and what I am doing now.
I am developing a plugin that creates a custom post type, adds some meta fields to it, and then displays that meta information in a specifically formatted way. The meta fields are for a YouTube link and an mp3 link, and the plugin displays tabbed content for those (first tab is an embedded YouTube player, second tab is an embedded audio player, third tab is a download link for the mp3). It was working great with the Twenty Twenty theme, but not with any of the other themes I tried. Here was my original code:
```
function my_custom_post_type_the_post($post_object)
{
// The post object is passed to this hook by reference so there is no need to return a value.
if(
$post_object->post_type == 'my_custom_post_type' &&
( is_post_type_archive('my_custom_post_type') || is_singular('my_custom_post_type') ) &&
! is_admin()
) {
$video = get_post_meta($post_object->ID, 'my_custom_post_type_video_url', true);
$mp3 = get_post_meta($post_object->ID, 'my_custom_post_type_mp3_url', true);
$textfield = get_post_meta($post_object->ID, 'my_custom_post_type_textfield', true);
// Convert meta data to HTML-formatted media content
$media_content = $this->create_media_content($video, $mp3, $bible);
// Prepend $media_content to $post_content
$post_object->post_content = $media_content . $post_object->post_content;
}
}
add_action( 'the_post', 'my_custom_post_type_the_post' );
```
I used print\_r($post\_content) at the end of this function to verify that the conditions were working as expected and that the $post\_object contained what I expect it to. For some reason, the Twenty Twenty theme would display the $media\_content, but with other themes, it was still missing.
I decided that perhaps I was mis-using the "the\_post" hook. I tried to modify my plugin to use the "the\_content" hook instead, and that got it working:
```
public function my_custom_post_type_the_content($content_object)
{
global $post;
if(
$post->post_type == 'my_custom_post_type' &&
( is_post_type_archive('my_custom_post_type') || is_singular('my_custom_post_type') ) && ! is_admin()
) {
$video = get_post_meta($post->ID, 'my_custom_post_type_video_url', true);
$mp3 = get_post_meta($post->ID, 'my_custom_post_type_mp3_url', true);
$textfield = get_post_meta($post->ID, 'my_custom_post_type_text_field', true);
$media_content = $this->create_media_content($video, $mp3, $textfield);
$content_object = $media_content . $content_object;
}
return $content_object
}
add_filter( 'the_content', 'my_custom_post_type_the_content');
```
Note that the "$content\_object" passed to the function is NOT passed by reference, so it has to be returned.
One thing that was not solved was that with this approach, the archive listing of the posts strips off all of the HTML, so that my media object is gone from archive listings. In my case I decided to not solve this problem, because I decided that loading all of these media objects for multiple posts on an archive page would negatively affect page load times too much.
Thanks again for the help! | There is basic Favicon functionality built into WP. Go to Theme Customiser > Site Identity and use the 'Site Icon'.
In some cases its better to have custom code in the head, and the above doesn't work for non WP pages within the site, if thats what you are using. However its worth a try if you hadn't already.
In the past I have also used a website that *generates real favicon* code for the head, including a variety of sizes and allows you control the look of favicons on smartphones etc. So going with a more detailed setup in the head may also be worth exploring? |
372,527 | <pre><code> Notice: wpdb::prepare was called incorrectly. The query argument of wpdb::prepare() must have a placeholder. Please see Debugging in WordPress for more information. (This message was added in version 3.9.0.) in /home/****/public_html/wp-includes/functions.php on line 5167
Notice: Undefined offset: 0 in /home/****/public_html/wp-includes/wp-db.php on line 1310
function branch_students(){
$content='';
$content.='<div class="container">';
$content.='<h1 align=center class="fofa">Enter Branch</h1>';
$content.='<form method="post" >';
$content.='<div class="b2">';
$content.='<input type="text" name="branch" id="branch" class="box" placeholder="Enter Branch" required */></div>';
$content.='<br>';
$content.='<div>';
$content.='<button type="submit" name="save" class="btn_Register" value="save">Save</button>';
$content.='</div>';
$content.='</form>';
$content.='</div>';
return $content;
}
this is my first form in this form i creates branches. now i want database of this branch form should be showed in the following table as selection options.
function arsh_forms(){
$content .='<div class="col-sm-6">';
$content .='<label class="fofa" style=" font: italic bold 12px/30px Georgia, serif; font-size:26px;color:black;">Select Branch</label>';
$content .='<select name="selectbranch"id="selectbranch" class="form-control"style=" font: italic bold 12px/30px Georgia, serif; font-size:20px;"placeholder="selectbranch"required/>';
$content .='<option value="0" >select branch</option>';
global $wpdb;
$table_name=$wpdb->prefix.'arsh_branch';
$select_branch = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name"));
if(count($select_branch) > 0){
foreach ($select_branch as $key=>$value){
$content .='<option value="<?php echo $value->branches; ?>">
<?php echo ucwords($value->branches);?></option>';
}
}
$content .='</select>';
$content.='<div class="col-sm-6">';
$content .='<button type="submit" name="submit" value="Register" style=" width:30%;height:35px;background-color:black;color:white;float:right; margin-top:40px;"
class="bt">Register</button>';
$content .='</div>';
}
</code></pre>
<p>i think now it is understandable.plz if anybody can help me?</p>
| [
{
"answer_id": 372509,
"author": "Ben",
"author_id": 190965,
"author_profile": "https://wordpress.stackexchange.com/users/190965",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds as though you know your username and password, but if not you can always go into PHPMyAdmin (Or whate... | 2020/08/07 | [
"https://wordpress.stackexchange.com/questions/372527",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191526/"
] | ```
Notice: wpdb::prepare was called incorrectly. The query argument of wpdb::prepare() must have a placeholder. Please see Debugging in WordPress for more information. (This message was added in version 3.9.0.) in /home/****/public_html/wp-includes/functions.php on line 5167
Notice: Undefined offset: 0 in /home/****/public_html/wp-includes/wp-db.php on line 1310
function branch_students(){
$content='';
$content.='<div class="container">';
$content.='<h1 align=center class="fofa">Enter Branch</h1>';
$content.='<form method="post" >';
$content.='<div class="b2">';
$content.='<input type="text" name="branch" id="branch" class="box" placeholder="Enter Branch" required */></div>';
$content.='<br>';
$content.='<div>';
$content.='<button type="submit" name="save" class="btn_Register" value="save">Save</button>';
$content.='</div>';
$content.='</form>';
$content.='</div>';
return $content;
}
this is my first form in this form i creates branches. now i want database of this branch form should be showed in the following table as selection options.
function arsh_forms(){
$content .='<div class="col-sm-6">';
$content .='<label class="fofa" style=" font: italic bold 12px/30px Georgia, serif; font-size:26px;color:black;">Select Branch</label>';
$content .='<select name="selectbranch"id="selectbranch" class="form-control"style=" font: italic bold 12px/30px Georgia, serif; font-size:20px;"placeholder="selectbranch"required/>';
$content .='<option value="0" >select branch</option>';
global $wpdb;
$table_name=$wpdb->prefix.'arsh_branch';
$select_branch = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name"));
if(count($select_branch) > 0){
foreach ($select_branch as $key=>$value){
$content .='<option value="<?php echo $value->branches; ?>">
<?php echo ucwords($value->branches);?></option>';
}
}
$content .='</select>';
$content.='<div class="col-sm-6">';
$content .='<button type="submit" name="submit" value="Register" style=" width:30%;height:35px;background-color:black;color:white;float:right; margin-top:40px;"
class="bt">Register</button>';
$content .='</div>';
}
```
i think now it is understandable.plz if anybody can help me? | It sounds as though you know your username and password, but if not you can always go into PHPMyAdmin (Or whatever Db tool your server uses) and navigate to the **users** table. In there you can see your users, and edit your details as required, including your password which you can simply overtype with new after encrypting it in **MD5** format.
If this is trying to log in and kicking you straight back to the login page it may be worth looking in your server root for a file named `error_log`, this will help you identify any errors, or you can edit `wp-config.php` in the site's root setting `wp_debug` to **true** near the end of the page. Doing this should stop the page from just redirecting you without notification and give a print out of the error, if there are, any at the top of the page.
This may not help, we could probably do with some more details from you before the community can help further. Depending on your hosting environment, it could be that your PHP version is out of date and needs updating.
Hope this helps. Ben. |
372,535 | <p>I have created a php script (generate.php) which is querying posts on set criteria and then writing result in custom xml file. I would like to execute the generate.php everytime the post Save/Update button is pressed. Do you have any clue on how to do this? May be with cron jobs every X minutes would be better?</p>
| [
{
"answer_id": 372536,
"author": "Oliver Gehrmann",
"author_id": 192667,
"author_profile": "https://wordpress.stackexchange.com/users/192667",
"pm_score": 0,
"selected": false,
"text": "<p>I believe you should look into status transitions: <a href=\"https://developer.wordpress.org/refere... | 2020/08/07 | [
"https://wordpress.stackexchange.com/questions/372535",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5878/"
] | I have created a php script (generate.php) which is querying posts on set criteria and then writing result in custom xml file. I would like to execute the generate.php everytime the post Save/Update button is pressed. Do you have any clue on how to do this? May be with cron jobs every X minutes would be better? | At the end, I solved with jQuery and ajax
```
jQuery( '.post-type-property #post' ).submit( function( e ) {
if(!(checkMetaFields() && checkCategories())){ //some validation functions
return false;
}else{
jQuery.ajax({
url:"https://demo.site.com/XML/6098123798/gen.php",
type:"post"
})
}
} );
``` |
372,578 | <p>I have a custom post type and in the CPT's <code>single-cpt.php</code> file I would like to pull in two posts instead of one.</p>
<p>The two posts will be the post the user clicked in the relevant archive, and the next post in date order (i.e. the default post sorting method of WordPress). The reason for this is the posts are essentially small, useful pieces of information and having two posts pulled in will create a better SEO and user experience.</p>
<p>Normally when I want to pull in a set number of posts on an archive page I would use <code>WP_Query()</code> and set <code>'posts_per_page' => 2</code> but out of the box this won't work on a <code>single-cpt.php</code> file because such code pulls in posts that are the most recent, not the post that was clicked on the archive page (and then the next most recent).</p>
<p>What I'm looking for is something that works with the WP loop so each post looks the same, but pulls in two posts (the selected one from the archive and then the next one in date order).</p>
<p><strong>Note:</strong> If this isn't possible with WP_Query() any other way to do it would be most welcome.</p>
<pre><code><?php
$newsArticles = new WP_Query(array(
'posts_per_page' => 2,
'post_type'=> 'news'
));
while( $newsArticles->have_posts()){
$newsArticles->the_post(); ?>
// HTML content goes here
<?php } ?>
<?php wp_reset_postdata(); ?>
</code></pre>
<p>Any help would be amazing.</p>
| [
{
"answer_id": 372577,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 1,
"selected": false,
"text": "<p>1 - Yes. You could manually update the <code>post_author</code> field on <code>wp_posts</code> table if you ... | 2020/08/07 | [
"https://wordpress.stackexchange.com/questions/372578",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] | I have a custom post type and in the CPT's `single-cpt.php` file I would like to pull in two posts instead of one.
The two posts will be the post the user clicked in the relevant archive, and the next post in date order (i.e. the default post sorting method of WordPress). The reason for this is the posts are essentially small, useful pieces of information and having two posts pulled in will create a better SEO and user experience.
Normally when I want to pull in a set number of posts on an archive page I would use `WP_Query()` and set `'posts_per_page' => 2` but out of the box this won't work on a `single-cpt.php` file because such code pulls in posts that are the most recent, not the post that was clicked on the archive page (and then the next most recent).
What I'm looking for is something that works with the WP loop so each post looks the same, but pulls in two posts (the selected one from the archive and then the next one in date order).
**Note:** If this isn't possible with WP\_Query() any other way to do it would be most welcome.
```
<?php
$newsArticles = new WP_Query(array(
'posts_per_page' => 2,
'post_type'=> 'news'
));
while( $newsArticles->have_posts()){
$newsArticles->the_post(); ?>
// HTML content goes here
<?php } ?>
<?php wp_reset_postdata(); ?>
```
Any help would be amazing. | Just to add to what MozBoz has already said, you can also set the author from the post / page in WP directly. You can usually do this from the editor itself, but there are a lot of page builders available, so I'd suggest going to WP Admin and to your **All Posts**, hover over the post you want to set the author of and select **Quick Edit**. This will pull down a tray of options, one of which will be an author dropdown where you can select the posts author from all of the users on your site. |
372,616 | <h2>Scenario</h2>
<p>I am working on a domain's website which is part of a multi-site installation.</p>
<p>I am looking to create a custom php page which will do some processing.
This page would be accessed from the main WP site using a Javascript <code>XMLHttpRequest</code></p>
<p>I do NOT want this page to have any of my theme's headers, content, etc. as this page will not actually be visited directly by the user's browser.</p>
<p><strong>Example php (simplified);</strong></p>
<pre class="lang-php prettyprint-override"><code><?php session_start() $_SESSION["stuff"] = "things"; echo "success"; exit(); ?>
</code></pre>
<h2>Things I've tried</h2>
<p>I tried using hooks and headers for the PHP within ‘elements’ however it appears that all of the available options only process the php after some headers have started being generated, therefore meaning that the php would not present data as accurately as expected.</p>
<p>It seemed obvious to me to simply create the '.php' file in the same way I would if weren't using WP, however I have struggled to find the directory where I should create such a file.
I checked the configuration of the file: /etc/apache2/sites-enabled/000-default.conf
but this just shows me 'DocumentRoot /var/www/wordpress' which is a the root directory of the multi-site area.
This lead me to believe that it may be a little more complex than simply creating the file in a certain directory directly on the server.</p>
<p>I have also tried to use the “disable elements” for this page when in 'edit page' however this doesn’t seem to do enough either.</p>
<p>I also tried reviewing this <a href="https://wordpress.stackexchange.com/questions/210304/add-a-page-outside-of-the-current-theme">previous thread</a> but I can't see the solution, I ideally don't want the WP functionality at all for this single page. I just want to be able to access it from <code>https://example.com/string.php</code> (or similar).</p>
<h2>Desired Outcome</h2>
<p>I want the page to be as plain as possible OR to be able to execute the php early enough that the <code>exit();</code> stops the actual page from being rendered into HTML (headers, etc.)</p>
<p>Also, I ideally don't want to just 'throw another plugin at it' if there's an alternative (but not ridiculous) way.</p>
<p>Please could you help me to find a solution?</p>
<p>Many Thanks!</p>
| [
{
"answer_id": 372577,
"author": "mozboz",
"author_id": 176814,
"author_profile": "https://wordpress.stackexchange.com/users/176814",
"pm_score": 1,
"selected": false,
"text": "<p>1 - Yes. You could manually update the <code>post_author</code> field on <code>wp_posts</code> table if you ... | 2020/08/08 | [
"https://wordpress.stackexchange.com/questions/372616",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/190928/"
] | Scenario
--------
I am working on a domain's website which is part of a multi-site installation.
I am looking to create a custom php page which will do some processing.
This page would be accessed from the main WP site using a Javascript `XMLHttpRequest`
I do NOT want this page to have any of my theme's headers, content, etc. as this page will not actually be visited directly by the user's browser.
**Example php (simplified);**
```php
<?php session_start() $_SESSION["stuff"] = "things"; echo "success"; exit(); ?>
```
Things I've tried
-----------------
I tried using hooks and headers for the PHP within ‘elements’ however it appears that all of the available options only process the php after some headers have started being generated, therefore meaning that the php would not present data as accurately as expected.
It seemed obvious to me to simply create the '.php' file in the same way I would if weren't using WP, however I have struggled to find the directory where I should create such a file.
I checked the configuration of the file: /etc/apache2/sites-enabled/000-default.conf
but this just shows me 'DocumentRoot /var/www/wordpress' which is a the root directory of the multi-site area.
This lead me to believe that it may be a little more complex than simply creating the file in a certain directory directly on the server.
I have also tried to use the “disable elements” for this page when in 'edit page' however this doesn’t seem to do enough either.
I also tried reviewing this [previous thread](https://wordpress.stackexchange.com/questions/210304/add-a-page-outside-of-the-current-theme) but I can't see the solution, I ideally don't want the WP functionality at all for this single page. I just want to be able to access it from `https://example.com/string.php` (or similar).
Desired Outcome
---------------
I want the page to be as plain as possible OR to be able to execute the php early enough that the `exit();` stops the actual page from being rendered into HTML (headers, etc.)
Also, I ideally don't want to just 'throw another plugin at it' if there's an alternative (but not ridiculous) way.
Please could you help me to find a solution?
Many Thanks! | Just to add to what MozBoz has already said, you can also set the author from the post / page in WP directly. You can usually do this from the editor itself, but there are a lot of page builders available, so I'd suggest going to WP Admin and to your **All Posts**, hover over the post you want to set the author of and select **Quick Edit**. This will pull down a tray of options, one of which will be an author dropdown where you can select the posts author from all of the users on your site. |
372,626 | <p>I am creating an Android app for a client whose site is in WordPress. I want to access the posts, but I don't know which API to hit. One of the APIs I found after some searching is <a href="https://www.example.com/wp-json/wp/v2/posts" rel="nofollow noreferrer">https://www.<code><mysite></code>.com/wp-json/wp/v2/posts</a>. This gives a ton of key value pairs, So I was tying to access this site via this URL. But for a particular <code>content</code> key, this is giving the following output:</p>
<pre><code> "content": {
"rendered": "<p>&nbsp;</p>\r\n\r\n<p>The next class for &#8220;MICROVITA&#8221; will be on &#8220;Aug 07th, 2020 at 8:00 PM IST / 10:30 AM EST on &#8220;MicroVita Science(माइक्रोवाइटा विषय समापन )&#8221; by Ac.Vimalananda Avt. </p>\r\n\r\n\r\n\r\n\n<div class=\"dpn-zvc-shortcode-op-wrapper\">\n\t <table class=\"vczapi-shortcode-meeting-table\">\n <tr class=\"vczapi-shortcode-meeting-table--row1\">\n <td>Meeting ID</td>\n <td>000000000</td>\n </tr>\n <tr class=\"vczapi-shortcode-meeting-table--row2\">..."
}
</code></pre>
<p>I am not sure how to retrieve the important information from such HTML content. Maybe that's a question better suited for other stack communities, but what I want to know is that if it is the expected behavior from a WordPress site API? Or is there some other API or plugin which might give me a better response?</p>
<p>To summarize:</p>
<ol>
<li>which WordPress API could give me a list of all the articles as JSON?</li>
<li>I found a particular API doing the above same task as point (1.). is it a standard one?</li>
<li>Is it a standard behavior of WordPress APIs to have HTML content directly inside their JSON key-value pairs?</li>
</ol>
| [
{
"answer_id": 372640,
"author": "Marcello Curto",
"author_id": 153572,
"author_profile": "https://wordpress.stackexchange.com/users/153572",
"pm_score": 2,
"selected": false,
"text": "<p>This is expected WordPress behavior. "content" data is WordPress post content data\nand st... | 2020/08/08 | [
"https://wordpress.stackexchange.com/questions/372626",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192852/"
] | I am creating an Android app for a client whose site is in WordPress. I want to access the posts, but I don't know which API to hit. One of the APIs I found after some searching is [https://www.`<mysite>`.com/wp-json/wp/v2/posts](https://www.example.com/wp-json/wp/v2/posts). This gives a ton of key value pairs, So I was tying to access this site via this URL. But for a particular `content` key, this is giving the following output:
```
"content": {
"rendered": "<p> </p>\r\n\r\n<p>The next class for “MICROVITA” will be on “Aug 07th, 2020 at 8:00 PM IST / 10:30 AM EST on “MicroVita Science(माइक्रोवाइटा विषय समापन )” by Ac.Vimalananda Avt. </p>\r\n\r\n\r\n\r\n\n<div class=\"dpn-zvc-shortcode-op-wrapper\">\n\t <table class=\"vczapi-shortcode-meeting-table\">\n <tr class=\"vczapi-shortcode-meeting-table--row1\">\n <td>Meeting ID</td>\n <td>000000000</td>\n </tr>\n <tr class=\"vczapi-shortcode-meeting-table--row2\">..."
}
```
I am not sure how to retrieve the important information from such HTML content. Maybe that's a question better suited for other stack communities, but what I want to know is that if it is the expected behavior from a WordPress site API? Or is there some other API or plugin which might give me a better response?
To summarize:
1. which WordPress API could give me a list of all the articles as JSON?
2. I found a particular API doing the above same task as point (1.). is it a standard one?
3. Is it a standard behavior of WordPress APIs to have HTML content directly inside their JSON key-value pairs? | >
> 1. which wordpress api could give me a list of all the articles as json?
>
>
>
You're already using the right API, just remember it's paginated so you need to request the second/third page/etc in a separate request. It'll pass how many apges there are in the http header
>
> 2. I found a particular api doing the above same task as point (1.). is it a standard one?
>
>
>
You list posts via the REST API by querying `wp-json/wp/v2/posts`. Other endpoints exist for other post types such as `pages` etc
>
> 3. Is it a standard behavior of wordpress apis to have html content directly inside their json key-value pairs?
>
>
>
Yes, if you wanted to display the post you would need the post content. Otherwise how would you display the post?
---
I think what we're seeing is a misunderstanding. **You never stated what it was that you wanted, just that it's somewhere in the content HTML**. So I think this is what has happened:
* The post uses a shortcode to display data taken from elsewhere
* Your app is pulling in the post via the REST API
* You're looking at the shortcodes output and wondering how to extract the data in your Android app.
You could parse the HTML using an android library of sorts, assuming it's consistent, or, you could look at where the shortcode gets its information from and access it directly.
Sadly, you never actually said what the data you wanted was, and we don't know what the shortcode that generates that output is. Without access to the implementation of the shortcode it's not possible to say how to expose the information. A shortcode is a PHP function that's registered under a name, and swaps a string such as `[shortcode]` with HTML tags. That PHP function might draw the data from post meta, or it might access a custom database table, or even make a HTTP request to a remote API, so no generic solution is possible.
`dpn-zvc-shortcode-op-wrapper` gives us a clue as to what the shortcode might be, but you would need to look at how the shortcode works to know that, and you didn't mentiion the shortcodes name. A quick google shows that HTML class appears in a support request for a Zoom plugin, so you would need to go via their support route as 3rd party plugin support is offtopic here. |
372,627 | <p>I am trying to figure out how to get a list of the permalinks for top-level pages only. My goal is to put them in a selection box on a form. I have spent a couple of hours searching here for an answer to no avail. I was hoping someone could point me in the right direction.</p>
| [
{
"answer_id": 372628,
"author": "Ben",
"author_id": 190965,
"author_profile": "https://wordpress.stackexchange.com/users/190965",
"pm_score": 0,
"selected": false,
"text": "<p>By the sounds of it, this should do what you're after. Just place it in wherever you want your list to output a... | 2020/08/08 | [
"https://wordpress.stackexchange.com/questions/372627",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192370/"
] | I am trying to figure out how to get a list of the permalinks for top-level pages only. My goal is to put them in a selection box on a form. I have spent a couple of hours searching here for an answer to no avail. I was hoping someone could point me in the right direction. | ```
$query_args = array(
'post_type' => 'page',
'post_status' => 'publish',
'parent' => 0,
);
$pages = get_pages( $query_args );
```
Function `get_pages()` accepts parameter with `parent`. Keeping it 0 (zero) will give us first level pages. In the example `$pages` will contain the first level pages. Use loop for `$pages` and you can use it in option as you require. |
372,687 | <p>I have a live website that is using the custom post type "virtual-programs" and I have a template that currently works called single-virtual-program.twig and single-virtual-program.php.</p>
<p>I am developing new templates (single-virtual-program-new.twig and single-virtual-program-new.php)</p>
<p>They will eventually replace (single-virtual-program.twig and single-virtual-program.php)</p>
<p>During development I want to have both templates active, then once I'm happy with it, I will activate the new templates and remove the the old templates.</p>
<p>To do this I will need to create custom URLs for my NEW templates so I can view them while the old templates are still live. How do I go about that?</p>
<p>FYI I'm using Timber (.twig).</p>
<p>Here is the code from single-virtual-program.php</p>
<pre><code>$post = Timber::query_post();
$context['post'] = $post;
$context['archive_link'] = get_site_url(null, str_replace('_', '-', $post->post_type));
$context['virtual_programs'] = Timber::get_posts(
array(
'post_type' => array('virtual_programs'),
'post__not_in' => array($post->ID),
'posts_per_page' => 5,
'meta_query' => array(
array(
'key' => 'event_type',
'value' => array('online', 'Online Short Course'),
'compare' => 'NOT IN'
)
)
)
);
$context["register_event_url"] = get_field("prices", $post->ID)[0]["register_link"];
Timber::render( 'single-virtual-programs-new.twig' , $context );
</code></pre>
<p>Thank you.</p>
| [
{
"answer_id": 372628,
"author": "Ben",
"author_id": 190965,
"author_profile": "https://wordpress.stackexchange.com/users/190965",
"pm_score": 0,
"selected": false,
"text": "<p>By the sounds of it, this should do what you're after. Just place it in wherever you want your list to output a... | 2020/08/10 | [
"https://wordpress.stackexchange.com/questions/372687",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93209/"
] | I have a live website that is using the custom post type "virtual-programs" and I have a template that currently works called single-virtual-program.twig and single-virtual-program.php.
I am developing new templates (single-virtual-program-new.twig and single-virtual-program-new.php)
They will eventually replace (single-virtual-program.twig and single-virtual-program.php)
During development I want to have both templates active, then once I'm happy with it, I will activate the new templates and remove the the old templates.
To do this I will need to create custom URLs for my NEW templates so I can view them while the old templates are still live. How do I go about that?
FYI I'm using Timber (.twig).
Here is the code from single-virtual-program.php
```
$post = Timber::query_post();
$context['post'] = $post;
$context['archive_link'] = get_site_url(null, str_replace('_', '-', $post->post_type));
$context['virtual_programs'] = Timber::get_posts(
array(
'post_type' => array('virtual_programs'),
'post__not_in' => array($post->ID),
'posts_per_page' => 5,
'meta_query' => array(
array(
'key' => 'event_type',
'value' => array('online', 'Online Short Course'),
'compare' => 'NOT IN'
)
)
)
);
$context["register_event_url"] = get_field("prices", $post->ID)[0]["register_link"];
Timber::render( 'single-virtual-programs-new.twig' , $context );
```
Thank you. | ```
$query_args = array(
'post_type' => 'page',
'post_status' => 'publish',
'parent' => 0,
);
$pages = get_pages( $query_args );
```
Function `get_pages()` accepts parameter with `parent`. Keeping it 0 (zero) will give us first level pages. In the example `$pages` will contain the first level pages. Use loop for `$pages` and you can use it in option as you require. |
372,690 | <p>I use <a href="https://github.com/timber/timber" rel="nofollow noreferrer">Timber</a> for all my projects, but I would also like to start using a templating language like HAML or Pug. I found a PHP implementation of HAML called <a href="https://github.com/arnaud-lb/MtHaml" rel="nofollow noreferrer">MtHaml</a>, which supports twig. I thought this could be great if I could get it to work with Timber.</p>
<p>Unfortunately, while this supports a number of CMS, Wordpress is not on the list. There is <a href="https://github.com/zachfeldman/wordpress-haml-sass" rel="nofollow noreferrer">a project</a> that brings MtHaml to wordpress, but it's from 7 years ago and I haven't yet figured out how it compiles. It looks like I have to run ./watch from command line to get it to autocompile.</p>
<p>I like Timber because it just compiles on the fly. I drop my twig file in the theme directory and it just works. I would like to do the same thing but with HAML + Twig (Timber). Does anyone know how I would go about this?</p>
<p>Alternatively, I would consider using Twig + Pug but I see even less support for this. Basically I want to get away from the traditional templating system of opening and closing tags, and move to an HTML shorthand</p>
| [
{
"answer_id": 372628,
"author": "Ben",
"author_id": 190965,
"author_profile": "https://wordpress.stackexchange.com/users/190965",
"pm_score": 0,
"selected": false,
"text": "<p>By the sounds of it, this should do what you're after. Just place it in wherever you want your list to output a... | 2020/08/10 | [
"https://wordpress.stackexchange.com/questions/372690",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13881/"
] | I use [Timber](https://github.com/timber/timber) for all my projects, but I would also like to start using a templating language like HAML or Pug. I found a PHP implementation of HAML called [MtHaml](https://github.com/arnaud-lb/MtHaml), which supports twig. I thought this could be great if I could get it to work with Timber.
Unfortunately, while this supports a number of CMS, Wordpress is not on the list. There is [a project](https://github.com/zachfeldman/wordpress-haml-sass) that brings MtHaml to wordpress, but it's from 7 years ago and I haven't yet figured out how it compiles. It looks like I have to run ./watch from command line to get it to autocompile.
I like Timber because it just compiles on the fly. I drop my twig file in the theme directory and it just works. I would like to do the same thing but with HAML + Twig (Timber). Does anyone know how I would go about this?
Alternatively, I would consider using Twig + Pug but I see even less support for this. Basically I want to get away from the traditional templating system of opening and closing tags, and move to an HTML shorthand | ```
$query_args = array(
'post_type' => 'page',
'post_status' => 'publish',
'parent' => 0,
);
$pages = get_pages( $query_args );
```
Function `get_pages()` accepts parameter with `parent`. Keeping it 0 (zero) will give us first level pages. In the example `$pages` will contain the first level pages. Use loop for `$pages` and you can use it in option as you require. |
372,705 | <p>This is my first time asking a question here. I'm kinda stuck on how to do <code>echo do_shortcode();</code> inside a shortcode.</p>
<p>I tried googling for an answer but to no avail.</p>
<p>I'd like to know if it is possible to echo a shortcode inside a shortcode. If it is, any pointer is much appreciated.</p>
<p>Thank you.</p>
<pre><code> function cpa_haven_banner() {
return '
<ul class="list-group list-group-horizontal entry-meta">
<li class="list-group-item list-group-action-item">
<strong>Female</strong> <?php echo do_shortcode("[get_sheet_value location='LOAN!B7']"); ?>
</li>
</ul>
';
}
add_shortcode('cpa-haven', 'cpa_haven_banner');
</code></pre>
| [
{
"answer_id": 372710,
"author": "Nate Allen",
"author_id": 32698,
"author_profile": "https://wordpress.stackexchange.com/users/32698",
"pm_score": 0,
"selected": false,
"text": "<p>I would put all the markup in a variable, and return the result of passing that through <code>do_shortcode... | 2020/08/10 | [
"https://wordpress.stackexchange.com/questions/372705",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192898/"
] | This is my first time asking a question here. I'm kinda stuck on how to do `echo do_shortcode();` inside a shortcode.
I tried googling for an answer but to no avail.
I'd like to know if it is possible to echo a shortcode inside a shortcode. If it is, any pointer is much appreciated.
Thank you.
```
function cpa_haven_banner() {
return '
<ul class="list-group list-group-horizontal entry-meta">
<li class="list-group-item list-group-action-item">
<strong>Female</strong> <?php echo do_shortcode("[get_sheet_value location='LOAN!B7']"); ?>
</li>
</ul>
';
}
add_shortcode('cpa-haven', 'cpa_haven_banner');
``` | This should work:
```
function cpa_haven_banner() {
$shortcode = do_shortcode("[get_sheet_value location='LOAN!B7']");
return '
<ul class="list-group list-group-horizontal entry-meta">
<li class="list-group-item list-group-action-item">
<strong>Female</strong> ' . $shortcode .
'</li>
</ul>
';
}
add_shortcode('cpa-haven', 'cpa_haven_banner');
``` |
372,764 | <p>Is it possible when using the <code>previous_post_link()</code> function to make it get the previous post after next i.e. make it skip a post. So if you're on post 5 in numerical order it skips to post 3?</p>
<p>The reason being I have custom post type <code>single-cpt.php</code> file that pulls in two posts, so when using the previous post link out of the box it means when you go to the next post, one of the ones from the previous post is there again.</p>
<p>Any help would be fabulous.</p>
| [
{
"answer_id": 372769,
"author": "Nate Allen",
"author_id": 32698,
"author_profile": "https://wordpress.stackexchange.com/users/32698",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote a couple functions that trick WordPress into thinking we're on the previous/next post before calli... | 2020/08/11 | [
"https://wordpress.stackexchange.com/questions/372764",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] | Is it possible when using the `previous_post_link()` function to make it get the previous post after next i.e. make it skip a post. So if you're on post 5 in numerical order it skips to post 3?
The reason being I have custom post type `single-cpt.php` file that pulls in two posts, so when using the previous post link out of the box it means when you go to the next post, one of the ones from the previous post is there again.
Any help would be fabulous. | ```
$current_id = get_the_ID();
$cpt = get_post_type();
$all_ids = get_posts(array(
'fields' => 'ids',
'posts_per_page' => -1,
'post_type' => $cpt,
'order_by' => 'post_date',
'order' => 'ASC',
));
$prev_key = array_search($current_id, $all_ids) - 2;
$next_key = array_search($current_id, $all_ids) + 2;
if(array_key_exists($prev_key, $all_ids)){
$prev_link = get_the_permalink($all_ids[$prev_key]);
echo $prev_link;
}
if(array_key_exists($next_key, $all_ids)){
$next_link = get_the_permalink($all_ids[$next_key]);
echo $next_link;
}
```
So I queried all the posts IDs from the current post type. Then since it’s a simple array key=>value, just found the current post key in the array and just added or subtracted so if your current post is the 8th one, your next is 10 and you previous is 6. Then if your array doesn’t have enough keys, say your current was the 8th but your array only had 9 that will mess it up, I check to see if the key exists. If it does, use get\_the\_permalink() with the value of the desired key.
Probably not the most graceful way to do it but… |
372,768 | <p>Attempting to make a search in a custom post type "comunicados" inside a shortcode in a custom plugin I send this to get_posts()</p>
<pre><code>Array
(
[posts_per_page] => -1
[post_type] => comunicados
[post_status] => publish
[orderby] => title
[order] => DESC
[s] => co
)
</code></pre>
<p>Here the actual code</p>
<pre><code>//QUERY
$opt = array(
'posts_per_page' => -1,
'post_type' => 'comunicados',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'DESC'
);
//SEARCH STRING
if($_GET['buscar'] != ''){
$opt['s'] = $_GET['buscar'];
}
print_r($opt);
$res = new WP_Query($opt);
print_r($res);
</code></pre>
<p>This returns all the content (pages, posts, other custom post types) but "comunicados"</p>
<p>I changed to WP_Query with the same result.</p>
<p>If I print_r the WP_Query I see this:</p>
<pre><code>WP_Query Object
(
[query] => Array
(
[posts_per_page] => -1
[post_type] => comunicados
[post_status] => publish
[orderby] => title
[order] => DESC
[s] => co
)
[query_vars] => Array
(
[posts_per_page] => -1
[post_type] => Array
(
[0] => post
[1] => page
[2] => evento
[3] => informes
[4] => publicaciones
[5] => noticias
)
[post_status] => publish
[orderby] => title
[order] => DESC
[s] => co
...
...
...
</code></pre>
<p>Note the post_type in query and in query_vars. Is not supossed to be the same?
Also I see this:</p>
<pre><code>[request] => SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND (((wp_posts.post_title LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}') OR (wp_posts.post_excerpt LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}') OR (wp_posts.post_content LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}'))) AND wp_posts.post_type IN ('post', 'page', 'evento', 'informes', 'publicaciones', 'noticias') AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_title DESC
</code></pre>
<p>It's not using my post_type and also these weird strings {48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}</p>
<p>I'm not sure how to make this work</p>
<p>This is the post type (create with CPT UI)</p>
<pre><code>function cptui_register_my_cpts_comunicados() {
/**
* Post Type: Comunicados.
*/
$labels = [
"name" => __( "Comunicados", "custom-post-type-ui" ),
"singular_name" => __( "Comunicados", "custom-post-type-ui" ),
"menu_name" => __( "Comunicados", "custom-post-type-ui" ),
"all_items" => __( "Todos los comunicados", "custom-post-type-ui" ),
"add_new" => __( "Nuevo comunicado", "custom-post-type-ui" ),
"add_new_item" => __( "Agregar comunicado", "custom-post-type-ui" ),
"edit_item" => __( "Editar comunicado", "custom-post-type-ui" ),
"new_item" => __( "Nuevo comunicado", "custom-post-type-ui" ),
"view_item" => __( "Ver comunicado", "custom-post-type-ui" ),
"view_items" => __( "Ver comunicados", "custom-post-type-ui" ),
];
$args = [
"label" => __( "Comunicados", "custom-post-type-ui" ),
"labels" => $labels,
"description" => "",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"show_in_rest" => true,
"rest_base" => "",
"rest_controller_class" => "WP_REST_Posts_Controller",
"has_archive" => false,
"show_in_menu" => true,
"show_in_nav_menus" => true,
"delete_with_user" => false,
"exclude_from_search" => false,
"capability_type" => "comunicado",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => [ "slug" => "comunicados", "with_front" => true ],
"query_var" => true,
"supports" => [ "title", "editor", "thumbnail", "excerpt" ],
"taxonomies" => [ "post_tag" ],
];
register_post_type( "comunicados", $args );
}
add_action( 'init', 'cptui_register_my_cpts_comunicados' );
</code></pre>
<p>Weird thing is, if the "s" paramether is not present, this works fine:</p>
<pre><code>WP_Query Object
(
[query] => Array
(
[posts_per_page] => -1
[post_type] => comunicados
[post_status] => publish
[orderby] => title
[order] => DESC
)
[query_vars] => Array
(
[posts_per_page] => -1
[post_type] => comunicados
[post_status] => publish
[orderby] => title
[order] => DESC
</code></pre>
<p>The resulting query is:</p>
<pre><code>SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'comunicados' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_title DESC
</code></pre>
| [
{
"answer_id": 372769,
"author": "Nate Allen",
"author_id": 32698,
"author_profile": "https://wordpress.stackexchange.com/users/32698",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote a couple functions that trick WordPress into thinking we're on the previous/next post before calli... | 2020/08/11 | [
"https://wordpress.stackexchange.com/questions/372768",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/178234/"
] | Attempting to make a search in a custom post type "comunicados" inside a shortcode in a custom plugin I send this to get\_posts()
```
Array
(
[posts_per_page] => -1
[post_type] => comunicados
[post_status] => publish
[orderby] => title
[order] => DESC
[s] => co
)
```
Here the actual code
```
//QUERY
$opt = array(
'posts_per_page' => -1,
'post_type' => 'comunicados',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'DESC'
);
//SEARCH STRING
if($_GET['buscar'] != ''){
$opt['s'] = $_GET['buscar'];
}
print_r($opt);
$res = new WP_Query($opt);
print_r($res);
```
This returns all the content (pages, posts, other custom post types) but "comunicados"
I changed to WP\_Query with the same result.
If I print\_r the WP\_Query I see this:
```
WP_Query Object
(
[query] => Array
(
[posts_per_page] => -1
[post_type] => comunicados
[post_status] => publish
[orderby] => title
[order] => DESC
[s] => co
)
[query_vars] => Array
(
[posts_per_page] => -1
[post_type] => Array
(
[0] => post
[1] => page
[2] => evento
[3] => informes
[4] => publicaciones
[5] => noticias
)
[post_status] => publish
[orderby] => title
[order] => DESC
[s] => co
...
...
...
```
Note the post\_type in query and in query\_vars. Is not supossed to be the same?
Also I see this:
```
[request] => SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND (((wp_posts.post_title LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}') OR (wp_posts.post_excerpt LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}') OR (wp_posts.post_content LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}'))) AND wp_posts.post_type IN ('post', 'page', 'evento', 'informes', 'publicaciones', 'noticias') AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_title DESC
```
It's not using my post\_type and also these weird strings {48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}
I'm not sure how to make this work
This is the post type (create with CPT UI)
```
function cptui_register_my_cpts_comunicados() {
/**
* Post Type: Comunicados.
*/
$labels = [
"name" => __( "Comunicados", "custom-post-type-ui" ),
"singular_name" => __( "Comunicados", "custom-post-type-ui" ),
"menu_name" => __( "Comunicados", "custom-post-type-ui" ),
"all_items" => __( "Todos los comunicados", "custom-post-type-ui" ),
"add_new" => __( "Nuevo comunicado", "custom-post-type-ui" ),
"add_new_item" => __( "Agregar comunicado", "custom-post-type-ui" ),
"edit_item" => __( "Editar comunicado", "custom-post-type-ui" ),
"new_item" => __( "Nuevo comunicado", "custom-post-type-ui" ),
"view_item" => __( "Ver comunicado", "custom-post-type-ui" ),
"view_items" => __( "Ver comunicados", "custom-post-type-ui" ),
];
$args = [
"label" => __( "Comunicados", "custom-post-type-ui" ),
"labels" => $labels,
"description" => "",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"show_in_rest" => true,
"rest_base" => "",
"rest_controller_class" => "WP_REST_Posts_Controller",
"has_archive" => false,
"show_in_menu" => true,
"show_in_nav_menus" => true,
"delete_with_user" => false,
"exclude_from_search" => false,
"capability_type" => "comunicado",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => [ "slug" => "comunicados", "with_front" => true ],
"query_var" => true,
"supports" => [ "title", "editor", "thumbnail", "excerpt" ],
"taxonomies" => [ "post_tag" ],
];
register_post_type( "comunicados", $args );
}
add_action( 'init', 'cptui_register_my_cpts_comunicados' );
```
Weird thing is, if the "s" paramether is not present, this works fine:
```
WP_Query Object
(
[query] => Array
(
[posts_per_page] => -1
[post_type] => comunicados
[post_status] => publish
[orderby] => title
[order] => DESC
)
[query_vars] => Array
(
[posts_per_page] => -1
[post_type] => comunicados
[post_status] => publish
[orderby] => title
[order] => DESC
```
The resulting query is:
```
SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'comunicados' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_title DESC
``` | ```
$current_id = get_the_ID();
$cpt = get_post_type();
$all_ids = get_posts(array(
'fields' => 'ids',
'posts_per_page' => -1,
'post_type' => $cpt,
'order_by' => 'post_date',
'order' => 'ASC',
));
$prev_key = array_search($current_id, $all_ids) - 2;
$next_key = array_search($current_id, $all_ids) + 2;
if(array_key_exists($prev_key, $all_ids)){
$prev_link = get_the_permalink($all_ids[$prev_key]);
echo $prev_link;
}
if(array_key_exists($next_key, $all_ids)){
$next_link = get_the_permalink($all_ids[$next_key]);
echo $next_link;
}
```
So I queried all the posts IDs from the current post type. Then since it’s a simple array key=>value, just found the current post key in the array and just added or subtracted so if your current post is the 8th one, your next is 10 and you previous is 6. Then if your array doesn’t have enough keys, say your current was the 8th but your array only had 9 that will mess it up, I check to see if the key exists. If it does, use get\_the\_permalink() with the value of the desired key.
Probably not the most graceful way to do it but… |
372,785 | <p>I built an image randomizer so that when I open a .php file in a URL that it displays the image with <code>readfile($randomImage);</code>. This works locally but when I upload it to the server it gets blocked by the firewall since we do not want to be able to load URLs like</p>
<pre><code>https://www.example.com/wp-content/themes/THEME/randomImage.php
</code></pre>
<p>I want to load a <code>.php</code> script on a <code>.jpg</code> file.
What needs to happen is that when I use the URL (for instance)</p>
<pre><code>https://www.example.com/image.jpg
</code></pre>
<p>and when I load this image that it runs a PHP file like</p>
<pre><code>https://www.example.com/randomizer.php
</code></pre>
<p>In other words, I want WordPress to think that it is loading a URL ending with <code>.jpg</code> but opens a <code>.php</code> file</p>
<p>Is this something that is realizable?</p>
| [
{
"answer_id": 372789,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 0,
"selected": false,
"text": "<p>Try the following at the <em>top</em> of the <code>.htaccess</code> file, <em>before</em> the existing WordPres... | 2020/08/11 | [
"https://wordpress.stackexchange.com/questions/372785",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/192959/"
] | I built an image randomizer so that when I open a .php file in a URL that it displays the image with `readfile($randomImage);`. This works locally but when I upload it to the server it gets blocked by the firewall since we do not want to be able to load URLs like
```
https://www.example.com/wp-content/themes/THEME/randomImage.php
```
I want to load a `.php` script on a `.jpg` file.
What needs to happen is that when I use the URL (for instance)
```
https://www.example.com/image.jpg
```
and when I load this image that it runs a PHP file like
```
https://www.example.com/randomizer.php
```
In other words, I want WordPress to think that it is loading a URL ending with `.jpg` but opens a `.php` file
Is this something that is realizable? | Try the following at the *top* of the `.htaccess` file, *before* the existing WordPress directives:
```
# Internally rewrite "/image.jpg" to "/randomizer.php"
RewriteRule ^image\.jpg$ randomizer.php [L]
```
This uses mod\_rewrite to rewrite the URL. There is no need to repeat the `RewriteEngine On` directive (that occurs later in the file).
Any request for `/image.jpg` (in the document root) is internally/silently rewritten to your `/randomizer.php` PHP script (also in the document root - assuming that is where your `.htaccess` file is located, *or* where the `RewriteBase` directive points to).
>
> I have a weird request maybe
>
>
>
This isn't weird at all. In fact, using URL-rewriting like this is probably preferable to linking directly to your PHP script. Although calling the URL `random-image.jpg` or something similar maybe a good idea.
This is actually pretty much identical to a question I answered yesterday on StackOverflow:
<https://stackoverflow.com/questions/63340667/htaccess-redirect-one-file-to-another-including-query-string> |
372,805 | <p>I hope this is not a far-away topic from this platform.</p>
<p>I plan to create a WordPress site, but I thought that maybe instead of hosting images on my own WordPress installation, I thought that if I just upload the images to a 3rd-party service like Imgur and then just insert them as linked images in my posts that would be a better idea?</p>
<p>My reasoning is:</p>
<ul>
<li>These 3rd-party services like Imgur already have a CDN, and they are
faster in loading than my website.</li>
<li>I won't have to buy/install some image optimization plugins, because images are hosted somewhere else and they already optimized
there.</li>
<li>Over time, I won't have to worry about storage/size issues because of the large number of pictures.</li>
<li>Some services have been there for 10, 15, 20 years... So they are trusted to not disappear over night.</li>
</ul>
<p>Of course, there might be some concerns about creating a backup just in case my pictures get removed or the 3rd-party service goes down... Is the idea generally good?</p>
<p>Is there anything else I have to worry about?</p>
| [
{
"answer_id": 372789,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 0,
"selected": false,
"text": "<p>Try the following at the <em>top</em> of the <code>.htaccess</code> file, <em>before</em> the existing WordPres... | 2020/08/11 | [
"https://wordpress.stackexchange.com/questions/372805",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193249/"
] | I hope this is not a far-away topic from this platform.
I plan to create a WordPress site, but I thought that maybe instead of hosting images on my own WordPress installation, I thought that if I just upload the images to a 3rd-party service like Imgur and then just insert them as linked images in my posts that would be a better idea?
My reasoning is:
* These 3rd-party services like Imgur already have a CDN, and they are
faster in loading than my website.
* I won't have to buy/install some image optimization plugins, because images are hosted somewhere else and they already optimized
there.
* Over time, I won't have to worry about storage/size issues because of the large number of pictures.
* Some services have been there for 10, 15, 20 years... So they are trusted to not disappear over night.
Of course, there might be some concerns about creating a backup just in case my pictures get removed or the 3rd-party service goes down... Is the idea generally good?
Is there anything else I have to worry about? | Try the following at the *top* of the `.htaccess` file, *before* the existing WordPress directives:
```
# Internally rewrite "/image.jpg" to "/randomizer.php"
RewriteRule ^image\.jpg$ randomizer.php [L]
```
This uses mod\_rewrite to rewrite the URL. There is no need to repeat the `RewriteEngine On` directive (that occurs later in the file).
Any request for `/image.jpg` (in the document root) is internally/silently rewritten to your `/randomizer.php` PHP script (also in the document root - assuming that is where your `.htaccess` file is located, *or* where the `RewriteBase` directive points to).
>
> I have a weird request maybe
>
>
>
This isn't weird at all. In fact, using URL-rewriting like this is probably preferable to linking directly to your PHP script. Although calling the URL `random-image.jpg` or something similar maybe a good idea.
This is actually pretty much identical to a question I answered yesterday on StackOverflow:
<https://stackoverflow.com/questions/63340667/htaccess-redirect-one-file-to-another-including-query-string> |
372,825 | <p>Since WP 5.5 just released and now you can set plugins to auto-update, can this be done via wp-cli?
Looking at the documentation, I don't see a sub-command for it: <a href="https://developer.wordpress.org/cli/commands/plugin/" rel="noreferrer">https://developer.wordpress.org/cli/commands/plugin/</a></p>
<p>I manage a lot of Wordpress sites, most of which are OK to auto-update and would save me a lot of time if they did, as well as reducing security risks.</p>
<p>I'd like to enable auto-updates for plugins across over many wordpress sites. Any solutions?</p>
| [
{
"answer_id": 384240,
"author": "Mike Eng",
"author_id": 7313,
"author_profile": "https://wordpress.stackexchange.com/users/7313",
"pm_score": 1,
"selected": false,
"text": "<p>This is not using wp-cli, but maybe the next best thing:</p>\n<p>From the Plugins page in WordPress Admin: sit... | 2020/08/11 | [
"https://wordpress.stackexchange.com/questions/372825",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31560/"
] | Since WP 5.5 just released and now you can set plugins to auto-update, can this be done via wp-cli?
Looking at the documentation, I don't see a sub-command for it: <https://developer.wordpress.org/cli/commands/plugin/>
I manage a lot of Wordpress sites, most of which are OK to auto-update and would save me a lot of time if they did, as well as reducing security risks.
I'd like to enable auto-updates for plugins across over many wordpress sites. Any solutions? | The simplest way via *wp-cli* that comes to mind (~~while it's not supported yet as far as I can see~~) is something like:
```
wp eval "update_option( 'auto_update_plugins', array_keys( get_plugins() ) );"
```
that will update the `auto_update_plugins` option with the array of all plugin files to update.
This should probably be extended further to only update plugins that are truly *updateable* or e.g. from a json list to use the json format option of *wp-cli*.
One can also enable all plugin updates with a filter in a plugin:
```
add_filter( 'auto_update_plugin', '__return_true' );
```
That will show up as "Auto-updates enabled" for each plugin in the plugins admin table but the user will not be able to change it from the UI.
ps: this *wp-cli* [command suggestion](https://github.com/WordPress/wp-autoupdates/issues/8) by Jeffrey Paul seems very useful.
**Update**: This seems to be supported in [wp-cli/extension-command](https://github.com/wp-cli/extension-command) version 2.0.12 by this [pull request](https://github.com/wp-cli/extension-command/pull/259):
```
wp plugin auto-updates status [<plugin>...] [--all] [--enabled-only] [--disabled-only] [--field=<field>]
wp plugin auto-updates enable [<plugin>...] [--all] [--disabled-only]
wp plugin auto-updates disable [<plugin>...] [--all] [--enabled-only]
```
but it looks like it's not merged into the main *wp-cli* yet in version 2.4.
It's possible to get the latest version with:
```
wp package install git@github.com:wp-cli/extension-command.git
```
according to the [installing](https://github.com/wp-cli/extension-command#installing) part of the *wp-cli/extension-command* docs. |
372,840 | <p>I want to export the form data and send it as an attachment. In this case, can i rewrite the file (/uploads/2020/08/sample.csv) with the form data and send it as an attachment.</p>
<p>right now, it is just a blank attachment when i receive it in my email</p>
<p>Here is my code in function.php, Please help me:</p>
<pre><code>add_action( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 1 );
function add_form_as_attachment(&$WPCF7_ContactForm) {
$contact_form = WPCF7_ContactForm::get_current();
$Fname = $formdata['firstName'];
$Lname = $formdata['lastName'];
$email = $formdata['email'];
$list = array (
array( 'First Name:',$Fname),
array( 'Last Name:', $Lname),
array( 'Email:', $email),
);
$fp = fopen( site_url() . 'uploads/2020/08/sample.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
}
</code></pre>
| [
{
"answer_id": 373724,
"author": "amitdutt24",
"author_id": 188153,
"author_profile": "https://wordpress.stackexchange.com/users/188153",
"pm_score": 0,
"selected": false,
"text": "<p>I solved mine problem with this code. Hope it could help others too -</p>\n<pre><code>add_action( 'wpcf7... | 2020/08/12 | [
"https://wordpress.stackexchange.com/questions/372840",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191358/"
] | I want to export the form data and send it as an attachment. In this case, can i rewrite the file (/uploads/2020/08/sample.csv) with the form data and send it as an attachment.
right now, it is just a blank attachment when i receive it in my email
Here is my code in function.php, Please help me:
```
add_action( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 1 );
function add_form_as_attachment(&$WPCF7_ContactForm) {
$contact_form = WPCF7_ContactForm::get_current();
$Fname = $formdata['firstName'];
$Lname = $formdata['lastName'];
$email = $formdata['email'];
$list = array (
array( 'First Name:',$Fname),
array( 'Last Name:', $Lname),
array( 'Email:', $email),
);
$fp = fopen( site_url() . 'uploads/2020/08/sample.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
}
``` | There are a few things omitted in the above solution, like defining the most params of wp\_mail.
Also I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution.
Here's my take:
```
add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 );
function add_form_as_attachment( $contact_form, $abort, $submission ) {
$form_id = $contact_form->id();
//Check for selected form id and actual submission
if ($form_id == 123 && $submission){
$posted_data = $submission->get_posted_data() ;
// Check again for posted data
if ( empty ($posted_data)){
return;
}
//Get your form fields
$firstname = $posted_data['your-name'];
$lastname = $posted_data['your-lastname'];
$email = $posted_data['your-email'];
$list = array (
array( 'First Name:',$firstname),
array( 'Last Name:', $lastname),
array( 'Email:', $email),
);
// Save file path separately
$upload_dir = wp_upload_dir();
$file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example
$fp = fopen( $file_path , 'w'); //overwrites file at each submission
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
// Modification of mail(1) start here
$properties = $contact_form->get_properties();
$properties['mail']['attachments'] = $file_path;
$contact_form->set_properties($properties);
return $contact_form;
}//endif ID && submission
}
``` |
372,871 | <p>I'm trying to translate the month names as underlined in <a href="https://i.imgur.com/s9x1LOO.png" rel="nofollow noreferrer">this image</a>, without <a href="https://i.imgur.com/gm9RH9L.png" rel="nofollow noreferrer">changing the entire WP backend</a> as well, as I require the backend to remain English.</p>
<p>I managed to translate the default strings via's <a href="https://wpastra.com/docs/astra-default-strings/" rel="nofollow noreferrer">Astra's Default String page</a>, but they don't provide strings for the month names.</p>
<p>Any help would be appreciated!</p>
<p>Thank you :)</p>
| [
{
"answer_id": 373724,
"author": "amitdutt24",
"author_id": 188153,
"author_profile": "https://wordpress.stackexchange.com/users/188153",
"pm_score": 0,
"selected": false,
"text": "<p>I solved mine problem with this code. Hope it could help others too -</p>\n<pre><code>add_action( 'wpcf7... | 2020/08/12 | [
"https://wordpress.stackexchange.com/questions/372871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193023/"
] | I'm trying to translate the month names as underlined in [this image](https://i.imgur.com/s9x1LOO.png), without [changing the entire WP backend](https://i.imgur.com/gm9RH9L.png) as well, as I require the backend to remain English.
I managed to translate the default strings via's [Astra's Default String page](https://wpastra.com/docs/astra-default-strings/), but they don't provide strings for the month names.
Any help would be appreciated!
Thank you :) | There are a few things omitted in the above solution, like defining the most params of wp\_mail.
Also I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution.
Here's my take:
```
add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 );
function add_form_as_attachment( $contact_form, $abort, $submission ) {
$form_id = $contact_form->id();
//Check for selected form id and actual submission
if ($form_id == 123 && $submission){
$posted_data = $submission->get_posted_data() ;
// Check again for posted data
if ( empty ($posted_data)){
return;
}
//Get your form fields
$firstname = $posted_data['your-name'];
$lastname = $posted_data['your-lastname'];
$email = $posted_data['your-email'];
$list = array (
array( 'First Name:',$firstname),
array( 'Last Name:', $lastname),
array( 'Email:', $email),
);
// Save file path separately
$upload_dir = wp_upload_dir();
$file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example
$fp = fopen( $file_path , 'w'); //overwrites file at each submission
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
// Modification of mail(1) start here
$properties = $contact_form->get_properties();
$properties['mail']['attachments'] = $file_path;
$contact_form->set_properties($properties);
return $contact_form;
}//endif ID && submission
}
``` |
372,877 | <p>I had installed a chat plugin called Crisp chat. But i still see crisp chat box in my mobile but not in PC. I have deleted it yet it is seen in mobile. please guide me.</p>
| [
{
"answer_id": 373724,
"author": "amitdutt24",
"author_id": 188153,
"author_profile": "https://wordpress.stackexchange.com/users/188153",
"pm_score": 0,
"selected": false,
"text": "<p>I solved mine problem with this code. Hope it could help others too -</p>\n<pre><code>add_action( 'wpcf7... | 2020/08/12 | [
"https://wordpress.stackexchange.com/questions/372877",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193030/"
] | I had installed a chat plugin called Crisp chat. But i still see crisp chat box in my mobile but not in PC. I have deleted it yet it is seen in mobile. please guide me. | There are a few things omitted in the above solution, like defining the most params of wp\_mail.
Also I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution.
Here's my take:
```
add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 );
function add_form_as_attachment( $contact_form, $abort, $submission ) {
$form_id = $contact_form->id();
//Check for selected form id and actual submission
if ($form_id == 123 && $submission){
$posted_data = $submission->get_posted_data() ;
// Check again for posted data
if ( empty ($posted_data)){
return;
}
//Get your form fields
$firstname = $posted_data['your-name'];
$lastname = $posted_data['your-lastname'];
$email = $posted_data['your-email'];
$list = array (
array( 'First Name:',$firstname),
array( 'Last Name:', $lastname),
array( 'Email:', $email),
);
// Save file path separately
$upload_dir = wp_upload_dir();
$file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example
$fp = fopen( $file_path , 'w'); //overwrites file at each submission
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
// Modification of mail(1) start here
$properties = $contact_form->get_properties();
$properties['mail']['attachments'] = $file_path;
$contact_form->set_properties($properties);
return $contact_form;
}//endif ID && submission
}
``` |
372,878 | <p>I am trying to get latest from specific categories (3 posts), but the code does not seem working. Instead of displaying posts from the mentioned categories, it is displaying posts from the first category.</p>
<p>Here is my code:</p>
<pre><code><?php do_action( 'hitmag_before_content' ); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<h1>Latest News</h1>
<?php do_action( 'hitmag_before_blog_posts' ); ?>
<?php $args = array(
'post_type' => 'post' ,
'orderby' => 'date' ,
'order' => 'DESC' ,
'posts_per_page' => 3,
'category' => '30','33','1',
'paged' => get_query_var('paged'),
'post_parent' => $parent
); ?>
<?php query_posts($args); ?>
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) : ?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
$archive_content_layout = get_option( 'archive_content_layout', 'th-grid-2' );
echo '<div class="posts-wrap ' . esc_attr( $archive_content_layout ) . '">';
/* Start the Loop */
while ( have_posts() ) : the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
echo '</div><!-- .posts-wrap -->';
else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
<?php do_action( 'hitmag_after_blog_posts' ); ?>
</main><!-- #main -->
</div><!-- #primary -->
</code></pre>
| [
{
"answer_id": 373724,
"author": "amitdutt24",
"author_id": 188153,
"author_profile": "https://wordpress.stackexchange.com/users/188153",
"pm_score": 0,
"selected": false,
"text": "<p>I solved mine problem with this code. Hope it could help others too -</p>\n<pre><code>add_action( 'wpcf7... | 2020/08/12 | [
"https://wordpress.stackexchange.com/questions/372878",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/182729/"
] | I am trying to get latest from specific categories (3 posts), but the code does not seem working. Instead of displaying posts from the mentioned categories, it is displaying posts from the first category.
Here is my code:
```
<?php do_action( 'hitmag_before_content' ); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<h1>Latest News</h1>
<?php do_action( 'hitmag_before_blog_posts' ); ?>
<?php $args = array(
'post_type' => 'post' ,
'orderby' => 'date' ,
'order' => 'DESC' ,
'posts_per_page' => 3,
'category' => '30','33','1',
'paged' => get_query_var('paged'),
'post_parent' => $parent
); ?>
<?php query_posts($args); ?>
<?php
if ( have_posts() ) :
if ( is_home() && ! is_front_page() ) : ?>
<header>
<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
</header>
<?php
endif;
$archive_content_layout = get_option( 'archive_content_layout', 'th-grid-2' );
echo '<div class="posts-wrap ' . esc_attr( $archive_content_layout ) . '">';
/* Start the Loop */
while ( have_posts() ) : the_post();
/*
* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
echo '</div><!-- .posts-wrap -->';
else :
get_template_part( 'template-parts/content', 'none' );
endif; ?>
<?php do_action( 'hitmag_after_blog_posts' ); ?>
</main><!-- #main -->
</div><!-- #primary -->
``` | There are a few things omitted in the above solution, like defining the most params of wp\_mail.
Also I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution.
Here's my take:
```
add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 );
function add_form_as_attachment( $contact_form, $abort, $submission ) {
$form_id = $contact_form->id();
//Check for selected form id and actual submission
if ($form_id == 123 && $submission){
$posted_data = $submission->get_posted_data() ;
// Check again for posted data
if ( empty ($posted_data)){
return;
}
//Get your form fields
$firstname = $posted_data['your-name'];
$lastname = $posted_data['your-lastname'];
$email = $posted_data['your-email'];
$list = array (
array( 'First Name:',$firstname),
array( 'Last Name:', $lastname),
array( 'Email:', $email),
);
// Save file path separately
$upload_dir = wp_upload_dir();
$file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example
$fp = fopen( $file_path , 'w'); //overwrites file at each submission
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
// Modification of mail(1) start here
$properties = $contact_form->get_properties();
$properties['mail']['attachments'] = $file_path;
$contact_form->set_properties($properties);
return $contact_form;
}//endif ID && submission
}
``` |
372,886 | <p>If I used /wp-json/wc/v3/products I am getting all products, but what if I want to receive only price and quantity, I searched all we web and couldn't find it!</p>
| [
{
"answer_id": 372888,
"author": "Sam",
"author_id": 193035,
"author_profile": "https://wordpress.stackexchange.com/users/193035",
"pm_score": 1,
"selected": false,
"text": "<p>First of all, sorry for my bad english!</p>\n<p>In PHP, after your file_get_contents(home_url().'/wp-json/wc/v3... | 2020/08/12 | [
"https://wordpress.stackexchange.com/questions/372886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151546/"
] | If I used /wp-json/wc/v3/products I am getting all products, but what if I want to receive only price and quantity, I searched all we web and couldn't find it! | Woocommerce rest API is an extension of WordPress rest API, so you should first check global parameters and specifically "\_fields" in the [REST API Handbook of Wordpress.org](https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/#_fields).
I will give you an example of the data that you want, price and quantity, but also the id and the name of the products for the response to be more human friendly.
```
/wp-json/wc/v3/products?per_page=100&_fields=id,name,regular_price,stock_quantity
```
>
> The "\_fields" attribute is used for every attribute you want to get.
>
>
> The "per\_page" attribute with value of "100" is used to get 100
> products which is the max acceptable value of this attribute and if
> you leave it empty the default is only "10".
>
>
>
Sorry for the 10 months later answer, but I hope that helped you and any other that is facing the same issue. |
372,895 | <p>site been hacked, and all posts been injected a line of js code under the content!</p>
<pre><code><script src='https://js.xxxxxxx.ga/stat.js?n=ns1' type='text/javascript'></script>
</code></pre>
<p>I have found the malware file in the root directory, which inject the JS code with the command:</p>
<pre><code>$q = "SELECT TABLE_SCHEMA,TABLE_NAME FROM information_schema.TABLES WHERE `TABLE_NAME` LIKE '%post%'";
$result = $conn->query($q);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$q2 = "SELECT post_content FROM " . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]." LIMIT 1 ";
$result2 = $conn->query($q2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$val = $row2['post_content'];
if(strpos($val, "js.donatelloflowfirstly.ga") === false){
if(strpos($val, "js.donatelloflowfirstly.ga") === false){
$q3 = "UPDATE " . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]." set post_content = CONCAT(post_content,\"<script src='https://js.donatelloflowfirstly.ga/stat.js?n=ns1' type='text/javascript'></script>\") WHERE post_content NOT LIKE '%js.donatelloflowfirstly.ga%'";
$conn->query($q3);
echo "sql:" . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"];
} else {
}
}
}
} else {
}
}
} else {
}
$conn->close();
</code></pre>
<p>Someone please help me with a MYSQL command so I can delet this code from the PHPmyadmin.</p>
| [
{
"answer_id": 372888,
"author": "Sam",
"author_id": 193035,
"author_profile": "https://wordpress.stackexchange.com/users/193035",
"pm_score": 1,
"selected": false,
"text": "<p>First of all, sorry for my bad english!</p>\n<p>In PHP, after your file_get_contents(home_url().'/wp-json/wc/v3... | 2020/08/12 | [
"https://wordpress.stackexchange.com/questions/372895",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193038/"
] | site been hacked, and all posts been injected a line of js code under the content!
```
<script src='https://js.xxxxxxx.ga/stat.js?n=ns1' type='text/javascript'></script>
```
I have found the malware file in the root directory, which inject the JS code with the command:
```
$q = "SELECT TABLE_SCHEMA,TABLE_NAME FROM information_schema.TABLES WHERE `TABLE_NAME` LIKE '%post%'";
$result = $conn->query($q);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$q2 = "SELECT post_content FROM " . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]." LIMIT 1 ";
$result2 = $conn->query($q2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$val = $row2['post_content'];
if(strpos($val, "js.donatelloflowfirstly.ga") === false){
if(strpos($val, "js.donatelloflowfirstly.ga") === false){
$q3 = "UPDATE " . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]." set post_content = CONCAT(post_content,\"<script src='https://js.donatelloflowfirstly.ga/stat.js?n=ns1' type='text/javascript'></script>\") WHERE post_content NOT LIKE '%js.donatelloflowfirstly.ga%'";
$conn->query($q3);
echo "sql:" . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"];
} else {
}
}
}
} else {
}
}
} else {
}
$conn->close();
```
Someone please help me with a MYSQL command so I can delet this code from the PHPmyadmin. | Woocommerce rest API is an extension of WordPress rest API, so you should first check global parameters and specifically "\_fields" in the [REST API Handbook of Wordpress.org](https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/#_fields).
I will give you an example of the data that you want, price and quantity, but also the id and the name of the products for the response to be more human friendly.
```
/wp-json/wc/v3/products?per_page=100&_fields=id,name,regular_price,stock_quantity
```
>
> The "\_fields" attribute is used for every attribute you want to get.
>
>
> The "per\_page" attribute with value of "100" is used to get 100
> products which is the max acceptable value of this attribute and if
> you leave it empty the default is only "10".
>
>
>
Sorry for the 10 months later answer, but I hope that helped you and any other that is facing the same issue. |
372,897 | <p>I recently updated a WordPress instance from 5.4 to 5.5 to end up with an annoying margin-top in the admin area, above the menu directly.</p>
<p><a href="https://i.stack.imgur.com/bGHZk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bGHZk.png" alt="enter image description here" /></a></p>
<p>I deactivated all plugins, switched themes, did some inspection, and I ended up with some findings.</p>
<p>The CSS class causing the margin-top is <code>.php-error</code>, which is appended to <code>#adminmenuwrap</code> when a php error is supposed to be displayed.</p>
<pre><code>/* in load-styles.php */
.php-error #adminmenuback, .php-error #adminmenuwrap {
margin-top: 2em;
}
/* the menu wrapper */
<div id="adminmenuwrap"></div>
/* the php script in /wp-admin/admin-header.php line 201 */
// Print a CSS class to make PHP errors visible.
if ( error_get_last() && WP_DEBUG && WP_DEBUG_DISPLAY && ini_get( 'display_errors' ) ) {
$admin_body_class .= ' php-error';
}
/* print_r(error_get_last()) outputs */
Array (
[type] => 8
[message] => unserialize(): Error at offset 11857 of 11895 bytes
[file] => .../wp-includes/functions.php
[line] => 624
)
/**
* Unserialize data only if it was serialized.
*
* @since 2.0.0
*
* @param string $data Data that might be unserialized.
* @return mixed Unserialized data can be any type.
*/
function maybe_unserialize( $data ) {
if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.
return @unserialize( trim( $data ) );
}
return $data;
}
</code></pre>
<p>It is perfectly normal that <code>WP_DEBUG && WP_DEBUG_DISPLAY && ini_get( 'display_errors' )</code> be true (because I'm actually debugging), but the problem is that no php error is being displayed.</p>
<p>This instance (with bug) is running on an online hosted server.
But I also have the exact same copy of this instance running on localhost, except it does not have this bug.</p>
<p>Did anyone encounter this scenario? What do you suggest?</p>
<p><strong>------- EDIT (Fix) --------</strong></p>
<p>The following manipulation did solve the problem but I'm still not sure about the origin or "real" cause behind the bug. This been said, it was a calculation error in serialized data, more precisely, in my case it came from the contents of Privacy Policy page sample (tutorial by WordPress).</p>
<p>Here's how I went about it:</p>
<pre><code>// Edit the function in /wp-includes/functions.php on line 624 and include some
// error logging.
// DO NOT FORGET TO REVERT BACK TO THE ORIGINAL CODE ONCE DONE DEBUGGING!
/**
* Unserialize data only if it was serialized.
*
* @since 2.0.0
*
* @param string $data Data that might be unserialized.
* @return mixed Unserialized data can be any type.
*/
function maybe_unserialize( $data ) {
if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.
error_log( "DATA DEBUGGING START ---------- \r");
error_log( "TRIMED: ");
error_log( trim( $data ) );
error_log( "UNSERIALIZED: ");
error_log( print_r(unserialize( trim( $data ) ), true));
error_log( "DATA DEBUGGING END ---------- \r\n");
return unserialize( trim( $data ) );
}
return $data;
}
</code></pre>
<p>This will log all serialized and unserialized values in your debug.log or error.log depending which method you are using. I'm using the default WordPress <code>define( 'WP_DEBUG_LOG', true );</code> in w-config.php, which logs errors in the file debug.log under /wp-content/.</p>
<p>Doing this allowed me to detect the exact row in database causing the problem.
The problem comes from a wrong count calculation.</p>
<pre><code>a:3:{s:11:"plugin_name";s:9:"WordPress";s:11:"policy_text";s:11789:".....
</code></pre>
<p>I did a characters/bytes count of the contents of that key and it turned out to be 11799 instead of 11789.</p>
<p>The value in <code>s:11789</code> must be <code>s:11799</code> in my case. So I changed it in the database and everything worked fine. I also edited the page in the Editor and saved it then rechecked and everything still work fine.</p>
<p>This fixed the issue but I guess something went wrong at some point. Most probably when I imported the local database to a different instance.</p>
<p>I hope this helps!</p>
| [
{
"answer_id": 373027,
"author": "RJR",
"author_id": 193141,
"author_profile": "https://wordpress.stackexchange.com/users/193141",
"pm_score": 3,
"selected": false,
"text": "<p>I ran into that issue too, and it turns out that it was because there actually was an error that wasn't display... | 2020/08/12 | [
"https://wordpress.stackexchange.com/questions/372897",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/191979/"
] | I recently updated a WordPress instance from 5.4 to 5.5 to end up with an annoying margin-top in the admin area, above the menu directly.
[](https://i.stack.imgur.com/bGHZk.png)
I deactivated all plugins, switched themes, did some inspection, and I ended up with some findings.
The CSS class causing the margin-top is `.php-error`, which is appended to `#adminmenuwrap` when a php error is supposed to be displayed.
```
/* in load-styles.php */
.php-error #adminmenuback, .php-error #adminmenuwrap {
margin-top: 2em;
}
/* the menu wrapper */
<div id="adminmenuwrap"></div>
/* the php script in /wp-admin/admin-header.php line 201 */
// Print a CSS class to make PHP errors visible.
if ( error_get_last() && WP_DEBUG && WP_DEBUG_DISPLAY && ini_get( 'display_errors' ) ) {
$admin_body_class .= ' php-error';
}
/* print_r(error_get_last()) outputs */
Array (
[type] => 8
[message] => unserialize(): Error at offset 11857 of 11895 bytes
[file] => .../wp-includes/functions.php
[line] => 624
)
/**
* Unserialize data only if it was serialized.
*
* @since 2.0.0
*
* @param string $data Data that might be unserialized.
* @return mixed Unserialized data can be any type.
*/
function maybe_unserialize( $data ) {
if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.
return @unserialize( trim( $data ) );
}
return $data;
}
```
It is perfectly normal that `WP_DEBUG && WP_DEBUG_DISPLAY && ini_get( 'display_errors' )` be true (because I'm actually debugging), but the problem is that no php error is being displayed.
This instance (with bug) is running on an online hosted server.
But I also have the exact same copy of this instance running on localhost, except it does not have this bug.
Did anyone encounter this scenario? What do you suggest?
**------- EDIT (Fix) --------**
The following manipulation did solve the problem but I'm still not sure about the origin or "real" cause behind the bug. This been said, it was a calculation error in serialized data, more precisely, in my case it came from the contents of Privacy Policy page sample (tutorial by WordPress).
Here's how I went about it:
```
// Edit the function in /wp-includes/functions.php on line 624 and include some
// error logging.
// DO NOT FORGET TO REVERT BACK TO THE ORIGINAL CODE ONCE DONE DEBUGGING!
/**
* Unserialize data only if it was serialized.
*
* @since 2.0.0
*
* @param string $data Data that might be unserialized.
* @return mixed Unserialized data can be any type.
*/
function maybe_unserialize( $data ) {
if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.
error_log( "DATA DEBUGGING START ---------- \r");
error_log( "TRIMED: ");
error_log( trim( $data ) );
error_log( "UNSERIALIZED: ");
error_log( print_r(unserialize( trim( $data ) ), true));
error_log( "DATA DEBUGGING END ---------- \r\n");
return unserialize( trim( $data ) );
}
return $data;
}
```
This will log all serialized and unserialized values in your debug.log or error.log depending which method you are using. I'm using the default WordPress `define( 'WP_DEBUG_LOG', true );` in w-config.php, which logs errors in the file debug.log under /wp-content/.
Doing this allowed me to detect the exact row in database causing the problem.
The problem comes from a wrong count calculation.
```
a:3:{s:11:"plugin_name";s:9:"WordPress";s:11:"policy_text";s:11789:".....
```
I did a characters/bytes count of the contents of that key and it turned out to be 11799 instead of 11789.
The value in `s:11789` must be `s:11799` in my case. So I changed it in the database and everything worked fine. I also edited the page in the Editor and saved it then rechecked and everything still work fine.
This fixed the issue but I guess something went wrong at some point. Most probably when I imported the local database to a different instance.
I hope this helps! | I ran into that issue too, and it turns out that it was because there actually was an error that wasn't displaying. Once I fixed that underlying error, the top margin problem went away.
This is in wp-admin/admin-header.php:
```
// Print a CSS class to make PHP errors visible.
if ( error_get_last() && WP_DEBUG && WP_DEBUG_DISPLAY && ini_get( 'display_errors' ) ) {
$admin_body_class .= ' php-error';
}
```
So I temporarily added a display of that error\_get\_last() output to one of my plugins:
```
$debug = print_r(error_get_last(),true);
echo '<p>php-error: '.esc_attr($debug).'</p>';
```
That showed me where the underlying error was. I fixed it, and problem solved! |
372,941 | <p>On a fresh WordPress install in Linux distributions, <code>wp-config-sample.php</code> contains Carriage Return control characters that are not found in any other .php file in the distribution.</p>
<p>Running</p>
<pre><code>egrep -l $'\r'\$ *.php
</code></pre>
<p>in WP's base dir, will return only <code>wp-config-sample.php</code></p>
<hr />
<p>I am not worried about eliminating the control character, nor am I worried that it interferes with install operations (it doesn’t).</p>
<p>I’d just like to find out if there’s a reason why <code>wp-config-sample.php</code> is the only file with this anomaly.</p>
<hr />
<p><strong>WP versions</strong><br />
Issue <a href="https://wordpress.org/support/topic/control-character-m-found-in-wp-config-sample-php/" rel="nofollow noreferrer">was reported</a> in version 4.6.15. It is still present in the latest version 5.5</p>
<p><strong>Environments</strong><br />
This behavior has been seen in</p>
<ul>
<li>Debian 10 CLI-only</li>
<li>Ubuntu 18.04.4 LTS</li>
<li>Ubuntu 12.04.5 LTS</li>
<li>Ubuntu 20.04.1 LTS</li>
</ul>
<p><strong>WordPress distributions</strong><br />
Install files have been downloaded either</p>
<ul>
<li>as .zip file (e.g. wordpress-5.5.zip) or</li>
<li>as .tar.gz file (e.g. wordpress-5.5.tar.gz)</li>
</ul>
<p><strong>Downloads methods</strong></p>
<ul>
<li>via wget: <code>wget https://wordpress.org/latest.zip</code></li>
<li>via WP CLI: <code>wp core download</code></li>
<li>via a Web browser (in GUI environments)</li>
</ul>
<p>Example screenshot from Ubuntu 12.04.5 LTS</p>
<p><a href="https://i.stack.imgur.com/quDcd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/quDcd.png" alt="Ubuntu 12.04.5 tar.gz version" /></a></p>
<hr />
<p>A <a href="https://www.google.co.uk/search?q=wp-config-sample.php%20Carriage%20Return%20control%20character%20(%5EM)" rel="nofollow noreferrer">Google search</a> doesn't provide any explanation. I have found only a <a href="https://wordpress.org/support/topic/control-character-m-found-in-wp-config-sample-php/" rel="nofollow noreferrer">similar question</a> in the WP support forum but the reply given is "don't worry about it" and does not provide an explanation for it.</p>
| [
{
"answer_id": 373033,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 2,
"selected": false,
"text": "<p>Unix and Unix-like operating systems (like Linux) use different line endings in their text files.</p>\n<blockqu... | 2020/08/13 | [
"https://wordpress.stackexchange.com/questions/372941",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/175096/"
] | On a fresh WordPress install in Linux distributions, `wp-config-sample.php` contains Carriage Return control characters that are not found in any other .php file in the distribution.
Running
```
egrep -l $'\r'\$ *.php
```
in WP's base dir, will return only `wp-config-sample.php`
---
I am not worried about eliminating the control character, nor am I worried that it interferes with install operations (it doesn’t).
I’d just like to find out if there’s a reason why `wp-config-sample.php` is the only file with this anomaly.
---
**WP versions**
Issue [was reported](https://wordpress.org/support/topic/control-character-m-found-in-wp-config-sample-php/) in version 4.6.15. It is still present in the latest version 5.5
**Environments**
This behavior has been seen in
* Debian 10 CLI-only
* Ubuntu 18.04.4 LTS
* Ubuntu 12.04.5 LTS
* Ubuntu 20.04.1 LTS
**WordPress distributions**
Install files have been downloaded either
* as .zip file (e.g. wordpress-5.5.zip) or
* as .tar.gz file (e.g. wordpress-5.5.tar.gz)
**Downloads methods**
* via wget: `wget https://wordpress.org/latest.zip`
* via WP CLI: `wp core download`
* via a Web browser (in GUI environments)
Example screenshot from Ubuntu 12.04.5 LTS
[](https://i.stack.imgur.com/quDcd.png)
---
A [Google search](https://www.google.co.uk/search?q=wp-config-sample.php%20Carriage%20Return%20control%20character%20(%5EM)) doesn't provide any explanation. I have found only a [similar question](https://wordpress.org/support/topic/control-character-m-found-in-wp-config-sample-php/) in the WP support forum but the reply given is "don't worry about it" and does not provide an explanation for it. | From Wordpress support:
>
> It’s for formatting on legacy DOS based systems. Some DOS and Windows based editors will not handle the file correctly without those additional `^M` carriage return character. A UNIX based system will work with or without them and that’s why they don’t matter.
>
>
> <https://en.wikipedia.org/wiki/Newline>
>
>
> This is how a portion of that file should edit.
>
>
>
> ```
> // ** MySQL settings - You can get this info from your web host ** //
> /** The name of the database for WordPress */
> define( 'DB_NAME', 'database_name_here' );
> /** MySQL database username */
> define( 'DB_USER', 'username_here' );
> /** MySQL database password */
> define( 'DB_PASSWORD', 'password_here' );
> /** MySQL hostname */
> define( 'DB_HOST', 'localhost' );
>
> ```
>
> Which is readable.
>
>
> If a new user used the Windows notepad editor then the file would may look like this especially on older versions of Windows.
>
>
>
> ```
> // ** MySQL settings - You can get this info from your web host ** ///** The name of the database for WordPress */define( 'DB_NAME', 'database_name_here' );/** MySQL database username */define( 'DB_USER', 'username_here' );/** MySQL database password */define( 'DB_PASSWORD', 'password_here' );/** MySQL hostname */define( 'DB_HOST', 'localhost' );
>
> ```
>
> Which is one line of mess. It would still work as a PHP file because the newline is less important than the `;` in the file. The additional `^M`s will be ignored and for those other editor applications the user will see something they can both parse and edit.
>
>
> |
372,950 | <p>I'm trying to inject some data into blocks via PHP but am running into trouble with parse_blocks/serialize_blocks breaking my content</p>
<p>I'm using the default 2020 theme and have no plugins installed</p>
<pre><code>add_action('wp', function() {
$oPost = get_post(119);
printf("<h1>Post Content</h1><p>%s</p>", var_dump($oPost->post_content));
$aBlocks = parse_blocks($oPost->post_content);
printf("<h1>Parsed Blocks</h1><pre>%s</pre>", print_r($aBlocks, true));
$sSerialisedBlocks = serialize_blocks($aBlocks);
printf("<h1>Serialised Blocks</h1><p>%s</p>", var_dump($sSerialisedBlocks));
}, PHP_INT_MAX);
</code></pre>
<p>The first print (just outputting the post content) contains this text...</p>
<p><code><h3>What types of accommodation are available in xxxx?<\/h3></code></p>
<p>The second (after parsing into blocks) contains this...</p>
<p><code><h3>What types of accommodation are available in xxxx?</h3></code></p>
<p>But after re-serialising the blocks I get this...</p>
<p><code>\u003ch3\u003eWhat types of accommodation are available in xxxx?\u003c\/h3\u003e</code></p>
<p>Could someone tell me what I'm doing wrong?</p>
<hr />
<p><strong>EDIT</strong></p>
<p>Ok so I followed the source code for serialize_blocks and it does seem like this is intentional with serialize_block_attributes explicitly converting some characters</p>
<p>My question is why then are these characters showing up in the WYSIWYG instead of being correctly converted back?</p>
| [
{
"answer_id": 373870,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>This happens in <code>serialize_block_attributes</code>, the docblock explains why:</p>\n<pre class=\"lang-p... | 2020/08/13 | [
"https://wordpress.stackexchange.com/questions/372950",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140806/"
] | I'm trying to inject some data into blocks via PHP but am running into trouble with parse\_blocks/serialize\_blocks breaking my content
I'm using the default 2020 theme and have no plugins installed
```
add_action('wp', function() {
$oPost = get_post(119);
printf("<h1>Post Content</h1><p>%s</p>", var_dump($oPost->post_content));
$aBlocks = parse_blocks($oPost->post_content);
printf("<h1>Parsed Blocks</h1><pre>%s</pre>", print_r($aBlocks, true));
$sSerialisedBlocks = serialize_blocks($aBlocks);
printf("<h1>Serialised Blocks</h1><p>%s</p>", var_dump($sSerialisedBlocks));
}, PHP_INT_MAX);
```
The first print (just outputting the post content) contains this text...
`<h3>What types of accommodation are available in xxxx?<\/h3>`
The second (after parsing into blocks) contains this...
`<h3>What types of accommodation are available in xxxx?</h3>`
But after re-serialising the blocks I get this...
`\u003ch3\u003eWhat types of accommodation are available in xxxx?\u003c\/h3\u003e`
Could someone tell me what I'm doing wrong?
---
**EDIT**
Ok so I followed the source code for serialize\_blocks and it does seem like this is intentional with serialize\_block\_attributes explicitly converting some characters
My question is why then are these characters showing up in the WYSIWYG instead of being correctly converted back? | This happens in `serialize_block_attributes`, the docblock explains why:
```php
/**
...
* The serialized result is a JSON-encoded string, with unicode escape sequence
* substitution for characters which might otherwise interfere with embedding
* the result in an HTML comment.
...
*/
```
So this is done as an encoding measure to avoid attributes accidentally closing a HTML comment and breaking the format of the document.
Without this, a HTML comment inside a block attribute would break the block and the rest of the content afterwards.
But How Do I Stop The Mangling?!!!
----------------------------------
**No, it isn't mangled.** It's just encoding certain characters by replacing them with unicode escaped versions to prevent breakage.
### Proof 1
Lets take the original code block from the question, and add the following fixes:
* Wrap all in `<pre>` tags
* Use `esc_html` so we can see the tags properly
* Fix the `printf` by removing `var_dump` and using `var_export` with the second parameter so it returns rather than outputs
* Add a final test case where we re-parse and re-serialize 10 times to compare the final result with the original
```php
function reparse_reserialize( string $content, int $loops = 10 ) : string {
$final_content = $content;
for ($x = 0; $x <= $loops; $x++) {
$blocks = parse_blocks( $final_content );
$final_content = serialize_blocks( $blocks );
}
return $final_content;
}
add_action(
'wp',
function() {
$p = get_post( 1 );
echo '<p>Original content:</p>';
echo '<pre>' . esc_html( var_export( $p->post_content, true ) ) . '</pre>';
$final = reparse_reserialize( $p->post_content );
echo '<p>10 parse and serialize loops later:</p>';
echo '<pre>' . esc_html( var_export( $final, true ) ) . '</pre>';
echo '<hr/>';
},
PHP_INT_MAX
);
```
Running that, we see that the content survived the process of being parsed and re-serialized 10 times. If mangling was occuring we would see progressively greater mangling occur
### Proof 2
If we take the mangled markup:
```
\u003ch3\u003eWhat types of accommodation are available in xxxx?\u003c\/h3\u003e
```
Turn it into a JSON string, then decode it:
```php
$json = '"\u003ch3\u003eWhat types of accommodation are available in xxxx?\u003c\/h3\u003e"';
echo '<pre>' . esc_html( json_decode( $json ) ) . '</pre>';
```
We get the original HTML:
```html
<h3>What types of accommodation are available in xxxx?</h3>
```
So no mangling has taken place.
Summary
-------
**There is no mangling or corruption.** It's just encoding the `<` and `>` to prevent breakage. JSON processors handle the unicode escape characters just fine.
If you are seeing these encoded characters in the block editor, then that is a bug, either in the block, or the ACF plugin. You should report it as such |
372,973 | <p>I just recently updated my Wordpress, theme, and plugins, and am now getting these two errors on top of the homepage and pages page.</p>
<blockquote>
<p>Deprecated: wp_make_content_images_responsive is deprecated since
version 5.5.0! Use wp_filter_content_tags() instead. in
/var/www/html/wp-includes/functions.php on line 4773</p>
</blockquote>
<p>and the pages page,</p>
<blockquote>
<p>Notice: register_rest_route was called incorrectly. The REST API route
definition for pum/v1/analytics is missing the required
permission_callback argument. For REST API routes that are intended to
be public, use __return_true as the permission callback. Please see
Debugging in WordPress for more information. (This message was added
in version 5.5.0.) in /var/www/html/wp-includes/functions.php on line
5225</p>
</blockquote>
<p>I also did this in another website but did not get any errors, the sites are built with the same theme/plugins.</p>
| [
{
"answer_id": 373009,
"author": "drcrow",
"author_id": 178234,
"author_profile": "https://wordpress.stackexchange.com/users/178234",
"pm_score": -1,
"selected": false,
"text": "<p>If nothing is broken, in your wp-config.php put this:</p>\n<pre><code>define( 'WP_DEBUG', false );\ndefine(... | 2020/08/13 | [
"https://wordpress.stackexchange.com/questions/372973",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193095/"
] | I just recently updated my Wordpress, theme, and plugins, and am now getting these two errors on top of the homepage and pages page.
>
> Deprecated: wp\_make\_content\_images\_responsive is deprecated since
> version 5.5.0! Use wp\_filter\_content\_tags() instead. in
> /var/www/html/wp-includes/functions.php on line 4773
>
>
>
and the pages page,
>
> Notice: register\_rest\_route was called incorrectly. The REST API route
> definition for pum/v1/analytics is missing the required
> permission\_callback argument. For REST API routes that are intended to
> be public, use \_\_return\_true as the permission callback. Please see
> Debugging in WordPress for more information. (This message was added
> in version 5.5.0.) in /var/www/html/wp-includes/functions.php on line
> 5225
>
>
>
I also did this in another website but did not get any errors, the sites are built with the same theme/plugins. | I suspect this is already resolved in the plugin, but I added a check for the new function in wp-content/plugins/fusion-builder/shortcodes/fusion-image.php:285.
```
if ( ! empty( $image_id ) && function_exists( 'wp_image_add_srcset_and_sizes' ) ) {
$content = wp_image_add_srcset_and_sizes(
$content,
wp_get_attachment_metadata( (int) $image_id ),
$image_id );
} elseif ( function_exists( 'wp_make_content_images_responsive' ) ) {
$content = wp_make_content_images_responsive( $content );
}
``` |
372,974 | <p>Wordpress sends some various default email texts to the users.</p>
<p>For example when the password reset email has been sent, then the user gets an automatic email like this:</p>
<blockquote>
<p><em>Hello user, This notification confirms the change of access password to NAMEOFWEBSITE. If you have not changed your password, please contact the Site Administrator at <strong>default-admin@email.com</strong> This message was sent to users-email@email.com Sincerely, All of us at NAMEOFWEBSITE <a href="https://www.nameofwebsite.com" rel="nofollow noreferrer">https://www.nameofwebsite.com</a></em></p>
</blockquote>
<p>I need to keep the default admin email that i set up in wordpress. But i need to filter all emails to have another email inside the text, like this :</p>
<blockquote>
<p><em>Hello user, This notification confirms the change of access password to NAMEOFWEBSITE. If you have not changed your password, please contact the Site Administrator at <strong>another-email@email.com</strong> This message was sent to users-email@email.com Sincerely, All of us at NAMEOFWEBSITE <a href="https://www.nameofwebsite.com" rel="nofollow noreferrer">https://www.nameofwebsite.com</a></em></p>
</blockquote>
<p>Any ideas if this is possible with some filter?</p>
| [
{
"answer_id": 372977,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 2,
"selected": false,
"text": "<p>There is definitely a filter for that!</p>\n<p>Here is the reference link to wordpress developers page: <a hre... | 2020/08/13 | [
"https://wordpress.stackexchange.com/questions/372974",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129972/"
] | Wordpress sends some various default email texts to the users.
For example when the password reset email has been sent, then the user gets an automatic email like this:
>
> *Hello user, This notification confirms the change of access password to NAMEOFWEBSITE. If you have not changed your password, please contact the Site Administrator at **default-admin@email.com** This message was sent to users-email@email.com Sincerely, All of us at NAMEOFWEBSITE <https://www.nameofwebsite.com>*
>
>
>
I need to keep the default admin email that i set up in wordpress. But i need to filter all emails to have another email inside the text, like this :
>
> *Hello user, This notification confirms the change of access password to NAMEOFWEBSITE. If you have not changed your password, please contact the Site Administrator at **another-email@email.com** This message was sent to users-email@email.com Sincerely, All of us at NAMEOFWEBSITE <https://www.nameofwebsite.com>*
>
>
>
Any ideas if this is possible with some filter? | There is definitely a filter for that!
Here is the reference link to wordpress developers page: <https://developer.wordpress.org/reference/hooks/password_change_email/>
Basically adding this function (with changes) to your functions.php will override your default password reset email.
```
apply_filters( 'password_change_email', array $pass_change_email, array $user, array $userdata )
```
full example:
```
add_filter( 'password_change_email', 'rt_change_password_mail_message', 10, 3 );
function rt_change_password_mail_message( $pass_change_mail, $user, $userdata ) {
$new_message_txt = __( 'Hi [first_name] [last_name],
This notice confirms that your email was changed on on our site.
If you did not change your email, please contact the Site Administrator on our site.
This email has been sent to [user_email]
Regards,
ME' );
$pass_change_mail[ 'message' ] = $new_message_txt;
return $pass_change_mail;
}
```
Checking the notes there, you'll see that the message is part of the `$pass_change_email` array. SO if you just want to add something to it try this...
```
add_filter( 'password_change_email', 'rt_change_password_mail_message', 10, 3 );
function rt_change_password_mail_message( $pass_change_mail, $user, $userdata ) {
$new_message_txt = __( 'new text with phone number' );
$pass_change_mail[ 'message' ] = $pass_change_mail[ 'message' ] . $new_message_txt;
return $pass_change_mail;
}
``` |
372,989 | <p>i want to show category list with custom post type count. but i have two different post types in every category. how can i do that . please help. this is my code:</p>
<pre><code><?php
$category_object = get_queried_object();
$current_category_taxonomy = $category_object->taxonomy;
$current_category_term_id = $category_object->term_id;
$current_category_name = $category_object->name;
$args = array(
'child_of' => $current_category_term_id,
'current_category' => $current_category_term_id,
'depth' => 0,
'echo' => 1,
'exclude' => '',
'exclude_tree' => '',
'feed' => '',
'feed_image' => '',
'feed_type' => '',
'hide_empty' => 0,
'hide_title_if_empty' => false,
'hierarchical' => true,
'order' => 'ASC',
'orderby' => 'name',
'separator' => '',
'show_count' => 1,
'show_option_all' => '',
'show_option_none' => __( 'No categories' ),
'style' => 'list',
'taxonomy' => 'category',
'title_li' => __( $current_category_name ),
'use_desc_for_title' => 0,
);
wp_list_categories($args);
?>
</code></pre>
| [
{
"answer_id": 372994,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function my_taxonomy_posts_count_func($atts)\n {\n extract(shortcode_atts(array... | 2020/08/14 | [
"https://wordpress.stackexchange.com/questions/372989",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/172323/"
] | i want to show category list with custom post type count. but i have two different post types in every category. how can i do that . please help. this is my code:
```
<?php
$category_object = get_queried_object();
$current_category_taxonomy = $category_object->taxonomy;
$current_category_term_id = $category_object->term_id;
$current_category_name = $category_object->name;
$args = array(
'child_of' => $current_category_term_id,
'current_category' => $current_category_term_id,
'depth' => 0,
'echo' => 1,
'exclude' => '',
'exclude_tree' => '',
'feed' => '',
'feed_image' => '',
'feed_type' => '',
'hide_empty' => 0,
'hide_title_if_empty' => false,
'hierarchical' => true,
'order' => 'ASC',
'orderby' => 'name',
'separator' => '',
'show_count' => 1,
'show_option_all' => '',
'show_option_none' => __( 'No categories' ),
'style' => 'list',
'taxonomy' => 'category',
'title_li' => __( $current_category_name ),
'use_desc_for_title' => 0,
);
wp_list_categories($args);
?>
``` | Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type.
In order to do this, you will need to output the markup yourself, and query for the counts yourself.
**This will be slow/heavy/expensive.**
So first we start with the current term/taxonomy:
```php
$category_object = get_queried_object();
$current_category_taxonomy = $category_object->taxonomy;
$current_category_term_id = $category_object->term_id;
$current_category_name = $category_object->name;
```
Then we grab all child terms that aren't empty:
```php
$children = get_terms(
[
'taxonomy' => $current_category_taxonomy,
'parent' => $category_object->term_id,
]
);
```
And loop over each term:
```php
foreach ( $children as $child ) {
//
}
```
Now inside that loop we need to check how many posts are of your particular post type, lets say the `changeme` post type:
```php
$args = [
'post_type' => 'changeme',
$term->taxonomy => $child->term_id,
'posts_per_page' => 1,
];
$q = new WP_Query( $args );
if ( $q->have_posts() ) {
echo '<li>' . esc_html( $term->name ) . ' ( '. intval( $q->found_posts ) . ' ) </li>';
}
```
Notice we used the `found_posts` parameter. At this point, it's just a matter of wrapping the whole thing in a `<ul>` tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with.
Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present.
Or you could just register another taxonomy specific for this post type, and avoid all of this. |
373,025 | <p>I'm trying to come up with a solution for a client.</p>
<p>They sell parasols and each one has the following attributes:</p>
<ul>
<li>Colour</li>
<li>Frame</li>
<li>Size</li>
<li>Base</li>
<li>Bar</li>
</ul>
<p>The way it is set up at the moment, there are 36 variations, and the colour attribute is set to 'any colour' as it doesn't effect price. The other 4 options, (Frame, Size Base & Bar) effect the price.</p>
<p>Now, they want to change the image when the colour swatch is clicked.</p>
<p>Normally, I would create variations from all attributes, and add a unique image for each variation. WooCommerce's native functionality would then take care of the image changing no problem. However, as each of the non-colour attribute affects price, it creates a situation where I need 180 variations!</p>
<p>To try to avoid this variation nightmare, I've built what I thought was a solution in ACF, where I create a relationship between the colour attributes and a custom image, and then I use JS to change the image when the swatch is clicked, independantly from the core functionality.</p>
<p>However, when a full combination is chosen and the price is generated, it calls the get_variation ajax call. This overides the image back to the default. This results in the image changing immediately when the swatch is clicked, but then sliding back to the default image when the variation loads.</p>
<p>Can anyone see a way around this whereby I can control the product image using the swatches, but not affect the variation.</p>
<p>Thanks.</p>
<p><a href="https://i.stack.imgur.com/PLsYH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PLsYH.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 372994,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function my_taxonomy_posts_count_func($atts)\n {\n extract(shortcode_atts(array... | 2020/08/14 | [
"https://wordpress.stackexchange.com/questions/373025",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44848/"
] | I'm trying to come up with a solution for a client.
They sell parasols and each one has the following attributes:
* Colour
* Frame
* Size
* Base
* Bar
The way it is set up at the moment, there are 36 variations, and the colour attribute is set to 'any colour' as it doesn't effect price. The other 4 options, (Frame, Size Base & Bar) effect the price.
Now, they want to change the image when the colour swatch is clicked.
Normally, I would create variations from all attributes, and add a unique image for each variation. WooCommerce's native functionality would then take care of the image changing no problem. However, as each of the non-colour attribute affects price, it creates a situation where I need 180 variations!
To try to avoid this variation nightmare, I've built what I thought was a solution in ACF, where I create a relationship between the colour attributes and a custom image, and then I use JS to change the image when the swatch is clicked, independantly from the core functionality.
However, when a full combination is chosen and the price is generated, it calls the get\_variation ajax call. This overides the image back to the default. This results in the image changing immediately when the swatch is clicked, but then sliding back to the default image when the variation loads.
Can anyone see a way around this whereby I can control the product image using the swatches, but not affect the variation.
Thanks.
[](https://i.stack.imgur.com/PLsYH.png) | Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type.
In order to do this, you will need to output the markup yourself, and query for the counts yourself.
**This will be slow/heavy/expensive.**
So first we start with the current term/taxonomy:
```php
$category_object = get_queried_object();
$current_category_taxonomy = $category_object->taxonomy;
$current_category_term_id = $category_object->term_id;
$current_category_name = $category_object->name;
```
Then we grab all child terms that aren't empty:
```php
$children = get_terms(
[
'taxonomy' => $current_category_taxonomy,
'parent' => $category_object->term_id,
]
);
```
And loop over each term:
```php
foreach ( $children as $child ) {
//
}
```
Now inside that loop we need to check how many posts are of your particular post type, lets say the `changeme` post type:
```php
$args = [
'post_type' => 'changeme',
$term->taxonomy => $child->term_id,
'posts_per_page' => 1,
];
$q = new WP_Query( $args );
if ( $q->have_posts() ) {
echo '<li>' . esc_html( $term->name ) . ' ( '. intval( $q->found_posts ) . ' ) </li>';
}
```
Notice we used the `found_posts` parameter. At this point, it's just a matter of wrapping the whole thing in a `<ul>` tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with.
Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present.
Or you could just register another taxonomy specific for this post type, and avoid all of this. |
373,030 | <p>In Gravity Forms, I have a confirmation set up with various conditional shortcodes. Example:</p>
<pre><code>[gravityforms action="conditional" merge_tag="{:3:value}" condition="contains" value="E"]*** GET A CATEGORY ***[/gravityforms]
</code></pre>
<p>Additionally, I have a PHP function that gets all posts by category, and I would like to use this function inside the conditional shortcode. I'm not figuring out a way to do this, so any help would be appreciated.</p>
<p>My function: <code>useful_tools_list(array( 'type' => 'documents', desc => 'true' ))</code></p>
<p>I also made it into a shortcode: <code>[useful-tools type="documents" desc="true"]</code></p>
<p>I tried using <code><?php ?></code>, but I realized I can't embed PHP into the editor. The conditional shortcode doesn't support nesting other shortcodes inside of it, so that doesn't work.</p>
<p>I'm wondering if there is a way to manipulate the GF conditional shortcode to allow nesting? Or another way of calling the function that I'm not aware of?</p>
| [
{
"answer_id": 372994,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function my_taxonomy_posts_count_func($atts)\n {\n extract(shortcode_atts(array... | 2020/08/14 | [
"https://wordpress.stackexchange.com/questions/373030",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/42925/"
] | In Gravity Forms, I have a confirmation set up with various conditional shortcodes. Example:
```
[gravityforms action="conditional" merge_tag="{:3:value}" condition="contains" value="E"]*** GET A CATEGORY ***[/gravityforms]
```
Additionally, I have a PHP function that gets all posts by category, and I would like to use this function inside the conditional shortcode. I'm not figuring out a way to do this, so any help would be appreciated.
My function: `useful_tools_list(array( 'type' => 'documents', desc => 'true' ))`
I also made it into a shortcode: `[useful-tools type="documents" desc="true"]`
I tried using `<?php ?>`, but I realized I can't embed PHP into the editor. The conditional shortcode doesn't support nesting other shortcodes inside of it, so that doesn't work.
I'm wondering if there is a way to manipulate the GF conditional shortcode to allow nesting? Or another way of calling the function that I'm not aware of? | Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type.
In order to do this, you will need to output the markup yourself, and query for the counts yourself.
**This will be slow/heavy/expensive.**
So first we start with the current term/taxonomy:
```php
$category_object = get_queried_object();
$current_category_taxonomy = $category_object->taxonomy;
$current_category_term_id = $category_object->term_id;
$current_category_name = $category_object->name;
```
Then we grab all child terms that aren't empty:
```php
$children = get_terms(
[
'taxonomy' => $current_category_taxonomy,
'parent' => $category_object->term_id,
]
);
```
And loop over each term:
```php
foreach ( $children as $child ) {
//
}
```
Now inside that loop we need to check how many posts are of your particular post type, lets say the `changeme` post type:
```php
$args = [
'post_type' => 'changeme',
$term->taxonomy => $child->term_id,
'posts_per_page' => 1,
];
$q = new WP_Query( $args );
if ( $q->have_posts() ) {
echo '<li>' . esc_html( $term->name ) . ' ( '. intval( $q->found_posts ) . ' ) </li>';
}
```
Notice we used the `found_posts` parameter. At this point, it's just a matter of wrapping the whole thing in a `<ul>` tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with.
Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present.
Or you could just register another taxonomy specific for this post type, and avoid all of this. |
373,037 | <p>I've been using WordPress for awhile now but one problem I'm constantly facing is creating a local clone of a production site so I can test changes/updates.</p>
<p>My current process goes something like this...</p>
<ul>
<li>Run XAMPP Server</li>
<li>Download the site files (Filzilla)</li>
<li>Download the database (phpMyAdmin)</li>
<li>Create a local database (phpMyAdmin)</li>
<li>Copy site files into XAMPP</li>
<li>Import database</li>
<li>Update WP hostname, settings, etc</li>
</ul>
<p>My question is simple. <strong>Is it possible to automate this entire process?</strong> If not, what can be automated to make this less time consuming?</p>
<p>I've kinda looked into Docker but it seems confusing and I don't know that it helps with most of these steps. I know there are plugins that can create backups of the site but again that only automates a couple steps. I'm pretty sure WP CLI can clone a site but I'm not sure if it can clone a remote site down to local. A solution using WP CLI would be great.</p>
<p>There has to be a better process than I'm doing now :(</p>
| [
{
"answer_id": 372994,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function my_taxonomy_posts_count_func($atts)\n {\n extract(shortcode_atts(array... | 2020/08/14 | [
"https://wordpress.stackexchange.com/questions/373037",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157172/"
] | I've been using WordPress for awhile now but one problem I'm constantly facing is creating a local clone of a production site so I can test changes/updates.
My current process goes something like this...
* Run XAMPP Server
* Download the site files (Filzilla)
* Download the database (phpMyAdmin)
* Create a local database (phpMyAdmin)
* Copy site files into XAMPP
* Import database
* Update WP hostname, settings, etc
My question is simple. **Is it possible to automate this entire process?** If not, what can be automated to make this less time consuming?
I've kinda looked into Docker but it seems confusing and I don't know that it helps with most of these steps. I know there are plugins that can create backups of the site but again that only automates a couple steps. I'm pretty sure WP CLI can clone a site but I'm not sure if it can clone a remote site down to local. A solution using WP CLI would be great.
There has to be a better process than I'm doing now :( | Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type.
In order to do this, you will need to output the markup yourself, and query for the counts yourself.
**This will be slow/heavy/expensive.**
So first we start with the current term/taxonomy:
```php
$category_object = get_queried_object();
$current_category_taxonomy = $category_object->taxonomy;
$current_category_term_id = $category_object->term_id;
$current_category_name = $category_object->name;
```
Then we grab all child terms that aren't empty:
```php
$children = get_terms(
[
'taxonomy' => $current_category_taxonomy,
'parent' => $category_object->term_id,
]
);
```
And loop over each term:
```php
foreach ( $children as $child ) {
//
}
```
Now inside that loop we need to check how many posts are of your particular post type, lets say the `changeme` post type:
```php
$args = [
'post_type' => 'changeme',
$term->taxonomy => $child->term_id,
'posts_per_page' => 1,
];
$q = new WP_Query( $args );
if ( $q->have_posts() ) {
echo '<li>' . esc_html( $term->name ) . ' ( '. intval( $q->found_posts ) . ' ) </li>';
}
```
Notice we used the `found_posts` parameter. At this point, it's just a matter of wrapping the whole thing in a `<ul>` tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with.
Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present.
Or you could just register another taxonomy specific for this post type, and avoid all of this. |
373,042 | <p>I am using <strong>Option 3</strong> from <a href="https://wordpress.stackexchange.com/a/333920">this answer</a> as my source. So far it is working great, it is splitting my search results by post type and listing the posts from each post type in their own sections. The only problem is that this solution does not appear to allow for hyperlinking the post titles using <code>the_permalink();</code> How can I adapt this code so that I can also wrap the post titles in an anchor tag that will direct to the post?</p>
<pre><code><?php get_header(); ?>
<?php
$search_query = new WP_Query(
array(
'posts_per_page' => -1,
's' => esc_attr($_GET['s']),
'post_status' => 'publish'
)
);
if ($search_query->have_posts()) : ?>
<section id="search-results">
<div class="container">
<div class="row">
<div class="col">
<h2><?php echo $search_query->found_posts.' Search results found'; ?> for: "<?php echo get_search_query(); ?>"</h2>
</div>
</div>
<div class="search-results-list">
<?php
$types = array( 'post', 'page', 'glossary' );
$posts_titles = [];
while($search_query->have_posts()) {
$search_query->the_post();
$type = $search_query->post->post_type;
if (!isset($posts_titles[$type]))
$posts_titles[$type] = [];
$posts_titles[$type][] = get_the_title();
}
rewind_posts();
foreach($types as $type) :
if (!isset($posts_titles[$type]))
continue;
?>
<div class="row">
<h3>
<?php
$post_type_obj = get_post_type_object($type);
echo $post_type_obj->labels->name
?>
</h3>
</div>
<div class="row">
<div class="col">
<ul>
<?php foreach($posts_titles[$type] as $title) : ?>
<li class="search-item">
<a href="PERMALINK SHOULD GO HERE"><?php echo htmlspecialchars($title); ?></a>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</section>
<?php else:
echo '<div class="search-suggestions-no-results">
<p>' . __('Sorry, no results found', 'text-domain') . '</p>
</div>';
endif; ?>
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 373180,
"author": "Jagruti Rakholiya",
"author_id": 193235,
"author_profile": "https://wordpress.stackexchange.com/users/193235",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this to add permalink</p>\n<pre><code>echo get_permalink( get_page_by_title( $title, ... | 2020/08/14 | [
"https://wordpress.stackexchange.com/questions/373042",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13286/"
] | I am using **Option 3** from [this answer](https://wordpress.stackexchange.com/a/333920) as my source. So far it is working great, it is splitting my search results by post type and listing the posts from each post type in their own sections. The only problem is that this solution does not appear to allow for hyperlinking the post titles using `the_permalink();` How can I adapt this code so that I can also wrap the post titles in an anchor tag that will direct to the post?
```
<?php get_header(); ?>
<?php
$search_query = new WP_Query(
array(
'posts_per_page' => -1,
's' => esc_attr($_GET['s']),
'post_status' => 'publish'
)
);
if ($search_query->have_posts()) : ?>
<section id="search-results">
<div class="container">
<div class="row">
<div class="col">
<h2><?php echo $search_query->found_posts.' Search results found'; ?> for: "<?php echo get_search_query(); ?>"</h2>
</div>
</div>
<div class="search-results-list">
<?php
$types = array( 'post', 'page', 'glossary' );
$posts_titles = [];
while($search_query->have_posts()) {
$search_query->the_post();
$type = $search_query->post->post_type;
if (!isset($posts_titles[$type]))
$posts_titles[$type] = [];
$posts_titles[$type][] = get_the_title();
}
rewind_posts();
foreach($types as $type) :
if (!isset($posts_titles[$type]))
continue;
?>
<div class="row">
<h3>
<?php
$post_type_obj = get_post_type_object($type);
echo $post_type_obj->labels->name
?>
</h3>
</div>
<div class="row">
<div class="col">
<ul>
<?php foreach($posts_titles[$type] as $title) : ?>
<li class="search-item">
<a href="PERMALINK SHOULD GO HERE"><?php echo htmlspecialchars($title); ?></a>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</section>
<?php else:
echo '<div class="search-suggestions-no-results">
<p>' . __('Sorry, no results found', 'text-domain') . '</p>
</div>';
endif; ?>
<?php get_footer(); ?>
``` | I would try a somewhat different approach.
I would move the array of post types to your new WP\_Query (since you are working with a limited defined set), and then below where you're looping through each post type in your first foreach statement, I would setup a second query to get all posts found within each $type. If you need to access non-standard postdata (i.e. custom metadata), use global $post, otherwise you don't need it.
That way you can use the\_permalink.
Modify your new WP\_Query like so:
```
$search_query = new WP_Query(
array(
'posts_per_page' => -1,
's' => esc_attr($_GET['s']),
'post_status' => 'publish',
'post_type' => array( 'post', 'page', 'glossary' )
)
);
```
Then, you can get rid of all the stuff directly below your opening div for your search-results-list and just skip to this:
```
foreach($types as $type) :
echo '<ul class="' . $type . '">';
while( have_posts() ) {
the_post();
if( $type == get_post_type() ){ ?>
<div class="entry-content">
<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( esc_html__( 'Permalink to %s', 'quark' ), the_title_attribute( 'echo=0' ) ) ); ?>">
<?php the_post_thumbnail( array(100,100) ); ?>
</a>
<?php } ?>
<?php the_excerpt(); ?>
<?php
}
rewind_posts();
echo '</ul>';
endforeach;
?>
```
OR Alternatively if you want to keep to WP's newer way of organizing content/templates, you could have a separate template part for each post type with it's own style options, etc.
```
echo '<ul class="' . $type . '">';
while( have_posts() ) {
the_post();
if( $type == get_post_type() ){
get_template_part('content', 'search' . $type);
}
rewind_posts();
echo '</ul>';
endforeach;
``` |
373,064 | <p>I'm not an expert in PHP and I'm trying to apply conditional formatting on data fetched from wpdb. To be fair, I'm trying to create shortcode for this. My motto is to fetch values for $previous_marks & $current_marks from the database and change the color of $current_marks according to if, else condition. According to condition:</p>
<ul>
<li>If $current_marks > $previous_marks, then value of $current_marks should be displayed in <em>green</em> color along with pass.png image next to the value.</li>
<li>Else value of $current_marks should be displayed in <em>red</em> color along with fail.png image next to the value.</li>
</ul>
<p>I also need help in displaying images next to $current_marks value & I have no code for it:</p>
<p>Here's how my code looks like:</p>
<pre><code> add_shortcode( 'marks_col', function () {
$subject = $_GET['subject'];
global $wpdb;
$previous_marks = $wpdb->get_results( "SELECT prev FROM grade WHERE sub='" .$subject. "'");
$current_marks = $wpdb->get_results( "SELECT current FROM grade WHERE sub='" .$subject. "'");
if ($previous_marks < $current_marks) {
echo "<p style="color:green">" .$current_marks. "</p>"; ##display pass.png next to $current_marks value
} else {
echo "<p style="color:red">" .$current_marks. "</p>"; ##display fail.png next to $current_marks value
}
} );
</code></pre>
<p>$subject is fetched from the website's URL: <a href="http://www.domain.com/results?subject=biology" rel="nofollow noreferrer">www.domain.com/results?subject=biology</a>. Currently, on using the shortcode <strong>[marks_col]</strong> on WP installation, it's just printing 'Array' in red color & nothing else.
Any help would be greatly appreciated.</p>
| [
{
"answer_id": 373180,
"author": "Jagruti Rakholiya",
"author_id": 193235,
"author_profile": "https://wordpress.stackexchange.com/users/193235",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this to add permalink</p>\n<pre><code>echo get_permalink( get_page_by_title( $title, ... | 2020/08/15 | [
"https://wordpress.stackexchange.com/questions/373064",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180322/"
] | I'm not an expert in PHP and I'm trying to apply conditional formatting on data fetched from wpdb. To be fair, I'm trying to create shortcode for this. My motto is to fetch values for $previous\_marks & $current\_marks from the database and change the color of $current\_marks according to if, else condition. According to condition:
* If $current\_marks > $previous\_marks, then value of $current\_marks should be displayed in *green* color along with pass.png image next to the value.
* Else value of $current\_marks should be displayed in *red* color along with fail.png image next to the value.
I also need help in displaying images next to $current\_marks value & I have no code for it:
Here's how my code looks like:
```
add_shortcode( 'marks_col', function () {
$subject = $_GET['subject'];
global $wpdb;
$previous_marks = $wpdb->get_results( "SELECT prev FROM grade WHERE sub='" .$subject. "'");
$current_marks = $wpdb->get_results( "SELECT current FROM grade WHERE sub='" .$subject. "'");
if ($previous_marks < $current_marks) {
echo "<p style="color:green">" .$current_marks. "</p>"; ##display pass.png next to $current_marks value
} else {
echo "<p style="color:red">" .$current_marks. "</p>"; ##display fail.png next to $current_marks value
}
} );
```
$subject is fetched from the website's URL: [www.domain.com/results?subject=biology](http://www.domain.com/results?subject=biology). Currently, on using the shortcode **[marks\_col]** on WP installation, it's just printing 'Array' in red color & nothing else.
Any help would be greatly appreciated. | I would try a somewhat different approach.
I would move the array of post types to your new WP\_Query (since you are working with a limited defined set), and then below where you're looping through each post type in your first foreach statement, I would setup a second query to get all posts found within each $type. If you need to access non-standard postdata (i.e. custom metadata), use global $post, otherwise you don't need it.
That way you can use the\_permalink.
Modify your new WP\_Query like so:
```
$search_query = new WP_Query(
array(
'posts_per_page' => -1,
's' => esc_attr($_GET['s']),
'post_status' => 'publish',
'post_type' => array( 'post', 'page', 'glossary' )
)
);
```
Then, you can get rid of all the stuff directly below your opening div for your search-results-list and just skip to this:
```
foreach($types as $type) :
echo '<ul class="' . $type . '">';
while( have_posts() ) {
the_post();
if( $type == get_post_type() ){ ?>
<div class="entry-content">
<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( esc_html__( 'Permalink to %s', 'quark' ), the_title_attribute( 'echo=0' ) ) ); ?>">
<?php the_post_thumbnail( array(100,100) ); ?>
</a>
<?php } ?>
<?php the_excerpt(); ?>
<?php
}
rewind_posts();
echo '</ul>';
endforeach;
?>
```
OR Alternatively if you want to keep to WP's newer way of organizing content/templates, you could have a separate template part for each post type with it's own style options, etc.
```
echo '<ul class="' . $type . '">';
while( have_posts() ) {
the_post();
if( $type == get_post_type() ){
get_template_part('content', 'search' . $type);
}
rewind_posts();
echo '</ul>';
endforeach;
``` |
373,141 | <p>I have an archive page that pulls in posts using <code>WP_Query()</code>. On the homepage of the site it shows 16 of the custom post type posts, so on the archive I offset the archive page by 16 posts.</p>
<p>The code for this is:</p>
<pre><code>$newsArticles = new WP_Query(array(
'posts_per_page' => 16,
'offset' => 16,
'post_type'=> 'news'
));
while( $newsArticles->have_posts()){
$newsArticles->the_post(); ?>
// HTML
<?php } ?>
</code></pre>
<p>However on this archive page the <code><?php echo paginate_links();?></code> function to show the pagination pages doesn't work. When I click on the page numbers or use the next and previous arrows, but it just shows the same posts on each page.</p>
<p>The pagination code I'm using is:</p>
<pre><code><p>
<?php echo paginate_links(array(
'prev_text' => 'NEWER',
'next_text' => 'OLDER',
));?>
</p>
</code></pre>
<p>Does anybody know how I get the pagination to work with the <code>WP_Query()</code> property <code>offset</code> so the archive pagination behaves like a normal archive page (with pagination) ?</p>
| [
{
"answer_id": 373180,
"author": "Jagruti Rakholiya",
"author_id": 193235,
"author_profile": "https://wordpress.stackexchange.com/users/193235",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this to add permalink</p>\n<pre><code>echo get_permalink( get_page_by_title( $title, ... | 2020/08/17 | [
"https://wordpress.stackexchange.com/questions/373141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] | I have an archive page that pulls in posts using `WP_Query()`. On the homepage of the site it shows 16 of the custom post type posts, so on the archive I offset the archive page by 16 posts.
The code for this is:
```
$newsArticles = new WP_Query(array(
'posts_per_page' => 16,
'offset' => 16,
'post_type'=> 'news'
));
while( $newsArticles->have_posts()){
$newsArticles->the_post(); ?>
// HTML
<?php } ?>
```
However on this archive page the `<?php echo paginate_links();?>` function to show the pagination pages doesn't work. When I click on the page numbers or use the next and previous arrows, but it just shows the same posts on each page.
The pagination code I'm using is:
```
<p>
<?php echo paginate_links(array(
'prev_text' => 'NEWER',
'next_text' => 'OLDER',
));?>
</p>
```
Does anybody know how I get the pagination to work with the `WP_Query()` property `offset` so the archive pagination behaves like a normal archive page (with pagination) ? | I would try a somewhat different approach.
I would move the array of post types to your new WP\_Query (since you are working with a limited defined set), and then below where you're looping through each post type in your first foreach statement, I would setup a second query to get all posts found within each $type. If you need to access non-standard postdata (i.e. custom metadata), use global $post, otherwise you don't need it.
That way you can use the\_permalink.
Modify your new WP\_Query like so:
```
$search_query = new WP_Query(
array(
'posts_per_page' => -1,
's' => esc_attr($_GET['s']),
'post_status' => 'publish',
'post_type' => array( 'post', 'page', 'glossary' )
)
);
```
Then, you can get rid of all the stuff directly below your opening div for your search-results-list and just skip to this:
```
foreach($types as $type) :
echo '<ul class="' . $type . '">';
while( have_posts() ) {
the_post();
if( $type == get_post_type() ){ ?>
<div class="entry-content">
<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( esc_html__( 'Permalink to %s', 'quark' ), the_title_attribute( 'echo=0' ) ) ); ?>">
<?php the_post_thumbnail( array(100,100) ); ?>
</a>
<?php } ?>
<?php the_excerpt(); ?>
<?php
}
rewind_posts();
echo '</ul>';
endforeach;
?>
```
OR Alternatively if you want to keep to WP's newer way of organizing content/templates, you could have a separate template part for each post type with it's own style options, etc.
```
echo '<ul class="' . $type . '">';
while( have_posts() ) {
the_post();
if( $type == get_post_type() ){
get_template_part('content', 'search' . $type);
}
rewind_posts();
echo '</ul>';
endforeach;
``` |
373,149 | <p>I'm using a plugin from LinkedIn Learning to customize into my own plugin's custom Gutenberg blocks.</p>
<p>After I've edited the file <code>plugin/src/index.js</code> (I edited the <code>edit()</code> & <code>save()</code> functions), I now have:</p>
<pre><code>const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
// Import SVG as React component using @svgr/webpack.
// https://www.npmjs.com/package/@svgr/webpack
import { ReactComponent as Logo } from "../bv-logo.svg";
// Import file as base64 encoded URI using url-loader.
// https://www.npmjs.com/package/url-loader
import logoWhiteURL from "../purity-logo.svg";
// https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-registration/
registerBlockType("podkit/home-slider", {
title: __("Home Slider", "podkit"),
icon: { src: Logo },
category: "podkit",
// https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-edit-save/
edit() {
return (
<section class="ad-waypoint" data-animate-down="site-primary-menu-lrg" data-animate-up="site-primary-menu-lrg">
<div class="sec-zero-wrapper">
<div class="item">
<div class="lSSlideOuter ">
<div class="lSSlideWrapper">
<ul class="home-slider content-slider lightSlider lSFade" style="height: 0px; padding-bottom: 71.9931%;">
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/bag-packer_250767238-opt2.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide active" style="display: list-item;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_43604071-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_123343987-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/wind-turbines_13504843-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
</ul>
</div>
<ul class="lSPager lSpg" style="margin-top: 5px;"
><li class=""><a href="#">1</a></li>
<li class="active"><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
</ul>
</div>
</div>
<div class="sec-zero-thematic">
<img src={logoWhiteURL} alt="main-brand-logo"/>
<h3>imagination is only the begining</h3>
</div>
<div class="secondary-menu">
<div class="center">
<div class="content-container">
<div style="margin-top:148px; position:absolute; width: calc(100% - 40px);" class="nav-rule"></div>
<div class="site-navigation-head-btm">
<div class="site-navigation-head-btm-25">
<div class="menu-primary-bottom-menu-container">
<ul id="menu-primary-bottom-menu" class="menu">
<li id="menu-item-1124" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1124"><a>Our clients</a></li>
<li id="menu-item-1125" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1125"><a>Relationships</a></li>
<li id="menu-item-1132" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1132"><a>Products</a></li>
<li id="menu-item-1133" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1133"><a>Latest News</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
);
},
save() {
return (
<section class="ad-waypoint" data-animate-down="site-primary-menu-lrg" data-animate-up="site-primary-menu-lrg">
<div class="sec-zero-wrapper">
<div class="item">
<div class="lSSlideOuter ">
<div class="lSSlideWrapper">
<ul class="home-slider content-slider lightSlider lSFade" style="height: 0px; padding-bottom: 71.9931%;">
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/bag-packer_250767238-opt2.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide active" style="display: list-item;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_43604071-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_123343987-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/wind-turbines_13504843-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
</ul>
</div>
<ul class="lSPager lSpg" style="margin-top: 5px;"
><li class=""><a href="#">1</a></li>
<li class="active"><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
</ul>
</div>
</div>
<div class="sec-zero-thematic">
<img src={logoWhiteURL} alt="main-brand-logo" />
<h3>imagination is only the begining</h3>
</div>
<div class="secondary-menu">
<div class="center">
<div class="content-container">
<div style="margin-top:148px; position:absolute; width: calc(100% - 40px);" class="nav-rule"></div>
<div class="site-navigation-head-btm">
<div class="site-navigation-head-btm-25">
<div class="menu-primary-bottom-menu-container">
<ul id="menu-primary-bottom-menu" class="menu">
<li id="menu-item-1124" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1124"><a>Our clients</a></li>
<li id="menu-item-1125" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1125"><a>Relationships</a></li>
<li id="menu-item-1132" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1132"><a>Products</a></li>
<li id="menu-item-1133" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1133"><a>Latest News</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
)
}
});
</code></pre>
<p>In Microsoft Visual Code, I am running the process <code>wp-scripts start</code> which recompiles the plugin after every save I believe. This process originally found some syntax errors for me, but I receive no more syntax errors in the output of <code>wp-scripts start</code>.</p>
<p>In a local dev WP site, when I try to add the new block, I receive an error:</p>
<blockquote>
<p>This block has encountered an error and cannot be previewed</p>
</blockquote>
<p>At the same time as adding the new block, in the Chrome console, I see:</p>
<pre><code>Error: Minified React error #62; visit https://reactjs.org/docs/error-decoder.html?invariant=62&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at Pd (react-dom.min.js?ver=16.9.0:47)
at nh (react-dom.min.js?ver=16.9.0:132)
at lh (react-dom.min.js?ver=16.9.0:126)
at O (react-dom.min.js?ver=16.9.0:121)
at ze (react-dom.min.js?ver=16.9.0:118)
at react-dom.min.js?ver=16.9.0:53
at unstable_runWithPriority (react.min.js?ver=16.9.0:26)
at Ma (react-dom.min.js?ver=16.9.0:52)
at mg (react-dom.min.js?ver=16.9.0:52)
at V (react-dom.min.js?ver=16.9.0:52)
</code></pre>
<p>which I'm having trouble understanding.</p>
<p>I've set:</p>
<pre><code>define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', true );
</code></pre>
<p>but there is no output on screen or in a debug log.</p>
<p>I've searched online for the error, and most solutions involve updating WordPress or disabling plugins. I only have Akismet & MainWP child, plus the plugin to produce the custom blocks.</p>
<p>Disabling Akismet & MainWP child does not resolve the issue.</p>
<p>How would I go about troubleshooting this error?</p>
<p>Help appreciated.</p>
| [
{
"answer_id": 373248,
"author": "Will",
"author_id": 48698,
"author_profile": "https://wordpress.stackexchange.com/users/48698",
"pm_score": 1,
"selected": false,
"text": "<p>Add this additional variable to your wp-config file:</p>\n<pre><code>define ( 'SCRIPT_DEBUG', true); \n</code></... | 2020/08/17 | [
"https://wordpress.stackexchange.com/questions/373149",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147186/"
] | I'm using a plugin from LinkedIn Learning to customize into my own plugin's custom Gutenberg blocks.
After I've edited the file `plugin/src/index.js` (I edited the `edit()` & `save()` functions), I now have:
```
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
// Import SVG as React component using @svgr/webpack.
// https://www.npmjs.com/package/@svgr/webpack
import { ReactComponent as Logo } from "../bv-logo.svg";
// Import file as base64 encoded URI using url-loader.
// https://www.npmjs.com/package/url-loader
import logoWhiteURL from "../purity-logo.svg";
// https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-registration/
registerBlockType("podkit/home-slider", {
title: __("Home Slider", "podkit"),
icon: { src: Logo },
category: "podkit",
// https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-edit-save/
edit() {
return (
<section class="ad-waypoint" data-animate-down="site-primary-menu-lrg" data-animate-up="site-primary-menu-lrg">
<div class="sec-zero-wrapper">
<div class="item">
<div class="lSSlideOuter ">
<div class="lSSlideWrapper">
<ul class="home-slider content-slider lightSlider lSFade" style="height: 0px; padding-bottom: 71.9931%;">
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/bag-packer_250767238-opt2.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide active" style="display: list-item;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_43604071-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_123343987-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/wind-turbines_13504843-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
</ul>
</div>
<ul class="lSPager lSpg" style="margin-top: 5px;"
><li class=""><a href="#">1</a></li>
<li class="active"><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
</ul>
</div>
</div>
<div class="sec-zero-thematic">
<img src={logoWhiteURL} alt="main-brand-logo"/>
<h3>imagination is only the begining</h3>
</div>
<div class="secondary-menu">
<div class="center">
<div class="content-container">
<div style="margin-top:148px; position:absolute; width: calc(100% - 40px);" class="nav-rule"></div>
<div class="site-navigation-head-btm">
<div class="site-navigation-head-btm-25">
<div class="menu-primary-bottom-menu-container">
<ul id="menu-primary-bottom-menu" class="menu">
<li id="menu-item-1124" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1124"><a>Our clients</a></li>
<li id="menu-item-1125" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1125"><a>Relationships</a></li>
<li id="menu-item-1132" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1132"><a>Products</a></li>
<li id="menu-item-1133" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1133"><a>Latest News</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
);
},
save() {
return (
<section class="ad-waypoint" data-animate-down="site-primary-menu-lrg" data-animate-up="site-primary-menu-lrg">
<div class="sec-zero-wrapper">
<div class="item">
<div class="lSSlideOuter ">
<div class="lSSlideWrapper">
<ul class="home-slider content-slider lightSlider lSFade" style="height: 0px; padding-bottom: 71.9931%;">
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/bag-packer_250767238-opt2.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide active" style="display: list-item;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_43604071-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_123343987-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
<li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/wind-turbines_13504843-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li>
</ul>
</div>
<ul class="lSPager lSpg" style="margin-top: 5px;"
><li class=""><a href="#">1</a></li>
<li class="active"><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
</ul>
</div>
</div>
<div class="sec-zero-thematic">
<img src={logoWhiteURL} alt="main-brand-logo" />
<h3>imagination is only the begining</h3>
</div>
<div class="secondary-menu">
<div class="center">
<div class="content-container">
<div style="margin-top:148px; position:absolute; width: calc(100% - 40px);" class="nav-rule"></div>
<div class="site-navigation-head-btm">
<div class="site-navigation-head-btm-25">
<div class="menu-primary-bottom-menu-container">
<ul id="menu-primary-bottom-menu" class="menu">
<li id="menu-item-1124" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1124"><a>Our clients</a></li>
<li id="menu-item-1125" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1125"><a>Relationships</a></li>
<li id="menu-item-1132" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1132"><a>Products</a></li>
<li id="menu-item-1133" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1133"><a>Latest News</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
)
}
});
```
In Microsoft Visual Code, I am running the process `wp-scripts start` which recompiles the plugin after every save I believe. This process originally found some syntax errors for me, but I receive no more syntax errors in the output of `wp-scripts start`.
In a local dev WP site, when I try to add the new block, I receive an error:
>
> This block has encountered an error and cannot be previewed
>
>
>
At the same time as adding the new block, in the Chrome console, I see:
```
Error: Minified React error #62; visit https://reactjs.org/docs/error-decoder.html?invariant=62&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at Pd (react-dom.min.js?ver=16.9.0:47)
at nh (react-dom.min.js?ver=16.9.0:132)
at lh (react-dom.min.js?ver=16.9.0:126)
at O (react-dom.min.js?ver=16.9.0:121)
at ze (react-dom.min.js?ver=16.9.0:118)
at react-dom.min.js?ver=16.9.0:53
at unstable_runWithPriority (react.min.js?ver=16.9.0:26)
at Ma (react-dom.min.js?ver=16.9.0:52)
at mg (react-dom.min.js?ver=16.9.0:52)
at V (react-dom.min.js?ver=16.9.0:52)
```
which I'm having trouble understanding.
I've set:
```
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', true );
```
but there is no output on screen or in a debug log.
I've searched online for the error, and most solutions involve updating WordPress or disabling plugins. I only have Akismet & MainWP child, plus the plugin to produce the custom blocks.
Disabling Akismet & MainWP child does not resolve the issue.
How would I go about troubleshooting this error?
Help appreciated. | Add this additional variable to your wp-config file:
```
define ( 'SCRIPT_DEBUG', true);
```
Also, [inline styling directly in react is declared differently](https://reactjs.org/docs/dom-elements.html#style) is similar but different in many ways than pure, vanilla CSS.
For example, `<ul class="home-slider content-slider lightSlider lSFade" style="height: 0px; padding-bottom: 71.9931%;">`
is written in react as:
`<ul className={ 'home-slider content-slider lightSlider lSFade'} style={{ paddingBottom: '71.9931%', height: 0}}> {'your content'} </ul>`
(my react code may not be exactly correct!)
As the above link notes, I would recommend to style your css in a separate file (which is already created for you in wp-scripts) instead of directly within react. |
373,157 | <p>I want to Add slider shortcodes. My all slider fields adds properly in shortcode, but the read more button and button link is not displaying. Can you please solve my problem?
This my slider code:</p>
<pre class="lang-php prettyprint-override"><code><section id="firstsection">
<div class="container-fluid">
<div class="col-xs-12 firstsection-maindiv">
<?php
$slide = array( 'post_type' => 'slider' ,);
$slider_query = new WP_Query( $slide );
?>
<?php
if( have_posts() ) : while($slider_query->have_posts() ) : $slider_query->the_post();
?>
<div id="explore-section" class="owl-carousel owl-theme">
<div class="item">
<div class="col-xs-12 firstsection-innerdiv">
<div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-left-div">
<p class="oneplace"><?php echo get_the_title(); ?></p>
<p class="slider-content"><?php echo get_the_content(); ?></p>
<?php $buttonname = get_post_meta($post->ID, "wp_producer_name" , true) ?>
<?php $buttonlink = get_post_meta($post->ID, "wp_button_link" , true) ?>
<button class="slider-btn" type="button"><a href="<?php echo $buttonlink ; ?>"> <?php echo $buttonname ; ?></a></button>
</div>
<div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-right-div">
<?php echo get_the_post_thumbnail(); ?>
</div>
</div>
</div>
</div>
<?php endwhile; endif; ?>
</div>
</div>
</section>
</code></pre>
<p>And this is my shortcodes code:</p>
<pre class="lang-php prettyprint-override"><code>// Add Shortcode
add_shortcode( 'valute-slider-shortcode', 'display_custom_post_type' );
function display_custom_post_type(){
$args = array(
'post_type' => 'Slider',
'post_status' => 'publish'
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
$string .= '<section id="firstsection">';
while( $query->have_posts() ){
$query->the_post();
$buttonname = get_post_meta($post->ID, "wp_producer_name" , true);
if( !empty($buttonname) ): endif;
$string .= '<div class="container-fluid">' .
'<div class="col-xs-12 firstsection-maindiv">' .
'<div id="explore-section" class="owl-carousel owl-theme">' .
'<div class="item">' .
'<div class="col-xs-12 firstsection-innerdiv">' .
' <div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-left-div">' .
' <p class="oneplace">' .get_the_title() . '</p>'.
' <p class="slider-content">' .get_the_content() . '</p>'.
' <button class="slider-btn" type="button">' . $buttonname . '</button>'.
'</div>' . ' <div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-right-div">' . get_the_post_thumbnail() . '</div>' .
'</div>' .
'</div>' .
'</div>' .
'</div>';
}
$string .= '</section>';
}
wp_reset_postdata();
return $string;
</code></pre>
| [
{
"answer_id": 373165,
"author": "Jagruti Rakholiya",
"author_id": 193235,
"author_profile": "https://wordpress.stackexchange.com/users/193235",
"pm_score": 2,
"selected": true,
"text": "<p>Use <code>get_the_ID()</code> instead of <code>$post->ID</code></p>\n<p>This will fix your prob... | 2020/08/17 | [
"https://wordpress.stackexchange.com/questions/373157",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/183253/"
] | I want to Add slider shortcodes. My all slider fields adds properly in shortcode, but the read more button and button link is not displaying. Can you please solve my problem?
This my slider code:
```php
<section id="firstsection">
<div class="container-fluid">
<div class="col-xs-12 firstsection-maindiv">
<?php
$slide = array( 'post_type' => 'slider' ,);
$slider_query = new WP_Query( $slide );
?>
<?php
if( have_posts() ) : while($slider_query->have_posts() ) : $slider_query->the_post();
?>
<div id="explore-section" class="owl-carousel owl-theme">
<div class="item">
<div class="col-xs-12 firstsection-innerdiv">
<div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-left-div">
<p class="oneplace"><?php echo get_the_title(); ?></p>
<p class="slider-content"><?php echo get_the_content(); ?></p>
<?php $buttonname = get_post_meta($post->ID, "wp_producer_name" , true) ?>
<?php $buttonlink = get_post_meta($post->ID, "wp_button_link" , true) ?>
<button class="slider-btn" type="button"><a href="<?php echo $buttonlink ; ?>"> <?php echo $buttonname ; ?></a></button>
</div>
<div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-right-div">
<?php echo get_the_post_thumbnail(); ?>
</div>
</div>
</div>
</div>
<?php endwhile; endif; ?>
</div>
</div>
</section>
```
And this is my shortcodes code:
```php
// Add Shortcode
add_shortcode( 'valute-slider-shortcode', 'display_custom_post_type' );
function display_custom_post_type(){
$args = array(
'post_type' => 'Slider',
'post_status' => 'publish'
);
$string = '';
$query = new WP_Query( $args );
if( $query->have_posts() ){
$string .= '<section id="firstsection">';
while( $query->have_posts() ){
$query->the_post();
$buttonname = get_post_meta($post->ID, "wp_producer_name" , true);
if( !empty($buttonname) ): endif;
$string .= '<div class="container-fluid">' .
'<div class="col-xs-12 firstsection-maindiv">' .
'<div id="explore-section" class="owl-carousel owl-theme">' .
'<div class="item">' .
'<div class="col-xs-12 firstsection-innerdiv">' .
' <div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-left-div">' .
' <p class="oneplace">' .get_the_title() . '</p>'.
' <p class="slider-content">' .get_the_content() . '</p>'.
' <button class="slider-btn" type="button">' . $buttonname . '</button>'.
'</div>' . ' <div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-right-div">' . get_the_post_thumbnail() . '</div>' .
'</div>' .
'</div>' .
'</div>' .
'</div>';
}
$string .= '</section>';
}
wp_reset_postdata();
return $string;
``` | Use `get_the_ID()` instead of `$post->ID`
This will fix your problem |
373,169 | <p>I'm building a webshop, and started to configure the product loop on the shop archive page.
I display the product category related to every product, and I would like to set to the categories to have a background that I've chosen on the admin page.</p>
<p>I've made an ACF colour picker field, and set the colors.</p>
<p>This is the code that I have:</p>
<pre><code>add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 );
function VS_woo_loop_product_title() {
echo '<h3>' . get_the_title() . '</h3>';
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) :
//only displayed if the product has at least one category
$cat_links = array();
foreach ( $terms as $term ) {
$cat_links[] = $term->name;
}
$on_cat = join( " ", $cat_links );
?>
<div style="background: <?php the_field('kollekcio_szine', $terms); ?>">
<?php echo $on_cat; ?>
</div>
<?php endif;
}
</code></pre>
<p>It simply does not work. The category shows up correctly, but the background color does not appear. If I inspect the element I see that the background property is empty.</p>
<p>How should I modify my code to get this work properly?</p>
<p>Thank you for your help!</p>
| [
{
"answer_id": 373171,
"author": "t2pe",
"author_id": 106499,
"author_profile": "https://wordpress.stackexchange.com/users/106499",
"pm_score": 0,
"selected": false,
"text": "<p>If I am reading this correctly, the variable $terms is an array at the point where you use it in the_field. I ... | 2020/08/17 | [
"https://wordpress.stackexchange.com/questions/373169",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/180651/"
] | I'm building a webshop, and started to configure the product loop on the shop archive page.
I display the product category related to every product, and I would like to set to the categories to have a background that I've chosen on the admin page.
I've made an ACF colour picker field, and set the colors.
This is the code that I have:
```
add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 );
function VS_woo_loop_product_title() {
echo '<h3>' . get_the_title() . '</h3>';
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) :
//only displayed if the product has at least one category
$cat_links = array();
foreach ( $terms as $term ) {
$cat_links[] = $term->name;
}
$on_cat = join( " ", $cat_links );
?>
<div style="background: <?php the_field('kollekcio_szine', $terms); ?>">
<?php echo $on_cat; ?>
</div>
<?php endif;
}
```
It simply does not work. The category shows up correctly, but the background color does not appear. If I inspect the element I see that the background property is empty.
How should I modify my code to get this work properly?
Thank you for your help! | The syntax to get the ACF field of a custom taxonomy is:
```
$var = get_field('name_of_acf_field', 'name_of_taxonomy' . '_' . taxonomy_ID);
```
so in your case you'll need to get product\_cat ID before and do something like:
```
add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 );
function VS_woo_loop_product_title() {
echo '<h3>' . get_the_title() . '</h3>';
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) :
//only displayed if the product has at least one category
$cat_links = array();
foreach ( $terms as $term ) {
$cat_links[] = $term->name;
$cat_id = $term->term_id;
}
$on_cat = join( " ", $cat_links );
$bgcolor = get_field('kollekcio_szine', 'product_cat' . '_' . $cat_id);
?>
<div style="background-color: <?php echo $bgcolor; ?>">
<?php echo $on_cat; ?>
</div>
<?php endif;
}
``` |
373,217 | <p>I have a html bootstrap slider which works fine with captions and everything.I would like to integrate it into my Wp theme (my forst one, so total newbie).I found a code, which seems to helo, but it only shows the three pictures and nothing slides...if I hard code the slider, it works.I understand I can just leave it hard coded, but then it's not really WP ;) THANKS.
Here is the code:
functions.php - now complete file.</p>
<pre><code>function load_stylesheets()
{
wp_register_style('style', get_template_directory_uri() . '/style.css', array(), 1,'all');
wp_enqueue_style('style');
wp_register_style('bootstrap', get_template_directory_uri() . '/bootstrap-4.1.3-dist/css/bootstrap.min.css', array(), 1,'all');
wp_enqueue_style('bootstrap');
wp_register_style('fixedcss', get_template_directory_uri() . '/css/fixed.css', array(), 1,'all');
wp_enqueue_style('fixedcss');
wp_register_style('custom', get_template_directory_uri() . '/custom.css', array(), 1,'all');
wp_enqueue_style('custom');
}
add_action('wp_enqueue_scripts', 'load_stylesheets');
//load scripts
function load_javascript()
{
wp_register_script('custom', get_template_directory_uri() . '/js/custom.js', 'jquery', 1, true);
wp_enqueue_script('custom');
wp_register_script('bootstrapjs', get_template_directory_uri() . '/bootstrap-4.1.3-dist/js/bootstrap.min.js',array('jquery'), 1 , true);
wp_enqueue_script('bootstrapjs');
}
add_action('wp_enqueue_scripts', 'load_javascript');
// normal menue theme support
add_theme_support('menus');
// register menus, =>__ is improtant for tansaltions!
register_nav_menus
(
array('top-menu' =>__('Top Menu', 'theme')
)
);
//woocommerce theme suport
function customtheme_add_woocommerce_support()
{
add_theme_support( 'woocommerce' );
}
add_action( 'after_setup_theme', 'customtheme_add_woocommerce_support' );
//Images Slider
function themename_slider_home_images_setup($wp_customize)
{
$wp_customize->add_section('home-slider-images', array(
'title' => 'Home Slider',
));
$wp_customize->add_setting('home-slider-first-image');
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'home-slider-first-image',
array(
'label' => __( 'First Image', 'theme_name' ),
'section' => 'home-slider-images',
'settings' => 'home-slider-first-image'
)
)
);
$wp_customize->add_setting('home-slider-second-image');
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'home-slider-second-image',
array(
'label' => __( 'Second Image', 'theme_name' ),
'section' => 'home-slider-images',
'settings' => 'home-slider-second-image'
)
)
);
$wp_customize->add_setting('home-slider-third-image');
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'home-slider-third-image',
array(
'label' => __( 'Third Image', 'theme_name' ),
'section' => 'home-slider-images',
'settings' => 'home-slider-third-image'
)
)
);
}
add_action('customize_register', 'themename_slider_home_images_setup');`
</code></pre>
<p>front-page.php:</p>
<pre><code> <div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img src="<?php echo get_theme_mod('home-slider-first-image');?>" alt="caption3!" >
</div>
<div class="item header-image"
<img src="<?php echo get_theme_mod('home-slider-second-image');?>" alt="caption2" >
</div>
<div class="item header-image">
<img src="<?php echo get_theme_mod('home-slider-third-image');?>" alt="I am a caption"
</div>
</div>
</code></pre>
| [
{
"answer_id": 373171,
"author": "t2pe",
"author_id": 106499,
"author_profile": "https://wordpress.stackexchange.com/users/106499",
"pm_score": 0,
"selected": false,
"text": "<p>If I am reading this correctly, the variable $terms is an array at the point where you use it in the_field. I ... | 2020/08/18 | [
"https://wordpress.stackexchange.com/questions/373217",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193291/"
] | I have a html bootstrap slider which works fine with captions and everything.I would like to integrate it into my Wp theme (my forst one, so total newbie).I found a code, which seems to helo, but it only shows the three pictures and nothing slides...if I hard code the slider, it works.I understand I can just leave it hard coded, but then it's not really WP ;) THANKS.
Here is the code:
functions.php - now complete file.
```
function load_stylesheets()
{
wp_register_style('style', get_template_directory_uri() . '/style.css', array(), 1,'all');
wp_enqueue_style('style');
wp_register_style('bootstrap', get_template_directory_uri() . '/bootstrap-4.1.3-dist/css/bootstrap.min.css', array(), 1,'all');
wp_enqueue_style('bootstrap');
wp_register_style('fixedcss', get_template_directory_uri() . '/css/fixed.css', array(), 1,'all');
wp_enqueue_style('fixedcss');
wp_register_style('custom', get_template_directory_uri() . '/custom.css', array(), 1,'all');
wp_enqueue_style('custom');
}
add_action('wp_enqueue_scripts', 'load_stylesheets');
//load scripts
function load_javascript()
{
wp_register_script('custom', get_template_directory_uri() . '/js/custom.js', 'jquery', 1, true);
wp_enqueue_script('custom');
wp_register_script('bootstrapjs', get_template_directory_uri() . '/bootstrap-4.1.3-dist/js/bootstrap.min.js',array('jquery'), 1 , true);
wp_enqueue_script('bootstrapjs');
}
add_action('wp_enqueue_scripts', 'load_javascript');
// normal menue theme support
add_theme_support('menus');
// register menus, =>__ is improtant for tansaltions!
register_nav_menus
(
array('top-menu' =>__('Top Menu', 'theme')
)
);
//woocommerce theme suport
function customtheme_add_woocommerce_support()
{
add_theme_support( 'woocommerce' );
}
add_action( 'after_setup_theme', 'customtheme_add_woocommerce_support' );
//Images Slider
function themename_slider_home_images_setup($wp_customize)
{
$wp_customize->add_section('home-slider-images', array(
'title' => 'Home Slider',
));
$wp_customize->add_setting('home-slider-first-image');
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'home-slider-first-image',
array(
'label' => __( 'First Image', 'theme_name' ),
'section' => 'home-slider-images',
'settings' => 'home-slider-first-image'
)
)
);
$wp_customize->add_setting('home-slider-second-image');
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'home-slider-second-image',
array(
'label' => __( 'Second Image', 'theme_name' ),
'section' => 'home-slider-images',
'settings' => 'home-slider-second-image'
)
)
);
$wp_customize->add_setting('home-slider-third-image');
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'home-slider-third-image',
array(
'label' => __( 'Third Image', 'theme_name' ),
'section' => 'home-slider-images',
'settings' => 'home-slider-third-image'
)
)
);
}
add_action('customize_register', 'themename_slider_home_images_setup');`
```
front-page.php:
```
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<img src="<?php echo get_theme_mod('home-slider-first-image');?>" alt="caption3!" >
</div>
<div class="item header-image"
<img src="<?php echo get_theme_mod('home-slider-second-image');?>" alt="caption2" >
</div>
<div class="item header-image">
<img src="<?php echo get_theme_mod('home-slider-third-image');?>" alt="I am a caption"
</div>
</div>
``` | The syntax to get the ACF field of a custom taxonomy is:
```
$var = get_field('name_of_acf_field', 'name_of_taxonomy' . '_' . taxonomy_ID);
```
so in your case you'll need to get product\_cat ID before and do something like:
```
add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 );
function VS_woo_loop_product_title() {
echo '<h3>' . get_the_title() . '</h3>';
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) :
//only displayed if the product has at least one category
$cat_links = array();
foreach ( $terms as $term ) {
$cat_links[] = $term->name;
$cat_id = $term->term_id;
}
$on_cat = join( " ", $cat_links );
$bgcolor = get_field('kollekcio_szine', 'product_cat' . '_' . $cat_id);
?>
<div style="background-color: <?php echo $bgcolor; ?>">
<?php echo $on_cat; ?>
</div>
<?php endif;
}
``` |
373,249 | <h1>The issue</h1>
<p>I am looking for a way to <strong>add linking functionality to a custom block</strong> of mine and found different approaches to this need.</p>
<p>There are:</p>
<ol>
<li>The <a href="https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/url-input#urlinputbutton" rel="nofollow noreferrer">URLInputButton Component</a></li>
<li>The <a href="https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/url-input#urlinput" rel="nofollow noreferrer">URLInput Component</a></li>
<li>The <a href="https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/link-control" rel="nofollow noreferrer">LinkControl Component</a></li>
<li>The <a href="https://github.com/WordPress/gutenberg/blob/73eaacb2e39bc05f520ab65d470512b365efb635/packages/block-editor/src/components/url-popover/README.md" rel="nofollow noreferrer">URLPopover Component</a></li>
</ol>
<p>I got it somehow working with the first two components:</p>
<pre><code>const {URLInputButton, URLInput, URLPopover} = wp.blockEditor;
registerBlockType('my-plugin-domain/textlink', {
title: __('Text Link', 'my-textdomain'),
...
attributes: {
url: {
type: 'string',
},
},
edit(props) {
const {
attributes,
setAttributes,
} = props;
const {url} = attributes;
const blockControls = (
!!isSelected && (
<BlockControls>
<Toolbar>
<URLInputButton
url={url}
onChange={(url, post) => setAttributes(
{url, title: (post && post.title) || __('Click here')},
)}
/>
<URLInput
className={className}
value={url}
onChange={(url, post) => setAttributes(
{url, text: (post && post.title) || 'Click here'})}
/>
</Toolbar>
}
...
});
</code></pre>
<p>Unfortunately the <code>URLInput</code> as well as the <code>URLInputButton</code> appear <strong>displaced/buggy</strong> when entering a link.</p>
<p>Hence I'm trying to figure out a way how to use the <code>LinkControl</code> Component and I can't get it to work. I wasn't even able to figure out from which Package it has to be imported yet.</p>
<pre><code>const {LinkControl} = wp.blockEditor; // This doesn't seem to work
const {LinkControl} = wp.components; // Neither this
...
// This is not working:
edit(props){
...
<LinkControl
onChange={(nextValue) => {
console.log(nextValue);
}}
/>
...
}
...
</code></pre>
<p>Also I wasn't able to get the <a href="https://github.com/WordPress/gutenberg/blob/73eaacb2e39bc05f520ab65d470512b365efb635/packages/block-editor/src/components/url-popover/README.md" rel="nofollow noreferrer">URLPopover</a> to work.</p>
<p>If anyone could point me into the right direction, it would be highly appreciated!</p>
| [
{
"answer_id": 376014,
"author": "fluoriteen",
"author_id": 178753,
"author_profile": "https://wordpress.stackexchange.com/users/178753",
"pm_score": 4,
"selected": true,
"text": "<p><em>LinkControl</em> is an experimental component, so it's declared differently in <em>blockEditor</em> p... | 2020/08/18 | [
"https://wordpress.stackexchange.com/questions/373249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/165265/"
] | The issue
=========
I am looking for a way to **add linking functionality to a custom block** of mine and found different approaches to this need.
There are:
1. The [URLInputButton Component](https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/url-input#urlinputbutton)
2. The [URLInput Component](https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/url-input#urlinput)
3. The [LinkControl Component](https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/link-control)
4. The [URLPopover Component](https://github.com/WordPress/gutenberg/blob/73eaacb2e39bc05f520ab65d470512b365efb635/packages/block-editor/src/components/url-popover/README.md)
I got it somehow working with the first two components:
```
const {URLInputButton, URLInput, URLPopover} = wp.blockEditor;
registerBlockType('my-plugin-domain/textlink', {
title: __('Text Link', 'my-textdomain'),
...
attributes: {
url: {
type: 'string',
},
},
edit(props) {
const {
attributes,
setAttributes,
} = props;
const {url} = attributes;
const blockControls = (
!!isSelected && (
<BlockControls>
<Toolbar>
<URLInputButton
url={url}
onChange={(url, post) => setAttributes(
{url, title: (post && post.title) || __('Click here')},
)}
/>
<URLInput
className={className}
value={url}
onChange={(url, post) => setAttributes(
{url, text: (post && post.title) || 'Click here'})}
/>
</Toolbar>
}
...
});
```
Unfortunately the `URLInput` as well as the `URLInputButton` appear **displaced/buggy** when entering a link.
Hence I'm trying to figure out a way how to use the `LinkControl` Component and I can't get it to work. I wasn't even able to figure out from which Package it has to be imported yet.
```
const {LinkControl} = wp.blockEditor; // This doesn't seem to work
const {LinkControl} = wp.components; // Neither this
...
// This is not working:
edit(props){
...
<LinkControl
onChange={(nextValue) => {
console.log(nextValue);
}}
/>
...
}
...
```
Also I wasn't able to get the [URLPopover](https://github.com/WordPress/gutenberg/blob/73eaacb2e39bc05f520ab65d470512b365efb635/packages/block-editor/src/components/url-popover/README.md) to work.
If anyone could point me into the right direction, it would be highly appreciated! | *LinkControl* is an experimental component, so it's declared differently in *blockEditor* package
try this as an import statement, this worked for me:
```
const {__experimentalLinkControl } = wp.blockEditor;
const LinkControl = __experimentalLinkControl;
``` |
373,267 | <p>Inside the loop, when logged in to a localhost test site as <code>$user->ID == 1</code> the function <code>is_author(get_current_user_id())</code> returns <code>false</code> when <code>get_the_author_meta('ID')</code> returns 1. Thus, the following conditional is never executed (<code>is_user_logged_in()</code> returns <code>true</code>):</p>
<pre><code>if( is_user_logged_in() && is_author(get_current_user_id()) ) {
// do stuff
}
</code></pre>
<p>Have I missed something obvious?</p>
| [
{
"answer_id": 373271,
"author": "Nate Allen",
"author_id": 32698,
"author_profile": "https://wordpress.stackexchange.com/users/32698",
"pm_score": 3,
"selected": true,
"text": "<p>Are you sure you're doing it within the loop? The <code>is_author</code> function checks if <code>$wp_query... | 2020/08/18 | [
"https://wordpress.stackexchange.com/questions/373267",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109240/"
] | Inside the loop, when logged in to a localhost test site as `$user->ID == 1` the function `is_author(get_current_user_id())` returns `false` when `get_the_author_meta('ID')` returns 1. Thus, the following conditional is never executed (`is_user_logged_in()` returns `true`):
```
if( is_user_logged_in() && is_author(get_current_user_id()) ) {
// do stuff
}
```
Have I missed something obvious? | Are you sure you're doing it within the loop? The `is_author` function checks if `$wp_query` is set.
Another option would be to try this:
```
$current_user = wp_get_current_user();
if (is_user_logged_in() && $current_user->ID == $post->post_author) {
// do stuff
}
``` |
373,346 | <p><a href="https://i.stack.imgur.com/wJfvk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wJfvk.jpg" alt="enter image description here" /></a></p>
<p>How to add Category name to post title ? “PostTitle + CategoryName”?</p>
| [
{
"answer_id": 373271,
"author": "Nate Allen",
"author_id": 32698,
"author_profile": "https://wordpress.stackexchange.com/users/32698",
"pm_score": 3,
"selected": true,
"text": "<p>Are you sure you're doing it within the loop? The <code>is_author</code> function checks if <code>$wp_query... | 2020/08/19 | [
"https://wordpress.stackexchange.com/questions/373346",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193395/"
] | [](https://i.stack.imgur.com/wJfvk.jpg)
How to add Category name to post title ? “PostTitle + CategoryName”? | Are you sure you're doing it within the loop? The `is_author` function checks if `$wp_query` is set.
Another option would be to try this:
```
$current_user = wp_get_current_user();
if (is_user_logged_in() && $current_user->ID == $post->post_author) {
// do stuff
}
``` |
373,355 | <p>Is there a way to change the size of featured images on posts? When I click on one of my blog posts, I can see it’s extremely large and inefficient.</p>
<p><a href="https://graduateinvestor.com" rel="nofollow noreferrer">https://graduateinvestor.com</a></p>
| [
{
"answer_id": 373271,
"author": "Nate Allen",
"author_id": 32698,
"author_profile": "https://wordpress.stackexchange.com/users/32698",
"pm_score": 3,
"selected": true,
"text": "<p>Are you sure you're doing it within the loop? The <code>is_author</code> function checks if <code>$wp_query... | 2020/08/20 | [
"https://wordpress.stackexchange.com/questions/373355",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193403/"
] | Is there a way to change the size of featured images on posts? When I click on one of my blog posts, I can see it’s extremely large and inefficient.
<https://graduateinvestor.com> | Are you sure you're doing it within the loop? The `is_author` function checks if `$wp_query` is set.
Another option would be to try this:
```
$current_user = wp_get_current_user();
if (is_user_logged_in() && $current_user->ID == $post->post_author) {
// do stuff
}
``` |
373,357 | <p>Simple question. I'm attempting to use <code>get_permalink()</code> in vanilla php but cannot access it. I have <code>include_once</code> all these "used" files:</p>
<ul>
<li>wp-settings.php</li>
<li>wp-includes/load.php</li>
<li>wp-includes/link-template.php</li>
<li>wp-includes/rewrite.php</li>
<li>wp-includes/functions.php</li>
</ul>
<p>and 10 other files. How do I access <code>get_permalink()</code>?</p>
| [
{
"answer_id": 373271,
"author": "Nate Allen",
"author_id": 32698,
"author_profile": "https://wordpress.stackexchange.com/users/32698",
"pm_score": 3,
"selected": true,
"text": "<p>Are you sure you're doing it within the loop? The <code>is_author</code> function checks if <code>$wp_query... | 2020/08/20 | [
"https://wordpress.stackexchange.com/questions/373357",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/189616/"
] | Simple question. I'm attempting to use `get_permalink()` in vanilla php but cannot access it. I have `include_once` all these "used" files:
* wp-settings.php
* wp-includes/load.php
* wp-includes/link-template.php
* wp-includes/rewrite.php
* wp-includes/functions.php
and 10 other files. How do I access `get_permalink()`? | Are you sure you're doing it within the loop? The `is_author` function checks if `$wp_query` is set.
Another option would be to try this:
```
$current_user = wp_get_current_user();
if (is_user_logged_in() && $current_user->ID == $post->post_author) {
// do stuff
}
``` |
373,367 | <p>So I've got the dreaded error too it seems. Apparently it's a very common issue but I can't really seem to get a hang on the fix.</p>
<p>One of the plugins my theme uses is causing the error as per the log I got in the email WordPress sent to my admin email. Here's the full log</p>
<pre><code>Error Details
=============
An error of type E_ERROR was caused in line 8 of the file /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/rb_metaboxes.php. Error message: Uncaught Error: Call to undefined function rb_get_metabox() in /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/rb_metaboxes.php:8
Stack trace:
#0 /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/metaboxes_exec.php(200): rb_setup_metaboxes()
#1 /home/younited/domains/younitedsupport.com/public_html/wp-includes/class-wp-hook.php(289): rb_save_metaboxes(4585)
#2 /home/younited/domains/younitedsupport.com/public_html/wp-includes/class-wp-hook.php(311): WP_Hook->apply_filters(NULL, Array)
#3 /home/younited/domains/younitedsupport.com/public_html/wp-includes/plugin.php(478): WP_Hook->do_action(Array)
#4 /home/younited/domains/younitedsupport.com/public_html/wp-includes/post.php(4260): do_action('save_post', 4585, Object(WP_Post), false)
#5 /home/younited/domains/younitedsupport.com/public_html/wp-admin/includes/post.php(687): wp_insert_post(Array)
#6 /home/younited/domains/younitedsupport.com/public_html/wp-admin/incl
</code></pre>
<p>Here's some additional information:<br />
WordPress version 5.5<br />
Current theme: Setech | Shared by WPTry.org (version 1.0.2)<br />
Current plugin: RB Essentials (version 1.0.1)<br />
PHP version 7.3.19</p>
<p>The website was running fine until yesterday on the exact same configuration. I made no changes that caused this error.</p>
<p>As you can guess, I have absolutely zero ideas what this means. I've tried disabling the plugin and reloading the site but it didn't work. Also, if I try to change the theme I get an HTTP 500 Internal Server Error(File "/home/younited/domains/younitedsupport.com/public_html/wp-admin/themes.php" is writeable by group) when clicking on the themes pages in WordPress.</p>
<p>The same site on my localhost works just fine BTW. Everything is identical between the two sites. Any ideas on how to fix this?</p>
| [
{
"answer_id": 373370,
"author": "t2pe",
"author_id": 106499,
"author_profile": "https://wordpress.stackexchange.com/users/106499",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think this is an answer as such but I need a bit more space than the comment box allows...</p>\n<p>You... | 2020/08/20 | [
"https://wordpress.stackexchange.com/questions/373367",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193417/"
] | So I've got the dreaded error too it seems. Apparently it's a very common issue but I can't really seem to get a hang on the fix.
One of the plugins my theme uses is causing the error as per the log I got in the email WordPress sent to my admin email. Here's the full log
```
Error Details
=============
An error of type E_ERROR was caused in line 8 of the file /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/rb_metaboxes.php. Error message: Uncaught Error: Call to undefined function rb_get_metabox() in /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/rb_metaboxes.php:8
Stack trace:
#0 /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/metaboxes_exec.php(200): rb_setup_metaboxes()
#1 /home/younited/domains/younitedsupport.com/public_html/wp-includes/class-wp-hook.php(289): rb_save_metaboxes(4585)
#2 /home/younited/domains/younitedsupport.com/public_html/wp-includes/class-wp-hook.php(311): WP_Hook->apply_filters(NULL, Array)
#3 /home/younited/domains/younitedsupport.com/public_html/wp-includes/plugin.php(478): WP_Hook->do_action(Array)
#4 /home/younited/domains/younitedsupport.com/public_html/wp-includes/post.php(4260): do_action('save_post', 4585, Object(WP_Post), false)
#5 /home/younited/domains/younitedsupport.com/public_html/wp-admin/includes/post.php(687): wp_insert_post(Array)
#6 /home/younited/domains/younitedsupport.com/public_html/wp-admin/incl
```
Here's some additional information:
WordPress version 5.5
Current theme: Setech | Shared by WPTry.org (version 1.0.2)
Current plugin: RB Essentials (version 1.0.1)
PHP version 7.3.19
The website was running fine until yesterday on the exact same configuration. I made no changes that caused this error.
As you can guess, I have absolutely zero ideas what this means. I've tried disabling the plugin and reloading the site but it didn't work. Also, if I try to change the theme I get an HTTP 500 Internal Server Error(File "/home/younited/domains/younitedsupport.com/public\_html/wp-admin/themes.php" is writeable by group) when clicking on the themes pages in WordPress.
The same site on my localhost works just fine BTW. Everything is identical between the two sites. Any ideas on how to fix this? | So I reinstalled WordPress on both my live and local environments and downgraded to version 5.4.2 and everything seems to be working just fine, so far.
I'll update if anything breaks again. |
373,386 | <p>How can I pass the results of a <code>WP_Query</code> call to a plugin? I've tried passing the data via a shortcode attribute, but I get the error "Object of class WP_Query could not be converted to string".</p>
<p>E.g.:</p>
<pre><code>$args = array(
// ...
);
$the_query = WP_Query($args);
echo do_shortcode( [example_custom_plugin query_payload="' . $the_query . '"] );
</code></pre>
<p>What are the different (and best advised) ways for a plugin to retrieve variables (which may be objects or arrays of data) that the WP template has set?</p>
<p>In my case, my plugin is instantiated via the shortcode call, hence why I am approaching it from that perspective; I want the plugin to have the results of the WP_Query at instantiation.</p>
| [
{
"answer_id": 373395,
"author": "Movs",
"author_id": 193435,
"author_profile": "https://wordpress.stackexchange.com/users/193435",
"pm_score": -1,
"selected": false,
"text": "<ol>\n<li>Use global variable</li>\n<li>Pass just $args and run the same query inside the plugin</li>\n<li>Seria... | 2020/08/20 | [
"https://wordpress.stackexchange.com/questions/373386",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90498/"
] | How can I pass the results of a `WP_Query` call to a plugin? I've tried passing the data via a shortcode attribute, but I get the error "Object of class WP\_Query could not be converted to string".
E.g.:
```
$args = array(
// ...
);
$the_query = WP_Query($args);
echo do_shortcode( [example_custom_plugin query_payload="' . $the_query . '"] );
```
What are the different (and best advised) ways for a plugin to retrieve variables (which may be objects or arrays of data) that the WP template has set?
In my case, my plugin is instantiated via the shortcode call, hence why I am approaching it from that perspective; I want the plugin to have the results of the WP\_Query at instantiation. | I think for shortcodes, which are generally used in the WYSIWYG editor by non-technical users, it's best to keep the parameters simple:
```
[custom-shortcode color="red" size="medium"]
```
In other words, shortcodes are designed to provide functionality that an end-user can place somewhere in their content, with the option of supplying a few different customizations.
For obtaining something as a complicated as `WP_Query` results, I would use:
```php
global $wp_query;
```
That gives you access to the current query being executed at the moment that your shortcode is run. You can do that in the function that your shortcode would call.
If you need to make an entirely custom query for different data, you can in fact just create a new `WP_Query`:
```php
function custom_shortcode() {
$params = [];
$q = new WP_Query($params);
// ...
}
```
So it's best for your plugin to go lookup or get the data versus expecting the data to be passed. That's not always the case, but with what you presented, that seems like the best route. |
373,404 | <p>I would like to add the following JavaScript function to a wordpress child theme (functions.php). Unfortunately I am not able to make it.
Function:</p>
<pre><code>$.fn.cityAutocomplete.transliterate = function (s) {
s = String(s);
return s;
};
</code></pre>
<p>I tried this:</p>
<pre><code><?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'listingpr-parent-style', get_template_directory_uri() . '/style.css' );
}
echo "<script>fn.cityAutocomplete.transliterate();</script>";
?>
</code></pre>
<p>But it dont work. Please help me to fix my issue.
Thanks you!</p>
<p>regards
shotput_wp</p>
| [
{
"answer_id": 373395,
"author": "Movs",
"author_id": 193435,
"author_profile": "https://wordpress.stackexchange.com/users/193435",
"pm_score": -1,
"selected": false,
"text": "<ol>\n<li>Use global variable</li>\n<li>Pass just $args and run the same query inside the plugin</li>\n<li>Seria... | 2020/08/20 | [
"https://wordpress.stackexchange.com/questions/373404",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193446/"
] | I would like to add the following JavaScript function to a wordpress child theme (functions.php). Unfortunately I am not able to make it.
Function:
```
$.fn.cityAutocomplete.transliterate = function (s) {
s = String(s);
return s;
};
```
I tried this:
```
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'listingpr-parent-style', get_template_directory_uri() . '/style.css' );
}
echo "<script>fn.cityAutocomplete.transliterate();</script>";
?>
```
But it dont work. Please help me to fix my issue.
Thanks you!
regards
shotput\_wp | I think for shortcodes, which are generally used in the WYSIWYG editor by non-technical users, it's best to keep the parameters simple:
```
[custom-shortcode color="red" size="medium"]
```
In other words, shortcodes are designed to provide functionality that an end-user can place somewhere in their content, with the option of supplying a few different customizations.
For obtaining something as a complicated as `WP_Query` results, I would use:
```php
global $wp_query;
```
That gives you access to the current query being executed at the moment that your shortcode is run. You can do that in the function that your shortcode would call.
If you need to make an entirely custom query for different data, you can in fact just create a new `WP_Query`:
```php
function custom_shortcode() {
$params = [];
$q = new WP_Query($params);
// ...
}
```
So it's best for your plugin to go lookup or get the data versus expecting the data to be passed. That's not always the case, but with what you presented, that seems like the best route. |
373,442 | <p>My permalinks is set to <code>/%post_id%/</code> (post id).</p>
<p><a href="https://elrons.co.il/%post_id%/" rel="nofollow noreferrer">https://elrons.co.il/%post_id%/</a></p>
<p>I want to change them all to <code>/%postname%/</code> (which is the post slug).</p>
<p><a href="https://elrons.co.il/%postname%/" rel="nofollow noreferrer">https://elrons.co.il/%postname%/</a></p>
<p>Problem is, whenever I change it, it gives 404 errors from my old page urls.</p>
<p>for example, this: <a href="https://elrons.co.il/1779/" rel="nofollow noreferrer">https://elrons.co.il/1779/</a></p>
<p>should change to: <a href="https://elrons.co.il/pil-kahol-font/" rel="nofollow noreferrer">https://elrons.co.il/pil-kahol-font/</a></p>
<p>But it gives 404 instead.</p>
<p>How do I make 301 redirection from <code>/%post_id%/</code> to <code>/%postname%/</code>?</p>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/21 | [
"https://wordpress.stackexchange.com/questions/373442",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98773/"
] | My permalinks is set to `/%post_id%/` (post id).
<https://elrons.co.il/%post_id%/>
I want to change them all to `/%postname%/` (which is the post slug).
<https://elrons.co.il/%postname%/>
Problem is, whenever I change it, it gives 404 errors from my old page urls.
for example, this: <https://elrons.co.il/1779/>
should change to: <https://elrons.co.il/pil-kahol-font/>
But it gives 404 instead.
How do I make 301 redirection from `/%post_id%/` to `/%postname%/`? | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,447 | <p>Is it possible to disable the cropping step when adding a site icon via the Theme Customizer in WordPress 5+ (occurred to me in 5.5)?</p>
<p>For me cropping is unnecessary because I always upload a square image in the directions of the recommendations.</p>
<p>That's why this step is not helping me at all, instead is actually causing the following problems:</p>
<ul>
<li>It creates an unnecessary copy of the image with a <code>cropped</code> prefix.</li>
<li>For the cropped image it creates a <strong>NEW</strong> attachment.</li>
</ul>
<p>Thus all the settings I did for the attachment of the un-cropped image are lost and the filename of the site icon will always include this <code>cropped</code> prefix.</p>
<p>Is there anyway to fix this without patching the source of this problem?</p>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/21 | [
"https://wordpress.stackexchange.com/questions/373447",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44637/"
] | Is it possible to disable the cropping step when adding a site icon via the Theme Customizer in WordPress 5+ (occurred to me in 5.5)?
For me cropping is unnecessary because I always upload a square image in the directions of the recommendations.
That's why this step is not helping me at all, instead is actually causing the following problems:
* It creates an unnecessary copy of the image with a `cropped` prefix.
* For the cropped image it creates a **NEW** attachment.
Thus all the settings I did for the attachment of the un-cropped image are lost and the filename of the site icon will always include this `cropped` prefix.
Is there anyway to fix this without patching the source of this problem? | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,563 | <p>I am updating an array saved in a users meta field using an ajax function.</p>
<p>The values added to the array are taken from the data-attributes within the tags which also act at the trigger to make the ajax call.</p>
<p>Whilst the function works 95% of the time, it can be a bit hit and miss whether the values save or not. I suspect this is because a user can fire these ajax calls too quickly and not give enough time for the original function call to save and update the meta field.</p>
<p>What would be the best method to ensure the ajax triggered function of updating the meta field value has been completed before allowing the function to run again?</p>
<p>Hope this makes sense - needless to say, please let me know if you need any more info.</p>
<p>Thanks in advance!!</p>
<p><strong>Sample HTML</strong></p>
<pre><code><div id="rjb_slots" class="slots">
<h5>Mon, 24th Aug 2020</h5>
<div class="slot">
<span class="time">10:30</span>
<a class="book" data-timestamp="1598265000" href="#"></a>
</div>
<div class="slot">
<span class="time">11:00</span>
<a class="booked" data-timestamp="1598266800" href="#"></a>
</div>
<div class="slot">
<span class="time">11:30</span>
<a class="booked" data-timestamp="1598268600" href="#"></a>
</div>
<div class="slot">
<span class="time">12:00</span>
<a class="book" data-timestamp="1598270400" href="#"></a>
</div>
<div class="slot">
<span class="time">12:30</span>
<a class="booked" data-timestamp="1598272200" href="#"></a>
</div>
<div class="slot">
<span class="time">13:00</span>
<a class="book" data-timestamp="1598274000" href="#"></a>
</div>
<div class="slot">
<span class="time">19:30</span>
<a class="book" data-timestamp="1598297400" href="#"></a>
</div>
</div>
</code></pre>
<p><strong>Ajax .js</strong></p>
<pre><code>$('.slot').on('click', 'a.book', function(e) {
e.preventDefault();
var user = $('#rjb_day').attr( 'data-user' );
var stamp = $(this).attr( 'data-timestamp' );
// console.log(bookCap);
$(this).removeClass('book').addClass('booked');
$.ajax({
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'rjb_make_diary_slots',
user: user,
stamp: stamp
},
success: function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
</code></pre>
<p><strong>Function that updates the user metafield</strong></p>
<pre><code>add_action( 'wp_ajax_rjb_make_diary_slots', 'rjb_make_diary_slots' );
function rjb_make_diary_slots() {
$user = $_POST['user'];
$stamp = array(
array(
'rjb_cal_day' => strtotime('today', $_POST['stamp']),
'rjb_cal_when' => $_POST['stamp'],
'rjb_cal_position_id' => '',
'rjb_cal_candidate_id' => ''
)
);
$calendar = get_user_meta( $user, 'rjb_cal', true);
$stamps = !empty($calendar) ? $calendar : array();
$new_stamp = array_merge($stamps, $stamp);
usort($new_stamp, function($a, $b) {
return $a['rjb_cal_when'] <=> $b['rjb_cal_when'];
});
update_user_meta( $user, 'rjb_cal', $new_stamp);
$log = print_r($stamp);
wp_die($log);
}
</code></pre>
<p><strong>Example of a value stored in the <code>rjb_cal</code> user meta field</strong></p>
<pre><code>array (
[0] => array (
[rjb_cal_day] => 1598227200
[rjb_cal_when] => 1598266800
[rjb_cal_position_id] =>
[rjb_cal_candidate_id] =>
)
[1] => array (
[rjb_cal_day] => 1598227200
[rjb_cal_when] => 1598268600
[rjb_cal_position_id] =>
[rjb_cal_candidate_id] =>
)
[2] => array (
[rjb_cal_day] => 1598227200
[rjb_cal_when] => 1598272200
[rjb_cal_position_id] =>
[rjb_cal_candidate_id] =>
)
)
</code></pre>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/23 | [
"https://wordpress.stackexchange.com/questions/373563",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57057/"
] | I am updating an array saved in a users meta field using an ajax function.
The values added to the array are taken from the data-attributes within the tags which also act at the trigger to make the ajax call.
Whilst the function works 95% of the time, it can be a bit hit and miss whether the values save or not. I suspect this is because a user can fire these ajax calls too quickly and not give enough time for the original function call to save and update the meta field.
What would be the best method to ensure the ajax triggered function of updating the meta field value has been completed before allowing the function to run again?
Hope this makes sense - needless to say, please let me know if you need any more info.
Thanks in advance!!
**Sample HTML**
```
<div id="rjb_slots" class="slots">
<h5>Mon, 24th Aug 2020</h5>
<div class="slot">
<span class="time">10:30</span>
<a class="book" data-timestamp="1598265000" href="#"></a>
</div>
<div class="slot">
<span class="time">11:00</span>
<a class="booked" data-timestamp="1598266800" href="#"></a>
</div>
<div class="slot">
<span class="time">11:30</span>
<a class="booked" data-timestamp="1598268600" href="#"></a>
</div>
<div class="slot">
<span class="time">12:00</span>
<a class="book" data-timestamp="1598270400" href="#"></a>
</div>
<div class="slot">
<span class="time">12:30</span>
<a class="booked" data-timestamp="1598272200" href="#"></a>
</div>
<div class="slot">
<span class="time">13:00</span>
<a class="book" data-timestamp="1598274000" href="#"></a>
</div>
<div class="slot">
<span class="time">19:30</span>
<a class="book" data-timestamp="1598297400" href="#"></a>
</div>
</div>
```
**Ajax .js**
```
$('.slot').on('click', 'a.book', function(e) {
e.preventDefault();
var user = $('#rjb_day').attr( 'data-user' );
var stamp = $(this).attr( 'data-timestamp' );
// console.log(bookCap);
$(this).removeClass('book').addClass('booked');
$.ajax({
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'rjb_make_diary_slots',
user: user,
stamp: stamp
},
success: function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
```
**Function that updates the user metafield**
```
add_action( 'wp_ajax_rjb_make_diary_slots', 'rjb_make_diary_slots' );
function rjb_make_diary_slots() {
$user = $_POST['user'];
$stamp = array(
array(
'rjb_cal_day' => strtotime('today', $_POST['stamp']),
'rjb_cal_when' => $_POST['stamp'],
'rjb_cal_position_id' => '',
'rjb_cal_candidate_id' => ''
)
);
$calendar = get_user_meta( $user, 'rjb_cal', true);
$stamps = !empty($calendar) ? $calendar : array();
$new_stamp = array_merge($stamps, $stamp);
usort($new_stamp, function($a, $b) {
return $a['rjb_cal_when'] <=> $b['rjb_cal_when'];
});
update_user_meta( $user, 'rjb_cal', $new_stamp);
$log = print_r($stamp);
wp_die($log);
}
```
**Example of a value stored in the `rjb_cal` user meta field**
```
array (
[0] => array (
[rjb_cal_day] => 1598227200
[rjb_cal_when] => 1598266800
[rjb_cal_position_id] =>
[rjb_cal_candidate_id] =>
)
[1] => array (
[rjb_cal_day] => 1598227200
[rjb_cal_when] => 1598268600
[rjb_cal_position_id] =>
[rjb_cal_candidate_id] =>
)
[2] => array (
[rjb_cal_day] => 1598227200
[rjb_cal_when] => 1598272200
[rjb_cal_position_id] =>
[rjb_cal_candidate_id] =>
)
)
``` | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,573 | <p>My local development WordPress install on ServerPress is not writing error logs. I made changes to my wp-config.php file to enable error log writing for WordPress, and also tried editing the php.ini file for xampplite to try and enable error tracking, But still, I could not get any logs going, so I reverted that to its original settings. My website currently displays</p>
<blockquote>
<p>There has been a critical error on your website.</p>
</blockquote>
<p>in the front-end. I added the following code before the <code>define( 'DB_NAME', 'blahblahblah');</code> configuration:</p>
<pre><code>/**Enable WP Debug */
define( 'WP_DEBUG', true );
/** Enable WP Debug Log */
define( 'WP_DEBUG_LOG', true );
/**Display debug on HTML page*/
define( 'WP_DEBUG_DISPLAY', false );
@ini_set('display_errors',0);
</code></pre>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/23 | [
"https://wordpress.stackexchange.com/questions/373573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121047/"
] | My local development WordPress install on ServerPress is not writing error logs. I made changes to my wp-config.php file to enable error log writing for WordPress, and also tried editing the php.ini file for xampplite to try and enable error tracking, But still, I could not get any logs going, so I reverted that to its original settings. My website currently displays
>
> There has been a critical error on your website.
>
>
>
in the front-end. I added the following code before the `define( 'DB_NAME', 'blahblahblah');` configuration:
```
/**Enable WP Debug */
define( 'WP_DEBUG', true );
/** Enable WP Debug Log */
define( 'WP_DEBUG_LOG', true );
/**Display debug on HTML page*/
define( 'WP_DEBUG_DISPLAY', false );
@ini_set('display_errors',0);
``` | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,599 | <p>I have two custom post types "Product" and "News".
I want to keep a description that describes each of these types and I want to display it under the custom post title inside a banner. Also the user should be able to change it from admin dashboard.
That means when I go to products page, there is a banner on top of the page and the title will be PRODUCTS and then product description should be displayed.</p>
<p>EX:</p>
<pre>
<h2><em>PRODUCTS</em></h2>
PRODUCTS DESCRIPTION
</pre>
<p>Now if I can add a meta box common to the product cpt which has an input field, I can display it on the web page. But I only know how to add meta boxes to each products under product type.</p>
<p>How do I solve this?</p>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/24 | [
"https://wordpress.stackexchange.com/questions/373599",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193585/"
] | I have two custom post types "Product" and "News".
I want to keep a description that describes each of these types and I want to display it under the custom post title inside a banner. Also the user should be able to change it from admin dashboard.
That means when I go to products page, there is a banner on top of the page and the title will be PRODUCTS and then product description should be displayed.
EX:
```
*PRODUCTS*
----------
PRODUCTS DESCRIPTION
```
Now if I can add a meta box common to the product cpt which has an input field, I can display it on the web page. But I only know how to add meta boxes to each products under product type.
How do I solve this? | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,614 | <p>I am looking for a SQL Query that can give the list of all categories created in WordPress Site along with it's category IDs. Please advise a query to get it as category/term relationship is quite complex in WordPress.</p>
<p>I got this but didn't work -</p>
<pre><code>SELECT ID,post_title FROM wp_posts INNER JOIN wp_term_relationships ON wp_term_relationships.object_id=wp_posts.ID INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id=wp_term_relationships.term_taxonomy_id INNER JOIN wp_terms ON wp_terms.term_id=wp_term_taxonomy.term_id WHERE name='category'
</code></pre>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/24 | [
"https://wordpress.stackexchange.com/questions/373614",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/188153/"
] | I am looking for a SQL Query that can give the list of all categories created in WordPress Site along with it's category IDs. Please advise a query to get it as category/term relationship is quite complex in WordPress.
I got this but didn't work -
```
SELECT ID,post_title FROM wp_posts INNER JOIN wp_term_relationships ON wp_term_relationships.object_id=wp_posts.ID INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id=wp_term_relationships.term_taxonomy_id INNER JOIN wp_terms ON wp_terms.term_id=wp_term_taxonomy.term_id WHERE name='category'
``` | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,667 | <p>In the WordPress customizer script, I am trying to pass the value from a select control into a custom control that displays taxonomies associated with the selected value (1st control).</p>
<pre><code>$wp_customize->add_control( new Tax_Dropdown_Control( $wp_customize, 'select_tax', array(
'section' => 'section_1',
'label' => __( 'Select Post Taxonomy', 'textdomain' ),
'description' => __( 'Select a taxonomy based on post type selected.', 'textdomain' ),
'dropdown_args' => array(
'post_type' => $wp_customize->get_setting("select_post_type"), // here I need to pass the first setting's value
),
) ) );
// custom controls related snippet
class Tax_Dropdown_Control extends WP_Customize_Control {
.....
$dropdown_args = wp_parse_args( $this->dropdown_args, array(
'post_type' => 'post',
) );
$dropdown_args['echo'] = false;
$taxonomies = get_object_taxonomies($dropdown_args);
if ($taxonomies) {
echo '<select>';
foreach ($taxonomies as $taxonomy ) {
echo '<option>'. $taxonomy. '</option>';
}
echo '</select>';
}
....
}
</code></pre>
<p>It would need to update the choices live when the select post type is changed. I'm not sure if maybe an <code>active_callback</code> can be used to recall the function with the updated variable?</p>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/24 | [
"https://wordpress.stackexchange.com/questions/373667",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24067/"
] | In the WordPress customizer script, I am trying to pass the value from a select control into a custom control that displays taxonomies associated with the selected value (1st control).
```
$wp_customize->add_control( new Tax_Dropdown_Control( $wp_customize, 'select_tax', array(
'section' => 'section_1',
'label' => __( 'Select Post Taxonomy', 'textdomain' ),
'description' => __( 'Select a taxonomy based on post type selected.', 'textdomain' ),
'dropdown_args' => array(
'post_type' => $wp_customize->get_setting("select_post_type"), // here I need to pass the first setting's value
),
) ) );
// custom controls related snippet
class Tax_Dropdown_Control extends WP_Customize_Control {
.....
$dropdown_args = wp_parse_args( $this->dropdown_args, array(
'post_type' => 'post',
) );
$dropdown_args['echo'] = false;
$taxonomies = get_object_taxonomies($dropdown_args);
if ($taxonomies) {
echo '<select>';
foreach ($taxonomies as $taxonomy ) {
echo '<option>'. $taxonomy. '</option>';
}
echo '</select>';
}
....
}
```
It would need to update the choices live when the select post type is changed. I'm not sure if maybe an `active_callback` can be used to recall the function with the updated variable? | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,729 | <p>Update:</p>
<p>I created a fresh new installation of WordPress, copied both Base and Base Child themes and activated Base Child. The Appearance/Customize gives the same white screen as described in point 1 below.</p>
<p>I then activated Base and the Appearance/Customize screen has the same error, which did not occur on the previous WP installation. This leads me to believe I have an issue with my customizer code. I WILL get to the bottom of this.</p>
<hr />
<p>I developed a custom theme, let's call it "Base", based on <a href="https://underscores.me/" rel="nofollow noreferrer">https://underscores.me/</a>, which is the boilerplate for several other child themes. The Base theme features several theme mods accessible via the theme customizer. I also created a child theme of Base, A.K.A. "Base Child", right now containing only the style.css file, which is copied below:</p>
<pre>
/*
Theme Name: Base Child
Template: base
Theme URI: https://blabla.com/
Author: Me
Author URI: https://blabla.com/
Description: Base Child
Version: 1.0.0
Text Domain: base-child
Tags: custom-background, custom-logo, custom-menu, featured-images, threaded-comments, translation-ready
*/
</pre>
<p>The only plugins installed are:</p>
<ol>
<li>ACF Photo Gallery Field</li>
<li>Advanced Custom Fields (the free version)</li>
<li>Simple Page Ordering</li>
</ol>
<p>Everything works fine when the Base theme is activated, meaning all custom post types are there, the theme customizer works perfectly, all shortcodes behave like they should etc.</p>
<p>Things can be very confusing from now on, so please be patient with me. As soon as I activate Base Child, weird things start to happen:</p>
<ol>
<li>If I go to Appearance/Customize, I get a screen showing only the "You are customizing Site Name" message and the page title is "Customizing: Loading..." forever. Nothing else works.</li>
<li>Related to point 1, a console inspection reveals this JS error on the page: <code>Uncaught SyntaxError: Unexpected token '<' on customize.php on line 5240</code>, and when looking at the page source, I'm finding what looks like a php error: <code>Warning: sprintf(): Too few arguments in C:\wamp64\www\base-boilerplate\wp-includes\theme.php on line <i>1027</i></code></li>
<li>Trying to replicate this issue with another theme, I installed Twenty Twenty and declared Base Child to be a child of Twenty Twenty in its <code>style.css</code>. I was amazed to see that all the custom post types created in Base were present in Base Child as a Twenty Twenty child. Going to Appearance/Customize, I get the same behavior as at point 1. It's as if Base Child was still a child of Base.</li>
<li>Clearing the browser cache has no effect on point 3.</li>
<li>Opening WP Admin in another browser not used before has no effect on point 3.</li>
<li>Activating Twenty Twenty and then activating Base Child (still as a child of Twenty Twenty) makes Base Child behave like a real child of Twenty Twenty. No more custom post types and Appearance/Customize works as expected. At this point, Base Child is activated.</li>
<li>Declared Base Child as a child of Base in its <code>style.css</code>. Went to the browser and it looks like Base Child is still a child of Twenty Twenty. No custom post types, no Appearance/Customize issues.</li>
<li>Activate Base, then activate Base Child as a child of Base: CPTs of Base appear, Appearance/Customize ceases to work as described in point 1.</li>
</ol>
<p>I'm baffled. Looked everywhere, tried everything, nothing helped. It seems WP has a cache of its own, database related perhaps, otherwise I can't explain why the CPTs remain when I switch themes. It has nothing to do with browser cache.</p>
<p>Please help.</p>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/25 | [
"https://wordpress.stackexchange.com/questions/373729",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193688/"
] | Update:
I created a fresh new installation of WordPress, copied both Base and Base Child themes and activated Base Child. The Appearance/Customize gives the same white screen as described in point 1 below.
I then activated Base and the Appearance/Customize screen has the same error, which did not occur on the previous WP installation. This leads me to believe I have an issue with my customizer code. I WILL get to the bottom of this.
---
I developed a custom theme, let's call it "Base", based on <https://underscores.me/>, which is the boilerplate for several other child themes. The Base theme features several theme mods accessible via the theme customizer. I also created a child theme of Base, A.K.A. "Base Child", right now containing only the style.css file, which is copied below:
```
/*
Theme Name: Base Child
Template: base
Theme URI: https://blabla.com/
Author: Me
Author URI: https://blabla.com/
Description: Base Child
Version: 1.0.0
Text Domain: base-child
Tags: custom-background, custom-logo, custom-menu, featured-images, threaded-comments, translation-ready
*/
```
The only plugins installed are:
1. ACF Photo Gallery Field
2. Advanced Custom Fields (the free version)
3. Simple Page Ordering
Everything works fine when the Base theme is activated, meaning all custom post types are there, the theme customizer works perfectly, all shortcodes behave like they should etc.
Things can be very confusing from now on, so please be patient with me. As soon as I activate Base Child, weird things start to happen:
1. If I go to Appearance/Customize, I get a screen showing only the "You are customizing Site Name" message and the page title is "Customizing: Loading..." forever. Nothing else works.
2. Related to point 1, a console inspection reveals this JS error on the page: `Uncaught SyntaxError: Unexpected token '<' on customize.php on line 5240`, and when looking at the page source, I'm finding what looks like a php error: `Warning: sprintf(): Too few arguments in C:\wamp64\www\base-boilerplate\wp-includes\theme.php on line <i>1027</i>`
3. Trying to replicate this issue with another theme, I installed Twenty Twenty and declared Base Child to be a child of Twenty Twenty in its `style.css`. I was amazed to see that all the custom post types created in Base were present in Base Child as a Twenty Twenty child. Going to Appearance/Customize, I get the same behavior as at point 1. It's as if Base Child was still a child of Base.
4. Clearing the browser cache has no effect on point 3.
5. Opening WP Admin in another browser not used before has no effect on point 3.
6. Activating Twenty Twenty and then activating Base Child (still as a child of Twenty Twenty) makes Base Child behave like a real child of Twenty Twenty. No more custom post types and Appearance/Customize works as expected. At this point, Base Child is activated.
7. Declared Base Child as a child of Base in its `style.css`. Went to the browser and it looks like Base Child is still a child of Twenty Twenty. No custom post types, no Appearance/Customize issues.
8. Activate Base, then activate Base Child as a child of Base: CPTs of Base appear, Appearance/Customize ceases to work as described in point 1.
I'm baffled. Looked everywhere, tried everything, nothing helped. It seems WP has a cache of its own, database related perhaps, otherwise I can't explain why the CPTs remain when I switch themes. It has nothing to do with browser cache.
Please help. | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,769 | <p>I am creating a plugin to send posts to an external program. But I get a problem by getting the posts.</p>
<p>I created the code below to get the posts and echo them. But if I run it, it goes to the empty error message. When I echo the response. It only gets 'Array'</p>
<p>If I just post <code>http://localhost/wordpress/wp-json/wp/v2/posts</code> in a browser, I get a JSON with my posts</p>
<p>What am I doing wrong?</p>
<pre><code>$remoteargs = array(
'timeout' => 20,
'redirection' => 5,
'httpversion' => '1.1',
'blocking' => false,
'headers' => array(),
'cookies' => array(),
'sslverify' => false,
);
$response = wp_remote_get( 'http://localhost/wordpress/wp-json/wp/v2/posts', $remoteargs );
// Exit if error.
if ( is_wp_error( $response ) ) {
echo $response->get_error_message();
return;
}
// Get the body.
$posts = json_decode( wp_remote_retrieve_body( $response ) );
// Exit if nothing is returned.
if ( empty( $posts ) ) {
echo 'emptyerror';
return;
}
foreach ( $posts as $post ) {
echo $post;
}**
</code></pre>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/26 | [
"https://wordpress.stackexchange.com/questions/373769",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193728/"
] | I am creating a plugin to send posts to an external program. But I get a problem by getting the posts.
I created the code below to get the posts and echo them. But if I run it, it goes to the empty error message. When I echo the response. It only gets 'Array'
If I just post `http://localhost/wordpress/wp-json/wp/v2/posts` in a browser, I get a JSON with my posts
What am I doing wrong?
```
$remoteargs = array(
'timeout' => 20,
'redirection' => 5,
'httpversion' => '1.1',
'blocking' => false,
'headers' => array(),
'cookies' => array(),
'sslverify' => false,
);
$response = wp_remote_get( 'http://localhost/wordpress/wp-json/wp/v2/posts', $remoteargs );
// Exit if error.
if ( is_wp_error( $response ) ) {
echo $response->get_error_message();
return;
}
// Get the body.
$posts = json_decode( wp_remote_retrieve_body( $response ) );
// Exit if nothing is returned.
if ( empty( $posts ) ) {
echo 'emptyerror';
return;
}
foreach ( $posts as $post ) {
echo $post;
}**
``` | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,771 | <p>So I've been integrating WooCommerce with Stripe checkout and set everything up correctly, but when it comes to paying I get this response after hitting 'Place Order':</p>
<pre><code>No such customer: 'cus_Hu9exn9bPLd3SA'; a similar object exists in test mode, but a live mode key was used to make this request.
</code></pre>
<p>I've set the test mode keys (and client ID) correctly in the backend - set woocommerce to 'enable test mode'. Everything seems ok. When viewing stripe test mode it creates the customer correctly as well, but its almost as if its 'redirecting' or 'reporting' back a live mode key or something?</p>
<p>Manually checked the source and definitely test mode keys there (its obviously working as its creating the customer in test mode as well). Looking at the webhook attempts it does this:
<a href="https://i.stack.imgur.com/jgxBo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jgxBo.png" alt="stripe webhook rows" /></a></p>
<p>So thats obviously working. But when it comes to 'charging' it seems to fail. In WooCommerce orders it shows 'pending payment'.`</p>
<p>Any help appreciated :?</p>
<p>Thanks</p>
<p>Nick</p>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/26 | [
"https://wordpress.stackexchange.com/questions/373771",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193731/"
] | So I've been integrating WooCommerce with Stripe checkout and set everything up correctly, but when it comes to paying I get this response after hitting 'Place Order':
```
No such customer: 'cus_Hu9exn9bPLd3SA'; a similar object exists in test mode, but a live mode key was used to make this request.
```
I've set the test mode keys (and client ID) correctly in the backend - set woocommerce to 'enable test mode'. Everything seems ok. When viewing stripe test mode it creates the customer correctly as well, but its almost as if its 'redirecting' or 'reporting' back a live mode key or something?
Manually checked the source and definitely test mode keys there (its obviously working as its creating the customer in test mode as well). Looking at the webhook attempts it does this:
[](https://i.stack.imgur.com/jgxBo.png)
So thats obviously working. But when it comes to 'charging' it seems to fail. In WooCommerce orders it shows 'pending payment'.`
Any help appreciated :?
Thanks
Nick | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,777 | <p>I have an input field and when users enter any text then that will check the category name is available or not which user entered.</p>
<p><strong>Js</strong></p>
<pre><code>(function($) { // ready handler
$(".universalSearchField").keypress(function() {
$.ajax({
url: "/wp-admin/admin-ajax.php",
type: "post",
data: { action: "universalSearchlist", keyword: $("#searchdata").val() },
success: function(data) {
console.log(data);
// $("#datafetch").html( data );
}
});
});
})(jQuery);
</code></pre>
<p>Function.php</p>
<pre><code> add_action('wp_ajax_universalSearchlist','universalSearch');
add_action('wp_ajax_nopriv_universalSearchlist','universalSearch');
function universalSearch(){
$the_query = new WP_Query( array('category_name' => esc_attr( $_POST['universalSearchlist'] ), 'post_type' => 'post' ) );
foreach ( $the_query->posts as $p ) {
$categories = get_the_category($p->ID);
if (!empty($categories) ) {
echo esc_html( $categories[0]->name );
}
}
}
</code></pre>
<p>I am getting all the categories and I want when the user starts to enter the text box then start checking the category name is available or not.</p>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/26 | [
"https://wordpress.stackexchange.com/questions/373777",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/177715/"
] | I have an input field and when users enter any text then that will check the category name is available or not which user entered.
**Js**
```
(function($) { // ready handler
$(".universalSearchField").keypress(function() {
$.ajax({
url: "/wp-admin/admin-ajax.php",
type: "post",
data: { action: "universalSearchlist", keyword: $("#searchdata").val() },
success: function(data) {
console.log(data);
// $("#datafetch").html( data );
}
});
});
})(jQuery);
```
Function.php
```
add_action('wp_ajax_universalSearchlist','universalSearch');
add_action('wp_ajax_nopriv_universalSearchlist','universalSearch');
function universalSearch(){
$the_query = new WP_Query( array('category_name' => esc_attr( $_POST['universalSearchlist'] ), 'post_type' => 'post' ) );
foreach ( $the_query->posts as $p ) {
$categories = get_the_category($p->ID);
if (!empty($categories) ) {
echo esc_html( $categories[0]->name );
}
}
}
```
I am getting all the categories and I want when the user starts to enter the text box then start checking the category name is available or not. | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,808 | <p>I try to create blog page with specific categories (by ID) and display only newest blog post from this category.
I have code like this but it shows only first category. I have work code for display only one category but when I put more id it doesn't work</p>
<pre><code><?php
/**
* Template Name: Porftfolio
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'cat' => '187,186',
'posts_per_page' => 1,
);
$arr_posts = new WP_Query( $args );
if ( $arr_posts->have_posts() ) :
while ( $arr_posts->have_posts() ) :
$arr_posts->the_post();
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
if ( has_post_thumbnail() ) :
the_post_thumbnail();
endif;
?>
<header class="entry-header">
<h1 class="entry-title"><?php the_title(); ?></h1>
</header>
<div class="entry-content">
<a href> <?php the_permalink(); ?> </a>
</div>
</article>
<?php
endwhile;
endif;
?>
</main><!-- .site-main -->
</div><!-- .content-area -->
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/26 | [
"https://wordpress.stackexchange.com/questions/373808",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193750/"
] | I try to create blog page with specific categories (by ID) and display only newest blog post from this category.
I have code like this but it shows only first category. I have work code for display only one category but when I put more id it doesn't work
```
<?php
/**
* Template Name: Porftfolio
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'cat' => '187,186',
'posts_per_page' => 1,
);
$arr_posts = new WP_Query( $args );
if ( $arr_posts->have_posts() ) :
while ( $arr_posts->have_posts() ) :
$arr_posts->the_post();
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
if ( has_post_thumbnail() ) :
the_post_thumbnail();
endif;
?>
<header class="entry-header">
<h1 class="entry-title"><?php the_title(); ?></h1>
</header>
<div class="entry-content">
<a href> <?php the_permalink(); ?> </a>
</div>
</article>
<?php
endwhile;
endif;
?>
</main><!-- .site-main -->
</div><!-- .content-area -->
<?php get_footer(); ?>
``` | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,847 | <p>Based on <a href="https://stackoverflow.com/questions/50183646/check-the-first-login-wordpress">this</a> answer i created a small functionality for users that are logging in for <em>the first 3 times</em> to make some elements classes use css animation. What i am trying to do is to adjust this code to count and control the first 3 times of <strong>all user roles</strong> except <strong>subscribers</strong>.</p>
<p>Basically i need this functionality to start counting the first login by user role. Lets say the first time a contributor login, or an editor, or better <strong>all user roles</strong> except <strong>subscribers</strong></p>
<p>Here is my code so far</p>
<pre><code>add_action( 'wp_login', 'track_user_logins', 10, 2 );
function track_user_logins( $user_login, $user ){
if( $login_amount = get_user_meta( $user->id, 'login_amount', true ) ){
// They've Logged In Before, increment existing total by 1
update_user_meta( $user->id, 'login_amount', ++$login_amount );
} else {
// First Login, set it to 1
update_user_meta( $user->id, 'login_amount', 1 );
}
}
add_action('wp_head', 'notificationcss');
function notificationcss{
if ( !current_user_can('subscriber') ) {
// Get current total amount of logins (should be at least 1)
$login_amount = get_user_meta( get_current_user_id(), 'login_amount', true );
// return content based on how many times they've logged in.
if( $login_amount <= 3 ){
echo '<style>.create-post {animation: pulse-blue 2s 7;} .bb-header-icon.logged-in-user.element-toggle.only-mobile img{animation: pulse-red 2s 7;} </style>';
} else {
echo '<style>.create-post {animation: none;} .bb-header-icon.logged-in-user.element-toggle.only-mobile img{animation: none;} </style>';
}
}
}
</code></pre>
<p>How could i manipulate the <em>track_user_logins</em> function to count the login times for all roles except subscribers. The existing function counts all users.</p>
<p><em>Example: A user is registered in the site for the first time with role <em>Subscriber</em>. After some login times(lets say 7-8), his role is being changes to <em>Contributor</em>. From that first time logged in as a Contributor the <em>track_user_logins</em> should start counting.</em></p>
<p>Any ideas would be gladly appreciated.</p>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/27 | [
"https://wordpress.stackexchange.com/questions/373847",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129972/"
] | Based on [this](https://stackoverflow.com/questions/50183646/check-the-first-login-wordpress) answer i created a small functionality for users that are logging in for *the first 3 times* to make some elements classes use css animation. What i am trying to do is to adjust this code to count and control the first 3 times of **all user roles** except **subscribers**.
Basically i need this functionality to start counting the first login by user role. Lets say the first time a contributor login, or an editor, or better **all user roles** except **subscribers**
Here is my code so far
```
add_action( 'wp_login', 'track_user_logins', 10, 2 );
function track_user_logins( $user_login, $user ){
if( $login_amount = get_user_meta( $user->id, 'login_amount', true ) ){
// They've Logged In Before, increment existing total by 1
update_user_meta( $user->id, 'login_amount', ++$login_amount );
} else {
// First Login, set it to 1
update_user_meta( $user->id, 'login_amount', 1 );
}
}
add_action('wp_head', 'notificationcss');
function notificationcss{
if ( !current_user_can('subscriber') ) {
// Get current total amount of logins (should be at least 1)
$login_amount = get_user_meta( get_current_user_id(), 'login_amount', true );
// return content based on how many times they've logged in.
if( $login_amount <= 3 ){
echo '<style>.create-post {animation: pulse-blue 2s 7;} .bb-header-icon.logged-in-user.element-toggle.only-mobile img{animation: pulse-red 2s 7;} </style>';
} else {
echo '<style>.create-post {animation: none;} .bb-header-icon.logged-in-user.element-toggle.only-mobile img{animation: none;} </style>';
}
}
}
```
How could i manipulate the *track\_user\_logins* function to count the login times for all roles except subscribers. The existing function counts all users.
*Example: A user is registered in the site for the first time with role *Subscriber*. After some login times(lets say 7-8), his role is being changes to *Contributor*. From that first time logged in as a Contributor the *track\_user\_logins* should start counting.*
Any ideas would be gladly appreciated. | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |
373,880 | <p>Hello WP DEV Community,</p>
<p>I understand this question has been asked ad nauseam...</p>
<p>I'm trying to customize a development workflow (WordPress + WooCommerce) that allows me to develop locally (to speed up development, see changes instantly in browser) -- then push to PROD.</p>
<p>After reading many StackExchange posts/articles/forums, this does not appear to be a trivial task.</p>
<p>I am hoping to gain some insights with the following question that will help me with the above goal. I am primarily trying to understand the specifics below (not necessarily how to go about designing the
actual workflow). I have a few models already in mind. Understanding these details will assist in how I tailor my workflow -- along with some other things I hope to accomplish.</p>
<ul>
<li>Admin Panel:</li>
</ul>
<p>Making WP config changes updates entries in the database only?</p>
<ul>
<li>Flatsome theme with UX Builder:</li>
</ul>
<p>Making changes here appears to touch both the theme flat-files and the database (if you create new pages)?</p>
<ul>
<li>WooCommerce:</li>
</ul>
<p>It appears that WooCommerce uses the WP DB/Tables (and not strictly it's own tables)?</p>
<p>"Products are a type of 'post,' meaning that you can migrate products between sites the same way you migrate posts. Products are stored in the database within the 'wp_posts' table, with meta data inside wp_postmeta."</p>
<p>I suspect that all customer accounts, comments etc are stored in the database as well (no flat-files are touched)?</p>
<p>The DB is live (constantly evolving) with updates by customers: new accounts, account changes, comments, orders etc.</p>
<p>There does not appear to be a clear (table-level) separation between WP core, Themes and WooCommerce?</p>
<p>Given the above, is it possible to export specific (non WooCommcerce) tables from the PROD DB and import to the DEV DB > make theme-level/WP changes > push flat-files/import specific tables back to PROD without without destroying anything in PROD?</p>
<p>Thanks!</p>
| [
{
"answer_id": 373443,
"author": "Suresh Shinde",
"author_id": 167466,
"author_profile": "https://wordpress.stackexchange.com/users/167466",
"pm_score": -1,
"selected": false,
"text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a hr... | 2020/08/27 | [
"https://wordpress.stackexchange.com/questions/373880",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/193719/"
] | Hello WP DEV Community,
I understand this question has been asked ad nauseam...
I'm trying to customize a development workflow (WordPress + WooCommerce) that allows me to develop locally (to speed up development, see changes instantly in browser) -- then push to PROD.
After reading many StackExchange posts/articles/forums, this does not appear to be a trivial task.
I am hoping to gain some insights with the following question that will help me with the above goal. I am primarily trying to understand the specifics below (not necessarily how to go about designing the
actual workflow). I have a few models already in mind. Understanding these details will assist in how I tailor my workflow -- along with some other things I hope to accomplish.
* Admin Panel:
Making WP config changes updates entries in the database only?
* Flatsome theme with UX Builder:
Making changes here appears to touch both the theme flat-files and the database (if you create new pages)?
* WooCommerce:
It appears that WooCommerce uses the WP DB/Tables (and not strictly it's own tables)?
"Products are a type of 'post,' meaning that you can migrate products between sites the same way you migrate posts. Products are stored in the database within the 'wp\_posts' table, with meta data inside wp\_postmeta."
I suspect that all customer accounts, comments etc are stored in the database as well (no flat-files are touched)?
The DB is live (constantly evolving) with updates by customers: new accounts, account changes, comments, orders etc.
There does not appear to be a clear (table-level) separation between WP core, Themes and WooCommerce?
Given the above, is it possible to export specific (non WooCommcerce) tables from the PROD DB and import to the DEV DB > make theme-level/WP changes > push flat-files/import specific tables back to PROD without without destroying anything in PROD?
Thanks! | I've written my own solution, sharing it and hoping it will help someone.
Add this to your `functions.php`:
```
<?php
add_action('parse_request', 'redirect_postid_to_postname');
function redirect_postid_to_postname($wp)
{
// If /%post_id%/
if (is_numeric($wp->request)) {
$post_id = $wp->request;
$slug = get_post_field( 'post_name', $post_id );
// If the post slug === the post number, prevent redirection loops.
if ($slug !== $post_id) {
// Adding url parameters manually to $redirect_to
$parameters = $_SERVER[QUERY_STRING];
$redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : "");
// Prevent loops
if($redirect_from !== $redirect_to) {
wp_redirect($redirect_to, 301);
exit;
}
}
}
}
``` |