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>&lt;?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>&lt;html&gt; &lt;body&gt; &lt;script&gt; &lt;!-- This is the dependent code that should run first and is put directly into the HTML file by the third party Plugin provider --&gt; var greetingnow = "Good Morning!"; alert(greetingnow); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </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_s...
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 =&gt; $value) { if ($files['name'][$key]) { $file = array( 'name' =&gt; $files['name'][$key], 'type' =&gt; $files['type'][$key], 'tmp_name' =&gt; $files['tmp_name'][$key], 'error' =&gt; $files['error'][$key], 'size' =&gt; $files['size'][$key] ); $_FILES = array("upload_attachment" =&gt; $file); foreach ($_FILES as $file =&gt; $array) { $newupload = my_handle_attachment($file,$post_id); update_post_meta($post_id, array_push($post_id, '_product_image_gallery',$newupload)); } } } } &lt;input type="file" name="upload_attachment[]" multiple="multiple" /&gt; </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_s...
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_s...
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=\"nofoll...
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') ) &amp;&amp; in_array( 'subscriber', (array) $user-&gt;roles ) ) { /* Is subscriber, is in category Locked, has amount of posts */ echo do_shortcode('[shortcode_name]'); } else if (( in_category('Locked') ) &amp;&amp; in_array( 'subscriber', (array) $user-&gt;roles ) ) { /* Is subscriber, is in category Locked, has NO amount of posts */ echo '&lt;div id="locked"&gt; You are subscriber without number of posts! &lt;/div&gt;'; } else if ( in_category('Locked') ) { /* Is NOT subscriber, is in category Locked, has NO amount of posts */ echo '&lt;div id="locked"&gt; Login or register pal! &lt;/div&gt;'; } 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') ) &amp;&amp; in_array( 'subscriber', (array) $user-&gt;roles ) ) &amp;&amp; ????? </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 nor...
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'...
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. [![VSCode screen showing sidebar with the installed plugin and the editor screen with the code from underneath in the question](https://i.stack.imgur.com/qdEYn.png)](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'...
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>&lt;sup&gt;&lt;/sup&gt;</code> and <code>&lt;sub&gt;&lt;/sub&gt;</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 ) =&gt; { return ( props ) =&gt; { return ( &lt;Fragment&gt; &lt;BlockControls&gt; // what should I enter here? &lt;/BlockControls&gt; &lt;BlockEdit { ...props } /&gt; &lt;/Fragment&gt; ); }; }, "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>&lt;BlockControls&gt;</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, th...
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: [![enter image description here](https://i.stack.imgur.com/3oG6s.png)](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 g...
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' =&gt; 'date_event', 'orderby' =&gt; 'meta_value_num', 'order' =&gt; '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> ...
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 ...
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...
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>Wor...
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 : abcde@gmail.com 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\...
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 : abcde@gmail.com 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<...
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<...
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-&gt;prepare('SELECT ID FROM ' . $ignore_url_table_name . " where url LIKE '%%%s%%'", $urlRequested); $wpdb-&gt;get_row($sql); if ($wpdb-&gt;num_rows &gt; 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-&gt;prepare('SELECT ID FROM ' . $ignore_url_table_name . " where url LIKE '%s'", '%' . $wpdb-&gt;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<...
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 i...
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>&lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;?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'); ?&gt; &lt;div class="col col-md-flex-6 col-lg-flex-3 "&gt; &lt;picture class="cat-agrupados-img"&gt; &lt;source media="(min-width: 768px)" srcset="&lt;?php echo esc_url($thumbail); ?&gt;"&gt; &lt;img src="&lt;?php echo esc_url($medium);?&gt;" alt="&lt;?php the_title(); ?&gt;"&gt; &lt;/picture&gt; &lt;h2 class="cat-agrupados-titulo-pedido"&gt;Pedido agrupado en &lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;p class="cat-fecha-publicacion"&gt;Fecha de publicación: &lt;strong&gt;&lt;?php the_date(); ?&gt;&lt;/strong&gt;&lt;/p&gt; &lt;p class="cat-agrupados-zona"&gt;Zonas: &lt;strong&gt;&lt;?php echo get_post_meta( get_the_ID(), 'yourprefix_agrupados_poblaciones', true ); ?&gt;&lt;/strong&gt;&lt;/p&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" class="cat-agrupados-link"&gt;Ver pedido agrupado&lt;/a&gt; &lt;/div&gt; &lt;!--cierre columna--&gt; &lt;?php endwhile; endif; ?&gt; </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 i...
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> &lt;?php wp_list_categories( array( 'title_li' =&gt; '', 'child_of' =&gt; 15, ) ); ?&gt; </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 i...
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 i...
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 i...
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><...
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...
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-&gt;add_setting('ion', array( 'sanitize_callback' =&gt; 'ion_checkbox' )); $wp_customize-&gt;add_control(new WP_Customize_Control($wp_customize, 'ion', array( 'label' =&gt; 'Check', 'type' =&gt; 'checkbox', 'section' =&gt; 'search_submit_section', 'settings' =&gt; '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 nee...
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&gt;*', ''); </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 nor...
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 glo...
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<pr...
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> &lt;div class=&quot;visible-only-if-sent&quot;&gt; &lt;a href=&quot;demo.ogi.co.uk/download/1323&quot; class=&quot;button big_large_full_width center default&quot;&gt;Download CVM10-Lite &lt;/a&gt; &lt;/div&gt; </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( 'wpcf7sub...
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' =&gt; __('Foo'), 'set_featured_image' =&gt; __('Set Foo'), 'remove_featured_image' =&gt; __('Remove Foo'), 'use_featured_image' =&gt; __('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 followi...
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-&gt;get_id()); $new_order-&gt;calculate_totals(); $new_order-&gt;save_meta_data(); $new_order-&gt;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-&gt;get_items() as $item){ $new_order-&gt;add_item($item); } $new_order-&gt;apply_changes(); $new_order-&gt;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 followi...
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() ) {...
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>&lt;?php $holidays = get_sub_field('holidays'); if( $holidays ): ?&gt; &lt;?php foreach( $holidays as $holiday): ?&gt; &lt;?php setup_postdata($holiday); ?&gt; &lt;a href="&lt;?php echo get_permalink( $holiday-&gt;ID ); ?&gt;"&gt; &lt;?php echo get_the_title( $holiday-&gt;ID ); ?&gt; &lt;/a&gt; &lt;?php endforeach; ?&gt; &lt;?php wp_reset_postdata(); ?&gt; </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() ) {...
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' =&gt; -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$use...
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. [![enter image description here](https://i.stack.imgur.com/JrDtT.jpg)](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' =&gt; array( 'relation' =&gt; 'AND', array( 'key'=&gt;'first_name', 'value' =&gt; $pieces[0], 'compare' =&gt; '=' ), array( 'key' =&gt; 'last_name', 'value' =&gt; $pieces[1], 'compare' =&gt; '=' ) ), 'number' =&gt; 1, 'count_total' =&gt; 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 pa...
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 y...
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><co...
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>&lt;p&gt;Tony (Property Manager)&lt;/p&gt;</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><co...
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 choo...
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: [![Gutenberg editor showing custom font sizes for a paragraph in a dropdown menu](https://i.stack.imgur.com/bT2cV.png)](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 ...
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 [![enter image description here](https://i.stack.imgur.com/IbMma.png)](https://i.stack.imgur.com/IbMma.png) On another site I cannot see "Store uploads in this folder" option in Media Settings [![enter image description here](https://i.stack.imgur.com/5tGIR.png)](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: [![enter image description here](https://i.stack.imgur.com/aVQXH.png)](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: [![enter image description here](https://i.stack.imgur.com/bCIfT.png)](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-&gt;id, 'pa_collection'); foreach ($collection_values as $collection_value){ echo '&lt;h2 class="collection_title"&gt;&lt;a href="'.get_term_link($collection_value-&gt;slug, $collection_value-&gt;taxonomy).'"&gt;'.$collection_value-&gt;name.'&lt;/a&gt;&lt;/h2&gt;'; } </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 ...
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: [![enter image description here](https://i.stack.imgur.com/aVQXH.png)](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: [![enter image description here](https://i.stack.imgur.com/bCIfT.png)](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 ...
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: [![enter image description here](https://i.stack.imgur.com/aVQXH.png)](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: [![enter image description here](https://i.stack.imgur.com/bCIfT.png)](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-&gt;parent_file) &amp;&amp; ('edit.php?post_type=certificate'==$screen-&gt;parent_file)) { ?&gt; &lt;input type="submit" name="export_all_posts" id="export_all_posts" class="button button-primary" value="Export All Posts"&gt; &lt;script type="text/javascript"&gt; jQuery(function($) { $('#export_all_posts').insertAfter('#post-query-submit'); }); &lt;/script&gt; &lt;?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' =&gt; 'certificate', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'list', 'field' =&gt; 'slug', 'terms' =&gt; $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 ...
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: [![enter image description here](https://i.stack.imgur.com/aVQXH.png)](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: [![enter image description here](https://i.stack.imgur.com/bCIfT.png)](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'=&gt;9, 'post_type'=&gt;'product_name', 'order' =&gt; 'ASC', 'brand_name' =&gt; $title, /*brand_name is my custom field name*/ 'paged' =&gt; 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...
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 h...
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()-&gt;cart-&gt;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"]=&gt; array(1) { [0]=&gt; int(39) } /// another stuff in the array ["category_ids"]=&gt; array(2) { [0]=&gt; int(32) [1]=&gt; 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()-&gt;cart-&gt;get_cart()-&gt;category_ids</code> but this return <code>NULL</code></p> <p>UPDATE: This </p> <pre><code>$cat_ids = array(); foreach ( wc()-&gt;cart-&gt;get_cart() as $cart_item_key =&gt; $cart_item ) { $cat_ids = array_merge( $cat_ids, $cart_item['data']-&gt;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 )); -&gt; int(1) var_dump($has_cat); -&gt; bool(true) var_dump(cat_ids); -&gt; array(1) { [0]=&gt; int(39) } &lt;---- 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 )); -&gt; int(1) var_dump($has_cat); -&gt; bool(true) var_dump(cat_ids); -&gt; array(1) { [0]=&gt; int(39) } </code></pre> <p>When: No category 39</p> <pre><code>var_dump(count( $cat_ids )); -&gt; int(2) var_dump($has_cat); -&gt; bool(false) var_dump(cat_ids); -&gt; array(2) { [0]=&gt; int(32) [1]=&gt; int(33) } &lt;--- 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']-&gt;get_category_ids()</code> to retrieve the category IDs:</p>\n\n<pre><code>...
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...
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&lt;$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>&lt;?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-&gt;prefix. $table .'` WHERE `ref` = %s'; $get_for_res = $wpdb-&gt;get_results($wpdb-&gt;prepare($get_for_sql, array($data[0]))); if (count($get_for_res) &lt;= 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]-&gt;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-&gt;prefix .'vendor_module_parts` WHERE `'. $search_field .'` = %d'; $delete_parts_sql = 'DELETE FROM `'. $wpdb-&gt;prefix .'vendor_module_parts` WHERE `'. $search_field .'` = %d'; $delete_components_sql = 'DELETE FROM `'. $wpdb-&gt;prefix .'vendor_module_components` WHERE `part_id` = %d'; $check_res = $wpdb-&gt;get_results($wpdb-&gt;prepare($check_sql, array($id))); if ($check_res) { $wpdb-&gt;query($wpdb-&gt;prepare($delete_parts_sql, array($id))); } $part_ids = $admin_functions-&gt;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 =&gt; $component) { $components[$key]['part_id'] = $part_ids[$component['part_ref']]; } # rm components from assoc part id foreach ($part_ids as $id) { $wpdb-&gt;query($wpdb-&gt;prepare($delete_components_sql, array($id))); } # insert components $admin_functions-&gt;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', '...
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 ...
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...
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 &amp; PHP. I'm using Ajax form validation &amp; 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: user@example.com 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-&gt;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' =&gt; $name, 'package' =&gt; $package, 'phone' =&gt; $phone, 'email' =&gt; $email, 'date' =&gt; $date, 'date' =&gt; $message, 'approved' =&gt; 0, 'featured' =&gt; 0, ); $args = array( 'post_title' =&gt; $name, 'post_content' =&gt; $message, 'post_author' =&gt; 1, 'post_status' =&gt; 'publish', 'post_type' =&gt; 'testimonial', 'meta_input' =&gt; array( '_zon_testimonial_key' =&gt; $data ) ); $postID = wp_insert_post( $args ); if ($postID) { $headers = "MIME-Version: 1.0\r\n" . "From: " . $current_user-&gt;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-&gt;return_json('success'); } } public function return_json( $status ) { $return = array( 'status' =&gt; $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> functi...
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: user@example.com 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( 'digitcrop@gmail.com', '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 "wordpress@yourdomain.com" 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 <example@email.com>" ``` 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>...
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>&lt;?php if ( is_single() &amp;&amp; is_post_type('product') || is_page(576) || is_single() &amp;&amp; is_post_type('post')) : ?&gt; &lt;div class="header-inner"&gt; &lt;style type="text/css"&gt;.header-inner { background-color:#861919!important; }&lt;/style&gt; &lt;?php else : ?&gt; &lt;div class="header-inner" style="background-color:rgba(0,0,0,0.30);"&gt; &lt;?php endif; ?&gt; </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>&lt;?php if ( is_single(893,892,843,895,894,896) ) : ?&gt; &lt;div class="header-inner" style="background-color:rgba(0,0,0,0.30);"&gt; &lt;?php else( is_single() &amp;&amp; is_post_type('product') || is_page(576) || is_single() &amp;&amp; is_post_type('post')) : ?&gt; &lt;div class="header-inner"&gt; &lt;style type="text/css"&gt;.header-inner { background-color:#861919!important; }&lt;/style&gt; &lt;?php elseif : ?&gt; &lt;div class="header-inner" style="background-color:rgba(0,0,0,0.30);"&gt; &lt;?php endif; ?&gt; </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 t...
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>&lt;?php //Find out how many posts $total_posts = wp_count_posts('smart_maps'); $total_posts = $total_posts-&gt;publish; $number_shown = 0; $the_query = new WP_Query( $args ); ?&gt; &lt;?php if ( $the_query-&gt;have_posts() ) : ?&gt; &lt;div id="smartmaps" class="smartmaps col xs-col-14 xs-offset-1 md-col-12 md-offset-2" style="display:none;"&gt; &lt;div class="in-here-smartmaps"&gt; &lt;?php while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;a href="&lt;?php echo get_permalink(get_the_ID());?&gt;"&gt; &lt;div class="single-smartmap col xs-col-16 md-col-8"&gt; &lt;div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center"&gt; &lt;div class="image-element"&gt; &lt;img src="&lt;?php the_field('thumbnail_image');?&gt;" class="circle"&gt; &lt;div class="image-overlay circle"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1"&gt; &lt;h5 class="smart-map-title"&gt;&lt;?php the_title();?&gt;&lt;/h5&gt; &lt;?php if(get_field('icons')) :?&gt; &lt;div class="block-icons"&gt; &lt;?php if(in_array('Heart', get_field('icons'))) :?&gt; &lt;span class="icon-heart"&gt;&lt;/span&gt; &lt;?php endif;?&gt; &lt;?php if(in_array('Plant', get_field('icons'))) :?&gt; &lt;span class="icon-plant"&gt;&lt;/span&gt; &lt;?php endif; ?&gt; &lt;?php if(in_array('Cup', get_field('icons'))) :?&gt; &lt;span class="icon-cup"&gt;&lt;/span&gt; &lt;?php endif;?&gt; &lt;?php if(in_array('Book', get_field('icons'))) :?&gt; &lt;span class="icon-book"&gt;&lt;/span&gt; &lt;?php endif;?&gt; &lt;/div&gt; &lt;?php endif;?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php $number_shown++; endwhile; ?&gt; &lt;?php endif;?&gt; &lt;/div&gt; &lt;?php if($number_shown != $total_posts) :?&gt; &lt;div class="loadmore smarties col xs-col-14 xs-offset-1 md-col-8 md-offset-4 center"&gt; &lt;h3&gt;&lt;a href="#"&gt;LOAD MORE&lt;/a&gt;&lt;/h3&gt; &lt;/div&gt; &lt;?php endif;?&gt; &lt;/div&gt; &lt;div clas="clearfix"&gt;&lt;/div&gt; </code></pre> <p>The second 1:</p> <pre><code>&lt;div id="strategic-events" class="strategicevents col xs-col-14 xs-offset-1 md-col-12 md-offset-2" style="display:none;"&gt; &lt;div class="in-here-strats"&gt; &lt;?php //Find out how many posts $total_posts = wp_count_posts('strategic_events'); $total_posts = $total_posts-&gt;publish; $number_shown = 0; $args = array( 'post_type' =&gt; 'strategic_events', 'posts_per_page' =&gt; 10, 'offset' =&gt; $the_offset ); $the_query2 = new WP_Query( $args ); ?&gt; &lt;?php if ( $the_query2-&gt;have_posts() ) : while ( $the_query2-&gt;have_posts() ) : $the_query2-&gt;the_post(); ?&gt; &lt;a href="&lt;?php echo get_permalink(get_the_ID());?&gt;"&gt; &lt;div class="single-strategicevent col xs-col-16 md-col-8"&gt; &lt;div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center"&gt; &lt;div class="image-element"&gt; &lt;img src="&lt;?php the_field('strategic_event_image');?&gt;" class="circle"&gt; &lt;div class="image-overlay circle"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1"&gt; &lt;h5 class="strategic-event-title"&gt;&lt;?php the_title();?&gt;&lt;/h5&gt; &lt;?php if(get_field('subtitle')) :?&gt; &lt;p&gt;&lt;?php the_field('subtitle');?&gt;&lt;/p&gt; &lt;small&gt;&lt;?php the_field('location_text');?&gt;&lt;/small&gt; &lt;?php endif;?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php $number_shown++; endwhile; endif; ?&gt; &lt;/div&gt; &lt;?php if($number_shown != $total_posts) :?&gt; &lt;div class="loadmore strats col xs-col-14 xs-offset-1 md-col-8 md-offset-4 center"&gt; &lt;h3&gt;&lt;a href="#"&gt;LOAD MORE&lt;/a&gt;&lt;/h3&gt; &lt;/div&gt; &lt;?php endif;?&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; </code></pre> <p>My JS code (both also in the page-work.php for now)...</p> <pre><code>&lt;script&gt; var ajaxurl = "&lt;?php echo admin_url( 'admin-ajax.php' ); ?&gt;"; var page = 2; jQuery(function($) { $('body').on('click', '.loadmore.strats', function(e) { e.preventDefault(); var data = { 'action': 'load_posts_by_ajax', 'page': page, 'security': '&lt;?php echo wp_create_nonce("load_strats_posts"); ?&gt;', 'max_page': '&lt;?php global $wp_query; echo $wp_query-&gt;max_num_pages;?&gt;' }; $.post(ajaxurl, data, function(response) { $('.in-here-strats').append(response); page++; }); }); }); </code></pre> <p></p> <pre><code>&lt;script&gt; var ajaxurl = "&lt;?php echo admin_url( 'admin-ajax.php' ); ?&gt;"; var page = 2; jQuery(function($) { $('body').on('click', '.loadmore.smarties', function(e) { e.preventDefault(); var data = { 'action': 'load_posts_by_ajax', 'page': page, 'security2': '&lt;?php echo wp_create_nonce("load_smartmaps_posts"); ?&gt;', 'max_page': '&lt;?php global $wp_query; echo $wp_query-&gt;max_num_pages;?&gt;' }; $.post(ajaxurl, data, function(response) { $('.in-here-smartmaps').append(response); page++; }); }); }); &lt;/script&gt; </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' =&gt; 'smart_maps', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; '10', 'paged' =&gt; $paged, ); $my_posts = new WP_Query( $args ); if ( $my_posts-&gt;have_posts() ) : ?&gt; &lt;?php $total_posts = wp_count_posts('smart_maps'); $total_posts = $total_posts-&gt;publish; $number_shown = $paged * 10 - 10;?&gt; &lt;?php while ( $my_posts-&gt;have_posts() ) : $my_posts-&gt;the_post() ?&gt; &lt;a href="&lt;?php echo get_permalink(get_the_ID());?&gt;"&gt; &lt;div class="single-smartmap col xs-col-16 md-col-8"&gt; &lt;div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center"&gt; &lt;div class="image-element"&gt; &lt;img src="&lt;?php the_field('thumbnail_image');?&gt;" class="circle"&gt; &lt;div class="image-overlay circle"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1"&gt; &lt;h5 class="smart-map-title"&gt;&lt;?php the_title();?&gt;&lt;/h5&gt; &lt;?php if(get_field('icons')) :?&gt; &lt;div class="block-icons"&gt; &lt;?php if(in_array('Heart', get_field('icons'))) :?&gt; &lt;span class="icon-heart"&gt;&lt;/span&gt; &lt;?php endif;?&gt; &lt;?php if(in_array('Plant', get_field('icons'))) :?&gt; &lt;span class="icon-plant"&gt;&lt;/span&gt; &lt;?php endif; ?&gt; &lt;?php if(in_array('Cup', get_field('icons'))) :?&gt; &lt;span class="icon-cup"&gt;&lt;/span&gt; &lt;?php endif;?&gt; &lt;?php if(in_array('Book', get_field('icons'))) :?&gt; &lt;span class="icon-book"&gt;&lt;/span&gt; &lt;?php endif;?&gt; &lt;/div&gt; &lt;?php endif;?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php $number_shown++; if ( $number_shown == $total_posts ) { echo '&lt;style&gt;.loadmore.smarties {display:none;}&lt;/style&gt;'; } endwhile ?&gt; &lt;?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' =&gt; 'strategic_events', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; '10', 'paged' =&gt; $paged, ); $my_posts = new WP_Query( $args ); if ( $my_posts-&gt;have_posts() ) : ?&gt; &lt;?php $total_posts = wp_count_posts('strategic_events'); $total_posts = $total_posts-&gt;publish; $number_shown = $paged * 10 - 10;?&gt; &lt;?php while ( $my_posts-&gt;have_posts() ) : $my_posts-&gt;the_post() ?&gt; &lt;a href="&lt;?php echo get_permalink(get_the_ID());?&gt;"&gt; &lt;div class="single-strategicevent col xs-col-16 md-col-8"&gt; &lt;div class="col xs-col-8 xs-offset-4 md-col-4 md-offset-0 center"&gt; &lt;div class="image-element"&gt; &lt;img src="&lt;?php the_field('strategic_event_image');?&gt;" class="circle"&gt; &lt;div class="image-overlay circle"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col xs-col-14 xs-offset-1 md-col-10 md-offset-1"&gt; &lt;h5 class="strategic-event-title"&gt;&lt;?php the_title();?&gt;&lt;/h5&gt; &lt;?php if(get_field('subtitle')) :?&gt; &lt;p&gt;&lt;?php the_field('subtitle');?&gt;&lt;/p&gt; &lt;small&gt;&lt;?php the_field('location_text');?&gt;&lt;/small&gt; &lt;?php endif;?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;?php $number_shown++; if ( $number_shown == $total_posts ) { echo '&lt;style&gt;.loadmore.strats {display:none;}&lt;/style&gt;'; } endwhile ?&gt; &lt;?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 ...
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 ...
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 ...
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 &amp; 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 =&gt; { return ( &lt;ul&gt; { props.attributes.items.map( (itemLabel, id) =&gt; ( &lt;li id={ `li_${id}` } draggable&gt; &lt;Draggable elementId={ `li_${id}` } transferData={ {} }&gt; { ({ onDraggableStart, onDraggableEnd }) =&gt; ( &lt;Dashicon icon="move" onDragStart={ onDraggableStart } onDragEnd={ onDraggableEnd } draggable /&gt; ) } &lt;/Draggable&gt; { itemLabel } &lt;/li&gt; )) } &lt;/ul&gt; ) }, save: () =&gt; { // 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 ...
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 [![enter image description here](https://i.stack.imgur.com/QMSVd.png)](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' =&gt; ['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...
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>&lt;title&gt;&lt;/title&gt;</code> or output title?</p>\n\n<p>If <strong>output title</stron...
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>&lt;title&gt;&lt;/title&gt;</code> or output title?</p>\n\n<p>If <strong>output title</stron...
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>&lt;li&gt;</code> and <code>&lt;a&gt;</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>&lt;li&gt;</code> and not only in the word / s of the link <code>&lt;a&gt;</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>&lt;div id="header-menu-nav"&gt; &lt;nav&gt; &lt;?php wp_nav_menu(array( 'container'=&gt; false, 'items_wrap' =&gt; '&lt;ul&gt;%3$s&lt;/ul&gt;', 'theme_location' =&gt; 'menu' )); ?&gt; &lt;/nav&gt; &lt;/div&gt; </code></pre> <p>And the answer I get is:</p> <pre><code>&lt;div id="header-menu-mobile-nav"&gt; &lt;nav&gt; &lt;ul id="header-menu-mobile-nav-ul"&gt; &lt;li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-181"&gt; &lt;a href="index.php"&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; </code></pre> <p>What I want is:</p> <pre><code>&lt;div id="header-menu-mobile-nav"&gt; &lt;nav&gt; &lt;ul id="header-menu-mobile-nav-ul"&gt; &lt;a href="index.php"&gt; &lt;li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-181"&gt;Home&lt;/li&gt; &lt;/a&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; </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>&lt;ul&gt;\n &lt;a&gt;\n &lt;li&gt;&lt;/li&gt;\n &lt;/a&gt;\n&lt;/ul&gt;\n</code><...
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']) &amp;&amp; $_GET['post_type'] == 'page') { echo '&lt;style type="text/css"&gt; #favorite-actions, .add-new-h2, .tablenav { display:none; } &lt;/style&gt;'; } </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>&lt;ul&gt;\n &lt;a&gt;\n &lt;li&gt;&lt;/li&gt;\n &lt;/a&gt;\n&lt;/ul&gt;\n</code><...
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>&lt;ul&gt;\n &lt;a&gt;\n &lt;li&gt;&lt;/li&gt;\n &lt;/a&gt;\n&lt;/ul&gt;\n</code><...
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 ' &lt;div class="signin_container"&gt; &lt;h4 class="signin_footer_head"&gt;Log In To My Account&lt;/h4&gt; &lt;a href="'.$siteURL.'/login/"&gt;Log In&lt;/a&gt; &lt;a href="'.$siteURL.'/register/"&gt;Sign Up&lt;/a&gt; &lt;/div&gt; '; } 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>&lt;ul&gt;\n &lt;a&gt;\n &lt;li&gt;&lt;/li&gt;\n &lt;/a&gt;\n&lt;/ul&gt;\n</code><...
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, hi...
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. [![enter image description here](https://i.stack.imgur.com/WX3Zz.png)](https://i.stack.imgur.com/WX3Zz.png) [![enter image description here](https://i.stack.imgur.com/Ahuf5.png)](https://i.stack.imgur.com/Ahuf5.png) [![enter image description here](https://i.stack.imgur.com/v5rVQ.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> co...
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...
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-&gt;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-&gt;query_vars['posts_per_page'] .</code> " posts per page if possible.</p> <p>We need a total of " <code>. $wp_query-&gt;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 I...
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 ...
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: [![enter image description here](https://i.stack.imgur.com/zINI3.jpg)](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( '&lt;a href="%1$s"&gt;%2$s&lt;/a&gt;', esc_url( $url ), wp_get_attachment_image( $custom_logo_id, 'full', false, array( 'class' =&gt; 'custom-logo',)) ); }elseif(is_category( 39 ) || cat_is_ancestor_of( 39, get_query_var( 'cat' ) )){ $html = sprintf( '&lt;a href="%1$s"&gt;%2$s&lt;/a&gt;', esc_url( $url ), wp_get_attachment_image( $custom_logo_id, 'full', false, array( 'class' =&gt; 'custom-logo',)) ); }elseif(in_category( array( 39,25,18,3,24,58 ) )){ $html = sprintf( '&lt;a href="%1$s"&gt;%2$s&lt;/a&gt;', esc_url( $url ), wp_get_attachment_image( $custom_logo_id, 'full', false, array( 'class' =&gt; '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>&lt;div class="contact_logo"&gt; &lt;?php xxx_show_logo(true, true); ?&gt; &lt;/div&gt; </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) &amp;&amp; empty($logo_fixed) &amp;&amp; empty($logo_footer) &amp;&amp; empty($logo_side) &amp;&amp; empty($logo_text)) $logo_text = get_bloginfo('name'); if ($logo_main || $logo_fixed || $logo_footer || $logo_side || $logo_text) { ?&gt; &lt;div class="logo"&gt; &lt;a href="&lt;?php echo esc_url(home_url('/')); ?&gt;"&gt;&lt;?php if (!empty($logo_main)) { $attr = xxx_getimagesize($logo_main); echo '&lt;img src="'.esc_url($logo_main).'" class="logo_main" alt="'.esc_attr__('Image', 'charity-is-hope').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'&gt;'; } if (!empty($logo_fixed)) { $attr = xxx_getimagesize($logo_fixed); echo '&lt;img src="'.esc_url($logo_fixed).'" class="logo_fixed" alt="'.esc_attr__('Image', 'charity-is-hope').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'&gt;'; } if (!empty($logo_footer)) { $attr = xxx_getimagesize($logo_footer); echo '&lt;img src="'.esc_url($logo_footer).'" class="logo_footer" alt="'.esc_attr__('Image', 'xxx').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'&gt;'; } if (!empty($logo_side)) { $attr = xxx_getimagesize($logo_side); echo '&lt;img src="'.esc_url($logo_side).'" class="logo_side" alt="'.esc_attr__('Image', 'xxx').'"'.(!empty($attr[3]) ? ' '.trim($attr[3]) : '').'&gt;'; } echo !empty($logo_text) ? '&lt;div class="logo_text"&gt;'.trim($logo_text).'&lt;/div&gt;' : ''; echo !empty($logo_slogan) ? '&lt;br&gt;&lt;div class="logo_slogan"&gt;' . esc_html($logo_slogan) . '&lt;/div&gt;' : ''; ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;?php } } } </code></pre> <p>Now I need to change this: <code>&lt;a href="&lt;?php echo esc_url(home_url('/')); ?&gt;"&gt;</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 ...
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 ...
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-&gt;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 workin...
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>&lt;?php $term_id = get_queried_object()-&gt;term_id; $tax_image = get_term_meta( $term_id, 'custom_taxonomy_image', true ); if ( $tax_image ) { printf( '&lt;div class="icon"&gt;&lt;img src=$s /&gt;&lt;/div&gt;', $tax_image ); } ?&gt; </code></pre> <p>I'm sure i'd need a foreach somewhere, like this:</p> <pre><code>&lt;ul class="amenity-icons"&gt; &lt;?php foreach( $terms as $term =&gt; $icon ) { if( isset( $term ) ) { echo '&lt;li&gt;' . $icon . '&lt;/li&gt;'; } } ?&gt; &lt;/ul&gt; </code></pre> <p>I can successfully retrieve the term list as words using: </p> <pre><code>&lt;?php the_terms( get_the_ID(), 'amenity' ); ?&gt; </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 workin...
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 &gt;= $u_time + 86400) { $updated_date = get_the_modified_time('F jS, Y'); $updated_time = get_the_modified_time('h:i a'); $custom_content .= '&lt;p class="last-updated" style="text-align:right"&gt;Last updated on '. $updated_date . ' at '. $updated_time .'&lt;/p&gt;'; } $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 <c...
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...
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 w...
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' =&gt; $_POST['nameChange'], 'slug' =&gt; $string, '_city' =&gt; $_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-&gt;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' =&gt; $_POST['nameChange'], 'slug' =&gt; $string, </code></pre> <p>But not '</p> <pre><code>'_city' =&gt; $_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 w...
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' =&gt; 5, 'display' =&gt; __( '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 ru...
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 ru...
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> inste...
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, ther...
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, &amp; it is working in Chrome &amp; 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 &amp; 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, ther...
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' ) &amp;&amp; OT_USE_THEME_OPTIONS ) { ot_register_settings( [ [ 'id' =&gt; 'option_tree', 'pages' =&gt; [ [ 'id' =&gt; 'ot_theme_options', 'parent_slug' =&gt; apply_filters( 'ot_theme_options_parent_slug', 'unite-welcome-page' ), 'page_title' =&gt; apply_filters( 'ot_theme_options_page_title', __( 'Theme Options', 'option-tree' ) ), 'menu_title' =&gt; apply_filters( 'ot_theme_options_menu_title', __( 'Theme Options', 'option-tree' ) ), 'capability' =&gt; $caps = apply_filters( 'ot_theme_options_capability', 'edit_theme_options' ), 'menu_slug' =&gt; apply_filters( 'ot_theme_options_menu_slug', 'ut_theme_options' ), 'icon_url' =&gt; apply_filters( 'ot_theme_options_icon_url', null ), 'position' =&gt; apply_filters( 'ot_theme_options_position', null ), 'updated_message' =&gt; apply_filters( 'ot_theme_options_updated_message', __( 'Theme Options updated.', 'option-tree' ) ), 'reset_message' =&gt; apply_filters( 'ot_theme_options_reset_message', __( 'Theme Options reset.', 'option-tree' ) ), 'button_text' =&gt; apply_filters( 'ot_theme_options_button_text', __( 'Save Changes', 'option-tree' ) ), 'screen_icon' =&gt; 'themes', 'sections' =&gt; $sections, 'settings' =&gt; $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 add...
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 add...
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 add...
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...
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>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"&gt;&lt;body&gt; the content goes here (output from the_content();) &lt;/body&gt;&lt;/html&gt;</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-&gt;loadHTML(utf8_decode($content)); $imgs = $document-&gt;getElementsByTagName('img'); foreach ($imgs as $img) { $classes = $img-&gt;getAttribute('class'); $img-&gt;setAttribute('class', $classes . ' img-fluid'); } $html = $document-&gt;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...
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...
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> &lt;?php if (is_category("event")) { get_sidebar('events'); } elseif (is_category('long-term-leasing')) { get_sidebar('long-term'); } else { get_sidebar(); } ?&gt; </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...
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...
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...
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...
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...
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 &gt; /dev/null 2&gt;&amp;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 &gt; /dev/null 2&gt;&amp;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...
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.o...
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.o...
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&mdash;a footer image. The image is entered like this on the WP back-end:</p> <pre><code>&lt;img src="https://widgets.guidestar.org/gximage2?o=7583405&amp;l=v4" /&gt; </code></pre> <p>Firebug > Inspect Element shows:</p> <pre><code>&lt;img src="https://widgets.guidestar.org/gximage2?o=7583405&amp;l=v4"&gt; </code></pre> <p>Firefox > View Source shows:</p> <pre><code>&lt;img src="https://widgets.guidestar.org/gximage2?o=7583405&amp;l=v4" /&gt; </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...
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...
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...
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...
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 ``` }