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
|
---|---|---|---|---|---|---|
320,377 | <p>I want to run my own JavaScript on a specific WordPress page but only after a third party's plugin runs as I am trying to slightly modify that plugin. My problem is that my JavaScript is running before, not after, the plugin's script. Is my mistake in how I am referring to the plugin's script (i.e. the dependent script) in the $deps array?</p>
<pre><code><?php
// What was originally in the child theme’s function.php file
add_action( 'wp_enqueue_scripts', 'you_enqueue_styles' );
function you_enqueue_styles()
{
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
// Added by me to the child theme’s function.php file
function load_new_js() {
if( is_page( 692 ) ) {
wp_enqueue_script('modify_plugin_js', 'https://www.example.com/mycustomscript.js', array('greetingnow', 'jquery'), '',false);
}
}
// Should I even bother putting in a priority of 100 to try and force this to be run last?
add_action('wp_enqueue_scripts', 'load_new_js', 100);
</code></pre>
<p>This is what the script in the HTML looks like:</p>
<pre><code><html>
<body>
<script>
<!-- This is the dependent code that should run first and is put directly into the HTML file by the third party Plugin provider -->
var greetingnow = "Good Morning!";
alert(greetingnow);
</script>
</body>
</html>
</code></pre>
| [
{
"answer_id": 320384,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": -1,
"selected": true,
"text": "<p>Try this...</p>\n\n<pre><code>function load_new_js() {\n if( is_page( 692 ) ) {\n wp_enqueue_script(\n 'modify_plugin_js',\n get_stylesheet_directory_uri() . '/mycustomscript.js',\n array('jquery','greetingnow')\n );\n\n }\n}\n</code></pre>\n\n<p>If that doesn't work, what plugin are you using?</p>\n"
},
{
"answer_id": 320402,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\"><code>wp_add_inline_script()</code></a>. It lets you add and inline script that's dependent on an enqueued script:</p>\n\n<pre><code>function wpse_320377_register_scripts() {\n wp_register_script( 'my-script-handle', 'https://www.example.com/mycustomscript.js', [ 'jquery' ], '', true );\n wp_add_inline_script( 'my-script-handle', 'var greetingnow = \"Good Morning!\"; alert(greetingnow);', 'before' );\n\n if ( is_page( 692 ) ) {\n wp_enqueue_script( 'my-script-handle' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_320377_register_scripts' );\n</code></pre>\n\n<p>In that example, it registers a custom script, <code>my-script-handle</code>, and then attaches the inline script to it using <code>wp_add_inline_script()</code> so that whenever <code>my-script-handle</code> is enqueued, the inline script will be output right before it. The result will look something like this:</p>\n\n<pre><code><script>\n var greetingnow = \"Good Morning!\"; alert(greetingnow);\n</script>\n<script type=\"text/javascript\" src=\"https://www.example.com/mycustomscript.js\"></script>\n</code></pre>\n"
}
]
| 2018/11/27 | [
"https://wordpress.stackexchange.com/questions/320377",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154831/"
]
| I want to run my own JavaScript on a specific WordPress page but only after a third party's plugin runs as I am trying to slightly modify that plugin. My problem is that my JavaScript is running before, not after, the plugin's script. Is my mistake in how I am referring to the plugin's script (i.e. the dependent script) in the $deps array?
```
<?php
// What was originally in the child theme’s function.php file
add_action( 'wp_enqueue_scripts', 'you_enqueue_styles' );
function you_enqueue_styles()
{
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
// Added by me to the child theme’s function.php file
function load_new_js() {
if( is_page( 692 ) ) {
wp_enqueue_script('modify_plugin_js', 'https://www.example.com/mycustomscript.js', array('greetingnow', 'jquery'), '',false);
}
}
// Should I even bother putting in a priority of 100 to try and force this to be run last?
add_action('wp_enqueue_scripts', 'load_new_js', 100);
```
This is what the script in the HTML looks like:
```
<html>
<body>
<script>
<!-- This is the dependent code that should run first and is put directly into the HTML file by the third party Plugin provider -->
var greetingnow = "Good Morning!";
alert(greetingnow);
</script>
</body>
</html>
``` | Try this...
```
function load_new_js() {
if( is_page( 692 ) ) {
wp_enqueue_script(
'modify_plugin_js',
get_stylesheet_directory_uri() . '/mycustomscript.js',
array('jquery','greetingnow')
);
}
}
```
If that doesn't work, what plugin are you using? |
320,417 | <p>Im using wp_insert_post to add products on the front end of a woocommerces site</p>
<p>My current code will upload all the images but only the last image will be in the product gallery images</p>
<p>heres my code;</p>
<p>functions.php</p>
<pre><code>function my_handle_attachment( $file_handler, $post_id, $set_thu=false) {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ( is_numeric( $attach_id ) ) {
update_post_meta( $post_id, '_product_image_gallery', $attach_id );
}
return $attach_id;
}
</code></pre>
<p>frontend</p>
<pre><code>if ( $_FILES ) {
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = my_handle_attachment($file,$post_id);
update_post_meta($post_id, array_push($post_id, '_product_image_gallery',$newupload));
}
}
}
}
<input type="file" name="upload_attachment[]" multiple="multiple" />
</code></pre>
<p>Is anything wrong in this code ?</p>
| [
{
"answer_id": 320384,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": -1,
"selected": true,
"text": "<p>Try this...</p>\n\n<pre><code>function load_new_js() {\n if( is_page( 692 ) ) {\n wp_enqueue_script(\n 'modify_plugin_js',\n get_stylesheet_directory_uri() . '/mycustomscript.js',\n array('jquery','greetingnow')\n );\n\n }\n}\n</code></pre>\n\n<p>If that doesn't work, what plugin are you using?</p>\n"
},
{
"answer_id": 320402,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\"><code>wp_add_inline_script()</code></a>. It lets you add and inline script that's dependent on an enqueued script:</p>\n\n<pre><code>function wpse_320377_register_scripts() {\n wp_register_script( 'my-script-handle', 'https://www.example.com/mycustomscript.js', [ 'jquery' ], '', true );\n wp_add_inline_script( 'my-script-handle', 'var greetingnow = \"Good Morning!\"; alert(greetingnow);', 'before' );\n\n if ( is_page( 692 ) ) {\n wp_enqueue_script( 'my-script-handle' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_320377_register_scripts' );\n</code></pre>\n\n<p>In that example, it registers a custom script, <code>my-script-handle</code>, and then attaches the inline script to it using <code>wp_add_inline_script()</code> so that whenever <code>my-script-handle</code> is enqueued, the inline script will be output right before it. The result will look something like this:</p>\n\n<pre><code><script>\n var greetingnow = \"Good Morning!\"; alert(greetingnow);\n</script>\n<script type=\"text/javascript\" src=\"https://www.example.com/mycustomscript.js\"></script>\n</code></pre>\n"
}
]
| 2018/11/28 | [
"https://wordpress.stackexchange.com/questions/320417",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140870/"
]
| Im using wp\_insert\_post to add products on the front end of a woocommerces site
My current code will upload all the images but only the last image will be in the product gallery images
heres my code;
functions.php
```
function my_handle_attachment( $file_handler, $post_id, $set_thu=false) {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ( is_numeric( $attach_id ) ) {
update_post_meta( $post_id, '_product_image_gallery', $attach_id );
}
return $attach_id;
}
```
frontend
```
if ( $_FILES ) {
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = my_handle_attachment($file,$post_id);
update_post_meta($post_id, array_push($post_id, '_product_image_gallery',$newupload));
}
}
}
}
<input type="file" name="upload_attachment[]" multiple="multiple" />
```
Is anything wrong in this code ? | Try this...
```
function load_new_js() {
if( is_page( 692 ) ) {
wp_enqueue_script(
'modify_plugin_js',
get_stylesheet_directory_uri() . '/mycustomscript.js',
array('jquery','greetingnow')
);
}
}
```
If that doesn't work, what plugin are you using? |
320,448 | <p>I am wondering if the below logic is correct and if certain circumstances should be present for it to work, since in some cases it does not seem to be working. </p>
<p>The example below is quite simple. Let's say that I want to use a function, that is defined elsewhere in a theme-related file, let's say <code>parent_theme_hooks.php</code>, through an action hook in my child-theme <code>functions.php</code>.</p>
<p><strong>parent_theme_hooks.php</strong></p>
<pre><code>function is_enabled(){
return true;
}
function check_if_enabled(){
do_action( 'my_hook', $some, $args );
}
</code></pre>
<p>Then in the child-theme <strong>functions.php</strong></p>
<pre><code>function my_function($some, $args) {
if ( is_enabled() ) {
$message = 'yes';
} else {
$message = 'no';
}
echo $message;
}
add_action( 'my_hook', 'my_function', 11, 2 );
</code></pre>
<p><strong>Question</strong>
So my question is if I can use the function <code>is_enabled()</code> in the child-theme <code>functions.php</code> when it is defined elsewhere in the parent theme?</p>
<p>Thanks</p>
| [
{
"answer_id": 320384,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": -1,
"selected": true,
"text": "<p>Try this...</p>\n\n<pre><code>function load_new_js() {\n if( is_page( 692 ) ) {\n wp_enqueue_script(\n 'modify_plugin_js',\n get_stylesheet_directory_uri() . '/mycustomscript.js',\n array('jquery','greetingnow')\n );\n\n }\n}\n</code></pre>\n\n<p>If that doesn't work, what plugin are you using?</p>\n"
},
{
"answer_id": 320402,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/wp_add_inline_script/\" rel=\"nofollow noreferrer\"><code>wp_add_inline_script()</code></a>. It lets you add and inline script that's dependent on an enqueued script:</p>\n\n<pre><code>function wpse_320377_register_scripts() {\n wp_register_script( 'my-script-handle', 'https://www.example.com/mycustomscript.js', [ 'jquery' ], '', true );\n wp_add_inline_script( 'my-script-handle', 'var greetingnow = \"Good Morning!\"; alert(greetingnow);', 'before' );\n\n if ( is_page( 692 ) ) {\n wp_enqueue_script( 'my-script-handle' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpse_320377_register_scripts' );\n</code></pre>\n\n<p>In that example, it registers a custom script, <code>my-script-handle</code>, and then attaches the inline script to it using <code>wp_add_inline_script()</code> so that whenever <code>my-script-handle</code> is enqueued, the inline script will be output right before it. The result will look something like this:</p>\n\n<pre><code><script>\n var greetingnow = \"Good Morning!\"; alert(greetingnow);\n</script>\n<script type=\"text/javascript\" src=\"https://www.example.com/mycustomscript.js\"></script>\n</code></pre>\n"
}
]
| 2018/11/28 | [
"https://wordpress.stackexchange.com/questions/320448",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124244/"
]
| I am wondering if the below logic is correct and if certain circumstances should be present for it to work, since in some cases it does not seem to be working.
The example below is quite simple. Let's say that I want to use a function, that is defined elsewhere in a theme-related file, let's say `parent_theme_hooks.php`, through an action hook in my child-theme `functions.php`.
**parent\_theme\_hooks.php**
```
function is_enabled(){
return true;
}
function check_if_enabled(){
do_action( 'my_hook', $some, $args );
}
```
Then in the child-theme **functions.php**
```
function my_function($some, $args) {
if ( is_enabled() ) {
$message = 'yes';
} else {
$message = 'no';
}
echo $message;
}
add_action( 'my_hook', 'my_function', 11, 2 );
```
**Question**
So my question is if I can use the function `is_enabled()` in the child-theme `functions.php` when it is defined elsewhere in the parent theme?
Thanks | Try this...
```
function load_new_js() {
if( is_page( 692 ) ) {
wp_enqueue_script(
'modify_plugin_js',
get_stylesheet_directory_uri() . '/mycustomscript.js',
array('jquery','greetingnow')
);
}
}
```
If that doesn't work, what plugin are you using? |
320,497 | <p>Within a single post I show all tags of the specific post by using this:</p>
<pre><code>the_tags( $tags_opening, ' ', $tags_ending );
</code></pre>
<p>But sometimes I mark a post with a tag that should not appear on that single page (but this tag shall still be found on - for example - an overview page with all tags).</p>
<p>How can I exclude specific tags by ID from this list of tags within the post (and just on the single page)?</p>
| [
{
"answer_id": 320506,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a> to get the terms of the <code>post_tag</code> taxonomy according to your needs. It offers parameters to achieve this, especially <code>exclude</code> or <code>exclude_tree</code>. All available parameters are documented at <a href=\"https://developer.wordpress.org/reference/classes/wp_term_query/__construct/#parameters\" rel=\"nofollow noreferrer\"><code>WP_Term_Query::__construct()</code></a>.</p>\n\n<p>Then you basically recreate what <code>the_tags()</code> does in a custom function. To elaborate a bit, <code>the_tags()</code> calls <a href=\"https://developer.wordpress.org/reference/functions/get_the_tag_list/\" rel=\"nofollow noreferrer\"><code>get_the_tag_list()</code></a> which calls <a href=\"https://developer.wordpress.org/reference/functions/get_the_term_list/\" rel=\"nofollow noreferrer\"><code>get_the_term_list()</code></a>. If you take a look at the documentation, source code you can easily create the same markup.</p>\n\n<p>Generally speaking it might be worth considering a different approach, for example using a custom taxonomy to collect those terms you want to show on overview pages but not on single pages.</p>\n"
},
{
"answer_id": 320511,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure that this is the best decision, but you can use the filter to cut your special tag without modifying templates.</p>\n\n<pre><code>add_filter('the_tags', 'wpse_320497_the_tags');\n\nfunction wpse_320497_the_tags($tags) {\n $exclude_tag = 'word';\n\n // You can add your own conditions here\n // For example, exclude specific tag only for posts or custom taxonomy\n if(!is_admin() && is_singular()) {\n $tags = preg_replace(\"~,\\s+<a[^>]+>{$exclude_tag}</a>~is\", \"\", $tags);\n }\n\n return $tags;\n});\n</code></pre>\n\n<p>If you confused with regexp, you can rewrite it with <code>explode</code> and <code>strpos</code> functions.</p>\n\n<p>Hope it helps.</p>\n"
}
]
| 2018/11/28 | [
"https://wordpress.stackexchange.com/questions/320497",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| Within a single post I show all tags of the specific post by using this:
```
the_tags( $tags_opening, ' ', $tags_ending );
```
But sometimes I mark a post with a tag that should not appear on that single page (but this tag shall still be found on - for example - an overview page with all tags).
How can I exclude specific tags by ID from this list of tags within the post (and just on the single page)? | Not sure that this is the best decision, but you can use the filter to cut your special tag without modifying templates.
```
add_filter('the_tags', 'wpse_320497_the_tags');
function wpse_320497_the_tags($tags) {
$exclude_tag = 'word';
// You can add your own conditions here
// For example, exclude specific tag only for posts or custom taxonomy
if(!is_admin() && is_singular()) {
$tags = preg_replace("~,\s+<a[^>]+>{$exclude_tag}</a>~is", "", $tags);
}
return $tags;
});
```
If you confused with regexp, you can rewrite it with `explode` and `strpos` functions.
Hope it helps. |
320,505 | <p>I have this function...</p>
<pre><code>$user = wp_get_current_user();
if (( in_category('Locked') ) && in_array( 'subscriber', (array) $user->roles ) ) {
/* Is subscriber, is in category Locked, has amount of posts */
echo do_shortcode('[shortcode_name]');
} else if (( in_category('Locked') ) && in_array( 'subscriber', (array) $user->roles ) ) {
/* Is subscriber, is in category Locked, has NO amount of posts */
echo '<div id="locked">
You are subscriber without number of posts!
</div>';
} else if ( in_category('Locked') ) {
/* Is NOT subscriber, is in category Locked, has NO amount of posts */
echo '<div id="locked">
Login or register pal!
</div>';
} else {
/* Is NOT subscriber, is NOT in category Locked, has NO amount of posts */
echo do_shortcode('[shortcode_name]');
}
</code></pre>
<p>I need to apply "has amount of posts" or "check if user is author of numebr of posts" on first part of code...</p>
<pre><code>if (( in_category('Locked') ) && in_array( 'subscriber', (array) $user->roles ) ) && ?????
</code></pre>
<p>If this way can't work, I would have one more possible solution, it is to auto move user from subscriber to contributor once subscriber posted number of posts, but this first solution would be better.</p>
| [
{
"answer_id": 320507,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>I guess <a href=\"https://codex.wordpress.org/Function_Reference/count_user_posts\" rel=\"nofollow noreferrer\"><code>count_user_posts</code></a> is what you're looking for ;)</p>\n\n<p>This is how you use it:</p>\n\n<pre><code>$user_post_count = count_user_posts( $userid , $post_type );\n</code></pre>\n\n<p>And it returns the number of published posts the user has written in this post type.</p>\n\n<p>PS. And if you want some more advanced count, <a href=\"https://codex.wordpress.org/Function_Reference/get_posts_by_author_sql\" rel=\"nofollow noreferrer\"><code>get_posts_by_author_sql</code></a> can come quite handy.</p>\n"
},
{
"answer_id": 320509,
"author": "MLL",
"author_id": 113798,
"author_profile": "https://wordpress.stackexchange.com/users/113798",
"pm_score": 1,
"selected": false,
"text": "<p>Guy above answered correctly, but for anyone needing this further, I will add full code as response too...</p>\n\n<pre><code>$user = wp_get_current_user();\n$user_ID = get_current_user_id();\n$user_post_count = count_user_posts( $user_ID );\n$my_post_meta = get_post_meta($post->ID, 'shortcode_name', true);\n\n\nif (( in_category('Locked') ) && in_array( 'subscriber', (array) $user->roles ) && $user_post_count == 5 ) {\n /* Is subscriber, is in category Locked, has amount of posts */\n echo do_shortcode('[shortcode_name]');\n\n} else if (( in_category('Locked') ) && in_array( 'subscriber', (array) $user->roles ) ) {\n /* Is subscriber, is in category Locked, has NO amount of posts */\n echo '<div id=\"locked\">\nYou are subscriber without number of posts!\n</div>';\n} else if (( in_category('Locked') ) && in_array( 'administrator', (array) $user->roles ) ) {\n /* Is subscriber, is in category Locked, has power */\necho do_shortcode('[shortcode_name]'); \n\n} else if ( in_category('Locked') ) {\n /* Is NOT subscriber, is in category Locked, has NO amount of posts */\n echo '<div id=\"locked\">\nLogin or register pal!\n</div>';\n\n} else if ( ! empty ( $my_post_meta ) ) { \n /* Post meta exist */\necho do_shortcode('[shortcode_name]'); \n\n\n} else { \n\n /* Is NOT subscriber, is NOT in category Locked, has NO amount of posts */\n /* Post meta NOT exist */\n echo do_shortcode('[shortcode_name_1]'); \n}\n</code></pre>\n"
}
]
| 2018/11/28 | [
"https://wordpress.stackexchange.com/questions/320505",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113798/"
]
| I have this function...
```
$user = wp_get_current_user();
if (( in_category('Locked') ) && in_array( 'subscriber', (array) $user->roles ) ) {
/* Is subscriber, is in category Locked, has amount of posts */
echo do_shortcode('[shortcode_name]');
} else if (( in_category('Locked') ) && in_array( 'subscriber', (array) $user->roles ) ) {
/* Is subscriber, is in category Locked, has NO amount of posts */
echo '<div id="locked">
You are subscriber without number of posts!
</div>';
} else if ( in_category('Locked') ) {
/* Is NOT subscriber, is in category Locked, has NO amount of posts */
echo '<div id="locked">
Login or register pal!
</div>';
} else {
/* Is NOT subscriber, is NOT in category Locked, has NO amount of posts */
echo do_shortcode('[shortcode_name]');
}
```
I need to apply "has amount of posts" or "check if user is author of numebr of posts" on first part of code...
```
if (( in_category('Locked') ) && in_array( 'subscriber', (array) $user->roles ) ) && ?????
```
If this way can't work, I would have one more possible solution, it is to auto move user from subscriber to contributor once subscriber posted number of posts, but this first solution would be better. | I guess [`count_user_posts`](https://codex.wordpress.org/Function_Reference/count_user_posts) is what you're looking for ;)
This is how you use it:
```
$user_post_count = count_user_posts( $userid , $post_type );
```
And it returns the number of published posts the user has written in this post type.
PS. And if you want some more advanced count, [`get_posts_by_author_sql`](https://codex.wordpress.org/Function_Reference/get_posts_by_author_sql) can come quite handy. |
320,538 | <p>I try to apply a check figuring out if a plugin is either not active or just not installed at all in the plugin directory. When I test I check for a plugin installed but not activated as seen in the screenshot. </p>
<p><a href="https://i.stack.imgur.com/qdEYn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qdEYn.png" alt="VSCode screen showing sidebar with the installed plugin and the editor screen with the code from underneath in the question"></a></p>
<p>The checking if inactive part works flawlessly: </p>
<pre><code>$isinactive = is_plugin_inactive( 'advanced-custom-fields/acf.php' );
var_dump( $isinactive );
</code></pre>
<p>While checking if the plugin is actually installed and present in the plugin directory does not. First I generate the path to the main plugin file: </p>
<pre><code>$pathpluginurl = plugins_url( 'advanced-custom-fields/acf.php' );
var_dump($pathpluginurl);
</code></pre>
<p>Then check if that file exists: </p>
<pre><code>$isinstalled = file_exists( $pathpluginurl );
var_dump($isinstalled);
</code></pre>
<p>And then check if the particular file does NOT exist: </p>
<pre><code>if ( ! file_exists( $pathpluginurl ) ) {
echo "File does not exist";
} else {
echo "File exists";
}
</code></pre>
<p>The output:</p>
<pre><code>true //true for that the plugin is not active
http://mysandbox.test/wp-content/plugins/advanced-custom-fields/acf.php
false // false for that the acf.php file actually exists
file not exists
</code></pre>
<p>I don't understand why file_exists is not stating the facts and states the contrary saying the plugin does not exist? </p>
| [
{
"answer_id": 320541,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 4,
"selected": true,
"text": "<p><code>file_exists</code> expects a <em>path</em>, not a URL. To get the path to an arbitrary plugin you'll need to use <code>WP_PLUGIN_DIR</code>:</p>\n\n<pre><code>$pathpluginurl = WP_PLUGIN_DIR . '/advanced-custom-fields/acf.php';\n\n$isinstalled = file_exists( $pathpluginurl );\n</code></pre>\n"
},
{
"answer_id": 320542,
"author": "Greg Winiarski",
"author_id": 154460,
"author_profile": "https://wordpress.stackexchange.com/users/154460",
"pm_score": 0,
"selected": false,
"text": "<p>you are using file_exists() function on an URL not on path to file, this will not work (in most cases).</p>\n\n<p>Instead of </p>\n\n<p><code>$pathpluginurl = plugins_url( 'advanced-custom-fields/acf.php' );</code></p>\n\n<p>you should do to get an absolute file path</p>\n\n<p><code>$pathpluginurl = ABSPATH . 'wp-content/plugins/advanced-custom-fields/acf.php';</code></p>\n"
}
]
| 2018/11/29 | [
"https://wordpress.stackexchange.com/questions/320538",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44742/"
]
| I try to apply a check figuring out if a plugin is either not active or just not installed at all in the plugin directory. When I test I check for a plugin installed but not activated as seen in the screenshot.
[](https://i.stack.imgur.com/qdEYn.png)
The checking if inactive part works flawlessly:
```
$isinactive = is_plugin_inactive( 'advanced-custom-fields/acf.php' );
var_dump( $isinactive );
```
While checking if the plugin is actually installed and present in the plugin directory does not. First I generate the path to the main plugin file:
```
$pathpluginurl = plugins_url( 'advanced-custom-fields/acf.php' );
var_dump($pathpluginurl);
```
Then check if that file exists:
```
$isinstalled = file_exists( $pathpluginurl );
var_dump($isinstalled);
```
And then check if the particular file does NOT exist:
```
if ( ! file_exists( $pathpluginurl ) ) {
echo "File does not exist";
} else {
echo "File exists";
}
```
The output:
```
true //true for that the plugin is not active
http://mysandbox.test/wp-content/plugins/advanced-custom-fields/acf.php
false // false for that the acf.php file actually exists
file not exists
```
I don't understand why file\_exists is not stating the facts and states the contrary saying the plugin does not exist? | `file_exists` expects a *path*, not a URL. To get the path to an arbitrary plugin you'll need to use `WP_PLUGIN_DIR`:
```
$pathpluginurl = WP_PLUGIN_DIR . '/advanced-custom-fields/acf.php';
$isinstalled = file_exists( $pathpluginurl );
``` |
320,547 | <p>I’ve got a question. Maybe it’s something existing and I don’t know the name. Or maybe it’s something custom.</p>
<p>I’ve got a post type for news. The news posts have categories.
These are some examples of separate news items</p>
<ul>
<li><p>News item 1.</p>
<ul>
<li>Category “purple”</li>
</ul></li>
<li><p>News item 2.</p>
<ul>
<li>Category “purple”</li>
<li>Category “red”</li>
</ul></li>
<li><p>News item 3.</p>
<ul>
<li>Category “red”</li>
</ul></li>
</ul>
<p>I have 3 pages where I show and filter the news:</p>
<ul>
<li>www.domain.com/news (This shows all the news)</li>
<li>www.domain.com/purple/news (This shows all the purple news)</li>
<li>www.domain.com/red/news (This shows all the purple news)</li>
</ul>
<p>Showing a filtered post grid on each news page is not the problem. The problem is displaying them.
By default the permalinks of each news post is:</p>
<ul>
<li>www.domain.com/news/news-item-1</li>
<li>www.domain.com/news/news-item-2</li>
<li>www.domain.com/news/news-item-3</li>
</ul>
<p>And this is fine for the news on www.domain.com/news/</p>
<p>But now I want to display the category news items like following:
From www.domain.com/<strong>purple</strong>/news I want to click on the news item and open it like:</p>
<ul>
<li>www.domain.com/<strong>purple</strong>/news/news-item-1</li>
<li>www.domain.com/<strong>purple</strong>/news/news-item-2</li>
</ul>
<p>And from www.domain.com/<strong>red</strong>/news I want to click on the news item and open it like:</p>
<ul>
<li>www.domain.com/<strong>red</strong>/news/news-item-2</li>
<li>www.domain.com/<strong>red</strong>/news/news-item-3</li>
</ul>
<h2>The Question</h2>
<p>How do I get the news on the category news pages to open and show the items on the preferred url? (this should also show up in the sitemap.xml)</p>
| [
{
"answer_id": 320541,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 4,
"selected": true,
"text": "<p><code>file_exists</code> expects a <em>path</em>, not a URL. To get the path to an arbitrary plugin you'll need to use <code>WP_PLUGIN_DIR</code>:</p>\n\n<pre><code>$pathpluginurl = WP_PLUGIN_DIR . '/advanced-custom-fields/acf.php';\n\n$isinstalled = file_exists( $pathpluginurl );\n</code></pre>\n"
},
{
"answer_id": 320542,
"author": "Greg Winiarski",
"author_id": 154460,
"author_profile": "https://wordpress.stackexchange.com/users/154460",
"pm_score": 0,
"selected": false,
"text": "<p>you are using file_exists() function on an URL not on path to file, this will not work (in most cases).</p>\n\n<p>Instead of </p>\n\n<p><code>$pathpluginurl = plugins_url( 'advanced-custom-fields/acf.php' );</code></p>\n\n<p>you should do to get an absolute file path</p>\n\n<p><code>$pathpluginurl = ABSPATH . 'wp-content/plugins/advanced-custom-fields/acf.php';</code></p>\n"
}
]
| 2018/11/29 | [
"https://wordpress.stackexchange.com/questions/320547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152589/"
]
| I’ve got a question. Maybe it’s something existing and I don’t know the name. Or maybe it’s something custom.
I’ve got a post type for news. The news posts have categories.
These are some examples of separate news items
* News item 1.
+ Category “purple”
* News item 2.
+ Category “purple”
+ Category “red”
* News item 3.
+ Category “red”
I have 3 pages where I show and filter the news:
* www.domain.com/news (This shows all the news)
* www.domain.com/purple/news (This shows all the purple news)
* www.domain.com/red/news (This shows all the purple news)
Showing a filtered post grid on each news page is not the problem. The problem is displaying them.
By default the permalinks of each news post is:
* www.domain.com/news/news-item-1
* www.domain.com/news/news-item-2
* www.domain.com/news/news-item-3
And this is fine for the news on www.domain.com/news/
But now I want to display the category news items like following:
From www.domain.com/**purple**/news I want to click on the news item and open it like:
* www.domain.com/**purple**/news/news-item-1
* www.domain.com/**purple**/news/news-item-2
And from www.domain.com/**red**/news I want to click on the news item and open it like:
* www.domain.com/**red**/news/news-item-2
* www.domain.com/**red**/news/news-item-3
The Question
------------
How do I get the news on the category news pages to open and show the items on the preferred url? (this should also show up in the sitemap.xml) | `file_exists` expects a *path*, not a URL. To get the path to an arbitrary plugin you'll need to use `WP_PLUGIN_DIR`:
```
$pathpluginurl = WP_PLUGIN_DIR . '/advanced-custom-fields/acf.php';
$isinstalled = file_exists( $pathpluginurl );
``` |
320,570 | <p>When inserting a core/paragraph block to the content, we can choose e.g. "bold", "add link" from the controls above the content:</p>
<p><a href="https://i.stack.imgur.com/3oG6s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3oG6s.png" alt="enter image description here"></a></p>
<p>For my customer, I would like to add formatting buttons for <code><sup></sup></code> and <code><sub></sub></code>, in order to make it possible to write simple chemical or mathematical formulas, e.g. CO2 or m2.</p>
<p>I tried something like this, with a filter (taken from <a href="https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#editor-blockedit" rel="nofollow noreferrer">here</a>):</p>
<pre><code>const { createHigherOrderComponent } = wp.compose;
const { Fragment } = wp.element;
const { InspectorControls, BlockControls } = wp.editor;
const { PanelBody, Toolbar } = wp.components;
const withInspectorControls = createHigherOrderComponent( ( BlockEdit ) => {
return ( props ) => {
return (
<Fragment>
<BlockControls>
// what should I enter here?
</BlockControls>
<BlockEdit { ...props } />
</Fragment>
);
};
}, "withInspectorControl" );
wp.hooks.addFilter( 'editor.BlockEdit', 'my-plugin/with-inspector-controls', withInspectorControls );
</code></pre>
<p>a) how can I add the required buttons in the filtered <code><BlockControls></code>?</p>
<p>b) is this the right approach?</p>
<p><strong>Update 2019-01-24</strong></p>
<p>An official tutorial is now available <a href="https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/tutorials/format-api" rel="nofollow noreferrer">here</a>. I haven't tried it yet, but it seems to be exactly what I was looking for.</p>
| [
{
"answer_id": 323274,
"author": "Fergus Bisset",
"author_id": 142589,
"author_profile": "https://wordpress.stackexchange.com/users/142589",
"pm_score": 1,
"selected": false,
"text": "<p>If I understand your requirements correctly, and assuming you haven't now discovered this already, this plugin might be helpful / provide you what you need: </p>\n\n<p><a href=\"https://wordpress.org/plugins/advanced-rich-text-tools/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/advanced-rich-text-tools/</a></p>\n\n<p>If you want to build it yourself, then the source code for this plugin might also be instructive <a href=\"https://github.com/iseulde/advanced-rich-text-tools/blob/master/sub-sup.js\" rel=\"nofollow noreferrer\">https://github.com/iseulde/advanced-rich-text-tools/blob/master/sub-sup.js</a> and will demand you using the new (Gutenberg) Format API.</p>\n"
},
{
"answer_id": 326605,
"author": "uruk",
"author_id": 40821,
"author_profile": "https://wordpress.stackexchange.com/users/40821",
"pm_score": 2,
"selected": false,
"text": "<p>An official tutorial to add custom buttons is now available <a href=\"https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/tutorials/format-api\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
}
]
| 2018/11/29 | [
"https://wordpress.stackexchange.com/questions/320570",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40821/"
]
| When inserting a core/paragraph block to the content, we can choose e.g. "bold", "add link" from the controls above the content:
[](https://i.stack.imgur.com/3oG6s.png)
For my customer, I would like to add formatting buttons for `<sup></sup>` and `<sub></sub>`, in order to make it possible to write simple chemical or mathematical formulas, e.g. CO2 or m2.
I tried something like this, with a filter (taken from [here](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#editor-blockedit)):
```
const { createHigherOrderComponent } = wp.compose;
const { Fragment } = wp.element;
const { InspectorControls, BlockControls } = wp.editor;
const { PanelBody, Toolbar } = wp.components;
const withInspectorControls = createHigherOrderComponent( ( BlockEdit ) => {
return ( props ) => {
return (
<Fragment>
<BlockControls>
// what should I enter here?
</BlockControls>
<BlockEdit { ...props } />
</Fragment>
);
};
}, "withInspectorControl" );
wp.hooks.addFilter( 'editor.BlockEdit', 'my-plugin/with-inspector-controls', withInspectorControls );
```
a) how can I add the required buttons in the filtered `<BlockControls>`?
b) is this the right approach?
**Update 2019-01-24**
An official tutorial is now available [here](https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/tutorials/format-api). I haven't tried it yet, but it seems to be exactly what I was looking for. | An official tutorial to add custom buttons is now available [here](https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/tutorials/format-api). |
320,579 | <p>I'm trying to set up, when a specific page/url is visited that a cookie is set and saved.</p>
<p>So far I've tried this:</p>
<pre><code>add_action('init', 'set_cookie', 1);
function set_cookie(){
if ( $currentURL == 'https://25dni.si/delovanje-uma/' ) :
if ( ! isset( $_COOKIE['opt_in'] ) ) :
setcookie( 'opt_in', has_opt_in, time()+31556926);
endif;
endif;
}
</code></pre>
<p>Now, when I visit the specific URL, cookie is detected, but when I move on to another page, cookie is gone.</p>
<p>How can the cookie be saved?</p>
<p>I'm pretty new to this, please help me understand.</p>
<p>Thank you!</p>
| [
{
"answer_id": 320597,
"author": "jdp",
"author_id": 115910,
"author_profile": "https://wordpress.stackexchange.com/users/115910",
"pm_score": 0,
"selected": false,
"text": "<p>I'm surprised it works at all since <code>$currentURL</code> is not defined in the function nor declared as a global.</p>\n\n<p>Look at the <a href=\"http://php.net/manual/en/function.setcookie.php\" rel=\"nofollow noreferrer\">documentation</a> for <code>setcookie()</code>. You did not declare a path for the cookie so try this:</p>\n\n<p><code>setcookie('opt_in','opt_in', time()+31556926, '/');</code></p>\n\n<p>That will set the cookie for the entire domain, if that's what you want to do. </p>\n"
},
{
"answer_id": 320741,
"author": "Alex",
"author_id": 154962,
"author_profile": "https://wordpress.stackexchange.com/users/154962",
"pm_score": 1,
"selected": false,
"text": "<p>I've used this and it works:</p>\n\n<pre><code> add_action('init', 'optin_cookie', 1);\n\n function optin_cookie(){\n\n $currentURL = \"https://\" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];\n\n if ( $currentURL == 'https://25dni.si/delovanje-uma/' ) :\n\n setcookie( 'opt_in', has_opt_in, time()+31556926, '/');\n\n elseif ( $currentURL != 'https://25dni.si/' ) :\n\n if ( ! isset( $_COOKIE['opt_in'] ) ) :\n\n endif;\n\n endif;\n\n }\n</code></pre>\n\n<p>I'm sure there is a much more elegant way to do it, but this got it working for me ...</p>\n"
}
]
| 2018/11/29 | [
"https://wordpress.stackexchange.com/questions/320579",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154962/"
]
| I'm trying to set up, when a specific page/url is visited that a cookie is set and saved.
So far I've tried this:
```
add_action('init', 'set_cookie', 1);
function set_cookie(){
if ( $currentURL == 'https://25dni.si/delovanje-uma/' ) :
if ( ! isset( $_COOKIE['opt_in'] ) ) :
setcookie( 'opt_in', has_opt_in, time()+31556926);
endif;
endif;
}
```
Now, when I visit the specific URL, cookie is detected, but when I move on to another page, cookie is gone.
How can the cookie be saved?
I'm pretty new to this, please help me understand.
Thank you! | I've used this and it works:
```
add_action('init', 'optin_cookie', 1);
function optin_cookie(){
$currentURL = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if ( $currentURL == 'https://25dni.si/delovanje-uma/' ) :
setcookie( 'opt_in', has_opt_in, time()+31556926, '/');
elseif ( $currentURL != 'https://25dni.si/' ) :
if ( ! isset( $_COOKIE['opt_in'] ) ) :
endif;
endif;
}
```
I'm sure there is a much more elegant way to do it, but this got it working for me ... |
320,599 | <p>I want to sort posts by a meta value in a custom field. Basically I've added a field called 'date_event' and want to sort the posts by that date (stored as YYYYMMMDD).</p>
<p>The only working example I have is this placed in the loop.php:</p>
<pre><code>$query = new WP_Query(
array(
'meta_key' => 'date_event',
'orderby' => 'meta_value_num',
'order' => 'DESC',
)
);
</code></pre>
<p>This does the trick by sorting, but it takes all posts and sorts them no matter what category I'm viewing. From what I can see it's because I've called the <code>$query</code> again and not 'filtering' the posts I guess. It might also just be bad coding. </p>
<p>Anyway my goal is to have the posts sorted but only display the posts that are in that category you are in.</p>
<p>Any tips or references are greatly appreciated.</p>
| [
{
"answer_id": 320591,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": false,
"text": "<p>I have used <a href=\"https://wordpress.org/plugins/polylang/\" rel=\"nofollow noreferrer\">Polyang</a> in the past which works nicely for manual translations. Here is a <a href=\"https://www.wpbeginner.com/beginners-guide/how-to-easily-create-a-multilingual-wordpress-site/\" rel=\"nofollow noreferrer\">guide</a> that covers it.</p>\n"
},
{
"answer_id": 320595,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Creating a Multilingual WordPress Site (Human Translation)\nFirst thing you need to do is install and activate the Polylang plugin. Upon activation, you need to visit Settings » Languages to configure the plugin.</p>\n\n<p>Polylang settings page</p>\n\n<p>The language settings page is divided into three tabs. The first tab is labeled ‘Languages’. This is where you add the languages you want to use on your site.</p>\n\n<p>You will need to add the default language, as well as select all other languages that users can choose on your site.</p>\n\n<p>After adding the languages, switch to the ‘Strings Translations’ tab. Here you need to translate site title, description, and then choose the date and time format.</p>\n\n<p>Translating strings</p>\n\n<p>Last step in the configuration is the Settings tab. This is where you can choose a default language for your site and other technical settings.</p>\n\n<p>Setting up a URL structure</p>\n\n<p>For most beginners, we recommend not changing the URL, so select the first option. Why? Because if you ever turn off this plugin, then all those links will be broken.</p>\n\n<p>For those who are looking to take full advantage of multi language SEO, then we recommend that you choose the second option for pretty permalinks as shown in the screenshot above.</p>\n\n<p>You should select the option for detecting browser’s preferred language, and automatically show them the content in their preferred language. By doing this, the user will see the content in their preferred language and can switch the language if needed.</p>\n\n<p>Once you are done, click on the save changes button to store your settings.</p>\n\n<p>Adding Multilingual Content in WordPress\nPolylang makes it super easy to add content in different languages. Simply create a new post/page or edit an existing one. On the post edit screen, you will notice the languages meta box.</p>\n\n<p>Adding Multi-Lingual Content in WordPress using Polylang plugin</p>\n\n<p>Your default language will automatically be selected, so you can first add content in your default language, and then translate it into others.</p>\n\n<p>To translate, you need to click on the + button next to a language and then add content for that language.</p>\n\n<p>A multi-lingual blog post in WordPress created with Polylang</p>\n\n<p>Repeat the process for all languages. Once you are done, you can publish your posts and pages.</p>\n\n<p>It’s important to note that Polylang works with custom post types, so it can definitely help you make your woocommerce store multilingual.</p>\n\n<p>Translating Categories, Tags, and Custom Taxonomies\nYou can also translate categories and tags, or any custom taxonomies you may be using.</p>\n\n<p>If you want to translate categories, then go to Posts » Categories.</p>\n\n<p>Translating categories</p>\n\n<p>Add a category in your default language and then click on the plus icon for each language to start adding translations.</p>\n\n<p>Displaying Multi Language Switcher on Your WordPress Site\nAdding a language switcher allows users to select a language when viewing your site. Polylang makes it super simple. Just go to Appearance » Widgets and add the language switcher widget to your sidebar or another widget-ready area.</p>\n\n<p>Language switcher</p>\n\n<p>You can choose a drop down, or use language names with flags. Once you are done, click the save button to store your widget settings.</p>\n\n<p>You can now preview your site to see the language switcher in action.</p>\n\n<p>Language switcher on a live WordPress site</p>\n\n<p>Using Google Translate to Create a Multilingual Site in WordPress\nWhile adding human translations definitely creates a better user experience, you may not have the resources or time to do that. In that case, you can try using Google Translate to automatically translate content on your site.</p>\n\n<p>First thing you need to do is install and activate the Google Language Translator plugin. Upon activation, visit Settings » Google Language Translator to configure the plugin.</p>\n\n<p>Google Language Translator plugin</p>\n\n<p>The plugin allows you to select the languages available with Google Translate. You can even remove Google’s branding from translation. This is a highly customizable plugin, so you need to go through the settings and configure it to your liking.</p>\n\n<p>For more details check out our tutorial on how to add Google Translate in WordPress with video and text instructions on how to set up the plugin.</p>\n\n<p>That’s all, we hope this article helped you learn how to create a multilingual site in WordPress. You should also look at our article on how to install WordPress in your language.</p>\n\n<p>If you are looking for a multilingual WordPress theme also referred to translation-ready themes, check out our guide on how to find translation ready WordPress themes that also has an easy way to translate existing WordPress themes.</p>\n"
}
]
| 2018/11/29 | [
"https://wordpress.stackexchange.com/questions/320599",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154977/"
]
| I want to sort posts by a meta value in a custom field. Basically I've added a field called 'date\_event' and want to sort the posts by that date (stored as YYYYMMMDD).
The only working example I have is this placed in the loop.php:
```
$query = new WP_Query(
array(
'meta_key' => 'date_event',
'orderby' => 'meta_value_num',
'order' => 'DESC',
)
);
```
This does the trick by sorting, but it takes all posts and sorts them no matter what category I'm viewing. From what I can see it's because I've called the `$query` again and not 'filtering' the posts I guess. It might also just be bad coding.
Anyway my goal is to have the posts sorted but only display the posts that are in that category you are in.
Any tips or references are greatly appreciated. | I have used [Polyang](https://wordpress.org/plugins/polylang/) in the past which works nicely for manual translations. Here is a [guide](https://www.wpbeginner.com/beginners-guide/how-to-easily-create-a-multilingual-wordpress-site/) that covers it. |
320,600 | <p>Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'wp_my_admin_enqueue_scripts' not found or invalid function name in /mnt/data/vhosts/casite-961871.cloudaccess.net/httpdocs/wp-includes/class-wp-hook.php on line 286</p>
| [
{
"answer_id": 320603,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 2,
"selected": false,
"text": "<p>This means you have a function named <code>wp_my_admin_enqueue_scripts</code> hooked to an action, either in your theme or a plugin, but that function name is not available to WordPress for some reason.</p>\n\n<p>When that action fires, any functions \"hooked\" to it are executed by WordPress. If one of the hooked functions is not available, this is the error presented.</p>\n\n<p>For example, in the sample code below the function named <code>sc_corporate_widgets_init</code> is executed when WordPress fires the <code>widgets_init</code> action.</p>\n\n<pre><code>add_action( 'widgets_init', 'sc_corporate_widgets_init' );\n</code></pre>\n\n<p>Make sure you do not have a spelling error with a function name. They must match exactly in order to prevent this error.</p>\n"
},
{
"answer_id": 320604,
"author": "Shir Gans",
"author_id": 35024,
"author_profile": "https://wordpress.stackexchange.com/users/35024",
"pm_score": 1,
"selected": false,
"text": "<p>This error means that you have a wrong action (hook). meaning the code is trying to call a function that does not exists.\nBut, from the path the error is coming from, I think:</p>\n<ol>\n<li>you may have tried to change the core code<br></li>\n<li>or more likley that your WordPress install is not complete, and you are missing files.</li>\n</ol>\n"
}
]
| 2018/11/29 | [
"https://wordpress.stackexchange.com/questions/320600",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154979/"
]
| Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'wp\_my\_admin\_enqueue\_scripts' not found or invalid function name in /mnt/data/vhosts/casite-961871.cloudaccess.net/httpdocs/wp-includes/class-wp-hook.php on line 286 | This means you have a function named `wp_my_admin_enqueue_scripts` hooked to an action, either in your theme or a plugin, but that function name is not available to WordPress for some reason.
When that action fires, any functions "hooked" to it are executed by WordPress. If one of the hooked functions is not available, this is the error presented.
For example, in the sample code below the function named `sc_corporate_widgets_init` is executed when WordPress fires the `widgets_init` action.
```
add_action( 'widgets_init', 'sc_corporate_widgets_init' );
```
Make sure you do not have a spelling error with a function name. They must match exactly in order to prevent this error. |
320,616 | <p>I just took over a website created with wordpress but is broken, the hosting provider reinstalled wordpress but kept the database, so all the information is there, however i can see that the code for the pages seems to have been generated by using some plugin or similar, so now I don't have information of which plugins were installed before but i do have pages that display this kind of code:</p>
<pre><code>[section__dd class= 'inhale-top inhale-bottom'][column_dd span='12'][text_dd]
</code></pre>
<p>does anyone recognize it and knows which plugin was it so i can restore the site or at least see some pages as they were before? I'm usually just in charge of hosting and db management not really familiar with plugins</p>
| [
{
"answer_id": 320618,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Plugins add additional functionality to a site. Page code is generated by the theme's templates, which query the database (where content is stored) and display the content with the styling (CSS) and 'structure' (how the content 'pieces' are displayed) as defined by the theme.</p>\n\n<p>The actual theme template used is based on the Theme's Template Hierarchy, which you can learn about here: <a href=\"https://developer.wordpress.org/themes/getting-started/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/getting-started/</a> . </p>\n\n<p>A good understanding of how themes work to display the content is the first step for you. The link above, along with tons of other information available via the googles, is a starting point.</p>\n"
},
{
"answer_id": 369598,
"author": "sebas",
"author_id": 190468,
"author_profile": "https://wordpress.stackexchange.com/users/190468",
"pm_score": 2,
"selected": true,
"text": "<p>I found the plugin by running a search for the string "text_dd" in the <code>wp-content/plugins/</code> directory.</p>\n<p>Looks like this specific plugin (which provides <code>text_dd</code>, <code>column_dd</code> and <code>section_dd</code> shortcodes) is called "dnd-shortcodes" and contains the following snippet of information:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Plugin Name: Drag and Drop Shortcodes\nPlugin URI: http://themeforest.net/user/AB-themes?ref=AB-themes\nDescription: Visual drag and drop page builder containing great collection of animated shortcodes with paralax effects and video backgrounds\nVersion: 1.2.2\nAuthor: Abdev\nAuthor URI: http://themeforest.net/user/AB-themes?ref=AB-themes\n</code></pre>\n"
}
]
| 2018/11/30 | [
"https://wordpress.stackexchange.com/questions/320616",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154996/"
]
| I just took over a website created with wordpress but is broken, the hosting provider reinstalled wordpress but kept the database, so all the information is there, however i can see that the code for the pages seems to have been generated by using some plugin or similar, so now I don't have information of which plugins were installed before but i do have pages that display this kind of code:
```
[section__dd class= 'inhale-top inhale-bottom'][column_dd span='12'][text_dd]
```
does anyone recognize it and knows which plugin was it so i can restore the site or at least see some pages as they were before? I'm usually just in charge of hosting and db management not really familiar with plugins | I found the plugin by running a search for the string "text\_dd" in the `wp-content/plugins/` directory.
Looks like this specific plugin (which provides `text_dd`, `column_dd` and `section_dd` shortcodes) is called "dnd-shortcodes" and contains the following snippet of information:
```none
Plugin Name: Drag and Drop Shortcodes
Plugin URI: http://themeforest.net/user/AB-themes?ref=AB-themes
Description: Visual drag and drop page builder containing great collection of animated shortcodes with paralax effects and video backgrounds
Version: 1.2.2
Author: Abdev
Author URI: http://themeforest.net/user/AB-themes?ref=AB-themes
``` |
320,653 | <p>The new editor called Gutenberg is here as plugin in 4.9, and as core functionality called Block Editor, in 5.0. Regarding to it, it is often needed to determine programmatically which editor is used to edit post or page in the site console. How to do it?</p>
<p><strong>Update:</strong> There are number of outdated answers to similar question:</p>
<ul>
<li><a href="https://wordpress.stackexchange.com/questions/320653/how-to-detect-the-usage-of-gutenberg#comment473849_320653"><code>gutenberg_post_has_blocks()</code></a> - this function exists only in Gutenberg plugin, and not in 5.0 Core</li>
<li><a href="https://wordpress.stackexchange.com/a/309955"><code>is_gutenberg_page()</code></a> - the same</li>
<li><a href="https://wordpress.stackexchange.com/questions/320653/how-to-detect-the-usage-of-gutenberg#comment473850_320653"><code>the_gutenberg_project()</code></a> - the same</li>
<li><a href="https://wordpress.stackexchange.com/a/312776"><code>has_blocks()</code></a> - does not work (returns false) when Classic Editor is on and its option "Default editor for all users" = "Block Editor"</li>
<li><a href="https://wordpress.stackexchange.com/a/319053">answer</a> simply produces fatal error <code>Call to undefined function get_current_screen()</code></li>
</ul>
<p>So, before commenting this question and answer, please take a work to check what do you propose. Check it now, with 4.9 and current version of WordPress, and all possible combinations of Classic Editor and Gutenberg/Block Editor. I will be happy to discuss tested solution, not links to something.</p>
| [
{
"answer_id": 320654,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 5,
"selected": true,
"text": "<p>There are several variants:</p>\n\n<ul>\n<li>WordPress 4.9, Gutenberg plugin is not active</li>\n<li>WordPress 4.9, Gutenberg plugin is active</li>\n<li>WordPress 5.0, Block Editor by default</li>\n<li>WordPress 5.0, Classic Editor plugin is active</li>\n<li>WordPress 5.0, Classic Editor plugin is active, but in site console in “Settings > Writing” the option “Use the Block editor by default…” is selected</li>\n</ul>\n\n<p>All the mentioned variants can be processed by the following code:</p>\n\n<pre><code>/**\n * Check if Block Editor is active.\n * Must only be used after plugins_loaded action is fired.\n *\n * @return bool\n */\nfunction is_active() {\n // Gutenberg plugin is installed and activated.\n $gutenberg = ! ( false === has_filter( 'replace_editor', 'gutenberg_init' ) );\n\n // Block editor since 5.0.\n $block_editor = version_compare( $GLOBALS['wp_version'], '5.0-beta', '>' );\n\n if ( ! $gutenberg && ! $block_editor ) {\n return false;\n }\n\n if ( is_classic_editor_plugin_active() ) {\n $editor_option = get_option( 'classic-editor-replace' );\n $block_editor_active = array( 'no-replace', 'block' );\n\n return in_array( $editor_option, $block_editor_active, true );\n }\n\n return true;\n}\n\n/**\n * Check if Classic Editor plugin is active.\n *\n * @return bool\n */\nfunction is_classic_editor_plugin_active() {\n if ( ! function_exists( 'is_plugin_active' ) ) {\n include_once ABSPATH . 'wp-admin/includes/plugin.php';\n }\n\n if ( is_plugin_active( 'classic-editor/classic-editor.php' ) ) {\n return true;\n }\n\n return false;\n}\n</code></pre>\n\n<p>Function returns true if block editor is active by any means, and false – in the case if classic editor is here. This function must only be used after <code>plugins_loaded</code> action is fired.</p>\n\n<p>P.S. Due release of version 1.2 of Classic Editor plugin, code is updated, as <code>classic-editor-replace</code> options now takes values not <code>replace</code> and <code>no-replace</code>, but <code>classic</code> and <code>block</code>.</p>\n"
},
{
"answer_id": 320684,
"author": "Marc",
"author_id": 155035,
"author_profile": "https://wordpress.stackexchange.com/users/155035",
"pm_score": 2,
"selected": false,
"text": "<p>You can use</p>\n\n<pre><code>add_action( 'enqueue_block_editor_assets', 'your_function_name' );\n</code></pre>\n\n<p>which is only fired when editing content with Gutenberg.</p>\n"
}
]
| 2018/11/30 | [
"https://wordpress.stackexchange.com/questions/320653",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108721/"
]
| The new editor called Gutenberg is here as plugin in 4.9, and as core functionality called Block Editor, in 5.0. Regarding to it, it is often needed to determine programmatically which editor is used to edit post or page in the site console. How to do it?
**Update:** There are number of outdated answers to similar question:
* [`gutenberg_post_has_blocks()`](https://wordpress.stackexchange.com/questions/320653/how-to-detect-the-usage-of-gutenberg#comment473849_320653) - this function exists only in Gutenberg plugin, and not in 5.0 Core
* [`is_gutenberg_page()`](https://wordpress.stackexchange.com/a/309955) - the same
* [`the_gutenberg_project()`](https://wordpress.stackexchange.com/questions/320653/how-to-detect-the-usage-of-gutenberg#comment473850_320653) - the same
* [`has_blocks()`](https://wordpress.stackexchange.com/a/312776) - does not work (returns false) when Classic Editor is on and its option "Default editor for all users" = "Block Editor"
* [answer](https://wordpress.stackexchange.com/a/319053) simply produces fatal error `Call to undefined function get_current_screen()`
So, before commenting this question and answer, please take a work to check what do you propose. Check it now, with 4.9 and current version of WordPress, and all possible combinations of Classic Editor and Gutenberg/Block Editor. I will be happy to discuss tested solution, not links to something. | There are several variants:
* WordPress 4.9, Gutenberg plugin is not active
* WordPress 4.9, Gutenberg plugin is active
* WordPress 5.0, Block Editor by default
* WordPress 5.0, Classic Editor plugin is active
* WordPress 5.0, Classic Editor plugin is active, but in site console in “Settings > Writing” the option “Use the Block editor by default…” is selected
All the mentioned variants can be processed by the following code:
```
/**
* Check if Block Editor is active.
* Must only be used after plugins_loaded action is fired.
*
* @return bool
*/
function is_active() {
// Gutenberg plugin is installed and activated.
$gutenberg = ! ( false === has_filter( 'replace_editor', 'gutenberg_init' ) );
// Block editor since 5.0.
$block_editor = version_compare( $GLOBALS['wp_version'], '5.0-beta', '>' );
if ( ! $gutenberg && ! $block_editor ) {
return false;
}
if ( is_classic_editor_plugin_active() ) {
$editor_option = get_option( 'classic-editor-replace' );
$block_editor_active = array( 'no-replace', 'block' );
return in_array( $editor_option, $block_editor_active, true );
}
return true;
}
/**
* Check if Classic Editor plugin is active.
*
* @return bool
*/
function is_classic_editor_plugin_active() {
if ( ! function_exists( 'is_plugin_active' ) ) {
include_once ABSPATH . 'wp-admin/includes/plugin.php';
}
if ( is_plugin_active( 'classic-editor/classic-editor.php' ) ) {
return true;
}
return false;
}
```
Function returns true if block editor is active by any means, and false – in the case if classic editor is here. This function must only be used after `plugins_loaded` action is fired.
P.S. Due release of version 1.2 of Classic Editor plugin, code is updated, as `classic-editor-replace` options now takes values not `replace` and `no-replace`, but `classic` and `block`. |
320,656 | <p>I set cookie for my users to know from which source they come to the site and I want when user contact us their message comes with their cookie as well.</p>
<p>So that I created a new shortcode and added in mail section but it mails direct shortcode not its returned value</p>
<p>Code :</p>
<pre><code>function my_shortcode( $atts ) {
return isset($_COOKIE['my_source']) ? $_COOKIE['my_source'] : '' ;
}
add_shortcode( 'my-source', 'my_shortcode' );
</code></pre>
<p><strong>Message body in contact form 7 :</strong></p>
<pre><code>Name : [your-name]
Email : [your-email]
Phone : [form-tel]
My Source : [my-source]
</code></pre>
<p><strong>Email I Received :</strong></p>
<pre><code>Name : Mohit Bumb
Email : [email protected]
Phone : 19191919191
My Source : [my-source]
</code></pre>
| [
{
"answer_id": 320658,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>You should do it like so:</p>\n\n<pre><code>add_action( 'wpcf7_init', 'custom_add_form_tag_my_source' );\n\nfunction custom_add_form_tag_my_source() {\n // \"my-source\" is the type of the form-tag\n wpcf7_add_form_tag( 'my-source', 'custom_my_source_form_tag_handler' );\n}\n\nfunction custom_my_source_form_tag_handler( $tag ) {\n return isset( $_COOKIE['my_source'] ) ? $_COOKIE['my_source'] : '';\n}\n</code></pre>\n\n<p>See the <a href=\"https://contactform7.com/2015/01/10/adding-a-custom-form-tag/\" rel=\"nofollow noreferrer\">documentation</a> for more details.</p>\n\n<p>Or you can also try this, to parse regular shortcodes:</p>\n\n<pre><code>add_filter( 'wpcf7_mail_components', function( $components ){\n $components['body'] = do_shortcode( $components['body'] );\n return $components;\n} );\n</code></pre>\n"
},
{
"answer_id": 321783,
"author": "lalo",
"author_id": 75628,
"author_profile": "https://wordpress.stackexchange.com/users/75628",
"pm_score": 1,
"selected": false,
"text": "<p>Use the filter \"wpcf7_special_mail_tags\"</p>\n\n<p>in this example my tag is \"tournaments\"</p>\n\n<pre><code>/**\n * A tag to be used in \"Mail\" section so the user receives the special tag\n * [tournaments]\n */\nadd_filter('wpcf7_special_mail_tags', 'wpcf7_tag_tournament', 10, 3);\nfunction wpcf7_tag_tournament($output, $name, $html)\n{\n $name = preg_replace('/^wpcf7\\./', '_', $name); // for back-compat\n\n $submission = WPCF7_Submission::get_instance();\n\n if (! $submission) {\n return $output;\n }\n\n if ('tournaments' == $name) {\n return $submission->get_posted_data(\"tournaments\");\n }\n\n return $output;\n}\n</code></pre>\n"
},
{
"answer_id": 321801,
"author": "lalo",
"author_id": 75628,
"author_profile": "https://wordpress.stackexchange.com/users/75628",
"pm_score": 0,
"selected": false,
"text": "<p>I solved and posted my answer here:</p>\n\n<h1>Adding A Custom Form-Tag to Contact Form 7 in Wordpress</h1>\n\n<p>(that also works to be sent in email)</p>\n\n<p><a href=\"https://stackoverflow.com/questions/53754577/how-to-make-contact-form-7-custom-field/\">https://stackoverflow.com/questions/53754577/how-to-make-contact-form-7-custom-field/</a></p>\n\n<h1>The code</h1>\n\n<p><a href=\"https://gist.github.com/eduardoarandah/83cad9227bc0ab13bf845ab14f2c4dad\" rel=\"nofollow noreferrer\">https://gist.github.com/eduardoarandah/83cad9227bc0ab13bf845ab14f2c4dad</a></p>\n"
},
{
"answer_id": 373226,
"author": "armin",
"author_id": 179860,
"author_profile": "https://wordpress.stackexchange.com/users/179860",
"pm_score": 1,
"selected": false,
"text": "<p>I am late but use special tag in this scenario</p>\n<pre><code>// Hook for additional special mail tag\nadd_filter( 'wpcf7_special_mail_tags', 'wti_special_mail_tag', 20, 3 );\nfunction wti_special_mail_tag( $output, $name, $html )\n{\n $name = preg_replace( '/^wpcf7\\./', '_', $name );\n if ( '_my_cookie' == $name ) {\n $output = isset( $_COOKIE['my_source'] ) ? $_COOKIE['my_source'] : '';\n }\n return $output;\n}\n</code></pre>\n<p>you can use <code>[_my_cookie]</code> to call its value</p>\n"
}
]
| 2018/11/30 | [
"https://wordpress.stackexchange.com/questions/320656",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8184/"
]
| I set cookie for my users to know from which source they come to the site and I want when user contact us their message comes with their cookie as well.
So that I created a new shortcode and added in mail section but it mails direct shortcode not its returned value
Code :
```
function my_shortcode( $atts ) {
return isset($_COOKIE['my_source']) ? $_COOKIE['my_source'] : '' ;
}
add_shortcode( 'my-source', 'my_shortcode' );
```
**Message body in contact form 7 :**
```
Name : [your-name]
Email : [your-email]
Phone : [form-tel]
My Source : [my-source]
```
**Email I Received :**
```
Name : Mohit Bumb
Email : [email protected]
Phone : 19191919191
My Source : [my-source]
``` | You should do it like so:
```
add_action( 'wpcf7_init', 'custom_add_form_tag_my_source' );
function custom_add_form_tag_my_source() {
// "my-source" is the type of the form-tag
wpcf7_add_form_tag( 'my-source', 'custom_my_source_form_tag_handler' );
}
function custom_my_source_form_tag_handler( $tag ) {
return isset( $_COOKIE['my_source'] ) ? $_COOKIE['my_source'] : '';
}
```
See the [documentation](https://contactform7.com/2015/01/10/adding-a-custom-form-tag/) for more details.
Or you can also try this, to parse regular shortcodes:
```
add_filter( 'wpcf7_mail_components', function( $components ){
$components['body'] = do_shortcode( $components['body'] );
return $components;
} );
``` |
320,690 | <p>I'd like to update my post status (of my own CPT) based on custom field "played". If played is 1 i want that the post shall be published, but if the custom field played is 0 the post shall be draft also if I tried to publish it.</p>
<p>Is it possible?</p>
<p>I tried to search in the forum but nothing found that works... also tried the code here but not working...</p>
<p><a href="https://wordpress.stackexchange.com/questions/180253/how-to-update-post-status-using-meta-data-in-custom-post-type">How to Update post status using meta data in Custom post TYpe</a></p>
| [
{
"answer_id": 320691,
"author": "JakeParis",
"author_id": 2044,
"author_profile": "https://wordpress.stackexchange.com/users/2044",
"pm_score": 1,
"selected": false,
"text": "<p>That might be quite a bit of code to paste in here, but your strategy should be along the lines of: </p>\n\n<ul>\n<li>Hook onto post_save event: \n\n<ul>\n<li>make a static variable that you've already checked this, to prevent infinite recursion in the case that you update the post from within this function.</li>\n<li>check if custom field == 'played'\n\n<ul>\n<li>if it is, modify the post status as needed, and do wp_update_post. </li>\n</ul></li>\n</ul></li>\n</ul>\n"
},
{
"answer_id": 320694,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>All you need to do is to use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\"><code>save_post</code></a> hook. Here's how:</p>\n\n<pre><code>function change_post_status_based_on_custom_field( $post_id ) {\n // If this is just a revision, don't do anything.\n if ( wp_is_post_revision( $post_id ) )\n return;\n\n // Get field value\n $value = get_post_meta( $post_id, 'played', true );\n\n $status = $value ? 'publish' : 'draft';\n\n // If status should be different, change it\n if ( get_post_status( $post_id ) != $status ) {\n // unhook this function so it doesn't loop infinitely\n remove_action( 'save_post', 'change_post_status_based_on_custom_field' );\n\n // update the post, which calls save_post again\n wp_update_post( array(\n 'ID' => $post_id,\n 'post_status' => $status\n ) );\n\n // re-hook this function\n add_action( 'save_post', 'change_post_status_based_on_custom_field' );\n }\n}\nadd_action( 'save_post', 'change_post_status_based_on_custom_field' );\n</code></pre>\n"
}
]
| 2018/11/30 | [
"https://wordpress.stackexchange.com/questions/320690",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134550/"
]
| I'd like to update my post status (of my own CPT) based on custom field "played". If played is 1 i want that the post shall be published, but if the custom field played is 0 the post shall be draft also if I tried to publish it.
Is it possible?
I tried to search in the forum but nothing found that works... also tried the code here but not working...
[How to Update post status using meta data in Custom post TYpe](https://wordpress.stackexchange.com/questions/180253/how-to-update-post-status-using-meta-data-in-custom-post-type) | All you need to do is to use [`save_post`](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) hook. Here's how:
```
function change_post_status_based_on_custom_field( $post_id ) {
// If this is just a revision, don't do anything.
if ( wp_is_post_revision( $post_id ) )
return;
// Get field value
$value = get_post_meta( $post_id, 'played', true );
$status = $value ? 'publish' : 'draft';
// If status should be different, change it
if ( get_post_status( $post_id ) != $status ) {
// unhook this function so it doesn't loop infinitely
remove_action( 'save_post', 'change_post_status_based_on_custom_field' );
// update the post, which calls save_post again
wp_update_post( array(
'ID' => $post_id,
'post_status' => $status
) );
// re-hook this function
add_action( 'save_post', 'change_post_status_based_on_custom_field' );
}
}
add_action( 'save_post', 'change_post_status_based_on_custom_field' );
``` |
320,695 | <p>I am trying to get the featured image of a post using the WordPress REST API. I am adding the extention of ?embed to the end if the REST API url and I am seeing the featured image data under ['wp:featuredmedia'], but I can't seem to display that data. </p>
<p>I am using Vue to display data from the REST API and so what I am doing currently to try and get the featured image source is: post._embedded['wp:featuredmedia'][0].source_url</p>
<p>But by doing that it can't find the source url of the featured image and I am not sure what is wrong with my path for it to not find the source url data?</p>
| [
{
"answer_id": 320691,
"author": "JakeParis",
"author_id": 2044,
"author_profile": "https://wordpress.stackexchange.com/users/2044",
"pm_score": 1,
"selected": false,
"text": "<p>That might be quite a bit of code to paste in here, but your strategy should be along the lines of: </p>\n\n<ul>\n<li>Hook onto post_save event: \n\n<ul>\n<li>make a static variable that you've already checked this, to prevent infinite recursion in the case that you update the post from within this function.</li>\n<li>check if custom field == 'played'\n\n<ul>\n<li>if it is, modify the post status as needed, and do wp_update_post. </li>\n</ul></li>\n</ul></li>\n</ul>\n"
},
{
"answer_id": 320694,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>All you need to do is to use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\"><code>save_post</code></a> hook. Here's how:</p>\n\n<pre><code>function change_post_status_based_on_custom_field( $post_id ) {\n // If this is just a revision, don't do anything.\n if ( wp_is_post_revision( $post_id ) )\n return;\n\n // Get field value\n $value = get_post_meta( $post_id, 'played', true );\n\n $status = $value ? 'publish' : 'draft';\n\n // If status should be different, change it\n if ( get_post_status( $post_id ) != $status ) {\n // unhook this function so it doesn't loop infinitely\n remove_action( 'save_post', 'change_post_status_based_on_custom_field' );\n\n // update the post, which calls save_post again\n wp_update_post( array(\n 'ID' => $post_id,\n 'post_status' => $status\n ) );\n\n // re-hook this function\n add_action( 'save_post', 'change_post_status_based_on_custom_field' );\n }\n}\nadd_action( 'save_post', 'change_post_status_based_on_custom_field' );\n</code></pre>\n"
}
]
| 2018/11/30 | [
"https://wordpress.stackexchange.com/questions/320695",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153404/"
]
| I am trying to get the featured image of a post using the WordPress REST API. I am adding the extention of ?embed to the end if the REST API url and I am seeing the featured image data under ['wp:featuredmedia'], but I can't seem to display that data.
I am using Vue to display data from the REST API and so what I am doing currently to try and get the featured image source is: post.\_embedded['wp:featuredmedia'][0].source\_url
But by doing that it can't find the source url of the featured image and I am not sure what is wrong with my path for it to not find the source url data? | All you need to do is to use [`save_post`](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) hook. Here's how:
```
function change_post_status_based_on_custom_field( $post_id ) {
// If this is just a revision, don't do anything.
if ( wp_is_post_revision( $post_id ) )
return;
// Get field value
$value = get_post_meta( $post_id, 'played', true );
$status = $value ? 'publish' : 'draft';
// If status should be different, change it
if ( get_post_status( $post_id ) != $status ) {
// unhook this function so it doesn't loop infinitely
remove_action( 'save_post', 'change_post_status_based_on_custom_field' );
// update the post, which calls save_post again
wp_update_post( array(
'ID' => $post_id,
'post_status' => $status
) );
// re-hook this function
add_action( 'save_post', 'change_post_status_based_on_custom_field' );
}
}
add_action( 'save_post', 'change_post_status_based_on_custom_field' );
``` |
320,751 | <p>Ok, I know similar questions have been asked before but none of the answers I found seem to work. Here's my code:</p>
<pre><code>$sql = $wpdb->prepare('SELECT ID FROM ' . $ignore_url_table_name . " where url LIKE '%%%s%%'", $urlRequested);
$wpdb->get_row($sql);
if ($wpdb->num_rows > 0) {
return;
}
</code></pre>
<p>Here's the problem: I'm trying to detect when a specific string is found in the URL. One example of the url in the talble to look for is: </p>
<p>doing_wp_cron</p>
<p>An example of the $urlRequested is:</p>
<p>doing_wp_cron=1543678213.5953478813171386718750</p>
<p>The above SQL statement doesn't find a match.</p>
<p>I've also attempted to use </p>
<pre><code>$sql = $wpdb->prepare('SELECT ID FROM ' . $ignore_url_table_name . " where url LIKE '%s'", '%' . $wpdb->esc_like($urlRequested) . '%');
</code></pre>
<p>This appears to turn the doing_wp_cron into doing//_wp//_cron which the query also doesn't find.</p>
<p>What am I doing wrong here?</p>
<p>Thanks</p>
<p>*Edit: So I echoed out the sql query and this looked strange.</p>
<pre><code>SELECT ID FROM URL_Ignores where url LIKE '{1b71fb783b53a0ae087bf6ac6b01addd9b80435193728fe4c7c7d70b30748268}/doing_wp_cron=1543682280.1607289314270019531250{1b71fb783b53a0ae087bf6ac6b01addd9b80435193728fe4c7c7d70b30748268}'
</code></pre>
<p>I have no idea why but it seems every way I try to $wpdb->prepare this it's converting the % into a random variable!???</p>
| [
{
"answer_id": 320691,
"author": "JakeParis",
"author_id": 2044,
"author_profile": "https://wordpress.stackexchange.com/users/2044",
"pm_score": 1,
"selected": false,
"text": "<p>That might be quite a bit of code to paste in here, but your strategy should be along the lines of: </p>\n\n<ul>\n<li>Hook onto post_save event: \n\n<ul>\n<li>make a static variable that you've already checked this, to prevent infinite recursion in the case that you update the post from within this function.</li>\n<li>check if custom field == 'played'\n\n<ul>\n<li>if it is, modify the post status as needed, and do wp_update_post. </li>\n</ul></li>\n</ul></li>\n</ul>\n"
},
{
"answer_id": 320694,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>All you need to do is to use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/save_post\" rel=\"nofollow noreferrer\"><code>save_post</code></a> hook. Here's how:</p>\n\n<pre><code>function change_post_status_based_on_custom_field( $post_id ) {\n // If this is just a revision, don't do anything.\n if ( wp_is_post_revision( $post_id ) )\n return;\n\n // Get field value\n $value = get_post_meta( $post_id, 'played', true );\n\n $status = $value ? 'publish' : 'draft';\n\n // If status should be different, change it\n if ( get_post_status( $post_id ) != $status ) {\n // unhook this function so it doesn't loop infinitely\n remove_action( 'save_post', 'change_post_status_based_on_custom_field' );\n\n // update the post, which calls save_post again\n wp_update_post( array(\n 'ID' => $post_id,\n 'post_status' => $status\n ) );\n\n // re-hook this function\n add_action( 'save_post', 'change_post_status_based_on_custom_field' );\n }\n}\nadd_action( 'save_post', 'change_post_status_based_on_custom_field' );\n</code></pre>\n"
}
]
| 2018/12/01 | [
"https://wordpress.stackexchange.com/questions/320751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155077/"
]
| Ok, I know similar questions have been asked before but none of the answers I found seem to work. Here's my code:
```
$sql = $wpdb->prepare('SELECT ID FROM ' . $ignore_url_table_name . " where url LIKE '%%%s%%'", $urlRequested);
$wpdb->get_row($sql);
if ($wpdb->num_rows > 0) {
return;
}
```
Here's the problem: I'm trying to detect when a specific string is found in the URL. One example of the url in the talble to look for is:
doing\_wp\_cron
An example of the $urlRequested is:
doing\_wp\_cron=1543678213.5953478813171386718750
The above SQL statement doesn't find a match.
I've also attempted to use
```
$sql = $wpdb->prepare('SELECT ID FROM ' . $ignore_url_table_name . " where url LIKE '%s'", '%' . $wpdb->esc_like($urlRequested) . '%');
```
This appears to turn the doing\_wp\_cron into doing//\_wp//\_cron which the query also doesn't find.
What am I doing wrong here?
Thanks
\*Edit: So I echoed out the sql query and this looked strange.
```
SELECT ID FROM URL_Ignores where url LIKE '{1b71fb783b53a0ae087bf6ac6b01addd9b80435193728fe4c7c7d70b30748268}/doing_wp_cron=1543682280.1607289314270019531250{1b71fb783b53a0ae087bf6ac6b01addd9b80435193728fe4c7c7d70b30748268}'
```
I have no idea why but it seems every way I try to $wpdb->prepare this it's converting the % into a random variable!??? | All you need to do is to use [`save_post`](https://codex.wordpress.org/Plugin_API/Action_Reference/save_post) hook. Here's how:
```
function change_post_status_based_on_custom_field( $post_id ) {
// If this is just a revision, don't do anything.
if ( wp_is_post_revision( $post_id ) )
return;
// Get field value
$value = get_post_meta( $post_id, 'played', true );
$status = $value ? 'publish' : 'draft';
// If status should be different, change it
if ( get_post_status( $post_id ) != $status ) {
// unhook this function so it doesn't loop infinitely
remove_action( 'save_post', 'change_post_status_based_on_custom_field' );
// update the post, which calls save_post again
wp_update_post( array(
'ID' => $post_id,
'post_status' => $status
) );
// re-hook this function
add_action( 'save_post', 'change_post_status_based_on_custom_field' );
}
}
add_action( 'save_post', 'change_post_status_based_on_custom_field' );
``` |
320,781 | <p>I want to apply the AJAX feature to the WordPress custom theme for search. And I need to target the input using id and class.</p>
<p>I didn't find any tutorial on adding id to the premade WordPress search form. Remember you, I am talking about the <strong>get_search_form()</strong> function. </p>
<p>I want to modify its input and want to add class to it. How can I do that whether using <code>add_filter</code> or anything else. Thanks in advance.</p>
| [
{
"answer_id": 320789,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 3,
"selected": true,
"text": "<p>You can hook into the <code>get_search_form()</code>. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180\" rel=\"nofollow noreferrer\">WordPress Search Form Function Track</a></p>\n\n<pre><code>function custom_search_form( $form ) {\n $form = '<form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . home_url( '/' ) . '\" >\n <div class=\"custom-search-form\"><label class=\"screen-reader-text\" for=\"s\">' . __( 'Search:' ) . '</label>\n <input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr__( 'Search' ) .'\" />\n </div>\n </form>';\n\n return $form;\n}\n\nadd_filter( 'get_search_form', 'custom_search_form', 100 );\n</code></pre>\n"
},
{
"answer_id": 320800,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>Let's take a look at <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180\" rel=\"nofollow noreferrer\"><code>get_search_form</code> code</a>.</p>\n\n<pre><code>function get_search_form( $echo = true ) {\n\n ...\n\n $search_form_template = locate_template( 'searchform.php' );\n if ( '' != $search_form_template ) {\n ob_start();\n require( $search_form_template );\n $form = ob_get_clean();\n } else {\n if ( 'html5' == $format ) {\n $form = '<form role=\"search\" method=\"get\" class=\"search-form\" action=\"' . esc_url( home_url( '/' ) ) . '\">\n <label>\n <span class=\"screen-reader-text\">' . _x( 'Search for:', 'label' ) . '</span>\n <input type=\"search\" class=\"search-field\" placeholder=\"' . esc_attr_x( 'Search &hellip;', 'placeholder' ) . '\" value=\"' . get_search_query() . '\" name=\"s\" />\n </label>\n <input type=\"submit\" class=\"search-submit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" />\n </form>';\n } else {\n $form = '<form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . esc_url( home_url( '/' ) ) . '\">\n <div>\n <label class=\"screen-reader-text\" for=\"s\">' . _x( 'Search for:', 'label' ) . '</label>\n <input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" />\n </div>\n </form>';\n }\n }\n\n ....\n\n $result = apply_filters( 'get_search_form', $form );\n\n if ( null === $result )\n $result = $form;\n\n if ( $echo )\n echo $result;\n else\n return $result;\n}\n</code></pre>\n\n<p>As you can see, there is <code>get_search_form</code> filter called just before returning/printing the form, so you can use it to add classes/ids to the form.</p>\n\n<p>There is one catch though... The code of the form may look in different ways. In the code above you already see 2 versions (html and html5), but the form may also be coded using template file... So it can be a little bit tricky...</p>\n\n<p>But still... Add your filter, check if the class attr exists, and change it, or add it...</p>\n"
}
]
| 2018/12/02 | [
"https://wordpress.stackexchange.com/questions/320781",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149333/"
]
| I want to apply the AJAX feature to the WordPress custom theme for search. And I need to target the input using id and class.
I didn't find any tutorial on adding id to the premade WordPress search form. Remember you, I am talking about the **get\_search\_form()** function.
I want to modify its input and want to add class to it. How can I do that whether using `add_filter` or anything else. Thanks in advance. | You can hook into the `get_search_form()`. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.
[WordPress Search Form Function Track](https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180)
```
function custom_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
<div class="custom-search-form"><label class="screen-reader-text" for="s">' . __( 'Search:' ) . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />
</div>
</form>';
return $form;
}
add_filter( 'get_search_form', 'custom_search_form', 100 );
``` |
320,836 | <p>Before I start, I have to say that I have tried to solve my problem in a thousand different ways and I have read several posts without success.</p>
<p>I have a CPT called "grouped", a taxonomy for that CPT called "orders" and within the WordPress panel I have created several "categories" within orders (terms).</p>
<p>I have a term called "Madrid", and I want to show the post of that term on a page-template. How can I do it? It is killing me literally.</p>
<p>I appreciate your help.</p>
<p>-- This is the loop and the code I used in a normal "taxonomy-template.php" and its work fine, but now I need to show the same information but only showing the post associated with the term "Madrid" in a page template.</p>
<pre><code><?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php
$full = get_the_post_thumbnail_url(get_the_ID(),'full');
$large = get_the_post_thumbnail_url(get_the_ID(),'large');
$medium = get_the_post_thumbnail_url(get_the_ID(),'medium');
$thumbnail = get_the_post_thumbnail_url(get_the_ID(),'thumbnail');
?>
<div class="col col-md-flex-6 col-lg-flex-3 ">
<picture class="cat-agrupados-img">
<source media="(min-width: 768px)" srcset="<?php echo esc_url($thumbail); ?>">
<img src="<?php echo esc_url($medium);?>" alt="<?php the_title(); ?>">
</picture>
<h2 class="cat-agrupados-titulo-pedido">Pedido agrupado en <?php the_title(); ?></h2>
<p class="cat-fecha-publicacion">Fecha de publicación: <strong><?php the_date(); ?></strong></p>
<p class="cat-agrupados-zona">Zonas: <strong><?php echo get_post_meta( get_the_ID(), 'yourprefix_agrupados_poblaciones', true ); ?></strong></p>
<a href="<?php the_permalink(); ?>" class="cat-agrupados-link">Ver pedido agrupado</a>
</div> <!--cierre columna-->
<?php endwhile; endif; ?>
</code></pre>
| [
{
"answer_id": 320789,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 3,
"selected": true,
"text": "<p>You can hook into the <code>get_search_form()</code>. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180\" rel=\"nofollow noreferrer\">WordPress Search Form Function Track</a></p>\n\n<pre><code>function custom_search_form( $form ) {\n $form = '<form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . home_url( '/' ) . '\" >\n <div class=\"custom-search-form\"><label class=\"screen-reader-text\" for=\"s\">' . __( 'Search:' ) . '</label>\n <input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr__( 'Search' ) .'\" />\n </div>\n </form>';\n\n return $form;\n}\n\nadd_filter( 'get_search_form', 'custom_search_form', 100 );\n</code></pre>\n"
},
{
"answer_id": 320800,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>Let's take a look at <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180\" rel=\"nofollow noreferrer\"><code>get_search_form</code> code</a>.</p>\n\n<pre><code>function get_search_form( $echo = true ) {\n\n ...\n\n $search_form_template = locate_template( 'searchform.php' );\n if ( '' != $search_form_template ) {\n ob_start();\n require( $search_form_template );\n $form = ob_get_clean();\n } else {\n if ( 'html5' == $format ) {\n $form = '<form role=\"search\" method=\"get\" class=\"search-form\" action=\"' . esc_url( home_url( '/' ) ) . '\">\n <label>\n <span class=\"screen-reader-text\">' . _x( 'Search for:', 'label' ) . '</span>\n <input type=\"search\" class=\"search-field\" placeholder=\"' . esc_attr_x( 'Search &hellip;', 'placeholder' ) . '\" value=\"' . get_search_query() . '\" name=\"s\" />\n </label>\n <input type=\"submit\" class=\"search-submit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" />\n </form>';\n } else {\n $form = '<form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . esc_url( home_url( '/' ) ) . '\">\n <div>\n <label class=\"screen-reader-text\" for=\"s\">' . _x( 'Search for:', 'label' ) . '</label>\n <input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" />\n </div>\n </form>';\n }\n }\n\n ....\n\n $result = apply_filters( 'get_search_form', $form );\n\n if ( null === $result )\n $result = $form;\n\n if ( $echo )\n echo $result;\n else\n return $result;\n}\n</code></pre>\n\n<p>As you can see, there is <code>get_search_form</code> filter called just before returning/printing the form, so you can use it to add classes/ids to the form.</p>\n\n<p>There is one catch though... The code of the form may look in different ways. In the code above you already see 2 versions (html and html5), but the form may also be coded using template file... So it can be a little bit tricky...</p>\n\n<p>But still... Add your filter, check if the class attr exists, and change it, or add it...</p>\n"
}
]
| 2018/12/02 | [
"https://wordpress.stackexchange.com/questions/320836",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155139/"
]
| Before I start, I have to say that I have tried to solve my problem in a thousand different ways and I have read several posts without success.
I have a CPT called "grouped", a taxonomy for that CPT called "orders" and within the WordPress panel I have created several "categories" within orders (terms).
I have a term called "Madrid", and I want to show the post of that term on a page-template. How can I do it? It is killing me literally.
I appreciate your help.
-- This is the loop and the code I used in a normal "taxonomy-template.php" and its work fine, but now I need to show the same information but only showing the post associated with the term "Madrid" in a page template.
```
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php
$full = get_the_post_thumbnail_url(get_the_ID(),'full');
$large = get_the_post_thumbnail_url(get_the_ID(),'large');
$medium = get_the_post_thumbnail_url(get_the_ID(),'medium');
$thumbnail = get_the_post_thumbnail_url(get_the_ID(),'thumbnail');
?>
<div class="col col-md-flex-6 col-lg-flex-3 ">
<picture class="cat-agrupados-img">
<source media="(min-width: 768px)" srcset="<?php echo esc_url($thumbail); ?>">
<img src="<?php echo esc_url($medium);?>" alt="<?php the_title(); ?>">
</picture>
<h2 class="cat-agrupados-titulo-pedido">Pedido agrupado en <?php the_title(); ?></h2>
<p class="cat-fecha-publicacion">Fecha de publicación: <strong><?php the_date(); ?></strong></p>
<p class="cat-agrupados-zona">Zonas: <strong><?php echo get_post_meta( get_the_ID(), 'yourprefix_agrupados_poblaciones', true ); ?></strong></p>
<a href="<?php the_permalink(); ?>" class="cat-agrupados-link">Ver pedido agrupado</a>
</div> <!--cierre columna-->
<?php endwhile; endif; ?>
``` | You can hook into the `get_search_form()`. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.
[WordPress Search Form Function Track](https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180)
```
function custom_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
<div class="custom-search-form"><label class="screen-reader-text" for="s">' . __( 'Search:' ) . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />
</div>
</form>';
return $form;
}
add_filter( 'get_search_form', 'custom_search_form', 100 );
``` |
320,841 | <p>Say a site has a category structure like:</p>
<ul>
<li>Dogs</li>
<li><ul>
<li>Boxer</li>
</ul></li>
<li><ul>
<li><ul>
<li>Fawn</li>
</ul></li>
</ul></li>
<li><ul>
<li><ul>
<li>Brindle</li>
</ul></li>
</ul></li>
<li><ul>
<li>Rottweiler</li>
</ul></li>
<li>Cats</li>
<li><ul>
<li>Calico </li>
</ul></li>
<li><ul>
<li>Siamese</li>
</ul></li>
</ul>
<p>Using it shows that and adds classes so that you can style it accordingly such as making sure sub levels are indented. </p>
<p>If you want to show just one hierarchy such as Dogs where the category Dogs is id 15 you could use:</p>
<pre><code> <?php wp_list_categories( array(
'title_li' => '',
'child_of' => 15,
) ); ?>
</code></pre>
<p>When doing that it does this however:</p>
<ul>
<li>Boxer</li>
<li>Brindle</li>
<li>Fawn</li>
<li>Rottweiler</li>
</ul>
<p>That is, it does show just the Dogs tree, but it doesn't add the children class to be able to indent sub categories accordingly and seems to order them all by name, rather than just top level name.</p>
<p>Should be: </p>
<ul>
<li>Boxer</li>
<li><ul>
<li>Fawn</li>
</ul></li>
<li><ul>
<li>Brindle</li>
</ul></li>
<li>Rottweiler</li>
</ul>
<p>Am I missing something? Also if there were a category under say Fawn, I don't want that level or any further depths to show. Tried using "depth => 2," and didn't work. Setting to 0 shows all, setting to any other number such as 1 or 2 such shows the lowest depth.</p>
| [
{
"answer_id": 320789,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 3,
"selected": true,
"text": "<p>You can hook into the <code>get_search_form()</code>. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180\" rel=\"nofollow noreferrer\">WordPress Search Form Function Track</a></p>\n\n<pre><code>function custom_search_form( $form ) {\n $form = '<form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . home_url( '/' ) . '\" >\n <div class=\"custom-search-form\"><label class=\"screen-reader-text\" for=\"s\">' . __( 'Search:' ) . '</label>\n <input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr__( 'Search' ) .'\" />\n </div>\n </form>';\n\n return $form;\n}\n\nadd_filter( 'get_search_form', 'custom_search_form', 100 );\n</code></pre>\n"
},
{
"answer_id": 320800,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>Let's take a look at <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180\" rel=\"nofollow noreferrer\"><code>get_search_form</code> code</a>.</p>\n\n<pre><code>function get_search_form( $echo = true ) {\n\n ...\n\n $search_form_template = locate_template( 'searchform.php' );\n if ( '' != $search_form_template ) {\n ob_start();\n require( $search_form_template );\n $form = ob_get_clean();\n } else {\n if ( 'html5' == $format ) {\n $form = '<form role=\"search\" method=\"get\" class=\"search-form\" action=\"' . esc_url( home_url( '/' ) ) . '\">\n <label>\n <span class=\"screen-reader-text\">' . _x( 'Search for:', 'label' ) . '</span>\n <input type=\"search\" class=\"search-field\" placeholder=\"' . esc_attr_x( 'Search &hellip;', 'placeholder' ) . '\" value=\"' . get_search_query() . '\" name=\"s\" />\n </label>\n <input type=\"submit\" class=\"search-submit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" />\n </form>';\n } else {\n $form = '<form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . esc_url( home_url( '/' ) ) . '\">\n <div>\n <label class=\"screen-reader-text\" for=\"s\">' . _x( 'Search for:', 'label' ) . '</label>\n <input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" />\n </div>\n </form>';\n }\n }\n\n ....\n\n $result = apply_filters( 'get_search_form', $form );\n\n if ( null === $result )\n $result = $form;\n\n if ( $echo )\n echo $result;\n else\n return $result;\n}\n</code></pre>\n\n<p>As you can see, there is <code>get_search_form</code> filter called just before returning/printing the form, so you can use it to add classes/ids to the form.</p>\n\n<p>There is one catch though... The code of the form may look in different ways. In the code above you already see 2 versions (html and html5), but the form may also be coded using template file... So it can be a little bit tricky...</p>\n\n<p>But still... Add your filter, check if the class attr exists, and change it, or add it...</p>\n"
}
]
| 2018/12/03 | [
"https://wordpress.stackexchange.com/questions/320841",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5465/"
]
| Say a site has a category structure like:
* Dogs
* + Boxer
* + - Fawn
* + - Brindle
* + Rottweiler
* Cats
* + Calico
* + Siamese
Using it shows that and adds classes so that you can style it accordingly such as making sure sub levels are indented.
If you want to show just one hierarchy such as Dogs where the category Dogs is id 15 you could use:
```
<?php wp_list_categories( array(
'title_li' => '',
'child_of' => 15,
) ); ?>
```
When doing that it does this however:
* Boxer
* Brindle
* Fawn
* Rottweiler
That is, it does show just the Dogs tree, but it doesn't add the children class to be able to indent sub categories accordingly and seems to order them all by name, rather than just top level name.
Should be:
* Boxer
* + Fawn
* + Brindle
* Rottweiler
Am I missing something? Also if there were a category under say Fawn, I don't want that level or any further depths to show. Tried using "depth => 2," and didn't work. Setting to 0 shows all, setting to any other number such as 1 or 2 such shows the lowest depth. | You can hook into the `get_search_form()`. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.
[WordPress Search Form Function Track](https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180)
```
function custom_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
<div class="custom-search-form"><label class="screen-reader-text" for="s">' . __( 'Search:' ) . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />
</div>
</form>';
return $form;
}
add_filter( 'get_search_form', 'custom_search_form', 100 );
``` |
320,845 | <p>I am creating a Wordpress site, but I have a problem with desktop version of Chrome and Opera - my header displays differently here (in all other browsers everything works just fine). </p>
<p>Here are screenshots showing what I mean:</p>
<p>Firefox: <a href="https://i.imgur.com/4U11dfN.png" rel="nofollow noreferrer">https://i.imgur.com/4U11dfN.png</a> (everything's fine)
Chrome (in Opera it looks the same): <a href="https://i.imgur.com/kkyeklc.jpg" rel="nofollow noreferrer">https://i.imgur.com/kkyeklc.jpg</a> (menu items are not aligned properly).</p>
<p>Here's my site: <a href="http://tophistorie.pl/" rel="nofollow noreferrer">http://tophistorie.pl/</a> </p>
<p>Do you guys have any ideas what could go wrong? I'm desperate for help - tried to figure it out for 2 hours.</p>
<p>Kacper</p>
| [
{
"answer_id": 320789,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 3,
"selected": true,
"text": "<p>You can hook into the <code>get_search_form()</code>. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180\" rel=\"nofollow noreferrer\">WordPress Search Form Function Track</a></p>\n\n<pre><code>function custom_search_form( $form ) {\n $form = '<form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . home_url( '/' ) . '\" >\n <div class=\"custom-search-form\"><label class=\"screen-reader-text\" for=\"s\">' . __( 'Search:' ) . '</label>\n <input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr__( 'Search' ) .'\" />\n </div>\n </form>';\n\n return $form;\n}\n\nadd_filter( 'get_search_form', 'custom_search_form', 100 );\n</code></pre>\n"
},
{
"answer_id": 320800,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>Let's take a look at <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180\" rel=\"nofollow noreferrer\"><code>get_search_form</code> code</a>.</p>\n\n<pre><code>function get_search_form( $echo = true ) {\n\n ...\n\n $search_form_template = locate_template( 'searchform.php' );\n if ( '' != $search_form_template ) {\n ob_start();\n require( $search_form_template );\n $form = ob_get_clean();\n } else {\n if ( 'html5' == $format ) {\n $form = '<form role=\"search\" method=\"get\" class=\"search-form\" action=\"' . esc_url( home_url( '/' ) ) . '\">\n <label>\n <span class=\"screen-reader-text\">' . _x( 'Search for:', 'label' ) . '</span>\n <input type=\"search\" class=\"search-field\" placeholder=\"' . esc_attr_x( 'Search &hellip;', 'placeholder' ) . '\" value=\"' . get_search_query() . '\" name=\"s\" />\n </label>\n <input type=\"submit\" class=\"search-submit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" />\n </form>';\n } else {\n $form = '<form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . esc_url( home_url( '/' ) ) . '\">\n <div>\n <label class=\"screen-reader-text\" for=\"s\">' . _x( 'Search for:', 'label' ) . '</label>\n <input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" />\n </div>\n </form>';\n }\n }\n\n ....\n\n $result = apply_filters( 'get_search_form', $form );\n\n if ( null === $result )\n $result = $form;\n\n if ( $echo )\n echo $result;\n else\n return $result;\n}\n</code></pre>\n\n<p>As you can see, there is <code>get_search_form</code> filter called just before returning/printing the form, so you can use it to add classes/ids to the form.</p>\n\n<p>There is one catch though... The code of the form may look in different ways. In the code above you already see 2 versions (html and html5), but the form may also be coded using template file... So it can be a little bit tricky...</p>\n\n<p>But still... Add your filter, check if the class attr exists, and change it, or add it...</p>\n"
}
]
| 2018/12/03 | [
"https://wordpress.stackexchange.com/questions/320845",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136124/"
]
| I am creating a Wordpress site, but I have a problem with desktop version of Chrome and Opera - my header displays differently here (in all other browsers everything works just fine).
Here are screenshots showing what I mean:
Firefox: <https://i.imgur.com/4U11dfN.png> (everything's fine)
Chrome (in Opera it looks the same): <https://i.imgur.com/kkyeklc.jpg> (menu items are not aligned properly).
Here's my site: <http://tophistorie.pl/>
Do you guys have any ideas what could go wrong? I'm desperate for help - tried to figure it out for 2 hours.
Kacper | You can hook into the `get_search_form()`. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.
[WordPress Search Form Function Track](https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180)
```
function custom_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
<div class="custom-search-form"><label class="screen-reader-text" for="s">' . __( 'Search:' ) . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />
</div>
</form>';
return $form;
}
add_filter( 'get_search_form', 'custom_search_form', 100 );
``` |
320,851 | <p>So, I'm using a wordpress theme (unfortunately, I'm not able to get support for the theme any longer), and it has a contact form that makes a direct ajax call to a php file in the theme's "includes" folder. However, all ajax calls to this file result in a 404 error. As a result, the contact form is not able to successfully post messages. </p>
<p>What server setting is most likely responsible for restricting public access to php files in the themes folder? </p>
| [
{
"answer_id": 320789,
"author": "Maqk",
"author_id": 86885,
"author_profile": "https://wordpress.stackexchange.com/users/86885",
"pm_score": 3,
"selected": true,
"text": "<p>You can hook into the <code>get_search_form()</code>. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180\" rel=\"nofollow noreferrer\">WordPress Search Form Function Track</a></p>\n\n<pre><code>function custom_search_form( $form ) {\n $form = '<form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . home_url( '/' ) . '\" >\n <div class=\"custom-search-form\"><label class=\"screen-reader-text\" for=\"s\">' . __( 'Search:' ) . '</label>\n <input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr__( 'Search' ) .'\" />\n </div>\n </form>';\n\n return $form;\n}\n\nadd_filter( 'get_search_form', 'custom_search_form', 100 );\n</code></pre>\n"
},
{
"answer_id": 320800,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>Let's take a look at <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180\" rel=\"nofollow noreferrer\"><code>get_search_form</code> code</a>.</p>\n\n<pre><code>function get_search_form( $echo = true ) {\n\n ...\n\n $search_form_template = locate_template( 'searchform.php' );\n if ( '' != $search_form_template ) {\n ob_start();\n require( $search_form_template );\n $form = ob_get_clean();\n } else {\n if ( 'html5' == $format ) {\n $form = '<form role=\"search\" method=\"get\" class=\"search-form\" action=\"' . esc_url( home_url( '/' ) ) . '\">\n <label>\n <span class=\"screen-reader-text\">' . _x( 'Search for:', 'label' ) . '</span>\n <input type=\"search\" class=\"search-field\" placeholder=\"' . esc_attr_x( 'Search &hellip;', 'placeholder' ) . '\" value=\"' . get_search_query() . '\" name=\"s\" />\n </label>\n <input type=\"submit\" class=\"search-submit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" />\n </form>';\n } else {\n $form = '<form role=\"search\" method=\"get\" id=\"searchform\" class=\"searchform\" action=\"' . esc_url( home_url( '/' ) ) . '\">\n <div>\n <label class=\"screen-reader-text\" for=\"s\">' . _x( 'Search for:', 'label' ) . '</label>\n <input type=\"text\" value=\"' . get_search_query() . '\" name=\"s\" id=\"s\" />\n <input type=\"submit\" id=\"searchsubmit\" value=\"'. esc_attr_x( 'Search', 'submit button' ) .'\" />\n </div>\n </form>';\n }\n }\n\n ....\n\n $result = apply_filters( 'get_search_form', $form );\n\n if ( null === $result )\n $result = $form;\n\n if ( $echo )\n echo $result;\n else\n return $result;\n}\n</code></pre>\n\n<p>As you can see, there is <code>get_search_form</code> filter called just before returning/printing the form, so you can use it to add classes/ids to the form.</p>\n\n<p>There is one catch though... The code of the form may look in different ways. In the code above you already see 2 versions (html and html5), but the form may also be coded using template file... So it can be a little bit tricky...</p>\n\n<p>But still... Add your filter, check if the class attr exists, and change it, or add it...</p>\n"
}
]
| 2018/12/03 | [
"https://wordpress.stackexchange.com/questions/320851",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155150/"
]
| So, I'm using a wordpress theme (unfortunately, I'm not able to get support for the theme any longer), and it has a contact form that makes a direct ajax call to a php file in the theme's "includes" folder. However, all ajax calls to this file result in a 404 error. As a result, the contact form is not able to successfully post messages.
What server setting is most likely responsible for restricting public access to php files in the themes folder? | You can hook into the `get_search_form()`. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.
[WordPress Search Form Function Track](https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/general-template.php#L180)
```
function custom_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
<div class="custom-search-form"><label class="screen-reader-text" for="s">' . __( 'Search:' ) . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />
</div>
</form>';
return $form;
}
add_filter( 'get_search_form', 'custom_search_form', 100 );
``` |
320,884 | <p>I'm trying to change the text in the 'Place order' button on my multilingual site in WooCommerce. My default lang is English US, other is Polish. I can easily modify the secondary language text via my WPML plugin, but I cannot change the default language.
I tried modifying the button text via a JS code which worked in the default EN page, but the Polish one started to display the new English text too. I also tried using Loco and adding English as a language, changed the English text - but that didn't work. How is this doable - to change text strings in default language and making them translatable via WPML in the same time?</p>
| [
{
"answer_id": 320898,
"author": "dado",
"author_id": 109316,
"author_profile": "https://wordpress.stackexchange.com/users/109316",
"pm_score": 0,
"selected": false,
"text": "<p>If you have static texts, which are hard-coded in the PHP, you can just use GetText calls, like:</p>\n\n<pre><code><?php __('Hello world','cool_theme'); ?>\n</code></pre>\n\n<p>WPML hooks to the GetText calls and makes these texts translatable via the String Translation interface. Please note that this method only works for texts that cannot be edited and are fixed in the theme.</p>\n"
},
{
"answer_id": 320910,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>You could use their filter to do this:</p>\n\n<pre><code>/* Add to the functions.php file of your theme */\n\nadd_filter( 'woocommerce_order_button_text', 'woo_custom_order_button_text' ); \n\nfunction woo_custom_order_button_text() {\n return __( 'Your new button text here', 'woocommerce' ); \n}\n</code></pre>\n"
}
]
| 2018/12/03 | [
"https://wordpress.stackexchange.com/questions/320884",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142331/"
]
| I'm trying to change the text in the 'Place order' button on my multilingual site in WooCommerce. My default lang is English US, other is Polish. I can easily modify the secondary language text via my WPML plugin, but I cannot change the default language.
I tried modifying the button text via a JS code which worked in the default EN page, but the Polish one started to display the new English text too. I also tried using Loco and adding English as a language, changed the English text - but that didn't work. How is this doable - to change text strings in default language and making them translatable via WPML in the same time? | You could use their filter to do this:
```
/* Add to the functions.php file of your theme */
add_filter( 'woocommerce_order_button_text', 'woo_custom_order_button_text' );
function woo_custom_order_button_text() {
return __( 'Your new button text here', 'woocommerce' );
}
``` |
320,964 | <p>I have a class "rty-downloads" I want this class to displayed only for WordPress login users, is that possible?</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 320966,
"author": "dado",
"author_id": 109316,
"author_profile": "https://wordpress.stackexchange.com/users/109316",
"pm_score": 0,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code> add_action( 'loop_start', 'your_function' );\n function your_function() {\n\n if ( is_user_logged_in() ) {\necho '<li id=\"text-2\" class=\"hide\">';\n} else {\necho '<li id=\"text-2\">'; \n}}\n</code></pre>\n"
},
{
"answer_id": 321009,
"author": "Sony ThePony",
"author_id": 145373,
"author_profile": "https://wordpress.stackexchange.com/users/145373",
"pm_score": 1,
"selected": false,
"text": "<p>Simplest solution: You can use pure css like so:</p>\n\n<pre><code>.button-class {display: none;}\n.logged-in .button-class {display: block;}\n</code></pre>\n"
},
{
"answer_id": 321010,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 3,
"selected": false,
"text": "<p>You can use this on any WordPress page / template.</p>\n\n<pre><code><?php if ( is_user_logged_in() ) : ?>\n //Code for only logged in users\n<?php endif; ?>\n</code></pre>\n\n<p>Checkout the docs for more info: <a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/is_user_logged_in/</a></p>\n"
},
{
"answer_id": 352241,
"author": "Johnymas",
"author_id": 178104,
"author_profile": "https://wordpress.stackexchange.com/users/178104",
"pm_score": 1,
"selected": false,
"text": "<p>For me only works</p>\n\n<pre><code>/* show blog button only if logged in */\nli.button-class {\n visibility: hidden !important;\n display: none !important;\n}\n.logged-in li.button-class { \n visibility: visible !important;\n display: inline-block !important;\n}\n</code></pre>\n"
},
{
"answer_id": 393854,
"author": "Bandi",
"author_id": 210754,
"author_profile": "https://wordpress.stackexchange.com/users/210754",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I use:</p>\n<p><strong>functions.php</strong> (in child theme):</p>\n<pre><code>add_action('shutdown', function() {\n $final = '';\n $levels = ob_get_level();\n for ($i = 0; $i < $levels; $i++)\n {\n $final .= ob_get_clean();\n }\n echo apply_filters('final_output', $final);\n}, 0);\n\nadd_filter('final_output', function($output) {\n $display1 = 'none';\n $display2 = 'block';\n\n if(is_user_logged_in()) {\n $display1 = 'block';\n $display2 = 'none';\n }\n\n $from = array('%display1%', '%display2%');\n $to = array($display1, $display2);\n $output = str_replace($from,$to,$output);\n\n return $output;\n});\n</code></pre>\n<p><strong>CSS:</strong></p>\n<pre><code>.for-logged-in-users {\ndisplay: %display1%;\n}\n.for-logged-out-users {\ndisplay: %display2%;\n}\n</code></pre>\n<p>Then you can just add these two class names for the elements that you want to display/hide.\nThis way you can display/hide any elements based on any logic.</p>\n"
}
]
| 2018/12/04 | [
"https://wordpress.stackexchange.com/questions/320964",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102195/"
]
| I have a class "rty-downloads" I want this class to displayed only for WordPress login users, is that possible?
Thanks in advance | You can use this on any WordPress page / template.
```
<?php if ( is_user_logged_in() ) : ?>
//Code for only logged in users
<?php endif; ?>
```
Checkout the docs for more info: <https://developer.wordpress.org/reference/functions/is_user_logged_in/> |
320,979 | <p>I am building a plugin and I want to add some settings which rely on checkboxes.
I know how to get data from the checkbox in PHP but got stuck in WordPress. Because we have no option to add the name attribute to the checkbox. for example, I am adding a checkbox in the customizer.</p>
<pre><code>$wp_customize->add_setting('ion', array(
'sanitize_callback' => 'ion_checkbox'
));
$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'ion', array(
'label' => 'Check',
'type' => 'checkbox',
'section' => 'search_submit_section',
'settings' => 'ion'
)));
</code></pre>
<p>As we see there is no option to add name attribute. How we will know whether the user has checked the checkbox or not. I hope you understand my question. </p>
| [
{
"answer_id": 320980,
"author": "dado",
"author_id": 109316,
"author_profile": "https://wordpress.stackexchange.com/users/109316",
"pm_score": 0,
"selected": false,
"text": "<p>Sanitizing a checkbox is quite easy. Since the checkbox value is either true or false (1 or 0), you simply need to return one of these values. A simple function can be written that tests if the checkbox has been set, and if so, it returns 1 otherwise it returns 0.</p>\n\n<pre><code> function mytheme_chkbox_sanitization( $input ) {\nif ( true === $input ) {\n return 1;\n } else {\n return 0;\n }\n}\n</code></pre>\n\n<p>When creating the Setting for your Checkbox, pass the name of this function \n to the sanitize_callback argument.</p>\n\n<pre><code> $wp_customize->add_setting( 'sample_default_checkbox',\n array(\n 'default' => 0,\n 'sanitize_callback' => 'mytheme_chkbox_sanitization',\n )\n);\n</code></pre>\n"
},
{
"answer_id": 404235,
"author": "Meraj",
"author_id": 214012,
"author_profile": "https://wordpress.stackexchange.com/users/214012",
"pm_score": 1,
"selected": false,
"text": "<p>It has been quite some time, but you can simply check if the mod value is <code>true</code> or <code>false</code>.</p>\n<pre><code> <?php\n if( get_theme_mod('ion') == true ){\n //your html\n }\n ?>\n</code></pre>\n"
}
]
| 2018/12/04 | [
"https://wordpress.stackexchange.com/questions/320979",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149333/"
]
| I am building a plugin and I want to add some settings which rely on checkboxes.
I know how to get data from the checkbox in PHP but got stuck in WordPress. Because we have no option to add the name attribute to the checkbox. for example, I am adding a checkbox in the customizer.
```
$wp_customize->add_setting('ion', array(
'sanitize_callback' => 'ion_checkbox'
));
$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'ion', array(
'label' => 'Check',
'type' => 'checkbox',
'section' => 'search_submit_section',
'settings' => 'ion'
)));
```
As we see there is no option to add name attribute. How we will know whether the user has checked the checkbox or not. I hope you understand my question. | It has been quite some time, but you can simply check if the mod value is `true` or `false`.
```
<?php
if( get_theme_mod('ion') == true ){
//your html
}
?>
``` |
321,018 | <p>I'm currently trying to unset a session variable in WordPress if the page get's reloaded. I've tried a lot but it's not working like I want it. This is my function:</p>
<pre><code>/**
* Unset filter session if page get's reloaded
*/
add_action( 'wp', 'unset_filter_session' );
function unset_filter_session() {
//Reset sessions on refresh page
unset( $_SESSION['expenditure_filter'] );
}
</code></pre>
<p>It's working but it's working too good. Because when I reload the <code>content-area</code> in WordPress via AJAX, the session get's unset too which should be avoided:</p>
<pre><code>jQuery('#content-area').load(location.href + ' #content-area>*', '');
</code></pre>
<p>So how can I do the unset of the session just on page load and exclude AJAX reloads?</p>
| [
{
"answer_id": 321019,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>Try using <a href=\"https://developer.wordpress.org/reference/functions/wp_doing_ajax/\" rel=\"nofollow noreferrer\"><code>wp_doing_ajax()</code></a> like so:</p>\n\n<pre><code>function unset_filter_session() {\n if ( ! wp_doing_ajax() ) {\n //Reset sessions on refresh page\n unset( $_SESSION['expenditure_filter'] );\n }\n}\n</code></pre>\n\n<h2>UPDATE</h2>\n\n<p><em>You can check the answer's revision for this update part..</em></p>\n\n<h2>UPDATE #2</h2>\n\n<p>Sorry, I didn't realize that you're loading a page fragment (<code>#content-area</code>) using the <a href=\"http://api.jquery.com/load/\" rel=\"nofollow noreferrer\"><code>jQuery.load()</code></a> method. Or that you're not using the <code>admin-ajax.php</code> to handle the AJAX request.</p>\n\n<p>So if you're <em>not</em> using the <a href=\"https://developer.wordpress.org/reference/hooks/wp_ajax__requestaction/\" rel=\"nofollow noreferrer\"><code>wp_ajax_{action}</code></a> or <a href=\"https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/\" rel=\"nofollow noreferrer\"><code>wp_ajax_nopriv_{action}</code></a> action, or with the way you do the AJAX request, you can check whether the <code>X-Requested-With</code> header is set and that its value is <code>XMLHttpRequest</code>, and if so, you can cancel the session unsetting, like so:</p>\n\n<pre><code>function unset_filter_session() {\n if ( empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ||\n 'XMLHttpRequest' !== $_SERVER['HTTP_X_REQUESTED_WITH'] ) {\n //Reset sessions on refresh page, if not doing AJAX request\n unset( $_SESSION['expenditure_filter'] );\n }\n}\n</code></pre>\n\n<p>That should work because jQuery always sets that header, unless you explicitly remove it — or change its value.</p>\n\n<p>See the <code>headers</code> option on the <code>jQuery.ajax()</code> <a href=\"http://api.jquery.com/jquery.ajax/\" rel=\"nofollow noreferrer\">reference</a>:</p>\n\n<blockquote>\n <p>The header <code>X-Requested-With: XMLHttpRequest</code> is always added, but its\n default <code>XMLHttpRequest</code> value can be changed</p>\n</blockquote>\n\n<p><strong>Note: The header name is <code>X-Requested-With</code>, but in the superglobal <code>$_SERVER</code>, its key is <code>HTTP_X_REQUESTED_WITH</code>. I.e. <em>Don't</em> use <code>$_SERVER['X-Requested-With']</code>.</strong></p>\n\n<h2>UPDATE #3</h2>\n\n<p>As suggested by <a href=\"https://wordpress.stackexchange.com/users/22714/lawrence-johnson\">Lawrence Johnson</a>, you (ahem, we) should use <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow noreferrer\"><code>filter_input()</code></a>:</p>\n\n<pre><code>function unset_filter_session() {\n if ( 'XMLHttpRequest' !== filter_input( INPUT_SERVER, 'HTTP_X_REQUESTED_WITH' ) ) {\n //Reset sessions on refresh page, if not doing AJAX request\n unset( $_SESSION['expenditure_filter'] );\n }\n}\n</code></pre>\n\n<p>(but I kept the previous code for reference)</p>\n"
},
{
"answer_id": 321036,
"author": "Lawrence Johnson",
"author_id": 22714,
"author_profile": "https://wordpress.stackexchange.com/users/22714",
"pm_score": 0,
"selected": false,
"text": "<p>One thing you could consider doing is adding a header variable to your AJAX requests. Even a <code>GET</code> or <code>POST</code> param would likely to the trick. Perhaps something like this:</p>\n\n<pre><code>/**\n * Unset filter session if page get's reloaded\n */\nadd_action( 'wp', 'unset_filter_session' );\nfunction unset_filter_session() {\n //Reset sessions on refresh page\n if (!filter_input(INPUT_POST, 'isContentLoader', FILTER_SANITIZE_NUMBER_INT)) {\n unset( $_SESSION['expenditure_filter'] );\n }\n}\n</code></pre>\n\n<p>And then</p>\n\n<pre><code>jQuery('#content-area').load(location.href + ' #content-area>*', { isContentLoader: 1 });\n</code></pre>\n"
}
]
| 2018/12/05 | [
"https://wordpress.stackexchange.com/questions/321018",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151233/"
]
| I'm currently trying to unset a session variable in WordPress if the page get's reloaded. I've tried a lot but it's not working like I want it. This is my function:
```
/**
* Unset filter session if page get's reloaded
*/
add_action( 'wp', 'unset_filter_session' );
function unset_filter_session() {
//Reset sessions on refresh page
unset( $_SESSION['expenditure_filter'] );
}
```
It's working but it's working too good. Because when I reload the `content-area` in WordPress via AJAX, the session get's unset too which should be avoided:
```
jQuery('#content-area').load(location.href + ' #content-area>*', '');
```
So how can I do the unset of the session just on page load and exclude AJAX reloads? | Try using [`wp_doing_ajax()`](https://developer.wordpress.org/reference/functions/wp_doing_ajax/) like so:
```
function unset_filter_session() {
if ( ! wp_doing_ajax() ) {
//Reset sessions on refresh page
unset( $_SESSION['expenditure_filter'] );
}
}
```
UPDATE
------
*You can check the answer's revision for this update part..*
UPDATE #2
---------
Sorry, I didn't realize that you're loading a page fragment (`#content-area`) using the [`jQuery.load()`](http://api.jquery.com/load/) method. Or that you're not using the `admin-ajax.php` to handle the AJAX request.
So if you're *not* using the [`wp_ajax_{action}`](https://developer.wordpress.org/reference/hooks/wp_ajax__requestaction/) or [`wp_ajax_nopriv_{action}`](https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/) action, or with the way you do the AJAX request, you can check whether the `X-Requested-With` header is set and that its value is `XMLHttpRequest`, and if so, you can cancel the session unsetting, like so:
```
function unset_filter_session() {
if ( empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ||
'XMLHttpRequest' !== $_SERVER['HTTP_X_REQUESTED_WITH'] ) {
//Reset sessions on refresh page, if not doing AJAX request
unset( $_SESSION['expenditure_filter'] );
}
}
```
That should work because jQuery always sets that header, unless you explicitly remove it — or change its value.
See the `headers` option on the `jQuery.ajax()` [reference](http://api.jquery.com/jquery.ajax/):
>
> The header `X-Requested-With: XMLHttpRequest` is always added, but its
> default `XMLHttpRequest` value can be changed
>
>
>
**Note: The header name is `X-Requested-With`, but in the superglobal `$_SERVER`, its key is `HTTP_X_REQUESTED_WITH`. I.e. *Don't* use `$_SERVER['X-Requested-With']`.**
UPDATE #3
---------
As suggested by [Lawrence Johnson](https://wordpress.stackexchange.com/users/22714/lawrence-johnson), you (ahem, we) should use [`filter_input()`](http://php.net/manual/en/function.filter-input.php):
```
function unset_filter_session() {
if ( 'XMLHttpRequest' !== filter_input( INPUT_SERVER, 'HTTP_X_REQUESTED_WITH' ) ) {
//Reset sessions on refresh page, if not doing AJAX request
unset( $_SESSION['expenditure_filter'] );
}
}
```
(but I kept the previous code for reference) |
321,078 | <p>As the 5.0 is getting real, and so is Gutenberg...</p>
<p>Is it possible to disable Gutenberg and use previous TinyMCE editor?</p>
<p>How to do this?</p>
| [
{
"answer_id": 321079,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, you can disable it.</p>\n\n<h2>You can do this with code</h2>\n\n<p>If you want to disable it globally, you can use this code:</p>\n\n<pre><code>if ( version_compare($GLOBALS['wp_version'], '5.0-beta', '>') ) {\n // WP > 5 beta\n add_filter( 'use_block_editor_for_post_type', '__return_false', 100 );\n} else {\n // WP < 5 beta\n add_filter( 'gutenberg_can_edit_post_type', '__return_false' );\n}\n</code></pre>\n\n<p>And if you want to disable it only for given post type, you can use:</p>\n\n<pre><code>function my_disable_gutenberg_for_post_type( $is_enabled, $post_type ) {\n if ( 'page' == $post_type ) { // disable for pages, change 'page' to you CPT slug\n return false;\n }\n\n return $is_enabled;\n}\nif ( version_compare($GLOBALS['wp_version'], '5.0-beta', '>') ) {\n // WP > 5 beta\n add_filter( 'use_block_editor_for_post_type', 'my_disable_gutenberg_for_post_type', 10, 2 );\n} else {\n // WP < 5 beta\n add_filter( 'gutenberg_can_edit_post_type', 'my_disable_gutenberg_for_post_type', 10, 2 );\n}\n</code></pre>\n\n<p>PS. If you don't want to support older versions, you can ignore filters beginning with 'gutenberg_', so no version checking is needed in such case.</p>\n\n<h2>Or using one of existing plugins</h2>\n\n<ol>\n<li><a href=\"https://wordpress.org/plugins/classic-editor/\" rel=\"nofollow noreferrer\">Classic Editor</a></li>\n<li><a href=\"https://wordpress.org/plugins/disable-gutenberg/\" rel=\"nofollow noreferrer\">Disable Gutenberg</a></li>\n<li><a href=\"https://wordpress.org/plugins/guten-free-options/\" rel=\"nofollow noreferrer\">Guten Free Options</a></li>\n<li><a href=\"https://wordpress.org/plugins/gutenberg-ramp/\" rel=\"nofollow noreferrer\">Gutenberg Ramp</a></li>\n</ol>\n"
},
{
"answer_id": 321151,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Generally the answer is no. Gutenberg stores content in a different format than how the pre 5.0 editor did. YMMV significantly if you try to disable gutenberg after content was already created, things might work for core blocks, but blocks created by plugins, who knows.</p>\n\n<p>Now if the question is about disabling before having any content edited in gutenberg, then you have a better chance with the other answers, but this is going to be a short term bandaid fix and is not a long term proper strategy. \nIn the long term all those options are not going to be tested against or just bit rot. And on top of that you might have a limited selection of themes and plugins you can work with.</p>\n\n<p>5.0 have already hard coded gutenberging of sample content. you are not going to escape the need to use it by hacks.</p>\n\n<p>If you want to use WordPress you should embrace its core features, and you do not want to build technical debt and be forced to migrate to gutenberg on a rush. It is better to just do it once it stabilizes and get done with it.</p>\n\n<p>If you do not want to embrace WordPress core features, why do you use it?</p>\n"
},
{
"answer_id": 323935,
"author": "dragoweb",
"author_id": 99073,
"author_profile": "https://wordpress.stackexchange.com/users/99073",
"pm_score": 2,
"selected": false,
"text": "<p>I just added this in my function.php and it works great</p>\n\n<pre><code>add_filter('use_block_editor_for_post', '__return_false');\n</code></pre>\n"
},
{
"answer_id": 325716,
"author": "Abhijeet Kumar",
"author_id": 149045,
"author_profile": "https://wordpress.stackexchange.com/users/149045",
"pm_score": 1,
"selected": false,
"text": "<p>You can disable Gutenberg by installing the Classic Editor plugin \n<a href=\"https://wordpress.org/plugins/classic-editor/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/classic-editor/</a>\nThis will disable the Gutenberg Editor.</p>\n\n<p>Thanks</p>\n"
}
]
| 2018/12/05 | [
"https://wordpress.stackexchange.com/questions/321078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34172/"
]
| As the 5.0 is getting real, and so is Gutenberg...
Is it possible to disable Gutenberg and use previous TinyMCE editor?
How to do this? | Yes, you can disable it.
You can do this with code
-------------------------
If you want to disable it globally, you can use this code:
```
if ( version_compare($GLOBALS['wp_version'], '5.0-beta', '>') ) {
// WP > 5 beta
add_filter( 'use_block_editor_for_post_type', '__return_false', 100 );
} else {
// WP < 5 beta
add_filter( 'gutenberg_can_edit_post_type', '__return_false' );
}
```
And if you want to disable it only for given post type, you can use:
```
function my_disable_gutenberg_for_post_type( $is_enabled, $post_type ) {
if ( 'page' == $post_type ) { // disable for pages, change 'page' to you CPT slug
return false;
}
return $is_enabled;
}
if ( version_compare($GLOBALS['wp_version'], '5.0-beta', '>') ) {
// WP > 5 beta
add_filter( 'use_block_editor_for_post_type', 'my_disable_gutenberg_for_post_type', 10, 2 );
} else {
// WP < 5 beta
add_filter( 'gutenberg_can_edit_post_type', 'my_disable_gutenberg_for_post_type', 10, 2 );
}
```
PS. If you don't want to support older versions, you can ignore filters beginning with 'gutenberg\_', so no version checking is needed in such case.
Or using one of existing plugins
--------------------------------
1. [Classic Editor](https://wordpress.org/plugins/classic-editor/)
2. [Disable Gutenberg](https://wordpress.org/plugins/disable-gutenberg/)
3. [Guten Free Options](https://wordpress.org/plugins/guten-free-options/)
4. [Gutenberg Ramp](https://wordpress.org/plugins/gutenberg-ramp/) |
321,084 | <p>I need to update date and time when I save posts.
I see the code on the following thread, but I need to have this trick only for posts contained in my custom post 'new_cpt'</p>
<p>Is it possible?</p>
<p>ref: <a href="https://wordpress.stackexchange.com/questions/121565/update-post-date-to-modified-date-automatically">Update post date to modified date automatically</a></p>
| [
{
"answer_id": 321085,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it is possible. All you have to do is to check the post type before you update dates:</p>\n\n<pre><code>function reset_post_date_wpse_321084( $data, $postarr ) {\n if ( array_key_exists('ID', $postarr) ) {\n $post_id = $postarr['ID'];\n\n if ( 'new_cpt' == get_post_type( $post_id ) ) {\n $data['post_date'] = $data['post_modified'];\n $data['post_date_gmt'] = $data['post_modified_gmt'];\n }\n }\n\n return $data;\n}\nadd_filter( 'wp_insert_post_data','reset_post_date_wpse_321084', 99, 2 );\n</code></pre>\n"
},
{
"answer_id": 321086,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": false,
"text": "<p>Using your example link, I just added an IF to check for post_type.</p>\n\n<pre><code>function reset_post_date_wpse_121565($data,$postarr) {\n // var_dump($data,$postarr); die;// debug\n if($data['post_type'] == 'new_cpt'){\n $data['post_date'] = $data['post_modified'];\n $data['post_date_gmt'] = $data['post_modified_gmt'];\n return $data;\n } \n}\nadd_filter('wp_insert_post_data','reset_post_date_wpse_121565',99,2);\n</code></pre>\n"
}
]
| 2018/12/05 | [
"https://wordpress.stackexchange.com/questions/321084",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134550/"
]
| I need to update date and time when I save posts.
I see the code on the following thread, but I need to have this trick only for posts contained in my custom post 'new\_cpt'
Is it possible?
ref: [Update post date to modified date automatically](https://wordpress.stackexchange.com/questions/121565/update-post-date-to-modified-date-automatically) | Using your example link, I just added an IF to check for post\_type.
```
function reset_post_date_wpse_121565($data,$postarr) {
// var_dump($data,$postarr); die;// debug
if($data['post_type'] == 'new_cpt'){
$data['post_date'] = $data['post_modified'];
$data['post_date_gmt'] = $data['post_modified_gmt'];
return $data;
}
}
add_filter('wp_insert_post_data','reset_post_date_wpse_121565',99,2);
``` |
321,095 | <p>I would appreciate any help. I have set a contact form up and want to show a button to download a file once the form is submitted. This is showing all the time and should be hidden until the form is filled in.</p>
<pre><code> <div class="visible-only-if-sent">
<a href="demo.ogi.co.uk/download/1323" class="button big_large_full_width center default">Download CVM10-Lite
</a>
</div>
</code></pre>
<p>But it is still showing on the page all the time. Can you please help me if I'm doing something wrong somewhere?</p>
| [
{
"answer_id": 321098,
"author": "dado",
"author_id": 109316,
"author_profile": "https://wordpress.stackexchange.com/users/109316",
"pm_score": 1,
"selected": false,
"text": "<p>You can add listener on submit ..something like this:</p>\n\n<pre><code> document.addEventListener( 'wpcf7submit', function( event ) \n\n{ if ( '123' == event.detail.contactFormId ) \n\n { alert( \"The contact form ID is 123.\" ); // do something productive } }, \n\n false );\n</code></pre>\n"
},
{
"answer_id": 372645,
"author": "pensebien",
"author_id": 189698,
"author_profile": "https://wordpress.stackexchange.com/users/189698",
"pm_score": 0,
"selected": false,
"text": "<p>Using JS,\nYou can add an event listener that listens for when the CF7 form is submitted and add the class "visible-only-if-sent" to the element in the DOM.</p>\n<p>Register your script in the <code>function.php</code> file in your Theme folder.</p>\n<p>function.php</p>\n<pre><code>wp_enqueue_script( 'js-file', get_template_directory_uri() . '/js/show-button.js');\n</code></pre>\n<p>Theme folder\nTheme/JS/show-button.js</p>\n<p>show-button.js</p>\n<pre><code> document.addEventListener( 'wpcf7submit', function( event ) \n { \n var button_clicked = document.getElementsByClassName("download-file"); \n button_clicked.classList.add("visible-only-if-sent");\n }, \n\n false );\n\n \n</code></pre>\n<p>Template file</p>\n<pre><code><div class="download-file"> \n <a href="demo.ogi.co.uk/download/1323" class="button big_large_full_width center default">Download CVM10-Lite\n </a> \n</div>\n</code></pre>\n"
},
{
"answer_id": 403539,
"author": "Mandeep Test",
"author_id": 220089,
"author_profile": "https://wordpress.stackexchange.com/users/220089",
"pm_score": 0,
"selected": false,
"text": "<p>Use This Code\nThis code work after completly submitting form 'wpcf7mailsent'</p>\n<pre><code><script>\ndocument.addEventListener( 'wpcf7mailsent', function( event ) \n\n { \n<!-- write whatever you want -->\n let btn = document.getElementById('show_pdf');\n btn.style.display = "block"; \n }, \n false );\n</script>\n</code></pre>\n"
}
]
| 2018/12/05 | [
"https://wordpress.stackexchange.com/questions/321095",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155342/"
]
| I would appreciate any help. I have set a contact form up and want to show a button to download a file once the form is submitted. This is showing all the time and should be hidden until the form is filled in.
```
<div class="visible-only-if-sent">
<a href="demo.ogi.co.uk/download/1323" class="button big_large_full_width center default">Download CVM10-Lite
</a>
</div>
```
But it is still showing on the page all the time. Can you please help me if I'm doing something wrong somewhere? | You can add listener on submit ..something like this:
```
document.addEventListener( 'wpcf7submit', function( event )
{ if ( '123' == event.detail.contactFormId )
{ alert( "The contact form ID is 123." ); // do something productive } },
false );
``` |
321,221 | <p>I'd like to be able to edit the description/help text that appears beneath the field in the CMS page editor for a custom post type.</p>
<p>I know I can change the name and button/link text by passing items into the <code>labels</code> array in register post type.</p>
<pre><code>'featured_image' => __('Foo'),
'set_featured_image' => __('Set Foo'),
'remove_featured_image' => __('Remove Foo'),
'use_featured_image' => __('Use as Foo')
</code></pre>
<p>But is there a way to add to edit the help text that displays beneath the field? It says "Click the image to edit or update" if an image is selected. I'd like to add further instructions as to precisely what kind of image to use.</p>
<p>Ideally this text should appear before an image is selected as well as after. But I'd settle for being able to edit the text that shows after.</p>
| [
{
"answer_id": 321222,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": false,
"text": "<h3>The following will add help text to the initial \"Set featured image\" text.</h3>\n\n<p>Add the following to your theme's functions.php. Replace \"Your custom text goes here\" with your help text.</p>\n\n<p>Tested and works.</p>\n\n<pre><code>function custom_featured_image_text( $content ) {\n return '<p>' . __('Your custom text goes here') . '</p>' . $content;\n}\nadd_filter( 'admin_post_thumbnail_html', 'custom_featured_image_text' );\n</code></pre>\n\n<h3>The following will add help text to the \"Click the image to edit or update\" text after you upload an image.</h3>\n\n<pre><code>function custom_featured_image_text_2( $content ) {\n return str_replace(__('Click the image to edit or update'), __('Your custom text goes here'), $content);\n}\nadd_filter( 'admin_post_thumbnail_html', 'custom_featured_image_text_2' );\n</code></pre>\n"
},
{
"answer_id": 321223,
"author": "dave",
"author_id": 90000,
"author_profile": "https://wordpress.stackexchange.com/users/90000",
"pm_score": 1,
"selected": true,
"text": "<p>@RiddleMeThis got me pointed in the right direction, but I needed it to only apply to a single post type so this is my solution:</p>\n\n<pre><code>add_filter('admin_post_thumbnail_html', function ($content) {\n global $pagenow;\n\n $isNewFoo = 'post-new.php' === $pagenow && isset($_GET['post_type']) && $_GET['post_type'] === 'foo';\n $isEditFoo = 'post.php' === $pagenow && isset($_GET['post']) && get_post_type($_GET['post']) === 'foo';\n\n if ($isNewFoo || $isEditFoo) {get_post_type($_GET['post']) === 'foo') {\n return '<p>' . __('Your custom text goes here') . '</p>' . $content;\n }\n\n return $content;\n});\n</code></pre>\n"
},
{
"answer_id": 401435,
"author": "Damien Stewart",
"author_id": 218042,
"author_profile": "https://wordpress.stackexchange.com/users/218042",
"pm_score": 0,
"selected": false,
"text": "<p>@dave The code in your answer is a bit broken so I rewrote it a little. This works:</p>\n<pre><code>// Change featured image descriptions for custom post type\nadd_filter('admin_post_thumbnail_html', function ($content) {\n global $pagenow;\n\n $isNewPost = 'post-new.php' === $pagenow && isset($_GET['post_type']) && $_GET['post_type'] === 'custom_post_type_slug';\n $isEditPost = 'post.php' === $pagenow && isset($_GET['post']) && get_post_type($_GET['post']) === 'custom_post_type_slug';\n\n if($isNewPost == true || $isEditPost == true) { \n $content .= '<p>' . __('Your custom text goes here') . '</p>';\n return $content;\n }\n\n return $content;\n});\n</code></pre>\n"
}
]
| 2018/12/06 | [
"https://wordpress.stackexchange.com/questions/321221",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90000/"
]
| I'd like to be able to edit the description/help text that appears beneath the field in the CMS page editor for a custom post type.
I know I can change the name and button/link text by passing items into the `labels` array in register post type.
```
'featured_image' => __('Foo'),
'set_featured_image' => __('Set Foo'),
'remove_featured_image' => __('Remove Foo'),
'use_featured_image' => __('Use as Foo')
```
But is there a way to add to edit the help text that displays beneath the field? It says "Click the image to edit or update" if an image is selected. I'd like to add further instructions as to precisely what kind of image to use.
Ideally this text should appear before an image is selected as well as after. But I'd settle for being able to edit the text that shows after. | @RiddleMeThis got me pointed in the right direction, but I needed it to only apply to a single post type so this is my solution:
```
add_filter('admin_post_thumbnail_html', function ($content) {
global $pagenow;
$isNewFoo = 'post-new.php' === $pagenow && isset($_GET['post_type']) && $_GET['post_type'] === 'foo';
$isEditFoo = 'post.php' === $pagenow && isset($_GET['post']) && get_post_type($_GET['post']) === 'foo';
if ($isNewFoo || $isEditFoo) {get_post_type($_GET['post']) === 'foo') {
return '<p>' . __('Your custom text goes here') . '</p>' . $content;
}
return $content;
});
``` |
321,225 | <p>I'm trying to make a plugin that merges two carts into one.</p>
<p>I am doing the following: </p>
<pre><code>$old_order = wc_get_order($old_order_id);
duplicate_line_items($new_order, $old_order);
//re-fetch order to make sure changes aren't lost.
$new_order = $wc_get_order($new_order->get_id());
$new_order->calculate_totals();
$new_order->save_meta_data();
$new_order->save();
</code></pre>
<p>My <code>duplicate_line_items()</code> function looks like this:</p>
<pre><code>function duplicate_line_items($source_order, $new_order){
foreach ($source_order->get_items() as $item){
$new_order->add_item($item);
}
$new_order->apply_changes();
$new_order->save();
}
</code></pre>
<p>When I run this code, the items do not display in the admin view of the "new" order (the destination order), nor do they show up in the database.</p>
<p>I do see that per the <code>WC_Order::add_item()</code> docs, "The order item will not persist until save.", but I am saving the order, several times.</p>
<p>Am I missing a step here or something?</p>
<p>Thanks! </p>
| [
{
"answer_id": 321222,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": false,
"text": "<h3>The following will add help text to the initial \"Set featured image\" text.</h3>\n\n<p>Add the following to your theme's functions.php. Replace \"Your custom text goes here\" with your help text.</p>\n\n<p>Tested and works.</p>\n\n<pre><code>function custom_featured_image_text( $content ) {\n return '<p>' . __('Your custom text goes here') . '</p>' . $content;\n}\nadd_filter( 'admin_post_thumbnail_html', 'custom_featured_image_text' );\n</code></pre>\n\n<h3>The following will add help text to the \"Click the image to edit or update\" text after you upload an image.</h3>\n\n<pre><code>function custom_featured_image_text_2( $content ) {\n return str_replace(__('Click the image to edit or update'), __('Your custom text goes here'), $content);\n}\nadd_filter( 'admin_post_thumbnail_html', 'custom_featured_image_text_2' );\n</code></pre>\n"
},
{
"answer_id": 321223,
"author": "dave",
"author_id": 90000,
"author_profile": "https://wordpress.stackexchange.com/users/90000",
"pm_score": 1,
"selected": true,
"text": "<p>@RiddleMeThis got me pointed in the right direction, but I needed it to only apply to a single post type so this is my solution:</p>\n\n<pre><code>add_filter('admin_post_thumbnail_html', function ($content) {\n global $pagenow;\n\n $isNewFoo = 'post-new.php' === $pagenow && isset($_GET['post_type']) && $_GET['post_type'] === 'foo';\n $isEditFoo = 'post.php' === $pagenow && isset($_GET['post']) && get_post_type($_GET['post']) === 'foo';\n\n if ($isNewFoo || $isEditFoo) {get_post_type($_GET['post']) === 'foo') {\n return '<p>' . __('Your custom text goes here') . '</p>' . $content;\n }\n\n return $content;\n});\n</code></pre>\n"
},
{
"answer_id": 401435,
"author": "Damien Stewart",
"author_id": 218042,
"author_profile": "https://wordpress.stackexchange.com/users/218042",
"pm_score": 0,
"selected": false,
"text": "<p>@dave The code in your answer is a bit broken so I rewrote it a little. This works:</p>\n<pre><code>// Change featured image descriptions for custom post type\nadd_filter('admin_post_thumbnail_html', function ($content) {\n global $pagenow;\n\n $isNewPost = 'post-new.php' === $pagenow && isset($_GET['post_type']) && $_GET['post_type'] === 'custom_post_type_slug';\n $isEditPost = 'post.php' === $pagenow && isset($_GET['post']) && get_post_type($_GET['post']) === 'custom_post_type_slug';\n\n if($isNewPost == true || $isEditPost == true) { \n $content .= '<p>' . __('Your custom text goes here') . '</p>';\n return $content;\n }\n\n return $content;\n});\n</code></pre>\n"
}
]
| 2018/12/06 | [
"https://wordpress.stackexchange.com/questions/321225",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155400/"
]
| I'm trying to make a plugin that merges two carts into one.
I am doing the following:
```
$old_order = wc_get_order($old_order_id);
duplicate_line_items($new_order, $old_order);
//re-fetch order to make sure changes aren't lost.
$new_order = $wc_get_order($new_order->get_id());
$new_order->calculate_totals();
$new_order->save_meta_data();
$new_order->save();
```
My `duplicate_line_items()` function looks like this:
```
function duplicate_line_items($source_order, $new_order){
foreach ($source_order->get_items() as $item){
$new_order->add_item($item);
}
$new_order->apply_changes();
$new_order->save();
}
```
When I run this code, the items do not display in the admin view of the "new" order (the destination order), nor do they show up in the database.
I do see that per the `WC_Order::add_item()` docs, "The order item will not persist until save.", but I am saving the order, several times.
Am I missing a step here or something?
Thanks! | @RiddleMeThis got me pointed in the right direction, but I needed it to only apply to a single post type so this is my solution:
```
add_filter('admin_post_thumbnail_html', function ($content) {
global $pagenow;
$isNewFoo = 'post-new.php' === $pagenow && isset($_GET['post_type']) && $_GET['post_type'] === 'foo';
$isEditFoo = 'post.php' === $pagenow && isset($_GET['post']) && get_post_type($_GET['post']) === 'foo';
if ($isNewFoo || $isEditFoo) {get_post_type($_GET['post']) === 'foo') {
return '<p>' . __('Your custom text goes here') . '</p>' . $content;
}
return $content;
});
``` |
321,250 | <p>I'm trying to find a way how to have a simple conditional whereby I can echo something depending on whether the post date is in the first half or last half of the post date year.</p>
| [
{
"answer_id": 321253,
"author": "windyjonas",
"author_id": 221,
"author_profile": "https://wordpress.stackexchange.com/users/221",
"pm_score": 2,
"selected": false,
"text": "<p>Are you thinking of something like this?</p>\n\n<pre><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n if ( absint( get_the_date( 'n' ) ) <= 6 ) {\n // First half of year\n ...\n } else {\n // Second half of year\n ...\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 321324,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 1,
"selected": true,
"text": "<p>I found this elsewhere and it worked for me...</p>\n\n<pre><code>if( (int)get_the_time( 'm' ) <= 6 ) {\n echo 'Some time between January and June.';\n} else {\n echo 'Some time between July and December.';\n}\n</code></pre>\n"
}
]
| 2018/12/07 | [
"https://wordpress.stackexchange.com/questions/321250",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
]
| I'm trying to find a way how to have a simple conditional whereby I can echo something depending on whether the post date is in the first half or last half of the post date year. | I found this elsewhere and it worked for me...
```
if( (int)get_the_time( 'm' ) <= 6 ) {
echo 'Some time between January and June.';
} else {
echo 'Some time between July and December.';
}
``` |
321,280 | <p>I have a relationship field that outputs posts from a custom post type. However, if I unpublish one of those posts, it still shows in the outputted code. </p>
<p>I'm aware it's possible to set the fields to only allow the user to select from published posts only (in the admin), but I'm not sure how to add a check in the ACF output code to see if the posts are published or not. </p>
<p>The most likely situation where this will occur is when the client has been using the site for a while and using the relationship fields, but then deletes or unpublishes one of the posts and forgets to manually remove them from the relationship field. </p>
<p>Is there a way to check this on the fly?</p>
<p>Code below:</p>
<pre><code><?php
$holidays = get_sub_field('holidays');
if( $holidays ): ?>
<?php foreach( $holidays as $holiday): ?>
<?php setup_postdata($holiday); ?>
<a href="<?php echo get_permalink( $holiday->ID ); ?>">
<?php echo get_the_title( $holiday->ID ); ?>
</a>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
</code></pre>
| [
{
"answer_id": 321253,
"author": "windyjonas",
"author_id": 221,
"author_profile": "https://wordpress.stackexchange.com/users/221",
"pm_score": 2,
"selected": false,
"text": "<p>Are you thinking of something like this?</p>\n\n<pre><code>if ( have_posts() ) {\n while ( have_posts() ) {\n the_post(); \n if ( absint( get_the_date( 'n' ) ) <= 6 ) {\n // First half of year\n ...\n } else {\n // Second half of year\n ...\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 321324,
"author": "Pete",
"author_id": 37346,
"author_profile": "https://wordpress.stackexchange.com/users/37346",
"pm_score": 1,
"selected": true,
"text": "<p>I found this elsewhere and it worked for me...</p>\n\n<pre><code>if( (int)get_the_time( 'm' ) <= 6 ) {\n echo 'Some time between January and June.';\n} else {\n echo 'Some time between July and December.';\n}\n</code></pre>\n"
}
]
| 2018/12/07 | [
"https://wordpress.stackexchange.com/questions/321280",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22448/"
]
| I have a relationship field that outputs posts from a custom post type. However, if I unpublish one of those posts, it still shows in the outputted code.
I'm aware it's possible to set the fields to only allow the user to select from published posts only (in the admin), but I'm not sure how to add a check in the ACF output code to see if the posts are published or not.
The most likely situation where this will occur is when the client has been using the site for a while and using the relationship fields, but then deletes or unpublishes one of the posts and forgets to manually remove them from the relationship field.
Is there a way to check this on the fly?
Code below:
```
<?php
$holidays = get_sub_field('holidays');
if( $holidays ): ?>
<?php foreach( $holidays as $holiday): ?>
<?php setup_postdata($holiday); ?>
<a href="<?php echo get_permalink( $holiday->ID ); ?>">
<?php echo get_the_title( $holiday->ID ); ?>
</a>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
``` | I found this elsewhere and it worked for me...
```
if( (int)get_the_time( 'm' ) <= 6 ) {
echo 'Some time between January and June.';
} else {
echo 'Some time between July and December.';
}
``` |
321,293 | <p>currently I am working on some customized blog templating and was wondering if there is any way to find out if the newest post of a category is also the newest post of the whole blog, so I can skip the first post of the category.</p>
<p><a href="https://i.stack.imgur.com/JrDtT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JrDtT.jpg" alt="enter image description here"></a></p>
<ul>
<li>(1) is the newest post of the whole blog, which is in category (B).</li>
<li>(2) is the newest post of the category (A)</li>
<li>(3) is the newest post of the category (B), also is (1)</li>
</ul>
<p><strong>Basically I am asking how I would do this:
If (3) = (1), skip (3) and show 2nd newest post in the category (in this case category (B)).</strong></p>
<hr>
<p>Additional information about my blog specifically, while the information above is more general/universal.</p>
<p>In my blog I also have a category that is excluded from the blog and only shown on a specific page. How would I exclude this category from the whole solution for the initial question? Would it simply be enough to write <code>'cat' => -123,</code>?</p>
| [
{
"answer_id": 321295,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Just use ‘post__not_in’ param in your second query.</p>\n\n<pre><code>$query1 = new WP_Query...\n$used_posts = array();\n\nwhile ( $query1->have_posts() ) :\n $query1->the_post();\n $used_posts[]= get_the_ID();\n ...\nendwhile;\n\n$query2 = new WP_Query( array(\n 'post__not_in' => $used_posts,\n...\n) );\n</code></pre>\n"
},
{
"answer_id": 321296,
"author": "jrmd",
"author_id": 155471,
"author_profile": "https://wordpress.stackexchange.com/users/155471",
"pm_score": 3,
"selected": true,
"text": "<p>So the easiest way to do this would be to store the ID of the first post <code>(1)</code> then in each of your category loops you can use the <code>post__not_in</code> property like so:</p>\n\n<pre><code>// inside the first loop at the top.\n$latest_post_id = get_the_ID();\n\n// WP_Query for fetching each category\n$category_query = new WP_Query( [\n // other parameters\n 'post__not_in' => [ $latest_post_id ],\n] );\n</code></pre>\n\n<p>Now to exclude a category in <code>WP_Query</code> you can use <code>category__not_in</code> which takes an array of category ID's. It's definitely worth checking out the wordpress codex for <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">WP_Query</a></p>\n"
}
]
| 2018/12/07 | [
"https://wordpress.stackexchange.com/questions/321293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94786/"
]
| currently I am working on some customized blog templating and was wondering if there is any way to find out if the newest post of a category is also the newest post of the whole blog, so I can skip the first post of the category.
[](https://i.stack.imgur.com/JrDtT.jpg)
* (1) is the newest post of the whole blog, which is in category (B).
* (2) is the newest post of the category (A)
* (3) is the newest post of the category (B), also is (1)
**Basically I am asking how I would do this:
If (3) = (1), skip (3) and show 2nd newest post in the category (in this case category (B)).**
---
Additional information about my blog specifically, while the information above is more general/universal.
In my blog I also have a category that is excluded from the blog and only shown on a specific page. How would I exclude this category from the whole solution for the initial question? Would it simply be enough to write `'cat' => -123,`? | So the easiest way to do this would be to store the ID of the first post `(1)` then in each of your category loops you can use the `post__not_in` property like so:
```
// inside the first loop at the top.
$latest_post_id = get_the_ID();
// WP_Query for fetching each category
$category_query = new WP_Query( [
// other parameters
'post__not_in' => [ $latest_post_id ],
] );
```
Now to exclude a category in `WP_Query` you can use `category__not_in` which takes an array of category ID's. It's definitely worth checking out the wordpress codex for [WP\_Query](https://codex.wordpress.org/Class_Reference/WP_Query) |
321,297 | <p>I am using a URL rewrite to put the user's display name in the URL to display a user profile. This part all works fine and the proper value is passed through the query_vars and I can get the correct user.</p>
<p>Since this is for a plugin, some plugin users may want to use the user's first/last name instead of the display name. I've set up an opportunity for them to do that where the first/last name is separated by an underscore(_).</p>
<p>To retrieve the user when the URL rewrite is passing the query_var "display_name", I am using a meta query in <code>get_users()</code>.</p>
<pre><code>// Get the custom query_var value.
$query_var = get_query_var( 'display_name' );
/**
* When the display_name query_var is first name/last name,
* (for example "john_smith"), split the value by unscore
* to get the individual first and last name values.
*/
$pieces = explode( '_', $query_var );
// User meta query to get the user ID by first_name/last_name.
$user = reset( get_users( array(
'meta_query' => array(
'relation' => 'AND',
array(
'key'=>'first_name',
'value' => $pieces[0],
'compare' => '='
),
array(
'key' => 'last_name',
'value' => $pieces[1],
'compare' => '='
)
),
'number' => 1,
'count_total' => false
) ) );
</code></pre>
<p>The meta query works fine and the correct user ID is returned, <strong><em>but</em></strong> I get a PHP notice as follows:</p>
<blockquote>
<p>Notice: Only variables should be passed by reference</p>
</blockquote>
<p>The line indicated is the meta query line <code>$user = reset( get_users( array(</code></p>
<p>Any thoughts on what is wrong and is throwing the PHP notice? Any ideas on a better query to get the user ID by first name/last name meta keys?</p>
| [
{
"answer_id": 321299,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$user = reset( get_users( array(\n</code></pre>\n\n<p>The function <code>reset()</code> changes the passed variable, hence it needs a reference. Function output of <code>get_users()</code> can't be referenced because it is not a variable. Just assign the return value to a variable and call that:</p>\n\n<pre><code>$users = get_users( array(\n //...\n) );\n$user = reset( $users );\n</code></pre>\n"
},
{
"answer_id": 321300,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>The value passed to <a href=\"http://php.net/manual/en/function.reset.php\" rel=\"nofollow noreferrer\"><code>reset()</code></a> is <a href=\"http://php.net/manual/en/language.references.pass.php\" rel=\"nofollow noreferrer\">passed by reference</a>, which means technically it modifies the original variable that's passed to it. For this to work you need to pass a variable, not a function that returns a value. </p>\n\n<blockquote>\n <p><strong>reset()</strong> rewinds <strong>array's</strong> internal pointer to the first element and\n returns the value of the first array element.</p>\n</blockquote>\n\n<p>All you need to do is assign the returned value if <code>get_users()</code> to a variable and then use <code>reset()</code> on <em>that</em>:</p>\n\n<pre><code>$users = get_users( array(\n 'meta_query' => array(\n 'relation' => 'AND',\n array(\n 'key'=>'first_name',\n 'value' => $pieces[0],\n 'compare' => '='\n ),\n array(\n 'key' => 'last_name',\n 'value' => $pieces[1],\n 'compare' => '='\n )\n ),\n 'number' => 1,\n 'count_total' => false\n) );\n\n$user = reset( $users );\n</code></pre>\n"
}
]
| 2018/12/07 | [
"https://wordpress.stackexchange.com/questions/321297",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38603/"
]
| I am using a URL rewrite to put the user's display name in the URL to display a user profile. This part all works fine and the proper value is passed through the query\_vars and I can get the correct user.
Since this is for a plugin, some plugin users may want to use the user's first/last name instead of the display name. I've set up an opportunity for them to do that where the first/last name is separated by an underscore(\_).
To retrieve the user when the URL rewrite is passing the query\_var "display\_name", I am using a meta query in `get_users()`.
```
// Get the custom query_var value.
$query_var = get_query_var( 'display_name' );
/**
* When the display_name query_var is first name/last name,
* (for example "john_smith"), split the value by unscore
* to get the individual first and last name values.
*/
$pieces = explode( '_', $query_var );
// User meta query to get the user ID by first_name/last_name.
$user = reset( get_users( array(
'meta_query' => array(
'relation' => 'AND',
array(
'key'=>'first_name',
'value' => $pieces[0],
'compare' => '='
),
array(
'key' => 'last_name',
'value' => $pieces[1],
'compare' => '='
)
),
'number' => 1,
'count_total' => false
) ) );
```
The meta query works fine and the correct user ID is returned, ***but*** I get a PHP notice as follows:
>
> Notice: Only variables should be passed by reference
>
>
>
The line indicated is the meta query line `$user = reset( get_users( array(`
Any thoughts on what is wrong and is throwing the PHP notice? Any ideas on a better query to get the user ID by first name/last name meta keys? | The value passed to [`reset()`](http://php.net/manual/en/function.reset.php) is [passed by reference](http://php.net/manual/en/language.references.pass.php), which means technically it modifies the original variable that's passed to it. For this to work you need to pass a variable, not a function that returns a value.
>
> **reset()** rewinds **array's** internal pointer to the first element and
> returns the value of the first array element.
>
>
>
All you need to do is assign the returned value if `get_users()` to a variable and then use `reset()` on *that*:
```
$users = get_users( array(
'meta_query' => array(
'relation' => 'AND',
array(
'key'=>'first_name',
'value' => $pieces[0],
'compare' => '='
),
array(
'key' => 'last_name',
'value' => $pieces[1],
'compare' => '='
)
),
'number' => 1,
'count_total' => false
) );
$user = reset( $users );
``` |
321,320 | <p>This is a common query to delete all post revisions:</p>
<pre><code>DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'revision'
</code></pre>
<p>Will this work to delete all drafts?</p>
<pre><code>DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'draft'
</code></pre>
<p>and is it better than this since it also deletes postmeta?</p>
<pre><code> DELETE FROM posts WHERE post_status = ‘draft’
</code></pre>
| [
{
"answer_id": 321321,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p><code>draft</code> is not a <code>post_type</code>, it's a <code>post_status</code>. So you should use your second block of code with that substitution:</p>\n\n<pre><code>DELETE a,b,c\nFROM wp_posts a\nLEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)\nLEFT JOIN wp_postmeta c ON (a.ID = c.post_id)\nWHERE a.post_status = 'draft'\n</code></pre>\n"
},
{
"answer_id": 379789,
"author": "Sumit Jangir",
"author_id": 198937,
"author_profile": "https://wordpress.stackexchange.com/users/198937",
"pm_score": 0,
"selected": false,
"text": "<p><strong>I would suggest if u want to delete any post manually from wp_posts. you need to perform the following steps:-</strong></p>\n<ol>\n<li><strong>Remove from postmeta table.</strong></li>\n</ol>\n<pre class=\"lang-sql prettyprint-override\"><code>delete FROM wp_postmeta WHERE post_id IN\n (\n select id from wp_posts where post_status='draft'\n );\n</code></pre>\n<ol start=\"2\">\n<li><strong>Remove from wp_term_relationships table.</strong></li>\n</ol>\n<pre class=\"lang-sql prettyprint-override\"><code>delete FROM wp_term_relationships WHERE object_id IN\n (\n select id from wp_posts where post_status='draft'\n );\n</code></pre>\n<ol start=\"3\">\n<li><strong>Remove from wp_posts table.</strong></li>\n</ol>\n<pre class=\"lang-sql prettyprint-override\"><code>delete from wp_posts where post_status='draft'\n</code></pre>\n"
}
]
| 2018/12/07 | [
"https://wordpress.stackexchange.com/questions/321320",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101490/"
]
| This is a common query to delete all post revisions:
```
DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'revision'
```
Will this work to delete all drafts?
```
DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'draft'
```
and is it better than this since it also deletes postmeta?
```
DELETE FROM posts WHERE post_status = ‘draft’
``` | `draft` is not a `post_type`, it's a `post_status`. So you should use your second block of code with that substitution:
```
DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_status = 'draft'
``` |
321,328 | <p>Today I tried to change the webserver to php fpm and it is really very fast
<br>
But there is a very serious problem I found when I installed Wordpress, when I changed the premalink to anything but the normal, it not working and gives me "404 error"
<br>
I don't know what is the problem, Is it a server problem or worpdress ?
<br>
I'm the server admin and I using CWP but don't know what to do</p>
| [
{
"answer_id": 321962,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 0,
"selected": false,
"text": "<p>Check your </p>\n\n<blockquote>\n <p>.htaccess file for apache server </p>\n</blockquote>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<p>file and check if you have updated PHP version. \nFor more info, you can refer to WordPress <a href=\"https://codex.wordpress.org/Using_Permalinks\" rel=\"nofollow noreferrer\">documentation</a> </p>\n\n<p>If still, you face issue then try .user.ini files analogue to .htaccess</p>\n"
},
{
"answer_id": 323478,
"author": "Gamal Elwazeery",
"author_id": 154315,
"author_profile": "https://wordpress.stackexchange.com/users/154315",
"pm_score": 1,
"selected": false,
"text": "<p>It was a nginx config problem\n<br>Solved it by adding this line to .conf file</p>\n\n<pre><code>try_files $uri $uri/ /index.php?q=$uri&$args;\n</code></pre>\n"
}
]
| 2018/12/07 | [
"https://wordpress.stackexchange.com/questions/321328",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154315/"
]
| Today I tried to change the webserver to php fpm and it is really very fast
But there is a very serious problem I found when I installed Wordpress, when I changed the premalink to anything but the normal, it not working and gives me "404 error"
I don't know what is the problem, Is it a server problem or worpdress ?
I'm the server admin and I using CWP but don't know what to do | It was a nginx config problem
Solved it by adding this line to .conf file
```
try_files $uri $uri/ /index.php?q=$uri&$args;
``` |
321,340 | <p>Right beneath the testimonial is the text <code><p>Tony (Property Manager)</p></code>, but it's overlapped by the WordPress 5.0 gallery that follows it. I don't think it's a float problem.</p>
<p>Here: <a href="http://www.sunnyexteriors.ca/tony-property-manager-soffits/" rel="nofollow noreferrer">http://www.sunnyexteriors.ca/tony-property-manager-soffits/</a></p>
| [
{
"answer_id": 321962,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 0,
"selected": false,
"text": "<p>Check your </p>\n\n<blockquote>\n <p>.htaccess file for apache server </p>\n</blockquote>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<p>file and check if you have updated PHP version. \nFor more info, you can refer to WordPress <a href=\"https://codex.wordpress.org/Using_Permalinks\" rel=\"nofollow noreferrer\">documentation</a> </p>\n\n<p>If still, you face issue then try .user.ini files analogue to .htaccess</p>\n"
},
{
"answer_id": 323478,
"author": "Gamal Elwazeery",
"author_id": 154315,
"author_profile": "https://wordpress.stackexchange.com/users/154315",
"pm_score": 1,
"selected": false,
"text": "<p>It was a nginx config problem\n<br>Solved it by adding this line to .conf file</p>\n\n<pre><code>try_files $uri $uri/ /index.php?q=$uri&$args;\n</code></pre>\n"
}
]
| 2018/12/07 | [
"https://wordpress.stackexchange.com/questions/321340",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155098/"
]
| Right beneath the testimonial is the text `<p>Tony (Property Manager)</p>`, but it's overlapped by the WordPress 5.0 gallery that follows it. I don't think it's a float problem.
Here: <http://www.sunnyexteriors.ca/tony-property-manager-soffits/> | It was a nginx config problem
Solved it by adding this line to .conf file
```
try_files $uri $uri/ /index.php?q=$uri&$args;
``` |
321,370 | <p>Is there a setting in WordPress Gutenberg editor to change the font size of the text we type while writing posts? I mean the text size inside the editor itself, not the published text that blog visitors view.</p>
| [
{
"answer_id": 321373,
"author": "Glenn Greening",
"author_id": 154275,
"author_profile": "https://wordpress.stackexchange.com/users/154275",
"pm_score": 2,
"selected": false,
"text": "<p>Just click on the settings/cog icon on the right hand side when you are editing paragraph. Then choose Block. You should then see the option to edit font size. You can choose from dropdown menu or type the font size you want. </p>\n\n<p><a href=\"https://i.stack.imgur.com/HAGr8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HAGr8.png\" alt=\"screenshot\"></a></p>\n\n<p>Hope this helps. :)</p>\n"
},
{
"answer_id": 321381,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>When we change the paragraph font size in Gutenberg via the <em>block text settings</em>, it will be added inline like:</p>\n\n<pre><code><p style=\"font-size:18px\">Lorem Ipsum</p>\n</code></pre>\n\n<p>If we are frequently changing the font-size (or other formatting) like that, it's easy to imagine the state of the content in few years, where most of the content formatting is hard coded.</p>\n\n<p>It could e.g. override the formatting from a new theme if we decide to switch to a new theme later on.</p>\n\n<p>So I would suggest using it with care.</p>\n\n<p>An alternative could be to target the formatting via unobtrusive CSS.</p>\n\n<p>If that's not possible one could then consider adding custom target CSS classes via the <em>Advanced</em> Gutenberg block setting:</p>\n\n<p><a href=\"https://i.stack.imgur.com/koY7E.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/koY7E.png\" alt=\"enter image description here\"></a></p>\n\n<p>that will generate a class attribute like:</p>\n\n<pre><code><p class=\"some__custom--class\">Lorem Ipsum</p>\n</code></pre>\n\n<p>where we define the CSS class in the corresponding stylesheet.</p>\n"
},
{
"answer_id": 353631,
"author": "Ryan",
"author_id": 4296,
"author_profile": "https://wordpress.stackexchange.com/users/4296",
"pm_score": 3,
"selected": false,
"text": "<p>If you came here, like me, looking for how to adjust the available text size options within Gutenberg, you can add this code to your theme's <code>functions.php</code> file (you can add as many options as you like):</p>\n\n<pre><code>add_theme_support(\n 'editor-font-sizes', \n array(\n array(\n 'name' => __( 'Normal', 'your-theme-text-domain' ),\n 'shortName' => __( 'N', 'your-theme-text-domain' ),\n 'size' => 14,\n 'slug' => 'normal'\n ),\n array(\n 'name' => __( 'Medium', 'your-theme-text-domain' ),\n 'shortName' => __( 'M', 'your-theme-text-domain' ),\n 'size' => 16,\n 'slug' => 'medium'\n )\n )\n);\n</code></pre>\n\n<p>This gives the following result within the Gutenberg editor:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bT2cV.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/bT2cV.png\" alt=\"Gutenberg editor showing custom font sizes for a paragraph in a dropdown menu\"></a></p>\n\n<p>You can add <code>add_theme_support( 'disable-custom-font-sizes' );</code> to your <code>functions.php</code> to remove the numerical input, although the \"Custom\" option will still be visible in the dropdown.</p>\n"
},
{
"answer_id": 354080,
"author": "Gustaf",
"author_id": 169997,
"author_profile": "https://wordpress.stackexchange.com/users/169997",
"pm_score": 2,
"selected": false,
"text": "<p>I had same question how to change heading font size in Editor, just found myself:</p>\n\n<p>PS: This is a generic solution for any WP customization:</p>\n\n<ol>\n<li>While in editor, using e.g. Firefox \"inspect element\", select the\nelement(any text or heading) you want to change; </li>\n<li>In the middle column, it will point to the setting css file, e.g.\neditor-style.css, it gives also the line number;</li>\n<li>Go [SIDE MENU]Appearance => Theme Editor => select the css setting file, change the font size, and update the css setting file. </li>\n<li>That's it!</li>\n</ol>\n\n<p>For your case, it is to change <strong>editor-blocks.css</strong>:</p>\n\n<pre><code>.edit-post-visual-editor .editor-block-list__block,\n.edit-post-visual-editor .editor-block-list__block p,\n.editor-default-block-appender textarea.editor-default-block-appender__content {\n font-size: 16px; /* change to your font size */\n }\n</code></pre>\n"
}
]
| 2018/12/08 | [
"https://wordpress.stackexchange.com/questions/321370",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112076/"
]
| Is there a setting in WordPress Gutenberg editor to change the font size of the text we type while writing posts? I mean the text size inside the editor itself, not the published text that blog visitors view. | If you came here, like me, looking for how to adjust the available text size options within Gutenberg, you can add this code to your theme's `functions.php` file (you can add as many options as you like):
```
add_theme_support(
'editor-font-sizes',
array(
array(
'name' => __( 'Normal', 'your-theme-text-domain' ),
'shortName' => __( 'N', 'your-theme-text-domain' ),
'size' => 14,
'slug' => 'normal'
),
array(
'name' => __( 'Medium', 'your-theme-text-domain' ),
'shortName' => __( 'M', 'your-theme-text-domain' ),
'size' => 16,
'slug' => 'medium'
)
)
);
```
This gives the following result within the Gutenberg editor:
[](https://i.stack.imgur.com/bT2cV.png)
You can add `add_theme_support( 'disable-custom-font-sizes' );` to your `functions.php` to remove the numerical input, although the "Custom" option will still be visible in the dropdown. |
321,398 | <p>I have two sites running WordPress 4.9.8</p>
<p>On one site I can see "Store uploads in this folder" option on in Media Settings</p>
<p><a href="https://i.stack.imgur.com/IbMma.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IbMma.png" alt="enter image description here"></a></p>
<p>On another site I cannot see "Store uploads in this folder" option in Media Settings</p>
<p><a href="https://i.stack.imgur.com/5tGIR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5tGIR.png" alt="enter image description here"></a></p>
<p>I am admin on both sites. Why it happens? How to make it visible on both sites? Thank you</p>
| [
{
"answer_id": 321402,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>IIRC the option was softly deprecated sometime in the past, but if you have an old install it will still be indicated that it should be displayed and let the user edit it.</p>\n\n<p>The second site is probably newer</p>\n\n<p>(answering the question literally, if you need to be able to change it and can not find the relevant option, just say so in the comments)</p>\n"
},
{
"answer_id": 321405,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>I think that the second site is running on a newer WordPress version, rather than 4.9.8. That's why, you are not seeing the \"Store uploads in this folder\" option in Media Settings. However, you are seeing it in the first site, as it is running on 4.9.8. </p>\n"
},
{
"answer_id": 321411,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 3,
"selected": true,
"text": "<p>While the other answers cover part of the answer (old WP install), it is important to note: The options appear, <strong>if one of the options is set</strong>. They are stored via the keys <code>upload_path</code> and <code>upload_url_path</code>.</p>\n\n<p>Before:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aVQXH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aVQXH.png\" alt=\"enter image description here\"></a></p>\n\n<p>Run (or add directly in the DB)</p>\n\n<pre><code>$ wp option set upload_path foo\n$ wp option set upload_url_path bar\n</code></pre>\n\n<p>After:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bCIfT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bCIfT.png\" alt=\"enter image description here\"></a></p>\n\n<p>As has been mentioned, these options are deprecated and shouldn't be used anymore.</p>\n"
}
]
| 2018/12/08 | [
"https://wordpress.stackexchange.com/questions/321398",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130520/"
]
| I have two sites running WordPress 4.9.8
On one site I can see "Store uploads in this folder" option on in Media Settings
[](https://i.stack.imgur.com/IbMma.png)
On another site I cannot see "Store uploads in this folder" option in Media Settings
[](https://i.stack.imgur.com/5tGIR.png)
I am admin on both sites. Why it happens? How to make it visible on both sites? Thank you | While the other answers cover part of the answer (old WP install), it is important to note: The options appear, **if one of the options is set**. They are stored via the keys `upload_path` and `upload_url_path`.
Before:
[](https://i.stack.imgur.com/aVQXH.png)
Run (or add directly in the DB)
```
$ wp option set upload_path foo
$ wp option set upload_url_path bar
```
After:
[](https://i.stack.imgur.com/bCIfT.png)
As has been mentioned, these options are deprecated and shouldn't be used anymore. |
321,422 | <p>very new here to php and wordpress coding (1 day lol). This is my code so far, the problem is that when there is no value assigned to this attribute I receive and error message. I know I need something that says if the value exists then display the rest of the code but not sure how to go about adding that. This is for a woocommerce product attribute btw.</p>
<p>Code so far:</p>
<pre><code>$collection_values = get_the_terms( $product->id, 'pa_collection');
foreach ($collection_values as $collection_value){
echo '<h2 class="collection_title"><a href="'.get_term_link($collection_value->slug, $collection_value->taxonomy).'">'.$collection_value->name.'</a></h2>';
}
</code></pre>
<p>Error message:</p>
<pre><code>Warning: Invalid argument supplied for foreach() in /app/public/wp-content/themes/savoy/woocommerce/single-product/title.php on line 21
</code></pre>
<p>EDIT: I am adding this above the product title in the title.php page.</p>
| [
{
"answer_id": 321402,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>IIRC the option was softly deprecated sometime in the past, but if you have an old install it will still be indicated that it should be displayed and let the user edit it.</p>\n\n<p>The second site is probably newer</p>\n\n<p>(answering the question literally, if you need to be able to change it and can not find the relevant option, just say so in the comments)</p>\n"
},
{
"answer_id": 321405,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>I think that the second site is running on a newer WordPress version, rather than 4.9.8. That's why, you are not seeing the \"Store uploads in this folder\" option in Media Settings. However, you are seeing it in the first site, as it is running on 4.9.8. </p>\n"
},
{
"answer_id": 321411,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 3,
"selected": true,
"text": "<p>While the other answers cover part of the answer (old WP install), it is important to note: The options appear, <strong>if one of the options is set</strong>. They are stored via the keys <code>upload_path</code> and <code>upload_url_path</code>.</p>\n\n<p>Before:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aVQXH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aVQXH.png\" alt=\"enter image description here\"></a></p>\n\n<p>Run (or add directly in the DB)</p>\n\n<pre><code>$ wp option set upload_path foo\n$ wp option set upload_url_path bar\n</code></pre>\n\n<p>After:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bCIfT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bCIfT.png\" alt=\"enter image description here\"></a></p>\n\n<p>As has been mentioned, these options are deprecated and shouldn't be used anymore.</p>\n"
}
]
| 2018/12/08 | [
"https://wordpress.stackexchange.com/questions/321422",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155554/"
]
| very new here to php and wordpress coding (1 day lol). This is my code so far, the problem is that when there is no value assigned to this attribute I receive and error message. I know I need something that says if the value exists then display the rest of the code but not sure how to go about adding that. This is for a woocommerce product attribute btw.
Code so far:
```
$collection_values = get_the_terms( $product->id, 'pa_collection');
foreach ($collection_values as $collection_value){
echo '<h2 class="collection_title"><a href="'.get_term_link($collection_value->slug, $collection_value->taxonomy).'">'.$collection_value->name.'</a></h2>';
}
```
Error message:
```
Warning: Invalid argument supplied for foreach() in /app/public/wp-content/themes/savoy/woocommerce/single-product/title.php on line 21
```
EDIT: I am adding this above the product title in the title.php page. | While the other answers cover part of the answer (old WP install), it is important to note: The options appear, **if one of the options is set**. They are stored via the keys `upload_path` and `upload_url_path`.
Before:
[](https://i.stack.imgur.com/aVQXH.png)
Run (or add directly in the DB)
```
$ wp option set upload_path foo
$ wp option set upload_url_path bar
```
After:
[](https://i.stack.imgur.com/bCIfT.png)
As has been mentioned, these options are deprecated and shouldn't be used anymore. |
321,450 | <p>I have some post in my autoblog that by cronjob mistake the feautured image being deleted.
how to find all of that post (<strong>post with broken image link</strong>) and delete all of it or set the default image if the featured image is missing without searching one by one through thousand of post.</p>
| [
{
"answer_id": 321402,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>IIRC the option was softly deprecated sometime in the past, but if you have an old install it will still be indicated that it should be displayed and let the user edit it.</p>\n\n<p>The second site is probably newer</p>\n\n<p>(answering the question literally, if you need to be able to change it and can not find the relevant option, just say so in the comments)</p>\n"
},
{
"answer_id": 321405,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>I think that the second site is running on a newer WordPress version, rather than 4.9.8. That's why, you are not seeing the \"Store uploads in this folder\" option in Media Settings. However, you are seeing it in the first site, as it is running on 4.9.8. </p>\n"
},
{
"answer_id": 321411,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 3,
"selected": true,
"text": "<p>While the other answers cover part of the answer (old WP install), it is important to note: The options appear, <strong>if one of the options is set</strong>. They are stored via the keys <code>upload_path</code> and <code>upload_url_path</code>.</p>\n\n<p>Before:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aVQXH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aVQXH.png\" alt=\"enter image description here\"></a></p>\n\n<p>Run (or add directly in the DB)</p>\n\n<pre><code>$ wp option set upload_path foo\n$ wp option set upload_url_path bar\n</code></pre>\n\n<p>After:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bCIfT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bCIfT.png\" alt=\"enter image description here\"></a></p>\n\n<p>As has been mentioned, these options are deprecated and shouldn't be used anymore.</p>\n"
}
]
| 2018/12/09 | [
"https://wordpress.stackexchange.com/questions/321450",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155571/"
]
| I have some post in my autoblog that by cronjob mistake the feautured image being deleted.
how to find all of that post (**post with broken image link**) and delete all of it or set the default image if the featured image is missing without searching one by one through thousand of post. | While the other answers cover part of the answer (old WP install), it is important to note: The options appear, **if one of the options is set**. They are stored via the keys `upload_path` and `upload_url_path`.
Before:
[](https://i.stack.imgur.com/aVQXH.png)
Run (or add directly in the DB)
```
$ wp option set upload_path foo
$ wp option set upload_url_path bar
```
After:
[](https://i.stack.imgur.com/bCIfT.png)
As has been mentioned, these options are deprecated and shouldn't be used anymore. |
321,474 | <p>I a problem with getting the query for custom taxonomy to work in this function. The $filter is filled with data but the get_posts() does not use it? The query works without the tax_query and there are: custom posts with the correct taxonomy(list)... want am I missing?</p>
<pre><code>add_action( 'restrict_manage_posts', 'add_export_button' );
function add_export_button() {
$screen = get_current_screen();
if (isset($screen->parent_file) && ('edit.php?post_type=certificate'==$screen->parent_file)) {
?>
<input type="submit" name="export_all_posts" id="export_all_posts" class="button button-primary" value="Export All Posts">
<script type="text/javascript">
jQuery(function($) {
$('#export_all_posts').insertAfter('#post-query-submit');
});
</script>
<?php
}
}
add_action( 'init', 'func_export_all_posts' );
function func_export_all_posts() {
if(isset($_GET['export_all_posts'])) {
if(isset($_GET['list'])) {
$filter = strval($_GET['list']);
};
$arg = array(
'post_type' => 'certificate',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'list',
'field' => 'slug',
'terms' => $filter ,
)
),
);
global $post;
$arr_post = get_posts($arg);
if ($arr_post) {
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="wp.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$file = fopen('php://output', 'w');
fputcsv($file, array('Post Title', 'URL'));
foreach ($arr_post as $post) {
setup_postdata($post);
fputcsv($file, array(get_the_title(), get_the_permalink()));
}
exit();
}
}
}
</code></pre>
| [
{
"answer_id": 321402,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>IIRC the option was softly deprecated sometime in the past, but if you have an old install it will still be indicated that it should be displayed and let the user edit it.</p>\n\n<p>The second site is probably newer</p>\n\n<p>(answering the question literally, if you need to be able to change it and can not find the relevant option, just say so in the comments)</p>\n"
},
{
"answer_id": 321405,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>I think that the second site is running on a newer WordPress version, rather than 4.9.8. That's why, you are not seeing the \"Store uploads in this folder\" option in Media Settings. However, you are seeing it in the first site, as it is running on 4.9.8. </p>\n"
},
{
"answer_id": 321411,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 3,
"selected": true,
"text": "<p>While the other answers cover part of the answer (old WP install), it is important to note: The options appear, <strong>if one of the options is set</strong>. They are stored via the keys <code>upload_path</code> and <code>upload_url_path</code>.</p>\n\n<p>Before:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aVQXH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aVQXH.png\" alt=\"enter image description here\"></a></p>\n\n<p>Run (or add directly in the DB)</p>\n\n<pre><code>$ wp option set upload_path foo\n$ wp option set upload_url_path bar\n</code></pre>\n\n<p>After:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bCIfT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bCIfT.png\" alt=\"enter image description here\"></a></p>\n\n<p>As has been mentioned, these options are deprecated and shouldn't be used anymore.</p>\n"
}
]
| 2018/12/09 | [
"https://wordpress.stackexchange.com/questions/321474",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155586/"
]
| I a problem with getting the query for custom taxonomy to work in this function. The $filter is filled with data but the get\_posts() does not use it? The query works without the tax\_query and there are: custom posts with the correct taxonomy(list)... want am I missing?
```
add_action( 'restrict_manage_posts', 'add_export_button' );
function add_export_button() {
$screen = get_current_screen();
if (isset($screen->parent_file) && ('edit.php?post_type=certificate'==$screen->parent_file)) {
?>
<input type="submit" name="export_all_posts" id="export_all_posts" class="button button-primary" value="Export All Posts">
<script type="text/javascript">
jQuery(function($) {
$('#export_all_posts').insertAfter('#post-query-submit');
});
</script>
<?php
}
}
add_action( 'init', 'func_export_all_posts' );
function func_export_all_posts() {
if(isset($_GET['export_all_posts'])) {
if(isset($_GET['list'])) {
$filter = strval($_GET['list']);
};
$arg = array(
'post_type' => 'certificate',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'list',
'field' => 'slug',
'terms' => $filter ,
)
),
);
global $post;
$arr_post = get_posts($arg);
if ($arr_post) {
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="wp.csv"');
header('Pragma: no-cache');
header('Expires: 0');
$file = fopen('php://output', 'w');
fputcsv($file, array('Post Title', 'URL'));
foreach ($arr_post as $post) {
setup_postdata($post);
fputcsv($file, array(get_the_title(), get_the_permalink()));
}
exit();
}
}
}
``` | While the other answers cover part of the answer (old WP install), it is important to note: The options appear, **if one of the options is set**. They are stored via the keys `upload_path` and `upload_url_path`.
Before:
[](https://i.stack.imgur.com/aVQXH.png)
Run (or add directly in the DB)
```
$ wp option set upload_path foo
$ wp option set upload_url_path bar
```
After:
[](https://i.stack.imgur.com/bCIfT.png)
As has been mentioned, these options are deprecated and shouldn't be used anymore. |
321,525 | <p>I want to get the data from advanced custom field using wp_query from another custom post type:</p>
<pre><code> $title = get_the_title();
$the_query = new WP_Query( array(
'posts_per_page'=>9,
'post_type'=>'product_name',
'order' => 'ASC',
'brand_name' => $title, /*brand_name is my custom field name*/
'paged' => get_query_var('paged') ? get_query_var('paged') : 1)
);
</code></pre>
| [
{
"answer_id": 321526,
"author": "Greg Winiarski",
"author_id": 154460,
"author_profile": "https://wordpress.stackexchange.com/users/154460",
"pm_score": 1,
"selected": false,
"text": "<p>ACF plugin stores data in the wp_postmeta like the default WordPress custom fields.</p>\n\n<p>To get data from a custom field your code should look like this (assuming the custom field name is \"brand_name\").</p>\n\n<pre><code>$title = get_the_title();\n$the_query = new WP_Query( array(\n 'posts_per_page'=>9,\n 'post_type'=>'product_name',\n 'order' => 'ASC',\n 'meta_query' => array(\n array( \"key\" => \"brand_name\", \"value\" => $title )\n ),\n 'paged' => get_query_var('paged') ? get_query_var('paged') : 1) \n);\n</code></pre>\n\n<p>For more details on using meta fields in the WP_Query please see <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters</a></p>\n"
},
{
"answer_id": 321528,
"author": "Tejas Gajjar",
"author_id": 140870,
"author_profile": "https://wordpress.stackexchange.com/users/140870",
"pm_score": 0,
"selected": false,
"text": "<p>You have to use meta query like that name of filed in key please follow this example and let me know if this helps or now</p>\n\n<pre><code> $args = array(\n'post_type' =>'post_type',\n 'paged' => $page,\n 'tax_query' => array( \n array(\n 'taxonomy' => 'product_cat',\n 'terms' => '386',\n 'field' => 'term_id',\n )),\n 'meta_query' =>array( \n array(\n 'key' => 'textbox_4',\n 'value' => $cond,\n 'compare' => 'LIKE'\n ),\n ),\n );\n</code></pre>\n"
},
{
"answer_id": 335043,
"author": "hyjinx",
"author_id": 146626,
"author_profile": "https://wordpress.stackexchange.com/users/146626",
"pm_score": 1,
"selected": false,
"text": "<p>You have to use the ACF API <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\"><code>get_field()</code></a> function.</p>\n\n<p>The <code>get_field()</code> function requires the name of the field. If you are using the loop then that's all you need. If you are outside the loop you will need to provide the post ID as the second argument. The final, optional argument is boolean and determines whether formatting is applied to the data, this defaults to true so if you don't want formatting you need to provide a false here.</p>\n\n<pre><code>$val = get_field('frequency', $postID, false);\n</code></pre>\n\n<p>Where <code>'frequency'</code> is the name of the custom field you desire.</p>\n\n<p>Since this method only requires that you are either in the loop or that you know the post ID you can use in any of the WordPress database methods that are available to you.</p>\n"
}
]
| 2018/12/10 | [
"https://wordpress.stackexchange.com/questions/321525",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| I want to get the data from advanced custom field using wp\_query from another custom post type:
```
$title = get_the_title();
$the_query = new WP_Query( array(
'posts_per_page'=>9,
'post_type'=>'product_name',
'order' => 'ASC',
'brand_name' => $title, /*brand_name is my custom field name*/
'paged' => get_query_var('paged') ? get_query_var('paged') : 1)
);
``` | ACF plugin stores data in the wp\_postmeta like the default WordPress custom fields.
To get data from a custom field your code should look like this (assuming the custom field name is "brand\_name").
```
$title = get_the_title();
$the_query = new WP_Query( array(
'posts_per_page'=>9,
'post_type'=>'product_name',
'order' => 'ASC',
'meta_query' => array(
array( "key" => "brand_name", "value" => $title )
),
'paged' => get_query_var('paged') ? get_query_var('paged') : 1)
);
```
For more details on using meta fields in the WP\_Query please see <https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters> |
321,538 | <p>And where do I (reliably) look for this kind of information? I find myself googling for 'wordpress changelog' on every other update...</p>
<p>Background: usually I use a "skeletal" WP installation (seperate <code>wp</code>/<code>app</code> and <code>wp-content</code> folders), so I could try out the new major version and check for theme incompatibilites by "hotswapping" the <code>wp</code> folder. And I'm worried that "swapping back" might not work due to a migrated DB. Yes I know, I should always back it up before an update anyway. Question still stands :)</p>
| [
{
"answer_id": 321540,
"author": "Jose Guerra",
"author_id": 153734,
"author_profile": "https://wordpress.stackexchange.com/users/153734",
"pm_score": 0,
"selected": false,
"text": "<p>I upgraded 2 of my sites from version 4.9.8 to 5.0 and it did not require any database update. Also I had installed Gutenberg and the update disables the plugin since it's already integrated with the new version.</p>\n\n<p>If you are concerned about the update, backup your database and site before the upgrading.</p>\n"
},
{
"answer_id": 321547,
"author": "kubi",
"author_id": 152837,
"author_profile": "https://wordpress.stackexchange.com/users/152837",
"pm_score": 3,
"selected": true,
"text": "<p>So after some thinking I came up with this:</p>\n\n<p><a href=\"https://codex.wordpress.org/Current_events\" rel=\"nofollow noreferrer\">Codex / Wordpress Versions</a> has Changelogs, but these seem to mention (recent) database upgrades implicitly, starting at 5.0. (Compare how <a href=\"https://matomo.org/changelog/piwik-3-0-0/\" rel=\"nofollow noreferrer\">Matomo explicitly states DB upgrades</a>). Maybe this will be enough for future versions, here's the thorough, cumbersome way that works for older versions, too:</p>\n\n<ol>\n<li>check <code>db_version</code> at <a href=\"https://codex.wordpress.org/Current_events\" rel=\"nofollow noreferrer\">Codex / Wordpress Versions</a>, <strong>or</strong> manually/programmatically:\n\n<ol>\n<li>check <code>wp-includes/version.php</code> of the version we are updating <em>from</em>, <a href=\"https://github.com/WordPress/WordPress/blob/4.9.8/wp-includes/version.php#L14\" rel=\"nofollow noreferrer\">4.9.8</a>:\n<code>$wp_db_version = 38590;</code></li>\n<li>repeat for version we are updating <em>to</em>; <a href=\"https://github.com/WordPress/WordPress/blob/5.0/wp-includes/version.php#L14\" rel=\"nofollow noreferrer\">5.0</a>: <code>$wp_db_version = 43764;</code></li>\n</ol></li>\n<li><p>check <code>upgrade_all</code> in <code>wp-admin/includes/upgrade.php</code>, for <a href=\"https://github.com/WordPress/WordPress/blob/5.0/wp-admin/includes/upgrade.php#L642-L643\" rel=\"nofollow noreferrer\">4.9.8→5.0 / 38590→43764</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>// ...\nif ( $wp_current_db_version < 37965 ) // false\n upgrade_460();\n\nif ( $wp_current_db_version < 43764 ) // true!\n upgrade_500();\n</code></pre></li>\n<li><p>finally, inspecting <a href=\"https://github.com/WordPress/WordPress/blob/5.0/wp-admin/includes/upgrade.php#L1820-L1836\" rel=\"nofollow noreferrer\"><code>upgrade_500</code></a>, reveals some Gutenberg-juggling and a <code>FIXME</code> :)</p></li>\n<li>Conclusion: Only very minor database upgrades (one site option is set), so it should be fine, just keep an eye out for Gutenberg & Classic Editor plugin.</li>\n</ol>\n\n<p>UPDATE/EDIT, regarding the \"Background\": So I did do a manual update 4.9.9→5.0 and then a manual downgrade 5.0→4.9.9 (4.9.8 and .9 don't differ DB-wise). I was presented with the \"DB Upgrade required\" screen <strong>both</strong> ways, and proceeded. What happens upon downgrade would need more research; my guess is that you only see the screen and none of the <code>upgrade_*</code> functions are executed. After up-and-downgrade everything <em>looks</em> normal, at least for this minimal, fresh install. So I will feel free to upgrade 4.9.8 to 5.0, knowing I can switch back should anything go wrong. YMMV, of course, especially when other plugins and themes are involved. Wouldn't do it for bigger version jumps, though :)</p>\n"
}
]
| 2018/12/10 | [
"https://wordpress.stackexchange.com/questions/321538",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152837/"
]
| And where do I (reliably) look for this kind of information? I find myself googling for 'wordpress changelog' on every other update...
Background: usually I use a "skeletal" WP installation (seperate `wp`/`app` and `wp-content` folders), so I could try out the new major version and check for theme incompatibilites by "hotswapping" the `wp` folder. And I'm worried that "swapping back" might not work due to a migrated DB. Yes I know, I should always back it up before an update anyway. Question still stands :) | So after some thinking I came up with this:
[Codex / Wordpress Versions](https://codex.wordpress.org/Current_events) has Changelogs, but these seem to mention (recent) database upgrades implicitly, starting at 5.0. (Compare how [Matomo explicitly states DB upgrades](https://matomo.org/changelog/piwik-3-0-0/)). Maybe this will be enough for future versions, here's the thorough, cumbersome way that works for older versions, too:
1. check `db_version` at [Codex / Wordpress Versions](https://codex.wordpress.org/Current_events), **or** manually/programmatically:
1. check `wp-includes/version.php` of the version we are updating *from*, [4.9.8](https://github.com/WordPress/WordPress/blob/4.9.8/wp-includes/version.php#L14):
`$wp_db_version = 38590;`
2. repeat for version we are updating *to*; [5.0](https://github.com/WordPress/WordPress/blob/5.0/wp-includes/version.php#L14): `$wp_db_version = 43764;`
2. check `upgrade_all` in `wp-admin/includes/upgrade.php`, for [4.9.8→5.0 / 38590→43764](https://github.com/WordPress/WordPress/blob/5.0/wp-admin/includes/upgrade.php#L642-L643):
```php
// ...
if ( $wp_current_db_version < 37965 ) // false
upgrade_460();
if ( $wp_current_db_version < 43764 ) // true!
upgrade_500();
```
3. finally, inspecting [`upgrade_500`](https://github.com/WordPress/WordPress/blob/5.0/wp-admin/includes/upgrade.php#L1820-L1836), reveals some Gutenberg-juggling and a `FIXME` :)
4. Conclusion: Only very minor database upgrades (one site option is set), so it should be fine, just keep an eye out for Gutenberg & Classic Editor plugin.
UPDATE/EDIT, regarding the "Background": So I did do a manual update 4.9.9→5.0 and then a manual downgrade 5.0→4.9.9 (4.9.8 and .9 don't differ DB-wise). I was presented with the "DB Upgrade required" screen **both** ways, and proceeded. What happens upon downgrade would need more research; my guess is that you only see the screen and none of the `upgrade_*` functions are executed. After up-and-downgrade everything *looks* normal, at least for this minimal, fresh install. So I will feel free to upgrade 4.9.8 to 5.0, knowing I can switch back should anything go wrong. YMMV, of course, especially when other plugins and themes are involved. Wouldn't do it for bigger version jumps, though :) |
321,542 | <p>What I'm trying to do is to take the categories for products which are in the cart. Then check via some conditions what category id is and show different notice. </p>
<p>So far I have this</p>
<pre><code>/**
* Cart collaterals hook.
*
* @hooked woocommerce_cross_sell_display
* @hooked woocommerce_cart_totals - 10
*/
$categories = array( 39 );
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$found = true; // Set to true
break; // Stop the loop
}
}
if( $found ) {
echo 'Category with ID = 39';
}
else if ($found != $cart_item['category_ids']) {
echo "Category with ID = 39 and other ID('s)";
}
else {
"Category with ID != 39";
}
</code></pre>
<p>Seems like <code>$cart_item['category_ids']</code> doesn't return categories. <code>$found</code> is working and showing category with ID = 39. </p>
<p>When I <code>var_dump($cart_items)</code> I do see different categories like this:</p>
<pre><code>["category_ids"]=>
array(1) {
[0]=>
int(39)
}
/// another stuff in the array
["category_ids"]=>
array(2) {
[0]=>
int(32)
[1]=>
int(33)
}
</code></pre>
<p>So, in cart I have products from categories with id <code>39</code>, <code>32</code> and <code>33</code>. </p>
<p>I've tried also <code>WC()->cart->get_cart()->category_ids</code> but this return <code>NULL</code></p>
<p>UPDATE: This </p>
<pre><code>$cat_ids = array();
foreach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {
$cat_ids = array_merge(
$cat_ids, $cart_item['data']->get_category_ids()
);
}
$cat_id = 39;
if ( in_array( $cat_id, $cat_ids ) ) {
echo 'Only 39 ';
} elseif ( ! empty( $cat_ids ) ) {
echo '39 + other';
} else {
echo ' all other without 39';
}
</code></pre>
<p>Currently matching</p>
<p>When: category 39 + other -> <code>Only 39</code></p>
<p>When: all other without 39 -> <code>39 + other</code></p>
<p>When: Only 39 -> <code>Only 39</code></p>
<p>It should be</p>
<p>When: category 39 + other -> <code>39 + other</code></p>
<p>When: all other without 39 -> <code>all other without 39</code></p>
<p>When: Only 39 -> <code>Only 39</code></p>
<p><strong>UPDATE</strong></p>
<p>When: Category 39 + product from other category ( Category ID = 32, 33 etc )</p>
<pre><code>var_dump(count( $cat_ids )); -> int(1)
var_dump($has_cat); -> bool(true)
var_dump(cat_ids); -> array(1) { [0]=> int(39) } <---- there are 3 products in the cart 2 of them are from other categories.
</code></pre>
<p>When: Category 39 only </p>
<pre><code>var_dump(count( $cat_ids )); -> int(1)
var_dump($has_cat); -> bool(true)
var_dump(cat_ids); -> array(1) { [0]=> int(39) }
</code></pre>
<p>When: No category 39</p>
<pre><code>var_dump(count( $cat_ids )); -> int(2)
var_dump($has_cat); -> bool(false)
var_dump(cat_ids); -> array(2) { [0]=> int(32) [1]=> int(33) } <--- product is added in 2 categories
</code></pre>
<p><strong>UPDATE 2</strong></p>
<p>Condition 1</p>
<pre><code>1) cat 30;
2) cat 39;
$cond = 2 (because there are products in cart from 39 + other category)
</code></pre>
<p>Condition 2</p>
<pre><code>1) cat 39;
$cond = 1 (because in cart is/are product/s only from cat 39)
</code></pre>
<p>Condition 3</p>
<pre><code>1) cat 40;
2) cat 15;
$cond = last one (because there is no product/s from cat 39 in cart)
</code></pre>
| [
{
"answer_id": 321555,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 3,
"selected": true,
"text": "<p>Use <code>$cart_item['data']->get_category_ids()</code> to retrieve the category IDs:</p>\n\n<pre><code>$category_ids = $cart_item['data']->get_category_ids(); // array\n</code></pre>\n\n<p>The <code>category_ids</code> you see is not a direct item in the <code>$cart_item</code> array:</p>\n\n<pre><code>var_dump( $cart_item['category_ids'] ); // null and PHP throws a notice\n</code></pre>\n\n<p>It's an item in a <em>protected</em> property of the product data (<code>$cart_item['data']</code>) which is an object, or a class instance — e.g. the class is <code>WC_Product_Simple</code> for Simple products.</p>\n\n<h2>UPDATE</h2>\n\n<p>If you want to collect all the product category IDs, you can do it like so:</p>\n\n<pre><code>$cat_ids = array();\nforeach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {\n $cat_ids = array_merge(\n $cat_ids, $cart_item['data']->get_category_ids()\n );\n}\nvar_dump( $cat_ids );\n</code></pre>\n\n<h2>UPDATE #2</h2>\n\n<p>You can use this to check if a product in the cart is in certain categories:</p>\n\n<pre><code>$cat_ids = array( 39 );\nforeach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {\n if ( has_term( $cat_ids, 'product_cat', $cart_item['data'] ) ) {\n echo 'Has category 39<br>';\n } else {\n echo 'No category 39<br>';\n }\n}\n</code></pre>\n\n<h2>UPDATE #3/#4/#5</h2>\n\n<p>This should work as expected:</p>\n\n<pre><code>// Collect the category IDs.\n$cat_ids = array();\nforeach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {\n $cat_ids = array_merge(\n $cat_ids, $cart_item['data']->get_category_ids()\n );\n}\n\n// And here we check the IDs.\n$cat_id = 39;\n$count = count( $cat_ids );\nif ( 1 === $count && in_array( $cat_id, $cat_ids ) ) {\n echo 'Only in category 39';\n} elseif ( $count && in_array( $cat_id, $cat_ids ) ) {\n echo 'In category 39 and other categories';\n} else {\n echo 'No category 39';\n}\n</code></pre>\n\n<p>Here's an alternate version of the <code>if</code> block above:</p>\n\n<pre><code>if ( $count && in_array( $cat_id, $cat_ids ) ) {\n // Only one category.\n if ( $count < 2 ) {\n echo 'Only in category 39';\n // Multiple categories.\n } else {\n echo 'In category 39 and other categories';\n }\n} else {\n echo 'No category 39';\n}\n</code></pre>\n"
},
{
"answer_id": 405676,
"author": "Conor Treacy",
"author_id": 222130,
"author_profile": "https://wordpress.stackexchange.com/users/222130",
"pm_score": 1,
"selected": false,
"text": "<p>The answer from @sally works great, as long as your products are Simple products.</p>\n<p>If your product uses a variation, then the above code no longer works as the $cart_item['data'] does not return the parent category for the variations.</p>\n<p>This will allow you to get any products with variations - using the "product_id" to look up the "category id"</p>\n<pre><code> $cat_id = '39'; // category to check against\n $cat_ids = [];\n foreach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {\n $the_product = wc_get_product( $cart_item['product_id'] );\n $array_cat = $the_product->get_category_ids();\n if ( in_array($cat_id, $array_cat)) {\n array_push($cat_ids, $cat_id);\n }\n else {\n $cat_ids = array_merge($cat_ids, $array_cat);\n } \n }\n\n // Count unique categories\n $count = count(array_unique($cat_ids));\n if ( ($count < 2) && ($cat_ids[0] == $cat_id)){\n echo 'only in category 39';\n }\n else {\n echo 'in category 39 and other';\n }\n</code></pre>\n"
}
]
| 2018/12/10 | [
"https://wordpress.stackexchange.com/questions/321542",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100661/"
]
| What I'm trying to do is to take the categories for products which are in the cart. Then check via some conditions what category id is and show different notice.
So far I have this
```
/**
* Cart collaterals hook.
*
* @hooked woocommerce_cross_sell_display
* @hooked woocommerce_cart_totals - 10
*/
$categories = array( 39 );
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$found = true; // Set to true
break; // Stop the loop
}
}
if( $found ) {
echo 'Category with ID = 39';
}
else if ($found != $cart_item['category_ids']) {
echo "Category with ID = 39 and other ID('s)";
}
else {
"Category with ID != 39";
}
```
Seems like `$cart_item['category_ids']` doesn't return categories. `$found` is working and showing category with ID = 39.
When I `var_dump($cart_items)` I do see different categories like this:
```
["category_ids"]=>
array(1) {
[0]=>
int(39)
}
/// another stuff in the array
["category_ids"]=>
array(2) {
[0]=>
int(32)
[1]=>
int(33)
}
```
So, in cart I have products from categories with id `39`, `32` and `33`.
I've tried also `WC()->cart->get_cart()->category_ids` but this return `NULL`
UPDATE: This
```
$cat_ids = array();
foreach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {
$cat_ids = array_merge(
$cat_ids, $cart_item['data']->get_category_ids()
);
}
$cat_id = 39;
if ( in_array( $cat_id, $cat_ids ) ) {
echo 'Only 39 ';
} elseif ( ! empty( $cat_ids ) ) {
echo '39 + other';
} else {
echo ' all other without 39';
}
```
Currently matching
When: category 39 + other -> `Only 39`
When: all other without 39 -> `39 + other`
When: Only 39 -> `Only 39`
It should be
When: category 39 + other -> `39 + other`
When: all other without 39 -> `all other without 39`
When: Only 39 -> `Only 39`
**UPDATE**
When: Category 39 + product from other category ( Category ID = 32, 33 etc )
```
var_dump(count( $cat_ids )); -> int(1)
var_dump($has_cat); -> bool(true)
var_dump(cat_ids); -> array(1) { [0]=> int(39) } <---- there are 3 products in the cart 2 of them are from other categories.
```
When: Category 39 only
```
var_dump(count( $cat_ids )); -> int(1)
var_dump($has_cat); -> bool(true)
var_dump(cat_ids); -> array(1) { [0]=> int(39) }
```
When: No category 39
```
var_dump(count( $cat_ids )); -> int(2)
var_dump($has_cat); -> bool(false)
var_dump(cat_ids); -> array(2) { [0]=> int(32) [1]=> int(33) } <--- product is added in 2 categories
```
**UPDATE 2**
Condition 1
```
1) cat 30;
2) cat 39;
$cond = 2 (because there are products in cart from 39 + other category)
```
Condition 2
```
1) cat 39;
$cond = 1 (because in cart is/are product/s only from cat 39)
```
Condition 3
```
1) cat 40;
2) cat 15;
$cond = last one (because there is no product/s from cat 39 in cart)
``` | Use `$cart_item['data']->get_category_ids()` to retrieve the category IDs:
```
$category_ids = $cart_item['data']->get_category_ids(); // array
```
The `category_ids` you see is not a direct item in the `$cart_item` array:
```
var_dump( $cart_item['category_ids'] ); // null and PHP throws a notice
```
It's an item in a *protected* property of the product data (`$cart_item['data']`) which is an object, or a class instance — e.g. the class is `WC_Product_Simple` for Simple products.
UPDATE
------
If you want to collect all the product category IDs, you can do it like so:
```
$cat_ids = array();
foreach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {
$cat_ids = array_merge(
$cat_ids, $cart_item['data']->get_category_ids()
);
}
var_dump( $cat_ids );
```
UPDATE #2
---------
You can use this to check if a product in the cart is in certain categories:
```
$cat_ids = array( 39 );
foreach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( has_term( $cat_ids, 'product_cat', $cart_item['data'] ) ) {
echo 'Has category 39<br>';
} else {
echo 'No category 39<br>';
}
}
```
UPDATE #3/#4/#5
---------------
This should work as expected:
```
// Collect the category IDs.
$cat_ids = array();
foreach ( wc()->cart->get_cart() as $cart_item_key => $cart_item ) {
$cat_ids = array_merge(
$cat_ids, $cart_item['data']->get_category_ids()
);
}
// And here we check the IDs.
$cat_id = 39;
$count = count( $cat_ids );
if ( 1 === $count && in_array( $cat_id, $cat_ids ) ) {
echo 'Only in category 39';
} elseif ( $count && in_array( $cat_id, $cat_ids ) ) {
echo 'In category 39 and other categories';
} else {
echo 'No category 39';
}
```
Here's an alternate version of the `if` block above:
```
if ( $count && in_array( $cat_id, $cat_ids ) ) {
// Only one category.
if ( $count < 2 ) {
echo 'Only in category 39';
// Multiple categories.
} else {
echo 'In category 39 and other categories';
}
} else {
echo 'No category 39';
}
``` |
321,606 | <pre><code>remove_action('woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title',10);
add_action('woocommerce_shop_loop_item_title','fun',10);
function fun()
{
echo 'custom_field_value';
}
</code></pre>
<p>Note: I want to replace the title on shop page with custom field value. The code is correct but the echo part I need help on it.</p>
| [
{
"answer_id": 321580,
"author": "lotto_guy",
"author_id": 124674,
"author_profile": "https://wordpress.stackexchange.com/users/124674",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the Theme My Login plugin where there is an option to have a custom registration page on the website.</p>\n\n<p>Theme my login just made a big update. I find that version 6 is better than 7.</p>\n"
},
{
"answer_id": 321586,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>The registration form is generated by code directly in <code>wp-login.php</code> (<a href=\"https://core.trac.wordpress.org/browser/branches/5.0/src/wp-login.php#L786\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/branches/5.0/src/wp-login.php#L786</a>) and this code is not wrapped with any function, so... I'm afraid there is no such function ready to use.</p>\n\n<p>Of course you can mimic the code from the file above and wrap it with your own function...</p>\n"
}
]
| 2018/12/11 | [
"https://wordpress.stackexchange.com/questions/321606",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155687/"
]
| ```
remove_action('woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title',10);
add_action('woocommerce_shop_loop_item_title','fun',10);
function fun()
{
echo 'custom_field_value';
}
```
Note: I want to replace the title on shop page with custom field value. The code is correct but the echo part I need help on it. | The registration form is generated by code directly in `wp-login.php` (<https://core.trac.wordpress.org/browser/branches/5.0/src/wp-login.php#L786>) and this code is not wrapped with any function, so... I'm afraid there is no such function ready to use.
Of course you can mimic the code from the file above and wrap it with your own function... |
321,657 | <p>I made a plugin that basically reads a CSV file and imports data to relevant tables.</p>
<p>However, the action seems to create an error:</p>
<blockquote>
<p>Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65015808 bytes) in <b>/var/www/proj/wp-includes/functions.php</b> on line </p>
</blockquote>
<p>which led me to this code in functions.php:</p>
<pre><code>function wp_ob_end_flush_all() {
$levels = ob_get_level();
for ($i=0; $i<$levels; $i++)
ob_end_flush();
}
</code></pre>
<p>I did a Google and came across two popular solutions, both of which didn't seem to work.</p>
<blockquote>
<p>Solution 1: disabling zlib - this is already disabled.<br />
Solution 2: <code>remove_action('shutdown', 'wp_ob_end_flush_all', 1);</code></p>
</blockquote>
<p>Solution 2 still errors but with no message, which, isn't exactly ideal.</p>
<p>This is the script that's causing the error:</p>
<pre><code><?php
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
# load core wp fnc
require_once $_SERVER['DOCUMENT_ROOT']. '/wp-load.php';
# load db functions
require_once $_SERVER['DOCUMENT_ROOT']. '/wp-admin/includes/upgrade.php';
# load admin fnc
require_once $_SERVER['DOCUMENT_ROOT']. '/wp-content/plugins/vendor-module/admin/inc/admin-functions.php';
global $wpdb;
$admin_functions = new vendor_module_admin_functions();
# get csv
$file = $_FILES['csv'];
$name = $file['name'];
$dir = $file['tmp_name'];
# rm spaces, replace with _
$name = str_replace(' ', '_', $name);
$file_location = $_SERVER['DOCUMENT_ROOT']. '/wp-content/plugins/vendor-module/uploads/import/'. $name;
# if successfully moved, carry on, else return
$moved = ($file['error'] == 0 ? true : false);
$error = false;
if (!$moved) {
echo 'Error! CSV file may be incorrectly formatted or there was an issue in reading the file. Please try again.';
} else {
move_uploaded_file($dir, $file_location);
$id = $_POST['val'];
$type = $_POST['type'];
$table = ($type == 1 ? 'vendor_module_type_one' : 'vendor_module_type_two');
$handle = fopen($file_location, 'r');
$parts = array();
$components = array();
$i = 0;
while (($data = fgetcsv($handle, 1000, ',')) !== false)
{
if (is_array($data)) {
if (empty($data[0])) {
echo 'Error! Reference can\'t be empty. Please ensure all rows are using a ref no.';
$error = true;
continue;
}
# get data
$get_for_sql = 'SELECT `id` FROM `'. $wpdb->prefix. $table .'` WHERE `ref` = %s';
$get_for_res = $wpdb->get_results($wpdb->prepare($get_for_sql, array($data[0])));
if (count($get_for_res) <= 0) {
echo 'Error! Reference has no match. Please ensure the CSV is using the correct ref no.';
$error = true;
exit();
}
$get_for_id = $get_for_res[0]->id;
# create data arrays
$parts[$i]['name'] = $data[1];
$parts[$i]['ref'] = $data[2];
$parts[$i]['for'] = $get_for_id;
$components[$i]['part_ref'] = $data[2];
$components[$i]['component_ref'] = $data[3];
$components[$i]['sku'] = $data[4];
$components[$i]['desc'] = utf8_decode($data[5]);
$components[$i]['req'] = $data[6];
$components[$i]['price'] = $data[7];
unset($get_for_id);
unset($get_for_res);
unset($get_for_sql);
$i++;
}
}
fclose($handle);
unlink($file_location);
# get unique parts only
$parts = array_unique($parts, SORT_REGULAR);
# check to see if part already exists, if so delete
$search_field = ($type == 1 ? 'id_field_one' : 'id_field_two');
$check_sql = 'SELECT `id` FROM `'. $wpdb->prefix .'vendor_module_parts` WHERE `'. $search_field .'` = %d';
$delete_parts_sql = 'DELETE FROM `'. $wpdb->prefix .'vendor_module_parts` WHERE `'. $search_field .'` = %d';
$delete_components_sql = 'DELETE FROM `'. $wpdb->prefix .'vendor_module_components` WHERE `part_id` = %d';
$check_res = $wpdb->get_results($wpdb->prepare($check_sql, array($id)));
if ($check_res) {
$wpdb->query($wpdb->prepare($delete_parts_sql, array($id)));
}
$part_ids = $admin_functions->insert_parts($parts, $type);
unset($parts);
unset($delete_parts_sql);
unset($search_field);
unset($check_sql);
unset($check_res);
unset($i);
# should never be empty, but just as a precaution ...
if (!empty($part_ids)) {
foreach ($components as $key => $component)
{
$components[$key]['part_id'] = $part_ids[$component['part_ref']];
}
# rm components from assoc part id
foreach ($part_ids as $id)
{
$wpdb->query($wpdb->prepare($delete_components_sql, array($id)));
}
# insert components
$admin_functions->insert_components($components);
} else {
echo 'Error!';
}
echo (!$error ? 'Success! File Successfully Imported.' : 'There be something wrong with the import. Please try again.');
}
</code></pre>
<p>it's triggered through a button press and uses AJAX to handle it etc.</p>
<p>I'm not sure why a memory leak is occurring or why WordPress doesn't offer more useful error messages. I don't call that function.. so I'm guessing it's something WordPress is doing in the background when things are run.</p>
<p>My info:</p>
<blockquote>
<p>PHP 7.2.10<br />
Apache 2.4<br/>
Linux Mint 19</p>
</blockquote>
<p>Also happens on my server:</p>
<blockquote>
<p>PHP 7.1.25<br />
Apache 2.4<br />
CentOS 7.6.1810</p>
</blockquote>
<p>WordPress running version: 4.9.8</p>
| [
{
"answer_id": 321660,
"author": "Tim Hallman",
"author_id": 38375,
"author_profile": "https://wordpress.stackexchange.com/users/38375",
"pm_score": 0,
"selected": false,
"text": "<p>In your functions file do something like this:</p>\n\n<pre><code>add_action('wp_ajax_import_parts_abc', 'import_parts_abc');\nfunction import_parts_abc() {\n include_once('/admin/inc/scripts/import-parts.php');\n exit();\n\n}\n</code></pre>\n\n<p>Then in your js file something like this:</p>\n\n<pre><code>jQuery(document).ready(function() {\n jQuery('.my-button').click(function() {\njQuery.ajax({ \n type: 'GET', \n url: ajaxurl, \n data: { \n action : 'import_parts_abc'\n }, \n success: function(textStatus){\n alert('processing complete')\n },\n error: function(MLHttpRequest, textStatus, errorThrown){ \n console.log(errorThrown); \n } \n }); \n});\n\n});\n</code></pre>\n"
},
{
"answer_id": 321666,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": true,
"text": "<p>Depending on what exactly you're trying to achieve, I agree with <a href=\"https://wordpress.stackexchange.com/questions/321657/memory-leak-in-plugin-action?noredirect=1#comment475327_321657\">Tom's comment</a>, that a WP-CLI command might be better. The advantage is that the command runs from php directly on the server (usually has no max execution time, loads different php.ini, etc.) and you don't need to involve the webserver.</p>\n\n<hr>\n\n<p>If that is not possible, the next best way is probably to <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">create a custom REST endpoint</a>. WordPress has a class <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_controller/\" rel=\"nofollow noreferrer\"><code>WP_REST_Controller</code></a>, usually I write classes that <code>extend</code> this and work from there. For simplicity the following example is not using inheritence, but I try to keep to the same lingo.</p>\n\n<p><strong>1. Register new route</strong></p>\n\n<p>New/custom routes are registered via <a href=\"https://developer.wordpress.org/reference/functions/register_rest_route/\" rel=\"nofollow noreferrer\"><code>register_rest_route()</code></a> like so</p>\n\n<pre><code>$version = 1;\n$namespace = sprintf('acme/v%u', $version);\n$base = '/import';\n\n\\register_rest_route(\n $namespace,\n $base,\n [\n [\n 'methods' => \\WP_REST_Server::CREATABLE,\n // equals ['POST','PUT','PATCH']\n\n 'callback' => [$this, 'import_csv'],\n 'permission_callback' => [$this, 'get_import_permissions_check'],\n 'args' => [],\n // used for OPTIONS calls, left out for simplicity's sake\n ],\n ]\n);\n</code></pre>\n\n<p>This will create a new route that you can call via</p>\n\n<pre><code>http://www.example.com/wp-json/acme/v1/import/\n default REST start-^ ^ ^\n namespace with version-| |-base\n</code></pre>\n\n<p><strong>2. Define permissions check</strong></p>\n\n<p>Maybe you need authentication? Use nonces?</p>\n\n<pre><code>public function get_import_permissions_check($request)\n{\n //TODO: implement\n return true;\n}\n</code></pre>\n\n<p><strong>3. Create your actual endpoint callback</strong></p>\n\n<p>The method previously defined gets passed a <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_request/\" rel=\"nofollow noreferrer\"><code>WP_REST_Request</code></a> object, use that to access request body, etc. To stay consistent, it is usually best to return a <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_response/\" rel=\"nofollow noreferrer\"><code>WP_REST_Response</code></a> instead of custom printing of JSON or similar.</p>\n\n<pre><code>public function import_csv($request)\n{\n $data = [];\n // do stuff\n return new \\WP_REST_Response($data, 200);\n}\n</code></pre>\n\n<hr>\n\n<p>If you do all of this in OOP style, you'll get the following class</p>\n\n<pre><code>class Import_CSV\n{\n\n /**\n * register routes for this controller\n */\n public function register_routes()\n {\n $version = 1;\n $namespace = sprintf('acme/v%u', $version);\n $base = '/import';\n\n \\register_rest_route(\n $namespace,\n $base,\n [\n [\n 'methods' => \\WP_REST_Server::CREATABLE,\n 'callback' => [$this, 'import_csv'],\n 'permission_callback' => [$this, 'get_import_permissions_check'],\n 'args' => [],\n ],\n ]\n );\n }\n\n /**\n * endpoint for POST|PUT|PATCH /acme/v1/import\n */\n public function import_csv($request)\n {\n $data = [];\n // do stuff\n return new \\WP_REST_Response($data, 200);\n }\n\n /**\n * check if user is permitted to access the import route\n */\n public function get_import_permissions_check($request)\n {\n //TODO: implement\n return true;\n }\n\n}\n</code></pre>\n\n<p>But .. still 404? Yes, simply defining the class sadly doesn't work (no autoloading by default :( ), so we need to run <code>register_routes()</code> like so (in your plugin file)</p>\n\n<pre><code>require_once 'Import_CSV.php';\nadd_action('rest_api_init', function(){\n $import_csv = new \\Import_CSV;\n $import_csv->register_routes();\n});\n</code></pre>\n"
}
]
| 2018/12/11 | [
"https://wordpress.stackexchange.com/questions/321657",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155748/"
]
| I made a plugin that basically reads a CSV file and imports data to relevant tables.
However, the action seems to create an error:
>
> Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65015808 bytes) in **/var/www/proj/wp-includes/functions.php** on line
>
>
>
which led me to this code in functions.php:
```
function wp_ob_end_flush_all() {
$levels = ob_get_level();
for ($i=0; $i<$levels; $i++)
ob_end_flush();
}
```
I did a Google and came across two popular solutions, both of which didn't seem to work.
>
> Solution 1: disabling zlib - this is already disabled.
>
> Solution 2: `remove_action('shutdown', 'wp_ob_end_flush_all', 1);`
>
>
>
Solution 2 still errors but with no message, which, isn't exactly ideal.
This is the script that's causing the error:
```
<?php
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
# load core wp fnc
require_once $_SERVER['DOCUMENT_ROOT']. '/wp-load.php';
# load db functions
require_once $_SERVER['DOCUMENT_ROOT']. '/wp-admin/includes/upgrade.php';
# load admin fnc
require_once $_SERVER['DOCUMENT_ROOT']. '/wp-content/plugins/vendor-module/admin/inc/admin-functions.php';
global $wpdb;
$admin_functions = new vendor_module_admin_functions();
# get csv
$file = $_FILES['csv'];
$name = $file['name'];
$dir = $file['tmp_name'];
# rm spaces, replace with _
$name = str_replace(' ', '_', $name);
$file_location = $_SERVER['DOCUMENT_ROOT']. '/wp-content/plugins/vendor-module/uploads/import/'. $name;
# if successfully moved, carry on, else return
$moved = ($file['error'] == 0 ? true : false);
$error = false;
if (!$moved) {
echo 'Error! CSV file may be incorrectly formatted or there was an issue in reading the file. Please try again.';
} else {
move_uploaded_file($dir, $file_location);
$id = $_POST['val'];
$type = $_POST['type'];
$table = ($type == 1 ? 'vendor_module_type_one' : 'vendor_module_type_two');
$handle = fopen($file_location, 'r');
$parts = array();
$components = array();
$i = 0;
while (($data = fgetcsv($handle, 1000, ',')) !== false)
{
if (is_array($data)) {
if (empty($data[0])) {
echo 'Error! Reference can\'t be empty. Please ensure all rows are using a ref no.';
$error = true;
continue;
}
# get data
$get_for_sql = 'SELECT `id` FROM `'. $wpdb->prefix. $table .'` WHERE `ref` = %s';
$get_for_res = $wpdb->get_results($wpdb->prepare($get_for_sql, array($data[0])));
if (count($get_for_res) <= 0) {
echo 'Error! Reference has no match. Please ensure the CSV is using the correct ref no.';
$error = true;
exit();
}
$get_for_id = $get_for_res[0]->id;
# create data arrays
$parts[$i]['name'] = $data[1];
$parts[$i]['ref'] = $data[2];
$parts[$i]['for'] = $get_for_id;
$components[$i]['part_ref'] = $data[2];
$components[$i]['component_ref'] = $data[3];
$components[$i]['sku'] = $data[4];
$components[$i]['desc'] = utf8_decode($data[5]);
$components[$i]['req'] = $data[6];
$components[$i]['price'] = $data[7];
unset($get_for_id);
unset($get_for_res);
unset($get_for_sql);
$i++;
}
}
fclose($handle);
unlink($file_location);
# get unique parts only
$parts = array_unique($parts, SORT_REGULAR);
# check to see if part already exists, if so delete
$search_field = ($type == 1 ? 'id_field_one' : 'id_field_two');
$check_sql = 'SELECT `id` FROM `'. $wpdb->prefix .'vendor_module_parts` WHERE `'. $search_field .'` = %d';
$delete_parts_sql = 'DELETE FROM `'. $wpdb->prefix .'vendor_module_parts` WHERE `'. $search_field .'` = %d';
$delete_components_sql = 'DELETE FROM `'. $wpdb->prefix .'vendor_module_components` WHERE `part_id` = %d';
$check_res = $wpdb->get_results($wpdb->prepare($check_sql, array($id)));
if ($check_res) {
$wpdb->query($wpdb->prepare($delete_parts_sql, array($id)));
}
$part_ids = $admin_functions->insert_parts($parts, $type);
unset($parts);
unset($delete_parts_sql);
unset($search_field);
unset($check_sql);
unset($check_res);
unset($i);
# should never be empty, but just as a precaution ...
if (!empty($part_ids)) {
foreach ($components as $key => $component)
{
$components[$key]['part_id'] = $part_ids[$component['part_ref']];
}
# rm components from assoc part id
foreach ($part_ids as $id)
{
$wpdb->query($wpdb->prepare($delete_components_sql, array($id)));
}
# insert components
$admin_functions->insert_components($components);
} else {
echo 'Error!';
}
echo (!$error ? 'Success! File Successfully Imported.' : 'There be something wrong with the import. Please try again.');
}
```
it's triggered through a button press and uses AJAX to handle it etc.
I'm not sure why a memory leak is occurring or why WordPress doesn't offer more useful error messages. I don't call that function.. so I'm guessing it's something WordPress is doing in the background when things are run.
My info:
>
> PHP 7.2.10
>
> Apache 2.4
>
> Linux Mint 19
>
>
>
Also happens on my server:
>
> PHP 7.1.25
>
> Apache 2.4
>
> CentOS 7.6.1810
>
>
>
WordPress running version: 4.9.8 | Depending on what exactly you're trying to achieve, I agree with [Tom's comment](https://wordpress.stackexchange.com/questions/321657/memory-leak-in-plugin-action?noredirect=1#comment475327_321657), that a WP-CLI command might be better. The advantage is that the command runs from php directly on the server (usually has no max execution time, loads different php.ini, etc.) and you don't need to involve the webserver.
---
If that is not possible, the next best way is probably to [create a custom REST endpoint](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/). WordPress has a class [`WP_REST_Controller`](https://developer.wordpress.org/reference/classes/wp_rest_controller/), usually I write classes that `extend` this and work from there. For simplicity the following example is not using inheritence, but I try to keep to the same lingo.
**1. Register new route**
New/custom routes are registered via [`register_rest_route()`](https://developer.wordpress.org/reference/functions/register_rest_route/) like so
```
$version = 1;
$namespace = sprintf('acme/v%u', $version);
$base = '/import';
\register_rest_route(
$namespace,
$base,
[
[
'methods' => \WP_REST_Server::CREATABLE,
// equals ['POST','PUT','PATCH']
'callback' => [$this, 'import_csv'],
'permission_callback' => [$this, 'get_import_permissions_check'],
'args' => [],
// used for OPTIONS calls, left out for simplicity's sake
],
]
);
```
This will create a new route that you can call via
```
http://www.example.com/wp-json/acme/v1/import/
default REST start-^ ^ ^
namespace with version-| |-base
```
**2. Define permissions check**
Maybe you need authentication? Use nonces?
```
public function get_import_permissions_check($request)
{
//TODO: implement
return true;
}
```
**3. Create your actual endpoint callback**
The method previously defined gets passed a [`WP_REST_Request`](https://developer.wordpress.org/reference/classes/wp_rest_request/) object, use that to access request body, etc. To stay consistent, it is usually best to return a [`WP_REST_Response`](https://developer.wordpress.org/reference/classes/wp_rest_response/) instead of custom printing of JSON or similar.
```
public function import_csv($request)
{
$data = [];
// do stuff
return new \WP_REST_Response($data, 200);
}
```
---
If you do all of this in OOP style, you'll get the following class
```
class Import_CSV
{
/**
* register routes for this controller
*/
public function register_routes()
{
$version = 1;
$namespace = sprintf('acme/v%u', $version);
$base = '/import';
\register_rest_route(
$namespace,
$base,
[
[
'methods' => \WP_REST_Server::CREATABLE,
'callback' => [$this, 'import_csv'],
'permission_callback' => [$this, 'get_import_permissions_check'],
'args' => [],
],
]
);
}
/**
* endpoint for POST|PUT|PATCH /acme/v1/import
*/
public function import_csv($request)
{
$data = [];
// do stuff
return new \WP_REST_Response($data, 200);
}
/**
* check if user is permitted to access the import route
*/
public function get_import_permissions_check($request)
{
//TODO: implement
return true;
}
}
```
But .. still 404? Yes, simply defining the class sadly doesn't work (no autoloading by default :( ), so we need to run `register_routes()` like so (in your plugin file)
```
require_once 'Import_CSV.php';
add_action('rest_api_init', function(){
$import_csv = new \Import_CSV;
$import_csv->register_routes();
});
``` |
321,662 | <p>I've registered a custom editor block with Advanced Custom Fields (ACF), and am using <code>render_template</code> with a PHP template partial to display the block contents.</p>
<p>Inside the template is some HTML (<code>section</code> with a <code>figure</code> and an <code>a</code> inside it). When the block is called and the template generates the HTML, it's exactly as I author it, but when displayed on the front end, the <code>a</code> gets wrapped in a <code>p</code> tag, and a couple of <code>br</code> elements are added (I assume from <code>wpautop()</code>). This isn't happening on the editor side, just on the front end, which leads me to believe the block HTML is getting run through <code>the_content</code> or some other filters that run <code>wpautop()</code> before display.</p>
<p>I've tried running the block content through buffering, which breaks the editor but fixes the front end, and tried disabling <code>wpautop</code> from running in <code>the_content</code> filter, but have had mixed results.</p>
<p>So my question is how to tell WordPress that I like my markup, thank you very much, and please leave it alone for this specific block?</p>
<p>Here's a Gist of the block template: <a href="https://gist.github.com/morganestes/eca76cf8490f7b943d2f44c75674b648" rel="nofollow noreferrer">https://gist.github.com/morganestes/eca76cf8490f7b943d2f44c75674b648</a>.</p>
| [
{
"answer_id": 321667,
"author": "Morgan Estes",
"author_id": 26317,
"author_profile": "https://wordpress.stackexchange.com/users/26317",
"pm_score": 2,
"selected": false,
"text": "<p>I've found that I can use the <code>render_block</code> filter to disable <code>wpautop()</code> when a block gets rendered. It looks to me that this only affects the immediate block, as the filter gets re-enabled from <code>do_blocks()</code> calling <code>_restore_wpautop_hook()</code>. This lets me avoid using output buffering inside the block template, and moves the logic for filtering output out of the template and into a filter callback, where it makes more sense.</p>\n\n<pre><code>/**\n * Try to disable wpautop inside specific blocks.\n *\n * @link https://wordpress.stackexchange.com/q/321662/26317\n *\n * @param string $block_content The HTML generated for the block.\n * @param array $block The block.\n */\nadd_filter( 'render_block', function ( $block_content, $block ) {\n if ( 'acf/featured-pages' === $block['blockName'] ) {\n remove_filter( 'the_content', 'wpautop' );\n }\n\n return $block_content;\n}, 10, 2 );\n</code></pre>\n\n<p>I'm not sure of all the ramifications of this, but it's working to solve my immediate problem.</p>\n"
},
{
"answer_id": 323451,
"author": "Abbas Arif",
"author_id": 157344,
"author_profile": "https://wordpress.stackexchange.com/users/157344",
"pm_score": 2,
"selected": false,
"text": "<p>@morgan-estes Great solution but it i think it should be better to <strong>add_filter</strong> in else so the next block or content gets filter with WPAUTOP</p>\n\n<pre><code>/**\n * Try to disable wpautop inside specific blocks.\n *\n * @link https://wordpress.stackexchange.com/q/321662/26317\n *\n * @param string $block_content The HTML generated for the block.\n * @param array $block The block.\n */\nadd_filter( 'render_block', function ( $block_content, $block ) {\n if ( 'acf/featured-pages' === $block['blockName'] ) {\n remove_filter( 'the_content', 'wpautop' );\n } elseif ( ! has_filter( 'the_content', 'wpautop' ) ) {\n add_filter( 'the_content', 'wpautop' );\n }\n\n return $block_content;\n}, 10, 2 );\n</code></pre>\n"
}
]
| 2018/12/11 | [
"https://wordpress.stackexchange.com/questions/321662",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26317/"
]
| I've registered a custom editor block with Advanced Custom Fields (ACF), and am using `render_template` with a PHP template partial to display the block contents.
Inside the template is some HTML (`section` with a `figure` and an `a` inside it). When the block is called and the template generates the HTML, it's exactly as I author it, but when displayed on the front end, the `a` gets wrapped in a `p` tag, and a couple of `br` elements are added (I assume from `wpautop()`). This isn't happening on the editor side, just on the front end, which leads me to believe the block HTML is getting run through `the_content` or some other filters that run `wpautop()` before display.
I've tried running the block content through buffering, which breaks the editor but fixes the front end, and tried disabling `wpautop` from running in `the_content` filter, but have had mixed results.
So my question is how to tell WordPress that I like my markup, thank you very much, and please leave it alone for this specific block?
Here's a Gist of the block template: <https://gist.github.com/morganestes/eca76cf8490f7b943d2f44c75674b648>. | I've found that I can use the `render_block` filter to disable `wpautop()` when a block gets rendered. It looks to me that this only affects the immediate block, as the filter gets re-enabled from `do_blocks()` calling `_restore_wpautop_hook()`. This lets me avoid using output buffering inside the block template, and moves the logic for filtering output out of the template and into a filter callback, where it makes more sense.
```
/**
* Try to disable wpautop inside specific blocks.
*
* @link https://wordpress.stackexchange.com/q/321662/26317
*
* @param string $block_content The HTML generated for the block.
* @param array $block The block.
*/
add_filter( 'render_block', function ( $block_content, $block ) {
if ( 'acf/featured-pages' === $block['blockName'] ) {
remove_filter( 'the_content', 'wpautop' );
}
return $block_content;
}, 10, 2 );
```
I'm not sure of all the ramifications of this, but it's working to solve my immediate problem. |
321,674 | <p>I don't understand why my request to WooCommerce API doesn't work.
My usage on react App via axios:</p>
<p>First try:</p>
<pre><code>return axios.get( 'http://domain/wp-json/wc/v3/products?featured=true',
{
headers: {
'consumer_key': 'ck_xxx',
'consumer_secret': 'cs_xxx',
'key_id': 111,
'key_permissions': 'read_write',
'user_id': 111,
}
)
</code></pre>
<p>Second one:</p>
<pre><code>return axios( {
url: 'http://domain/wp-json/wc/v3/products?featured=true',
headers: {
'origin': 'http;//localhost:3000',
'consumer_key': 'ck_x',
'consumer_secret': 'cs_x',
'key_id': 111,
'key_permissions': 'read_write',
'user_id': 111,
},
method: 'GET',
}
} )
</code></pre>
<p>And I get CORS error. But using Insomnia software I create a GET request to <code>http://domain/wp-json/wc/v3/products?featured=true</code> with Basic Auth tab:</p>
<pre><code>USERNAME ck_x
PASSWORD cs_x
</code></pre>
<p>therefore response status is 200 OK.</p>
<p>I appreciate to understand what I'm doing wrong in axios inside my React App.</p>
| [
{
"answer_id": 339181,
"author": "Caio Mar",
"author_id": 54189,
"author_profile": "https://wordpress.stackexchange.com/users/54189",
"pm_score": 3,
"selected": true,
"text": "<p>I was having the same issue with Woocommerce Oauth 1.0 authentication and <a href=\"https://stackoverflow.com/a/45465247/2550766\">this solution</a> worked for me. I'm running it on localhost, so far so good.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Let me elaborate this answer a bit more. I just started learning React last night and the best way to learn is by doing. I'll explain as a newbie for a newbie. Here we go...</p>\n\n<p>I created this <em>Woocommerce helper object</em> that can be called from any component and it does all the hard work for you:</p>\n\n<p><strong><code>Woocommerce.js</code></strong></p>\n\n<pre><code>import axios from \"axios\";\nimport Oauth from \"oauth-1.0a\";\nimport CryptoJS from \"crypto-js\";\nimport jQuery from \"jquery\";\n\nconst ck = \"ck_...\";\nconst cs = \"cs_...\";\nconst baseURL = \"http://yourdomain.com/wp-json\";\n\nconst Woocommerce = {\n getProducts: () => {\n return makeRequest(\"/wc/v3/products\");\n },\n getProductByID: id => {\n return makeRequest(\"/wc/v3/products/\" + id);\n }\n};\n\nfunction makeRequest(endpoint, method = \"GET\") {\n const oauth = getOauth();\n\n const requestData = {\n url: baseURL + endpoint,\n method\n };\n\n const requestHTTP =\n requestData.url + \"?\" + jQuery.param(oauth.authorize(requestData));\n\n return axios.get(requestHTTP);\n}\n\nfunction getOauth() {\n return Oauth({\n consumer: {\n key: ck,\n secret: cs\n },\n signature_method: \"HMAC-SHA1\",\n hash_function: function(base_string, key) {\n return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(base_string, key));\n }\n });\n}\n\nexport default Woocommerce;\n</code></pre>\n\n<p>You will need to install all the necessary packages by running the commands:</p>\n\n<pre><code>npm install axios jquery crypto-js\nnpm install oauth-1.0a --production\n</code></pre>\n\n<p><strong>How to use it</strong></p>\n\n<p>First import it to the component:</p>\n\n<pre><code>import Woocommerce from \"./functions/Woocommerce\";\n</code></pre>\n\n<p>Then from inside the component you can call it like this to get all the products:</p>\n\n<pre><code>// All products (array of objects)\nstate = { products: [], isLoaded: false };\n\ncomponentWillMount() {\n Woocommerce.getProducts().then(res =>\n this.setState({ products: res.data, isLoaded: true })\n );\n}\n</code></pre>\n\n<p>Or, to get only one product by ID, you can do:</p>\n\n<pre><code>// Single product (object)\nstate = { product: {}, isLoaded: false };\n\ncomponentWillMount() {\n Woocommerce.getProductByID(123).then(res =>\n this.setState({ product: res.data, isLoaded: true })\n );\n}\n</code></pre>\n\n<p>As you can probably see, you can elaborate more functions inside of the Woocommerce helper and retrieve products using the Woocommerce REST API as you wish. </p>\n\n<p>Happy coding... ;)</p>\n"
},
{
"answer_id": 377077,
"author": "Xavier Lopez",
"author_id": 179859,
"author_profile": "https://wordpress.stackexchange.com/users/179859",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks, @ColdTuna!</p>\n<p>Just in case anyone wants a sample code with React Hooks:</p>\n<p><strong>Products.js</strong></p>\n<pre><code>import React from 'react';\nimport { useEffect, useState } from "react";\nimport Woocommerce from "../functions/Woocommerce";\n\n\nfunction Products() {\n const [products, setProducts] = useState(0);\n \n useEffect(() => {\n Woocommerce.getProducts()\n .then( (res) => {\n setProducts(res.data)\n } ); \n },[]\n );\n\n return (\n <ul>\n {Object.values(products).map( (item, itemIndex) => {\n return <li key={item.id}>{itemIndex}-{item.name},{item.price} - \n {\n item.images.map( (image, imgIndex) => {\n return <img key={imgIndex} src={image.src}></img>;\n })\n } \n </li>\n })\n }\n </ul>\n );\n}\n \nexport default Products\n</code></pre>\n"
},
{
"answer_id": 407166,
"author": "necip",
"author_id": 222320,
"author_profile": "https://wordpress.stackexchange.com/users/222320",
"pm_score": 0,
"selected": false,
"text": "<p>It's old question but maybe it works for who struggle with this problem. You can use woocommerce 's own api (<a href=\"https://woocommerce.github.io/woocommerce-rest-api-docs/\" rel=\"nofollow noreferrer\">https://woocommerce.github.io/woocommerce-rest-api-docs/</a>)</p>\n<pre><code>// Install:\n// npm install --save @woocommerce/woocommerce-rest-api\n\n// Setup:\nconst WooCommerceRestApi = require("@woocommerce/woocommerce-rest- api").default;\n// import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api"; // Supports ESM\n\nconst WooCommerce = new WooCommerceRestApi({\n url: 'http://example.com', // Your store URL\n consumerKey: 'consumer_key', // Your consumer key\n consumerSecret: 'consumer_secret', // Your consumer secret\n version: 'wc/v3' // WooCommerce WP REST API version\n});\n</code></pre>\n"
}
]
| 2018/12/11 | [
"https://wordpress.stackexchange.com/questions/321674",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89766/"
]
| I don't understand why my request to WooCommerce API doesn't work.
My usage on react App via axios:
First try:
```
return axios.get( 'http://domain/wp-json/wc/v3/products?featured=true',
{
headers: {
'consumer_key': 'ck_xxx',
'consumer_secret': 'cs_xxx',
'key_id': 111,
'key_permissions': 'read_write',
'user_id': 111,
}
)
```
Second one:
```
return axios( {
url: 'http://domain/wp-json/wc/v3/products?featured=true',
headers: {
'origin': 'http;//localhost:3000',
'consumer_key': 'ck_x',
'consumer_secret': 'cs_x',
'key_id': 111,
'key_permissions': 'read_write',
'user_id': 111,
},
method: 'GET',
}
} )
```
And I get CORS error. But using Insomnia software I create a GET request to `http://domain/wp-json/wc/v3/products?featured=true` with Basic Auth tab:
```
USERNAME ck_x
PASSWORD cs_x
```
therefore response status is 200 OK.
I appreciate to understand what I'm doing wrong in axios inside my React App. | I was having the same issue with Woocommerce Oauth 1.0 authentication and [this solution](https://stackoverflow.com/a/45465247/2550766) worked for me. I'm running it on localhost, so far so good.
**Edit:**
Let me elaborate this answer a bit more. I just started learning React last night and the best way to learn is by doing. I'll explain as a newbie for a newbie. Here we go...
I created this *Woocommerce helper object* that can be called from any component and it does all the hard work for you:
**`Woocommerce.js`**
```
import axios from "axios";
import Oauth from "oauth-1.0a";
import CryptoJS from "crypto-js";
import jQuery from "jquery";
const ck = "ck_...";
const cs = "cs_...";
const baseURL = "http://yourdomain.com/wp-json";
const Woocommerce = {
getProducts: () => {
return makeRequest("/wc/v3/products");
},
getProductByID: id => {
return makeRequest("/wc/v3/products/" + id);
}
};
function makeRequest(endpoint, method = "GET") {
const oauth = getOauth();
const requestData = {
url: baseURL + endpoint,
method
};
const requestHTTP =
requestData.url + "?" + jQuery.param(oauth.authorize(requestData));
return axios.get(requestHTTP);
}
function getOauth() {
return Oauth({
consumer: {
key: ck,
secret: cs
},
signature_method: "HMAC-SHA1",
hash_function: function(base_string, key) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(base_string, key));
}
});
}
export default Woocommerce;
```
You will need to install all the necessary packages by running the commands:
```
npm install axios jquery crypto-js
npm install oauth-1.0a --production
```
**How to use it**
First import it to the component:
```
import Woocommerce from "./functions/Woocommerce";
```
Then from inside the component you can call it like this to get all the products:
```
// All products (array of objects)
state = { products: [], isLoaded: false };
componentWillMount() {
Woocommerce.getProducts().then(res =>
this.setState({ products: res.data, isLoaded: true })
);
}
```
Or, to get only one product by ID, you can do:
```
// Single product (object)
state = { product: {}, isLoaded: false };
componentWillMount() {
Woocommerce.getProductByID(123).then(res =>
this.setState({ product: res.data, isLoaded: true })
);
}
```
As you can probably see, you can elaborate more functions inside of the Woocommerce helper and retrieve products using the Woocommerce REST API as you wish.
Happy coding... ;) |
321,726 | <p>I have a CPT and inside the CPT I have a contact form. The contact form directly sends to WordPress dashboard, Now I'm trying to implement when a user submits the contact form they will receive a "Thanks for contacting US" message in their Email address(User fill email in the form) I'm new in WordPress & PHP. I'm using Ajax form validation & pass data. <code>$email = sanitize_email($_POST['email']);</code>. This variable data capture from user email address an after send their email address thanks email. Have any help greatly appreciated.</p>
<p><strong>EDIT</strong></p>
<p>I can Email to my WordPress site hosted email id eg: [email protected] another Gmail,hotmail,live like email proveders not working. I checked a small plugin <a href="https://wordpress.org/plugins/check-email/" rel="nofollow noreferrer">check email</a> it is not a smtp but that can send email to any email providers. I don't know what wrong with with me, I tried Everything I can.</p>
<pre><code>public function submit_testimonial()
{
if (! DOING_AJAX || ! check_ajax_referer('testimonial-nonce', 'nonce') ) {
return $this->return_json('error');
}
$name = sanitize_text_field($_POST['name']);
$package = sanitize_text_field($_POST['package']);
$phone = sanitize_text_field($_POST['phone']);
$date = sanitize_text_field($_POST['date']);
$email = sanitize_email($_POST['email']);
$message = sanitize_textarea_field($_POST['message']);
$data = array(
'name' => $name,
'package' => $package,
'phone' => $phone,
'email' => $email,
'date' => $date,
'date' => $message,
'approved' => 0,
'featured' => 0,
);
$args = array(
'post_title' => $name,
'post_content' => $message,
'post_author' => 1,
'post_status' => 'publish',
'post_type' => 'testimonial',
'meta_input' => array(
'_zon_testimonial_key' => $data
)
);
$postID = wp_insert_post( $args );
if ($postID) {
$headers = "MIME-Version: 1.0\r\n" .
"From: " . $current_user->user_email . "\r\n" .
"Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\r\n";
$to = $email;
$title = "Test email from";
$body = "Hello " . $name . " Your ZonPackage " . $package . " Booking Confirmed ." ;
$subject ="Zon Package Booking";
wp_mail( $to, $subject, $body, $headers );
}
if ($postID) {
return $this->return_json('success');
}
}
public function return_json( $status ) {
$return = array(
'status' => $status
);
wp_send_json($return);
}
</code></pre>
| [
{
"answer_id": 321735,
"author": "Greg Winiarski",
"author_id": 154460,
"author_profile": "https://wordpress.stackexchange.com/users/154460",
"pm_score": 0,
"selected": false,
"text": "<p>If the post is saved in the database then your <code>mail()</code> nor <code>wp_mail()</code> functions are not run because the function ends here</p>\n\n<pre><code>if ($postID) {\n return $this->return_json('success');\n}\n</code></pre>\n\n<p>Cut these three lines of code and paste them before <code>return $this->return_json('error');</code></p>\n\n<p>Additionally, you do not need the wp_die() function as the wp_send_json() will run exit; for you.</p>\n"
},
{
"answer_id": 321740,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 3,
"selected": true,
"text": "<p>I revised your code to address some issues, but there is the possibility that the issue is not your code.</p>\n\n<p>First, you are returning too early. Your original code returns on success before you send the email. I moved this to the end so that it sets a value (success or error) at the end based on whether you have a post ID or not, then returns. That way you get your mail functions as well.</p>\n\n<p>It's unlikely that you need both <code>wp_mail()</code> and <code>mail()</code>. If you're doing that because you think <code>wp_mail()</code> is not working, that's really not going to help. <code>wp_mail()</code> uses the phpMailer library If you haven't done any customization, phpMailer is going to use <code>mail()</code> - so these are ultimately the same unless this was run without WP in which case you'd get errors because functions like <code>wp_insert_post()</code> would be undefined.</p>\n\n<p>Also, the documentation for <a href=\"https://codex.wordpress.org/Function_Reference/wp_send_json\" rel=\"nofollow noreferrer\"><code>wp_send_json()</code></a> indicates that you do not need <code>wp_die()</code> as it handles that for you in the function.</p>\n\n<p>Here's your code with those changes:</p>\n\n<pre><code>public function submit_contact() {\n\n if (! DOING_AJAX || ! check_ajax_referer('contact-nonce', 'nonce') ) {\n return $this->return_json('error');\n }\n\n $name = sanitize_text_field( $_POST['name'] );\n $phone = sanitize_text_field( $_POST['phone'] );\n $email = sanitize_email( $_POST['email'] );\n $message = sanitize_textarea_field( $_POST['message'] );\n\n $data = array(\n\n 'name' => $name,\n 'package' => $package,\n 'phone' => $phone,\n 'email' => $email,\n 'date' => $date,\n 'date' => $message,\n 'approved' => 0,\n 'featured' => 0,\n );\n\n $args = array(\n 'post_title' => $name,\n 'post_content' => $message,\n 'post_author' => 1,\n 'post_status' => 'publish',\n 'post_type' => 'contact',\n 'meta_input' => array(\n '_zon_contact_key' => $data\n )\n );\n\n $postID = wp_insert_post( $args );\n\n if ( $postID ) {\n wp_mail( '[email protected]', 'The subject', 'The message' );\n }\n\n $return_val = ( $postID ) ? 'success' : 'error';\n return $return_val;\n}\n\npublic function return_json( $status ) {\n\n $return = array(\n 'status' => $status\n );\n\n wp_send_json($return);\n\n}\n</code></pre>\n\n<p><strong>If you're still not getting emails</strong>, I would do some troubleshooting on the email side of things. If the post is inserted and no email, your code is working and it's likely an issue with the mail send, not your code.</p>\n\n<p>If you're on shared hosting, you need to check into rules for sending email via scripts. WP will send from \"[email protected]\" by default. Some hosts require the \"from\" address be a real email. So check into that. Also, you've got this code set up for testing with a simple subject and message body. There is the possibility that the sending host is rejecting because it thinks it's spam based on the body text being so short.</p>\n\n<p><strong>Note: I updated and clarified this section</strong></p>\n\n<p>My suspicion is that if you put in an email logger, you'll may find that the <code>wp_mail()</code> is running (and logging) as if the mail is sent, but that you still don't receive it. And if that's the case, it's because your host is rejecting the send.</p>\n\n<p>It's easy to avoid all of these things by setting up to send through SMTP. That would avoid most issues. There are a lot of ways to do that, using a plugin or using code. The Internet abounds with examples - <a href=\"https://www.butlerblog.com/2013/12/12/easy-smtp-email-wordpress-wp_mail/\" rel=\"nofollow noreferrer\">this is just one of them</a>.</p>\n\n<p>If you can't use SMTP, then you may need to troubleshoot other possible email issues with WP's default headers and things like that. Here's <a href=\"https://www.butlerblog.com/2013/09/24/troubleshooting-the-wp_mail-function/\" rel=\"nofollow noreferrer\">an article with more information on that kind of troubleshooting</a>.</p>\n\n<p><strong>UPDATE #2 - Address Email Not Being Received</strong></p>\n\n<p>Based on your update, your issue is email not being received. IMO, that's likely due to the way you're setting the headers. As a result, your email is getting rejected.</p>\n\n<p>As I stated in the original answer, you're better off setting up to send through an SMTP account. That will help you avoid a lot of potential problems.</p>\n\n<p>Regardless of whether you do that or not, you need to fix your header issue. Don't mess with headers unless you absolutely need to. I'd recommend you take that out completely. </p>\n\n<p>If you must leave it in, you need to fix the following:</p>\n\n<ol>\n<li>Unless you're changing something, don't declare it.</li>\n<li>$current_user is undefined.</li>\n<li>Pass headers as array values.</li>\n<li>\"From\" value in the header is malformed.</li>\n</ol>\n\n<p><strong>Unless you're changing something, don't declare it.</strong> <code>wp_mail()</code> sets any defaults that are not declared. I would suggest you take out the mime type declaration and the content type for sure.</p>\n\n<p><strong><code>$current_user</code> is undefined</strong> in the code that you posted. Add the following to make sure it's defined:</p>\n\n<pre><code>$current_user = wp_get_current_user();\n</code></pre>\n\n<p><strong>Pass headers as array values</strong>. <code>wp_mail()</code> takes either a string or array, but if it's a string, it gets exploded into an array, so you may as well start with an array.</p>\n\n<p><strong>\"From\" value in the header is malformed</strong> the way you have it. You must also have a \"from\" name in addition to the address. It needs to be in the following format:</p>\n\n<pre><code>\"From: The From Name <[email protected]>\"\n</code></pre>\n\n<p>If you don't have the \"name\", substitute the email address:</p>\n\n<pre><code>$headers[] = 'From: ' . $current_user->user_email . '<' . $current_user->user_email . '>';\n</code></pre>\n\n<p>So with those things addressed, here's what I recommend:</p>\n\n<pre><code> if ($postID) {\n $current_user = wp_get_current_user();\n $headers[] = 'From: ' . $current_user->user_email . '<' . $current_user->user_email . '>';\n $to = $email;\n $title = \"Test email from\";\n $body = \"Hello \" . $name . \" Your ZonPackage \" . $package . \" Booking Confirmed .\" ;\n $subject =\"Zon Package Booking\";\n wp_mail( $to, $subject, $body, $headers );\n }\n</code></pre>\n\n<p>Keep in mind that may not solve your problem entirely. If your \"from\" address doesn't have a domain that matches the sending domain, you may still look \"spammy\" and get rejected. Also, be sure to check your spam folder to see if your messages are being received but are flagged as spam.</p>\n"
}
]
| 2018/12/12 | [
"https://wordpress.stackexchange.com/questions/321726",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/149857/"
]
| I have a CPT and inside the CPT I have a contact form. The contact form directly sends to WordPress dashboard, Now I'm trying to implement when a user submits the contact form they will receive a "Thanks for contacting US" message in their Email address(User fill email in the form) I'm new in WordPress & PHP. I'm using Ajax form validation & pass data. `$email = sanitize_email($_POST['email']);`. This variable data capture from user email address an after send their email address thanks email. Have any help greatly appreciated.
**EDIT**
I can Email to my WordPress site hosted email id eg: [email protected] another Gmail,hotmail,live like email proveders not working. I checked a small plugin [check email](https://wordpress.org/plugins/check-email/) it is not a smtp but that can send email to any email providers. I don't know what wrong with with me, I tried Everything I can.
```
public function submit_testimonial()
{
if (! DOING_AJAX || ! check_ajax_referer('testimonial-nonce', 'nonce') ) {
return $this->return_json('error');
}
$name = sanitize_text_field($_POST['name']);
$package = sanitize_text_field($_POST['package']);
$phone = sanitize_text_field($_POST['phone']);
$date = sanitize_text_field($_POST['date']);
$email = sanitize_email($_POST['email']);
$message = sanitize_textarea_field($_POST['message']);
$data = array(
'name' => $name,
'package' => $package,
'phone' => $phone,
'email' => $email,
'date' => $date,
'date' => $message,
'approved' => 0,
'featured' => 0,
);
$args = array(
'post_title' => $name,
'post_content' => $message,
'post_author' => 1,
'post_status' => 'publish',
'post_type' => 'testimonial',
'meta_input' => array(
'_zon_testimonial_key' => $data
)
);
$postID = wp_insert_post( $args );
if ($postID) {
$headers = "MIME-Version: 1.0\r\n" .
"From: " . $current_user->user_email . "\r\n" .
"Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\r\n";
$to = $email;
$title = "Test email from";
$body = "Hello " . $name . " Your ZonPackage " . $package . " Booking Confirmed ." ;
$subject ="Zon Package Booking";
wp_mail( $to, $subject, $body, $headers );
}
if ($postID) {
return $this->return_json('success');
}
}
public function return_json( $status ) {
$return = array(
'status' => $status
);
wp_send_json($return);
}
``` | I revised your code to address some issues, but there is the possibility that the issue is not your code.
First, you are returning too early. Your original code returns on success before you send the email. I moved this to the end so that it sets a value (success or error) at the end based on whether you have a post ID or not, then returns. That way you get your mail functions as well.
It's unlikely that you need both `wp_mail()` and `mail()`. If you're doing that because you think `wp_mail()` is not working, that's really not going to help. `wp_mail()` uses the phpMailer library If you haven't done any customization, phpMailer is going to use `mail()` - so these are ultimately the same unless this was run without WP in which case you'd get errors because functions like `wp_insert_post()` would be undefined.
Also, the documentation for [`wp_send_json()`](https://codex.wordpress.org/Function_Reference/wp_send_json) indicates that you do not need `wp_die()` as it handles that for you in the function.
Here's your code with those changes:
```
public function submit_contact() {
if (! DOING_AJAX || ! check_ajax_referer('contact-nonce', 'nonce') ) {
return $this->return_json('error');
}
$name = sanitize_text_field( $_POST['name'] );
$phone = sanitize_text_field( $_POST['phone'] );
$email = sanitize_email( $_POST['email'] );
$message = sanitize_textarea_field( $_POST['message'] );
$data = array(
'name' => $name,
'package' => $package,
'phone' => $phone,
'email' => $email,
'date' => $date,
'date' => $message,
'approved' => 0,
'featured' => 0,
);
$args = array(
'post_title' => $name,
'post_content' => $message,
'post_author' => 1,
'post_status' => 'publish',
'post_type' => 'contact',
'meta_input' => array(
'_zon_contact_key' => $data
)
);
$postID = wp_insert_post( $args );
if ( $postID ) {
wp_mail( '[email protected]', 'The subject', 'The message' );
}
$return_val = ( $postID ) ? 'success' : 'error';
return $return_val;
}
public function return_json( $status ) {
$return = array(
'status' => $status
);
wp_send_json($return);
}
```
**If you're still not getting emails**, I would do some troubleshooting on the email side of things. If the post is inserted and no email, your code is working and it's likely an issue with the mail send, not your code.
If you're on shared hosting, you need to check into rules for sending email via scripts. WP will send from "[email protected]" by default. Some hosts require the "from" address be a real email. So check into that. Also, you've got this code set up for testing with a simple subject and message body. There is the possibility that the sending host is rejecting because it thinks it's spam based on the body text being so short.
**Note: I updated and clarified this section**
My suspicion is that if you put in an email logger, you'll may find that the `wp_mail()` is running (and logging) as if the mail is sent, but that you still don't receive it. And if that's the case, it's because your host is rejecting the send.
It's easy to avoid all of these things by setting up to send through SMTP. That would avoid most issues. There are a lot of ways to do that, using a plugin or using code. The Internet abounds with examples - [this is just one of them](https://www.butlerblog.com/2013/12/12/easy-smtp-email-wordpress-wp_mail/).
If you can't use SMTP, then you may need to troubleshoot other possible email issues with WP's default headers and things like that. Here's [an article with more information on that kind of troubleshooting](https://www.butlerblog.com/2013/09/24/troubleshooting-the-wp_mail-function/).
**UPDATE #2 - Address Email Not Being Received**
Based on your update, your issue is email not being received. IMO, that's likely due to the way you're setting the headers. As a result, your email is getting rejected.
As I stated in the original answer, you're better off setting up to send through an SMTP account. That will help you avoid a lot of potential problems.
Regardless of whether you do that or not, you need to fix your header issue. Don't mess with headers unless you absolutely need to. I'd recommend you take that out completely.
If you must leave it in, you need to fix the following:
1. Unless you're changing something, don't declare it.
2. $current\_user is undefined.
3. Pass headers as array values.
4. "From" value in the header is malformed.
**Unless you're changing something, don't declare it.** `wp_mail()` sets any defaults that are not declared. I would suggest you take out the mime type declaration and the content type for sure.
**`$current_user` is undefined** in the code that you posted. Add the following to make sure it's defined:
```
$current_user = wp_get_current_user();
```
**Pass headers as array values**. `wp_mail()` takes either a string or array, but if it's a string, it gets exploded into an array, so you may as well start with an array.
**"From" value in the header is malformed** the way you have it. You must also have a "from" name in addition to the address. It needs to be in the following format:
```
"From: The From Name <[email protected]>"
```
If you don't have the "name", substitute the email address:
```
$headers[] = 'From: ' . $current_user->user_email . '<' . $current_user->user_email . '>';
```
So with those things addressed, here's what I recommend:
```
if ($postID) {
$current_user = wp_get_current_user();
$headers[] = 'From: ' . $current_user->user_email . '<' . $current_user->user_email . '>';
$to = $email;
$title = "Test email from";
$body = "Hello " . $name . " Your ZonPackage " . $package . " Booking Confirmed ." ;
$subject ="Zon Package Booking";
wp_mail( $to, $subject, $body, $headers );
}
```
Keep in mind that may not solve your problem entirely. If your "from" address doesn't have a domain that matches the sending domain, you may still look "spammy" and get rejected. Also, be sure to check your spam folder to see if your messages are being received but are flagged as spam. |
321,764 | <p>Somehow when I was working with my local dev environment, I have made some mistakes in some php files which I could not figure it out.</p>
<p>So, I have decided to copy the files from the <code>public_html</code> and paste in my local copy of the WordPress..</p>
<p>Now when I open my website in my local machine, it shows the front page without any problem. But when I click on any other links, to visit any other page, it just kicks me back to </p>
<pre><code>localhost:8080/dashboard
</code></pre>
<p>Why this is happening?? </p>
<p>I could understand one thing that the permalinks has to be refreshed. But, I could not even access the <code>localhost:8080/mysite/wp-admin</code>. Is there any other way, that I can refresh the permalinks??</p>
<p>What is the procedure to take a copy of wordpress website from online server to offline?? </p>
<p>PS: I use xmapp with sql and WordPress 4.9.8</p>
| [
{
"answer_id": 321802,
"author": "Kevin",
"author_id": 153905,
"author_profile": "https://wordpress.stackexchange.com/users/153905",
"pm_score": -1,
"selected": false,
"text": "<p>One solution is that you might want to include a .htaccess file to your <strong>local</strong> instance.</p>\n"
},
{
"answer_id": 321811,
"author": "Remzi Cavdar",
"author_id": 149484,
"author_profile": "https://wordpress.stackexchange.com/users/149484",
"pm_score": 1,
"selected": false,
"text": "<h1>XAMPP dashboard</h1>\n\n<p>XAMP has some default files (example files), you should delete that.\nIt's just there to show you that everything works as expected.</p>\n\n<p>With also an example .htacess which redirects you to dashboard. Before you copy and paste your files, you should have deleted everything in <strong>C:\\xampp\\htdocs (your htdocs)</strong></p>\n\n<h2>Manual install or automatic</h2>\n\n<p>You could install WordPress by yourself, you will need to download WP, create a database and database user and edited the WP config.php file.</p>\n\n<p>You could also just download an Add-on for XAMPP which does this for you: <a href=\"https://www.apachefriends.org/add-ons.html\" rel=\"nofollow noreferrer\">https://www.apachefriends.org/add-ons.html</a></p>\n\n<p>And it will install this in a separate folder <strong>C:\\xampp\\apps\\wordpress\\htdocs</strong> which is handy if you want to test other things then only WordPress.</p>\n"
}
]
| 2018/12/12 | [
"https://wordpress.stackexchange.com/questions/321764",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111408/"
]
| Somehow when I was working with my local dev environment, I have made some mistakes in some php files which I could not figure it out.
So, I have decided to copy the files from the `public_html` and paste in my local copy of the WordPress..
Now when I open my website in my local machine, it shows the front page without any problem. But when I click on any other links, to visit any other page, it just kicks me back to
```
localhost:8080/dashboard
```
Why this is happening??
I could understand one thing that the permalinks has to be refreshed. But, I could not even access the `localhost:8080/mysite/wp-admin`. Is there any other way, that I can refresh the permalinks??
What is the procedure to take a copy of wordpress website from online server to offline??
PS: I use xmapp with sql and WordPress 4.9.8 | XAMPP dashboard
===============
XAMP has some default files (example files), you should delete that.
It's just there to show you that everything works as expected.
With also an example .htacess which redirects you to dashboard. Before you copy and paste your files, you should have deleted everything in **C:\xampp\htdocs (your htdocs)**
Manual install or automatic
---------------------------
You could install WordPress by yourself, you will need to download WP, create a database and database user and edited the WP config.php file.
You could also just download an Add-on for XAMPP which does this for you: <https://www.apachefriends.org/add-ons.html>
And it will install this in a separate folder **C:\xampp\apps\wordpress\htdocs** which is handy if you want to test other things then only WordPress. |
321,866 | <p>For my site, I need to have different header colors depending on the page it's on. Here's the code I have for my site that is working:</p>
<pre><code><?php if ( is_single() && is_post_type('product') || is_page(576) || is_single() && is_post_type('post')) : ?>
<div class="header-inner">
<style type="text/css">.header-inner { background-color:#861919!important; }</style>
<?php else : ?>
<div class="header-inner" style="background-color:rgba(0,0,0,0.30);">
<?php endif; ?>
</code></pre>
<p>I am trying to modify the above to exclude certain product posts due to their design. I will note that most products use post-template.php, and the ones I need to have a transparent header are using product-specialty.php. My developer installed the plugin WP Post to be able to select the different templates. Here's my attempt at the modified code but it's resulting in nothing loading:</p>
<pre><code><?php if ( is_single(893,892,843,895,894,896) ) : ?>
<div class="header-inner" style="background-color:rgba(0,0,0,0.30);">
<?php else( is_single() && is_post_type('product') || is_page(576) || is_single() && is_post_type('post')) : ?>
<div class="header-inner">
<style type="text/css">.header-inner { background-color:#861919!important; }</style>
<?php elseif : ?>
<div class="header-inner" style="background-color:rgba(0,0,0,0.30);">
<?php endif; ?>
</code></pre>
<p>Any idea what I'm doing wrong there?</p>
| [
{
"answer_id": 321869,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 1,
"selected": false,
"text": "<p>You are just passing through multiple values instead of a list. Switch to an array.</p>\n\n<p>Change this line: </p>\n\n<pre><code><?php if ( is_single(893,892,843,895,894,896) ) : ?>\n</code></pre>\n\n<p>to:</p>\n\n<pre><code><?php if ( is_single(array(893,892,843,895,894,896)) ) : ?>\n</code></pre>\n\n<p>More info: \n<a href=\"https://developer.wordpress.org/reference/functions/is_single/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/is_single/</a></p>\n"
},
{
"answer_id": 321870,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": true,
"text": "<p>Here is an alternative solution. I think it would be cleaner than adding all these if statements and page IDs. You can do this using CSS and the body class WP adds.</p>\n\n<p>For example, go to one of your single pages and look at the class on the body tag. You should see something like page-id-###. Then just simply add a rule in your stylesheet or the CSS customizer.</p>\n\n<p>Something like this...</p>\n\n<pre><code>body.page-id-123 .header-inner,\nbody.page-id-124 .header-inner,\nbody.page-id-125 .header-inner, {\n background-color:#861919!important;\n}\n</code></pre>\n\n<p>Here is how you can target some of your other pages.</p>\n\n<ul>\n<li>All Single Product Pages - body.single-product .header-inner {}</li>\n<li>Specific Single Post - body.postid-### .header-inner {}</li>\n<li>Blog Page - body.blog .header-inner {}</li>\n<li>All Single Blog Pages - body.single-post .header-inner {}</li>\n<li>Etc...</li>\n</ul>\n\n<p>Just inspect each page and you should get the idea.</p>\n\n<p><strong>Create your own body class</strong></p>\n\n<p>If needed you could create your own body class by using the body_class filter, here is a basic example of how to use it. Of course you could do more by adding conditionals or checking for templates.</p>\n\n<pre><code>function my_custom_body_class($classes) {\n $classes[] = 'foo';\n return $classes;\n}\n\nadd_filter('body_class', 'my_custom_body_class');\n</code></pre>\n"
}
]
| 2018/12/13 | [
"https://wordpress.stackexchange.com/questions/321866",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155767/"
]
| For my site, I need to have different header colors depending on the page it's on. Here's the code I have for my site that is working:
```
<?php if ( is_single() && is_post_type('product') || is_page(576) || is_single() && is_post_type('post')) : ?>
<div class="header-inner">
<style type="text/css">.header-inner { background-color:#861919!important; }</style>
<?php else : ?>
<div class="header-inner" style="background-color:rgba(0,0,0,0.30);">
<?php endif; ?>
```
I am trying to modify the above to exclude certain product posts due to their design. I will note that most products use post-template.php, and the ones I need to have a transparent header are using product-specialty.php. My developer installed the plugin WP Post to be able to select the different templates. Here's my attempt at the modified code but it's resulting in nothing loading:
```
<?php if ( is_single(893,892,843,895,894,896) ) : ?>
<div class="header-inner" style="background-color:rgba(0,0,0,0.30);">
<?php else( is_single() && is_post_type('product') || is_page(576) || is_single() && is_post_type('post')) : ?>
<div class="header-inner">
<style type="text/css">.header-inner { background-color:#861919!important; }</style>
<?php elseif : ?>
<div class="header-inner" style="background-color:rgba(0,0,0,0.30);">
<?php endif; ?>
```
Any idea what I'm doing wrong there? | Here is an alternative solution. I think it would be cleaner than adding all these if statements and page IDs. You can do this using CSS and the body class WP adds.
For example, go to one of your single pages and look at the class on the body tag. You should see something like page-id-###. Then just simply add a rule in your stylesheet or the CSS customizer.
Something like this...
```
body.page-id-123 .header-inner,
body.page-id-124 .header-inner,
body.page-id-125 .header-inner, {
background-color:#861919!important;
}
```
Here is how you can target some of your other pages.
* All Single Product Pages - body.single-product .header-inner {}
* Specific Single Post - body.postid-### .header-inner {}
* Blog Page - body.blog .header-inner {}
* All Single Blog Pages - body.single-post .header-inner {}
* Etc...
Just inspect each page and you should get the idea.
**Create your own body class**
If needed you could create your own body class by using the body\_class filter, here is a basic example of how to use it. Of course you could do more by adding conditionals or checking for templates.
```
function my_custom_body_class($classes) {
$classes[] = 'foo';
return $classes;
}
add_filter('body_class', 'my_custom_body_class');
``` |
321,868 | <p>I have multiple wp_query's on the same page. Each one of those queries has an AJAX "read more" button at the bottom. The problem I'm finding is that I can only get one to work at a time. Whichever function is added first in the functions.php, that one works - the other one gets a 403 error for admin-ajax.php. </p>
<p>I'm pretty new to AJAX, so I've probably made a total hash of it, and I'm sure there's a way to combine this into a single function (preferred!) but if I can even just find a way for them all to work independently, that work be fine.</p>
<p>Here's my code:</p>
<p>The 2 WP_Queries in a custom page-work.php template:</p>
<p>First one: </p>
<pre><code><?php
//Find out how many posts
$total_posts = wp_count_posts('smart_maps');
$total_posts = $total_posts->publish;
$number_shown = 0;
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<div id="smartmaps" class="smartmaps col xs-col-14 xs-offset-1 md-col-12 md-offset-2" style="display:none;">
<div class="in-here-smartmaps">
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<a href="<?php echo get_permalink(get_the_ID());?>">
<div class="single-smartmap col xs-col-16 md-col-8">
<div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center">
<div class="image-element">
<img src="<?php the_field('thumbnail_image');?>" class="circle">
<div class="image-overlay circle"></div>
</div>
</div>
<div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1">
<h5 class="smart-map-title"><?php the_title();?></h5>
<?php if(get_field('icons')) :?>
<div class="block-icons">
<?php if(in_array('Heart', get_field('icons'))) :?>
<span class="icon-heart"></span>
<?php endif;?>
<?php if(in_array('Plant', get_field('icons'))) :?>
<span class="icon-plant"></span>
<?php endif; ?>
<?php if(in_array('Cup', get_field('icons'))) :?>
<span class="icon-cup"></span>
<?php endif;?>
<?php if(in_array('Book', get_field('icons'))) :?>
<span class="icon-book"></span>
<?php endif;?>
</div>
<?php endif;?>
</div>
</div>
</a>
<?php $number_shown++;
endwhile; ?>
<?php endif;?>
</div>
<?php if($number_shown != $total_posts) :?>
<div class="loadmore smarties col xs-col-14 xs-offset-1 md-col-8 md-offset-4 center">
<h3><a href="#">LOAD MORE</a></h3>
</div>
<?php endif;?>
</div>
<div clas="clearfix"></div>
</code></pre>
<p>The second 1:</p>
<pre><code><div id="strategic-events" class="strategicevents col xs-col-14 xs-offset-1 md-col-12 md-offset-2" style="display:none;">
<div class="in-here-strats">
<?php
//Find out how many posts
$total_posts = wp_count_posts('strategic_events');
$total_posts = $total_posts->publish;
$number_shown = 0;
$args = array( 'post_type' => 'strategic_events', 'posts_per_page' => 10, 'offset' => $the_offset );
$the_query2 = new WP_Query( $args ); ?>
<?php if ( $the_query2->have_posts() ) :
while ( $the_query2->have_posts() ) : $the_query2->the_post(); ?>
<a href="<?php echo get_permalink(get_the_ID());?>">
<div class="single-strategicevent col xs-col-16 md-col-8">
<div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center">
<div class="image-element">
<img src="<?php the_field('strategic_event_image');?>" class="circle">
<div class="image-overlay circle"></div>
</div>
</div>
<div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1">
<h5 class="strategic-event-title"><?php the_title();?></h5>
<?php if(get_field('subtitle')) :?>
<p><?php the_field('subtitle');?></p>
<small><?php the_field('location_text');?></small>
<?php endif;?>
</div>
</div>
</a>
<?php $number_shown++;
endwhile;
endif; ?>
</div>
<?php if($number_shown != $total_posts) :?>
<div class="loadmore strats col xs-col-14 xs-offset-1 md-col-8 md-offset-4 center">
<h3><a href="#">LOAD MORE</a></h3>
</div>
<?php endif;?>
</div>
<div class="clearfix"></div>
</code></pre>
<p>My JS code (both also in the page-work.php for now)...</p>
<pre><code><script>
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore.strats', function(e) {
e.preventDefault();
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'security': '<?php echo wp_create_nonce("load_strats_posts"); ?>',
'max_page': '<?php global $wp_query; echo $wp_query->max_num_pages;?>'
};
$.post(ajaxurl, data, function(response) {
$('.in-here-strats').append(response);
page++;
});
});
});
</code></pre>
<p></p>
<pre><code><script>
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore.smarties', function(e) {
e.preventDefault();
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'security2': '<?php echo wp_create_nonce("load_smartmaps_posts"); ?>',
'max_page': '<?php global $wp_query; echo $wp_query->max_num_pages;?>'
};
$.post(ajaxurl, data, function(response) {
$('.in-here-smartmaps').append(response);
page++;
});
});
});
</script>
</code></pre>
<p>And the AJAX functions in my function.php:</p>
<pre><code>//Load More Smart Maps
add_action('wp_ajax_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
function load_smart_maps_by_ajax_callback() {
check_ajax_referer('load_smartmaps_posts', 'security2');
$paged = $_POST['page'];
$args = array(
'post_type' => 'smart_maps',
'post_status' => 'publish',
'posts_per_page' => '10',
'paged' => $paged,
);
$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) :
?>
<?php
$total_posts = wp_count_posts('smart_maps');
$total_posts = $total_posts->publish;
$number_shown = $paged * 10 - 10;?>
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?>
<a href="<?php echo get_permalink(get_the_ID());?>">
<div class="single-smartmap col xs-col-16 md-col-8">
<div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center">
<div class="image-element">
<img src="<?php the_field('thumbnail_image');?>" class="circle">
<div class="image-overlay circle"></div>
</div>
</div>
<div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1">
<h5 class="smart-map-title"><?php the_title();?></h5>
<?php if(get_field('icons')) :?>
<div class="block-icons">
<?php if(in_array('Heart', get_field('icons'))) :?>
<span class="icon-heart"></span>
<?php endif;?>
<?php if(in_array('Plant', get_field('icons'))) :?>
<span class="icon-plant"></span>
<?php endif; ?>
<?php if(in_array('Cup', get_field('icons'))) :?>
<span class="icon-cup"></span>
<?php endif;?>
<?php if(in_array('Book', get_field('icons'))) :?>
<span class="icon-book"></span>
<?php endif;?>
</div>
<?php endif;?>
</div>
</div>
</a>
<?php $number_shown++;
if ( $number_shown == $total_posts ) {
echo '<style>.loadmore.smarties {display:none;}</style>';
}
endwhile ?>
<?php endif;
wp_die();
}
//Load More Strategic Events
add_action('wp_ajax_load_posts_by_ajax', 'load_strats_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_strats_by_ajax_callback');
function load_strats_by_ajax_callback() {
check_ajax_referer('load_strats_posts', 'security');
$paged = $_POST['page'];
$args = array(
'post_type' => 'strategic_events',
'post_status' => 'publish',
'posts_per_page' => '10',
'paged' => $paged,
);
$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) :
?>
<?php
$total_posts = wp_count_posts('strategic_events');
$total_posts = $total_posts->publish;
$number_shown = $paged * 10 - 10;?>
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?>
<a href="<?php echo get_permalink(get_the_ID());?>">
<div class="single-strategicevent col xs-col-16 md-col-8">
<div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center">
<div class="image-element">
<img src="<?php the_field('strategic_event_image');?>" class="circle">
<div class="image-overlay circle"></div>
</div>
</div>
<div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1">
<h5 class="strategic-event-title"><?php the_title();?></h5>
<?php if(get_field('subtitle')) :?>
<p><?php the_field('subtitle');?></p>
<small><?php the_field('location_text');?></small>
<?php endif;?>
</div>
</div>
</a>
<?php $number_shown++;
if ( $number_shown == $total_posts ) {
echo '<style>.loadmore.strats {display:none;}</style>';
}
endwhile ?>
<?php endif;
wp_die();
}
</code></pre>
<p>I'm all up for simplifying this into a single function if possible, or if not, at least getting it to work independently. I'm guessing that it's only viewing 1 wp_nonce's and checking it against both AJAX calls, so the first one it reads is fine, the second is coming up with a 403?</p>
| [
{
"answer_id": 321883,
"author": "Elkrat",
"author_id": 122051,
"author_profile": "https://wordpress.stackexchange.com/users/122051",
"pm_score": 2,
"selected": false,
"text": "<p>WP ajax is a bit strange. You enqueue the script to get it to show up on the page. You also LOCALIZE your script in order to stick variables into the page the script will need, variables such as nonces, ajax addresses, or even other weird things you may find useful.</p>\n\n<p>Register and localize the script like this:</p>\n\n<pre><code> wp_enqueue_script( 'name_of_function', get_stylesheet_directory_uri() . '/js/my_special_script.js', array( 'jquery' ), '1.0', true );\n wp_localize_script( 'name_of_function',\n 'name_the_script_will_see',\n array(\n 'ajax_url' => admin_url('admin-ajax.php'),\n 'ajax_nonce' => wp_create_nonce('your_nonce'),\n ));\n</code></pre>\n\n<p>And then you have to add the ajax action TWICE, once for public and again for admin pages.</p>\n\n<pre><code>add_action('wp_ajax_this_is_the_ajax_name', 'function_name_in_php' );\nadd_action('wp_ajax_nopriv_this_is_the_ajax_name', 'function_name_in_php' );\n</code></pre>\n\n<p>Then in your script you pick up the values something like this:</p>\n\n<pre><code>var data = {\n 'action': 'this_is_the_ajax_name',\n 'post_nonce': name_the_script_will_see.ajax_nonce,\n 'other_value_needed': value_generated_by_script,\n };\n$.post( name_the_script_will_see.ajax_url, data, function( response_data ) { \n\n if ( response_data.success ) {\n alert (\"Success\");\n } else {\n alert (\"Error\");\n }\n</code></pre>\n\n<p>Your php script will get the data as post data:</p>\n\n<pre><code>function function_name_in_php(){\n $nonce = $_POST['post_nonce'];\n $other_data = $_POST['other_value_needed'];\n if ( ! wp_verify_nonce( $nonce, 'your_nonce' ) ) {\n wp_send_json_error(array(\n 'message'=>'Security Token Failure',\n )); // sends json_encoded success=false\n}\n</code></pre>\n\n<p>I will use one nonce in many different scripts. All I'm really doing is making sure my requester is actually coming from my site. There's no point in generating 17 different nonces for that. Often I stick the nonce into a submission button as a data-attribute, then pull the nonce from that rather than from the wordpress localization scheme. It's more convenient when there are many scripts on a single page and they are accessing some of the same back end functions.</p>\n\n<pre><code>var postData = {};\n var nonce = $('#register_button').attr('data-nonce');\n postData.nonce = nonce;\n postData.action = 'this_is_the_ajax_name';\n$.post( name_the_script_will_see.ajax_url, postData, function( response_data ) { \n\n if ( response_data.success ) {\n alert (\"success\");\n } else {\n alert (\"Error\");\n }\n</code></pre>\n\n<p>Hope this helps! </p>\n"
},
{
"answer_id": 321916,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>The problem I'm finding is that I can only get one to work at a time.\n Whichever function is added first in the functions.php, that one works\n - the other one gets a 403 error for admin-ajax.php.</p>\n</blockquote>\n\n<p>Yes, because both your PHP functions (or AJAX callbacks) there are hooked to the <em>same</em> AJAX action, which is <code>load_posts_by_ajax</code>:</p>\n\n<pre><code>// #1 AJAX action = load_posts_by_ajax\nadd_action('wp_ajax_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\n\n// #2 AJAX action = load_posts_by_ajax\nadd_action('wp_ajax_load_posts_by_ajax', 'load_strats_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_strats_by_ajax_callback');\n</code></pre>\n\n<p>And <code>check_ajax_referer()</code> by default exits the page with a <code>403</code> (\"forbidden\") status, when for example the nonce is not specified or has already expired:</p>\n\n<pre><code>// #1 $_REQUEST['security2'] will be checked for the load_smartmaps_posts nonce action.\ncheck_ajax_referer('load_smartmaps_posts', 'security2');\n\n// #2 $_REQUEST['security'] will be checked for the load_strats_posts nonce action.\ncheck_ajax_referer('load_strats_posts', 'security');\n</code></pre>\n\n<p>You can send both nonces (although nobody would do that), or you can use the same nonce and same <code>$_REQUEST</code> key (e.g. <code>security</code>), but you'd still get an unexpected results/response.</p>\n\n<p>So if you want a \"single function\", you can use a <em>secondary \"action\"</em>:</p>\n\n<ol>\n<li><p>PHP part in <code>functions.php</code>:</p>\n\n<pre><code>// #1 Load More Smart Maps\n// No add_action( 'wp_ajax_...' ) calls here.\nfunction load_smart_maps_by_ajax_callback() {\n // No need to call check_ajax_referer()\n ...your code here...\n}\n\n\n// #2 Load More Strategic Events\n// No add_action( 'wp_ajax_...' ) calls here.\nfunction load_strats_by_ajax_callback() {\n // No need to call check_ajax_referer()\n ...your code here...\n}\n\nadd_action( 'wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax' );\nadd_action( 'wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax' );\nfunction load_posts_by_ajax() {\n check_ajax_referer( 'load_posts_by_ajax', 'security' );\n\n switch ( filter_input( INPUT_POST, 'action2' ) ) {\n case 'load_smartmaps_posts':\n load_smart_maps_by_ajax_callback();\n break;\n\n case 'load_strats_posts':\n load_strats_by_ajax_callback();\n break;\n }\n\n wp_die();\n}\n</code></pre></li>\n<li><p>JS part — the <code>data</code> object:</p>\n\n<pre><code>// #1 On click of `.loadmore.smarties`\nvar data = {\n 'action': 'load_posts_by_ajax',\n 'action2': 'load_smartmaps_posts',\n 'security': '<?php echo wp_create_nonce( \"load_posts_by_ajax\" ); ?>', // same nonce\n ...other properties...\n};\n\n// #2 On click of `.loadmore.strats`\nvar data = {\n 'action': 'load_posts_by_ajax',\n 'action2': 'load_strats_posts',\n 'security': '<?php echo wp_create_nonce( \"load_posts_by_ajax\" ); ?>', // same nonce\n ...other properties...\n};\n</code></pre></li>\n</ol>\n\n<p>But why not hook the callbacks to their own specific AJAX action:</p>\n\n<pre><code>// #1 AJAX action = load_smart_maps_posts_by_ajax\nadd_action('wp_ajax_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\n\n// #2 AJAX action = load_strats_posts_by_ajax\nadd_action('wp_ajax_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');\n</code></pre>\n"
}
]
| 2018/12/13 | [
"https://wordpress.stackexchange.com/questions/321868",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111198/"
]
| I have multiple wp\_query's on the same page. Each one of those queries has an AJAX "read more" button at the bottom. The problem I'm finding is that I can only get one to work at a time. Whichever function is added first in the functions.php, that one works - the other one gets a 403 error for admin-ajax.php.
I'm pretty new to AJAX, so I've probably made a total hash of it, and I'm sure there's a way to combine this into a single function (preferred!) but if I can even just find a way for them all to work independently, that work be fine.
Here's my code:
The 2 WP\_Queries in a custom page-work.php template:
First one:
```
<?php
//Find out how many posts
$total_posts = wp_count_posts('smart_maps');
$total_posts = $total_posts->publish;
$number_shown = 0;
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<div id="smartmaps" class="smartmaps col xs-col-14 xs-offset-1 md-col-12 md-offset-2" style="display:none;">
<div class="in-here-smartmaps">
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<a href="<?php echo get_permalink(get_the_ID());?>">
<div class="single-smartmap col xs-col-16 md-col-8">
<div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center">
<div class="image-element">
<img src="<?php the_field('thumbnail_image');?>" class="circle">
<div class="image-overlay circle"></div>
</div>
</div>
<div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1">
<h5 class="smart-map-title"><?php the_title();?></h5>
<?php if(get_field('icons')) :?>
<div class="block-icons">
<?php if(in_array('Heart', get_field('icons'))) :?>
<span class="icon-heart"></span>
<?php endif;?>
<?php if(in_array('Plant', get_field('icons'))) :?>
<span class="icon-plant"></span>
<?php endif; ?>
<?php if(in_array('Cup', get_field('icons'))) :?>
<span class="icon-cup"></span>
<?php endif;?>
<?php if(in_array('Book', get_field('icons'))) :?>
<span class="icon-book"></span>
<?php endif;?>
</div>
<?php endif;?>
</div>
</div>
</a>
<?php $number_shown++;
endwhile; ?>
<?php endif;?>
</div>
<?php if($number_shown != $total_posts) :?>
<div class="loadmore smarties col xs-col-14 xs-offset-1 md-col-8 md-offset-4 center">
<h3><a href="#">LOAD MORE</a></h3>
</div>
<?php endif;?>
</div>
<div clas="clearfix"></div>
```
The second 1:
```
<div id="strategic-events" class="strategicevents col xs-col-14 xs-offset-1 md-col-12 md-offset-2" style="display:none;">
<div class="in-here-strats">
<?php
//Find out how many posts
$total_posts = wp_count_posts('strategic_events');
$total_posts = $total_posts->publish;
$number_shown = 0;
$args = array( 'post_type' => 'strategic_events', 'posts_per_page' => 10, 'offset' => $the_offset );
$the_query2 = new WP_Query( $args ); ?>
<?php if ( $the_query2->have_posts() ) :
while ( $the_query2->have_posts() ) : $the_query2->the_post(); ?>
<a href="<?php echo get_permalink(get_the_ID());?>">
<div class="single-strategicevent col xs-col-16 md-col-8">
<div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center">
<div class="image-element">
<img src="<?php the_field('strategic_event_image');?>" class="circle">
<div class="image-overlay circle"></div>
</div>
</div>
<div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1">
<h5 class="strategic-event-title"><?php the_title();?></h5>
<?php if(get_field('subtitle')) :?>
<p><?php the_field('subtitle');?></p>
<small><?php the_field('location_text');?></small>
<?php endif;?>
</div>
</div>
</a>
<?php $number_shown++;
endwhile;
endif; ?>
</div>
<?php if($number_shown != $total_posts) :?>
<div class="loadmore strats col xs-col-14 xs-offset-1 md-col-8 md-offset-4 center">
<h3><a href="#">LOAD MORE</a></h3>
</div>
<?php endif;?>
</div>
<div class="clearfix"></div>
```
My JS code (both also in the page-work.php for now)...
```
<script>
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore.strats', function(e) {
e.preventDefault();
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'security': '<?php echo wp_create_nonce("load_strats_posts"); ?>',
'max_page': '<?php global $wp_query; echo $wp_query->max_num_pages;?>'
};
$.post(ajaxurl, data, function(response) {
$('.in-here-strats').append(response);
page++;
});
});
});
```
```
<script>
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore.smarties', function(e) {
e.preventDefault();
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'security2': '<?php echo wp_create_nonce("load_smartmaps_posts"); ?>',
'max_page': '<?php global $wp_query; echo $wp_query->max_num_pages;?>'
};
$.post(ajaxurl, data, function(response) {
$('.in-here-smartmaps').append(response);
page++;
});
});
});
</script>
```
And the AJAX functions in my function.php:
```
//Load More Smart Maps
add_action('wp_ajax_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
function load_smart_maps_by_ajax_callback() {
check_ajax_referer('load_smartmaps_posts', 'security2');
$paged = $_POST['page'];
$args = array(
'post_type' => 'smart_maps',
'post_status' => 'publish',
'posts_per_page' => '10',
'paged' => $paged,
);
$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) :
?>
<?php
$total_posts = wp_count_posts('smart_maps');
$total_posts = $total_posts->publish;
$number_shown = $paged * 10 - 10;?>
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?>
<a href="<?php echo get_permalink(get_the_ID());?>">
<div class="single-smartmap col xs-col-16 md-col-8">
<div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center">
<div class="image-element">
<img src="<?php the_field('thumbnail_image');?>" class="circle">
<div class="image-overlay circle"></div>
</div>
</div>
<div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1">
<h5 class="smart-map-title"><?php the_title();?></h5>
<?php if(get_field('icons')) :?>
<div class="block-icons">
<?php if(in_array('Heart', get_field('icons'))) :?>
<span class="icon-heart"></span>
<?php endif;?>
<?php if(in_array('Plant', get_field('icons'))) :?>
<span class="icon-plant"></span>
<?php endif; ?>
<?php if(in_array('Cup', get_field('icons'))) :?>
<span class="icon-cup"></span>
<?php endif;?>
<?php if(in_array('Book', get_field('icons'))) :?>
<span class="icon-book"></span>
<?php endif;?>
</div>
<?php endif;?>
</div>
</div>
</a>
<?php $number_shown++;
if ( $number_shown == $total_posts ) {
echo '<style>.loadmore.smarties {display:none;}</style>';
}
endwhile ?>
<?php endif;
wp_die();
}
//Load More Strategic Events
add_action('wp_ajax_load_posts_by_ajax', 'load_strats_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_strats_by_ajax_callback');
function load_strats_by_ajax_callback() {
check_ajax_referer('load_strats_posts', 'security');
$paged = $_POST['page'];
$args = array(
'post_type' => 'strategic_events',
'post_status' => 'publish',
'posts_per_page' => '10',
'paged' => $paged,
);
$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) :
?>
<?php
$total_posts = wp_count_posts('strategic_events');
$total_posts = $total_posts->publish;
$number_shown = $paged * 10 - 10;?>
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?>
<a href="<?php echo get_permalink(get_the_ID());?>">
<div class="single-strategicevent col xs-col-16 md-col-8">
<div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center">
<div class="image-element">
<img src="<?php the_field('strategic_event_image');?>" class="circle">
<div class="image-overlay circle"></div>
</div>
</div>
<div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1">
<h5 class="strategic-event-title"><?php the_title();?></h5>
<?php if(get_field('subtitle')) :?>
<p><?php the_field('subtitle');?></p>
<small><?php the_field('location_text');?></small>
<?php endif;?>
</div>
</div>
</a>
<?php $number_shown++;
if ( $number_shown == $total_posts ) {
echo '<style>.loadmore.strats {display:none;}</style>';
}
endwhile ?>
<?php endif;
wp_die();
}
```
I'm all up for simplifying this into a single function if possible, or if not, at least getting it to work independently. I'm guessing that it's only viewing 1 wp\_nonce's and checking it against both AJAX calls, so the first one it reads is fine, the second is coming up with a 403? | >
> The problem I'm finding is that I can only get one to work at a time.
> Whichever function is added first in the functions.php, that one works
> - the other one gets a 403 error for admin-ajax.php.
>
>
>
Yes, because both your PHP functions (or AJAX callbacks) there are hooked to the *same* AJAX action, which is `load_posts_by_ajax`:
```
// #1 AJAX action = load_posts_by_ajax
add_action('wp_ajax_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
// #2 AJAX action = load_posts_by_ajax
add_action('wp_ajax_load_posts_by_ajax', 'load_strats_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_strats_by_ajax_callback');
```
And `check_ajax_referer()` by default exits the page with a `403` ("forbidden") status, when for example the nonce is not specified or has already expired:
```
// #1 $_REQUEST['security2'] will be checked for the load_smartmaps_posts nonce action.
check_ajax_referer('load_smartmaps_posts', 'security2');
// #2 $_REQUEST['security'] will be checked for the load_strats_posts nonce action.
check_ajax_referer('load_strats_posts', 'security');
```
You can send both nonces (although nobody would do that), or you can use the same nonce and same `$_REQUEST` key (e.g. `security`), but you'd still get an unexpected results/response.
So if you want a "single function", you can use a *secondary "action"*:
1. PHP part in `functions.php`:
```
// #1 Load More Smart Maps
// No add_action( 'wp_ajax_...' ) calls here.
function load_smart_maps_by_ajax_callback() {
// No need to call check_ajax_referer()
...your code here...
}
// #2 Load More Strategic Events
// No add_action( 'wp_ajax_...' ) calls here.
function load_strats_by_ajax_callback() {
// No need to call check_ajax_referer()
...your code here...
}
add_action( 'wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax' );
add_action( 'wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax' );
function load_posts_by_ajax() {
check_ajax_referer( 'load_posts_by_ajax', 'security' );
switch ( filter_input( INPUT_POST, 'action2' ) ) {
case 'load_smartmaps_posts':
load_smart_maps_by_ajax_callback();
break;
case 'load_strats_posts':
load_strats_by_ajax_callback();
break;
}
wp_die();
}
```
2. JS part — the `data` object:
```
// #1 On click of `.loadmore.smarties`
var data = {
'action': 'load_posts_by_ajax',
'action2': 'load_smartmaps_posts',
'security': '<?php echo wp_create_nonce( "load_posts_by_ajax" ); ?>', // same nonce
...other properties...
};
// #2 On click of `.loadmore.strats`
var data = {
'action': 'load_posts_by_ajax',
'action2': 'load_strats_posts',
'security': '<?php echo wp_create_nonce( "load_posts_by_ajax" ); ?>', // same nonce
...other properties...
};
```
But why not hook the callbacks to their own specific AJAX action:
```
// #1 AJAX action = load_smart_maps_posts_by_ajax
add_action('wp_ajax_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
add_action('wp_ajax_nopriv_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
// #2 AJAX action = load_strats_posts_by_ajax
add_action('wp_ajax_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');
add_action('wp_ajax_nopriv_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');
``` |
321,903 | <p>I'm new to building plugins and just for testing purposes I would like to build a simple plugin that changes the title of website. What hooks or filter would I need? </p>
| [
{
"answer_id": 321883,
"author": "Elkrat",
"author_id": 122051,
"author_profile": "https://wordpress.stackexchange.com/users/122051",
"pm_score": 2,
"selected": false,
"text": "<p>WP ajax is a bit strange. You enqueue the script to get it to show up on the page. You also LOCALIZE your script in order to stick variables into the page the script will need, variables such as nonces, ajax addresses, or even other weird things you may find useful.</p>\n\n<p>Register and localize the script like this:</p>\n\n<pre><code> wp_enqueue_script( 'name_of_function', get_stylesheet_directory_uri() . '/js/my_special_script.js', array( 'jquery' ), '1.0', true );\n wp_localize_script( 'name_of_function',\n 'name_the_script_will_see',\n array(\n 'ajax_url' => admin_url('admin-ajax.php'),\n 'ajax_nonce' => wp_create_nonce('your_nonce'),\n ));\n</code></pre>\n\n<p>And then you have to add the ajax action TWICE, once for public and again for admin pages.</p>\n\n<pre><code>add_action('wp_ajax_this_is_the_ajax_name', 'function_name_in_php' );\nadd_action('wp_ajax_nopriv_this_is_the_ajax_name', 'function_name_in_php' );\n</code></pre>\n\n<p>Then in your script you pick up the values something like this:</p>\n\n<pre><code>var data = {\n 'action': 'this_is_the_ajax_name',\n 'post_nonce': name_the_script_will_see.ajax_nonce,\n 'other_value_needed': value_generated_by_script,\n };\n$.post( name_the_script_will_see.ajax_url, data, function( response_data ) { \n\n if ( response_data.success ) {\n alert (\"Success\");\n } else {\n alert (\"Error\");\n }\n</code></pre>\n\n<p>Your php script will get the data as post data:</p>\n\n<pre><code>function function_name_in_php(){\n $nonce = $_POST['post_nonce'];\n $other_data = $_POST['other_value_needed'];\n if ( ! wp_verify_nonce( $nonce, 'your_nonce' ) ) {\n wp_send_json_error(array(\n 'message'=>'Security Token Failure',\n )); // sends json_encoded success=false\n}\n</code></pre>\n\n<p>I will use one nonce in many different scripts. All I'm really doing is making sure my requester is actually coming from my site. There's no point in generating 17 different nonces for that. Often I stick the nonce into a submission button as a data-attribute, then pull the nonce from that rather than from the wordpress localization scheme. It's more convenient when there are many scripts on a single page and they are accessing some of the same back end functions.</p>\n\n<pre><code>var postData = {};\n var nonce = $('#register_button').attr('data-nonce');\n postData.nonce = nonce;\n postData.action = 'this_is_the_ajax_name';\n$.post( name_the_script_will_see.ajax_url, postData, function( response_data ) { \n\n if ( response_data.success ) {\n alert (\"success\");\n } else {\n alert (\"Error\");\n }\n</code></pre>\n\n<p>Hope this helps! </p>\n"
},
{
"answer_id": 321916,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>The problem I'm finding is that I can only get one to work at a time.\n Whichever function is added first in the functions.php, that one works\n - the other one gets a 403 error for admin-ajax.php.</p>\n</blockquote>\n\n<p>Yes, because both your PHP functions (or AJAX callbacks) there are hooked to the <em>same</em> AJAX action, which is <code>load_posts_by_ajax</code>:</p>\n\n<pre><code>// #1 AJAX action = load_posts_by_ajax\nadd_action('wp_ajax_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\n\n// #2 AJAX action = load_posts_by_ajax\nadd_action('wp_ajax_load_posts_by_ajax', 'load_strats_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_strats_by_ajax_callback');\n</code></pre>\n\n<p>And <code>check_ajax_referer()</code> by default exits the page with a <code>403</code> (\"forbidden\") status, when for example the nonce is not specified or has already expired:</p>\n\n<pre><code>// #1 $_REQUEST['security2'] will be checked for the load_smartmaps_posts nonce action.\ncheck_ajax_referer('load_smartmaps_posts', 'security2');\n\n// #2 $_REQUEST['security'] will be checked for the load_strats_posts nonce action.\ncheck_ajax_referer('load_strats_posts', 'security');\n</code></pre>\n\n<p>You can send both nonces (although nobody would do that), or you can use the same nonce and same <code>$_REQUEST</code> key (e.g. <code>security</code>), but you'd still get an unexpected results/response.</p>\n\n<p>So if you want a \"single function\", you can use a <em>secondary \"action\"</em>:</p>\n\n<ol>\n<li><p>PHP part in <code>functions.php</code>:</p>\n\n<pre><code>// #1 Load More Smart Maps\n// No add_action( 'wp_ajax_...' ) calls here.\nfunction load_smart_maps_by_ajax_callback() {\n // No need to call check_ajax_referer()\n ...your code here...\n}\n\n\n// #2 Load More Strategic Events\n// No add_action( 'wp_ajax_...' ) calls here.\nfunction load_strats_by_ajax_callback() {\n // No need to call check_ajax_referer()\n ...your code here...\n}\n\nadd_action( 'wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax' );\nadd_action( 'wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax' );\nfunction load_posts_by_ajax() {\n check_ajax_referer( 'load_posts_by_ajax', 'security' );\n\n switch ( filter_input( INPUT_POST, 'action2' ) ) {\n case 'load_smartmaps_posts':\n load_smart_maps_by_ajax_callback();\n break;\n\n case 'load_strats_posts':\n load_strats_by_ajax_callback();\n break;\n }\n\n wp_die();\n}\n</code></pre></li>\n<li><p>JS part — the <code>data</code> object:</p>\n\n<pre><code>// #1 On click of `.loadmore.smarties`\nvar data = {\n 'action': 'load_posts_by_ajax',\n 'action2': 'load_smartmaps_posts',\n 'security': '<?php echo wp_create_nonce( \"load_posts_by_ajax\" ); ?>', // same nonce\n ...other properties...\n};\n\n// #2 On click of `.loadmore.strats`\nvar data = {\n 'action': 'load_posts_by_ajax',\n 'action2': 'load_strats_posts',\n 'security': '<?php echo wp_create_nonce( \"load_posts_by_ajax\" ); ?>', // same nonce\n ...other properties...\n};\n</code></pre></li>\n</ol>\n\n<p>But why not hook the callbacks to their own specific AJAX action:</p>\n\n<pre><code>// #1 AJAX action = load_smart_maps_posts_by_ajax\nadd_action('wp_ajax_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\n\n// #2 AJAX action = load_strats_posts_by_ajax\nadd_action('wp_ajax_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');\n</code></pre>\n"
}
]
| 2018/12/14 | [
"https://wordpress.stackexchange.com/questions/321903",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155932/"
]
| I'm new to building plugins and just for testing purposes I would like to build a simple plugin that changes the title of website. What hooks or filter would I need? | >
> The problem I'm finding is that I can only get one to work at a time.
> Whichever function is added first in the functions.php, that one works
> - the other one gets a 403 error for admin-ajax.php.
>
>
>
Yes, because both your PHP functions (or AJAX callbacks) there are hooked to the *same* AJAX action, which is `load_posts_by_ajax`:
```
// #1 AJAX action = load_posts_by_ajax
add_action('wp_ajax_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
// #2 AJAX action = load_posts_by_ajax
add_action('wp_ajax_load_posts_by_ajax', 'load_strats_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_strats_by_ajax_callback');
```
And `check_ajax_referer()` by default exits the page with a `403` ("forbidden") status, when for example the nonce is not specified or has already expired:
```
// #1 $_REQUEST['security2'] will be checked for the load_smartmaps_posts nonce action.
check_ajax_referer('load_smartmaps_posts', 'security2');
// #2 $_REQUEST['security'] will be checked for the load_strats_posts nonce action.
check_ajax_referer('load_strats_posts', 'security');
```
You can send both nonces (although nobody would do that), or you can use the same nonce and same `$_REQUEST` key (e.g. `security`), but you'd still get an unexpected results/response.
So if you want a "single function", you can use a *secondary "action"*:
1. PHP part in `functions.php`:
```
// #1 Load More Smart Maps
// No add_action( 'wp_ajax_...' ) calls here.
function load_smart_maps_by_ajax_callback() {
// No need to call check_ajax_referer()
...your code here...
}
// #2 Load More Strategic Events
// No add_action( 'wp_ajax_...' ) calls here.
function load_strats_by_ajax_callback() {
// No need to call check_ajax_referer()
...your code here...
}
add_action( 'wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax' );
add_action( 'wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax' );
function load_posts_by_ajax() {
check_ajax_referer( 'load_posts_by_ajax', 'security' );
switch ( filter_input( INPUT_POST, 'action2' ) ) {
case 'load_smartmaps_posts':
load_smart_maps_by_ajax_callback();
break;
case 'load_strats_posts':
load_strats_by_ajax_callback();
break;
}
wp_die();
}
```
2. JS part — the `data` object:
```
// #1 On click of `.loadmore.smarties`
var data = {
'action': 'load_posts_by_ajax',
'action2': 'load_smartmaps_posts',
'security': '<?php echo wp_create_nonce( "load_posts_by_ajax" ); ?>', // same nonce
...other properties...
};
// #2 On click of `.loadmore.strats`
var data = {
'action': 'load_posts_by_ajax',
'action2': 'load_strats_posts',
'security': '<?php echo wp_create_nonce( "load_posts_by_ajax" ); ?>', // same nonce
...other properties...
};
```
But why not hook the callbacks to their own specific AJAX action:
```
// #1 AJAX action = load_smart_maps_posts_by_ajax
add_action('wp_ajax_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
add_action('wp_ajax_nopriv_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
// #2 AJAX action = load_strats_posts_by_ajax
add_action('wp_ajax_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');
add_action('wp_ajax_nopriv_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');
``` |
321,951 | <p>I recently changed the permalink structure on my 2-month-old blog to a user friendly one which means a whole bunch of 404s. I wish to redirect the following:</p>
<pre><code>https://example.com/poastname.html
</code></pre>
<p>to</p>
<pre><code>https://example.com/postname/
</code></pre>
<p>Before coming here, I spent days looking for this redirect online but never found. The redirect plugins recommended don't work. I just need a <code>.htaccess</code> rule to fix this.</p>
| [
{
"answer_id": 321883,
"author": "Elkrat",
"author_id": 122051,
"author_profile": "https://wordpress.stackexchange.com/users/122051",
"pm_score": 2,
"selected": false,
"text": "<p>WP ajax is a bit strange. You enqueue the script to get it to show up on the page. You also LOCALIZE your script in order to stick variables into the page the script will need, variables such as nonces, ajax addresses, or even other weird things you may find useful.</p>\n\n<p>Register and localize the script like this:</p>\n\n<pre><code> wp_enqueue_script( 'name_of_function', get_stylesheet_directory_uri() . '/js/my_special_script.js', array( 'jquery' ), '1.0', true );\n wp_localize_script( 'name_of_function',\n 'name_the_script_will_see',\n array(\n 'ajax_url' => admin_url('admin-ajax.php'),\n 'ajax_nonce' => wp_create_nonce('your_nonce'),\n ));\n</code></pre>\n\n<p>And then you have to add the ajax action TWICE, once for public and again for admin pages.</p>\n\n<pre><code>add_action('wp_ajax_this_is_the_ajax_name', 'function_name_in_php' );\nadd_action('wp_ajax_nopriv_this_is_the_ajax_name', 'function_name_in_php' );\n</code></pre>\n\n<p>Then in your script you pick up the values something like this:</p>\n\n<pre><code>var data = {\n 'action': 'this_is_the_ajax_name',\n 'post_nonce': name_the_script_will_see.ajax_nonce,\n 'other_value_needed': value_generated_by_script,\n };\n$.post( name_the_script_will_see.ajax_url, data, function( response_data ) { \n\n if ( response_data.success ) {\n alert (\"Success\");\n } else {\n alert (\"Error\");\n }\n</code></pre>\n\n<p>Your php script will get the data as post data:</p>\n\n<pre><code>function function_name_in_php(){\n $nonce = $_POST['post_nonce'];\n $other_data = $_POST['other_value_needed'];\n if ( ! wp_verify_nonce( $nonce, 'your_nonce' ) ) {\n wp_send_json_error(array(\n 'message'=>'Security Token Failure',\n )); // sends json_encoded success=false\n}\n</code></pre>\n\n<p>I will use one nonce in many different scripts. All I'm really doing is making sure my requester is actually coming from my site. There's no point in generating 17 different nonces for that. Often I stick the nonce into a submission button as a data-attribute, then pull the nonce from that rather than from the wordpress localization scheme. It's more convenient when there are many scripts on a single page and they are accessing some of the same back end functions.</p>\n\n<pre><code>var postData = {};\n var nonce = $('#register_button').attr('data-nonce');\n postData.nonce = nonce;\n postData.action = 'this_is_the_ajax_name';\n$.post( name_the_script_will_see.ajax_url, postData, function( response_data ) { \n\n if ( response_data.success ) {\n alert (\"success\");\n } else {\n alert (\"Error\");\n }\n</code></pre>\n\n<p>Hope this helps! </p>\n"
},
{
"answer_id": 321916,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>The problem I'm finding is that I can only get one to work at a time.\n Whichever function is added first in the functions.php, that one works\n - the other one gets a 403 error for admin-ajax.php.</p>\n</blockquote>\n\n<p>Yes, because both your PHP functions (or AJAX callbacks) there are hooked to the <em>same</em> AJAX action, which is <code>load_posts_by_ajax</code>:</p>\n\n<pre><code>// #1 AJAX action = load_posts_by_ajax\nadd_action('wp_ajax_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\n\n// #2 AJAX action = load_posts_by_ajax\nadd_action('wp_ajax_load_posts_by_ajax', 'load_strats_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_strats_by_ajax_callback');\n</code></pre>\n\n<p>And <code>check_ajax_referer()</code> by default exits the page with a <code>403</code> (\"forbidden\") status, when for example the nonce is not specified or has already expired:</p>\n\n<pre><code>// #1 $_REQUEST['security2'] will be checked for the load_smartmaps_posts nonce action.\ncheck_ajax_referer('load_smartmaps_posts', 'security2');\n\n// #2 $_REQUEST['security'] will be checked for the load_strats_posts nonce action.\ncheck_ajax_referer('load_strats_posts', 'security');\n</code></pre>\n\n<p>You can send both nonces (although nobody would do that), or you can use the same nonce and same <code>$_REQUEST</code> key (e.g. <code>security</code>), but you'd still get an unexpected results/response.</p>\n\n<p>So if you want a \"single function\", you can use a <em>secondary \"action\"</em>:</p>\n\n<ol>\n<li><p>PHP part in <code>functions.php</code>:</p>\n\n<pre><code>// #1 Load More Smart Maps\n// No add_action( 'wp_ajax_...' ) calls here.\nfunction load_smart_maps_by_ajax_callback() {\n // No need to call check_ajax_referer()\n ...your code here...\n}\n\n\n// #2 Load More Strategic Events\n// No add_action( 'wp_ajax_...' ) calls here.\nfunction load_strats_by_ajax_callback() {\n // No need to call check_ajax_referer()\n ...your code here...\n}\n\nadd_action( 'wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax' );\nadd_action( 'wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax' );\nfunction load_posts_by_ajax() {\n check_ajax_referer( 'load_posts_by_ajax', 'security' );\n\n switch ( filter_input( INPUT_POST, 'action2' ) ) {\n case 'load_smartmaps_posts':\n load_smart_maps_by_ajax_callback();\n break;\n\n case 'load_strats_posts':\n load_strats_by_ajax_callback();\n break;\n }\n\n wp_die();\n}\n</code></pre></li>\n<li><p>JS part — the <code>data</code> object:</p>\n\n<pre><code>// #1 On click of `.loadmore.smarties`\nvar data = {\n 'action': 'load_posts_by_ajax',\n 'action2': 'load_smartmaps_posts',\n 'security': '<?php echo wp_create_nonce( \"load_posts_by_ajax\" ); ?>', // same nonce\n ...other properties...\n};\n\n// #2 On click of `.loadmore.strats`\nvar data = {\n 'action': 'load_posts_by_ajax',\n 'action2': 'load_strats_posts',\n 'security': '<?php echo wp_create_nonce( \"load_posts_by_ajax\" ); ?>', // same nonce\n ...other properties...\n};\n</code></pre></li>\n</ol>\n\n<p>But why not hook the callbacks to their own specific AJAX action:</p>\n\n<pre><code>// #1 AJAX action = load_smart_maps_posts_by_ajax\nadd_action('wp_ajax_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\n\n// #2 AJAX action = load_strats_posts_by_ajax\nadd_action('wp_ajax_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');\n</code></pre>\n"
}
]
| 2018/12/14 | [
"https://wordpress.stackexchange.com/questions/321951",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155978/"
]
| I recently changed the permalink structure on my 2-month-old blog to a user friendly one which means a whole bunch of 404s. I wish to redirect the following:
```
https://example.com/poastname.html
```
to
```
https://example.com/postname/
```
Before coming here, I spent days looking for this redirect online but never found. The redirect plugins recommended don't work. I just need a `.htaccess` rule to fix this. | >
> The problem I'm finding is that I can only get one to work at a time.
> Whichever function is added first in the functions.php, that one works
> - the other one gets a 403 error for admin-ajax.php.
>
>
>
Yes, because both your PHP functions (or AJAX callbacks) there are hooked to the *same* AJAX action, which is `load_posts_by_ajax`:
```
// #1 AJAX action = load_posts_by_ajax
add_action('wp_ajax_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
// #2 AJAX action = load_posts_by_ajax
add_action('wp_ajax_load_posts_by_ajax', 'load_strats_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_strats_by_ajax_callback');
```
And `check_ajax_referer()` by default exits the page with a `403` ("forbidden") status, when for example the nonce is not specified or has already expired:
```
// #1 $_REQUEST['security2'] will be checked for the load_smartmaps_posts nonce action.
check_ajax_referer('load_smartmaps_posts', 'security2');
// #2 $_REQUEST['security'] will be checked for the load_strats_posts nonce action.
check_ajax_referer('load_strats_posts', 'security');
```
You can send both nonces (although nobody would do that), or you can use the same nonce and same `$_REQUEST` key (e.g. `security`), but you'd still get an unexpected results/response.
So if you want a "single function", you can use a *secondary "action"*:
1. PHP part in `functions.php`:
```
// #1 Load More Smart Maps
// No add_action( 'wp_ajax_...' ) calls here.
function load_smart_maps_by_ajax_callback() {
// No need to call check_ajax_referer()
...your code here...
}
// #2 Load More Strategic Events
// No add_action( 'wp_ajax_...' ) calls here.
function load_strats_by_ajax_callback() {
// No need to call check_ajax_referer()
...your code here...
}
add_action( 'wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax' );
add_action( 'wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax' );
function load_posts_by_ajax() {
check_ajax_referer( 'load_posts_by_ajax', 'security' );
switch ( filter_input( INPUT_POST, 'action2' ) ) {
case 'load_smartmaps_posts':
load_smart_maps_by_ajax_callback();
break;
case 'load_strats_posts':
load_strats_by_ajax_callback();
break;
}
wp_die();
}
```
2. JS part — the `data` object:
```
// #1 On click of `.loadmore.smarties`
var data = {
'action': 'load_posts_by_ajax',
'action2': 'load_smartmaps_posts',
'security': '<?php echo wp_create_nonce( "load_posts_by_ajax" ); ?>', // same nonce
...other properties...
};
// #2 On click of `.loadmore.strats`
var data = {
'action': 'load_posts_by_ajax',
'action2': 'load_strats_posts',
'security': '<?php echo wp_create_nonce( "load_posts_by_ajax" ); ?>', // same nonce
...other properties...
};
```
But why not hook the callbacks to their own specific AJAX action:
```
// #1 AJAX action = load_smart_maps_posts_by_ajax
add_action('wp_ajax_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
add_action('wp_ajax_nopriv_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
// #2 AJAX action = load_strats_posts_by_ajax
add_action('wp_ajax_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');
add_action('wp_ajax_nopriv_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');
``` |
321,974 | <p>I'm developing some custom blocks in the new Gutenberg editor experience, and I'm struggle to understand how to use some build-in components, mostly the Draggable components.</p>
<p>What I would like to achieve is a list of items (let's say many <code>li</code> in a <code>ul</code>) and I want them to be orderable with a drag & drop feature.</p>
<p>Here is my code:</p>
<pre><code>import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import { Draggable, Dashicon } from '@wordpress/components';
import './style.scss';
import './editor.scss';
registerBlockType( 'namespace/my-custom-block',
{
title: __( 'Custom block', 'namespace'),
description: __( 'Description of the custom block', 'namespace' ),
category: 'common',
icon: 'clipboard',
keywords: [
__( 'list', 'namespace' ),
__( 'item', 'namespace' ),
__( 'order', 'namespace' )
],
supports: {
html: false,
multiple: false,
},
attributes: {
items: {
type: 'array',
default: [ 'One' ,'Two' ,'Tree' ,'Four' ,'Five' ,'Six' ,'Seven' ,'Eight' ,'Nine' ,'Ten' ]
}
},
edit: props => {
return (
<ul>
{ props.attributes.items.map( (itemLabel, id) => (
<li id={ `li_${id}` } draggable>
<Draggable
elementId={ `li_${id}` }
transferData={ {} }>
{
({ onDraggableStart, onDraggableEnd }) => (
<Dashicon
icon="move"
onDragStart={ onDraggableStart }
onDragEnd={ onDraggableEnd }
draggable
/>
)
}
</Draggable>
{ itemLabel }
</li>
))
}
</ul>
)
},
save: () => {
// Return null to be rendered on the server
return null;
}
}
)
</code></pre>
<p>On the backend side it is correctly rendered but the items are not draggable</p>
<p><a href="https://i.stack.imgur.com/QMSVd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QMSVd.png" alt="enter image description here"></a></p>
<p>Unfortunately the gutenberg developer handbook doesn't give much info
<a href="https://wordpress.org/gutenberg/handbook/designers-developers/developers/components/draggable/" rel="nofollow noreferrer">https://wordpress.org/gutenberg/handbook/designers-developers/developers/components/draggable/</a> and I'm not seeing how should I do it.</p>
<p>Thanks and cheers</p>
| [
{
"answer_id": 321883,
"author": "Elkrat",
"author_id": 122051,
"author_profile": "https://wordpress.stackexchange.com/users/122051",
"pm_score": 2,
"selected": false,
"text": "<p>WP ajax is a bit strange. You enqueue the script to get it to show up on the page. You also LOCALIZE your script in order to stick variables into the page the script will need, variables such as nonces, ajax addresses, or even other weird things you may find useful.</p>\n\n<p>Register and localize the script like this:</p>\n\n<pre><code> wp_enqueue_script( 'name_of_function', get_stylesheet_directory_uri() . '/js/my_special_script.js', array( 'jquery' ), '1.0', true );\n wp_localize_script( 'name_of_function',\n 'name_the_script_will_see',\n array(\n 'ajax_url' => admin_url('admin-ajax.php'),\n 'ajax_nonce' => wp_create_nonce('your_nonce'),\n ));\n</code></pre>\n\n<p>And then you have to add the ajax action TWICE, once for public and again for admin pages.</p>\n\n<pre><code>add_action('wp_ajax_this_is_the_ajax_name', 'function_name_in_php' );\nadd_action('wp_ajax_nopriv_this_is_the_ajax_name', 'function_name_in_php' );\n</code></pre>\n\n<p>Then in your script you pick up the values something like this:</p>\n\n<pre><code>var data = {\n 'action': 'this_is_the_ajax_name',\n 'post_nonce': name_the_script_will_see.ajax_nonce,\n 'other_value_needed': value_generated_by_script,\n };\n$.post( name_the_script_will_see.ajax_url, data, function( response_data ) { \n\n if ( response_data.success ) {\n alert (\"Success\");\n } else {\n alert (\"Error\");\n }\n</code></pre>\n\n<p>Your php script will get the data as post data:</p>\n\n<pre><code>function function_name_in_php(){\n $nonce = $_POST['post_nonce'];\n $other_data = $_POST['other_value_needed'];\n if ( ! wp_verify_nonce( $nonce, 'your_nonce' ) ) {\n wp_send_json_error(array(\n 'message'=>'Security Token Failure',\n )); // sends json_encoded success=false\n}\n</code></pre>\n\n<p>I will use one nonce in many different scripts. All I'm really doing is making sure my requester is actually coming from my site. There's no point in generating 17 different nonces for that. Often I stick the nonce into a submission button as a data-attribute, then pull the nonce from that rather than from the wordpress localization scheme. It's more convenient when there are many scripts on a single page and they are accessing some of the same back end functions.</p>\n\n<pre><code>var postData = {};\n var nonce = $('#register_button').attr('data-nonce');\n postData.nonce = nonce;\n postData.action = 'this_is_the_ajax_name';\n$.post( name_the_script_will_see.ajax_url, postData, function( response_data ) { \n\n if ( response_data.success ) {\n alert (\"success\");\n } else {\n alert (\"Error\");\n }\n</code></pre>\n\n<p>Hope this helps! </p>\n"
},
{
"answer_id": 321916,
"author": "Sally CJ",
"author_id": 137402,
"author_profile": "https://wordpress.stackexchange.com/users/137402",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>The problem I'm finding is that I can only get one to work at a time.\n Whichever function is added first in the functions.php, that one works\n - the other one gets a 403 error for admin-ajax.php.</p>\n</blockquote>\n\n<p>Yes, because both your PHP functions (or AJAX callbacks) there are hooked to the <em>same</em> AJAX action, which is <code>load_posts_by_ajax</code>:</p>\n\n<pre><code>// #1 AJAX action = load_posts_by_ajax\nadd_action('wp_ajax_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\n\n// #2 AJAX action = load_posts_by_ajax\nadd_action('wp_ajax_load_posts_by_ajax', 'load_strats_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_strats_by_ajax_callback');\n</code></pre>\n\n<p>And <code>check_ajax_referer()</code> by default exits the page with a <code>403</code> (\"forbidden\") status, when for example the nonce is not specified or has already expired:</p>\n\n<pre><code>// #1 $_REQUEST['security2'] will be checked for the load_smartmaps_posts nonce action.\ncheck_ajax_referer('load_smartmaps_posts', 'security2');\n\n// #2 $_REQUEST['security'] will be checked for the load_strats_posts nonce action.\ncheck_ajax_referer('load_strats_posts', 'security');\n</code></pre>\n\n<p>You can send both nonces (although nobody would do that), or you can use the same nonce and same <code>$_REQUEST</code> key (e.g. <code>security</code>), but you'd still get an unexpected results/response.</p>\n\n<p>So if you want a \"single function\", you can use a <em>secondary \"action\"</em>:</p>\n\n<ol>\n<li><p>PHP part in <code>functions.php</code>:</p>\n\n<pre><code>// #1 Load More Smart Maps\n// No add_action( 'wp_ajax_...' ) calls here.\nfunction load_smart_maps_by_ajax_callback() {\n // No need to call check_ajax_referer()\n ...your code here...\n}\n\n\n// #2 Load More Strategic Events\n// No add_action( 'wp_ajax_...' ) calls here.\nfunction load_strats_by_ajax_callback() {\n // No need to call check_ajax_referer()\n ...your code here...\n}\n\nadd_action( 'wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax' );\nadd_action( 'wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax' );\nfunction load_posts_by_ajax() {\n check_ajax_referer( 'load_posts_by_ajax', 'security' );\n\n switch ( filter_input( INPUT_POST, 'action2' ) ) {\n case 'load_smartmaps_posts':\n load_smart_maps_by_ajax_callback();\n break;\n\n case 'load_strats_posts':\n load_strats_by_ajax_callback();\n break;\n }\n\n wp_die();\n}\n</code></pre></li>\n<li><p>JS part — the <code>data</code> object:</p>\n\n<pre><code>// #1 On click of `.loadmore.smarties`\nvar data = {\n 'action': 'load_posts_by_ajax',\n 'action2': 'load_smartmaps_posts',\n 'security': '<?php echo wp_create_nonce( \"load_posts_by_ajax\" ); ?>', // same nonce\n ...other properties...\n};\n\n// #2 On click of `.loadmore.strats`\nvar data = {\n 'action': 'load_posts_by_ajax',\n 'action2': 'load_strats_posts',\n 'security': '<?php echo wp_create_nonce( \"load_posts_by_ajax\" ); ?>', // same nonce\n ...other properties...\n};\n</code></pre></li>\n</ol>\n\n<p>But why not hook the callbacks to their own specific AJAX action:</p>\n\n<pre><code>// #1 AJAX action = load_smart_maps_posts_by_ajax\nadd_action('wp_ajax_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');\n\n// #2 AJAX action = load_strats_posts_by_ajax\nadd_action('wp_ajax_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');\n</code></pre>\n"
}
]
| 2018/12/14 | [
"https://wordpress.stackexchange.com/questions/321974",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86838/"
]
| I'm developing some custom blocks in the new Gutenberg editor experience, and I'm struggle to understand how to use some build-in components, mostly the Draggable components.
What I would like to achieve is a list of items (let's say many `li` in a `ul`) and I want them to be orderable with a drag & drop feature.
Here is my code:
```
import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import { Draggable, Dashicon } from '@wordpress/components';
import './style.scss';
import './editor.scss';
registerBlockType( 'namespace/my-custom-block',
{
title: __( 'Custom block', 'namespace'),
description: __( 'Description of the custom block', 'namespace' ),
category: 'common',
icon: 'clipboard',
keywords: [
__( 'list', 'namespace' ),
__( 'item', 'namespace' ),
__( 'order', 'namespace' )
],
supports: {
html: false,
multiple: false,
},
attributes: {
items: {
type: 'array',
default: [ 'One' ,'Two' ,'Tree' ,'Four' ,'Five' ,'Six' ,'Seven' ,'Eight' ,'Nine' ,'Ten' ]
}
},
edit: props => {
return (
<ul>
{ props.attributes.items.map( (itemLabel, id) => (
<li id={ `li_${id}` } draggable>
<Draggable
elementId={ `li_${id}` }
transferData={ {} }>
{
({ onDraggableStart, onDraggableEnd }) => (
<Dashicon
icon="move"
onDragStart={ onDraggableStart }
onDragEnd={ onDraggableEnd }
draggable
/>
)
}
</Draggable>
{ itemLabel }
</li>
))
}
</ul>
)
},
save: () => {
// Return null to be rendered on the server
return null;
}
}
)
```
On the backend side it is correctly rendered but the items are not draggable
[](https://i.stack.imgur.com/QMSVd.png)
Unfortunately the gutenberg developer handbook doesn't give much info
<https://wordpress.org/gutenberg/handbook/designers-developers/developers/components/draggable/> and I'm not seeing how should I do it.
Thanks and cheers | >
> The problem I'm finding is that I can only get one to work at a time.
> Whichever function is added first in the functions.php, that one works
> - the other one gets a 403 error for admin-ajax.php.
>
>
>
Yes, because both your PHP functions (or AJAX callbacks) there are hooked to the *same* AJAX action, which is `load_posts_by_ajax`:
```
// #1 AJAX action = load_posts_by_ajax
add_action('wp_ajax_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
// #2 AJAX action = load_posts_by_ajax
add_action('wp_ajax_load_posts_by_ajax', 'load_strats_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_strats_by_ajax_callback');
```
And `check_ajax_referer()` by default exits the page with a `403` ("forbidden") status, when for example the nonce is not specified or has already expired:
```
// #1 $_REQUEST['security2'] will be checked for the load_smartmaps_posts nonce action.
check_ajax_referer('load_smartmaps_posts', 'security2');
// #2 $_REQUEST['security'] will be checked for the load_strats_posts nonce action.
check_ajax_referer('load_strats_posts', 'security');
```
You can send both nonces (although nobody would do that), or you can use the same nonce and same `$_REQUEST` key (e.g. `security`), but you'd still get an unexpected results/response.
So if you want a "single function", you can use a *secondary "action"*:
1. PHP part in `functions.php`:
```
// #1 Load More Smart Maps
// No add_action( 'wp_ajax_...' ) calls here.
function load_smart_maps_by_ajax_callback() {
// No need to call check_ajax_referer()
...your code here...
}
// #2 Load More Strategic Events
// No add_action( 'wp_ajax_...' ) calls here.
function load_strats_by_ajax_callback() {
// No need to call check_ajax_referer()
...your code here...
}
add_action( 'wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax' );
add_action( 'wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax' );
function load_posts_by_ajax() {
check_ajax_referer( 'load_posts_by_ajax', 'security' );
switch ( filter_input( INPUT_POST, 'action2' ) ) {
case 'load_smartmaps_posts':
load_smart_maps_by_ajax_callback();
break;
case 'load_strats_posts':
load_strats_by_ajax_callback();
break;
}
wp_die();
}
```
2. JS part — the `data` object:
```
// #1 On click of `.loadmore.smarties`
var data = {
'action': 'load_posts_by_ajax',
'action2': 'load_smartmaps_posts',
'security': '<?php echo wp_create_nonce( "load_posts_by_ajax" ); ?>', // same nonce
...other properties...
};
// #2 On click of `.loadmore.strats`
var data = {
'action': 'load_posts_by_ajax',
'action2': 'load_strats_posts',
'security': '<?php echo wp_create_nonce( "load_posts_by_ajax" ); ?>', // same nonce
...other properties...
};
```
But why not hook the callbacks to their own specific AJAX action:
```
// #1 AJAX action = load_smart_maps_posts_by_ajax
add_action('wp_ajax_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
add_action('wp_ajax_nopriv_load_smart_maps_posts_by_ajax', 'load_smart_maps_by_ajax_callback');
// #2 AJAX action = load_strats_posts_by_ajax
add_action('wp_ajax_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');
add_action('wp_ajax_nopriv_load_strats_posts_by_ajax', 'load_strats_by_ajax_callback');
``` |
322,005 | <p>i.e. when post is registered, like this:</p>
<pre><code>$args= [
'supports' => ['thumbnail', 'title', 'post-formats' ...]
]
</code></pre>
<p>If later, I want to get all <code>supports</code> attribute for specific post type, which function should I use? i.e. something like <code>get_supports('post');</code></p>
| [
{
"answer_id": 322006,
"author": "T.Todua",
"author_id": 33667,
"author_profile": "https://wordpress.stackexchange.com/users/33667",
"pm_score": 0,
"selected": false,
"text": "<p>I've chosen to use <code>$GLOBALS['_wp_post_type_features']</code>, that returns like this:</p>\n\n<pre><code>Array\n(\n [post] => Array\n (\n [title] => 1\n [editor] => 1\n [author] => 1\n [thumbnail] => 1\n [excerpt] => 1\n [trackbacks] => 1\n [custom-fields] => 1\n [comments] => 1\n [revisions] => 1\n [post-formats] => 1 \n )\n\n [page] => Array\n (\n [title] => 1\n [editor] => 1\n [author] => 1\n [thumbnail] => 1\n [page-attributes] => 1\n [custom-fields] => 1\n [comments] => 1\n [revisions] => 1\n )\n ...\n</code></pre>\n"
},
{
"answer_id": 322008,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>There exists the <a href=\"https://developer.wordpress.org/reference/functions/get_all_post_type_supports/\" rel=\"nofollow noreferrer\"><code>get_all_post_type_supports()</code></a> to get the supported features for a given post type. It's a wrapper for the <code>_wp_post_type_features</code> global variable:</p>\n\n<pre><code>/**\n * Get all the post type features\n *\n * @since 3.4.0\n *\n * @global array $_wp_post_type_features\n *\n * @param string $post_type The post type.\n * @return array Post type supports list.\n */\nfunction get_all_post_type_supports( $post_type ) {\n global $_wp_post_type_features;\n\n if ( isset( $_wp_post_type_features[$post_type] ) )\n return $_wp_post_type_features[$post_type];\n\n return array();\n}\n</code></pre>\n\n<h2>Example:</h2>\n\n<p>Here's an usage example from the wp shell for the <code>'post'</code> post type:</p>\n\n<pre><code>wp> print_r( get_all_post_type_supports( 'post' ) );\nArray\n(\n [title] => 1\n [editor] => 1\n [author] => 1\n [thumbnail] => 1\n [excerpt] => 1\n [trackbacks] => 1\n [custom-fields] => 1\n [comments] => 1\n [revisions] => 1\n [post-formats] => 1\n)\n</code></pre>\n\n<p>Another useful wrapper is <a href=\"https://developer.wordpress.org/reference/functions/get_all_post_type_supports/\" rel=\"nofollow noreferrer\"><code>get_post_types_by_support()</code></a>.</p>\n"
}
]
| 2018/12/15 | [
"https://wordpress.stackexchange.com/questions/322005",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33667/"
]
| i.e. when post is registered, like this:
```
$args= [
'supports' => ['thumbnail', 'title', 'post-formats' ...]
]
```
If later, I want to get all `supports` attribute for specific post type, which function should I use? i.e. something like `get_supports('post');` | There exists the [`get_all_post_type_supports()`](https://developer.wordpress.org/reference/functions/get_all_post_type_supports/) to get the supported features for a given post type. It's a wrapper for the `_wp_post_type_features` global variable:
```
/**
* Get all the post type features
*
* @since 3.4.0
*
* @global array $_wp_post_type_features
*
* @param string $post_type The post type.
* @return array Post type supports list.
*/
function get_all_post_type_supports( $post_type ) {
global $_wp_post_type_features;
if ( isset( $_wp_post_type_features[$post_type] ) )
return $_wp_post_type_features[$post_type];
return array();
}
```
Example:
--------
Here's an usage example from the wp shell for the `'post'` post type:
```
wp> print_r( get_all_post_type_supports( 'post' ) );
Array
(
[title] => 1
[editor] => 1
[author] => 1
[thumbnail] => 1
[excerpt] => 1
[trackbacks] => 1
[custom-fields] => 1
[comments] => 1
[revisions] => 1
[post-formats] => 1
)
```
Another useful wrapper is [`get_post_types_by_support()`](https://developer.wordpress.org/reference/functions/get_all_post_type_supports/). |
323,051 | <p>Hello i wonder if you can help me. How do you make to post titles capitalize the first letter of every word?</p>
<p>Is there a way to do it in wordpress?</p>
| [
{
"answer_id": 323052,
"author": "WPZA",
"author_id": 146181,
"author_profile": "https://wordpress.stackexchange.com/users/146181",
"pm_score": 0,
"selected": false,
"text": "<p>Is this for <code><title></title></code> or output title?</p>\n\n<p>If <strong>output title</strong>, call your title as <code>echo ucwords( get_the_title() );</code> on your page.</p>\n\n<p>If <strong><code><title></title></code></strong>, you can do the same as above by applying a filter to <code>wpseo_title</code> in your functions file.</p>\n"
},
{
"answer_id": 323054,
"author": "cbos",
"author_id": 83730,
"author_profile": "https://wordpress.stackexchange.com/users/83730",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress is based on PHP. So, a better question might be, \"Is there a PHP function that will do this?\" The answer given above <a href=\"https://php.net/manual/en/function.ucwords.php\" rel=\"nofollow noreferrer\">ucwords</a>; is correct. However, there may be words you don't want capitalized, such as \"a\", \"an\" or \"the\". If that is the case, there needs to be a filter that prevents these words from being capitalized. However, that is beyond the scope of this question.</p>\n"
},
{
"answer_id": 323068,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>The code below was assembled of different pieces I've found around and it was not tested. Consider it as an idea only.</p>\n\n<pre><code><?php\nadd_filter( 'the_title', 'my_capitalize_title', 10, 2 );\n\nfunction my_capitalize_title( $title, $id ) {\n\n // get separate words\n $words = preg_split( '/[^\\w]*([\\s]+[^\\w]*|$)/', $title, NULL, PREG_SPLIT_NO_EMPTY );\n\n $stop_words = array(\n 'the', //\n 'a',\n 'and',\n 'of',\n );\n\n $title_case = '';\n\n foreach( $words as $word ) {\n // concatenate stop word intact\n if ( in_array( $word, $stop_words ) ) {\n $title_case .= $word;\n }\n // or concatenate capitalized word\n $title_case .= ucfirst( $word );\n }\n\n return $title_case;\n}\n</code></pre>\n\n<p>You have to polish the idea: you don't want \"<strong>The</strong> Simpsons\" to become \"<strong>the</strong> Simpsons\".</p>\n"
}
]
| 2018/12/16 | [
"https://wordpress.stackexchange.com/questions/323051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157056/"
]
| Hello i wonder if you can help me. How do you make to post titles capitalize the first letter of every word?
Is there a way to do it in wordpress? | The code below was assembled of different pieces I've found around and it was not tested. Consider it as an idea only.
```
<?php
add_filter( 'the_title', 'my_capitalize_title', 10, 2 );
function my_capitalize_title( $title, $id ) {
// get separate words
$words = preg_split( '/[^\w]*([\s]+[^\w]*|$)/', $title, NULL, PREG_SPLIT_NO_EMPTY );
$stop_words = array(
'the', //
'a',
'and',
'of',
);
$title_case = '';
foreach( $words as $word ) {
// concatenate stop word intact
if ( in_array( $word, $stop_words ) ) {
$title_case .= $word;
}
// or concatenate capitalized word
$title_case .= ucfirst( $word );
}
return $title_case;
}
```
You have to polish the idea: you don't want "**The** Simpsons" to become "**the** Simpsons". |
323,080 | <p>I'm trying to create a new development workflow and for that I need to enqueue some scripts to be available only when I'm developing. What is the correct way to do this? Should I use <code>WP_DEBUG</code> as a condition or is there a better way? </p>
<pre><code>if (WP_DEBUG === true) {
wp_enqueue_script('script_for_development', 'script.js'...);
}
</code></pre>
| [
{
"answer_id": 323052,
"author": "WPZA",
"author_id": 146181,
"author_profile": "https://wordpress.stackexchange.com/users/146181",
"pm_score": 0,
"selected": false,
"text": "<p>Is this for <code><title></title></code> or output title?</p>\n\n<p>If <strong>output title</strong>, call your title as <code>echo ucwords( get_the_title() );</code> on your page.</p>\n\n<p>If <strong><code><title></title></code></strong>, you can do the same as above by applying a filter to <code>wpseo_title</code> in your functions file.</p>\n"
},
{
"answer_id": 323054,
"author": "cbos",
"author_id": 83730,
"author_profile": "https://wordpress.stackexchange.com/users/83730",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress is based on PHP. So, a better question might be, \"Is there a PHP function that will do this?\" The answer given above <a href=\"https://php.net/manual/en/function.ucwords.php\" rel=\"nofollow noreferrer\">ucwords</a>; is correct. However, there may be words you don't want capitalized, such as \"a\", \"an\" or \"the\". If that is the case, there needs to be a filter that prevents these words from being capitalized. However, that is beyond the scope of this question.</p>\n"
},
{
"answer_id": 323068,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>The code below was assembled of different pieces I've found around and it was not tested. Consider it as an idea only.</p>\n\n<pre><code><?php\nadd_filter( 'the_title', 'my_capitalize_title', 10, 2 );\n\nfunction my_capitalize_title( $title, $id ) {\n\n // get separate words\n $words = preg_split( '/[^\\w]*([\\s]+[^\\w]*|$)/', $title, NULL, PREG_SPLIT_NO_EMPTY );\n\n $stop_words = array(\n 'the', //\n 'a',\n 'and',\n 'of',\n );\n\n $title_case = '';\n\n foreach( $words as $word ) {\n // concatenate stop word intact\n if ( in_array( $word, $stop_words ) ) {\n $title_case .= $word;\n }\n // or concatenate capitalized word\n $title_case .= ucfirst( $word );\n }\n\n return $title_case;\n}\n</code></pre>\n\n<p>You have to polish the idea: you don't want \"<strong>The</strong> Simpsons\" to become \"<strong>the</strong> Simpsons\".</p>\n"
}
]
| 2018/12/16 | [
"https://wordpress.stackexchange.com/questions/323080",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121208/"
]
| I'm trying to create a new development workflow and for that I need to enqueue some scripts to be available only when I'm developing. What is the correct way to do this? Should I use `WP_DEBUG` as a condition or is there a better way?
```
if (WP_DEBUG === true) {
wp_enqueue_script('script_for_development', 'script.js'...);
}
``` | The code below was assembled of different pieces I've found around and it was not tested. Consider it as an idea only.
```
<?php
add_filter( 'the_title', 'my_capitalize_title', 10, 2 );
function my_capitalize_title( $title, $id ) {
// get separate words
$words = preg_split( '/[^\w]*([\s]+[^\w]*|$)/', $title, NULL, PREG_SPLIT_NO_EMPTY );
$stop_words = array(
'the', //
'a',
'and',
'of',
);
$title_case = '';
foreach( $words as $word ) {
// concatenate stop word intact
if ( in_array( $word, $stop_words ) ) {
$title_case .= $word;
}
// or concatenate capitalized word
$title_case .= ucfirst( $word );
}
return $title_case;
}
```
You have to polish the idea: you don't want "**The** Simpsons" to become "**the** Simpsons". |
323,117 | <p>I am trying to invert the order of <code><li></code> and <code><a></code> in a <code>wp_nav_menu</code>, since for a responsive mobile design I like more when the click is done in all the <code><li></code> and not only in the word / s of the link <code><a></code> because is easier for the finger.
Thank you.
PS: I must say that I am a newbie in Wordpress development.</p>
<p>This is the code I use:</p>
<pre><code><div id="header-menu-nav">
<nav>
<?php
wp_nav_menu(array(
'container'=> false,
'items_wrap' => '<ul>%3$s</ul>',
'theme_location' => 'menu'
));
?>
</nav>
</div>
</code></pre>
<p>And the answer I get is:</p>
<pre><code><div id="header-menu-mobile-nav">
<nav>
<ul id="header-menu-mobile-nav-ul">
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-181">
<a href="index.php">Home</a>
</li>
</ul>
</nav>
</div>
</code></pre>
<p>What I want is:</p>
<pre><code><div id="header-menu-mobile-nav">
<nav>
<ul id="header-menu-mobile-nav-ul">
<a href="index.php">
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-181">Home</li>
</a>
</ul>
</nav>
</div>
</code></pre>
| [
{
"answer_id": 323124,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<pre><code><ul>\n <a>\n <li></li>\n </a>\n</ul>\n</code></pre>\n\n<p>Is not valid HTML. An <code><a></code> tag cannot be a child of a <code><ul></code> tag. So what you're asking for isn't possible. It's not your actual problem either.</p>\n\n<p>Your problem is a styling problem. If you want a larger touch target on the link, you need to add padding around the <code><a></code> tag, not the <code><li></code> tag.</p>\n"
},
{
"answer_id": 323161,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Finally I have kept the correct HTML format:</p>\n\n<pre><code><ul>\n <li>\n <a></a>\n </li>\n</ul>\n</code></pre>\n\n<p>And in CSS I put the element <code><a></code> with <code>display: bock;</code> and the padding that I want, and therefore occupies 100% of the elementu <code><li></code>.\nThank you.</p>\n"
}
]
| 2018/12/16 | [
"https://wordpress.stackexchange.com/questions/323117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| I am trying to invert the order of `<li>` and `<a>` in a `wp_nav_menu`, since for a responsive mobile design I like more when the click is done in all the `<li>` and not only in the word / s of the link `<a>` because is easier for the finger.
Thank you.
PS: I must say that I am a newbie in Wordpress development.
This is the code I use:
```
<div id="header-menu-nav">
<nav>
<?php
wp_nav_menu(array(
'container'=> false,
'items_wrap' => '<ul>%3$s</ul>',
'theme_location' => 'menu'
));
?>
</nav>
</div>
```
And the answer I get is:
```
<div id="header-menu-mobile-nav">
<nav>
<ul id="header-menu-mobile-nav-ul">
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-181">
<a href="index.php">Home</a>
</li>
</ul>
</nav>
</div>
```
What I want is:
```
<div id="header-menu-mobile-nav">
<nav>
<ul id="header-menu-mobile-nav-ul">
<a href="index.php">
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-181">Home</li>
</a>
</ul>
</nav>
</div>
``` | ```
<ul>
<a>
<li></li>
</a>
</ul>
```
Is not valid HTML. An `<a>` tag cannot be a child of a `<ul>` tag. So what you're asking for isn't possible. It's not your actual problem either.
Your problem is a styling problem. If you want a larger touch target on the link, you need to add padding around the `<a>` tag, not the `<li>` tag. |
323,153 | <p>I want to hide the add new page button from users that are not administrators. I managed to hide the submenu item from the right column like this:</p>
<pre><code>$page = remove_submenu_page( 'edit.php?post_type=page', 'post-new.php?post_type=page' );
</code></pre>
<p>I tried to hide the button in the page with css proposed in this <a href="https://wordpress.stackexchange.com/questions/169170/how-can-i-remove-the-add-new-button-in-my-custom-post-type">question</a> but didn't work. How I can achieve that? Here is my -failed- attempt:</p>
<pre><code>if (isset($_GET['post_type']) && $_GET['post_type'] == 'page') {
echo '<style type="text/css">
#favorite-actions, .add-new-h2, .tablenav { display:none; }
</style>';
}
</code></pre>
| [
{
"answer_id": 323124,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<pre><code><ul>\n <a>\n <li></li>\n </a>\n</ul>\n</code></pre>\n\n<p>Is not valid HTML. An <code><a></code> tag cannot be a child of a <code><ul></code> tag. So what you're asking for isn't possible. It's not your actual problem either.</p>\n\n<p>Your problem is a styling problem. If you want a larger touch target on the link, you need to add padding around the <code><a></code> tag, not the <code><li></code> tag.</p>\n"
},
{
"answer_id": 323161,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Finally I have kept the correct HTML format:</p>\n\n<pre><code><ul>\n <li>\n <a></a>\n </li>\n</ul>\n</code></pre>\n\n<p>And in CSS I put the element <code><a></code> with <code>display: bock;</code> and the padding that I want, and therefore occupies 100% of the elementu <code><li></code>.\nThank you.</p>\n"
}
]
| 2018/12/17 | [
"https://wordpress.stackexchange.com/questions/323153",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157147/"
]
| I want to hide the add new page button from users that are not administrators. I managed to hide the submenu item from the right column like this:
```
$page = remove_submenu_page( 'edit.php?post_type=page', 'post-new.php?post_type=page' );
```
I tried to hide the button in the page with css proposed in this [question](https://wordpress.stackexchange.com/questions/169170/how-can-i-remove-the-add-new-button-in-my-custom-post-type) but didn't work. How I can achieve that? Here is my -failed- attempt:
```
if (isset($_GET['post_type']) && $_GET['post_type'] == 'page') {
echo '<style type="text/css">
#favorite-actions, .add-new-h2, .tablenav { display:none; }
</style>';
}
``` | ```
<ul>
<a>
<li></li>
</a>
</ul>
```
Is not valid HTML. An `<a>` tag cannot be a child of a `<ul>` tag. So what you're asking for isn't possible. It's not your actual problem either.
Your problem is a styling problem. If you want a larger touch target on the link, you need to add padding around the `<a>` tag, not the `<li>` tag. |
323,155 | <p>My website - <strong>www.In2BalanceKInesiology.com.au</strong> had an WordPress auto update a few days ago and I have not been able to access it since - it is a white screen of death...</p>
| [
{
"answer_id": 323124,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<pre><code><ul>\n <a>\n <li></li>\n </a>\n</ul>\n</code></pre>\n\n<p>Is not valid HTML. An <code><a></code> tag cannot be a child of a <code><ul></code> tag. So what you're asking for isn't possible. It's not your actual problem either.</p>\n\n<p>Your problem is a styling problem. If you want a larger touch target on the link, you need to add padding around the <code><a></code> tag, not the <code><li></code> tag.</p>\n"
},
{
"answer_id": 323161,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Finally I have kept the correct HTML format:</p>\n\n<pre><code><ul>\n <li>\n <a></a>\n </li>\n</ul>\n</code></pre>\n\n<p>And in CSS I put the element <code><a></code> with <code>display: bock;</code> and the padding that I want, and therefore occupies 100% of the elementu <code><li></code>.\nThank you.</p>\n"
}
]
| 2018/12/17 | [
"https://wordpress.stackexchange.com/questions/323155",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157150/"
]
| My website - **www.In2BalanceKInesiology.com.au** had an WordPress auto update a few days ago and I have not been able to access it since - it is a white screen of death... | ```
<ul>
<a>
<li></li>
</a>
</ul>
```
Is not valid HTML. An `<a>` tag cannot be a child of a `<ul>` tag. So what you're asking for isn't possible. It's not your actual problem either.
Your problem is a styling problem. If you want a larger touch target on the link, you need to add padding around the `<a>` tag, not the `<li>` tag. |
323,192 | <p>I have a shortcode that displays a block of content. Is there a way I can display different HTML depending on if the user is logged in or not? Below is what I have so far.</p>
<pre><code>function footer_shortcode(){
$siteURL = site_url();
$logoutURL = wp_logout_url(home_url());
echo '
<div class="signin_container">
<h4 class="signin_footer_head">Log In To My Account</h4>
<a href="'.$siteURL.'/login/">Log In</a>
<a href="'.$siteURL.'/register/">Sign Up</a>
</div>
';
}
add_shortcode('footerShortcode', 'footer_shortcode');
</code></pre>
| [
{
"answer_id": 323124,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<pre><code><ul>\n <a>\n <li></li>\n </a>\n</ul>\n</code></pre>\n\n<p>Is not valid HTML. An <code><a></code> tag cannot be a child of a <code><ul></code> tag. So what you're asking for isn't possible. It's not your actual problem either.</p>\n\n<p>Your problem is a styling problem. If you want a larger touch target on the link, you need to add padding around the <code><a></code> tag, not the <code><li></code> tag.</p>\n"
},
{
"answer_id": 323161,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Finally I have kept the correct HTML format:</p>\n\n<pre><code><ul>\n <li>\n <a></a>\n </li>\n</ul>\n</code></pre>\n\n<p>And in CSS I put the element <code><a></code> with <code>display: bock;</code> and the padding that I want, and therefore occupies 100% of the elementu <code><li></code>.\nThank you.</p>\n"
}
]
| 2018/12/17 | [
"https://wordpress.stackexchange.com/questions/323192",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157172/"
]
| I have a shortcode that displays a block of content. Is there a way I can display different HTML depending on if the user is logged in or not? Below is what I have so far.
```
function footer_shortcode(){
$siteURL = site_url();
$logoutURL = wp_logout_url(home_url());
echo '
<div class="signin_container">
<h4 class="signin_footer_head">Log In To My Account</h4>
<a href="'.$siteURL.'/login/">Log In</a>
<a href="'.$siteURL.'/register/">Sign Up</a>
</div>
';
}
add_shortcode('footerShortcode', 'footer_shortcode');
``` | ```
<ul>
<a>
<li></li>
</a>
</ul>
```
Is not valid HTML. An `<a>` tag cannot be a child of a `<ul>` tag. So what you're asking for isn't possible. It's not your actual problem either.
Your problem is a styling problem. If you want a larger touch target on the link, you need to add padding around the `<a>` tag, not the `<li>` tag. |
323,212 | <p>Where and how should I even begin to fix terrible design problems? I can't change the theme, I must learn how to fix it the current one, I guess via CSS? How to align all textboxes properly, how to change box (top is gray) color and button color as well? These are all in simple pages via shortcodes. Thanks.</p>
<p><a href="https://i.stack.imgur.com/WX3Zz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WX3Zz.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/Ahuf5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ahuf5.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/v5rVQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v5rVQ.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 323216,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": true,
"text": "<p>Yes, this can easily be cleaned up with a little CSS. You can start by using the browser's inspector, hit F12 to open it, and select the element you want to style. </p>\n\n<p>See if that form or something around has an ID, use that to target each element so you don't effect other pages or unwanted elements.</p>\n\n<p>Here are couple example that might help.</p>\n\n<pre><code>#myFormID label,\n#myFormID input[type=\"text\"],\n#myFormID select {\n display: block;\n}\n</code></pre>\n\n<p>That will put your labels and form elements on different lines.</p>\n\n<p>The best thing to do is just inspect the page and start playing around with the CSS.</p>\n"
},
{
"answer_id": 323220,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 1,
"selected": false,
"text": "<p>Without seeing the actual CSS that is already applied, it is difficult to say \"change this and this to fix this and that.\"</p>\n\n<p>But... to address your concern about the theme, etc. What you should be doing is <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">using a child theme</a>. That way you can customize your work. That allows you to customize in a way that still allows you to update if the theme developer publishes an update.</p>\n\n<p>Another thing to consider is that the WordPress Customizer now has the ability for applying custom CSS within the Customizer interface.</p>\n\n<p>So this may not ultimately be the answer that you need, but hopefully it has some info you can use to make the process easier.</p>\n"
}
]
| 2018/12/17 | [
"https://wordpress.stackexchange.com/questions/323212",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157188/"
]
| Where and how should I even begin to fix terrible design problems? I can't change the theme, I must learn how to fix it the current one, I guess via CSS? How to align all textboxes properly, how to change box (top is gray) color and button color as well? These are all in simple pages via shortcodes. Thanks.
[](https://i.stack.imgur.com/WX3Zz.png)
[](https://i.stack.imgur.com/Ahuf5.png)
[](https://i.stack.imgur.com/v5rVQ.png) | Yes, this can easily be cleaned up with a little CSS. You can start by using the browser's inspector, hit F12 to open it, and select the element you want to style.
See if that form or something around has an ID, use that to target each element so you don't effect other pages or unwanted elements.
Here are couple example that might help.
```
#myFormID label,
#myFormID input[type="text"],
#myFormID select {
display: block;
}
```
That will put your labels and form elements on different lines.
The best thing to do is just inspect the page and start playing around with the CSS. |
323,221 | <p>I've tried both of these, but I'm still getting the error message: "Sorry, this file type is not permitted for security reasons."</p>
<pre><code>// add support for webp mime types
function webp_upload_mimes( $existing_mimes ) {
// add webp to the list of mime types
$existing_mimes['webp'] = 'image/webp';
// return the array back to the function with our added mime type
return $existing_mimes;
}
add_filter( 'mime_types', 'webp_upload_mimes' );
function my_custom_upload_mimes($mimes = array()) {
// add webp to the list of mime types
$existing_mimes['webp'] = 'image/webp';
return $mimes;
}
add_action('upload_mimes', 'my_custom_upload_mimes');
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 323225,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>Sometimes the uploads are limited by your host. Try and define the <code>ALLOW_UNFILTERED_UPLOADS</code> constant that allows upload for every file type:</p>\n\n<pre><code>define( 'ALLOW_UNFILTERED_UPLOADS', true );\n</code></pre>\n\n<p>Use this in your <code>wp-config.php</code> file for a moment, for testing purposes. Then re-upload your file, and if it still doesn't work, it's probable that the hosting has blocked that file type from being uploaded. Make sure you remove the constant as soon as possible, when you are done trying.</p>\n\n<p>Additionally, You can use the <a href=\"https://codex.wordpress.org/Function_Reference/get_allowed_mime_types\" rel=\"nofollow noreferrer\"><code>get_allowed_mime_types()</code></a> function to check the allowed upload mimes.</p>\n"
},
{
"answer_id": 323226,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 6,
"selected": true,
"text": "<p>It's necessary to use the <code>wp_check_filetype_and_ext</code> filter to set the mime type and extension for webp files in addition to using the <code>upload_mimes</code> filter to add the mime type to the list of uploadable mimes.</p>\n\n<pre><code>/**\n * Sets the extension and mime type for .webp files.\n *\n * @param array $wp_check_filetype_and_ext File data array containing 'ext', 'type', and\n * 'proper_filename' keys.\n * @param string $file Full path to the file.\n * @param string $filename The name of the file (may differ from $file due to\n * $file being in a tmp directory).\n * @param array $mimes Key is the file extension with value as the mime type.\n */\nadd_filter( 'wp_check_filetype_and_ext', 'wpse_file_and_ext_webp', 10, 4 );\nfunction wpse_file_and_ext_webp( $types, $file, $filename, $mimes ) {\n if ( false !== strpos( $filename, '.webp' ) ) {\n $types['ext'] = 'webp';\n $types['type'] = 'image/webp';\n }\n\n return $types;\n}\n\n/**\n * Adds webp filetype to allowed mimes\n * \n * @see https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_mimes\n * \n * @param array $mimes Mime types keyed by the file extension regex corresponding to\n * those types. 'swf' and 'exe' removed from full list. 'htm|html' also\n * removed depending on '$user' capabilities.\n *\n * @return array\n */\nadd_filter( 'upload_mimes', 'wpse_mime_types_webp' );\nfunction wpse_mime_types_webp( $mimes ) {\n $mimes['webp'] = 'image/webp';\n\n return $mimes;\n}\n</code></pre>\n\n<p>I tested this on WP v5.0.1 and was able to upload webp files after adding this code.</p>\n"
},
{
"answer_id": 349982,
"author": "wp-overwatch.com",
"author_id": 73963,
"author_profile": "https://wordpress.stackexchange.com/users/73963",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to get it to work by creating the following plugin. (You just have to add this code to a new file in the <code>/wp-content/plugins/</code> directory to create the plugin. Make sure you activate the plugin after creating it.)</p>\n\n<pre><code><?php\n/**\n * Plugin Name: WPSE Allow Webp Uploads\n */\n\nfunction webp_file_and_ext( $mime, $file, $filename, $mimes ) {\n\n $wp_filetype = wp_check_filetype( $filename, $mimes );\n if ( in_array( $wp_filetype['ext'], [ 'webp' ] ) ) {\n $mime['ext'] = true;\n $mime['type'] = true;\n }\n\n return $mime;\n}\nadd_filter( 'wp_check_filetype_and_ext', 'webp_file_and_ext', 10, 4 );\n\nfunction add_webp_mime_type( $mimes ) {\n $mimes['webp'] = 'image/webp';\n return $mimes;\n}\nadd_filter( 'upload_mimes', 'add_webp_mime_type' );\n</code></pre>\n"
}
]
| 2018/12/17 | [
"https://wordpress.stackexchange.com/questions/323221",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145165/"
]
| I've tried both of these, but I'm still getting the error message: "Sorry, this file type is not permitted for security reasons."
```
// add support for webp mime types
function webp_upload_mimes( $existing_mimes ) {
// add webp to the list of mime types
$existing_mimes['webp'] = 'image/webp';
// return the array back to the function with our added mime type
return $existing_mimes;
}
add_filter( 'mime_types', 'webp_upload_mimes' );
function my_custom_upload_mimes($mimes = array()) {
// add webp to the list of mime types
$existing_mimes['webp'] = 'image/webp';
return $mimes;
}
add_action('upload_mimes', 'my_custom_upload_mimes');
```
Any ideas? | It's necessary to use the `wp_check_filetype_and_ext` filter to set the mime type and extension for webp files in addition to using the `upload_mimes` filter to add the mime type to the list of uploadable mimes.
```
/**
* Sets the extension and mime type for .webp files.
*
* @param array $wp_check_filetype_and_ext File data array containing 'ext', 'type', and
* 'proper_filename' keys.
* @param string $file Full path to the file.
* @param string $filename The name of the file (may differ from $file due to
* $file being in a tmp directory).
* @param array $mimes Key is the file extension with value as the mime type.
*/
add_filter( 'wp_check_filetype_and_ext', 'wpse_file_and_ext_webp', 10, 4 );
function wpse_file_and_ext_webp( $types, $file, $filename, $mimes ) {
if ( false !== strpos( $filename, '.webp' ) ) {
$types['ext'] = 'webp';
$types['type'] = 'image/webp';
}
return $types;
}
/**
* Adds webp filetype to allowed mimes
*
* @see https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_mimes
*
* @param array $mimes Mime types keyed by the file extension regex corresponding to
* those types. 'swf' and 'exe' removed from full list. 'htm|html' also
* removed depending on '$user' capabilities.
*
* @return array
*/
add_filter( 'upload_mimes', 'wpse_mime_types_webp' );
function wpse_mime_types_webp( $mimes ) {
$mimes['webp'] = 'image/webp';
return $mimes;
}
```
I tested this on WP v5.0.1 and was able to upload webp files after adding this code. |
323,256 | <p>I'm writing a standalone script for Wordpress so I can display things like the username on a page outside of Wordpress.</p>
<p>My method so far is to try to include or require wp-load.php in my script directory. I've tried</p>
<pre><code>chdir ( ".." );
include "wp-load.php";
</code></pre>
<p>as well as absolute paths to the web root where Wordpress is located for both the chdir and the include. I don't get any errors but wp_get_current_user() always returns empty.</p>
<p>If I move my script up a level to the same folder with Wordpress it works fine. How can I include wp-load.php and keep all of the files in my subfolder?</p>
<p>EDIT: file structure</p>
<ul>
<li>public_html (wordpress is installed here so wp-load.php is also here)
<ul>
<li>myScript (directory)
<ul>
<li>script.php</li>
<li>This is where I try to use chdir ( ".." ) or include ( "../wp-load.php" ) without success</li>
</ul></li>
</ul></li>
</ul>
| [
{
"answer_id": 323234,
"author": "Keonramses",
"author_id": 157195,
"author_profile": "https://wordpress.stackexchange.com/users/157195",
"pm_score": 2,
"selected": false,
"text": "<p>you can try doing a manual update, so as long as you didn't make any changes to the WordPress core files(if you did I suggest you take note of them and reapply after the upgrade), just head over to WordPress.org download the latest WordPress package and copy it over to your root folder on the server make sure you overwrite only the core WordPress files, leave the wp-content folder out of this, input your details to the wp-config.php file and that should probably sort this issue out for you.\nPS. remember to back up your database and original WordPress folders before continuing.</p>\n"
},
{
"answer_id": 333478,
"author": "RouteXL",
"author_id": 164454,
"author_profile": "https://wordpress.stackexchange.com/users/164454",
"pm_score": 2,
"selected": false,
"text": "<p>You'll get this error also if WP can not insert a <code>lock</code> in the <code>wp_options</code> table. It may be that the table is not configured correctly, e.g. when copied from another source. The <code>option_id</code> should be autoincrement or the update fails. Check if can insert a lock entry in the database manually:</p>\n\n<pre><code>INSERT INTO `wp_options` (`option_name`, `option_value`, `autoload`) VALUES ('core_updater.lock', '1', 'no');\n</code></pre>\n\n<p>If the <code>option_id</code> is not autoincrement and this query fails, you'll need to make the <code>option_id</code> field autoincrement. You may need to remove the index in this field before making it autoincrement.</p>\n"
},
{
"answer_id": 379172,
"author": "Ryan Wehrle",
"author_id": 198366,
"author_profile": "https://wordpress.stackexchange.com/users/198366",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if this will help expand the conversation to help figure this out but I've narrowed the error message down to being generated by line 118-122 of class-core-upgrade.php (wp-admin/includes)</p>\n<pre><code>// Lock to prevent multiple Core Updates occurring.\n$lock = WP_Upgrader::create_lock( 'core_updater', 15 * MINUTE_IN_SECONDS );\nif ( ! $lock ) {\n return new WP_Error( 'locked', $this->strings['locked'] );\n}\n</code></pre>\n<p>function create_lock is in file class-wp-upgrader.php on line 885-918</p>\n<p>putting echo codes in before the returns, I was able to narrow it down to these lines in the function (899-901)</p>\n<pre><code>// If a lock couldn't be created, and there isn't a lock, bail.\nif ( ! $lock_result ) {\n return false;\n}\n</code></pre>\n<p>For some reason, I am able to query the code above by RouteXL and a lock gets generated, but WP is failing to insert the query on line 893</p>\n<pre><code>$lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_option, time() ) );\n</code></pre>\n<p>Inserting this line right after 893</p>\n<pre><code>echo $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_option, time() );\n</code></pre>\n<p>gives me the echo code when doing an update</p>\n<pre><code>INSERT IGNORE INTO `wp_options` ( `option_name`, `option_value`, `autoload` ) VALUES ('core_updater.lock', '1606851384', 'no') /* LOCK */\n</code></pre>\n<p>I ran this query manually and it inserts the row correctly into the MySQL database using the same user/pass as my WP install.</p>\n<p>I'm not entirely sure why wordpress is failing to do this but I can do it manually using the same credentials.</p>\n"
},
{
"answer_id": 379173,
"author": "Ryan Wehrle",
"author_id": 198366,
"author_profile": "https://wordpress.stackexchange.com/users/198366",
"pm_score": 1,
"selected": false,
"text": "<p>I modified the create_lock function to produce some error codes and information. I also changed the query removing the IGNORE after INSERT and it finally gives me an error when trying to update with the MySQL:</p>\n<p><strong>update-core.php</strong> now generates:</p>\n<pre><code>Update WordPress\nQUERY[ INSERT INTO `wp_options` ( `option_name`, `option_value`, `autoload` ) VALUES ('core_updater.lock', '1606853111', 'no') /* LOCK */ ]\nQUERY ERROR[ Duplicate entry 'core_updater.lock' for key 'option_name' ]\nThere is where I'm failing\nAnother update is currently in progress.\n</code></pre>\n<p><strong>Duplicate entry 'core_updater.lock' for key 'option_name'</strong>\nThis is why it's failing!</p>\n<p>The kicker? I don't see that line or value in my wp_options table! Very very strange!\nNow I need to see why it's saying it's a duplicate, even though this option doesn't exist in my database!</p>\n<p><strong>class-wp-upgrader.php</strong> (modified to produce diag data)</p>\n<pre><code>public static function create_lock( $lock_name, $release_timeout = null ) {\n global $wpdb;\n if ( ! $release_timeout ) {\n $release_timeout = HOUR_IN_SECONDS;\n }\n $lock_option = $lock_name . '.lock';\n\n // Try to lock.\n $q = $wpdb->prepare( "INSERT INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_option, time() );\n $lock_result = $wpdb->query( $q );\n\n echo "QUERY[ $q ]<br>";\n echo "QUERY ERROR[ ".$wpdb->last_error." ]<br>";\n //$test_result = $wpdb->query( "INSERT INTO wp_options (option_name, option_value, autoload) VALUES('ZZZ', '1', 'no')");\n //if( ! $test_result ) echo "test failed";\n \n if ( ! $lock_result ) \n {\n $lock_result = get_option( $lock_option );\n\n // If a lock couldn't be created, and there isn't a lock, bail.\n if ( ! $lock_result ) {\n echo "There is where I'm failing<br>";\n return false;\n }\n\n // Check to see if the lock is still valid. If it is, bail.\n if ( $lock_result > ( time() - $release_timeout ) ) {\n return false;\n }\n\n // There must exist an expired lock, clear it and re-gain it.\n WP_Upgrader::release_lock( $lock_name );\n return WP_Upgrader::create_lock( $lock_name, $release_timeout );\n }\n\n // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.\n update_option( $lock_option, time() );\n\n return true;\n}\n</code></pre>\n"
}
]
| 2018/12/18 | [
"https://wordpress.stackexchange.com/questions/323256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157212/"
]
| I'm writing a standalone script for Wordpress so I can display things like the username on a page outside of Wordpress.
My method so far is to try to include or require wp-load.php in my script directory. I've tried
```
chdir ( ".." );
include "wp-load.php";
```
as well as absolute paths to the web root where Wordpress is located for both the chdir and the include. I don't get any errors but wp\_get\_current\_user() always returns empty.
If I move my script up a level to the same folder with Wordpress it works fine. How can I include wp-load.php and keep all of the files in my subfolder?
EDIT: file structure
* public\_html (wordpress is installed here so wp-load.php is also here)
+ myScript (directory)
- script.php
- This is where I try to use chdir ( ".." ) or include ( "../wp-load.php" ) without success | you can try doing a manual update, so as long as you didn't make any changes to the WordPress core files(if you did I suggest you take note of them and reapply after the upgrade), just head over to WordPress.org download the latest WordPress package and copy it over to your root folder on the server make sure you overwrite only the core WordPress files, leave the wp-content folder out of this, input your details to the wp-config.php file and that should probably sort this issue out for you.
PS. remember to back up your database and original WordPress folders before continuing. |
323,280 | <p>I want to get all post IDs from the current query. I know how to get all IDs of the current page using the following:</p>
<pre><code>global $wp_query;
$post_ids = wp_list_pluck( $wp_query->posts, "ID" );
</code></pre>
<p>This will give me an array of all post IDs, but limited to the current page.</p>
<p>How can I get all IDs but not limited by <code>'posts_per_page'</code>. (I don't want to modify the query by changing 'posts_per_page'.)</p>
<p>I know that there is already information available from the global <code>$wp_query</code> such as:</p>
<p>We will be displaying " <code>. $wp_query->query_vars['posts_per_page'] .</code> " posts per page if possible.</p>
<p>We need a total of " <code>. $wp_query->max_num_pages .</code> " pages to display the results.</p>
<p><em>Additional Details:</em></p>
<p>I am trying to get WooCommerce product IDs and hooking into the <code>woocommerce_archive_description</code> action to do this.</p>
| [
{
"answer_id": 352791,
"author": "Joe",
"author_id": 40614,
"author_profile": "https://wordpress.stackexchange.com/users/40614",
"pm_score": 2,
"selected": false,
"text": "<p>Slightly old post I know but I just hit this exact issue myself.</p>\n\n<p>Given a main_query find all the post IDs for it not limited by pagination. </p>\n\n<p>I have made this function to return all terms for the main wp_query.</p>\n\n<pre><code>/*\n * Get terms for a given wp_query no paging\n * */\nfunction get_terms_for_current_posts($tax='post_tag',$the_wp_query=false){\n global $wp_query;\n // Use global WP_Query but option to override\n $q = $wp_query;\n if($the_wp_query){\n $q = $the_wp_query;\n }\n\n $q->query_vars['posts_per_page'] = 200;// setting -1 does not seem to work here?\n $q->query_vars['fields'] = 'ids';// I only want the post IDs\n $the_query = new WP_Query($q->query_vars);// get the posts\n // $the_query->posts is an array of all found post IDs\n // get all terms for the given array of post IDs\n $y = wp_get_object_terms( $the_query->posts, $tax );\n return $y;// array of term objects\n}\n</code></pre>\n\n<p>Hope this helps you or someone else stumbling across this.</p>\n"
},
{
"answer_id": 400947,
"author": "amarinediary",
"author_id": 190376,
"author_profile": "https://wordpress.stackexchange.com/users/190376",
"pm_score": 0,
"selected": false,
"text": "<p>Wanted to share my two cents.</p>\n<p>Indeed, the main <code>$wp_query</code> will only return the posts correlating to the current <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters\" rel=\"nofollow noreferrer\">Pagination Parameters</a>.</p>\n<p>Like Milo pointed out in the comments you can actually create a new query with a different set of pagination parameters (eg: <code>nopaging</code>, <code>posts_per_page</code>, <code>posts_per_archive_page </code>...).</p>\n<p>We can mirror the main query parameters and merge them with our new pagination parameters. As we're only interested in the posts ids, we can use the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#return-fields-parameter\" rel=\"nofollow noreferrer\"><code>fields query parameter</code></a> to only return the posts ids.</p>\n<pre><code>/**\n * Retrieve the IDs of the items in the main WordPress query.\n * \n * Intercept the main query, retrieve the current parameters to create a new query.\n * Return the IDs of the items in the main query as an array.\n * \n * @see https://wordpress.stackexchange.com/a/400947/190376\n * \n * @return Array The IDs of the items in the WordPress Loop. False if $post is not set.\n * \n * @since 1.0.0\n */\npublic function wpso_323280() {\n\n if ( is_main_query() ) {\n\n global $wp_query;\n\n $buffer_query = $wp_query->query;\n \n $args = array(\n 'nopaging' => true,\n 'fields' => 'ids',\n );\n \n $custom_query = new WP_Query( array_merge( $buffer_query, $args ) );\n \n wp_reset_postdata();\n \n return $custom_query->posts;\n\n };\n\n}\n</code></pre>\n"
}
]
| 2018/12/18 | [
"https://wordpress.stackexchange.com/questions/323280",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81143/"
]
| I want to get all post IDs from the current query. I know how to get all IDs of the current page using the following:
```
global $wp_query;
$post_ids = wp_list_pluck( $wp_query->posts, "ID" );
```
This will give me an array of all post IDs, but limited to the current page.
How can I get all IDs but not limited by `'posts_per_page'`. (I don't want to modify the query by changing 'posts\_per\_page'.)
I know that there is already information available from the global `$wp_query` such as:
We will be displaying " `. $wp_query->query_vars['posts_per_page'] .` " posts per page if possible.
We need a total of " `. $wp_query->max_num_pages .` " pages to display the results.
*Additional Details:*
I am trying to get WooCommerce product IDs and hooking into the `woocommerce_archive_description` action to do this. | Slightly old post I know but I just hit this exact issue myself.
Given a main\_query find all the post IDs for it not limited by pagination.
I have made this function to return all terms for the main wp\_query.
```
/*
* Get terms for a given wp_query no paging
* */
function get_terms_for_current_posts($tax='post_tag',$the_wp_query=false){
global $wp_query;
// Use global WP_Query but option to override
$q = $wp_query;
if($the_wp_query){
$q = $the_wp_query;
}
$q->query_vars['posts_per_page'] = 200;// setting -1 does not seem to work here?
$q->query_vars['fields'] = 'ids';// I only want the post IDs
$the_query = new WP_Query($q->query_vars);// get the posts
// $the_query->posts is an array of all found post IDs
// get all terms for the given array of post IDs
$y = wp_get_object_terms( $the_query->posts, $tax );
return $y;// array of term objects
}
```
Hope this helps you or someone else stumbling across this. |
323,300 | <p>so, I know this is kind of a basic question, but it somehow oddly doesn't work for me.</p>
<p>What I want:</p>
<ul>
<li><a href="https://example.com/blog/thema/" rel="nofollow noreferrer">https://example.com/blog/thema/</a><em>categoryname</em>/<em>postname</em> (for posts)</li>
<li><a href="https://example.com/blog/thema/" rel="nofollow noreferrer">https://example.com/blog/thema/</a><em>categoryname</em> (for categories)</li>
</ul>
<p>Here are my settings:
<a href="https://i.stack.imgur.com/zINI3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zINI3.jpg" alt="enter image description here"></a></p>
<p>Sadly that doesn't work. Here is a detailed information on what works on what settings:</p>
<ul>
<li><strong>Posts:</strong> <code>/blog/thema/%category%/%postname%/</code> + <strong>Category:</strong> <code>blog/thema</code> = categories work, posts getting 404</li>
<li><strong>Posts:</strong> <code>/%category%/%postname%/</code> + <strong>Category:</strong> <code>blog/thema</code> = categories work, posts are <code>example.com/categoryname/postname</code></li>
<li><strong>Posts:</strong> <code>/thema/%category%/%postname%/</code> + <strong>Category:</strong> <code>blog/thema</code> = categories work, posts are <code>example.com/thema/categoryname/postname</code></li>
<li><strong>Posts:</strong> <code>/blog/thema/%category%/%postname%/</code> + <strong>Category:</strong> <code>thema</code> = posts work as <code>example.com/blog/thema/categoryname/postname/</code> but categories work like <code>example.com/thema/categoryname</code></li>
</ul>
<p>Maybe someone can help me. I won't mind if this is only solvable with some htaccess magic or whatever. :)</p>
| [
{
"answer_id": 323301,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": -1,
"selected": false,
"text": "<p>The problem with what you're trying to do is that with your desired structure it's impossible to tell if a URL is for a subcategory or a post.</p>\n\n<p>Take this URL, for example:</p>\n\n<pre><code>http://example.com/blog/thema/abc/def/\n</code></pre>\n\n<p>Is <code>def</code> a <em>post</em> in the <code>abc</code> category? Or is <code>def</code> a <em>subcategory</em> of <code>abc</code>? I can't tell by looking at the URL, and neither can WordPress. The issue is that WordPress isn't going to try both options.</p>\n\n<p>WordPress is only ever going to look for one type of content when parsing the URL. So when WordPress sees that URL it checks if there's a subcategory of <code>abc</code> called <code>def</code>, and if that category doesn't exist WordPress will return a 404. This is why you're getting a 404 when attempting to view a post.</p>\n\n<p>You're going to need to add something to the structure to differentiate a post from a subcategory. For example, if you used <code>/blog/post/%category%/%postname%</code> as the structure, then the above URL would look like this for a subcategory:</p>\n\n<pre><code>http://example.com/blog/thema/abc/def/\n</code></pre>\n\n<p>And this for a post:</p>\n\n<pre><code>http://example.com/blog/post/abc/def/\n</code></pre>\n"
},
{
"answer_id": 323309,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>It's possible to have them share the same slug, but you need to manually resolve conflicts yourself. You have to check if the end of the requested URL is an existing term, and reset the query vars accordingly if it's not found:</p>\n\n<pre><code>function wpd_post_request_filter( $request ){\n if( array_key_exists( 'category_name' , $request )\n && ! get_term_by( 'slug', basename( $request['category_name'] ), 'category' ) ){\n $request['name'] = basename( $request['category_name'] );\n $request['post_type'] = 'post';\n unset( $request['category_name'] );\n }\n return $request;\n}\nadd_filter( 'request', 'wpd_post_request_filter' );\n</code></pre>\n\n<p>The obvious downsides to this are an extra trip to the database for every post or category view, and the inability to have a category slug that matches a post slug.</p>\n"
}
]
| 2018/12/18 | [
"https://wordpress.stackexchange.com/questions/323300",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94786/"
]
| so, I know this is kind of a basic question, but it somehow oddly doesn't work for me.
What I want:
* <https://example.com/blog/thema/>*categoryname*/*postname* (for posts)
* <https://example.com/blog/thema/>*categoryname* (for categories)
Here are my settings:
[](https://i.stack.imgur.com/zINI3.jpg)
Sadly that doesn't work. Here is a detailed information on what works on what settings:
* **Posts:** `/blog/thema/%category%/%postname%/` + **Category:** `blog/thema` = categories work, posts getting 404
* **Posts:** `/%category%/%postname%/` + **Category:** `blog/thema` = categories work, posts are `example.com/categoryname/postname`
* **Posts:** `/thema/%category%/%postname%/` + **Category:** `blog/thema` = categories work, posts are `example.com/thema/categoryname/postname`
* **Posts:** `/blog/thema/%category%/%postname%/` + **Category:** `thema` = posts work as `example.com/blog/thema/categoryname/postname/` but categories work like `example.com/thema/categoryname`
Maybe someone can help me. I won't mind if this is only solvable with some htaccess magic or whatever. :) | It's possible to have them share the same slug, but you need to manually resolve conflicts yourself. You have to check if the end of the requested URL is an existing term, and reset the query vars accordingly if it's not found:
```
function wpd_post_request_filter( $request ){
if( array_key_exists( 'category_name' , $request )
&& ! get_term_by( 'slug', basename( $request['category_name'] ), 'category' ) ){
$request['name'] = basename( $request['category_name'] );
$request['post_type'] = 'post';
unset( $request['category_name'] );
}
return $request;
}
add_filter( 'request', 'wpd_post_request_filter' );
```
The obvious downsides to this are an extra trip to the database for every post or category view, and the inability to have a category slug that matches a post slug. |
323,329 | <p>I'm trying to change the logo url for some categories and pages. In the Theme options there is the possibility to change the logo img for categories and pages, but can't change the logo url. I have tried this code in my child theme function.php file but it is not working:</p>
<pre><code>function change_logo_url_animacao($html) {
$custom_logo_id = get_theme_mod( 'custom_logo' );
$url = home_url( 'pimeanimacao', 'relative' );
if(is_page( array( 6447, 7 ) )){
$html = sprintf( '<a href="%1$s">%2$s</a>',
esc_url( $url ),
wp_get_attachment_image( $custom_logo_id, 'full', false, array(
'class' => 'custom-logo',))
);
}elseif(is_category( 39 ) || cat_is_ancestor_of( 39, get_query_var( 'cat' ) )){
$html = sprintf( '<a href="%1$s">%2$s</a>',
esc_url( $url ),
wp_get_attachment_image( $custom_logo_id, 'full', false, array(
'class' => 'custom-logo',))
);
}elseif(in_category( array( 39,25,18,3,24,58 ) )){
$html = sprintf( '<a href="%1$s">%2$s</a>',
esc_url( $url ),
wp_get_attachment_image( $custom_logo_id, 'full', false, array(
'class' => 'custom-logo',))
);
}
return $html;
}
add_filter('get_custom_logo','change_logo_url_animacao');
</code></pre>
<p>The header I'm using have this code to load the logo:</p>
<pre><code><div class="contact_logo">
<?php xxx_show_logo(true, true); ?>
</div>
</code></pre>
<p>And the function called here xxx_show_logo in in the file core.theme.php of the framework. Here is the funcion:</p>
<pre><code>if ( !function_exists( 'xxx_show_logo' ) ) {
function xxx_show_logo($logo_main=true, $logo_fixed=false, $logo_footer=false, $logo_side=false, $logo_text=true, $logo_slogan=true) {
if ($logo_main===true) $logo_main = xxx_storage_get('logo');
if ($logo_fixed===true) $logo_fixed = xxx_storage_get('logo_fixed');
if ($logo_footer===true) $logo_footer = xxx_storage_get('logo_footer');
if ($logo_side===true) $logo_side = xxx_storage_get('logo_side');
if ($logo_text===true) $logo_text = xxx_storage_get('logo_text');
if ($logo_slogan===true) $logo_slogan = xxx_storage_get('logo_slogan');
if (empty($logo_main) && empty($logo_fixed) && empty($logo_footer) && empty($logo_side) && empty($logo_text))
$logo_text = get_bloginfo('name');
if ($logo_main || $logo_fixed || $logo_footer || $logo_side || $logo_text) {
?>
<div class="logo">
<a href="<?php echo esc_url(home_url('/')); ?>"><?php
if (!empty($logo_main)) {
$attr = xxx_getimagesize($logo_main);
echo '<img src="'.esc_url($logo_main).'" class="logo_main" alt="'.esc_attr__('Image', 'charity-is-hope').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'>';
}
if (!empty($logo_fixed)) {
$attr = xxx_getimagesize($logo_fixed);
echo '<img src="'.esc_url($logo_fixed).'" class="logo_fixed" alt="'.esc_attr__('Image', 'charity-is-hope').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'>';
}
if (!empty($logo_footer)) {
$attr = xxx_getimagesize($logo_footer);
echo '<img src="'.esc_url($logo_footer).'" class="logo_footer" alt="'.esc_attr__('Image', 'xxx').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'>';
}
if (!empty($logo_side)) {
$attr = xxx_getimagesize($logo_side);
echo '<img src="'.esc_url($logo_side).'" class="logo_side" alt="'.esc_attr__('Image', 'xxx').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'>';
}
echo !empty($logo_text) ? '<div class="logo_text">'.trim($logo_text).'</div>' : '';
echo !empty($logo_slogan) ? '<br><div class="logo_slogan">' . esc_html($logo_slogan) . '</div>' : '';
?></a>
</div>
<?php
}
}
}
</code></pre>
<p>Now I need to change this: <code><a href="<?php echo esc_url(home_url('/')); ?>"></code>
in some categories and pages to this link "site_domain/pimeanimacao".
How can I solve it?
Thank you in advance for helping me! </p>
| [
{
"answer_id": 323301,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": -1,
"selected": false,
"text": "<p>The problem with what you're trying to do is that with your desired structure it's impossible to tell if a URL is for a subcategory or a post.</p>\n\n<p>Take this URL, for example:</p>\n\n<pre><code>http://example.com/blog/thema/abc/def/\n</code></pre>\n\n<p>Is <code>def</code> a <em>post</em> in the <code>abc</code> category? Or is <code>def</code> a <em>subcategory</em> of <code>abc</code>? I can't tell by looking at the URL, and neither can WordPress. The issue is that WordPress isn't going to try both options.</p>\n\n<p>WordPress is only ever going to look for one type of content when parsing the URL. So when WordPress sees that URL it checks if there's a subcategory of <code>abc</code> called <code>def</code>, and if that category doesn't exist WordPress will return a 404. This is why you're getting a 404 when attempting to view a post.</p>\n\n<p>You're going to need to add something to the structure to differentiate a post from a subcategory. For example, if you used <code>/blog/post/%category%/%postname%</code> as the structure, then the above URL would look like this for a subcategory:</p>\n\n<pre><code>http://example.com/blog/thema/abc/def/\n</code></pre>\n\n<p>And this for a post:</p>\n\n<pre><code>http://example.com/blog/post/abc/def/\n</code></pre>\n"
},
{
"answer_id": 323309,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>It's possible to have them share the same slug, but you need to manually resolve conflicts yourself. You have to check if the end of the requested URL is an existing term, and reset the query vars accordingly if it's not found:</p>\n\n<pre><code>function wpd_post_request_filter( $request ){\n if( array_key_exists( 'category_name' , $request )\n && ! get_term_by( 'slug', basename( $request['category_name'] ), 'category' ) ){\n $request['name'] = basename( $request['category_name'] );\n $request['post_type'] = 'post';\n unset( $request['category_name'] );\n }\n return $request;\n}\nadd_filter( 'request', 'wpd_post_request_filter' );\n</code></pre>\n\n<p>The obvious downsides to this are an extra trip to the database for every post or category view, and the inability to have a category slug that matches a post slug.</p>\n"
}
]
| 2018/12/18 | [
"https://wordpress.stackexchange.com/questions/323329",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154563/"
]
| I'm trying to change the logo url for some categories and pages. In the Theme options there is the possibility to change the logo img for categories and pages, but can't change the logo url. I have tried this code in my child theme function.php file but it is not working:
```
function change_logo_url_animacao($html) {
$custom_logo_id = get_theme_mod( 'custom_logo' );
$url = home_url( 'pimeanimacao', 'relative' );
if(is_page( array( 6447, 7 ) )){
$html = sprintf( '<a href="%1$s">%2$s</a>',
esc_url( $url ),
wp_get_attachment_image( $custom_logo_id, 'full', false, array(
'class' => 'custom-logo',))
);
}elseif(is_category( 39 ) || cat_is_ancestor_of( 39, get_query_var( 'cat' ) )){
$html = sprintf( '<a href="%1$s">%2$s</a>',
esc_url( $url ),
wp_get_attachment_image( $custom_logo_id, 'full', false, array(
'class' => 'custom-logo',))
);
}elseif(in_category( array( 39,25,18,3,24,58 ) )){
$html = sprintf( '<a href="%1$s">%2$s</a>',
esc_url( $url ),
wp_get_attachment_image( $custom_logo_id, 'full', false, array(
'class' => 'custom-logo',))
);
}
return $html;
}
add_filter('get_custom_logo','change_logo_url_animacao');
```
The header I'm using have this code to load the logo:
```
<div class="contact_logo">
<?php xxx_show_logo(true, true); ?>
</div>
```
And the function called here xxx\_show\_logo in in the file core.theme.php of the framework. Here is the funcion:
```
if ( !function_exists( 'xxx_show_logo' ) ) {
function xxx_show_logo($logo_main=true, $logo_fixed=false, $logo_footer=false, $logo_side=false, $logo_text=true, $logo_slogan=true) {
if ($logo_main===true) $logo_main = xxx_storage_get('logo');
if ($logo_fixed===true) $logo_fixed = xxx_storage_get('logo_fixed');
if ($logo_footer===true) $logo_footer = xxx_storage_get('logo_footer');
if ($logo_side===true) $logo_side = xxx_storage_get('logo_side');
if ($logo_text===true) $logo_text = xxx_storage_get('logo_text');
if ($logo_slogan===true) $logo_slogan = xxx_storage_get('logo_slogan');
if (empty($logo_main) && empty($logo_fixed) && empty($logo_footer) && empty($logo_side) && empty($logo_text))
$logo_text = get_bloginfo('name');
if ($logo_main || $logo_fixed || $logo_footer || $logo_side || $logo_text) {
?>
<div class="logo">
<a href="<?php echo esc_url(home_url('/')); ?>"><?php
if (!empty($logo_main)) {
$attr = xxx_getimagesize($logo_main);
echo '<img src="'.esc_url($logo_main).'" class="logo_main" alt="'.esc_attr__('Image', 'charity-is-hope').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'>';
}
if (!empty($logo_fixed)) {
$attr = xxx_getimagesize($logo_fixed);
echo '<img src="'.esc_url($logo_fixed).'" class="logo_fixed" alt="'.esc_attr__('Image', 'charity-is-hope').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'>';
}
if (!empty($logo_footer)) {
$attr = xxx_getimagesize($logo_footer);
echo '<img src="'.esc_url($logo_footer).'" class="logo_footer" alt="'.esc_attr__('Image', 'xxx').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'>';
}
if (!empty($logo_side)) {
$attr = xxx_getimagesize($logo_side);
echo '<img src="'.esc_url($logo_side).'" class="logo_side" alt="'.esc_attr__('Image', 'xxx').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'>';
}
echo !empty($logo_text) ? '<div class="logo_text">'.trim($logo_text).'</div>' : '';
echo !empty($logo_slogan) ? '<br><div class="logo_slogan">' . esc_html($logo_slogan) . '</div>' : '';
?></a>
</div>
<?php
}
}
}
```
Now I need to change this: `<a href="<?php echo esc_url(home_url('/')); ?>">`
in some categories and pages to this link "site\_domain/pimeanimacao".
How can I solve it?
Thank you in advance for helping me! | It's possible to have them share the same slug, but you need to manually resolve conflicts yourself. You have to check if the end of the requested URL is an existing term, and reset the query vars accordingly if it's not found:
```
function wpd_post_request_filter( $request ){
if( array_key_exists( 'category_name' , $request )
&& ! get_term_by( 'slug', basename( $request['category_name'] ), 'category' ) ){
$request['name'] = basename( $request['category_name'] );
$request['post_type'] = 'post';
unset( $request['category_name'] );
}
return $request;
}
add_filter( 'request', 'wpd_post_request_filter' );
```
The obvious downsides to this are an extra trip to the database for every post or category view, and the inability to have a category slug that matches a post slug. |
323,338 | <p>I am working on this jQuery which will eventually populate fields from the Parent field (Features) to the Children fields (Description, address, etc.) within a List Field. I have been able to get the fields to populate in a certain column, but when I change the first row parent, it changes the children field in all the rows.</p>
<p>You can see an idea of what I am working on here: <a href="https://goadrifttravel.com/00-test/" rel="nofollow noreferrer">https://goadrifttravel.com/00-test/</a></p>
<p>Also this is the code I have been working with:</p>
<pre><code>jQuery(document).ready(function($) {
// START Place Jquery in here
$( "select" ).change(function() {
$(this).parent().click(function() {
var str = "";
$( "td.gfield_list_1_cell4 option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$( "td.gfield_list_1_cell5 input" ).val( str );
})
.trigger( "change" );
});
});
</code></pre>
<p>Any thoughts on how to target one jQuery Row at a time within the List Field? I've been trying the each() function, but so far no luck.</p>
| [
{
"answer_id": 323301,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": -1,
"selected": false,
"text": "<p>The problem with what you're trying to do is that with your desired structure it's impossible to tell if a URL is for a subcategory or a post.</p>\n\n<p>Take this URL, for example:</p>\n\n<pre><code>http://example.com/blog/thema/abc/def/\n</code></pre>\n\n<p>Is <code>def</code> a <em>post</em> in the <code>abc</code> category? Or is <code>def</code> a <em>subcategory</em> of <code>abc</code>? I can't tell by looking at the URL, and neither can WordPress. The issue is that WordPress isn't going to try both options.</p>\n\n<p>WordPress is only ever going to look for one type of content when parsing the URL. So when WordPress sees that URL it checks if there's a subcategory of <code>abc</code> called <code>def</code>, and if that category doesn't exist WordPress will return a 404. This is why you're getting a 404 when attempting to view a post.</p>\n\n<p>You're going to need to add something to the structure to differentiate a post from a subcategory. For example, if you used <code>/blog/post/%category%/%postname%</code> as the structure, then the above URL would look like this for a subcategory:</p>\n\n<pre><code>http://example.com/blog/thema/abc/def/\n</code></pre>\n\n<p>And this for a post:</p>\n\n<pre><code>http://example.com/blog/post/abc/def/\n</code></pre>\n"
},
{
"answer_id": 323309,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>It's possible to have them share the same slug, but you need to manually resolve conflicts yourself. You have to check if the end of the requested URL is an existing term, and reset the query vars accordingly if it's not found:</p>\n\n<pre><code>function wpd_post_request_filter( $request ){\n if( array_key_exists( 'category_name' , $request )\n && ! get_term_by( 'slug', basename( $request['category_name'] ), 'category' ) ){\n $request['name'] = basename( $request['category_name'] );\n $request['post_type'] = 'post';\n unset( $request['category_name'] );\n }\n return $request;\n}\nadd_filter( 'request', 'wpd_post_request_filter' );\n</code></pre>\n\n<p>The obvious downsides to this are an extra trip to the database for every post or category view, and the inability to have a category slug that matches a post slug.</p>\n"
}
]
| 2018/12/18 | [
"https://wordpress.stackexchange.com/questions/323338",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/146177/"
]
| I am working on this jQuery which will eventually populate fields from the Parent field (Features) to the Children fields (Description, address, etc.) within a List Field. I have been able to get the fields to populate in a certain column, but when I change the first row parent, it changes the children field in all the rows.
You can see an idea of what I am working on here: <https://goadrifttravel.com/00-test/>
Also this is the code I have been working with:
```
jQuery(document).ready(function($) {
// START Place Jquery in here
$( "select" ).change(function() {
$(this).parent().click(function() {
var str = "";
$( "td.gfield_list_1_cell4 option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$( "td.gfield_list_1_cell5 input" ).val( str );
})
.trigger( "change" );
});
});
```
Any thoughts on how to target one jQuery Row at a time within the List Field? I've been trying the each() function, but so far no luck. | It's possible to have them share the same slug, but you need to manually resolve conflicts yourself. You have to check if the end of the requested URL is an existing term, and reset the query vars accordingly if it's not found:
```
function wpd_post_request_filter( $request ){
if( array_key_exists( 'category_name' , $request )
&& ! get_term_by( 'slug', basename( $request['category_name'] ), 'category' ) ){
$request['name'] = basename( $request['category_name'] );
$request['post_type'] = 'post';
unset( $request['category_name'] );
}
return $request;
}
add_filter( 'request', 'wpd_post_request_filter' );
```
The obvious downsides to this are an extra trip to the database for every post or category view, and the inability to have a category slug that matches a post slug. |
323,339 | <p>Disclaimer: I'm rubbish at PHP, so please bear with me as I'm still learning. I'm getting the PHP error <code>Array to string conversion</code> for the following code:</p>
<pre><code>function osu_add_role_to_body($classes = '') {
$current_user = new WP_User(get_current_user_id());
$user_role = array_shift($current_user->roles);
$classes = [];
$classes[] = 'role-' . $user_role;
return $classes;
}
add_filter('body_class','osu_add_role_to_body');
</code></pre>
<p>This only started happening since I upgraded to PHP 7.2 so I'm assuming things have changed with how I need to deal with arrays right? Any idea of how to fix?</p>
| [
{
"answer_id": 323399,
"author": "Osu",
"author_id": 2685,
"author_profile": "https://wordpress.stackexchange.com/users/2685",
"pm_score": 0,
"selected": false,
"text": "<p>I found that the problem was I was not checking if the user was logged in before adding the class. Here's my working code for anyone with the same issue:</p>\n\n<p><strong>header.php</strong></p>\n\n<pre><code><body <?php body_class( 'animate' ); ?> id=\"top\">\n</code></pre>\n\n<p>(Note: the 'animate' class is irrelevant, it's just used in my site)</p>\n\n<p><strong>functions.php</strong></p>\n\n<pre><code>function osu_add_role_to_body($classes = '') {\n if( is_user_logged_in() ) {\n $current_user = new WP_User(get_current_user_id());\n $user_role = array_shift($current_user->roles);\n $classes[] = 'role-' . $user_role;\n }\n return $classes;\n}\nadd_filter('body_class','osu_add_role_to_body');\n</code></pre>\n"
},
{
"answer_id": 337446,
"author": "coolpasta",
"author_id": 143406,
"author_profile": "https://wordpress.stackexchange.com/users/143406",
"pm_score": 1,
"selected": false,
"text": "<p>This code works and is perfectly valid, running on 7.3, except when your user has two roles:</p>\n\n<pre><code>add_filter( 'body_class', function( $classes = '' ) {\n $current_user = new \\WP_User(get_current_user_id());\n $user_role = ['administrator', 'moderator']; //just a test, but this is what it'll look like if it had 2 roles.\n $classes = [];\n $classes[] = 'role-' . $user_role;\n return $classes;\n});\n</code></pre>\n\n<p>Then, what do you know, the same error appears. Also, you're passing a string as <code>$classes</code> to your anonymous function, where-as the filter clearly demands an array.</p>\n\n<p>Do this instead:</p>\n\n<pre><code>add_filter( 'body_class', function( $classes ) {\n $current_user = wp_get_current_user();\n\n foreach( $current_user->roles as $user_role ) {\n $classes[] = 'role-' . $user_role;\n }\n return $classes;\n});\n</code></pre>\n"
}
]
| 2018/12/18 | [
"https://wordpress.stackexchange.com/questions/323339",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2685/"
]
| Disclaimer: I'm rubbish at PHP, so please bear with me as I'm still learning. I'm getting the PHP error `Array to string conversion` for the following code:
```
function osu_add_role_to_body($classes = '') {
$current_user = new WP_User(get_current_user_id());
$user_role = array_shift($current_user->roles);
$classes = [];
$classes[] = 'role-' . $user_role;
return $classes;
}
add_filter('body_class','osu_add_role_to_body');
```
This only started happening since I upgraded to PHP 7.2 so I'm assuming things have changed with how I need to deal with arrays right? Any idea of how to fix? | This code works and is perfectly valid, running on 7.3, except when your user has two roles:
```
add_filter( 'body_class', function( $classes = '' ) {
$current_user = new \WP_User(get_current_user_id());
$user_role = ['administrator', 'moderator']; //just a test, but this is what it'll look like if it had 2 roles.
$classes = [];
$classes[] = 'role-' . $user_role;
return $classes;
});
```
Then, what do you know, the same error appears. Also, you're passing a string as `$classes` to your anonymous function, where-as the filter clearly demands an array.
Do this instead:
```
add_filter( 'body_class', function( $classes ) {
$current_user = wp_get_current_user();
foreach( $current_user->roles as $user_role ) {
$classes[] = 'role-' . $user_role;
}
return $classes;
});
``` |
323,354 | <p>I have created a custom image taxonomy field in WordPress using CMB2. I cannot get the images to display for website visitors even though my code uses <strong>get_term_meta</strong>. (The taxonomy images are amenity icons such as WiFi, shower head, electricity etc). </p>
<p>What am I doing wrong?</p>
<p>Relevant (not working) code in single-accommodation.php:</p>
<pre><code><?php
$term_id = get_queried_object()->term_id;
$tax_image = get_term_meta( $term_id, 'custom_taxonomy_image', true );
if ( $tax_image ) {
printf( '<div class="icon"><img src=$s /></div>', $tax_image );
}
?>
</code></pre>
<p>I'm sure i'd need a foreach somewhere, like this:</p>
<pre><code><ul class="amenity-icons">
<?php
foreach( $terms as $term => $icon ) {
if( isset( $term ) ) {
echo '<li>' . $icon . '</li>';
}
}
?>
</ul>
</code></pre>
<p>I can successfully retrieve the term list as words using: </p>
<pre><code><?php the_terms( get_the_ID(), 'amenity' ); ?>
</code></pre>
| [
{
"answer_id": 323399,
"author": "Osu",
"author_id": 2685,
"author_profile": "https://wordpress.stackexchange.com/users/2685",
"pm_score": 0,
"selected": false,
"text": "<p>I found that the problem was I was not checking if the user was logged in before adding the class. Here's my working code for anyone with the same issue:</p>\n\n<p><strong>header.php</strong></p>\n\n<pre><code><body <?php body_class( 'animate' ); ?> id=\"top\">\n</code></pre>\n\n<p>(Note: the 'animate' class is irrelevant, it's just used in my site)</p>\n\n<p><strong>functions.php</strong></p>\n\n<pre><code>function osu_add_role_to_body($classes = '') {\n if( is_user_logged_in() ) {\n $current_user = new WP_User(get_current_user_id());\n $user_role = array_shift($current_user->roles);\n $classes[] = 'role-' . $user_role;\n }\n return $classes;\n}\nadd_filter('body_class','osu_add_role_to_body');\n</code></pre>\n"
},
{
"answer_id": 337446,
"author": "coolpasta",
"author_id": 143406,
"author_profile": "https://wordpress.stackexchange.com/users/143406",
"pm_score": 1,
"selected": false,
"text": "<p>This code works and is perfectly valid, running on 7.3, except when your user has two roles:</p>\n\n<pre><code>add_filter( 'body_class', function( $classes = '' ) {\n $current_user = new \\WP_User(get_current_user_id());\n $user_role = ['administrator', 'moderator']; //just a test, but this is what it'll look like if it had 2 roles.\n $classes = [];\n $classes[] = 'role-' . $user_role;\n return $classes;\n});\n</code></pre>\n\n<p>Then, what do you know, the same error appears. Also, you're passing a string as <code>$classes</code> to your anonymous function, where-as the filter clearly demands an array.</p>\n\n<p>Do this instead:</p>\n\n<pre><code>add_filter( 'body_class', function( $classes ) {\n $current_user = wp_get_current_user();\n\n foreach( $current_user->roles as $user_role ) {\n $classes[] = 'role-' . $user_role;\n }\n return $classes;\n});\n</code></pre>\n"
}
]
| 2018/12/19 | [
"https://wordpress.stackexchange.com/questions/323354",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| I have created a custom image taxonomy field in WordPress using CMB2. I cannot get the images to display for website visitors even though my code uses **get\_term\_meta**. (The taxonomy images are amenity icons such as WiFi, shower head, electricity etc).
What am I doing wrong?
Relevant (not working) code in single-accommodation.php:
```
<?php
$term_id = get_queried_object()->term_id;
$tax_image = get_term_meta( $term_id, 'custom_taxonomy_image', true );
if ( $tax_image ) {
printf( '<div class="icon"><img src=$s /></div>', $tax_image );
}
?>
```
I'm sure i'd need a foreach somewhere, like this:
```
<ul class="amenity-icons">
<?php
foreach( $terms as $term => $icon ) {
if( isset( $term ) ) {
echo '<li>' . $icon . '</li>';
}
}
?>
</ul>
```
I can successfully retrieve the term list as words using:
```
<?php the_terms( get_the_ID(), 'amenity' ); ?>
``` | This code works and is perfectly valid, running on 7.3, except when your user has two roles:
```
add_filter( 'body_class', function( $classes = '' ) {
$current_user = new \WP_User(get_current_user_id());
$user_role = ['administrator', 'moderator']; //just a test, but this is what it'll look like if it had 2 roles.
$classes = [];
$classes[] = 'role-' . $user_role;
return $classes;
});
```
Then, what do you know, the same error appears. Also, you're passing a string as `$classes` to your anonymous function, where-as the filter clearly demands an array.
Do this instead:
```
add_filter( 'body_class', function( $classes ) {
$current_user = wp_get_current_user();
foreach( $current_user->roles as $user_role ) {
$classes[] = 'role-' . $user_role;
}
return $classes;
});
``` |
323,361 | <p>I want to show the <strong>"last updated date"</strong> on the front of the post and page.<br>
so I add the following code in the functions.php file.<br></p>
<pre><code>function wpb_last_updated_date( $content ) {
$u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
if ($u_modified_time >= $u_time + 86400) {
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a');
$custom_content .= '<p class="last-updated" style="text-align:right">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
}
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
</code></pre>
<p>It works,but I don`t want to show <strong>it</strong> on my home page.<br></p>
<p>How can I do ?</p>
| [
{
"answer_id": 323428,
"author": "scytale",
"author_id": 128374,
"author_profile": "https://wordpress.stackexchange.com/users/128374",
"pm_score": 2,
"selected": true,
"text": "<p>You can check for your \"home page\" at the start of your function by using <code>is_home()</code> and/or <code>is_front_page()</code> and just return original content without date. See <a href=\"https://wordpress.stackexchange.com/questions/30385/when-to-use-is-home-vs-is-front-page\">is_home vs is_front_page</a></p>\n\n<pre><code>function wpb_last_updated_date( $content ) {\n if ( is_home() || is_front_page() ) return $content; //homepage return content without date\n\n // your original function code\n\n}\n</code></pre>\n\n<p>Alterantively you could embes your add_filter in an if statement</p>\n"
},
{
"answer_id": 323467,
"author": "cindy",
"author_id": 157283,
"author_profile": "https://wordpress.stackexchange.com/users/157283",
"pm_score": 0,
"selected": false,
"text": "<p>I finally solved the problem !!</p>\n\n<pre><code>function wpb_last_updated_date( $content ) {\nif( is_front_page() || is_home() ) {\n return $content;\n}\nif( is_page(array(1017,927))){ \n return $content; \n}\n$u_time = get_the_time('U');\n$u_modified_time = get_the_modified_time('U');\nif ($u_modified_time >= $u_time + 86400) {\n$updated_date = get_the_modified_time('F jS, Y');\n$updated_time = get_the_modified_time('h:i a');\n$custom_content .= '<p class=\"last-updated\">Last updated on '. $updated_date . ' at '. $updated_time .'</p>'; \n}\n $custom_content .= $content;\n return $custom_content;\n}\nadd_filter( 'the_content', 'wpb_last_updated_date' );\n</code></pre>\n"
}
]
| 2018/12/19 | [
"https://wordpress.stackexchange.com/questions/323361",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157283/"
]
| I want to show the **"last updated date"** on the front of the post and page.
so I add the following code in the functions.php file.
```
function wpb_last_updated_date( $content ) {
$u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
if ($u_modified_time >= $u_time + 86400) {
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a');
$custom_content .= '<p class="last-updated" style="text-align:right">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
}
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
```
It works,but I don`t want to show **it** on my home page.
How can I do ? | You can check for your "home page" at the start of your function by using `is_home()` and/or `is_front_page()` and just return original content without date. See [is\_home vs is\_front\_page](https://wordpress.stackexchange.com/questions/30385/when-to-use-is-home-vs-is-front-page)
```
function wpb_last_updated_date( $content ) {
if ( is_home() || is_front_page() ) return $content; //homepage return content without date
// your original function code
}
```
Alterantively you could embes your add\_filter in an if statement |
323,380 | <p>I have a WordPress website which was working good before WordPress 5.0. after update to WordPress 5.0 I get an 404 error on loading resources. </p>
<pre><code>style.min-rtl.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)
</code></pre>
<p>and the missing file address is :</p>
<pre><code>http://example.com/wp-includes/css/dist/block-library/style.min-rtl.css?ver=5.0.1
</code></pre>
<p>I am wondering why I got this error? in the older versions of WordPress there was not such a file or directory but I was not getting this error. I was hoping this will be fixed in the latest WP update v5.0.1 but it's not.</p>
<p>Is it a problem in my theme or WP or maybe something else?</p>
| [
{
"answer_id": 323392,
"author": "CRavon",
"author_id": 122086,
"author_profile": "https://wordpress.stackexchange.com/users/122086",
"pm_score": 0,
"selected": false,
"text": "<p>The name of the file in WP 5.0.1 is \"style-rtl.min.css\" and not \"style.min-rtl.css\". \nSo did you try to check for plugin of cache or optimization that would have wrongly rename it ? </p>\n"
},
{
"answer_id": 323396,
"author": "ehsan",
"author_id": 109403,
"author_profile": "https://wordpress.stackexchange.com/users/109403",
"pm_score": 2,
"selected": true,
"text": "<p>First I tried to disable all plugins and change theme to the default WordPress theme and error is showing yet.</p>\n\n<p>Then tried to install a new WordPress 5.0.1 and got 2 errors:</p>\n\n<pre><code>theme.min-rtl.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)\nstyle.min-rtl.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)\n</code></pre>\n\n<p>I changed the WP language to English and the errors gone. and the errors comeback on all right to left languages. so it seems to be a WP issue and needs to be fixed in future versions.</p>\n"
}
]
| 2018/12/19 | [
"https://wordpress.stackexchange.com/questions/323380",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109403/"
]
| I have a WordPress website which was working good before WordPress 5.0. after update to WordPress 5.0 I get an 404 error on loading resources.
```
style.min-rtl.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)
```
and the missing file address is :
```
http://example.com/wp-includes/css/dist/block-library/style.min-rtl.css?ver=5.0.1
```
I am wondering why I got this error? in the older versions of WordPress there was not such a file or directory but I was not getting this error. I was hoping this will be fixed in the latest WP update v5.0.1 but it's not.
Is it a problem in my theme or WP or maybe something else? | First I tried to disable all plugins and change theme to the default WordPress theme and error is showing yet.
Then tried to install a new WordPress 5.0.1 and got 2 errors:
```
theme.min-rtl.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)
style.min-rtl.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)
```
I changed the WP language to English and the errors gone. and the errors comeback on all right to left languages. so it seems to be a WP issue and needs to be fixed in future versions. |
323,404 | <p>I have been looking around for the answer but did not find any.</p>
<p>I am creating an <code>iframe</code> payment gateway while the iframe is loaded inside the checkout page. My goal is once the customer clicks on a certain button, the function which validates that the customer has filled all the required input is triggered and if it returns <code>true</code> the iframe loads.</p>
<p>Otherwise, the notice from the validating function is triggered.</p>
<p>I found the function as a method called <code>update_checkout_action</code> inside the <code>wc_checkout_form</code> class.</p>
<p>Hope it's enough information, if needed any more, please let me know and I'll provide.</p>
<p>Thanks.</p>
| [
{
"answer_id": 323425,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into this a few times, I have yet to find a straight forward method of handling it. But here is what I've done in the past.</p>\n\n<p>You can trigger checkout validation easily by forcing a click on the submit button.</p>\n\n<pre><code> $('#myButton').on('click', function(){\n $('#place_order').click();\n });\n</code></pre>\n\n<p>However, this isn't really useful for you because it will just submit the order if there are no errors.</p>\n\n<p>There is also the checkout_error callback, but it only fires if there is a error. </p>\n\n<pre><code> $(document.body).on('checkout_error', function () {\n // There was a validation error\n });\n</code></pre>\n\n<p>Here is what we need to do.</p>\n\n<ul>\n<li>Detect when the submit button is clicked</li>\n<li>Check for errors</li>\n<li>If there are errors let Woo handle them as normal</li>\n<li>If there are No errors, stop the order from completing</li>\n<li>Show your iframe</li>\n<li>... Re-Validate / Re-submit Order</li>\n</ul>\n\n<hr>\n\n<hr>\n\n<p>As soon as the submit button is clicked, we can add a hidden field and set the value to 1. We can detect the submit event by using checkout_place_order. This should go in your JS file.</p>\n\n<pre><code>var checkout_form = $('form.woocommerce-checkout');\n\ncheckout_form.on('checkout_place_order', function () {\n if ($('#confirm-order-flag').length == 0) {\n checkout_form.append('<input type=\"hidden\" id=\"confirm-order-flag\" name=\"confirm-order-flag\" value=\"1\">');\n }\n return true;\n});\n</code></pre>\n\n<p>Now, add a function to functions.php that will check that hidden input and stop the order if the value == 1. It stops the order by adding an error.</p>\n\n<pre><code>function add_fake_error($posted) {\n if ($_POST['confirm-order-flag'] == \"1\") {\n wc_add_notice( __( \"custom_notice\", 'fake_error' ), 'error');\n } \n}\n\nadd_action('woocommerce_after_checkout_validation', 'add_fake_error');\n</code></pre>\n\n<p>Back in our JS file, we can use the checkout_error callback, if it has 1 error we know it was the fake error we created so we can show the iframe. If it has more than 1 error it means there are other real errors on the page.</p>\n\n<pre><code>$(document.body).on('checkout_error', function () {\n var error_count = $('.woocommerce-error li').length;\n\n if (error_count == 1) { // Validation Passed (Just the Fake Error Exists)\n // Show iFrame\n }else{ // Validation Failed (Real Errors Exists, Remove the Fake One)\n $('.woocommerce-error li').each(function(){\n var error_text = $(this).text();\n if (error_text == 'custom_notice'){\n $(this).css('display', 'none');\n }\n });\n }\n});\n</code></pre>\n\n<p>In the commented out section, // Show iFrame, I would probably open in it in a lightbox. At some point you will need another submit button that triggers the form submit and set the hidden input.</p>\n\n<pre><code>$('#confirm-order-button').click(function () {\n $('#confirm-order-flag').val('');\n $('#place_order').trigger('click');\n});\n</code></pre>\n"
},
{
"answer_id": 357940,
"author": "Zak the Gear",
"author_id": 155300,
"author_profile": "https://wordpress.stackexchange.com/users/155300",
"pm_score": 0,
"selected": false,
"text": "<p>I got a fast and simple JS decision for myself in this case (there were woocommerce and stripe forms). That is based on preventing the checkout button from submit but still makes forms verifications.</p>\n\n<pre><code>// making the wrap click event on dinamic element\n\n$('body').on('click', 'button#place_order_wrap', function(event) { \n\n // main interval where all things will be \n\n var validatoins = setInterval(function(){ happen\n\n // checking for errors\n\n if(no_errors==0){ \n\n // making the setTimeout() function with limited time like 200ms \n // to limit checkout function for just make verification\n\n setTimeout(function(){ \n\n // triggering original button\n\n $('button#place_order').click(); \n\n // if there some errors, stop the interval, return false\n\n if(($('element').find('ul.woocommerce_error').length!==0)||($('element').find('.woocommerce-invalid-required-field').length!==0)){ \n\n clearInterval(validatoins);\n return false;\n\n }else{\n\n no_errors=1;\n\n }\n }, 200);\n }\n\n\n if(no_errors==1){ \n\n // same error checking\n\n if($('#step5').find('ul.woocommerce_error').length!=0||($('#step5').find('.woocommerce-invalid-required-field').length!==0)){ \n\n // if there some errors, stop the interval, return false\n\n clearInterval(validatoins);\n return false; \n }\n\n\n setTimeout(function(){\n\n // if no errors\n\n if(($('#step5').find('ul.woocommerce_error').length==0)&&($('#step5').find('.woocommerce-invalid-required-field').length==0)){ \n\n // do something, mark that finished\n\n return false;\n }\n }, 1000);\n\n\n // if something finished\n\n if() {\n\n setTimeout(function(){\n\n // trigger original checkout click\n\n $('button#place_order').click(); \n clearInterval(validatoins);\n }, 1000);\n\n }\n\n }\n\n }, 1000);\n}\n</code></pre>\n"
}
]
| 2018/12/19 | [
"https://wordpress.stackexchange.com/questions/323404",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147331/"
]
| I have been looking around for the answer but did not find any.
I am creating an `iframe` payment gateway while the iframe is loaded inside the checkout page. My goal is once the customer clicks on a certain button, the function which validates that the customer has filled all the required input is triggered and if it returns `true` the iframe loads.
Otherwise, the notice from the validating function is triggered.
I found the function as a method called `update_checkout_action` inside the `wc_checkout_form` class.
Hope it's enough information, if needed any more, please let me know and I'll provide.
Thanks. | I ran into this a few times, I have yet to find a straight forward method of handling it. But here is what I've done in the past.
You can trigger checkout validation easily by forcing a click on the submit button.
```
$('#myButton').on('click', function(){
$('#place_order').click();
});
```
However, this isn't really useful for you because it will just submit the order if there are no errors.
There is also the checkout\_error callback, but it only fires if there is a error.
```
$(document.body).on('checkout_error', function () {
// There was a validation error
});
```
Here is what we need to do.
* Detect when the submit button is clicked
* Check for errors
* If there are errors let Woo handle them as normal
* If there are No errors, stop the order from completing
* Show your iframe
* ... Re-Validate / Re-submit Order
---
---
As soon as the submit button is clicked, we can add a hidden field and set the value to 1. We can detect the submit event by using checkout\_place\_order. This should go in your JS file.
```
var checkout_form = $('form.woocommerce-checkout');
checkout_form.on('checkout_place_order', function () {
if ($('#confirm-order-flag').length == 0) {
checkout_form.append('<input type="hidden" id="confirm-order-flag" name="confirm-order-flag" value="1">');
}
return true;
});
```
Now, add a function to functions.php that will check that hidden input and stop the order if the value == 1. It stops the order by adding an error.
```
function add_fake_error($posted) {
if ($_POST['confirm-order-flag'] == "1") {
wc_add_notice( __( "custom_notice", 'fake_error' ), 'error');
}
}
add_action('woocommerce_after_checkout_validation', 'add_fake_error');
```
Back in our JS file, we can use the checkout\_error callback, if it has 1 error we know it was the fake error we created so we can show the iframe. If it has more than 1 error it means there are other real errors on the page.
```
$(document.body).on('checkout_error', function () {
var error_count = $('.woocommerce-error li').length;
if (error_count == 1) { // Validation Passed (Just the Fake Error Exists)
// Show iFrame
}else{ // Validation Failed (Real Errors Exists, Remove the Fake One)
$('.woocommerce-error li').each(function(){
var error_text = $(this).text();
if (error_text == 'custom_notice'){
$(this).css('display', 'none');
}
});
}
});
```
In the commented out section, // Show iFrame, I would probably open in it in a lightbox. At some point you will need another submit button that triggers the form submit and set the hidden input.
```
$('#confirm-order-button').click(function () {
$('#confirm-order-flag').val('');
$('#place_order').trigger('click');
});
``` |
323,408 | <p>I tried:</p>
<pre><code> wp_update_term($personid, 'category', array(
'name' => $_POST['nameChange'],
'slug' => $string,
'_city' => $_POST['newDob'],
));
</code></pre>
<p>Where <code>_city</code> is my category custom field.</p>
<p>This is how I retrieve it:</p>
<pre><code>$fields = get_term_meta( $cat->cat_ID );
$newDob = $fields['_city'][0];
</code></pre>
<p>But I am not sure how to I can change it on front end, these two are working and updating</p>
<pre><code>'name' => $_POST['nameChange'],
'slug' => $string,
</code></pre>
<p>But not '</p>
<pre><code>'_city' => $_POST['newDob'],
</code></pre>
<p><a href="https://codex.wordpress.org/Function_Reference/wp_update_term" rel="nofollow noreferrer">I followed the docs</a></p>
| [
{
"answer_id": 323425,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into this a few times, I have yet to find a straight forward method of handling it. But here is what I've done in the past.</p>\n\n<p>You can trigger checkout validation easily by forcing a click on the submit button.</p>\n\n<pre><code> $('#myButton').on('click', function(){\n $('#place_order').click();\n });\n</code></pre>\n\n<p>However, this isn't really useful for you because it will just submit the order if there are no errors.</p>\n\n<p>There is also the checkout_error callback, but it only fires if there is a error. </p>\n\n<pre><code> $(document.body).on('checkout_error', function () {\n // There was a validation error\n });\n</code></pre>\n\n<p>Here is what we need to do.</p>\n\n<ul>\n<li>Detect when the submit button is clicked</li>\n<li>Check for errors</li>\n<li>If there are errors let Woo handle them as normal</li>\n<li>If there are No errors, stop the order from completing</li>\n<li>Show your iframe</li>\n<li>... Re-Validate / Re-submit Order</li>\n</ul>\n\n<hr>\n\n<hr>\n\n<p>As soon as the submit button is clicked, we can add a hidden field and set the value to 1. We can detect the submit event by using checkout_place_order. This should go in your JS file.</p>\n\n<pre><code>var checkout_form = $('form.woocommerce-checkout');\n\ncheckout_form.on('checkout_place_order', function () {\n if ($('#confirm-order-flag').length == 0) {\n checkout_form.append('<input type=\"hidden\" id=\"confirm-order-flag\" name=\"confirm-order-flag\" value=\"1\">');\n }\n return true;\n});\n</code></pre>\n\n<p>Now, add a function to functions.php that will check that hidden input and stop the order if the value == 1. It stops the order by adding an error.</p>\n\n<pre><code>function add_fake_error($posted) {\n if ($_POST['confirm-order-flag'] == \"1\") {\n wc_add_notice( __( \"custom_notice\", 'fake_error' ), 'error');\n } \n}\n\nadd_action('woocommerce_after_checkout_validation', 'add_fake_error');\n</code></pre>\n\n<p>Back in our JS file, we can use the checkout_error callback, if it has 1 error we know it was the fake error we created so we can show the iframe. If it has more than 1 error it means there are other real errors on the page.</p>\n\n<pre><code>$(document.body).on('checkout_error', function () {\n var error_count = $('.woocommerce-error li').length;\n\n if (error_count == 1) { // Validation Passed (Just the Fake Error Exists)\n // Show iFrame\n }else{ // Validation Failed (Real Errors Exists, Remove the Fake One)\n $('.woocommerce-error li').each(function(){\n var error_text = $(this).text();\n if (error_text == 'custom_notice'){\n $(this).css('display', 'none');\n }\n });\n }\n});\n</code></pre>\n\n<p>In the commented out section, // Show iFrame, I would probably open in it in a lightbox. At some point you will need another submit button that triggers the form submit and set the hidden input.</p>\n\n<pre><code>$('#confirm-order-button').click(function () {\n $('#confirm-order-flag').val('');\n $('#place_order').trigger('click');\n});\n</code></pre>\n"
},
{
"answer_id": 357940,
"author": "Zak the Gear",
"author_id": 155300,
"author_profile": "https://wordpress.stackexchange.com/users/155300",
"pm_score": 0,
"selected": false,
"text": "<p>I got a fast and simple JS decision for myself in this case (there were woocommerce and stripe forms). That is based on preventing the checkout button from submit but still makes forms verifications.</p>\n\n<pre><code>// making the wrap click event on dinamic element\n\n$('body').on('click', 'button#place_order_wrap', function(event) { \n\n // main interval where all things will be \n\n var validatoins = setInterval(function(){ happen\n\n // checking for errors\n\n if(no_errors==0){ \n\n // making the setTimeout() function with limited time like 200ms \n // to limit checkout function for just make verification\n\n setTimeout(function(){ \n\n // triggering original button\n\n $('button#place_order').click(); \n\n // if there some errors, stop the interval, return false\n\n if(($('element').find('ul.woocommerce_error').length!==0)||($('element').find('.woocommerce-invalid-required-field').length!==0)){ \n\n clearInterval(validatoins);\n return false;\n\n }else{\n\n no_errors=1;\n\n }\n }, 200);\n }\n\n\n if(no_errors==1){ \n\n // same error checking\n\n if($('#step5').find('ul.woocommerce_error').length!=0||($('#step5').find('.woocommerce-invalid-required-field').length!==0)){ \n\n // if there some errors, stop the interval, return false\n\n clearInterval(validatoins);\n return false; \n }\n\n\n setTimeout(function(){\n\n // if no errors\n\n if(($('#step5').find('ul.woocommerce_error').length==0)&&($('#step5').find('.woocommerce-invalid-required-field').length==0)){ \n\n // do something, mark that finished\n\n return false;\n }\n }, 1000);\n\n\n // if something finished\n\n if() {\n\n setTimeout(function(){\n\n // trigger original checkout click\n\n $('button#place_order').click(); \n clearInterval(validatoins);\n }, 1000);\n\n }\n\n }\n\n }, 1000);\n}\n</code></pre>\n"
}
]
| 2018/12/19 | [
"https://wordpress.stackexchange.com/questions/323408",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26593/"
]
| I tried:
```
wp_update_term($personid, 'category', array(
'name' => $_POST['nameChange'],
'slug' => $string,
'_city' => $_POST['newDob'],
));
```
Where `_city` is my category custom field.
This is how I retrieve it:
```
$fields = get_term_meta( $cat->cat_ID );
$newDob = $fields['_city'][0];
```
But I am not sure how to I can change it on front end, these two are working and updating
```
'name' => $_POST['nameChange'],
'slug' => $string,
```
But not '
```
'_city' => $_POST['newDob'],
```
[I followed the docs](https://codex.wordpress.org/Function_Reference/wp_update_term) | I ran into this a few times, I have yet to find a straight forward method of handling it. But here is what I've done in the past.
You can trigger checkout validation easily by forcing a click on the submit button.
```
$('#myButton').on('click', function(){
$('#place_order').click();
});
```
However, this isn't really useful for you because it will just submit the order if there are no errors.
There is also the checkout\_error callback, but it only fires if there is a error.
```
$(document.body).on('checkout_error', function () {
// There was a validation error
});
```
Here is what we need to do.
* Detect when the submit button is clicked
* Check for errors
* If there are errors let Woo handle them as normal
* If there are No errors, stop the order from completing
* Show your iframe
* ... Re-Validate / Re-submit Order
---
---
As soon as the submit button is clicked, we can add a hidden field and set the value to 1. We can detect the submit event by using checkout\_place\_order. This should go in your JS file.
```
var checkout_form = $('form.woocommerce-checkout');
checkout_form.on('checkout_place_order', function () {
if ($('#confirm-order-flag').length == 0) {
checkout_form.append('<input type="hidden" id="confirm-order-flag" name="confirm-order-flag" value="1">');
}
return true;
});
```
Now, add a function to functions.php that will check that hidden input and stop the order if the value == 1. It stops the order by adding an error.
```
function add_fake_error($posted) {
if ($_POST['confirm-order-flag'] == "1") {
wc_add_notice( __( "custom_notice", 'fake_error' ), 'error');
}
}
add_action('woocommerce_after_checkout_validation', 'add_fake_error');
```
Back in our JS file, we can use the checkout\_error callback, if it has 1 error we know it was the fake error we created so we can show the iframe. If it has more than 1 error it means there are other real errors on the page.
```
$(document.body).on('checkout_error', function () {
var error_count = $('.woocommerce-error li').length;
if (error_count == 1) { // Validation Passed (Just the Fake Error Exists)
// Show iFrame
}else{ // Validation Failed (Real Errors Exists, Remove the Fake One)
$('.woocommerce-error li').each(function(){
var error_text = $(this).text();
if (error_text == 'custom_notice'){
$(this).css('display', 'none');
}
});
}
});
```
In the commented out section, // Show iFrame, I would probably open in it in a lightbox. At some point you will need another submit button that triggers the form submit and set the hidden input.
```
$('#confirm-order-button').click(function () {
$('#confirm-order-flag').val('');
$('#place_order').trigger('click');
});
``` |
323,436 | <p>Here is my code</p>
<pre><code>function cron_add_weekly( $schedules ) {
$schedules['seconds'] = array(
'interval' => 5,
'display' => __( '5 Seconds' )
);
return $schedules;
}
add_filter( 'cron_schedules', 'cron_add_weekly' );
register_activation_hook(__FILE__, 'my_activation');
function my_activation() {
if ( ! wp_next_scheduled( 'my_hook' ) ) {
wp_schedule_event( time(), 'seconds', 'my_hook' );
}
}
add_action( 'my_hook', 'my_exec' );
register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
wp_clear_scheduled_hook('my_hook');
}
function my_exec() {
$value = 91;
update_user_meta($value + 1, 'from_cron', 'updated');
}
</code></pre>
<p>The user meta ought to be updated every 5 seconds after refreshing the page. But the cron runs only the first time</p>
| [
{
"answer_id": 323440,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming your code above is correct (I didn't test it) it is important to note that wp-cron will only run when someone visits the site, so it will not run every 5 seconds in the background, like you might be thinking.</p>\n\n<p>As a work around you can disable wp-cron and then implement a real cron job.</p>\n\n<p>Here is a <a href=\"https://www.lucasrolff.com/wordpress/why-wp-cron-sucks/\" rel=\"nofollow noreferrer\">good article</a> on this topic.</p>\n\n<p>EDIT: Try adding it like this</p>\n\n<pre><code>function cron_every_5_seconds( $schedules ) {\n $schedules['every_5_seconds'] = array(\n 'interval' => 5,\n 'display' => __( 'Every 5 Seconds', 'textdomain' )\n );\n return $schedules;\n}\n\nadd_filter('cron_schedules', 'cron_every_5_seconds');\n\nif (! wp_next_scheduled( 'cron_every_5_seconds')) {\n wp_schedule_event(time(), 'every_5_seconds', 'cron_every_5_seconds');\n}\n\nadd_action('cron_every_5_seconds', 'cron_every_5_seconds_action');\n function cron_every_5_seconds_action() {\n $value = 91;\n update_user_meta($value + 1, 'from_cron', 'updated');\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 323445,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": true,
"text": "<p>OK, so I've tested your code and I'm pretty sure it can't run even once... And here's why...</p>\n\n<p>If you'll take a look at <a href=\"https://core.trac.wordpress.org/browser/tags/5.0/src/wp-includes/cron.php#L97\" rel=\"nofollow noreferrer\"><code>wp_schedule_event</code></a> you'll see this check at the top of the function:</p>\n\n<pre><code>if ( !isset( $schedules[$recurrence] ) )\n return false;\n</code></pre>\n\n<p>It means that you can't schedule event with unknown recurrence. </p>\n\n<p>So let's go back to your code... What it does is:</p>\n\n<ul>\n<li>adds your custom recurrence (using <code>cron_schedules</code> hook),</li>\n<li>schedules an event with that recurrence during plugin activation.</li>\n</ul>\n\n<p>Everything look good, right? Well, no - it does not.</p>\n\n<p>Activation hook is fired during plugin activation. So that plugin is not working before the activation is run. So your custom recurrence is not registered. So... your hook is not scheduled. I've tested that and the result of <code>wp_schedule_event</code> in your activation hook is false, so the event is not scheduled.</p>\n\n<h2>So what to do?</h2>\n\n<p>Simple - don't schedule your event on activation hook, if you want to use custom recurrence.</p>\n\n<p>So here's your safer code:</p>\n\n<pre><code>register_deactivation_hook(__FILE__, 'my_deactivation');\nfunction my_deactivation() {\n wp_clear_scheduled_hook('cron_every_5_seconds');\n}\n\nfunction add_every_5_seconds_cron_schedule( $schedules ) {\n $schedules['every_5_seconds'] = array(\n 'interval' => 5,\n 'display' => __( 'Every 5 Seconds', 'textdomain' )\n );\n return $schedules;\n}\nadd_filter( 'cron_schedules', 'add_every_5_seconds_cron_schedule' );\n\nfunction schedule_my_cron_events() {\n if ( ! wp_next_scheduled( 'cron_every_5_seconds') ) {\n wp_schedule_event( time(), 'every_5_seconds', 'cron_every_5_seconds' );\n }\n}\nadd_action( 'init', 'schedule_my_cron_events' );\n\nfunction cron_every_5_seconds_action() {\n $value = 91;\n update_user_meta( $value + 1, 'from_cron', 'updated' );\n}\nadd_action( 'cron_every_5_seconds', 'cron_every_5_seconds_action' );\n</code></pre>\n\n<p>PS. <strong>(but it may be important)</strong> There is one more flaw with your code, but maybe it's just cause by some edits before posting here...</p>\n\n<p>You won't be able to check if your cron runs only once or many times. Your event action updates user meta. But the new value that is set is always equal 91. And since you use <code>update_user_meta</code>, only one such meta will be stored in the DB. </p>\n"
}
]
| 2018/12/19 | [
"https://wordpress.stackexchange.com/questions/323436",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157336/"
]
| Here is my code
```
function cron_add_weekly( $schedules ) {
$schedules['seconds'] = array(
'interval' => 5,
'display' => __( '5 Seconds' )
);
return $schedules;
}
add_filter( 'cron_schedules', 'cron_add_weekly' );
register_activation_hook(__FILE__, 'my_activation');
function my_activation() {
if ( ! wp_next_scheduled( 'my_hook' ) ) {
wp_schedule_event( time(), 'seconds', 'my_hook' );
}
}
add_action( 'my_hook', 'my_exec' );
register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
wp_clear_scheduled_hook('my_hook');
}
function my_exec() {
$value = 91;
update_user_meta($value + 1, 'from_cron', 'updated');
}
```
The user meta ought to be updated every 5 seconds after refreshing the page. But the cron runs only the first time | OK, so I've tested your code and I'm pretty sure it can't run even once... And here's why...
If you'll take a look at [`wp_schedule_event`](https://core.trac.wordpress.org/browser/tags/5.0/src/wp-includes/cron.php#L97) you'll see this check at the top of the function:
```
if ( !isset( $schedules[$recurrence] ) )
return false;
```
It means that you can't schedule event with unknown recurrence.
So let's go back to your code... What it does is:
* adds your custom recurrence (using `cron_schedules` hook),
* schedules an event with that recurrence during plugin activation.
Everything look good, right? Well, no - it does not.
Activation hook is fired during plugin activation. So that plugin is not working before the activation is run. So your custom recurrence is not registered. So... your hook is not scheduled. I've tested that and the result of `wp_schedule_event` in your activation hook is false, so the event is not scheduled.
So what to do?
--------------
Simple - don't schedule your event on activation hook, if you want to use custom recurrence.
So here's your safer code:
```
register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
wp_clear_scheduled_hook('cron_every_5_seconds');
}
function add_every_5_seconds_cron_schedule( $schedules ) {
$schedules['every_5_seconds'] = array(
'interval' => 5,
'display' => __( 'Every 5 Seconds', 'textdomain' )
);
return $schedules;
}
add_filter( 'cron_schedules', 'add_every_5_seconds_cron_schedule' );
function schedule_my_cron_events() {
if ( ! wp_next_scheduled( 'cron_every_5_seconds') ) {
wp_schedule_event( time(), 'every_5_seconds', 'cron_every_5_seconds' );
}
}
add_action( 'init', 'schedule_my_cron_events' );
function cron_every_5_seconds_action() {
$value = 91;
update_user_meta( $value + 1, 'from_cron', 'updated' );
}
add_action( 'cron_every_5_seconds', 'cron_every_5_seconds_action' );
```
PS. **(but it may be important)** There is one more flaw with your code, but maybe it's just cause by some edits before posting here...
You won't be able to check if your cron runs only once or many times. Your event action updates user meta. But the new value that is set is always equal 91. And since you use `update_user_meta`, only one such meta will be stored in the DB. |
323,439 | <p>HOW do you Redirect buddypress login to EDIT tab not PROFILE tab on profile page?</p>
| [
{
"answer_id": 323440,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming your code above is correct (I didn't test it) it is important to note that wp-cron will only run when someone visits the site, so it will not run every 5 seconds in the background, like you might be thinking.</p>\n\n<p>As a work around you can disable wp-cron and then implement a real cron job.</p>\n\n<p>Here is a <a href=\"https://www.lucasrolff.com/wordpress/why-wp-cron-sucks/\" rel=\"nofollow noreferrer\">good article</a> on this topic.</p>\n\n<p>EDIT: Try adding it like this</p>\n\n<pre><code>function cron_every_5_seconds( $schedules ) {\n $schedules['every_5_seconds'] = array(\n 'interval' => 5,\n 'display' => __( 'Every 5 Seconds', 'textdomain' )\n );\n return $schedules;\n}\n\nadd_filter('cron_schedules', 'cron_every_5_seconds');\n\nif (! wp_next_scheduled( 'cron_every_5_seconds')) {\n wp_schedule_event(time(), 'every_5_seconds', 'cron_every_5_seconds');\n}\n\nadd_action('cron_every_5_seconds', 'cron_every_5_seconds_action');\n function cron_every_5_seconds_action() {\n $value = 91;\n update_user_meta($value + 1, 'from_cron', 'updated');\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 323445,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": true,
"text": "<p>OK, so I've tested your code and I'm pretty sure it can't run even once... And here's why...</p>\n\n<p>If you'll take a look at <a href=\"https://core.trac.wordpress.org/browser/tags/5.0/src/wp-includes/cron.php#L97\" rel=\"nofollow noreferrer\"><code>wp_schedule_event</code></a> you'll see this check at the top of the function:</p>\n\n<pre><code>if ( !isset( $schedules[$recurrence] ) )\n return false;\n</code></pre>\n\n<p>It means that you can't schedule event with unknown recurrence. </p>\n\n<p>So let's go back to your code... What it does is:</p>\n\n<ul>\n<li>adds your custom recurrence (using <code>cron_schedules</code> hook),</li>\n<li>schedules an event with that recurrence during plugin activation.</li>\n</ul>\n\n<p>Everything look good, right? Well, no - it does not.</p>\n\n<p>Activation hook is fired during plugin activation. So that plugin is not working before the activation is run. So your custom recurrence is not registered. So... your hook is not scheduled. I've tested that and the result of <code>wp_schedule_event</code> in your activation hook is false, so the event is not scheduled.</p>\n\n<h2>So what to do?</h2>\n\n<p>Simple - don't schedule your event on activation hook, if you want to use custom recurrence.</p>\n\n<p>So here's your safer code:</p>\n\n<pre><code>register_deactivation_hook(__FILE__, 'my_deactivation');\nfunction my_deactivation() {\n wp_clear_scheduled_hook('cron_every_5_seconds');\n}\n\nfunction add_every_5_seconds_cron_schedule( $schedules ) {\n $schedules['every_5_seconds'] = array(\n 'interval' => 5,\n 'display' => __( 'Every 5 Seconds', 'textdomain' )\n );\n return $schedules;\n}\nadd_filter( 'cron_schedules', 'add_every_5_seconds_cron_schedule' );\n\nfunction schedule_my_cron_events() {\n if ( ! wp_next_scheduled( 'cron_every_5_seconds') ) {\n wp_schedule_event( time(), 'every_5_seconds', 'cron_every_5_seconds' );\n }\n}\nadd_action( 'init', 'schedule_my_cron_events' );\n\nfunction cron_every_5_seconds_action() {\n $value = 91;\n update_user_meta( $value + 1, 'from_cron', 'updated' );\n}\nadd_action( 'cron_every_5_seconds', 'cron_every_5_seconds_action' );\n</code></pre>\n\n<p>PS. <strong>(but it may be important)</strong> There is one more flaw with your code, but maybe it's just cause by some edits before posting here...</p>\n\n<p>You won't be able to check if your cron runs only once or many times. Your event action updates user meta. But the new value that is set is always equal 91. And since you use <code>update_user_meta</code>, only one such meta will be stored in the DB. </p>\n"
}
]
| 2018/12/19 | [
"https://wordpress.stackexchange.com/questions/323439",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138327/"
]
| HOW do you Redirect buddypress login to EDIT tab not PROFILE tab on profile page? | OK, so I've tested your code and I'm pretty sure it can't run even once... And here's why...
If you'll take a look at [`wp_schedule_event`](https://core.trac.wordpress.org/browser/tags/5.0/src/wp-includes/cron.php#L97) you'll see this check at the top of the function:
```
if ( !isset( $schedules[$recurrence] ) )
return false;
```
It means that you can't schedule event with unknown recurrence.
So let's go back to your code... What it does is:
* adds your custom recurrence (using `cron_schedules` hook),
* schedules an event with that recurrence during plugin activation.
Everything look good, right? Well, no - it does not.
Activation hook is fired during plugin activation. So that plugin is not working before the activation is run. So your custom recurrence is not registered. So... your hook is not scheduled. I've tested that and the result of `wp_schedule_event` in your activation hook is false, so the event is not scheduled.
So what to do?
--------------
Simple - don't schedule your event on activation hook, if you want to use custom recurrence.
So here's your safer code:
```
register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
wp_clear_scheduled_hook('cron_every_5_seconds');
}
function add_every_5_seconds_cron_schedule( $schedules ) {
$schedules['every_5_seconds'] = array(
'interval' => 5,
'display' => __( 'Every 5 Seconds', 'textdomain' )
);
return $schedules;
}
add_filter( 'cron_schedules', 'add_every_5_seconds_cron_schedule' );
function schedule_my_cron_events() {
if ( ! wp_next_scheduled( 'cron_every_5_seconds') ) {
wp_schedule_event( time(), 'every_5_seconds', 'cron_every_5_seconds' );
}
}
add_action( 'init', 'schedule_my_cron_events' );
function cron_every_5_seconds_action() {
$value = 91;
update_user_meta( $value + 1, 'from_cron', 'updated' );
}
add_action( 'cron_every_5_seconds', 'cron_every_5_seconds_action' );
```
PS. **(but it may be important)** There is one more flaw with your code, but maybe it's just cause by some edits before posting here...
You won't be able to check if your cron runs only once or many times. Your event action updates user meta. But the new value that is set is always equal 91. And since you use `update_user_meta`, only one such meta will be stored in the DB. |
323,494 | <p>I'm trying to enqueue a JS file (located at /js/example-script.js), just to get an alert on page load.</p>
<p>Can anyone tell me what I'm doing wrong?</p>
<p>In my example-script.js:</p>
<pre><code>jQuery(document).ready(function($) {
alert("hi");
});
</code></pre>
<p>And in my functions file:</p>
<pre><code>function my_theme_scripts() {
wp_enqueue_script( 'example-script', get_template_directory_uri() . '/js/example-script.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
</code></pre>
<p>jQuery is loaded in my sources, so that's not the problem...</p>
| [
{
"answer_id": 323515,
"author": "CRavon",
"author_id": 122086,
"author_profile": "https://wordpress.stackexchange.com/users/122086",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using a child theme ? In this case you have to use <code>get_stylesheet_directory_uri()</code> instead of <code>get_stylesheet_template_uri()</code>which returns the parent theme uri\n<a href=\"https://developer.wordpress.org/reference/functions/get_template_directory/#usage\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_template_directory/#usage</a></p>\n"
},
{
"answer_id": 323552,
"author": "Remzi Cavdar",
"author_id": 149484,
"author_profile": "https://wordpress.stackexchange.com/users/149484",
"pm_score": 1,
"selected": false,
"text": "<h2>Example for themes</h2>\n\n<p>I would recommend using <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a> with <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"nofollow noreferrer\">get_theme_file_uri</a> this allows child themes to overwrite this file.</p>\n\n<blockquote>\n <h2>get_theme_file_uri() function</h2>\n \n <p>Searches in the stylesheet directory before the template directory so\n themes which inherit from a parent theme can just override one file.</p>\n</blockquote>\n\n<pre><code>wp_enqueue_script( 'example-script', get_theme_file_uri( '/js/example-script.js' ), array('jquery'), null, true );\n</code></pre>\n\n<p><br></p>\n\n<h2>Example for plugins</h2>\n\n<pre><code>wp_enqueue_script( 'example-script', plugins_url('/js/example-script.js', __FILE__), array(), null );\n</code></pre>\n"
},
{
"answer_id": 323591,
"author": "JohnG",
"author_id": 121694,
"author_profile": "https://wordpress.stackexchange.com/users/121694",
"pm_score": 0,
"selected": false,
"text": "<p>All answers correct - in my case I'd done it right, just wasn't loading the WP Footer, despite jQuery showing in my sources. As soon as I added in get_footer(), all worked fine.</p>\n"
}
]
| 2018/12/20 | [
"https://wordpress.stackexchange.com/questions/323494",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121694/"
]
| I'm trying to enqueue a JS file (located at /js/example-script.js), just to get an alert on page load.
Can anyone tell me what I'm doing wrong?
In my example-script.js:
```
jQuery(document).ready(function($) {
alert("hi");
});
```
And in my functions file:
```
function my_theme_scripts() {
wp_enqueue_script( 'example-script', get_template_directory_uri() . '/js/example-script.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
```
jQuery is loaded in my sources, so that's not the problem... | Are you using a child theme ? In this case you have to use `get_stylesheet_directory_uri()` instead of `get_stylesheet_template_uri()`which returns the parent theme uri
<https://developer.wordpress.org/reference/functions/get_template_directory/#usage> |
323,506 | <p>I am trying to allow gedcom file uploads. These files have a .ged extension.</p>
<p>Gedcom files do not have a mime type. </p>
<p>I have tried the following code with various text/types such as csv, rtf etc without success.</p>
<pre><code> function my_mime_types($mime_types){
$mime_types['ged'] = 'text/csv';
return $mime_types;}
add_filter('upload_mimes', 'my_mime_types', 1, 1);
</code></pre>
<p>Any suggestions as to how to add this type of file extension to the permitted uploads?</p>
| [
{
"answer_id": 323522,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": -1,
"selected": false,
"text": "<p>I think that there is a conflict between your theme and another plugin. In other words, there are two parts of code that give conflicting signals. Try the following steps:</p>\n\n<ol>\n<li>Switch to a default WordPress theme.</li>\n<li>Temporarily deactivate all plugins except WooCommerce and the\nWooCommerce extensions</li>\n<li>Reactivate the plugins one by one and detect the defective ones.</li>\n</ol>\n\n<p>You can find more information about the steps <a href=\"https://docs.woocommerce.com/document/how-to-test-for-conflicts/\" rel=\"nofollow noreferrer\">here</a>. </p>\n"
},
{
"answer_id": 323533,
"author": "Yordan Kostadinov",
"author_id": 87650,
"author_profile": "https://wordpress.stackexchange.com/users/87650",
"pm_score": -1,
"selected": false,
"text": "<p>You can enable debugging in your wp-config.php file.</p>\n\n<p>Add this:</p>\n\n<pre><code>define('WP_DEBUG', true);\ndefine('WP_DEBUG_LOG', true);\ndefine('WP_DEBUG_DISPLAY', false);\n</code></pre>\n\n<p>It enables debugging and will log any problems in a file \"debug.log\"</p>\n"
},
{
"answer_id": 323534,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": false,
"text": "<p>This is a know issue with WP Update 5.02.</p>\n\n<p>View the topic <a href=\"https://github.com/woocommerce/woocommerce/issues/22271\" rel=\"nofollow noreferrer\">HERE</a>.</p>\n\n<p>And the fix <a href=\"https://github.com/woocommerce/woocommerce/pull/22273\" rel=\"nofollow noreferrer\">HERE</a>.</p>\n"
},
{
"answer_id": 323536,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>This was an issue with a change in WordPress 5.0.2. The issue has been fixed in WooCommerce 3.5.3, which was just released: <a href=\"https://woocommerce.wordpress.com/2018/12/20/woocommerce-3-5-3-release-notes/\" rel=\"nofollow noreferrer\">https://woocommerce.wordpress.com/2018/12/20/woocommerce-3-5-3-release-notes/</a></p>\n"
},
{
"answer_id": 364943,
"author": "Montassar Billeh Hazgui",
"author_id": 104567,
"author_profile": "https://wordpress.stackexchange.com/users/104567",
"pm_score": 0,
"selected": false,
"text": "<p>If the issues persist after this type of test, then try updating the database by adding this link below after your site domain name.</p>\n\n<pre><code>/wp-admin/admin.php?page=wc-settings&do_update_woocommerce=true\n</code></pre>\n"
}
]
| 2018/12/20 | [
"https://wordpress.stackexchange.com/questions/323506",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36113/"
]
| I am trying to allow gedcom file uploads. These files have a .ged extension.
Gedcom files do not have a mime type.
I have tried the following code with various text/types such as csv, rtf etc without success.
```
function my_mime_types($mime_types){
$mime_types['ged'] = 'text/csv';
return $mime_types;}
add_filter('upload_mimes', 'my_mime_types', 1, 1);
```
Any suggestions as to how to add this type of file extension to the permitted uploads? | This is a know issue with WP Update 5.02.
View the topic [HERE](https://github.com/woocommerce/woocommerce/issues/22271).
And the fix [HERE](https://github.com/woocommerce/woocommerce/pull/22273). |
323,539 | <p>I'm trying to load external content into an iframe, & it is working in Chrome & Firefox, but it won't load in Safari. In Safari I get the error message:</p>
<blockquote>
<p>Refused to display 'my_content' in a frame because it set
'X-Frame-Options' to 'sameorigin'</p>
</blockquote>
<p>I think the issue may be that my WordPress install is in a subdirectory:</p>
<ul>
<li><p>WordPress Address (URL): <a href="https://example.com/wp" rel="nofollow noreferrer">https://example.com/wp</a></p></li>
<li><p>Site Address (URL): <a href="https://example.com" rel="nofollow noreferrer">https://example.com</a></p></li>
</ul>
<p>The header for my external content includes the following:</p>
<pre><code> X-Frame-Options: sameorigin
Content-Security-Policy: frame-ancestors 'self' https://example.com
X-Content-Security-Policy: frame-ancestors 'self' https://example.com
</code></pre>
<p>This article lists a number of possible reasons for the issue with Safari & SAMEORIGIN <a href="https://halfelf.org/2018/safari-and-sameorigin/" rel="nofollow noreferrer">https://halfelf.org/2018/safari-and-sameorigin/</a>. I don't have any extra X-Frame-Options in my .htaccess file, so I'm wondering if the issue is related to my WordPress install being located in a subdirectory. Is there a workaround for this? Or is this caused by something else?</p>
| [
{
"answer_id": 323522,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": -1,
"selected": false,
"text": "<p>I think that there is a conflict between your theme and another plugin. In other words, there are two parts of code that give conflicting signals. Try the following steps:</p>\n\n<ol>\n<li>Switch to a default WordPress theme.</li>\n<li>Temporarily deactivate all plugins except WooCommerce and the\nWooCommerce extensions</li>\n<li>Reactivate the plugins one by one and detect the defective ones.</li>\n</ol>\n\n<p>You can find more information about the steps <a href=\"https://docs.woocommerce.com/document/how-to-test-for-conflicts/\" rel=\"nofollow noreferrer\">here</a>. </p>\n"
},
{
"answer_id": 323533,
"author": "Yordan Kostadinov",
"author_id": 87650,
"author_profile": "https://wordpress.stackexchange.com/users/87650",
"pm_score": -1,
"selected": false,
"text": "<p>You can enable debugging in your wp-config.php file.</p>\n\n<p>Add this:</p>\n\n<pre><code>define('WP_DEBUG', true);\ndefine('WP_DEBUG_LOG', true);\ndefine('WP_DEBUG_DISPLAY', false);\n</code></pre>\n\n<p>It enables debugging and will log any problems in a file \"debug.log\"</p>\n"
},
{
"answer_id": 323534,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": false,
"text": "<p>This is a know issue with WP Update 5.02.</p>\n\n<p>View the topic <a href=\"https://github.com/woocommerce/woocommerce/issues/22271\" rel=\"nofollow noreferrer\">HERE</a>.</p>\n\n<p>And the fix <a href=\"https://github.com/woocommerce/woocommerce/pull/22273\" rel=\"nofollow noreferrer\">HERE</a>.</p>\n"
},
{
"answer_id": 323536,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>This was an issue with a change in WordPress 5.0.2. The issue has been fixed in WooCommerce 3.5.3, which was just released: <a href=\"https://woocommerce.wordpress.com/2018/12/20/woocommerce-3-5-3-release-notes/\" rel=\"nofollow noreferrer\">https://woocommerce.wordpress.com/2018/12/20/woocommerce-3-5-3-release-notes/</a></p>\n"
},
{
"answer_id": 364943,
"author": "Montassar Billeh Hazgui",
"author_id": 104567,
"author_profile": "https://wordpress.stackexchange.com/users/104567",
"pm_score": 0,
"selected": false,
"text": "<p>If the issues persist after this type of test, then try updating the database by adding this link below after your site domain name.</p>\n\n<pre><code>/wp-admin/admin.php?page=wc-settings&do_update_woocommerce=true\n</code></pre>\n"
}
]
| 2018/12/20 | [
"https://wordpress.stackexchange.com/questions/323539",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73347/"
]
| I'm trying to load external content into an iframe, & it is working in Chrome & Firefox, but it won't load in Safari. In Safari I get the error message:
>
> Refused to display 'my\_content' in a frame because it set
> 'X-Frame-Options' to 'sameorigin'
>
>
>
I think the issue may be that my WordPress install is in a subdirectory:
* WordPress Address (URL): <https://example.com/wp>
* Site Address (URL): <https://example.com>
The header for my external content includes the following:
```
X-Frame-Options: sameorigin
Content-Security-Policy: frame-ancestors 'self' https://example.com
X-Content-Security-Policy: frame-ancestors 'self' https://example.com
```
This article lists a number of possible reasons for the issue with Safari & SAMEORIGIN <https://halfelf.org/2018/safari-and-sameorigin/>. I don't have any extra X-Frame-Options in my .htaccess file, so I'm wondering if the issue is related to my WordPress install being located in a subdirectory. Is there a workaround for this? Or is this caused by something else? | This is a know issue with WP Update 5.02.
View the topic [HERE](https://github.com/woocommerce/woocommerce/issues/22271).
And the fix [HERE](https://github.com/woocommerce/woocommerce/pull/22273). |
323,562 | <p>This theme I was handed from another dev company is littered with <code>add_action/filter( 'hook/filter', create_function( '', 'return blah('blah')' );</code> We will be moving this site to a server running <code>php 7.2</code>.</p>
<p>I am wondering what's the appropriate method to remove these actions and filters. Or can I simply just copy and paste the /path/to/file in the child directory and know that this will be overwritten?</p>
<h3>Here's an example</h3>
<pre><code>if ( ! function_exists( 'ot_register_theme_options_page' ) ) {
function ot_register_theme_options_page() {
/* get the settings array */
$get_settings = _ut_theme_options();
/* sections array */
$sections = isset( $get_settings['sections'] ) ? $get_settings['sections'] : [];
/* settings array */
$settings = isset( $get_settings['settings'] ) ? $get_settings['settings'] : [];
/* build the Theme Options */
if ( function_exists( 'ot_register_settings' ) && OT_USE_THEME_OPTIONS ) {
ot_register_settings(
[
[
'id' => 'option_tree',
'pages' => [
[
'id' => 'ot_theme_options',
'parent_slug' => apply_filters( 'ot_theme_options_parent_slug', 'unite-welcome-page' ),
'page_title' => apply_filters( 'ot_theme_options_page_title', __( 'Theme Options', 'option-tree' ) ),
'menu_title' => apply_filters( 'ot_theme_options_menu_title', __( 'Theme Options', 'option-tree' ) ),
'capability' => $caps = apply_filters( 'ot_theme_options_capability', 'edit_theme_options' ),
'menu_slug' => apply_filters( 'ot_theme_options_menu_slug', 'ut_theme_options' ),
'icon_url' => apply_filters( 'ot_theme_options_icon_url', null ),
'position' => apply_filters( 'ot_theme_options_position', null ),
'updated_message' => apply_filters( 'ot_theme_options_updated_message', __( 'Theme Options updated.', 'option-tree' ) ),
'reset_message' => apply_filters( 'ot_theme_options_reset_message', __( 'Theme Options reset.', 'option-tree' ) ),
'button_text' => apply_filters( 'ot_theme_options_button_text', __( 'Save Changes', 'option-tree' ) ),
'screen_icon' => 'themes',
'sections' => $sections,
'settings' => $settings,
],
],
],
]
);
// Filters the options.php to add the minimum user capabilities.
add_filter( 'option_page_capability_option_tree', create_function( '$caps', "return '$caps';" ), 999 );
}
}
}
</code></pre>
<p>I'm aware the appropriate <code>add_filter</code> would come out to being <code>add_filter( 'option_page_capability_option_tree', function($caps) { return $caps; }, 999);</code></p>
| [
{
"answer_id": 323564,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>In order to remove the hooks and filters, we need to be able to get a reference to the callable that was added, but in this case, <code>create_function</code> was used, so that's extremely difficult. It's also the reason you're getting deprecation notices. Sadly the only way to fix those deprecations is to change the parent theme to fix it.</p>\n<h3>Fixing The Deprecations</h3>\n<p>The PHP docs say that <code>create_function</code> works like this:</p>\n<blockquote>\n<pre><code>string create_function ( string $args , string $code )\n</code></pre>\n<p>Creates an anonymous function from the parameters passed, and returns a unique name for it.</p>\n</blockquote>\n<p>And of note, <code>create_function</code> is deprecated in PHP 7.2</p>\n<p>So this:</p>\n<pre><code>create_function( '$a', 'return $a + 1;' )\n</code></pre>\n<p>Becomes:</p>\n<pre><code>function( $a ) {\n return $a + 1;\n}\n</code></pre>\n<p>Or even</p>\n<pre><code>function add_one( $a ) {\n return $a + 1;\n}\n</code></pre>\n<p>This should eliminate the <code>create_function</code> calls, and turn the anonymous functions into normal calls that can be removed in a child theme</p>\n<h3>Removing The Hooks and Filters</h3>\n<p>Now that we've done that, we can now remove and replace them in the child theme.</p>\n<p>To do this, we need 2 things:</p>\n<ul>\n<li>to run the removal code <strong>after</strong> they were added</li>\n<li>to be able to unhook the filters/actions</li>\n</ul>\n<p>Putting your replacement in is easy, just use <code>add_filter</code> and <code>add_action</code>, but that adds your version, we need to remove the parent themes version.</p>\n<p>Lets assume that this code is in the parent theme:</p>\n<pre><code>add_filter('wp_add_numbers_together' 'add_one' );\n</code></pre>\n<p>And that we want to replace it with a <code>multiply_by_two</code> function. First lets do this on the <code>init</code> hook:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function nickm_remove_parent_hooks() {\n //\n}\nadd_action('init', 'nickm_remove_parent_hooks' );\n</code></pre>\n<p>Then call <code>remove_filter and </code>add_filter`:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function nickm_remove_parent_hooks() {\n remove_filter( 'wp_add_numbers_together' 'add_one' );\n}\nadd_action( 'init', 'nickm_remove_parent_hooks' );\nadd_action( 'wp_add_numbers_together', 'multiply_by_two' );\n</code></pre>\n<p>Keep in mind that child themes let you override templates, but <code>functions.php</code> is not a template, and child themes don't change how <code>include</code> or <code>require</code> work. A child themes <code>functions.php</code> is loaded first, but otherwise, they're similar to plugins.</p>\n<h3>And Finally</h3>\n<p>You shouldn't be registering post types, roles, capabilities, and taxonomies in a theme, it's a big red flag and creates lock in, preventing data portability. These things are supposed to be in plugins, not themes</p>\n"
},
{
"answer_id": 323615,
"author": "Nick M",
"author_id": 157435,
"author_profile": "https://wordpress.stackexchange.com/users/157435",
"pm_score": 0,
"selected": false,
"text": "<p>So turns out taking the following, and just removing <code>if ( ! function_exists( 'ot_register_theme_options_page' ) ) { }</code> and adjusting the filter will take priority over the parent theme.</p>\n\n<pre><code>if ( ! function_exists( 'ot_register_theme_options_page' ) ) {\n\n function ot_register_theme_options_page() {\n\n /* get the settings array */\n $get_settings = _ut_theme_options();\n\n /* sections array */\n $sections = isset( $get_settings['sections'] ) ? $get_settings['sections'] : [];\n\n /* settings array */\n $settings = isset( $get_settings['settings'] ) ? $get_settings['settings'] : [];\n\n /* build the Theme Options */\n if ( function_exists( 'ot_register_settings' ) && OT_USE_THEME_OPTIONS ) {\n\n ot_register_settings(\n [\n [\n 'id' => 'option_tree',\n 'pages' => [\n [\n 'id' => 'ot_theme_options',\n 'parent_slug' => apply_filters( 'ot_theme_options_parent_slug', 'unite-welcome-page' ),\n 'page_title' => apply_filters( 'ot_theme_options_page_title', __( 'Theme Options', 'option-tree' ) ),\n 'menu_title' => apply_filters( 'ot_theme_options_menu_title', __( 'Theme Options', 'option-tree' ) ),\n 'capability' => $caps = apply_filters( 'ot_theme_options_capability', 'edit_theme_options' ),\n 'menu_slug' => apply_filters( 'ot_theme_options_menu_slug', 'ut_theme_options' ),\n 'icon_url' => apply_filters( 'ot_theme_options_icon_url', null ),\n 'position' => apply_filters( 'ot_theme_options_position', null ),\n 'updated_message' => apply_filters( 'ot_theme_options_updated_message', __( 'Theme Options updated.', 'option-tree' ) ),\n 'reset_message' => apply_filters( 'ot_theme_options_reset_message', __( 'Theme Options reset.', 'option-tree' ) ),\n 'button_text' => apply_filters( 'ot_theme_options_button_text', __( 'Save Changes', 'option-tree' ) ),\n 'screen_icon' => 'themes',\n 'sections' => $sections,\n 'settings' => $settings,\n ],\n ],\n ],\n ]\n );\n\n // Filters the options.php to add the minimum user capabilities.\n add_filter( 'option_page_capability_option_tree', create_function( '$caps', \"return '$caps';\" ), 999 );\n\n }\n\n }\n\n}\n</code></pre>\n"
}
]
| 2018/12/20 | [
"https://wordpress.stackexchange.com/questions/323562",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157435/"
]
| This theme I was handed from another dev company is littered with `add_action/filter( 'hook/filter', create_function( '', 'return blah('blah')' );` We will be moving this site to a server running `php 7.2`.
I am wondering what's the appropriate method to remove these actions and filters. Or can I simply just copy and paste the /path/to/file in the child directory and know that this will be overwritten?
### Here's an example
```
if ( ! function_exists( 'ot_register_theme_options_page' ) ) {
function ot_register_theme_options_page() {
/* get the settings array */
$get_settings = _ut_theme_options();
/* sections array */
$sections = isset( $get_settings['sections'] ) ? $get_settings['sections'] : [];
/* settings array */
$settings = isset( $get_settings['settings'] ) ? $get_settings['settings'] : [];
/* build the Theme Options */
if ( function_exists( 'ot_register_settings' ) && OT_USE_THEME_OPTIONS ) {
ot_register_settings(
[
[
'id' => 'option_tree',
'pages' => [
[
'id' => 'ot_theme_options',
'parent_slug' => apply_filters( 'ot_theme_options_parent_slug', 'unite-welcome-page' ),
'page_title' => apply_filters( 'ot_theme_options_page_title', __( 'Theme Options', 'option-tree' ) ),
'menu_title' => apply_filters( 'ot_theme_options_menu_title', __( 'Theme Options', 'option-tree' ) ),
'capability' => $caps = apply_filters( 'ot_theme_options_capability', 'edit_theme_options' ),
'menu_slug' => apply_filters( 'ot_theme_options_menu_slug', 'ut_theme_options' ),
'icon_url' => apply_filters( 'ot_theme_options_icon_url', null ),
'position' => apply_filters( 'ot_theme_options_position', null ),
'updated_message' => apply_filters( 'ot_theme_options_updated_message', __( 'Theme Options updated.', 'option-tree' ) ),
'reset_message' => apply_filters( 'ot_theme_options_reset_message', __( 'Theme Options reset.', 'option-tree' ) ),
'button_text' => apply_filters( 'ot_theme_options_button_text', __( 'Save Changes', 'option-tree' ) ),
'screen_icon' => 'themes',
'sections' => $sections,
'settings' => $settings,
],
],
],
]
);
// Filters the options.php to add the minimum user capabilities.
add_filter( 'option_page_capability_option_tree', create_function( '$caps', "return '$caps';" ), 999 );
}
}
}
```
I'm aware the appropriate `add_filter` would come out to being `add_filter( 'option_page_capability_option_tree', function($caps) { return $caps; }, 999);` | In order to remove the hooks and filters, we need to be able to get a reference to the callable that was added, but in this case, `create_function` was used, so that's extremely difficult. It's also the reason you're getting deprecation notices. Sadly the only way to fix those deprecations is to change the parent theme to fix it.
### Fixing The Deprecations
The PHP docs say that `create_function` works like this:
>
>
> ```
> string create_function ( string $args , string $code )
>
> ```
>
> Creates an anonymous function from the parameters passed, and returns a unique name for it.
>
>
>
And of note, `create_function` is deprecated in PHP 7.2
So this:
```
create_function( '$a', 'return $a + 1;' )
```
Becomes:
```
function( $a ) {
return $a + 1;
}
```
Or even
```
function add_one( $a ) {
return $a + 1;
}
```
This should eliminate the `create_function` calls, and turn the anonymous functions into normal calls that can be removed in a child theme
### Removing The Hooks and Filters
Now that we've done that, we can now remove and replace them in the child theme.
To do this, we need 2 things:
* to run the removal code **after** they were added
* to be able to unhook the filters/actions
Putting your replacement in is easy, just use `add_filter` and `add_action`, but that adds your version, we need to remove the parent themes version.
Lets assume that this code is in the parent theme:
```
add_filter('wp_add_numbers_together' 'add_one' );
```
And that we want to replace it with a `multiply_by_two` function. First lets do this on the `init` hook:
```php
function nickm_remove_parent_hooks() {
//
}
add_action('init', 'nickm_remove_parent_hooks' );
```
Then call `remove_filter and` add\_filter`:
```php
function nickm_remove_parent_hooks() {
remove_filter( 'wp_add_numbers_together' 'add_one' );
}
add_action( 'init', 'nickm_remove_parent_hooks' );
add_action( 'wp_add_numbers_together', 'multiply_by_two' );
```
Keep in mind that child themes let you override templates, but `functions.php` is not a template, and child themes don't change how `include` or `require` work. A child themes `functions.php` is loaded first, but otherwise, they're similar to plugins.
### And Finally
You shouldn't be registering post types, roles, capabilities, and taxonomies in a theme, it's a big red flag and creates lock in, preventing data portability. These things are supposed to be in plugins, not themes |
323,603 | <p>By default wooCommerce displays price as "Regular price" first and "Sale price" second. I wish to reverse the order for all types (simple,variation,...). Is this possible? How?</p>
<p>Thx</p>
| [
{
"answer_id": 323564,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>In order to remove the hooks and filters, we need to be able to get a reference to the callable that was added, but in this case, <code>create_function</code> was used, so that's extremely difficult. It's also the reason you're getting deprecation notices. Sadly the only way to fix those deprecations is to change the parent theme to fix it.</p>\n<h3>Fixing The Deprecations</h3>\n<p>The PHP docs say that <code>create_function</code> works like this:</p>\n<blockquote>\n<pre><code>string create_function ( string $args , string $code )\n</code></pre>\n<p>Creates an anonymous function from the parameters passed, and returns a unique name for it.</p>\n</blockquote>\n<p>And of note, <code>create_function</code> is deprecated in PHP 7.2</p>\n<p>So this:</p>\n<pre><code>create_function( '$a', 'return $a + 1;' )\n</code></pre>\n<p>Becomes:</p>\n<pre><code>function( $a ) {\n return $a + 1;\n}\n</code></pre>\n<p>Or even</p>\n<pre><code>function add_one( $a ) {\n return $a + 1;\n}\n</code></pre>\n<p>This should eliminate the <code>create_function</code> calls, and turn the anonymous functions into normal calls that can be removed in a child theme</p>\n<h3>Removing The Hooks and Filters</h3>\n<p>Now that we've done that, we can now remove and replace them in the child theme.</p>\n<p>To do this, we need 2 things:</p>\n<ul>\n<li>to run the removal code <strong>after</strong> they were added</li>\n<li>to be able to unhook the filters/actions</li>\n</ul>\n<p>Putting your replacement in is easy, just use <code>add_filter</code> and <code>add_action</code>, but that adds your version, we need to remove the parent themes version.</p>\n<p>Lets assume that this code is in the parent theme:</p>\n<pre><code>add_filter('wp_add_numbers_together' 'add_one' );\n</code></pre>\n<p>And that we want to replace it with a <code>multiply_by_two</code> function. First lets do this on the <code>init</code> hook:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function nickm_remove_parent_hooks() {\n //\n}\nadd_action('init', 'nickm_remove_parent_hooks' );\n</code></pre>\n<p>Then call <code>remove_filter and </code>add_filter`:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function nickm_remove_parent_hooks() {\n remove_filter( 'wp_add_numbers_together' 'add_one' );\n}\nadd_action( 'init', 'nickm_remove_parent_hooks' );\nadd_action( 'wp_add_numbers_together', 'multiply_by_two' );\n</code></pre>\n<p>Keep in mind that child themes let you override templates, but <code>functions.php</code> is not a template, and child themes don't change how <code>include</code> or <code>require</code> work. A child themes <code>functions.php</code> is loaded first, but otherwise, they're similar to plugins.</p>\n<h3>And Finally</h3>\n<p>You shouldn't be registering post types, roles, capabilities, and taxonomies in a theme, it's a big red flag and creates lock in, preventing data portability. These things are supposed to be in plugins, not themes</p>\n"
},
{
"answer_id": 323615,
"author": "Nick M",
"author_id": 157435,
"author_profile": "https://wordpress.stackexchange.com/users/157435",
"pm_score": 0,
"selected": false,
"text": "<p>So turns out taking the following, and just removing <code>if ( ! function_exists( 'ot_register_theme_options_page' ) ) { }</code> and adjusting the filter will take priority over the parent theme.</p>\n\n<pre><code>if ( ! function_exists( 'ot_register_theme_options_page' ) ) {\n\n function ot_register_theme_options_page() {\n\n /* get the settings array */\n $get_settings = _ut_theme_options();\n\n /* sections array */\n $sections = isset( $get_settings['sections'] ) ? $get_settings['sections'] : [];\n\n /* settings array */\n $settings = isset( $get_settings['settings'] ) ? $get_settings['settings'] : [];\n\n /* build the Theme Options */\n if ( function_exists( 'ot_register_settings' ) && OT_USE_THEME_OPTIONS ) {\n\n ot_register_settings(\n [\n [\n 'id' => 'option_tree',\n 'pages' => [\n [\n 'id' => 'ot_theme_options',\n 'parent_slug' => apply_filters( 'ot_theme_options_parent_slug', 'unite-welcome-page' ),\n 'page_title' => apply_filters( 'ot_theme_options_page_title', __( 'Theme Options', 'option-tree' ) ),\n 'menu_title' => apply_filters( 'ot_theme_options_menu_title', __( 'Theme Options', 'option-tree' ) ),\n 'capability' => $caps = apply_filters( 'ot_theme_options_capability', 'edit_theme_options' ),\n 'menu_slug' => apply_filters( 'ot_theme_options_menu_slug', 'ut_theme_options' ),\n 'icon_url' => apply_filters( 'ot_theme_options_icon_url', null ),\n 'position' => apply_filters( 'ot_theme_options_position', null ),\n 'updated_message' => apply_filters( 'ot_theme_options_updated_message', __( 'Theme Options updated.', 'option-tree' ) ),\n 'reset_message' => apply_filters( 'ot_theme_options_reset_message', __( 'Theme Options reset.', 'option-tree' ) ),\n 'button_text' => apply_filters( 'ot_theme_options_button_text', __( 'Save Changes', 'option-tree' ) ),\n 'screen_icon' => 'themes',\n 'sections' => $sections,\n 'settings' => $settings,\n ],\n ],\n ],\n ]\n );\n\n // Filters the options.php to add the minimum user capabilities.\n add_filter( 'option_page_capability_option_tree', create_function( '$caps', \"return '$caps';\" ), 999 );\n\n }\n\n }\n\n}\n</code></pre>\n"
}
]
| 2018/12/21 | [
"https://wordpress.stackexchange.com/questions/323603",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28159/"
]
| By default wooCommerce displays price as "Regular price" first and "Sale price" second. I wish to reverse the order for all types (simple,variation,...). Is this possible? How?
Thx | In order to remove the hooks and filters, we need to be able to get a reference to the callable that was added, but in this case, `create_function` was used, so that's extremely difficult. It's also the reason you're getting deprecation notices. Sadly the only way to fix those deprecations is to change the parent theme to fix it.
### Fixing The Deprecations
The PHP docs say that `create_function` works like this:
>
>
> ```
> string create_function ( string $args , string $code )
>
> ```
>
> Creates an anonymous function from the parameters passed, and returns a unique name for it.
>
>
>
And of note, `create_function` is deprecated in PHP 7.2
So this:
```
create_function( '$a', 'return $a + 1;' )
```
Becomes:
```
function( $a ) {
return $a + 1;
}
```
Or even
```
function add_one( $a ) {
return $a + 1;
}
```
This should eliminate the `create_function` calls, and turn the anonymous functions into normal calls that can be removed in a child theme
### Removing The Hooks and Filters
Now that we've done that, we can now remove and replace them in the child theme.
To do this, we need 2 things:
* to run the removal code **after** they were added
* to be able to unhook the filters/actions
Putting your replacement in is easy, just use `add_filter` and `add_action`, but that adds your version, we need to remove the parent themes version.
Lets assume that this code is in the parent theme:
```
add_filter('wp_add_numbers_together' 'add_one' );
```
And that we want to replace it with a `multiply_by_two` function. First lets do this on the `init` hook:
```php
function nickm_remove_parent_hooks() {
//
}
add_action('init', 'nickm_remove_parent_hooks' );
```
Then call `remove_filter and` add\_filter`:
```php
function nickm_remove_parent_hooks() {
remove_filter( 'wp_add_numbers_together' 'add_one' );
}
add_action( 'init', 'nickm_remove_parent_hooks' );
add_action( 'wp_add_numbers_together', 'multiply_by_two' );
```
Keep in mind that child themes let you override templates, but `functions.php` is not a template, and child themes don't change how `include` or `require` work. A child themes `functions.php` is loaded first, but otherwise, they're similar to plugins.
### And Finally
You shouldn't be registering post types, roles, capabilities, and taxonomies in a theme, it's a big red flag and creates lock in, preventing data portability. These things are supposed to be in plugins, not themes |
323,630 | <p>I want to export some specific posts from my database (csv or sql) and then replace content to these and import them back without changing the id number of the posts.I s this possible to do it and if it is, how?</p>
<p>Thank you in advance. </p>
| [
{
"answer_id": 323564,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>In order to remove the hooks and filters, we need to be able to get a reference to the callable that was added, but in this case, <code>create_function</code> was used, so that's extremely difficult. It's also the reason you're getting deprecation notices. Sadly the only way to fix those deprecations is to change the parent theme to fix it.</p>\n<h3>Fixing The Deprecations</h3>\n<p>The PHP docs say that <code>create_function</code> works like this:</p>\n<blockquote>\n<pre><code>string create_function ( string $args , string $code )\n</code></pre>\n<p>Creates an anonymous function from the parameters passed, and returns a unique name for it.</p>\n</blockquote>\n<p>And of note, <code>create_function</code> is deprecated in PHP 7.2</p>\n<p>So this:</p>\n<pre><code>create_function( '$a', 'return $a + 1;' )\n</code></pre>\n<p>Becomes:</p>\n<pre><code>function( $a ) {\n return $a + 1;\n}\n</code></pre>\n<p>Or even</p>\n<pre><code>function add_one( $a ) {\n return $a + 1;\n}\n</code></pre>\n<p>This should eliminate the <code>create_function</code> calls, and turn the anonymous functions into normal calls that can be removed in a child theme</p>\n<h3>Removing The Hooks and Filters</h3>\n<p>Now that we've done that, we can now remove and replace them in the child theme.</p>\n<p>To do this, we need 2 things:</p>\n<ul>\n<li>to run the removal code <strong>after</strong> they were added</li>\n<li>to be able to unhook the filters/actions</li>\n</ul>\n<p>Putting your replacement in is easy, just use <code>add_filter</code> and <code>add_action</code>, but that adds your version, we need to remove the parent themes version.</p>\n<p>Lets assume that this code is in the parent theme:</p>\n<pre><code>add_filter('wp_add_numbers_together' 'add_one' );\n</code></pre>\n<p>And that we want to replace it with a <code>multiply_by_two</code> function. First lets do this on the <code>init</code> hook:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function nickm_remove_parent_hooks() {\n //\n}\nadd_action('init', 'nickm_remove_parent_hooks' );\n</code></pre>\n<p>Then call <code>remove_filter and </code>add_filter`:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function nickm_remove_parent_hooks() {\n remove_filter( 'wp_add_numbers_together' 'add_one' );\n}\nadd_action( 'init', 'nickm_remove_parent_hooks' );\nadd_action( 'wp_add_numbers_together', 'multiply_by_two' );\n</code></pre>\n<p>Keep in mind that child themes let you override templates, but <code>functions.php</code> is not a template, and child themes don't change how <code>include</code> or <code>require</code> work. A child themes <code>functions.php</code> is loaded first, but otherwise, they're similar to plugins.</p>\n<h3>And Finally</h3>\n<p>You shouldn't be registering post types, roles, capabilities, and taxonomies in a theme, it's a big red flag and creates lock in, preventing data portability. These things are supposed to be in plugins, not themes</p>\n"
},
{
"answer_id": 323615,
"author": "Nick M",
"author_id": 157435,
"author_profile": "https://wordpress.stackexchange.com/users/157435",
"pm_score": 0,
"selected": false,
"text": "<p>So turns out taking the following, and just removing <code>if ( ! function_exists( 'ot_register_theme_options_page' ) ) { }</code> and adjusting the filter will take priority over the parent theme.</p>\n\n<pre><code>if ( ! function_exists( 'ot_register_theme_options_page' ) ) {\n\n function ot_register_theme_options_page() {\n\n /* get the settings array */\n $get_settings = _ut_theme_options();\n\n /* sections array */\n $sections = isset( $get_settings['sections'] ) ? $get_settings['sections'] : [];\n\n /* settings array */\n $settings = isset( $get_settings['settings'] ) ? $get_settings['settings'] : [];\n\n /* build the Theme Options */\n if ( function_exists( 'ot_register_settings' ) && OT_USE_THEME_OPTIONS ) {\n\n ot_register_settings(\n [\n [\n 'id' => 'option_tree',\n 'pages' => [\n [\n 'id' => 'ot_theme_options',\n 'parent_slug' => apply_filters( 'ot_theme_options_parent_slug', 'unite-welcome-page' ),\n 'page_title' => apply_filters( 'ot_theme_options_page_title', __( 'Theme Options', 'option-tree' ) ),\n 'menu_title' => apply_filters( 'ot_theme_options_menu_title', __( 'Theme Options', 'option-tree' ) ),\n 'capability' => $caps = apply_filters( 'ot_theme_options_capability', 'edit_theme_options' ),\n 'menu_slug' => apply_filters( 'ot_theme_options_menu_slug', 'ut_theme_options' ),\n 'icon_url' => apply_filters( 'ot_theme_options_icon_url', null ),\n 'position' => apply_filters( 'ot_theme_options_position', null ),\n 'updated_message' => apply_filters( 'ot_theme_options_updated_message', __( 'Theme Options updated.', 'option-tree' ) ),\n 'reset_message' => apply_filters( 'ot_theme_options_reset_message', __( 'Theme Options reset.', 'option-tree' ) ),\n 'button_text' => apply_filters( 'ot_theme_options_button_text', __( 'Save Changes', 'option-tree' ) ),\n 'screen_icon' => 'themes',\n 'sections' => $sections,\n 'settings' => $settings,\n ],\n ],\n ],\n ]\n );\n\n // Filters the options.php to add the minimum user capabilities.\n add_filter( 'option_page_capability_option_tree', create_function( '$caps', \"return '$caps';\" ), 999 );\n\n }\n\n }\n\n}\n</code></pre>\n"
}
]
| 2018/12/21 | [
"https://wordpress.stackexchange.com/questions/323630",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129970/"
]
| I want to export some specific posts from my database (csv or sql) and then replace content to these and import them back without changing the id number of the posts.I s this possible to do it and if it is, how?
Thank you in advance. | In order to remove the hooks and filters, we need to be able to get a reference to the callable that was added, but in this case, `create_function` was used, so that's extremely difficult. It's also the reason you're getting deprecation notices. Sadly the only way to fix those deprecations is to change the parent theme to fix it.
### Fixing The Deprecations
The PHP docs say that `create_function` works like this:
>
>
> ```
> string create_function ( string $args , string $code )
>
> ```
>
> Creates an anonymous function from the parameters passed, and returns a unique name for it.
>
>
>
And of note, `create_function` is deprecated in PHP 7.2
So this:
```
create_function( '$a', 'return $a + 1;' )
```
Becomes:
```
function( $a ) {
return $a + 1;
}
```
Or even
```
function add_one( $a ) {
return $a + 1;
}
```
This should eliminate the `create_function` calls, and turn the anonymous functions into normal calls that can be removed in a child theme
### Removing The Hooks and Filters
Now that we've done that, we can now remove and replace them in the child theme.
To do this, we need 2 things:
* to run the removal code **after** they were added
* to be able to unhook the filters/actions
Putting your replacement in is easy, just use `add_filter` and `add_action`, but that adds your version, we need to remove the parent themes version.
Lets assume that this code is in the parent theme:
```
add_filter('wp_add_numbers_together' 'add_one' );
```
And that we want to replace it with a `multiply_by_two` function. First lets do this on the `init` hook:
```php
function nickm_remove_parent_hooks() {
//
}
add_action('init', 'nickm_remove_parent_hooks' );
```
Then call `remove_filter and` add\_filter`:
```php
function nickm_remove_parent_hooks() {
remove_filter( 'wp_add_numbers_together' 'add_one' );
}
add_action( 'init', 'nickm_remove_parent_hooks' );
add_action( 'wp_add_numbers_together', 'multiply_by_two' );
```
Keep in mind that child themes let you override templates, but `functions.php` is not a template, and child themes don't change how `include` or `require` work. A child themes `functions.php` is loaded first, but otherwise, they're similar to plugins.
### And Finally
You shouldn't be registering post types, roles, capabilities, and taxonomies in a theme, it's a big red flag and creates lock in, preventing data portability. These things are supposed to be in plugins, not themes |
323,637 | <p>I would like to understand the best practices regarding nonce validation in REST APIs.</p>
<p>I see a lot of people talking about <code>wp_rest</code> nonce for REST requests. But upon looking on WordPress core code, I saw that <code>wp_rest</code> is just a nonce to validate a logged in user status, if it's not present, it just runs the request as guest.</p>
<p>That said, should I submit two nonces upon sending a POST request to a REST API? One for authentication <code>wp_rest</code> and another for the action <code>foo_action</code>?</p>
<p>If so, how should I send <code>wp_rest</code> and <code>foo_action</code> nonce in JavaScript, and, in PHP, what's the correct place to validate those nonces? (I mean validate_callback for a arg? permission_callback?)</p>
| [
{
"answer_id": 323638,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 4,
"selected": false,
"text": "<p>You should pass the special <code>wp_rest</code> nonce as part of the request. Without it, the <code>global $current_user</code> object will not be available in your REST class. You can pass this from several ways, from $_GET to $_POST to headers.</p>\n<p>The action nonce is optional. If you add it, you can't use the REST endpoint from an external server, only from requests dispatched from within WordPress itself. The user can authenticate itself using <a href=\"https://github.com/WP-API/Basic-Auth\" rel=\"nofollow noreferrer\">Basic Auth</a>, <a href=\"https://github.com/WP-API/OAuth2\" rel=\"nofollow noreferrer\">OAuth2</a>, or <a href=\"https://github.com/WP-API/jwt-auth\" rel=\"nofollow noreferrer\">JWT</a> from an external server even without the <code>wp_rest</code> nonce, but if you add an action nonce as well, it won't work.</p>\n<p>So the action nonce is optional. Add it if you want the endpoint to work locally only.</p>\n<p>Example:</p>\n<pre><code>/**\n* First step, registering, localizing and enqueueing the JavaScript\n*/\nwp_register_script( 'main-js', get_template_directory_uri() . '/js/main.js', [ 'jquery' ] );\nwp_localize_script( 'main-js', 'data', [\n 'rest' => [\n 'endpoints' => [\n 'my_endpoint' => esc_url_raw( rest_url( 'my_plugin/v1/my_endpoint' ) ),\n ],\n 'timeout' => (int) apply_filters( "my_plugin_rest_timeout", 60 ),\n 'nonce' => wp_create_nonce( 'wp_rest' ),\n //'action_nonce' => wp_create_nonce( 'action_nonce' ), \n ],\n] );\nwp_enqueue_script( 'main-js' );\n\n/**\n* Second step, the request on the JavaScript file\n*/\njQuery(document).on('click', '#some_element', function () {\n let ajax_data = {\n 'some_value': jQuery( ".some_value" ).val(),\n //'action_nonce': data.rest.action_nonce\n };\n\n jQuery.ajax({\n url: data.rest.endpoints.my_endpoint,\n method: "GET",\n dataType: "json",\n timeout: data.rest.timeout,\n data: ajax_data,\n beforeSend: function (xhr) {\n xhr.setRequestHeader('X-WP-Nonce', data.rest.nonce);\n }\n }).done(function (results) {\n console.log(results);\n alert("Success!");\n }).fail(function (xhr) {\n console.log(results);\n alert("Error!");\n });\n});\n\n/**\n* Third step, the REST endpoint itself\n*/\nclass My_Endpoint {\n public function registerRoutes() {\n register_rest_route( 'my_plugin', 'v1/my_endpoint', [\n 'methods' => WP_REST_Server::READABLE,\n 'callback' => [ $this, 'get_something' ],\n 'args' => [\n 'some_value' => [\n 'required' => true,\n ],\n ],\n 'permission_callback' => function ( WP_REST_Request $request ) {\n return true;\n },\n ] );\n }\n\n /**\n * @return WP_REST_Response\n */\n private function get_something( WP_REST_Request $request ) {\n //if ( ! wp_verify_nonce( $request['nonce'], 'action_nonce' ) ) {\n // return false;\n //}\n\n $some_value = $request['some_value'];\n\n if ( strlen( $some_value ) < 5 ) {\n return new WP_REST_Response( 'Sorry, Some Value must be at least 5 characters long.', 400 );\n }\n\n // Since we are passing the "X-WP-Nonce" header, this will work:\n $user = wp_get_current_user();\n\n if ( $user instanceof WP_User ) {\n return new WP_REST_Response( 'Sorry, could not get the name.', 400 );\n } else {\n return new WP_REST_Response( 'Your username name is: ' . $user->display_name, 200 );\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 359521,
"author": "Danny Watts",
"author_id": 183391,
"author_profile": "https://wordpress.stackexchange.com/users/183391",
"pm_score": 2,
"selected": false,
"text": "<p>Building on what @lucas-bustamante wrote (which helped me a ton!), once you have the X-WP-Nonce header setup in your custom routes you can do the following:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> register_rest_route('v1', '/my_post', [\n 'methods' => WP_REST_Server::CREATABLE,\n 'callback' => [$this, 'create_post'],\n 'args' => [\n 'post_title' => [\n 'required' => true,\n ],\n 'post_excerpt' => [\n 'required' => true,\n ]\n ],\n 'permission_callback' => function ( ) {\n return current_user_can( 'publish_posts' );\n },\n ]);\n</code></pre>\n\n<p>Note that the <code>permission_callback</code> is on the root level not under args (<a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback\" rel=\"nofollow noreferrer\">documented here</a>) and I've removed the additional <code>nonce</code> check from <code>args</code> since checking the permission alone will fail if the nonce is invalid or not supplied (I've tested this extensively and can confirm I get an error when no nonce is supplied or it's invalid).</p>\n"
},
{
"answer_id": 413874,
"author": "JDandChips",
"author_id": 134142,
"author_profile": "https://wordpress.stackexchange.com/users/134142",
"pm_score": 0,
"selected": false,
"text": "<p>One thing to note about @Lucas Bustamante's answer is that the verification process described is user-based authentication. This means if you have an anonymous API end point which doesn't require a user, then by simply by not providing the <code>X-WP-NONCE</code> header you'll pass the described nonce check. Supplying an incorrect nonce will still throw an error.</p>\n<p>The reason for this is that the <code>rest_cookie_check_errors</code> which is what does the verification will simply set the <code>current_user</code> to empty if no nonce is provided. This works fine when a user is required, but not otherwise. (see: <a href=\"https://developer.wordpress.org/reference/functions/rest_cookie_check_errors/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/rest_cookie_check_errors/</a>)</p>\n<p>If you want to expand on Lucas' answer to also include annonymous end points, then you can add a manual nonce check to the start of your end point, like this:</p>\n<pre><code>if ( !$_SERVER['HTTP_X_WP_NONCE'] || !wp_verify_nonce( $_SERVER['HTTP_X_WP_NONCE'], 'wp_rest' ) ) {\n header('HTTP/1.0 403 Forbidden');\n exit;\n}\n</code></pre>\n"
}
]
| 2018/12/22 | [
"https://wordpress.stackexchange.com/questions/323637",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27278/"
]
| I would like to understand the best practices regarding nonce validation in REST APIs.
I see a lot of people talking about `wp_rest` nonce for REST requests. But upon looking on WordPress core code, I saw that `wp_rest` is just a nonce to validate a logged in user status, if it's not present, it just runs the request as guest.
That said, should I submit two nonces upon sending a POST request to a REST API? One for authentication `wp_rest` and another for the action `foo_action`?
If so, how should I send `wp_rest` and `foo_action` nonce in JavaScript, and, in PHP, what's the correct place to validate those nonces? (I mean validate\_callback for a arg? permission\_callback?) | You should pass the special `wp_rest` nonce as part of the request. Without it, the `global $current_user` object will not be available in your REST class. You can pass this from several ways, from $\_GET to $\_POST to headers.
The action nonce is optional. If you add it, you can't use the REST endpoint from an external server, only from requests dispatched from within WordPress itself. The user can authenticate itself using [Basic Auth](https://github.com/WP-API/Basic-Auth), [OAuth2](https://github.com/WP-API/OAuth2), or [JWT](https://github.com/WP-API/jwt-auth) from an external server even without the `wp_rest` nonce, but if you add an action nonce as well, it won't work.
So the action nonce is optional. Add it if you want the endpoint to work locally only.
Example:
```
/**
* First step, registering, localizing and enqueueing the JavaScript
*/
wp_register_script( 'main-js', get_template_directory_uri() . '/js/main.js', [ 'jquery' ] );
wp_localize_script( 'main-js', 'data', [
'rest' => [
'endpoints' => [
'my_endpoint' => esc_url_raw( rest_url( 'my_plugin/v1/my_endpoint' ) ),
],
'timeout' => (int) apply_filters( "my_plugin_rest_timeout", 60 ),
'nonce' => wp_create_nonce( 'wp_rest' ),
//'action_nonce' => wp_create_nonce( 'action_nonce' ),
],
] );
wp_enqueue_script( 'main-js' );
/**
* Second step, the request on the JavaScript file
*/
jQuery(document).on('click', '#some_element', function () {
let ajax_data = {
'some_value': jQuery( ".some_value" ).val(),
//'action_nonce': data.rest.action_nonce
};
jQuery.ajax({
url: data.rest.endpoints.my_endpoint,
method: "GET",
dataType: "json",
timeout: data.rest.timeout,
data: ajax_data,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', data.rest.nonce);
}
}).done(function (results) {
console.log(results);
alert("Success!");
}).fail(function (xhr) {
console.log(results);
alert("Error!");
});
});
/**
* Third step, the REST endpoint itself
*/
class My_Endpoint {
public function registerRoutes() {
register_rest_route( 'my_plugin', 'v1/my_endpoint', [
'methods' => WP_REST_Server::READABLE,
'callback' => [ $this, 'get_something' ],
'args' => [
'some_value' => [
'required' => true,
],
],
'permission_callback' => function ( WP_REST_Request $request ) {
return true;
},
] );
}
/**
* @return WP_REST_Response
*/
private function get_something( WP_REST_Request $request ) {
//if ( ! wp_verify_nonce( $request['nonce'], 'action_nonce' ) ) {
// return false;
//}
$some_value = $request['some_value'];
if ( strlen( $some_value ) < 5 ) {
return new WP_REST_Response( 'Sorry, Some Value must be at least 5 characters long.', 400 );
}
// Since we are passing the "X-WP-Nonce" header, this will work:
$user = wp_get_current_user();
if ( $user instanceof WP_User ) {
return new WP_REST_Response( 'Sorry, could not get the name.', 400 );
} else {
return new WP_REST_Response( 'Your username name is: ' . $user->display_name, 200 );
}
}
}
``` |
323,705 | <p>I have used this function to add a responsive class to all the images in content but this breaks the html structure of the website. This wraps the content with :
<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"><body> the content goes here (output from the_content();) </body></html></code></p>
<pre><code>function add_responsive_class($content)
{
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
if (!empty($content)) {
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
$imgs = $document->getElementsByTagName('img');
foreach ($imgs as $img) {
$classes = $img->getAttribute('class');
$img->setAttribute('class', $classes . ' img-fluid');
}
$html = $document->saveHTML();
return $html;
}
}
add_filter('the_content', 'add_responsive_class');
add_filter('acf_the_content', 'add_responsive_class');
</code></pre>
<p>Can i know why? any alternative solution for this?</p>
| [
{
"answer_id": 323638,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 4,
"selected": false,
"text": "<p>You should pass the special <code>wp_rest</code> nonce as part of the request. Without it, the <code>global $current_user</code> object will not be available in your REST class. You can pass this from several ways, from $_GET to $_POST to headers.</p>\n<p>The action nonce is optional. If you add it, you can't use the REST endpoint from an external server, only from requests dispatched from within WordPress itself. The user can authenticate itself using <a href=\"https://github.com/WP-API/Basic-Auth\" rel=\"nofollow noreferrer\">Basic Auth</a>, <a href=\"https://github.com/WP-API/OAuth2\" rel=\"nofollow noreferrer\">OAuth2</a>, or <a href=\"https://github.com/WP-API/jwt-auth\" rel=\"nofollow noreferrer\">JWT</a> from an external server even without the <code>wp_rest</code> nonce, but if you add an action nonce as well, it won't work.</p>\n<p>So the action nonce is optional. Add it if you want the endpoint to work locally only.</p>\n<p>Example:</p>\n<pre><code>/**\n* First step, registering, localizing and enqueueing the JavaScript\n*/\nwp_register_script( 'main-js', get_template_directory_uri() . '/js/main.js', [ 'jquery' ] );\nwp_localize_script( 'main-js', 'data', [\n 'rest' => [\n 'endpoints' => [\n 'my_endpoint' => esc_url_raw( rest_url( 'my_plugin/v1/my_endpoint' ) ),\n ],\n 'timeout' => (int) apply_filters( "my_plugin_rest_timeout", 60 ),\n 'nonce' => wp_create_nonce( 'wp_rest' ),\n //'action_nonce' => wp_create_nonce( 'action_nonce' ), \n ],\n] );\nwp_enqueue_script( 'main-js' );\n\n/**\n* Second step, the request on the JavaScript file\n*/\njQuery(document).on('click', '#some_element', function () {\n let ajax_data = {\n 'some_value': jQuery( ".some_value" ).val(),\n //'action_nonce': data.rest.action_nonce\n };\n\n jQuery.ajax({\n url: data.rest.endpoints.my_endpoint,\n method: "GET",\n dataType: "json",\n timeout: data.rest.timeout,\n data: ajax_data,\n beforeSend: function (xhr) {\n xhr.setRequestHeader('X-WP-Nonce', data.rest.nonce);\n }\n }).done(function (results) {\n console.log(results);\n alert("Success!");\n }).fail(function (xhr) {\n console.log(results);\n alert("Error!");\n });\n});\n\n/**\n* Third step, the REST endpoint itself\n*/\nclass My_Endpoint {\n public function registerRoutes() {\n register_rest_route( 'my_plugin', 'v1/my_endpoint', [\n 'methods' => WP_REST_Server::READABLE,\n 'callback' => [ $this, 'get_something' ],\n 'args' => [\n 'some_value' => [\n 'required' => true,\n ],\n ],\n 'permission_callback' => function ( WP_REST_Request $request ) {\n return true;\n },\n ] );\n }\n\n /**\n * @return WP_REST_Response\n */\n private function get_something( WP_REST_Request $request ) {\n //if ( ! wp_verify_nonce( $request['nonce'], 'action_nonce' ) ) {\n // return false;\n //}\n\n $some_value = $request['some_value'];\n\n if ( strlen( $some_value ) < 5 ) {\n return new WP_REST_Response( 'Sorry, Some Value must be at least 5 characters long.', 400 );\n }\n\n // Since we are passing the "X-WP-Nonce" header, this will work:\n $user = wp_get_current_user();\n\n if ( $user instanceof WP_User ) {\n return new WP_REST_Response( 'Sorry, could not get the name.', 400 );\n } else {\n return new WP_REST_Response( 'Your username name is: ' . $user->display_name, 200 );\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 359521,
"author": "Danny Watts",
"author_id": 183391,
"author_profile": "https://wordpress.stackexchange.com/users/183391",
"pm_score": 2,
"selected": false,
"text": "<p>Building on what @lucas-bustamante wrote (which helped me a ton!), once you have the X-WP-Nonce header setup in your custom routes you can do the following:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code> register_rest_route('v1', '/my_post', [\n 'methods' => WP_REST_Server::CREATABLE,\n 'callback' => [$this, 'create_post'],\n 'args' => [\n 'post_title' => [\n 'required' => true,\n ],\n 'post_excerpt' => [\n 'required' => true,\n ]\n ],\n 'permission_callback' => function ( ) {\n return current_user_can( 'publish_posts' );\n },\n ]);\n</code></pre>\n\n<p>Note that the <code>permission_callback</code> is on the root level not under args (<a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/#permissions-callback\" rel=\"nofollow noreferrer\">documented here</a>) and I've removed the additional <code>nonce</code> check from <code>args</code> since checking the permission alone will fail if the nonce is invalid or not supplied (I've tested this extensively and can confirm I get an error when no nonce is supplied or it's invalid).</p>\n"
},
{
"answer_id": 413874,
"author": "JDandChips",
"author_id": 134142,
"author_profile": "https://wordpress.stackexchange.com/users/134142",
"pm_score": 0,
"selected": false,
"text": "<p>One thing to note about @Lucas Bustamante's answer is that the verification process described is user-based authentication. This means if you have an anonymous API end point which doesn't require a user, then by simply by not providing the <code>X-WP-NONCE</code> header you'll pass the described nonce check. Supplying an incorrect nonce will still throw an error.</p>\n<p>The reason for this is that the <code>rest_cookie_check_errors</code> which is what does the verification will simply set the <code>current_user</code> to empty if no nonce is provided. This works fine when a user is required, but not otherwise. (see: <a href=\"https://developer.wordpress.org/reference/functions/rest_cookie_check_errors/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/rest_cookie_check_errors/</a>)</p>\n<p>If you want to expand on Lucas' answer to also include annonymous end points, then you can add a manual nonce check to the start of your end point, like this:</p>\n<pre><code>if ( !$_SERVER['HTTP_X_WP_NONCE'] || !wp_verify_nonce( $_SERVER['HTTP_X_WP_NONCE'], 'wp_rest' ) ) {\n header('HTTP/1.0 403 Forbidden');\n exit;\n}\n</code></pre>\n"
}
]
| 2018/12/22 | [
"https://wordpress.stackexchange.com/questions/323705",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| I have used this function to add a responsive class to all the images in content but this breaks the html structure of the website. This wraps the content with :
`<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"><body> the content goes here (output from the_content();) </body></html>`
```
function add_responsive_class($content)
{
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
if (!empty($content)) {
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
$imgs = $document->getElementsByTagName('img');
foreach ($imgs as $img) {
$classes = $img->getAttribute('class');
$img->setAttribute('class', $classes . ' img-fluid');
}
$html = $document->saveHTML();
return $html;
}
}
add_filter('the_content', 'add_responsive_class');
add_filter('acf_the_content', 'add_responsive_class');
```
Can i know why? any alternative solution for this? | You should pass the special `wp_rest` nonce as part of the request. Without it, the `global $current_user` object will not be available in your REST class. You can pass this from several ways, from $\_GET to $\_POST to headers.
The action nonce is optional. If you add it, you can't use the REST endpoint from an external server, only from requests dispatched from within WordPress itself. The user can authenticate itself using [Basic Auth](https://github.com/WP-API/Basic-Auth), [OAuth2](https://github.com/WP-API/OAuth2), or [JWT](https://github.com/WP-API/jwt-auth) from an external server even without the `wp_rest` nonce, but if you add an action nonce as well, it won't work.
So the action nonce is optional. Add it if you want the endpoint to work locally only.
Example:
```
/**
* First step, registering, localizing and enqueueing the JavaScript
*/
wp_register_script( 'main-js', get_template_directory_uri() . '/js/main.js', [ 'jquery' ] );
wp_localize_script( 'main-js', 'data', [
'rest' => [
'endpoints' => [
'my_endpoint' => esc_url_raw( rest_url( 'my_plugin/v1/my_endpoint' ) ),
],
'timeout' => (int) apply_filters( "my_plugin_rest_timeout", 60 ),
'nonce' => wp_create_nonce( 'wp_rest' ),
//'action_nonce' => wp_create_nonce( 'action_nonce' ),
],
] );
wp_enqueue_script( 'main-js' );
/**
* Second step, the request on the JavaScript file
*/
jQuery(document).on('click', '#some_element', function () {
let ajax_data = {
'some_value': jQuery( ".some_value" ).val(),
//'action_nonce': data.rest.action_nonce
};
jQuery.ajax({
url: data.rest.endpoints.my_endpoint,
method: "GET",
dataType: "json",
timeout: data.rest.timeout,
data: ajax_data,
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', data.rest.nonce);
}
}).done(function (results) {
console.log(results);
alert("Success!");
}).fail(function (xhr) {
console.log(results);
alert("Error!");
});
});
/**
* Third step, the REST endpoint itself
*/
class My_Endpoint {
public function registerRoutes() {
register_rest_route( 'my_plugin', 'v1/my_endpoint', [
'methods' => WP_REST_Server::READABLE,
'callback' => [ $this, 'get_something' ],
'args' => [
'some_value' => [
'required' => true,
],
],
'permission_callback' => function ( WP_REST_Request $request ) {
return true;
},
] );
}
/**
* @return WP_REST_Response
*/
private function get_something( WP_REST_Request $request ) {
//if ( ! wp_verify_nonce( $request['nonce'], 'action_nonce' ) ) {
// return false;
//}
$some_value = $request['some_value'];
if ( strlen( $some_value ) < 5 ) {
return new WP_REST_Response( 'Sorry, Some Value must be at least 5 characters long.', 400 );
}
// Since we are passing the "X-WP-Nonce" header, this will work:
$user = wp_get_current_user();
if ( $user instanceof WP_User ) {
return new WP_REST_Response( 'Sorry, could not get the name.', 400 );
} else {
return new WP_REST_Response( 'Your username name is: ' . $user->display_name, 200 );
}
}
}
``` |
323,713 | <p>I am looking for a good approach regarding the creation of custom post types in WordPress, using object orientation. How can I create CPTs in an clean, organized way?</p>
<p>Take into consideration these 3 scenarios:</p>
<ol>
<li>Plugin for distribution (5.2 compatible)</li>
<li>Theme for distribution</li>
<li>Own project, with total control over the PHP version and dependencies</li>
</ol>
| [
{
"answer_id": 323714,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 3,
"selected": false,
"text": "<p>I'll answer <strong>scenario #3</strong>, even though it can be adapted for scenarios #1 and #2, too.</p>\n\n<p>WordPress codex <a href=\"https://codex.wordpress.org/Post_Types#A_word_about_custom_post_types_as_a_plugin\" rel=\"noreferrer\">recommends</a> that we create Custom Post Types (CPTs) in a plugin. Following that recommendation, I will write my answer using modern PHP, which is not meant for a distributed plugin, but rather for own projects where you have control over the PHP version running.</p>\n\n<p>In the example code bellow, I will use raw examples just to give an idea of the architecture behind the creation of CPTs in a OOP manner, but in a real project, \"my-plugin\" would be something like \"my-project\", and the creation of CPTs would be a sort of module of that plugin.</p>\n\n<p><strong>my-plugin/my-plugin.php</strong></p>\n\n<pre><code><?php\n/**\n* Plugin name: My Custom Post Types\n*/\nnamespace MyPlugin;\n\nuse MyPlugin/CPT/Car;\n\n// ... Composer autoload or similar here\n\nCar::register();\n</code></pre>\n\n<p><strong>my-plugin/CPT/Car.php</strong></p>\n\n<pre><code><?php\n\nnamespace MyPlugin\\CPT;\n\n/**\n * Class Car\n *\n * Handles the creation of a \"Car\" custom post type\n*/\nclass Car\n{\n public static function register()\n {\n $instance = new self;\n\n add_action('init', [$instance, 'registerPostType']);\n add_action('add_meta_boxes', [$instance, 'registerMetaboxes']);\n\n // Do something else related to \"Car\" post type\n }\n\n public function registerPostType()\n {\n register_post_type( 'car', [\n 'label' => 'Cars',\n ]);\n }\n\n public function registerMetaBoxes()\n {\n // Color metabox\n add_meta_box(\n 'car-color-metabox',\n __('Color', 'my-plugin'),\n [$this, 'colorMetabox'],\n 'car'\n );\n }\n\n public function colorMetabox()\n {\n echo 'Foo';\n }\n}\n</code></pre>\n\n<p>This way we have a namespace for our CPTs, and an object where we can manage it's properties, such as registering the post type, adding or removing metaboxes, etc.</p>\n\n<p>If we are accepting insertion of \"Cars\" from the frontend, we would use the <a href=\"https://developer.wordpress.org/rest-api/\" rel=\"noreferrer\">REST API</a> to receive the POST request and handle it in a <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/controller-classes/\" rel=\"noreferrer\">REST Controller Class</a>, but that is out of the scope of this answer.</p>\n"
},
{
"answer_id": 323720,
"author": "Justin Waulters",
"author_id": 137235,
"author_profile": "https://wordpress.stackexchange.com/users/137235",
"pm_score": 2,
"selected": false,
"text": "<p>I typically use something like this:</p>\n\n<pre><code><?php\n\n/*\nPlugin Name: My Plugin\nPlugin URI: https://my.plugin.com\nDescription: My plugin description\nVersion: 1.0.0\nAuthor: Me\nAuthor URI: https://my.website.com\nLicense: GPL2 (or whatever)\n\nNotes:\n*/\n\nclass myClass {\n\n function __construct() {\n\n add_action( 'init', array( $this, 'create_post_type' ) );\n\n }\n\n function create_post_type() {\n\n $name = 'Foos';\n $singular_name = 'Foo';\n register_post_type( \n 'rg_' . strtolower( $name ),\n array(\n 'labels' => array(\n 'name' => _x( $name, 'post type general name' ),\n 'singular_name' => _x( $singular_name, 'post type singular name'),\n 'menu_name' => _x( $name, 'admin menu' ),\n 'name_admin_bar' => _x( $singular_name, 'add new on admin bar' ),\n 'add_new' => _x( 'Add New', strtolower( $name ) ),\n 'add_new_item' => __( 'Add New ' . $singular_name ),\n 'new_item' => __( 'New ' . $singular_name ),\n 'edit_item' => __( 'Edit ' . $singular_name ),\n 'view_item' => __( 'View ' . $singular_name ),\n 'all_items' => __( 'All ' . $name ),\n 'search_items' => __( 'Search ' . $name ),\n 'parent_item_colon' => __( 'Parent :' . $name ),\n 'not_found' => __( 'No ' . strtolower( $name ) . ' found.'),\n 'not_found_in_trash' => __( 'No ' . strtolower( $name ) . ' found in Trash.' )\n ),\n 'public' => true,\n 'has_archive' => strtolower($taxonomy_name),\n 'hierarchical' => false,\n 'rewrite' => array( 'slug' => $name ),\n 'menu_icon' => 'dashicons-carrot'\n )\n );\n\n }\n\n}\n\n$my_class = new myClass();\n\n?>\n</code></pre>\n\n<p>You can call the <code>add_action</code> function to another function too, as long as the action is part of the init callbacks. </p>\n\n<p>Note how the <code>add_action</code> function uses an array instead of a string when it is placed inside a class.</p>\n\n<p>You can just use this as the main file in your plugin if you want.</p>\n\n<p>The codex doesn't show using the variables <code>$name</code> and <code>$singular_name</code>, but i like to start this way so that I can easily change it whenever I want during development.</p>\n\n<p>Here is more information about creating post types:\n<a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/register_post_type/</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n"
}
]
| 2018/12/22 | [
"https://wordpress.stackexchange.com/questions/323713",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27278/"
]
| I am looking for a good approach regarding the creation of custom post types in WordPress, using object orientation. How can I create CPTs in an clean, organized way?
Take into consideration these 3 scenarios:
1. Plugin for distribution (5.2 compatible)
2. Theme for distribution
3. Own project, with total control over the PHP version and dependencies | I'll answer **scenario #3**, even though it can be adapted for scenarios #1 and #2, too.
WordPress codex [recommends](https://codex.wordpress.org/Post_Types#A_word_about_custom_post_types_as_a_plugin) that we create Custom Post Types (CPTs) in a plugin. Following that recommendation, I will write my answer using modern PHP, which is not meant for a distributed plugin, but rather for own projects where you have control over the PHP version running.
In the example code bellow, I will use raw examples just to give an idea of the architecture behind the creation of CPTs in a OOP manner, but in a real project, "my-plugin" would be something like "my-project", and the creation of CPTs would be a sort of module of that plugin.
**my-plugin/my-plugin.php**
```
<?php
/**
* Plugin name: My Custom Post Types
*/
namespace MyPlugin;
use MyPlugin/CPT/Car;
// ... Composer autoload or similar here
Car::register();
```
**my-plugin/CPT/Car.php**
```
<?php
namespace MyPlugin\CPT;
/**
* Class Car
*
* Handles the creation of a "Car" custom post type
*/
class Car
{
public static function register()
{
$instance = new self;
add_action('init', [$instance, 'registerPostType']);
add_action('add_meta_boxes', [$instance, 'registerMetaboxes']);
// Do something else related to "Car" post type
}
public function registerPostType()
{
register_post_type( 'car', [
'label' => 'Cars',
]);
}
public function registerMetaBoxes()
{
// Color metabox
add_meta_box(
'car-color-metabox',
__('Color', 'my-plugin'),
[$this, 'colorMetabox'],
'car'
);
}
public function colorMetabox()
{
echo 'Foo';
}
}
```
This way we have a namespace for our CPTs, and an object where we can manage it's properties, such as registering the post type, adding or removing metaboxes, etc.
If we are accepting insertion of "Cars" from the frontend, we would use the [REST API](https://developer.wordpress.org/rest-api/) to receive the POST request and handle it in a [REST Controller Class](https://developer.wordpress.org/rest-api/extending-the-rest-api/controller-classes/), but that is out of the scope of this answer. |
323,715 | <p>I have two categories for my posts, "event" and "long-term-leasing." I have sidebar-events.php and sidebar-long-term.php. I wrote a conditional statement in single.php, but when I view a post it only shows me the generic sidebar. I did a copy/paste of the categories to avoid typos. Where is my mistake?</p>
<pre><code> <?php
if (is_category("event")) {
get_sidebar('events');
} elseif (is_category('long-term-leasing')) {
get_sidebar('long-term');
} else {
get_sidebar();
}
?>
</code></pre>
| [
{
"answer_id": 323714,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 3,
"selected": false,
"text": "<p>I'll answer <strong>scenario #3</strong>, even though it can be adapted for scenarios #1 and #2, too.</p>\n\n<p>WordPress codex <a href=\"https://codex.wordpress.org/Post_Types#A_word_about_custom_post_types_as_a_plugin\" rel=\"noreferrer\">recommends</a> that we create Custom Post Types (CPTs) in a plugin. Following that recommendation, I will write my answer using modern PHP, which is not meant for a distributed plugin, but rather for own projects where you have control over the PHP version running.</p>\n\n<p>In the example code bellow, I will use raw examples just to give an idea of the architecture behind the creation of CPTs in a OOP manner, but in a real project, \"my-plugin\" would be something like \"my-project\", and the creation of CPTs would be a sort of module of that plugin.</p>\n\n<p><strong>my-plugin/my-plugin.php</strong></p>\n\n<pre><code><?php\n/**\n* Plugin name: My Custom Post Types\n*/\nnamespace MyPlugin;\n\nuse MyPlugin/CPT/Car;\n\n// ... Composer autoload or similar here\n\nCar::register();\n</code></pre>\n\n<p><strong>my-plugin/CPT/Car.php</strong></p>\n\n<pre><code><?php\n\nnamespace MyPlugin\\CPT;\n\n/**\n * Class Car\n *\n * Handles the creation of a \"Car\" custom post type\n*/\nclass Car\n{\n public static function register()\n {\n $instance = new self;\n\n add_action('init', [$instance, 'registerPostType']);\n add_action('add_meta_boxes', [$instance, 'registerMetaboxes']);\n\n // Do something else related to \"Car\" post type\n }\n\n public function registerPostType()\n {\n register_post_type( 'car', [\n 'label' => 'Cars',\n ]);\n }\n\n public function registerMetaBoxes()\n {\n // Color metabox\n add_meta_box(\n 'car-color-metabox',\n __('Color', 'my-plugin'),\n [$this, 'colorMetabox'],\n 'car'\n );\n }\n\n public function colorMetabox()\n {\n echo 'Foo';\n }\n}\n</code></pre>\n\n<p>This way we have a namespace for our CPTs, and an object where we can manage it's properties, such as registering the post type, adding or removing metaboxes, etc.</p>\n\n<p>If we are accepting insertion of \"Cars\" from the frontend, we would use the <a href=\"https://developer.wordpress.org/rest-api/\" rel=\"noreferrer\">REST API</a> to receive the POST request and handle it in a <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/controller-classes/\" rel=\"noreferrer\">REST Controller Class</a>, but that is out of the scope of this answer.</p>\n"
},
{
"answer_id": 323720,
"author": "Justin Waulters",
"author_id": 137235,
"author_profile": "https://wordpress.stackexchange.com/users/137235",
"pm_score": 2,
"selected": false,
"text": "<p>I typically use something like this:</p>\n\n<pre><code><?php\n\n/*\nPlugin Name: My Plugin\nPlugin URI: https://my.plugin.com\nDescription: My plugin description\nVersion: 1.0.0\nAuthor: Me\nAuthor URI: https://my.website.com\nLicense: GPL2 (or whatever)\n\nNotes:\n*/\n\nclass myClass {\n\n function __construct() {\n\n add_action( 'init', array( $this, 'create_post_type' ) );\n\n }\n\n function create_post_type() {\n\n $name = 'Foos';\n $singular_name = 'Foo';\n register_post_type( \n 'rg_' . strtolower( $name ),\n array(\n 'labels' => array(\n 'name' => _x( $name, 'post type general name' ),\n 'singular_name' => _x( $singular_name, 'post type singular name'),\n 'menu_name' => _x( $name, 'admin menu' ),\n 'name_admin_bar' => _x( $singular_name, 'add new on admin bar' ),\n 'add_new' => _x( 'Add New', strtolower( $name ) ),\n 'add_new_item' => __( 'Add New ' . $singular_name ),\n 'new_item' => __( 'New ' . $singular_name ),\n 'edit_item' => __( 'Edit ' . $singular_name ),\n 'view_item' => __( 'View ' . $singular_name ),\n 'all_items' => __( 'All ' . $name ),\n 'search_items' => __( 'Search ' . $name ),\n 'parent_item_colon' => __( 'Parent :' . $name ),\n 'not_found' => __( 'No ' . strtolower( $name ) . ' found.'),\n 'not_found_in_trash' => __( 'No ' . strtolower( $name ) . ' found in Trash.' )\n ),\n 'public' => true,\n 'has_archive' => strtolower($taxonomy_name),\n 'hierarchical' => false,\n 'rewrite' => array( 'slug' => $name ),\n 'menu_icon' => 'dashicons-carrot'\n )\n );\n\n }\n\n}\n\n$my_class = new myClass();\n\n?>\n</code></pre>\n\n<p>You can call the <code>add_action</code> function to another function too, as long as the action is part of the init callbacks. </p>\n\n<p>Note how the <code>add_action</code> function uses an array instead of a string when it is placed inside a class.</p>\n\n<p>You can just use this as the main file in your plugin if you want.</p>\n\n<p>The codex doesn't show using the variables <code>$name</code> and <code>$singular_name</code>, but i like to start this way so that I can easily change it whenever I want during development.</p>\n\n<p>Here is more information about creating post types:\n<a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/register_post_type/</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n"
}
]
| 2018/12/22 | [
"https://wordpress.stackexchange.com/questions/323715",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157494/"
]
| I have two categories for my posts, "event" and "long-term-leasing." I have sidebar-events.php and sidebar-long-term.php. I wrote a conditional statement in single.php, but when I view a post it only shows me the generic sidebar. I did a copy/paste of the categories to avoid typos. Where is my mistake?
```
<?php
if (is_category("event")) {
get_sidebar('events');
} elseif (is_category('long-term-leasing')) {
get_sidebar('long-term');
} else {
get_sidebar();
}
?>
``` | I'll answer **scenario #3**, even though it can be adapted for scenarios #1 and #2, too.
WordPress codex [recommends](https://codex.wordpress.org/Post_Types#A_word_about_custom_post_types_as_a_plugin) that we create Custom Post Types (CPTs) in a plugin. Following that recommendation, I will write my answer using modern PHP, which is not meant for a distributed plugin, but rather for own projects where you have control over the PHP version running.
In the example code bellow, I will use raw examples just to give an idea of the architecture behind the creation of CPTs in a OOP manner, but in a real project, "my-plugin" would be something like "my-project", and the creation of CPTs would be a sort of module of that plugin.
**my-plugin/my-plugin.php**
```
<?php
/**
* Plugin name: My Custom Post Types
*/
namespace MyPlugin;
use MyPlugin/CPT/Car;
// ... Composer autoload or similar here
Car::register();
```
**my-plugin/CPT/Car.php**
```
<?php
namespace MyPlugin\CPT;
/**
* Class Car
*
* Handles the creation of a "Car" custom post type
*/
class Car
{
public static function register()
{
$instance = new self;
add_action('init', [$instance, 'registerPostType']);
add_action('add_meta_boxes', [$instance, 'registerMetaboxes']);
// Do something else related to "Car" post type
}
public function registerPostType()
{
register_post_type( 'car', [
'label' => 'Cars',
]);
}
public function registerMetaBoxes()
{
// Color metabox
add_meta_box(
'car-color-metabox',
__('Color', 'my-plugin'),
[$this, 'colorMetabox'],
'car'
);
}
public function colorMetabox()
{
echo 'Foo';
}
}
```
This way we have a namespace for our CPTs, and an object where we can manage it's properties, such as registering the post type, adding or removing metaboxes, etc.
If we are accepting insertion of "Cars" from the frontend, we would use the [REST API](https://developer.wordpress.org/rest-api/) to receive the POST request and handle it in a [REST Controller Class](https://developer.wordpress.org/rest-api/extending-the-rest-api/controller-classes/), but that is out of the scope of this answer. |
323,737 | <p>my theme has option that there is a button in each post that I can give it a link. But I want to open a modal with clicking on this button and be able to modify the modal in each post. It means each post a special modal. Is it possible?</p>
| [
{
"answer_id": 323714,
"author": "Lucas Bustamante",
"author_id": 27278,
"author_profile": "https://wordpress.stackexchange.com/users/27278",
"pm_score": 3,
"selected": false,
"text": "<p>I'll answer <strong>scenario #3</strong>, even though it can be adapted for scenarios #1 and #2, too.</p>\n\n<p>WordPress codex <a href=\"https://codex.wordpress.org/Post_Types#A_word_about_custom_post_types_as_a_plugin\" rel=\"noreferrer\">recommends</a> that we create Custom Post Types (CPTs) in a plugin. Following that recommendation, I will write my answer using modern PHP, which is not meant for a distributed plugin, but rather for own projects where you have control over the PHP version running.</p>\n\n<p>In the example code bellow, I will use raw examples just to give an idea of the architecture behind the creation of CPTs in a OOP manner, but in a real project, \"my-plugin\" would be something like \"my-project\", and the creation of CPTs would be a sort of module of that plugin.</p>\n\n<p><strong>my-plugin/my-plugin.php</strong></p>\n\n<pre><code><?php\n/**\n* Plugin name: My Custom Post Types\n*/\nnamespace MyPlugin;\n\nuse MyPlugin/CPT/Car;\n\n// ... Composer autoload or similar here\n\nCar::register();\n</code></pre>\n\n<p><strong>my-plugin/CPT/Car.php</strong></p>\n\n<pre><code><?php\n\nnamespace MyPlugin\\CPT;\n\n/**\n * Class Car\n *\n * Handles the creation of a \"Car\" custom post type\n*/\nclass Car\n{\n public static function register()\n {\n $instance = new self;\n\n add_action('init', [$instance, 'registerPostType']);\n add_action('add_meta_boxes', [$instance, 'registerMetaboxes']);\n\n // Do something else related to \"Car\" post type\n }\n\n public function registerPostType()\n {\n register_post_type( 'car', [\n 'label' => 'Cars',\n ]);\n }\n\n public function registerMetaBoxes()\n {\n // Color metabox\n add_meta_box(\n 'car-color-metabox',\n __('Color', 'my-plugin'),\n [$this, 'colorMetabox'],\n 'car'\n );\n }\n\n public function colorMetabox()\n {\n echo 'Foo';\n }\n}\n</code></pre>\n\n<p>This way we have a namespace for our CPTs, and an object where we can manage it's properties, such as registering the post type, adding or removing metaboxes, etc.</p>\n\n<p>If we are accepting insertion of \"Cars\" from the frontend, we would use the <a href=\"https://developer.wordpress.org/rest-api/\" rel=\"noreferrer\">REST API</a> to receive the POST request and handle it in a <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/controller-classes/\" rel=\"noreferrer\">REST Controller Class</a>, but that is out of the scope of this answer.</p>\n"
},
{
"answer_id": 323720,
"author": "Justin Waulters",
"author_id": 137235,
"author_profile": "https://wordpress.stackexchange.com/users/137235",
"pm_score": 2,
"selected": false,
"text": "<p>I typically use something like this:</p>\n\n<pre><code><?php\n\n/*\nPlugin Name: My Plugin\nPlugin URI: https://my.plugin.com\nDescription: My plugin description\nVersion: 1.0.0\nAuthor: Me\nAuthor URI: https://my.website.com\nLicense: GPL2 (or whatever)\n\nNotes:\n*/\n\nclass myClass {\n\n function __construct() {\n\n add_action( 'init', array( $this, 'create_post_type' ) );\n\n }\n\n function create_post_type() {\n\n $name = 'Foos';\n $singular_name = 'Foo';\n register_post_type( \n 'rg_' . strtolower( $name ),\n array(\n 'labels' => array(\n 'name' => _x( $name, 'post type general name' ),\n 'singular_name' => _x( $singular_name, 'post type singular name'),\n 'menu_name' => _x( $name, 'admin menu' ),\n 'name_admin_bar' => _x( $singular_name, 'add new on admin bar' ),\n 'add_new' => _x( 'Add New', strtolower( $name ) ),\n 'add_new_item' => __( 'Add New ' . $singular_name ),\n 'new_item' => __( 'New ' . $singular_name ),\n 'edit_item' => __( 'Edit ' . $singular_name ),\n 'view_item' => __( 'View ' . $singular_name ),\n 'all_items' => __( 'All ' . $name ),\n 'search_items' => __( 'Search ' . $name ),\n 'parent_item_colon' => __( 'Parent :' . $name ),\n 'not_found' => __( 'No ' . strtolower( $name ) . ' found.'),\n 'not_found_in_trash' => __( 'No ' . strtolower( $name ) . ' found in Trash.' )\n ),\n 'public' => true,\n 'has_archive' => strtolower($taxonomy_name),\n 'hierarchical' => false,\n 'rewrite' => array( 'slug' => $name ),\n 'menu_icon' => 'dashicons-carrot'\n )\n );\n\n }\n\n}\n\n$my_class = new myClass();\n\n?>\n</code></pre>\n\n<p>You can call the <code>add_action</code> function to another function too, as long as the action is part of the init callbacks. </p>\n\n<p>Note how the <code>add_action</code> function uses an array instead of a string when it is placed inside a class.</p>\n\n<p>You can just use this as the main file in your plugin if you want.</p>\n\n<p>The codex doesn't show using the variables <code>$name</code> and <code>$singular_name</code>, but i like to start this way so that I can easily change it whenever I want during development.</p>\n\n<p>Here is more information about creating post types:\n<a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/register_post_type/</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n"
}
]
| 2018/12/23 | [
"https://wordpress.stackexchange.com/questions/323737",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157582/"
]
| my theme has option that there is a button in each post that I can give it a link. But I want to open a modal with clicking on this button and be able to modify the modal in each post. It means each post a special modal. Is it possible? | I'll answer **scenario #3**, even though it can be adapted for scenarios #1 and #2, too.
WordPress codex [recommends](https://codex.wordpress.org/Post_Types#A_word_about_custom_post_types_as_a_plugin) that we create Custom Post Types (CPTs) in a plugin. Following that recommendation, I will write my answer using modern PHP, which is not meant for a distributed plugin, but rather for own projects where you have control over the PHP version running.
In the example code bellow, I will use raw examples just to give an idea of the architecture behind the creation of CPTs in a OOP manner, but in a real project, "my-plugin" would be something like "my-project", and the creation of CPTs would be a sort of module of that plugin.
**my-plugin/my-plugin.php**
```
<?php
/**
* Plugin name: My Custom Post Types
*/
namespace MyPlugin;
use MyPlugin/CPT/Car;
// ... Composer autoload or similar here
Car::register();
```
**my-plugin/CPT/Car.php**
```
<?php
namespace MyPlugin\CPT;
/**
* Class Car
*
* Handles the creation of a "Car" custom post type
*/
class Car
{
public static function register()
{
$instance = new self;
add_action('init', [$instance, 'registerPostType']);
add_action('add_meta_boxes', [$instance, 'registerMetaboxes']);
// Do something else related to "Car" post type
}
public function registerPostType()
{
register_post_type( 'car', [
'label' => 'Cars',
]);
}
public function registerMetaBoxes()
{
// Color metabox
add_meta_box(
'car-color-metabox',
__('Color', 'my-plugin'),
[$this, 'colorMetabox'],
'car'
);
}
public function colorMetabox()
{
echo 'Foo';
}
}
```
This way we have a namespace for our CPTs, and an object where we can manage it's properties, such as registering the post type, adding or removing metaboxes, etc.
If we are accepting insertion of "Cars" from the frontend, we would use the [REST API](https://developer.wordpress.org/rest-api/) to receive the POST request and handle it in a [REST Controller Class](https://developer.wordpress.org/rest-api/extending-the-rest-api/controller-classes/), but that is out of the scope of this answer. |
323,750 | <p>To allow extra file types for upload, we use:</p>
<pre><code>add_filter('mime_types', 'my_mimes');
function my_mimes($all)
{
$all['zip'] = 'application/zip';
return $all;
}
</code></pre>
<p>But how to assign multiple file types to 1 extension?
For example, <code>zip</code> extension might have <code>application/zip</code> mime and also <code>application/x-zip</code> (like, coming from <code>7zip</code>). This way doesn't work:</p>
<pre><code>$all['zip'] = ['application/zip', 'application/x-zip'] ;
</code></pre>
| [
{
"answer_id": 323757,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>Note the stricter mime type check since WP 5.0.1 where the file content and file extension must match. See e.g. this recent <a href=\"https://wordpress.stackexchange.com/q/321804/26350\">question</a> on the <code>vtt</code> file type.</p>\n\n<h2>Secondary mime type for a given file extension</h2>\n\n<p>Here's a suggestion how to support a secondary mime type for a given file extension. Let's take <code>.vtt</code> as an example. The core assumes the mime type of <code>text/vtt</code> for that file extension, but the real mime type from <code>finfo_file()</code> can sometimes be <code>text/plain</code>. The <code>finfo_file()</code> seems to be somewhat <a href=\"https://bugs.php.net/bug.php?id=75380\" rel=\"noreferrer\">buggy</a>. We can add a support for it as a secondary mime type with:</p>\n\n<pre><code>/**\n * Support for 'text/plain' as the secondary mime type of .vtt files,\n * in addition to the default 'text/vtt' support.\n */\nadd_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 ); \n\nfunction wpse323750_secondary_mime( $check, $file, $filename, $mimes ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n // Adjust to your needs!\n $secondary_mime = [ 'vtt' => 'text/plain' ];\n\n // Run another check, but only for our secondary mime and not on core mime types.\n remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );\n $check = wp_check_filetype_and_ext( $file, $filename, $secondary_mime );\n add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );\n }\n return $check;\n}\n</code></pre>\n\n<p>Here we use the <code>wp_check_filetype_and_ext</code> filter to see if the check failed. In that case we run <code>wp_check_filetype_and_ext()</code> again but now only on our secondary mime type, disabling our filter callback in the meanwhile to avoid an infinite loop.</p>\n\n<h2>Multiple mime types for a given file extension</h2>\n\n<p>If we need to support more than two mime types for the <code>.vtt</code> files, then we can expand the above snippet with:</p>\n\n<pre><code>/**\n * Demo: Support for 'text/foo' and 'text/bar' mime types of .vtt files,\n * in addition to the default 'text/vtt' support.\n */\nadd_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n\nfunction wpse323750_multi_mimes( $check, $file, $filename, $mimes ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n // Adjust to your needs!\n $multi_mimes = [ [ 'vtt' => 'text/foo' ], [ 'vtt' => 'text/bar' ] ];\n\n // Run new checks for our custom mime types and not on core mime types.\n foreach( $multi_mimes as $mime ) {\n remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n $check = wp_check_filetype_and_ext( $file, $filename, $mime );\n add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {\n return $check;\n }\n }\n }\n return $check;\n}\n</code></pre>\n\n<p>I hope you can test it further and adjust it to your needs.</p>\n"
},
{
"answer_id": 346169,
"author": "Sergio Zaharchenko",
"author_id": 136533,
"author_profile": "https://wordpress.stackexchange.com/users/136533",
"pm_score": 2,
"selected": false,
"text": "<p>A little improved birgire's answer. Had to add multiple mime types for <code>svg</code>, but because <code>svg</code> is forbidden by default, had to add dynamic filter to <code>upload_mimes</code>:</p>\n\n<pre><code>class Multiple_Mimes {\n\n public static function init() {\n add_filter( 'wp_check_filetype_and_ext', [self::class, 'add_multiple_mime_types'], 99, 3 );\n }\n\n\n public static function add_multiple_mime_types( $check, $file, $filename ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n foreach ( self::get_allowed_mime_types() as $mime ) {\n remove_filter( 'wp_check_filetype_and_ext', [ self::class, 'add_multiple_mime_types' ], 99 );\n $mime_filter = function($mimes) use ($mime) {\n return array_merge($mimes, $mime);\n };\n\n add_filter('upload_mimes', $mime_filter, 99);\n $check = wp_check_filetype_and_ext( $file, $filename, $mime );\n remove_filter('upload_mimes', $mime_filter, 99);\n add_filter( 'wp_check_filetype_and_ext', [ self::class, 'add_multiple_mime_types' ], 99, 3 );\n if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {\n return $check;\n }\n }\n }\n\n return $check;\n }\n\n\n public static function get_allowed_mime_types(){\n return [\n [ 'svg' => 'image/svg' ],\n [ 'svg' => 'image/svg+xml' ],\n ];\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 370151,
"author": "bobbingwide",
"author_id": 77573,
"author_profile": "https://wordpress.stackexchange.com/users/77573",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem to solve where .zip files were seen as <code>application/zip</code> by PHP but detected as <code>application/x-zip-compressed</code>.</p>\n<p>My workaround was to add this new value with an invented key</p>\n<pre><code>'xzip' => '`application/x-zip-compressed';\n</code></pre>\n<p>See <a href=\"https://github.com/WordPress/gutenberg/issues/23510\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/issues/23510</a></p>\n<p>See also two WordPress TRACs:</p>\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/40175\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/40175</a></li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/46775\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/46775</a></li>\n</ul>\n"
}
]
| 2018/12/23 | [
"https://wordpress.stackexchange.com/questions/323750",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33667/"
]
| To allow extra file types for upload, we use:
```
add_filter('mime_types', 'my_mimes');
function my_mimes($all)
{
$all['zip'] = 'application/zip';
return $all;
}
```
But how to assign multiple file types to 1 extension?
For example, `zip` extension might have `application/zip` mime and also `application/x-zip` (like, coming from `7zip`). This way doesn't work:
```
$all['zip'] = ['application/zip', 'application/x-zip'] ;
``` | Note the stricter mime type check since WP 5.0.1 where the file content and file extension must match. See e.g. this recent [question](https://wordpress.stackexchange.com/q/321804/26350) on the `vtt` file type.
Secondary mime type for a given file extension
----------------------------------------------
Here's a suggestion how to support a secondary mime type for a given file extension. Let's take `.vtt` as an example. The core assumes the mime type of `text/vtt` for that file extension, but the real mime type from `finfo_file()` can sometimes be `text/plain`. The `finfo_file()` seems to be somewhat [buggy](https://bugs.php.net/bug.php?id=75380). We can add a support for it as a secondary mime type with:
```
/**
* Support for 'text/plain' as the secondary mime type of .vtt files,
* in addition to the default 'text/vtt' support.
*/
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
function wpse323750_secondary_mime( $check, $file, $filename, $mimes ) {
if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {
// Adjust to your needs!
$secondary_mime = [ 'vtt' => 'text/plain' ];
// Run another check, but only for our secondary mime and not on core mime types.
remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
$check = wp_check_filetype_and_ext( $file, $filename, $secondary_mime );
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
}
return $check;
}
```
Here we use the `wp_check_filetype_and_ext` filter to see if the check failed. In that case we run `wp_check_filetype_and_ext()` again but now only on our secondary mime type, disabling our filter callback in the meanwhile to avoid an infinite loop.
Multiple mime types for a given file extension
----------------------------------------------
If we need to support more than two mime types for the `.vtt` files, then we can expand the above snippet with:
```
/**
* Demo: Support for 'text/foo' and 'text/bar' mime types of .vtt files,
* in addition to the default 'text/vtt' support.
*/
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
function wpse323750_multi_mimes( $check, $file, $filename, $mimes ) {
if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {
// Adjust to your needs!
$multi_mimes = [ [ 'vtt' => 'text/foo' ], [ 'vtt' => 'text/bar' ] ];
// Run new checks for our custom mime types and not on core mime types.
foreach( $multi_mimes as $mime ) {
remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
$check = wp_check_filetype_and_ext( $file, $filename, $mime );
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {
return $check;
}
}
}
return $check;
}
```
I hope you can test it further and adjust it to your needs. |
323,760 | <p>I am able to create a new post but I get a generic error message <code>Publishing failed</code> if I try to publish it. Same thing if I try to edit it (or any other post).
If I try to delete the post using the <code>Move to trash</code> button, I get another error: <code>The response is not a valid JSON response.</code></p>
<p>The issue only happens in the new Gutenberg interface (<code>wp-admin/post.php</code>) I am able to publish or remove the post using the "quick edit" functions on the posts list view (<code>wp-admin/edit.php</code>)
The problem occurs with all users and for all post types (I tried with posts and pages). Deactivating all plugins and visiting the permalinks page did not solve the issue.</p>
| [
{
"answer_id": 323757,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>Note the stricter mime type check since WP 5.0.1 where the file content and file extension must match. See e.g. this recent <a href=\"https://wordpress.stackexchange.com/q/321804/26350\">question</a> on the <code>vtt</code> file type.</p>\n\n<h2>Secondary mime type for a given file extension</h2>\n\n<p>Here's a suggestion how to support a secondary mime type for a given file extension. Let's take <code>.vtt</code> as an example. The core assumes the mime type of <code>text/vtt</code> for that file extension, but the real mime type from <code>finfo_file()</code> can sometimes be <code>text/plain</code>. The <code>finfo_file()</code> seems to be somewhat <a href=\"https://bugs.php.net/bug.php?id=75380\" rel=\"noreferrer\">buggy</a>. We can add a support for it as a secondary mime type with:</p>\n\n<pre><code>/**\n * Support for 'text/plain' as the secondary mime type of .vtt files,\n * in addition to the default 'text/vtt' support.\n */\nadd_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 ); \n\nfunction wpse323750_secondary_mime( $check, $file, $filename, $mimes ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n // Adjust to your needs!\n $secondary_mime = [ 'vtt' => 'text/plain' ];\n\n // Run another check, but only for our secondary mime and not on core mime types.\n remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );\n $check = wp_check_filetype_and_ext( $file, $filename, $secondary_mime );\n add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );\n }\n return $check;\n}\n</code></pre>\n\n<p>Here we use the <code>wp_check_filetype_and_ext</code> filter to see if the check failed. In that case we run <code>wp_check_filetype_and_ext()</code> again but now only on our secondary mime type, disabling our filter callback in the meanwhile to avoid an infinite loop.</p>\n\n<h2>Multiple mime types for a given file extension</h2>\n\n<p>If we need to support more than two mime types for the <code>.vtt</code> files, then we can expand the above snippet with:</p>\n\n<pre><code>/**\n * Demo: Support for 'text/foo' and 'text/bar' mime types of .vtt files,\n * in addition to the default 'text/vtt' support.\n */\nadd_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n\nfunction wpse323750_multi_mimes( $check, $file, $filename, $mimes ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n // Adjust to your needs!\n $multi_mimes = [ [ 'vtt' => 'text/foo' ], [ 'vtt' => 'text/bar' ] ];\n\n // Run new checks for our custom mime types and not on core mime types.\n foreach( $multi_mimes as $mime ) {\n remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n $check = wp_check_filetype_and_ext( $file, $filename, $mime );\n add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {\n return $check;\n }\n }\n }\n return $check;\n}\n</code></pre>\n\n<p>I hope you can test it further and adjust it to your needs.</p>\n"
},
{
"answer_id": 346169,
"author": "Sergio Zaharchenko",
"author_id": 136533,
"author_profile": "https://wordpress.stackexchange.com/users/136533",
"pm_score": 2,
"selected": false,
"text": "<p>A little improved birgire's answer. Had to add multiple mime types for <code>svg</code>, but because <code>svg</code> is forbidden by default, had to add dynamic filter to <code>upload_mimes</code>:</p>\n\n<pre><code>class Multiple_Mimes {\n\n public static function init() {\n add_filter( 'wp_check_filetype_and_ext', [self::class, 'add_multiple_mime_types'], 99, 3 );\n }\n\n\n public static function add_multiple_mime_types( $check, $file, $filename ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n foreach ( self::get_allowed_mime_types() as $mime ) {\n remove_filter( 'wp_check_filetype_and_ext', [ self::class, 'add_multiple_mime_types' ], 99 );\n $mime_filter = function($mimes) use ($mime) {\n return array_merge($mimes, $mime);\n };\n\n add_filter('upload_mimes', $mime_filter, 99);\n $check = wp_check_filetype_and_ext( $file, $filename, $mime );\n remove_filter('upload_mimes', $mime_filter, 99);\n add_filter( 'wp_check_filetype_and_ext', [ self::class, 'add_multiple_mime_types' ], 99, 3 );\n if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {\n return $check;\n }\n }\n }\n\n return $check;\n }\n\n\n public static function get_allowed_mime_types(){\n return [\n [ 'svg' => 'image/svg' ],\n [ 'svg' => 'image/svg+xml' ],\n ];\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 370151,
"author": "bobbingwide",
"author_id": 77573,
"author_profile": "https://wordpress.stackexchange.com/users/77573",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem to solve where .zip files were seen as <code>application/zip</code> by PHP but detected as <code>application/x-zip-compressed</code>.</p>\n<p>My workaround was to add this new value with an invented key</p>\n<pre><code>'xzip' => '`application/x-zip-compressed';\n</code></pre>\n<p>See <a href=\"https://github.com/WordPress/gutenberg/issues/23510\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/issues/23510</a></p>\n<p>See also two WordPress TRACs:</p>\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/40175\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/40175</a></li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/46775\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/46775</a></li>\n</ul>\n"
}
]
| 2018/12/23 | [
"https://wordpress.stackexchange.com/questions/323760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60539/"
]
| I am able to create a new post but I get a generic error message `Publishing failed` if I try to publish it. Same thing if I try to edit it (or any other post).
If I try to delete the post using the `Move to trash` button, I get another error: `The response is not a valid JSON response.`
The issue only happens in the new Gutenberg interface (`wp-admin/post.php`) I am able to publish or remove the post using the "quick edit" functions on the posts list view (`wp-admin/edit.php`)
The problem occurs with all users and for all post types (I tried with posts and pages). Deactivating all plugins and visiting the permalinks page did not solve the issue. | Note the stricter mime type check since WP 5.0.1 where the file content and file extension must match. See e.g. this recent [question](https://wordpress.stackexchange.com/q/321804/26350) on the `vtt` file type.
Secondary mime type for a given file extension
----------------------------------------------
Here's a suggestion how to support a secondary mime type for a given file extension. Let's take `.vtt` as an example. The core assumes the mime type of `text/vtt` for that file extension, but the real mime type from `finfo_file()` can sometimes be `text/plain`. The `finfo_file()` seems to be somewhat [buggy](https://bugs.php.net/bug.php?id=75380). We can add a support for it as a secondary mime type with:
```
/**
* Support for 'text/plain' as the secondary mime type of .vtt files,
* in addition to the default 'text/vtt' support.
*/
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
function wpse323750_secondary_mime( $check, $file, $filename, $mimes ) {
if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {
// Adjust to your needs!
$secondary_mime = [ 'vtt' => 'text/plain' ];
// Run another check, but only for our secondary mime and not on core mime types.
remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
$check = wp_check_filetype_and_ext( $file, $filename, $secondary_mime );
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
}
return $check;
}
```
Here we use the `wp_check_filetype_and_ext` filter to see if the check failed. In that case we run `wp_check_filetype_and_ext()` again but now only on our secondary mime type, disabling our filter callback in the meanwhile to avoid an infinite loop.
Multiple mime types for a given file extension
----------------------------------------------
If we need to support more than two mime types for the `.vtt` files, then we can expand the above snippet with:
```
/**
* Demo: Support for 'text/foo' and 'text/bar' mime types of .vtt files,
* in addition to the default 'text/vtt' support.
*/
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
function wpse323750_multi_mimes( $check, $file, $filename, $mimes ) {
if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {
// Adjust to your needs!
$multi_mimes = [ [ 'vtt' => 'text/foo' ], [ 'vtt' => 'text/bar' ] ];
// Run new checks for our custom mime types and not on core mime types.
foreach( $multi_mimes as $mime ) {
remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
$check = wp_check_filetype_and_ext( $file, $filename, $mime );
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {
return $check;
}
}
}
return $check;
}
```
I hope you can test it further and adjust it to your needs. |
323,771 | <p>I've been looking for the whole day for a plugin that help me to solve my problem with my website.</p>
<p>Is there a way to create a specific form that could send a custom e-mail when the user complete it? </p>
<p>Thanks!</p>
| [
{
"answer_id": 323757,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>Note the stricter mime type check since WP 5.0.1 where the file content and file extension must match. See e.g. this recent <a href=\"https://wordpress.stackexchange.com/q/321804/26350\">question</a> on the <code>vtt</code> file type.</p>\n\n<h2>Secondary mime type for a given file extension</h2>\n\n<p>Here's a suggestion how to support a secondary mime type for a given file extension. Let's take <code>.vtt</code> as an example. The core assumes the mime type of <code>text/vtt</code> for that file extension, but the real mime type from <code>finfo_file()</code> can sometimes be <code>text/plain</code>. The <code>finfo_file()</code> seems to be somewhat <a href=\"https://bugs.php.net/bug.php?id=75380\" rel=\"noreferrer\">buggy</a>. We can add a support for it as a secondary mime type with:</p>\n\n<pre><code>/**\n * Support for 'text/plain' as the secondary mime type of .vtt files,\n * in addition to the default 'text/vtt' support.\n */\nadd_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 ); \n\nfunction wpse323750_secondary_mime( $check, $file, $filename, $mimes ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n // Adjust to your needs!\n $secondary_mime = [ 'vtt' => 'text/plain' ];\n\n // Run another check, but only for our secondary mime and not on core mime types.\n remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );\n $check = wp_check_filetype_and_ext( $file, $filename, $secondary_mime );\n add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );\n }\n return $check;\n}\n</code></pre>\n\n<p>Here we use the <code>wp_check_filetype_and_ext</code> filter to see if the check failed. In that case we run <code>wp_check_filetype_and_ext()</code> again but now only on our secondary mime type, disabling our filter callback in the meanwhile to avoid an infinite loop.</p>\n\n<h2>Multiple mime types for a given file extension</h2>\n\n<p>If we need to support more than two mime types for the <code>.vtt</code> files, then we can expand the above snippet with:</p>\n\n<pre><code>/**\n * Demo: Support for 'text/foo' and 'text/bar' mime types of .vtt files,\n * in addition to the default 'text/vtt' support.\n */\nadd_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n\nfunction wpse323750_multi_mimes( $check, $file, $filename, $mimes ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n // Adjust to your needs!\n $multi_mimes = [ [ 'vtt' => 'text/foo' ], [ 'vtt' => 'text/bar' ] ];\n\n // Run new checks for our custom mime types and not on core mime types.\n foreach( $multi_mimes as $mime ) {\n remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n $check = wp_check_filetype_and_ext( $file, $filename, $mime );\n add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {\n return $check;\n }\n }\n }\n return $check;\n}\n</code></pre>\n\n<p>I hope you can test it further and adjust it to your needs.</p>\n"
},
{
"answer_id": 346169,
"author": "Sergio Zaharchenko",
"author_id": 136533,
"author_profile": "https://wordpress.stackexchange.com/users/136533",
"pm_score": 2,
"selected": false,
"text": "<p>A little improved birgire's answer. Had to add multiple mime types for <code>svg</code>, but because <code>svg</code> is forbidden by default, had to add dynamic filter to <code>upload_mimes</code>:</p>\n\n<pre><code>class Multiple_Mimes {\n\n public static function init() {\n add_filter( 'wp_check_filetype_and_ext', [self::class, 'add_multiple_mime_types'], 99, 3 );\n }\n\n\n public static function add_multiple_mime_types( $check, $file, $filename ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n foreach ( self::get_allowed_mime_types() as $mime ) {\n remove_filter( 'wp_check_filetype_and_ext', [ self::class, 'add_multiple_mime_types' ], 99 );\n $mime_filter = function($mimes) use ($mime) {\n return array_merge($mimes, $mime);\n };\n\n add_filter('upload_mimes', $mime_filter, 99);\n $check = wp_check_filetype_and_ext( $file, $filename, $mime );\n remove_filter('upload_mimes', $mime_filter, 99);\n add_filter( 'wp_check_filetype_and_ext', [ self::class, 'add_multiple_mime_types' ], 99, 3 );\n if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {\n return $check;\n }\n }\n }\n\n return $check;\n }\n\n\n public static function get_allowed_mime_types(){\n return [\n [ 'svg' => 'image/svg' ],\n [ 'svg' => 'image/svg+xml' ],\n ];\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 370151,
"author": "bobbingwide",
"author_id": 77573,
"author_profile": "https://wordpress.stackexchange.com/users/77573",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem to solve where .zip files were seen as <code>application/zip</code> by PHP but detected as <code>application/x-zip-compressed</code>.</p>\n<p>My workaround was to add this new value with an invented key</p>\n<pre><code>'xzip' => '`application/x-zip-compressed';\n</code></pre>\n<p>See <a href=\"https://github.com/WordPress/gutenberg/issues/23510\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/issues/23510</a></p>\n<p>See also two WordPress TRACs:</p>\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/40175\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/40175</a></li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/46775\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/46775</a></li>\n</ul>\n"
}
]
| 2018/12/23 | [
"https://wordpress.stackexchange.com/questions/323771",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/148532/"
]
| I've been looking for the whole day for a plugin that help me to solve my problem with my website.
Is there a way to create a specific form that could send a custom e-mail when the user complete it?
Thanks! | Note the stricter mime type check since WP 5.0.1 where the file content and file extension must match. See e.g. this recent [question](https://wordpress.stackexchange.com/q/321804/26350) on the `vtt` file type.
Secondary mime type for a given file extension
----------------------------------------------
Here's a suggestion how to support a secondary mime type for a given file extension. Let's take `.vtt` as an example. The core assumes the mime type of `text/vtt` for that file extension, but the real mime type from `finfo_file()` can sometimes be `text/plain`. The `finfo_file()` seems to be somewhat [buggy](https://bugs.php.net/bug.php?id=75380). We can add a support for it as a secondary mime type with:
```
/**
* Support for 'text/plain' as the secondary mime type of .vtt files,
* in addition to the default 'text/vtt' support.
*/
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
function wpse323750_secondary_mime( $check, $file, $filename, $mimes ) {
if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {
// Adjust to your needs!
$secondary_mime = [ 'vtt' => 'text/plain' ];
// Run another check, but only for our secondary mime and not on core mime types.
remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
$check = wp_check_filetype_and_ext( $file, $filename, $secondary_mime );
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
}
return $check;
}
```
Here we use the `wp_check_filetype_and_ext` filter to see if the check failed. In that case we run `wp_check_filetype_and_ext()` again but now only on our secondary mime type, disabling our filter callback in the meanwhile to avoid an infinite loop.
Multiple mime types for a given file extension
----------------------------------------------
If we need to support more than two mime types for the `.vtt` files, then we can expand the above snippet with:
```
/**
* Demo: Support for 'text/foo' and 'text/bar' mime types of .vtt files,
* in addition to the default 'text/vtt' support.
*/
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
function wpse323750_multi_mimes( $check, $file, $filename, $mimes ) {
if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {
// Adjust to your needs!
$multi_mimes = [ [ 'vtt' => 'text/foo' ], [ 'vtt' => 'text/bar' ] ];
// Run new checks for our custom mime types and not on core mime types.
foreach( $multi_mimes as $mime ) {
remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
$check = wp_check_filetype_and_ext( $file, $filename, $mime );
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {
return $check;
}
}
}
return $check;
}
```
I hope you can test it further and adjust it to your needs. |
323,807 | <p>I have recently decided it would be best if i disable the built in wordpress cron function and move to the system cron which will activate the wordpress cron every 15 minutes. </p>
<p>I am wondering which way is best and what the differences are performance wise etc?</p>
<p>The two ways I have seen this done are:</p>
<pre><code>curl http://example.com/wp-cron.php?doing_wp_cron > /dev/null 2>&1
</code></pre>
<p>and</p>
<pre><code>cd /var/www/example.com/htdocs; php /var/www/example.com/htdocs/wp-cron.php?doing_wp_cron > /dev/null 2>&1
</code></pre>
<p>Which way is better, and what are the benefits of a certain way?<br>
Any advice would be great and appreciated! </p>
| [
{
"answer_id": 323757,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>Note the stricter mime type check since WP 5.0.1 where the file content and file extension must match. See e.g. this recent <a href=\"https://wordpress.stackexchange.com/q/321804/26350\">question</a> on the <code>vtt</code> file type.</p>\n\n<h2>Secondary mime type for a given file extension</h2>\n\n<p>Here's a suggestion how to support a secondary mime type for a given file extension. Let's take <code>.vtt</code> as an example. The core assumes the mime type of <code>text/vtt</code> for that file extension, but the real mime type from <code>finfo_file()</code> can sometimes be <code>text/plain</code>. The <code>finfo_file()</code> seems to be somewhat <a href=\"https://bugs.php.net/bug.php?id=75380\" rel=\"noreferrer\">buggy</a>. We can add a support for it as a secondary mime type with:</p>\n\n<pre><code>/**\n * Support for 'text/plain' as the secondary mime type of .vtt files,\n * in addition to the default 'text/vtt' support.\n */\nadd_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 ); \n\nfunction wpse323750_secondary_mime( $check, $file, $filename, $mimes ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n // Adjust to your needs!\n $secondary_mime = [ 'vtt' => 'text/plain' ];\n\n // Run another check, but only for our secondary mime and not on core mime types.\n remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );\n $check = wp_check_filetype_and_ext( $file, $filename, $secondary_mime );\n add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );\n }\n return $check;\n}\n</code></pre>\n\n<p>Here we use the <code>wp_check_filetype_and_ext</code> filter to see if the check failed. In that case we run <code>wp_check_filetype_and_ext()</code> again but now only on our secondary mime type, disabling our filter callback in the meanwhile to avoid an infinite loop.</p>\n\n<h2>Multiple mime types for a given file extension</h2>\n\n<p>If we need to support more than two mime types for the <code>.vtt</code> files, then we can expand the above snippet with:</p>\n\n<pre><code>/**\n * Demo: Support for 'text/foo' and 'text/bar' mime types of .vtt files,\n * in addition to the default 'text/vtt' support.\n */\nadd_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n\nfunction wpse323750_multi_mimes( $check, $file, $filename, $mimes ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n // Adjust to your needs!\n $multi_mimes = [ [ 'vtt' => 'text/foo' ], [ 'vtt' => 'text/bar' ] ];\n\n // Run new checks for our custom mime types and not on core mime types.\n foreach( $multi_mimes as $mime ) {\n remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n $check = wp_check_filetype_and_ext( $file, $filename, $mime );\n add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );\n if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {\n return $check;\n }\n }\n }\n return $check;\n}\n</code></pre>\n\n<p>I hope you can test it further and adjust it to your needs.</p>\n"
},
{
"answer_id": 346169,
"author": "Sergio Zaharchenko",
"author_id": 136533,
"author_profile": "https://wordpress.stackexchange.com/users/136533",
"pm_score": 2,
"selected": false,
"text": "<p>A little improved birgire's answer. Had to add multiple mime types for <code>svg</code>, but because <code>svg</code> is forbidden by default, had to add dynamic filter to <code>upload_mimes</code>:</p>\n\n<pre><code>class Multiple_Mimes {\n\n public static function init() {\n add_filter( 'wp_check_filetype_and_ext', [self::class, 'add_multiple_mime_types'], 99, 3 );\n }\n\n\n public static function add_multiple_mime_types( $check, $file, $filename ) {\n if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {\n foreach ( self::get_allowed_mime_types() as $mime ) {\n remove_filter( 'wp_check_filetype_and_ext', [ self::class, 'add_multiple_mime_types' ], 99 );\n $mime_filter = function($mimes) use ($mime) {\n return array_merge($mimes, $mime);\n };\n\n add_filter('upload_mimes', $mime_filter, 99);\n $check = wp_check_filetype_and_ext( $file, $filename, $mime );\n remove_filter('upload_mimes', $mime_filter, 99);\n add_filter( 'wp_check_filetype_and_ext', [ self::class, 'add_multiple_mime_types' ], 99, 3 );\n if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {\n return $check;\n }\n }\n }\n\n return $check;\n }\n\n\n public static function get_allowed_mime_types(){\n return [\n [ 'svg' => 'image/svg' ],\n [ 'svg' => 'image/svg+xml' ],\n ];\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 370151,
"author": "bobbingwide",
"author_id": 77573,
"author_profile": "https://wordpress.stackexchange.com/users/77573",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem to solve where .zip files were seen as <code>application/zip</code> by PHP but detected as <code>application/x-zip-compressed</code>.</p>\n<p>My workaround was to add this new value with an invented key</p>\n<pre><code>'xzip' => '`application/x-zip-compressed';\n</code></pre>\n<p>See <a href=\"https://github.com/WordPress/gutenberg/issues/23510\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/issues/23510</a></p>\n<p>See also two WordPress TRACs:</p>\n<ul>\n<li><a href=\"https://core.trac.wordpress.org/ticket/40175\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/40175</a></li>\n<li><a href=\"https://core.trac.wordpress.org/ticket/46775\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/46775</a></li>\n</ul>\n"
}
]
| 2018/12/24 | [
"https://wordpress.stackexchange.com/questions/323807",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157634/"
]
| I have recently decided it would be best if i disable the built in wordpress cron function and move to the system cron which will activate the wordpress cron every 15 minutes.
I am wondering which way is best and what the differences are performance wise etc?
The two ways I have seen this done are:
```
curl http://example.com/wp-cron.php?doing_wp_cron > /dev/null 2>&1
```
and
```
cd /var/www/example.com/htdocs; php /var/www/example.com/htdocs/wp-cron.php?doing_wp_cron > /dev/null 2>&1
```
Which way is better, and what are the benefits of a certain way?
Any advice would be great and appreciated! | Note the stricter mime type check since WP 5.0.1 where the file content and file extension must match. See e.g. this recent [question](https://wordpress.stackexchange.com/q/321804/26350) on the `vtt` file type.
Secondary mime type for a given file extension
----------------------------------------------
Here's a suggestion how to support a secondary mime type for a given file extension. Let's take `.vtt` as an example. The core assumes the mime type of `text/vtt` for that file extension, but the real mime type from `finfo_file()` can sometimes be `text/plain`. The `finfo_file()` seems to be somewhat [buggy](https://bugs.php.net/bug.php?id=75380). We can add a support for it as a secondary mime type with:
```
/**
* Support for 'text/plain' as the secondary mime type of .vtt files,
* in addition to the default 'text/vtt' support.
*/
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
function wpse323750_secondary_mime( $check, $file, $filename, $mimes ) {
if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {
// Adjust to your needs!
$secondary_mime = [ 'vtt' => 'text/plain' ];
// Run another check, but only for our secondary mime and not on core mime types.
remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
$check = wp_check_filetype_and_ext( $file, $filename, $secondary_mime );
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_secondary_mime', 99, 4 );
}
return $check;
}
```
Here we use the `wp_check_filetype_and_ext` filter to see if the check failed. In that case we run `wp_check_filetype_and_ext()` again but now only on our secondary mime type, disabling our filter callback in the meanwhile to avoid an infinite loop.
Multiple mime types for a given file extension
----------------------------------------------
If we need to support more than two mime types for the `.vtt` files, then we can expand the above snippet with:
```
/**
* Demo: Support for 'text/foo' and 'text/bar' mime types of .vtt files,
* in addition to the default 'text/vtt' support.
*/
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
function wpse323750_multi_mimes( $check, $file, $filename, $mimes ) {
if ( empty( $check['ext'] ) && empty( $check['type'] ) ) {
// Adjust to your needs!
$multi_mimes = [ [ 'vtt' => 'text/foo' ], [ 'vtt' => 'text/bar' ] ];
// Run new checks for our custom mime types and not on core mime types.
foreach( $multi_mimes as $mime ) {
remove_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
$check = wp_check_filetype_and_ext( $file, $filename, $mime );
add_filter( 'wp_check_filetype_and_ext', 'wpse323750_multi_mimes', 99, 4 );
if ( ! empty( $check['ext'] ) || ! empty( $check['type'] ) ) {
return $check;
}
}
}
return $check;
}
```
I hope you can test it further and adjust it to your needs. |
323,927 | <p>I'm looking to customize the "There is a new version of XYZ available." text on the Plugins list page. I know the code is in <a href="https://github.com/WordPress/WordPress/blob/56c162fbc9867f923862f64f1b4570d885f1ff03/wp-admin/includes/update.php#L592" rel="noreferrer">wp-admin/includes/update.php</a>, however I'm not certain how to call this out or pull it out in a filter/callback. Basically, I want to be able to customize this message in a plugin. Thanks for any help or direction!</p>
| [
{
"answer_id": 323929,
"author": "Jory Hogeveen",
"author_id": 99325,
"author_profile": "https://wordpress.stackexchange.com/users/99325",
"pm_score": 0,
"selected": false,
"text": "<p>This text can't be filtered afaik.\nYou can append text though: <a href=\"https://developer.wordpress.org/reference/hooks/in_plugin_update_message-file/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/in_plugin_update_message-file/</a></p>\n"
},
{
"answer_id": 323939,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Since the text is processed by <code>_()</code> function, then, of course, you can modify it using <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext\" rel=\"nofollow noreferrer\"><code>gettext</code></a> filter.</p>\n\n<pre><code>function change_update_notification_msg( $translated_text, $untranslated_text, $domain ) \n{\n\n if ( is_admin() ) {\n $texts = array(\n 'There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a>.' => 'My custom notification. There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a>.',\n 'There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>' => 'My custom notification. There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>',\n 'There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a> or <a href=\"%5$s\" %6$s>update now</a>.' => 'My custom notification. There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a> or <a href=\"%5$s\" %6$s>update now</a>.'\n );\n\n if ( array_key_exists( $untranslated_text, $texts ) ) {\n return $texts[$untranslated_text];\n }\n }\n\n return $translated_text;\n}\nadd_filter( 'gettext', 'change_update_notification_msg', 20, 3 );\n</code></pre>\n"
}
]
| 2018/12/26 | [
"https://wordpress.stackexchange.com/questions/323927",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157755/"
]
| I'm looking to customize the "There is a new version of XYZ available." text on the Plugins list page. I know the code is in [wp-admin/includes/update.php](https://github.com/WordPress/WordPress/blob/56c162fbc9867f923862f64f1b4570d885f1ff03/wp-admin/includes/update.php#L592), however I'm not certain how to call this out or pull it out in a filter/callback. Basically, I want to be able to customize this message in a plugin. Thanks for any help or direction! | Since the text is processed by `_()` function, then, of course, you can modify it using [`gettext`](https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext) filter.
```
function change_update_notification_msg( $translated_text, $untranslated_text, $domain )
{
if ( is_admin() ) {
$texts = array(
'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>.' => 'My custom notification. There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>.',
'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>' => 'My custom notification. There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>',
'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a> or <a href="%5$s" %6$s>update now</a>.' => 'My custom notification. There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a> or <a href="%5$s" %6$s>update now</a>.'
);
if ( array_key_exists( $untranslated_text, $texts ) ) {
return $texts[$untranslated_text];
}
}
return $translated_text;
}
add_filter( 'gettext', 'change_update_notification_msg', 20, 3 );
``` |
323,932 | <p>I'm using a theme for my WordPress which uses 'Raleway' and it requests (13 requests in gtmetrix waterfall) it from Google fonts API. I want to keep using the font. However, I'm trying to reduce the number of requests and the size of my page. Can I include/integrate the fonts on my website so the browser won't have to execute any external requests?
many thanks </p>
| [
{
"answer_id": 323929,
"author": "Jory Hogeveen",
"author_id": 99325,
"author_profile": "https://wordpress.stackexchange.com/users/99325",
"pm_score": 0,
"selected": false,
"text": "<p>This text can't be filtered afaik.\nYou can append text though: <a href=\"https://developer.wordpress.org/reference/hooks/in_plugin_update_message-file/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/in_plugin_update_message-file/</a></p>\n"
},
{
"answer_id": 323939,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>Since the text is processed by <code>_()</code> function, then, of course, you can modify it using <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext\" rel=\"nofollow noreferrer\"><code>gettext</code></a> filter.</p>\n\n<pre><code>function change_update_notification_msg( $translated_text, $untranslated_text, $domain ) \n{\n\n if ( is_admin() ) {\n $texts = array(\n 'There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a>.' => 'My custom notification. There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a>.',\n 'There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>' => 'My custom notification. There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>',\n 'There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a> or <a href=\"%5$s\" %6$s>update now</a>.' => 'My custom notification. There is a new version of %1$s available. <a href=\"%2$s\" %3$s>View version %4$s details</a> or <a href=\"%5$s\" %6$s>update now</a>.'\n );\n\n if ( array_key_exists( $untranslated_text, $texts ) ) {\n return $texts[$untranslated_text];\n }\n }\n\n return $translated_text;\n}\nadd_filter( 'gettext', 'change_update_notification_msg', 20, 3 );\n</code></pre>\n"
}
]
| 2018/12/26 | [
"https://wordpress.stackexchange.com/questions/323932",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157759/"
]
| I'm using a theme for my WordPress which uses 'Raleway' and it requests (13 requests in gtmetrix waterfall) it from Google fonts API. I want to keep using the font. However, I'm trying to reduce the number of requests and the size of my page. Can I include/integrate the fonts on my website so the browser won't have to execute any external requests?
many thanks | Since the text is processed by `_()` function, then, of course, you can modify it using [`gettext`](https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext) filter.
```
function change_update_notification_msg( $translated_text, $untranslated_text, $domain )
{
if ( is_admin() ) {
$texts = array(
'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>.' => 'My custom notification. There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>.',
'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>' => 'My custom notification. There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>',
'There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a> or <a href="%5$s" %6$s>update now</a>.' => 'My custom notification. There is a new version of %1$s available. <a href="%2$s" %3$s>View version %4$s details</a> or <a href="%5$s" %6$s>update now</a>.'
);
if ( array_key_exists( $untranslated_text, $texts ) ) {
return $texts[$untranslated_text];
}
}
return $translated_text;
}
add_filter( 'gettext', 'change_update_notification_msg', 20, 3 );
``` |
324,008 | <p>Previously Chrome, Firefox, Edge, and other browsers showed <a href="https://wisconsinwetlands.org" rel="nofollow noreferrer">our site</a> as fully SSL/HTTPS secure. For some reason, they now warn about mixed content.</p>
<p>But the content in question seems to be secure.</p>
<p>This only affects a subset of the images on each page. Here's one example—a footer image. The image is entered like this on the WP back-end:</p>
<pre><code><img src="https://widgets.guidestar.org/gximage2?o=7583405&l=v4" />
</code></pre>
<p>Firebug > Inspect Element shows:</p>
<pre><code><img src="https://widgets.guidestar.org/gximage2?o=7583405&l=v4">
</code></pre>
<p>Firefox > View Source shows:</p>
<pre><code><img src="https://widgets.guidestar.org/gximage2?o=7583405&l=v4" />
</code></pre>
<p>But Firebug > Network tab > Protocol column reports the image as:</p>
<pre><code>HTTP/1.1
</code></pre>
<p>Chrome developer tools show the same results. What could cause this problem?</p>
| [
{
"answer_id": 324009,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>301 redirects are the reason.</p>\n\n<p>In your site you have this image:</p>\n\n<p><code>https://www.wisconsinwetlands.org/wp-content/uploads/2015/04/mainheader7-1.jpg</code></p>\n\n<p>So it looks like HTTPS, but... If you go and visit that link, you'll get redirected with 301 to:</p>\n\n<p><code>http://wisconsinwetlands.org/wp-content/uploads/2015/04/mainheader7-1.jpg</code></p>\n\n<p>So it's not over HTTPS.</p>\n"
},
{
"answer_id": 324018,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 3,
"selected": true,
"text": "<p>You have \"www.wisconsinwetlands.org\" URLs redirecting to insecure \"<a href=\"http://wisconsinwetlands.org\" rel=\"nofollow noreferrer\">http://wisconsinwetlands.org</a>\".</p>\n\n<p>The cases you have used these is in the images on the page. Every image that is set as \"<a href=\"https://www\" rel=\"nofollow noreferrer\">https://www</a>.\" redirects to the insecure version.</p>\n\n<p>So while you do need to fix that and correctly configure your setup so that both \"www\" and non-www URLs are secure, you could quickly solve the problem by removing the www from your image URLs.</p>\n"
}
]
| 2018/12/27 | [
"https://wordpress.stackexchange.com/questions/324008",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3864/"
]
| Previously Chrome, Firefox, Edge, and other browsers showed [our site](https://wisconsinwetlands.org) as fully SSL/HTTPS secure. For some reason, they now warn about mixed content.
But the content in question seems to be secure.
This only affects a subset of the images on each page. Here's one example—a footer image. The image is entered like this on the WP back-end:
```
<img src="https://widgets.guidestar.org/gximage2?o=7583405&l=v4" />
```
Firebug > Inspect Element shows:
```
<img src="https://widgets.guidestar.org/gximage2?o=7583405&l=v4">
```
Firefox > View Source shows:
```
<img src="https://widgets.guidestar.org/gximage2?o=7583405&l=v4" />
```
But Firebug > Network tab > Protocol column reports the image as:
```
HTTP/1.1
```
Chrome developer tools show the same results. What could cause this problem? | You have "www.wisconsinwetlands.org" URLs redirecting to insecure "<http://wisconsinwetlands.org>".
The cases you have used these is in the images on the page. Every image that is set as "<https://www>." redirects to the insecure version.
So while you do need to fix that and correctly configure your setup so that both "www" and non-www URLs are secure, you could quickly solve the problem by removing the www from your image URLs. |
324,043 | <p>I am trying to remove two links from users dashboard keeping it on admin but it goes off on both user and admin.</p>
<p>One i need to remove from user dashboard and other is contact form plugin link contact.</p>
<p>I am trying t o use below code.also post link goes off.</p>
<pre><code> add_filter( 'admin_menu', 'remove_menus', 99 );
if (!current_user_can('manage_options')) {
add_action('wp_dashboard_setup', 'remove_menus' );
}
function remove_menus(){
remove_menu_page( 'index.php' ); //dashboard
}
</code></pre>
| [
{
"answer_id": 324009,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>301 redirects are the reason.</p>\n\n<p>In your site you have this image:</p>\n\n<p><code>https://www.wisconsinwetlands.org/wp-content/uploads/2015/04/mainheader7-1.jpg</code></p>\n\n<p>So it looks like HTTPS, but... If you go and visit that link, you'll get redirected with 301 to:</p>\n\n<p><code>http://wisconsinwetlands.org/wp-content/uploads/2015/04/mainheader7-1.jpg</code></p>\n\n<p>So it's not over HTTPS.</p>\n"
},
{
"answer_id": 324018,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 3,
"selected": true,
"text": "<p>You have \"www.wisconsinwetlands.org\" URLs redirecting to insecure \"<a href=\"http://wisconsinwetlands.org\" rel=\"nofollow noreferrer\">http://wisconsinwetlands.org</a>\".</p>\n\n<p>The cases you have used these is in the images on the page. Every image that is set as \"<a href=\"https://www\" rel=\"nofollow noreferrer\">https://www</a>.\" redirects to the insecure version.</p>\n\n<p>So while you do need to fix that and correctly configure your setup so that both \"www\" and non-www URLs are secure, you could quickly solve the problem by removing the www from your image URLs.</p>\n"
}
]
| 2018/12/28 | [
"https://wordpress.stackexchange.com/questions/324043",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157850/"
]
| I am trying to remove two links from users dashboard keeping it on admin but it goes off on both user and admin.
One i need to remove from user dashboard and other is contact form plugin link contact.
I am trying t o use below code.also post link goes off.
```
add_filter( 'admin_menu', 'remove_menus', 99 );
if (!current_user_can('manage_options')) {
add_action('wp_dashboard_setup', 'remove_menus' );
}
function remove_menus(){
remove_menu_page( 'index.php' ); //dashboard
}
``` | You have "www.wisconsinwetlands.org" URLs redirecting to insecure "<http://wisconsinwetlands.org>".
The cases you have used these is in the images on the page. Every image that is set as "<https://www>." redirects to the insecure version.
So while you do need to fix that and correctly configure your setup so that both "www" and non-www URLs are secure, you could quickly solve the problem by removing the www from your image URLs. |
324,051 | <p>I would like to add <code>edit.php</code> to user dashboard who registers as subscriber on a website. Code which i using is </p>
<pre><code>add_action( 'admin_menu', 'remove_menus' );
function remove_menus(){
if(!current_user_can('subscriber'))
add_menu_page( 'edit.php' ); //dashboard
}
</code></pre>
<p>even has administrator instead subscriber didn't work</p>
| [
{
"answer_id": 324053,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 0,
"selected": false,
"text": "<p>Please update the code as below </p>\n\n<pre><code>add_action( 'admin_menu', 'remove_menus' );\nfunction remove_menus(){\n $user = wp_get_current_user();\n $role = ( array ) $user->roles;\n if($role[0]==subscriber)\n add_menu_page( 'edit.php' ); //dashboard\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 324065,
"author": "Debabrata Karfa",
"author_id": 122064,
"author_profile": "https://wordpress.stackexchange.com/users/122064",
"pm_score": -1,
"selected": false,
"text": "<p><code>\nfunction add_custom_caps() {\n global $wp_roles;\n if ( ! isset( $wp_roles ) ) {\n $wp_roles = new WP_Roles();\n }\n $role = get_role( 'subscriber' );\n foreach ($wp_roles->get_role('editor')->capabilities as $key => $value){\n $role->add_cap( $key );\n }\n}\nadd_action( 'admin_init', 'add_custom_caps');\n</code></p>\n\n<p>It will clone all capability of Editor role and add them to Subscriber role</p>\n"
}
]
| 2018/12/28 | [
"https://wordpress.stackexchange.com/questions/324051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157850/"
]
| I would like to add `edit.php` to user dashboard who registers as subscriber on a website. Code which i using is
```
add_action( 'admin_menu', 'remove_menus' );
function remove_menus(){
if(!current_user_can('subscriber'))
add_menu_page( 'edit.php' ); //dashboard
}
```
even has administrator instead subscriber didn't work | Please update the code as below
```
add_action( 'admin_menu', 'remove_menus' );
function remove_menus(){
$user = wp_get_current_user();
$role = ( array ) $user->roles;
if($role[0]==subscriber)
add_menu_page( 'edit.php' ); //dashboard
```
} |
324,077 | <p>I have disabled the registered users to select the admin color scheme as I want all of them to use the 'Coffee' scheme. I have also made the 'Coffee' color scheme the default one for registered users. </p>
<p>However, WordPress still shows the default (black) admin bar for nonregistered/nonlogged users of the website.</p>
<p>Do you know how I can force it show the admin bar in the 'Coffee' color scheme even in those cases?</p>
<p>Thank you very much in advance.</p>
| [
{
"answer_id": 324053,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 0,
"selected": false,
"text": "<p>Please update the code as below </p>\n\n<pre><code>add_action( 'admin_menu', 'remove_menus' );\nfunction remove_menus(){\n $user = wp_get_current_user();\n $role = ( array ) $user->roles;\n if($role[0]==subscriber)\n add_menu_page( 'edit.php' ); //dashboard\n</code></pre>\n\n<p>}</p>\n"
},
{
"answer_id": 324065,
"author": "Debabrata Karfa",
"author_id": 122064,
"author_profile": "https://wordpress.stackexchange.com/users/122064",
"pm_score": -1,
"selected": false,
"text": "<p><code>\nfunction add_custom_caps() {\n global $wp_roles;\n if ( ! isset( $wp_roles ) ) {\n $wp_roles = new WP_Roles();\n }\n $role = get_role( 'subscriber' );\n foreach ($wp_roles->get_role('editor')->capabilities as $key => $value){\n $role->add_cap( $key );\n }\n}\nadd_action( 'admin_init', 'add_custom_caps');\n</code></p>\n\n<p>It will clone all capability of Editor role and add them to Subscriber role</p>\n"
}
]
| 2018/12/28 | [
"https://wordpress.stackexchange.com/questions/324077",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110642/"
]
| I have disabled the registered users to select the admin color scheme as I want all of them to use the 'Coffee' scheme. I have also made the 'Coffee' color scheme the default one for registered users.
However, WordPress still shows the default (black) admin bar for nonregistered/nonlogged users of the website.
Do you know how I can force it show the admin bar in the 'Coffee' color scheme even in those cases?
Thank you very much in advance. | Please update the code as below
```
add_action( 'admin_menu', 'remove_menus' );
function remove_menus(){
$user = wp_get_current_user();
$role = ( array ) $user->roles;
if($role[0]==subscriber)
add_menu_page( 'edit.php' ); //dashboard
```
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.