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
383,360
<p>I have, based on post category, added a password form (shortcode) whereof the purpose is to hide certain HTML code.</p> <p>To do this, I have wrapped certain HTML-tags in a shortcode using the <code>the_content</code> filter.</p> <p>The password itself is added through an array, which would be much better suited as an global setting through the WP admin settings page - but that's a different story.</p> <p><strong>My main problem is this;</strong> after submitting the password - no matter if the password is right or wrong - the user get &quot;scrolled&quot; all the way to the top of the page.</p> <p>That should not happen, which is why I added a ID to the form. Upon submitting the correct password, the user should be kept in the same place, which is where the form was which is where the HTML code now is.</p> <p>Makes sense? Part of the problem is this; there's no message for &quot;password successful&quot; or &quot;incorrect password&quot;.</p> <p>As you can see in the code, I've already tried to add the ID to the path using this: <code>path=/#functioncode</code> without success.</p> <p><strong>This is the full code:</strong></p> <pre><code>add_shortcode( 'protected', 'protected_html' ); function protected_html( $atts, $content=null ) { $functionUserPassword = isset( $_REQUEST['password']) ? $_REQUEST['password'] : ( isset( $_COOKIE['functionUserPassword']) ? $_COOKIE['functionUserPassword'] : NULL ); if ( in_array( $functionUserPassword, array('password') ) ) { $return_html_content = do_shortcode($content); } else { $return_html_content = '&lt;div id=&quot;functioncode&quot; style=&quot;margin-top:20px;font-size:15px;&quot;&gt;To view the content of this section, submit your password.&lt;/div&gt; &lt;form method=&quot;post&quot; onsubmit=&quot;functionCookie(this); return false;&quot;&gt; &lt;input required style=&quot;display: block; width: 69%; height: 50px; margin-right: 1%; float: left; border: 2px solid #333;&quot; type=&quot;text&quot; placeholder=&quot;&amp;#32;Password Here&quot; name=&quot;password&quot; id=&quot;functionUserPassword&quot;&gt; &lt;input style=&quot;display: block; margin: 0px; width: 30%; height: 50px; background-color: #333; color: #fff;&quot; type=&quot;submit&quot; value=&quot;Submit&quot;&gt; &lt;/form&gt; &lt;script&gt; function functionCookie(form){ document.cookie = &quot;functionUserPassword=&quot; + escape(form.functionUserPassword.value) + &quot;; path=/#functioncode&quot;; &lt;/script&gt;'; } return $return_html_content; } </code></pre> <p><strong>Here's the code which I am using with the content filter:</strong></p> <pre><code>add_filter( 'the_content', 'wrap_html_in_shortcode', 9 ); function wrap_html_in_shortcode( $content ) { if ( ! in_category( 'premium' ) ) return $content; $content = preg_replace('/(&lt;span[^&gt;]*&gt;\s*&lt;div[^&gt;]*&gt;)/',&quot;[protected]$1&quot;, $content); $content = preg_replace('/(&lt;\/div&gt;\s*&lt;\/span&gt;)/', &quot;$1[/protected]&quot;, $content); return $content; } </code></pre>
[ { "answer_id": 383485, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>Not exactly sure what you are trying to do and this doesn't look like a WordPress issue, but submitting a html f...
2021/02/14
[ "https://wordpress.stackexchange.com/questions/383360", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/201877/" ]
I have, based on post category, added a password form (shortcode) whereof the purpose is to hide certain HTML code. To do this, I have wrapped certain HTML-tags in a shortcode using the `the_content` filter. The password itself is added through an array, which would be much better suited as an global setting through the WP admin settings page - but that's a different story. **My main problem is this;** after submitting the password - no matter if the password is right or wrong - the user get "scrolled" all the way to the top of the page. That should not happen, which is why I added a ID to the form. Upon submitting the correct password, the user should be kept in the same place, which is where the form was which is where the HTML code now is. Makes sense? Part of the problem is this; there's no message for "password successful" or "incorrect password". As you can see in the code, I've already tried to add the ID to the path using this: `path=/#functioncode` without success. **This is the full code:** ``` add_shortcode( 'protected', 'protected_html' ); function protected_html( $atts, $content=null ) { $functionUserPassword = isset( $_REQUEST['password']) ? $_REQUEST['password'] : ( isset( $_COOKIE['functionUserPassword']) ? $_COOKIE['functionUserPassword'] : NULL ); if ( in_array( $functionUserPassword, array('password') ) ) { $return_html_content = do_shortcode($content); } else { $return_html_content = '<div id="functioncode" style="margin-top:20px;font-size:15px;">To view the content of this section, submit your password.</div> <form method="post" onsubmit="functionCookie(this); return false;"> <input required style="display: block; width: 69%; height: 50px; margin-right: 1%; float: left; border: 2px solid #333;" type="text" placeholder="&#32;Password Here" name="password" id="functionUserPassword"> <input style="display: block; margin: 0px; width: 30%; height: 50px; background-color: #333; color: #fff;" type="submit" value="Submit"> </form> <script> function functionCookie(form){ document.cookie = "functionUserPassword=" + escape(form.functionUserPassword.value) + "; path=/#functioncode"; </script>'; } return $return_html_content; } ``` **Here's the code which I am using with the content filter:** ``` add_filter( 'the_content', 'wrap_html_in_shortcode', 9 ); function wrap_html_in_shortcode( $content ) { if ( ! in_category( 'premium' ) ) return $content; $content = preg_replace('/(<span[^>]*>\s*<div[^>]*>)/',"[protected]$1", $content); $content = preg_replace('/(<\/div>\s*<\/span>)/', "$1[/protected]", $content); return $content; } ```
Not exactly sure what you are trying to do and this doesn't look like a WordPress issue, but submitting a html form will certainly lead to a new page load. So what you want is redirect not to the same page (which happens when you specify no action, leading the page to scroll to the top) but to an anchor on that page. The [usual way to do this](https://stackoverflow.com/questions/8395269/what-do-form-action-and-form-method-post-action-do) is to include it in the `action` variable of your `form` like this: ``` <a name="somewhere"></a> <form method="POST" action="#somewhere"> ... </form> ```
383,498
<p>I have a site that uses a set of 3 images for the header of its subpages. Each page has a different set of images. From what I could find, my best way to accomplish this would be to place an if statement within my <code>header-subpage.php</code>. The following is a snippet of my code.</p> <pre><code>&lt;?php if ( is_page( 'available-homes' ) ) { get_template_part( 'sections/banner-images', 'available-homes' ); } elseif ( is_page( 'design-services' ) ) { get_template_part( 'sections/banner-images', 'design-services' ); } elseif ( is_page( 'about-us' ) ) { get_template_part( 'sections/banner-images', 'about-us' ); } ........ } elseif ( is_page( 'portfolio' ) ) { get_template_part( 'sections/banner-images', 'portfolio' ); } elseif ( is_page( 'galleries' ) ) { get_template_part( 'sections/banner-images', 'galleries' ); } else { echo &quot;page images undefined...&quot;; } </code></pre> <p>Is there a more efficient way for me to do this? I am still learning PHP, but it seems like there might be a better more efficient way to loop through the pages than what I have done.</p> <p>Thank you for any suggestions.</p>
[ { "answer_id": 383363, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>There isn’t a way. You need to create a child theme or a plugin and put the functions there.</p>\n<p>No...
2021/02/16
[ "https://wordpress.stackexchange.com/questions/383498", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202028/" ]
I have a site that uses a set of 3 images for the header of its subpages. Each page has a different set of images. From what I could find, my best way to accomplish this would be to place an if statement within my `header-subpage.php`. The following is a snippet of my code. ``` <?php if ( is_page( 'available-homes' ) ) { get_template_part( 'sections/banner-images', 'available-homes' ); } elseif ( is_page( 'design-services' ) ) { get_template_part( 'sections/banner-images', 'design-services' ); } elseif ( is_page( 'about-us' ) ) { get_template_part( 'sections/banner-images', 'about-us' ); } ........ } elseif ( is_page( 'portfolio' ) ) { get_template_part( 'sections/banner-images', 'portfolio' ); } elseif ( is_page( 'galleries' ) ) { get_template_part( 'sections/banner-images', 'galleries' ); } else { echo "page images undefined..."; } ``` Is there a more efficient way for me to do this? I am still learning PHP, but it seems like there might be a better more efficient way to loop through the pages than what I have done. Thank you for any suggestions.
There isn’t a way. You need to create a child theme or a plugin and put the functions there. Note that there’s nothing special about child themes. The point is to put the code into something that somebody else isn’t going to update. So third party child themes aren’t safe either.
383,511
<p>We have a normal WordPress gallery on a <a href="https://herodevelopment.com.au/allbathroomgear/design-build/bathrooms/" rel="nofollow noreferrer">development webpage</a>.</p> <p><a href="https://i.stack.imgur.com/x4XcK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x4XcK.png" alt="enter image description here" /></a></p> <p>The page is custom content through Advanced Custom Fields, and we are wrapping the section above's content like so:</p> <pre><code>&lt;?php $content = get_sub_field('wysiwyg'); if ( function_exists('slb_activate') ) { $content = slb_activate($content); } echo $content; ?&gt; </code></pre> <p>The lightbox functionality is generated by <a href="https://wordpress.org/plugins/simple-lightbox/" rel="nofollow noreferrer">Simple Lightbox</a>, and <code>slb_activate</code> is a function of this plugin, which adds the lightbox functionality to any gallery in the ACF content.</p> <p>The designer wants the last image in the gallery (the purple one) to link to a different WordPress page while maintaining the lightbox functionality for the rest of the gallery.</p> <p>I don't know if we need a WordPress filter (which to me would be complicated by the <code>slb_activate</code> function, or some jQuery, and target <code>.gallery-item:last-of-type</code>, replacing the URL with a new one?</p> <p>If so, we'd like to take the page slug (bathrooms) from <code>https://herodevelopment.com.au/allbathroomgear/design-build/bathrooms/</code> and use this slug to generate a new URL of <code>https://herodevelopment.com.au/allbathroomgear/album/bathrooms/</code></p> <p>(so going from <code>/design-build/bathrooms/</code> to <code>/album/bathrooms/</code> on the final production website).</p> <p>I'd appreciate any help, as I am unfortunately not a developer.</p>
[ { "answer_id": 383363, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>There isn’t a way. You need to create a child theme or a plugin and put the functions there.</p>\n<p>No...
2021/02/17
[ "https://wordpress.stackexchange.com/questions/383511", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/201824/" ]
We have a normal WordPress gallery on a [development webpage](https://herodevelopment.com.au/allbathroomgear/design-build/bathrooms/). [![enter image description here](https://i.stack.imgur.com/x4XcK.png)](https://i.stack.imgur.com/x4XcK.png) The page is custom content through Advanced Custom Fields, and we are wrapping the section above's content like so: ``` <?php $content = get_sub_field('wysiwyg'); if ( function_exists('slb_activate') ) { $content = slb_activate($content); } echo $content; ?> ``` The lightbox functionality is generated by [Simple Lightbox](https://wordpress.org/plugins/simple-lightbox/), and `slb_activate` is a function of this plugin, which adds the lightbox functionality to any gallery in the ACF content. The designer wants the last image in the gallery (the purple one) to link to a different WordPress page while maintaining the lightbox functionality for the rest of the gallery. I don't know if we need a WordPress filter (which to me would be complicated by the `slb_activate` function, or some jQuery, and target `.gallery-item:last-of-type`, replacing the URL with a new one? If so, we'd like to take the page slug (bathrooms) from `https://herodevelopment.com.au/allbathroomgear/design-build/bathrooms/` and use this slug to generate a new URL of `https://herodevelopment.com.au/allbathroomgear/album/bathrooms/` (so going from `/design-build/bathrooms/` to `/album/bathrooms/` on the final production website). I'd appreciate any help, as I am unfortunately not a developer.
There isn’t a way. You need to create a child theme or a plugin and put the functions there. Note that there’s nothing special about child themes. The point is to put the code into something that somebody else isn’t going to update. So third party child themes aren’t safe either.
383,539
<p>My aim is to import all XML files from a folder inside the WordPress installation (/data/*.xml)</p> <p>To achieve this, I added action in functions.php:</p> <pre><code>/** * Show 'insert posts' button on backend */ add_action( &quot;admin_notices&quot;, function() { echo &quot;&lt;div class='updated'&gt;&quot;; echo &quot;&lt;p&gt;&quot;; echo &quot;To insert the posts into the database, click the button to the right.&quot;; echo &quot;&lt;a class='button button-primary' style='margin:0.25em 1em' href='{$_SERVER[&quot;REQUEST_URI&quot;]}&amp;insert_mti_posts'&gt;Insert Posts&lt;/a&gt;&quot;; echo &quot;&lt;/p&gt;&quot;; echo &quot;&lt;/div&gt;&quot;; }); </code></pre> <p>Here's my code:</p> <pre><code>/** * Create and insert posts from CSV files */ add_action( &quot;admin_init&quot;, function() { global $wpdb; // I'd recommend replacing this with your own code to make sure // the post creation _only_ happens when you want it to. if ( ! isset( $_GET[&quot;insert_mti_posts&quot;] ) ) { return; } // Change these to whatever you set $getposttype = array( &quot;custom-post-type&quot; =&gt; &quot;cikkek&quot; ); // Get the data from all those XMLs! $posts = function() { $xmlfiles = glob( __DIR__ . &quot;/data/*.xml&quot; ); $data = array(); $errors = array(); // Get array of XML files foreach ( $xmlfiles as $key=&gt;$xmlfile ) { $xml = simplexml_load_file($xmlfile); $xmldata = json_decode(json_encode($xml), true); $posttitle = $xmldata['THIR']['CIM']; $postlead = $xmldata['THIR']['LEAD']; $postcontent = $xmldata['THIR']['HIRSZOVEG']; $data = array( $key =&gt; array( &quot;title&quot; =&gt; $posttitle, &quot;description&quot; =&gt; $postlead, &quot;content&quot; =&gt; $postcontent ) ); $data[] = $post; }; if ( ! empty( $errors ) ) { // ... do stuff with the errors } return $data; }; // Simple check to see if the current post exists within the // database. This isn't very efficient, but it works. $post_exists = function( $title ) use ( $wpdb, $getposttype ) { // Get an array of all posts within our custom post type $posts = $wpdb-&gt;get_col( &quot;SELECT post_title FROM {$wpdb-&gt;posts} WHERE post_type = '{$getposttype[&quot;custom-post-type&quot;]}'&quot; ); // Check if the passed title exists in array return in_array( $title, $posts ); }; foreach ( $posts() as $post ) { // If the post exists, skip this post and go to the next one if ( $post_exists( $post[&quot;title&quot;] ) ) { continue; } // Insert the post into the database $post[&quot;id&quot;] = wp_insert_post( array( &quot;post_title&quot; =&gt; $post[&quot;title&quot;], &quot;post_content&quot; =&gt; $post[&quot;content&quot;], &quot;post_type&quot; =&gt; $getposttype[&quot;custom-post-type&quot;], &quot;post_status&quot; =&gt; &quot;draft&quot; )); } }); </code></pre> <p><strong>Issue 1:</strong></p> <p>The code kind of works, but it <strong>only inserts the first .XML</strong> into the WordPress database. I don't understand why, as I loop through all of them and send back an array.</p> <p><strong>Issue 2:</strong> The code checks the title of the given XML and matches it up against the database -&gt; should not add it if it's the same content. Unfortunately, it does.</p> <p><strong>Issue 3:</strong> I think this is because the admin_init action, but unfortunately, the import runs each time I refresh the admin. I only want it to run, if I click the Insert Posts button in admin. Is there another hook that is better suited for this?</p>
[ { "answer_id": 383363, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>There isn’t a way. You need to create a child theme or a plugin and put the functions there.</p>\n<p>No...
2021/02/17
[ "https://wordpress.stackexchange.com/questions/383539", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112604/" ]
My aim is to import all XML files from a folder inside the WordPress installation (/data/\*.xml) To achieve this, I added action in functions.php: ``` /** * Show 'insert posts' button on backend */ add_action( "admin_notices", function() { echo "<div class='updated'>"; echo "<p>"; echo "To insert the posts into the database, click the button to the right."; echo "<a class='button button-primary' style='margin:0.25em 1em' href='{$_SERVER["REQUEST_URI"]}&insert_mti_posts'>Insert Posts</a>"; echo "</p>"; echo "</div>"; }); ``` Here's my code: ``` /** * Create and insert posts from CSV files */ add_action( "admin_init", function() { global $wpdb; // I'd recommend replacing this with your own code to make sure // the post creation _only_ happens when you want it to. if ( ! isset( $_GET["insert_mti_posts"] ) ) { return; } // Change these to whatever you set $getposttype = array( "custom-post-type" => "cikkek" ); // Get the data from all those XMLs! $posts = function() { $xmlfiles = glob( __DIR__ . "/data/*.xml" ); $data = array(); $errors = array(); // Get array of XML files foreach ( $xmlfiles as $key=>$xmlfile ) { $xml = simplexml_load_file($xmlfile); $xmldata = json_decode(json_encode($xml), true); $posttitle = $xmldata['THIR']['CIM']; $postlead = $xmldata['THIR']['LEAD']; $postcontent = $xmldata['THIR']['HIRSZOVEG']; $data = array( $key => array( "title" => $posttitle, "description" => $postlead, "content" => $postcontent ) ); $data[] = $post; }; if ( ! empty( $errors ) ) { // ... do stuff with the errors } return $data; }; // Simple check to see if the current post exists within the // database. This isn't very efficient, but it works. $post_exists = function( $title ) use ( $wpdb, $getposttype ) { // Get an array of all posts within our custom post type $posts = $wpdb->get_col( "SELECT post_title FROM {$wpdb->posts} WHERE post_type = '{$getposttype["custom-post-type"]}'" ); // Check if the passed title exists in array return in_array( $title, $posts ); }; foreach ( $posts() as $post ) { // If the post exists, skip this post and go to the next one if ( $post_exists( $post["title"] ) ) { continue; } // Insert the post into the database $post["id"] = wp_insert_post( array( "post_title" => $post["title"], "post_content" => $post["content"], "post_type" => $getposttype["custom-post-type"], "post_status" => "draft" )); } }); ``` **Issue 1:** The code kind of works, but it **only inserts the first .XML** into the WordPress database. I don't understand why, as I loop through all of them and send back an array. **Issue 2:** The code checks the title of the given XML and matches it up against the database -> should not add it if it's the same content. Unfortunately, it does. **Issue 3:** I think this is because the admin\_init action, but unfortunately, the import runs each time I refresh the admin. I only want it to run, if I click the Insert Posts button in admin. Is there another hook that is better suited for this?
There isn’t a way. You need to create a child theme or a plugin and put the functions there. Note that there’s nothing special about child themes. The point is to put the code into something that somebody else isn’t going to update. So third party child themes aren’t safe either.
383,632
<p>I struggle with columns block in my plugin. I try to filter all blocks of the type &quot;heading&quot;:</p> <pre><code>$post = get_post(); $blocks = parse_blocks($post-&gt;post_content); $headings = array_values(array_filter($blocks, function ($block) { return $block['blockName'] === 'core/heading'; })); </code></pre> <p>This returns an array of all heading block. But if the post contains columns the array $blocks is a nested multidimensional array. array_filter does not select blocks nested like this:</p> <pre><code>} [1]=&gt; array(5) { [&quot;blockName&quot;]=&gt; string(11) &quot;core/column&quot; [&quot;attrs&quot;]=&gt; array(0) { } [&quot;innerBlocks&quot;]=&gt; array(4) { [0]=&gt; array(5) { [&quot;blockName&quot;]=&gt; string(12) &quot;core/heading&quot; [&quot;attrs&quot;]=&gt; array(0) { } [&quot;innerBlocks&quot;]=&gt; array(0) { } [&quot;innerHTML&quot;]=&gt; string(26) &quot; &lt;h2&gt;HEADING.COLUMN1&lt;/h2&gt; &quot; [&quot;innerContent&quot;]=&gt; array(1) { [0]=&gt; string(26) &quot; &lt;h2&gt;HEADING.COLUMN1&lt;/h2&gt; &quot; } } </code></pre> <p>Is there a way to select only heading blocks with parse_blocks or some other clever way?</p>
[ { "answer_id": 383639, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/parse_blocks/\" rel=\"nofollow noreferrer\"><...
2021/02/18
[ "https://wordpress.stackexchange.com/questions/383632", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33797/" ]
I struggle with columns block in my plugin. I try to filter all blocks of the type "heading": ``` $post = get_post(); $blocks = parse_blocks($post->post_content); $headings = array_values(array_filter($blocks, function ($block) { return $block['blockName'] === 'core/heading'; })); ``` This returns an array of all heading block. But if the post contains columns the array $blocks is a nested multidimensional array. array\_filter does not select blocks nested like this: ``` } [1]=> array(5) { ["blockName"]=> string(11) "core/column" ["attrs"]=> array(0) { } ["innerBlocks"]=> array(4) { [0]=> array(5) { ["blockName"]=> string(12) "core/heading" ["attrs"]=> array(0) { } ["innerBlocks"]=> array(0) { } ["innerHTML"]=> string(26) " <h2>HEADING.COLUMN1</h2> " ["innerContent"]=> array(1) { [0]=> string(26) " <h2>HEADING.COLUMN1</h2> " } } ``` Is there a way to select only heading blocks with parse\_blocks or some other clever way?
[`parse_blocks()`](https://developer.wordpress.org/reference/functions/parse_blocks/) simply returns all blocks found in the post content, so for what you're trying to get, you could use a function which calls itself recursively like so: ```php function my_find_heading_blocks( $blocks ) { $list = array(); foreach ( $blocks as $block ) { if ( 'core/heading' === $block['blockName'] ) { // add current item, if it's a heading block $list[] = $block; } elseif ( ! empty( $block['innerBlocks'] ) ) { // or call the function recursively, to find heading blocks in inner blocks $list = array_merge( $list, my_find_heading_blocks( $block['innerBlocks'] ) ); } } return $list; } // Sample usage: $post = get_post(); $blocks = parse_blocks( $post->post_content ); $headings = my_find_heading_blocks( $blocks ); ```
383,658
<p>I am trying to understand some fundamentals of php with regards to adding new functions to actions. I found a tutorial where he adds a new function to the <code>save_post</code> action…</p> <pre><code>add_action('save_post', 'log_when_saved'); function log_when_saved($post_id){ do something with $post_id }; </code></pre> <p>Is my understanding correct that when we fire the action elsewhere via <code>do_action('save_post', $post_ID, $post, $update)</code> the parameters we pass it at this time are automatically &amp; instantly available to use in our new function we are adding to the action and that is what is going on here?</p> <p>When we write <code>add_action('save_post', ‘log_when_saved’);</code> we are adding some new function to be run when the action is fired. This new function to be run can automatically use the variable values that were defined when we fired the action via the <code>do_action</code>. Is this correct?</p> <p>What if we wanted to pass in the <code>$post</code> and <code>$update</code> parameters to this new function also… would we have to do the following…</p> <pre><code>add_action('save_post', 'log_when_saved'); function log_when_saved($post_id, $post, $update){ do something with $post_id, $post, $update}; </code></pre> <p>One of the fundamental things I am trying to understand is do the parameters that we are passing our new function strictly have to be in the order that they were defined in <code>do_action('save_post', $post_ID, $post, $update)</code> and similarly, would you have to call all 3 if we wanted to get the last parameter <code>$update</code> to use in our function?</p> <p>With regards to naming rules, could we also do the following…</p> <pre><code>add_action('save_post', 'log_when_saved'); function log_when_saved($some_random_variable_name){ do something with $post_id }; </code></pre> <p>and it would know that <code>$some_random_variable_name</code> would be the post id because is first defined argument in our <code>do_action(‘save_post’, $post_ID, $post, $update)</code> statement?</p> <p>Thank you in advance,</p>
[ { "answer_id": 383662, "author": "Buttered_Toast", "author_id": 192133, "author_profile": "https://wordpress.stackexchange.com/users/192133", "pm_score": 3, "selected": false, "text": "<p>For this example lets say we have the following</p>\n<pre><code>do_action('bt_custom_action', get_th...
2021/02/19
[ "https://wordpress.stackexchange.com/questions/383658", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202161/" ]
I am trying to understand some fundamentals of php with regards to adding new functions to actions. I found a tutorial where he adds a new function to the `save_post` action… ``` add_action('save_post', 'log_when_saved'); function log_when_saved($post_id){ do something with $post_id }; ``` Is my understanding correct that when we fire the action elsewhere via `do_action('save_post', $post_ID, $post, $update)` the parameters we pass it at this time are automatically & instantly available to use in our new function we are adding to the action and that is what is going on here? When we write `add_action('save_post', ‘log_when_saved’);` we are adding some new function to be run when the action is fired. This new function to be run can automatically use the variable values that were defined when we fired the action via the `do_action`. Is this correct? What if we wanted to pass in the `$post` and `$update` parameters to this new function also… would we have to do the following… ``` add_action('save_post', 'log_when_saved'); function log_when_saved($post_id, $post, $update){ do something with $post_id, $post, $update}; ``` One of the fundamental things I am trying to understand is do the parameters that we are passing our new function strictly have to be in the order that they were defined in `do_action('save_post', $post_ID, $post, $update)` and similarly, would you have to call all 3 if we wanted to get the last parameter `$update` to use in our function? With regards to naming rules, could we also do the following… ``` add_action('save_post', 'log_when_saved'); function log_when_saved($some_random_variable_name){ do something with $post_id }; ``` and it would know that `$some_random_variable_name` would be the post id because is first defined argument in our `do_action(‘save_post’, $post_ID, $post, $update)` statement? Thank you in advance,
For this example lets say we have the following ``` do_action('bt_custom_action', get_the_ID(), get_the_title(), get_the_content()); ``` The arguments that will be passed to `add_action` would be in this order 1. the post id 2. the post title 3. the post content By default if we hook into our `do_action` without any arguments, like this ``` add_action('bt_custom_action', 'bt_callback_func'); ``` Our call back function "gets" one argument, in this case the ID ``` function bt_callback_func ($id) { echo $id; } ``` In order to get the post content we would need to do something like this ``` add_action('bt_custom_action', 'bt_callback_func', 10, 3); ``` This will pass three arguments to our callback function and to use them we would do something like this ``` function bt_callback_func ($id, $title, $content) { echo $id . '<br>' . $title . '<br>' . $content; } ``` Now to finally answer your question about getting a specific argument. If we go by this example ``` add_action('bt_custom_action', 'bt_callback_func', 10, 3); ``` we know that our callback function will get three arguments, but we only need the content. We don't have to set parameters for each and every expected argument. We can use PHPs `...`, see [Variable-length argument lists](https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list). So now our callback function will look like this ``` function bt_callback_func (...$args) { echo args[2]; } ``` Because in our add action we told that our callback will expect three arguments and we know that the third argument is what we need (the content), using `...` we now created a variable that will contain all passed argumnets. In this case it will contain an array with three elements in order. ID, title and then content. We know that content is last, third, in our array. We can target it directly like this `$args[2]`. Hope this helps =]
383,684
<p>I created a loop for my Custom Posts Type <code>workshop</code> with two custom taxonomies <code>group</code> and <code>teacher</code> on the same page. The Ajax filter works perfectly thanks to the solution provided <a href="https://wordpress.stackexchange.com/questions/383666/ajax-filter-with-custom-taxonomies">here</a>. The user can select one taxonomy or both to display the posts.</p> <p>Each links of the filter works with a <code>&lt;input type=&quot;radio&quot;...&gt;</code>, for both taxonomies lists. What I'm trying to achieve is to create a button <code>.filter-reset</code> which resets all the radio inputs and displays all the posts of my Custom Posts Type.</p> <p>The issue is when I click the button, it returns &quot;No posts found&quot;.</p> <p>Here is the PHP code for the filter in the frontend:</p> <pre><code>&lt;form action=&quot;&lt;?php echo site_url() ?&gt;/wp-admin/admin-ajax.php&quot; method=&quot;POST&quot; id=&quot;filter&quot; class=&quot;form-filter&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;?php if( $terms = get_terms( 'group', 'orderby=name&amp;exclude=-1' ) ) : echo '&lt;div class=&quot;filter-tax filter--group&quot;&gt;'; foreach ( $terms as $term ) : echo '&lt;input class=&quot;btn-radio&quot; type=&quot;radio&quot; name=&quot;categoryfilter1&quot; value=&quot;' . $term-&gt;term_id . '&quot;&gt;&lt;label&gt;' . $term-&gt;name . '&lt;/label&gt;'; endforeach; echo '&lt;/div&gt;'; endif; if( $terms = get_terms( 'teacher', 'orderby=name&amp;exclude=-1' ) ) : echo '&lt;div class=&quot;filter-tax filter--teacher&quot;&gt;'; foreach ( $terms as $term ) : echo '&lt;input class=&quot;btn-radio&quot; type=&quot;radio&quot; name=&quot;categoryfilter2&quot; value=&quot;' . $term-&gt;term_id . '&quot;&gt;&lt;label&gt;' . $term-&gt;name . '&lt;/label&gt;'; endforeach; echo '&lt;/div&gt;'; endif; ?&gt; &lt;a href=&quot;#&quot; class=&quot;filter-reset&quot;&gt;View all&lt;/a&gt; &lt;input type=&quot;hidden&quot; name=&quot;action&quot; value=&quot;myfilter&quot;&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>The PHP code for the AJAX filter in my functions.php:</p> <pre><code>add_action('wp_ajax_myfilter', 'mysite_filter_function'); add_action('wp_ajax_nopriv_myfilter', 'mysite_filter_function'); function mysite_filter_function(){ $args = array( 'orderby' =&gt; 'date', 'posts_per_page' =&gt; -1 ); if (isset($_POST['categoryfilter1']) &amp;&amp; isset($_POST['categoryfilter2'])) { $args['tax_query'] = array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'group', 'field' =&gt; 'id', 'terms' =&gt; $_POST['categoryfilter1'] ), array( 'taxonomy' =&gt; 'teacher', 'field' =&gt; 'id', 'terms' =&gt; $_POST['categoryfilter2'] ), ); } elseif (isset($_POST['categoryfilter1']) &amp;&amp; !isset($_POST['categoryfilter2'])) { $args['tax_query'] = array( array( 'taxonomy' =&gt; 'group', 'field' =&gt; 'id', 'terms' =&gt; $_POST['categoryfilter1'] ) ); } elseif (!isset($_POST['categoryfilter1']) &amp;&amp; isset($_POST['categoryfilter2'])) { $args['tax_query'] = array( array( 'taxonomy' =&gt; 'teacher', 'field' =&gt; 'id', 'terms' =&gt; $_POST['categoryfilter2'] ) ); } $query = new WP_Query( $args ); if( $query-&gt;have_posts() ) : while( $query-&gt;have_posts() ): $query-&gt;the_post(); get_template_part( 'template-parts/content-archive' ); endwhile; wp_reset_postdata(); else : echo 'No posts found'; endif; die(); } </code></pre> <p>The JS code:</p> <pre><code>$('#filter').change(function(){ var filter = $('#filter'); $.ajax({ url:filter.attr('action'), data:filter.serialize(), type:filter.attr('method'), beforeSend:function(xhr){ //filter.find('button').text('Processing...'); }, success:function(data){ //filter.find('button').text('Filter'); $('.loop-archive').html(data); } }); return false; }); $(&quot;.filter-reset&quot;).click(function() { document.getElementById('filter').reset(); $('.loop-archive-workshop').append(); var filter = $('#filter'); $.ajax({ url:filter.attr('action'), type:filter.attr('method'), data:filter.serialize(), success:function(data){ $('.loop-archive').html(data); } }); return false; }); </code></pre> <p>Thank you.</p> <blockquote> <p>EDIT</p> </blockquote> <p>Here is the log.txt when I click the reset button:</p> <pre><code>Array ( [action] =&gt; myfilter ) </code></pre>
[ { "answer_id": 383685, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>The issue is using <code>isset()</code> for the conditions:</p>\n<pre><code>isset($_POST['categoryfilte...
2021/02/19
[ "https://wordpress.stackexchange.com/questions/383684", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110282/" ]
I created a loop for my Custom Posts Type `workshop` with two custom taxonomies `group` and `teacher` on the same page. The Ajax filter works perfectly thanks to the solution provided [here](https://wordpress.stackexchange.com/questions/383666/ajax-filter-with-custom-taxonomies). The user can select one taxonomy or both to display the posts. Each links of the filter works with a `<input type="radio"...>`, for both taxonomies lists. What I'm trying to achieve is to create a button `.filter-reset` which resets all the radio inputs and displays all the posts of my Custom Posts Type. The issue is when I click the button, it returns "No posts found". Here is the PHP code for the filter in the frontend: ``` <form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter" class="form-filter"> <div class="container"> <?php if( $terms = get_terms( 'group', 'orderby=name&exclude=-1' ) ) : echo '<div class="filter-tax filter--group">'; foreach ( $terms as $term ) : echo '<input class="btn-radio" type="radio" name="categoryfilter1" value="' . $term->term_id . '"><label>' . $term->name . '</label>'; endforeach; echo '</div>'; endif; if( $terms = get_terms( 'teacher', 'orderby=name&exclude=-1' ) ) : echo '<div class="filter-tax filter--teacher">'; foreach ( $terms as $term ) : echo '<input class="btn-radio" type="radio" name="categoryfilter2" value="' . $term->term_id . '"><label>' . $term->name . '</label>'; endforeach; echo '</div>'; endif; ?> <a href="#" class="filter-reset">View all</a> <input type="hidden" name="action" value="myfilter"> </div> </form> ``` The PHP code for the AJAX filter in my functions.php: ``` add_action('wp_ajax_myfilter', 'mysite_filter_function'); add_action('wp_ajax_nopriv_myfilter', 'mysite_filter_function'); function mysite_filter_function(){ $args = array( 'orderby' => 'date', 'posts_per_page' => -1 ); if (isset($_POST['categoryfilter1']) && isset($_POST['categoryfilter2'])) { $args['tax_query'] = array( 'relation' => 'AND', array( 'taxonomy' => 'group', 'field' => 'id', 'terms' => $_POST['categoryfilter1'] ), array( 'taxonomy' => 'teacher', 'field' => 'id', 'terms' => $_POST['categoryfilter2'] ), ); } elseif (isset($_POST['categoryfilter1']) && !isset($_POST['categoryfilter2'])) { $args['tax_query'] = array( array( 'taxonomy' => 'group', 'field' => 'id', 'terms' => $_POST['categoryfilter1'] ) ); } elseif (!isset($_POST['categoryfilter1']) && isset($_POST['categoryfilter2'])) { $args['tax_query'] = array( array( 'taxonomy' => 'teacher', 'field' => 'id', 'terms' => $_POST['categoryfilter2'] ) ); } $query = new WP_Query( $args ); if( $query->have_posts() ) : while( $query->have_posts() ): $query->the_post(); get_template_part( 'template-parts/content-archive' ); endwhile; wp_reset_postdata(); else : echo 'No posts found'; endif; die(); } ``` The JS code: ``` $('#filter').change(function(){ var filter = $('#filter'); $.ajax({ url:filter.attr('action'), data:filter.serialize(), type:filter.attr('method'), beforeSend:function(xhr){ //filter.find('button').text('Processing...'); }, success:function(data){ //filter.find('button').text('Filter'); $('.loop-archive').html(data); } }); return false; }); $(".filter-reset").click(function() { document.getElementById('filter').reset(); $('.loop-archive-workshop').append(); var filter = $('#filter'); $.ajax({ url:filter.attr('action'), type:filter.attr('method'), data:filter.serialize(), success:function(data){ $('.loop-archive').html(data); } }); return false; }); ``` Thank you. > > EDIT > > > Here is the log.txt when I click the reset button: ``` Array ( [action] => myfilter ) ```
Going by what @JacobPeattie said, that they are still set but empty you need to change the conditional login to check for empty. In our previous discussion I wrote this conditions ``` if ((isset($_POST['categoryfilter1']) && !empty($_POST['categoryfilter1'])) && (isset($_POST['categoryfilter2']) && !empty($_POST['categoryfilter2']))) { // both properties are set and have value (not empty) } elseif ((isset($_POST['categoryfilter1']) && !empty($_POST['categoryfilter1'])) && (!isset($_POST['categoryfilter2']) || empty($_POST['categoryfilter2']))) { // only categoryfilter1 is set and has value and categoryfilter2 is either not set or set but has no value } elseif ((!isset($_POST['categoryfilter1']) || empty($_POST['categoryfilter1'])) && (isset($_POST['categoryfilter2']) && !empty($_POST['categoryfilter2']))) { // only categoryfilter2 is set and has value and categoryfilter1 is either not set or set but has no value } ``` Try using it and see if it helps > > EDIT > > > I dont know what post type you want to get but try adding it to the $args as well. So you initial $args will look like this ``` $args = array( 'post_type' => 'post', // 'post_status' => 'publish', // this is optional, this will get only published posts 'orderby' => 'date', 'posts_per_page' => -1 ); ``` I think that this creates the problem
383,690
<p>So i need to get and echo current users last post date.</p> <p>What i have researched and tested.</p> <p>Red article here: <a href="https://developer.wordpress.org/reference/functions/get_most_recent_post_of_user/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/functions/get_most_recent_post_of_user/</a></p> <p>Red this thread here but none of the codes worked: <a href="https://wordpress.stackexchange.com/questions/123051/get-how-many-days-since-last-post-of-the-current-user">Get how many days since last post of the current user</a></p> <p>The best codes i tried was this and it didn't work.</p> <pre><code>$user_id = wp_get_current_user(); echo get_most_recent_post_of_user( $user_id ); $user_id == 2; echo get_most_recent_post_of_user( $user_id ); </code></pre>
[ { "answer_id": 383685, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>The issue is using <code>isset()</code> for the conditions:</p>\n<pre><code>isset($_POST['categoryfilte...
2021/02/19
[ "https://wordpress.stackexchange.com/questions/383690", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138704/" ]
So i need to get and echo current users last post date. What i have researched and tested. Red article here: <https://developer.wordpress.org/reference/functions/get_most_recent_post_of_user/> Red this thread here but none of the codes worked: [Get how many days since last post of the current user](https://wordpress.stackexchange.com/questions/123051/get-how-many-days-since-last-post-of-the-current-user) The best codes i tried was this and it didn't work. ``` $user_id = wp_get_current_user(); echo get_most_recent_post_of_user( $user_id ); $user_id == 2; echo get_most_recent_post_of_user( $user_id ); ```
Going by what @JacobPeattie said, that they are still set but empty you need to change the conditional login to check for empty. In our previous discussion I wrote this conditions ``` if ((isset($_POST['categoryfilter1']) && !empty($_POST['categoryfilter1'])) && (isset($_POST['categoryfilter2']) && !empty($_POST['categoryfilter2']))) { // both properties are set and have value (not empty) } elseif ((isset($_POST['categoryfilter1']) && !empty($_POST['categoryfilter1'])) && (!isset($_POST['categoryfilter2']) || empty($_POST['categoryfilter2']))) { // only categoryfilter1 is set and has value and categoryfilter2 is either not set or set but has no value } elseif ((!isset($_POST['categoryfilter1']) || empty($_POST['categoryfilter1'])) && (isset($_POST['categoryfilter2']) && !empty($_POST['categoryfilter2']))) { // only categoryfilter2 is set and has value and categoryfilter1 is either not set or set but has no value } ``` Try using it and see if it helps > > EDIT > > > I dont know what post type you want to get but try adding it to the $args as well. So you initial $args will look like this ``` $args = array( 'post_type' => 'post', // 'post_status' => 'publish', // this is optional, this will get only published posts 'orderby' => 'date', 'posts_per_page' => -1 ); ``` I think that this creates the problem
383,794
<p>WordPress has a cron named &quot;<code>delete_expired_transients</code>&quot; as seen in the image below.</p> <p><a href="https://i.stack.imgur.com/901Ap.png" rel="noreferrer"><img src="https://i.stack.imgur.com/901Ap.png" alt="enter image description here" /></a></p> <p>In this way, does it clean expired <strong>transients</strong> daily?</p> <hr /> <p><strong>Or is it just giving us action?</strong></p> <p>Should we clean it ourselves in this way according to the hook?</p> <pre class="lang-php prettyprint-override"><code>add_action('delete_expired_transients', 'my_custom_fn'); function my_custom_fn() { delete_expired_transients(); } </code></pre> <p>See also: <a href="https://developer.wordpress.org/reference/functions/delete_expired_transients/" rel="noreferrer">delete_expired_transients()</a></p>
[ { "answer_id": 383796, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 4, "selected": true, "text": "<p>Yes, <code>delete_expired_transients</code> is a cron event that runs once per day and the function <code>d...
2021/02/21
[ "https://wordpress.stackexchange.com/questions/383794", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/162608/" ]
WordPress has a cron named "`delete_expired_transients`" as seen in the image below. [![enter image description here](https://i.stack.imgur.com/901Ap.png)](https://i.stack.imgur.com/901Ap.png) In this way, does it clean expired **transients** daily? --- **Or is it just giving us action?** Should we clean it ourselves in this way according to the hook? ```php add_action('delete_expired_transients', 'my_custom_fn'); function my_custom_fn() { delete_expired_transients(); } ``` See also: [delete\_expired\_transients()](https://developer.wordpress.org/reference/functions/delete_expired_transients/)
Yes, `delete_expired_transients` is a cron event that runs once per day and the function `delete_expired_transients()` is automatically called when the cron event runs — see [*wp-includes/default-filters.php*](https://core.trac.wordpress.org/browser/tags/5.6.1/src/wp-includes/default-filters.php#L387). So you do not need to call the function manually like you did in your `my_custom_fn()` function. And if you use a plugin like [WP Crontrol](https://wordpress.org/plugins/wp-crontrol/), you can easily view the cron events in your site and the actions (functions) that will be called when a specific cron event runs.
383,824
<p>I am desperately attempting to find a way to get an alert when a specific article on my WordPress is visited (and no, I will not be flooded by emails, the code will be used temporarely) Being new to php, I used this code, but the site gets a critical error if I put it into the functions.php?</p> <pre><code> function email_alert() { wp_mail( 'aprilia@example.net', 'Alert', 'This Site was Visited!' ); } if(is_article(1234)){ } add_action( 'wp', 'email_alert' ); </code></pre> <p>please help/advice, a big thank you!</p>
[ { "answer_id": 383829, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 1, "selected": false, "text": "<p>There's no <code>is_article</code>. I assume you guessed there would be analogously to is_page, but I don't think a...
2021/02/22
[ "https://wordpress.stackexchange.com/questions/383824", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202302/" ]
I am desperately attempting to find a way to get an alert when a specific article on my WordPress is visited (and no, I will not be flooded by emails, the code will be used temporarely) Being new to php, I used this code, but the site gets a critical error if I put it into the functions.php? ``` function email_alert() { wp_mail( 'aprilia@example.net', 'Alert', 'This Site was Visited!' ); } if(is_article(1234)){ } add_action( 'wp', 'email_alert' ); ``` please help/advice, a big thank you!
here we go, this is the code that works, triggering an email-alert when a specific article is viewed ``` function email_alert() { global $post; if( $post->ID == 1234) { wp_mail( 'aprilia@example.net', 'Alert', 'This Site was Visited!' ); } } add_action( 'wp', 'email_alert' ); ```
383,894
<p>I have a single page site with all content on it. The only other page I have is a &quot;thanks for submitting the contact form&quot; page. In this &quot;thankssubmit.php&quot; page I have my PHP form submission code.</p> <p>I'm new to wordpress so I may be doing this totally wrong but I've created a custom page template for this &quot;thankssubmit.php&quot; page using /<em>Template Name: Thanks Submit</em>/.</p> <p>I've then applied that template to a brand new page in WP. I can't add .php to the slug which is maybe the only problem but I can't see a way around this. A strange issue is that when I submit the form I go to the correct URL but get a &quot;page not found&quot; error. If I copy and paste this exact same URL I go to the correct page...</p> <p>Below is the code for all.</p> <p>I've had a look and I can't see this question being a repeat but if so a nudge in the right direction would be greatly appreciated!</p> <p>Form</p> <pre><code>&lt;form method=&quot;post&quot; action=&quot;thankssubmit.php&quot;&gt; &lt;h3&gt;Drop Us a Message&lt;/h3&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-sm&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;input id=&quot;nameInput&quot; type=&quot;text&quot; name=&quot;name&quot; onkeyup=&quot;manage(this)&quot; class=&quot;form-control&quot; placeholder=&quot;Your Name *&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;input id=&quot;emailInput&quot; type=&quot;text&quot; name=&quot;email&quot; onkeyup=&quot;manage(this)&quot; class=&quot;form-control&quot; placeholder=&quot;Your Email *&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;phone&quot; class=&quot;form-control&quot; placeholder=&quot;Your Phone Number&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;input id=&quot;weddingDatePicker&quot; type=&quot;date&quot; name=&quot;date&quot; class=&quot;form-control&quot; placeholder=&quot;Your Wedding Date -&quot; /&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;hear&quot; class=&quot;form-control&quot; placeholder=&quot;How did you hear about us?&quot; /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col&quot;&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;textarea id=&quot;messageInput&quot; name=&quot;message&quot; onkeyup=&quot;manage(this)&quot; class=&quot;form-control&quot; placeholder=&quot;Your Message *&quot; style=&quot;width: 100%; height: 254px;&quot;&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;input id=&quot;contactSubmitBtn&quot; type=&quot;submit&quot; disabled name=&quot;btnSubmit&quot; class=&quot;btn&quot; value=&quot;Send Message&quot; /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>thankssubmit.php page</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;!-- THANKS OR SUCCESS MESSAGE AFTER THE EMAIL HAS BEEN SENT --&gt; &lt;section id=&quot;thanksMsgPG&quot;&gt; &lt;h1 class=&quot;thanksmsg&quot;&gt;Thanks for getting in touch.&lt;/h1&gt; &lt;h3 class=&quot;thanksmsg&quot;&gt;We'll get back to you ASAP!&lt;/h3&gt; &lt;a href=&quot;/&quot;&gt;&lt;button class=&quot;btn &quot;&gt;Back&lt;/button&gt;&lt;/a&gt; &lt;/section&gt; &lt;?php get_footer(); ?&gt; &lt;?php /* Template Name: Thanks Submit */ if (isset($_POST['btnSubmit'])) { // EMAIL AND SUBJECT OF EMAIL BEING SENT $email_to = &quot;hello@everafterfilmsni.com&quot;; $subject = &quot;Contact Submission Form&quot;; //ERROR MESSAGES IF DIED FUCNTION IS CALLED (SEMI-REDUNDANT BECAUSE SEND BUTTON WONT BE ENABLED UNTIL INPUT FIELDS ARE FILLED CORRECTLY ANYWAY) function died($error) { echo &quot;We are very sorry, but there were error(s) found with the form you submitted. &quot;; echo &quot;These errors appear below.&lt;br /&gt;&lt;br /&gt;&quot;; echo $error . &quot;&lt;br /&gt;&lt;br /&gt;&quot;; echo &quot;Please go back and fix these errors.&lt;br /&gt;&lt;br /&gt;&quot;; die(); } // IF NOTHING ENTERED THEN THROW ERROR MESSAGE if (!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['message'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } //GETTING THE NAME EMAIL PHONE MESSAGE FROM THE FORM AND PUTTING IT INTO VARIABLES $full_name = $_POST['name']; // required $email_from = $_POST['email']; // required $phone = $_POST['phone']; $date = $_POST['date']; $hear = $_POST['hear']; // required $message = $_POST['message']; // required $error_message = &quot;&quot;; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; //CHECKING TO MAKE SURE VALID EMAIL IS ENTERED if (!preg_match($email_exp, $email_from)) { $error_message .= 'The e-mail you entered does not appear to be valid.&lt;br /&gt;'; } //CHECKING TO MAKE SURE VALID NAME IS ENTERED $string_exp = &quot;/^[A-Za-z .'-]+$/&quot;; if (!preg_match($string_exp, $full_name)) { $error_message .= 'The name you entered does not appear to be valid.&lt;br /&gt;'; } //CHECKING TO MAKE SURE MESSAGE IS MORE THAN 2 CHARACTERS if (strlen($message) &lt; 2) { $error_message .= 'The message you entered does not appear to be valid.&lt;br /&gt;'; } if (strlen($error_message) &gt; 0) { died($error_message); } $email_message = &quot;Form details below.\n\n&quot;; //MAKING SURE THERE ARE NO HEADER INJECTIONS function clean_string($string) { $bad = array(&quot;content-type&quot;, &quot;bcc:&quot;, &quot;to:&quot;, &quot;cc:&quot;, &quot;href&quot;); return str_replace($bad, &quot;&quot;, $string); } //THE FORMAT OF THE EMAIL BEING SENT. CLEAN STRING CLEANING ANY WHITE SPACE $email_message .= &quot;Name: &quot; . clean_string($full_name) . &quot;\n&quot;; $email_message .= &quot;Email: &quot; . clean_string($email_from) . &quot;\n&quot;; $email_message .= &quot;Phone: &quot; . clean_string($phone) . &quot;\n&quot;; $email_message .= &quot;Wedding Date: &quot; . clean_string($date) . &quot;\n&quot;; $email_message .= &quot;I heard about you via: &quot; . clean_string($hear) . &quot;\n&quot;; $email_message .= &quot;Message: \r\n&quot; . clean_string($message) . &quot;\n&quot;; $email_from = $full_name . '&lt;' . $email_from . '&gt;'; // CREATING EMAIL HEADER FOR GMAIL TO RECOGNISE $headers = 'From: ' . $email_from . &quot;\r\n&quot; . 'Reply-To: ' . $email_from . &quot;\r\n&quot; . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $subject, $email_message, $headers); // echo $email_message; ?&gt; &lt;?php } ?&gt; </code></pre> <p>First image below shows the URL error after we submit the form and the second shows after we reload the pages URL.<a href="https://i.stack.imgur.com/JuN0p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JuN0p.png" alt="After click submit button on previous page" /></a></p> <p><a href="https://i.stack.imgur.com/0NnZI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0NnZI.png" alt="After reload of URL" /></a></p>
[ { "answer_id": 383829, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 1, "selected": false, "text": "<p>There's no <code>is_article</code>. I assume you guessed there would be analogously to is_page, but I don't think a...
2021/02/23
[ "https://wordpress.stackexchange.com/questions/383894", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202384/" ]
I have a single page site with all content on it. The only other page I have is a "thanks for submitting the contact form" page. In this "thankssubmit.php" page I have my PHP form submission code. I'm new to wordpress so I may be doing this totally wrong but I've created a custom page template for this "thankssubmit.php" page using /*Template Name: Thanks Submit*/. I've then applied that template to a brand new page in WP. I can't add .php to the slug which is maybe the only problem but I can't see a way around this. A strange issue is that when I submit the form I go to the correct URL but get a "page not found" error. If I copy and paste this exact same URL I go to the correct page... Below is the code for all. I've had a look and I can't see this question being a repeat but if so a nudge in the right direction would be greatly appreciated! Form ``` <form method="post" action="thankssubmit.php"> <h3>Drop Us a Message</h3> <div class="row"> <div class="col-sm"> <div class="form-group"> <input id="nameInput" type="text" name="name" onkeyup="manage(this)" class="form-control" placeholder="Your Name *" /> </div> <div class="form-group"> <input id="emailInput" type="text" name="email" onkeyup="manage(this)" class="form-control" placeholder="Your Email *" /> </div> <div class="form-group"> <input type="text" name="phone" class="form-control" placeholder="Your Phone Number" /> </div> <div class="form-group"> <input id="weddingDatePicker" type="date" name="date" class="form-control" placeholder="Your Wedding Date -" /> </div> <div class="form-group"> <input type="text" name="hear" class="form-control" placeholder="How did you hear about us?" /> </div> </div> <div class="col"> <div class="form-group"> <textarea id="messageInput" name="message" onkeyup="manage(this)" class="form-control" placeholder="Your Message *" style="width: 100%; height: 254px;"></textarea> </div> <div class="form-group"> <input id="contactSubmitBtn" type="submit" disabled name="btnSubmit" class="btn" value="Send Message" /> </div> </div> </div> </form> ``` thankssubmit.php page ``` <?php get_header(); ?> <!-- THANKS OR SUCCESS MESSAGE AFTER THE EMAIL HAS BEEN SENT --> <section id="thanksMsgPG"> <h1 class="thanksmsg">Thanks for getting in touch.</h1> <h3 class="thanksmsg">We'll get back to you ASAP!</h3> <a href="/"><button class="btn ">Back</button></a> </section> <?php get_footer(); ?> <?php /* Template Name: Thanks Submit */ if (isset($_POST['btnSubmit'])) { // EMAIL AND SUBJECT OF EMAIL BEING SENT $email_to = "hello@everafterfilmsni.com"; $subject = "Contact Submission Form"; //ERROR MESSAGES IF DIED FUCNTION IS CALLED (SEMI-REDUNDANT BECAUSE SEND BUTTON WONT BE ENABLED UNTIL INPUT FIELDS ARE FILLED CORRECTLY ANYWAY) function died($error) { echo "We are very sorry, but there were error(s) found with the form you submitted. "; echo "These errors appear below.<br /><br />"; echo $error . "<br /><br />"; echo "Please go back and fix these errors.<br /><br />"; die(); } // IF NOTHING ENTERED THEN THROW ERROR MESSAGE if (!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['message'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } //GETTING THE NAME EMAIL PHONE MESSAGE FROM THE FORM AND PUTTING IT INTO VARIABLES $full_name = $_POST['name']; // required $email_from = $_POST['email']; // required $phone = $_POST['phone']; $date = $_POST['date']; $hear = $_POST['hear']; // required $message = $_POST['message']; // required $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; //CHECKING TO MAKE SURE VALID EMAIL IS ENTERED if (!preg_match($email_exp, $email_from)) { $error_message .= 'The e-mail you entered does not appear to be valid.<br />'; } //CHECKING TO MAKE SURE VALID NAME IS ENTERED $string_exp = "/^[A-Za-z .'-]+$/"; if (!preg_match($string_exp, $full_name)) { $error_message .= 'The name you entered does not appear to be valid.<br />'; } //CHECKING TO MAKE SURE MESSAGE IS MORE THAN 2 CHARACTERS if (strlen($message) < 2) { $error_message .= 'The message you entered does not appear to be valid.<br />'; } if (strlen($error_message) > 0) { died($error_message); } $email_message = "Form details below.\n\n"; //MAKING SURE THERE ARE NO HEADER INJECTIONS function clean_string($string) { $bad = array("content-type", "bcc:", "to:", "cc:", "href"); return str_replace($bad, "", $string); } //THE FORMAT OF THE EMAIL BEING SENT. CLEAN STRING CLEANING ANY WHITE SPACE $email_message .= "Name: " . clean_string($full_name) . "\n"; $email_message .= "Email: " . clean_string($email_from) . "\n"; $email_message .= "Phone: " . clean_string($phone) . "\n"; $email_message .= "Wedding Date: " . clean_string($date) . "\n"; $email_message .= "I heard about you via: " . clean_string($hear) . "\n"; $email_message .= "Message: \r\n" . clean_string($message) . "\n"; $email_from = $full_name . '<' . $email_from . '>'; // CREATING EMAIL HEADER FOR GMAIL TO RECOGNISE $headers = 'From: ' . $email_from . "\r\n" . 'Reply-To: ' . $email_from . "\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $subject, $email_message, $headers); // echo $email_message; ?> <?php } ?> ``` First image below shows the URL error after we submit the form and the second shows after we reload the pages URL.[![After click submit button on previous page](https://i.stack.imgur.com/JuN0p.png)](https://i.stack.imgur.com/JuN0p.png) [![After reload of URL](https://i.stack.imgur.com/0NnZI.png)](https://i.stack.imgur.com/0NnZI.png)
here we go, this is the code that works, triggering an email-alert when a specific article is viewed ``` function email_alert() { global $post; if( $post->ID == 1234) { wp_mail( 'aprilia@example.net', 'Alert', 'This Site was Visited!' ); } } add_action( 'wp', 'email_alert' ); ```
384,038
<p>I'm using the following code to set my Open Graph meta data in functions.php</p> <p>It works great for selecting the featured image, however I would like to set it to use the product gallery image instead (which is better for social media marketing). Here's a screen grab to be more specific: <a href="https://snipboard.io/buvHfk.jpg" rel="nofollow noreferrer">https://snipboard.io/buvHfk.jpg</a></p> <p>How can I modify the code below to target the 1st WooCommerce gallery image? I could not find <em>anything</em> on this.</p> <pre><code>function insert_fb_in_head() { global $post; if ( !is_singular()) //if it is not a post or a page return; echo '&lt;meta property=&quot;og:title&quot; content=&quot;' . get_the_title() . '&quot;/&gt;'; echo '&lt;meta property=&quot;og:type&quot; content=&quot;article&quot;/&gt;'; echo '&lt;meta property=&quot;og:url&quot; content=&quot;' . get_permalink() . '&quot;/&gt;'; echo '&lt;meta property=&quot;og:site_name&quot; content=&quot;My Website&quot;/&gt;'; if( isset( $gallery_image_ids[1] ) ) { //the post does not have featured image, use a default image $default_image=&quot;https://www.website.com&quot;; //replace this with a default image on your server or an image in your media library echo '&lt;meta property=&quot;og:image&quot; content=&quot;' . $default_image . '&quot;/&gt;'; } else{ $thumbnail_src = wp_get_attachment_image_url( $gallery_image_ids[1], 'single-post-thumbnail'); echo '&lt;meta property=&quot;og:image&quot; content=&quot;' . esc_attr( $thumbnail_src[0] ) . '&quot;/&gt;'; } echo &quot; &quot;; } add_action( 'wp_head', 'insert_fb_in_head', 5 ); </code></pre> <p>Thank you in advance for your help.</p> <p>Dan</p>
[ { "answer_id": 383829, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 1, "selected": false, "text": "<p>There's no <code>is_article</code>. I assume you guessed there would be analogously to is_page, but I don't think a...
2021/02/25
[ "https://wordpress.stackexchange.com/questions/384038", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/73776/" ]
I'm using the following code to set my Open Graph meta data in functions.php It works great for selecting the featured image, however I would like to set it to use the product gallery image instead (which is better for social media marketing). Here's a screen grab to be more specific: <https://snipboard.io/buvHfk.jpg> How can I modify the code below to target the 1st WooCommerce gallery image? I could not find *anything* on this. ``` function insert_fb_in_head() { global $post; if ( !is_singular()) //if it is not a post or a page return; echo '<meta property="og:title" content="' . get_the_title() . '"/>'; echo '<meta property="og:type" content="article"/>'; echo '<meta property="og:url" content="' . get_permalink() . '"/>'; echo '<meta property="og:site_name" content="My Website"/>'; if( isset( $gallery_image_ids[1] ) ) { //the post does not have featured image, use a default image $default_image="https://www.website.com"; //replace this with a default image on your server or an image in your media library echo '<meta property="og:image" content="' . $default_image . '"/>'; } else{ $thumbnail_src = wp_get_attachment_image_url( $gallery_image_ids[1], 'single-post-thumbnail'); echo '<meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>'; } echo " "; } add_action( 'wp_head', 'insert_fb_in_head', 5 ); ``` Thank you in advance for your help. Dan
here we go, this is the code that works, triggering an email-alert when a specific article is viewed ``` function email_alert() { global $post; if( $post->ID == 1234) { wp_mail( 'aprilia@example.net', 'Alert', 'This Site was Visited!' ); } } add_action( 'wp', 'email_alert' ); ```
384,040
<p>I have custom post type.</p> <p>How it is possible to loop through the page created in this custom post type please ?</p> <p>Thanks.</p>
[ { "answer_id": 383829, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 1, "selected": false, "text": "<p>There's no <code>is_article</code>. I assume you guessed there would be analogously to is_page, but I don't think a...
2021/02/25
[ "https://wordpress.stackexchange.com/questions/384040", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202291/" ]
I have custom post type. How it is possible to loop through the page created in this custom post type please ? Thanks.
here we go, this is the code that works, triggering an email-alert when a specific article is viewed ``` function email_alert() { global $post; if( $post->ID == 1234) { wp_mail( 'aprilia@example.net', 'Alert', 'This Site was Visited!' ); } } add_action( 'wp', 'email_alert' ); ```
384,067
<p>Let´s say a user signs up to multiple memberships, each on a different date.</p> <p>User signs up to:</p> <ul> <li>Membership A on 05.03.2021</li> <li>Membership B on 17.05.2021</li> <li>Membership C on 29.07.2021</li> </ul> <p>I would like the dates for that user to be saved with the same meta_key. Each saved value/date should be linked to the specific membership, so that I can run a check and get the date when the user signed up for a specific membership.</p> <p>I have the following so far:</p> <pre class="lang-php prettyprint-override"><code>$parameters = array( 'member_id' =&gt; $user_id, 'membership' =&gt; array ( array ( 'tags' =&gt; $tags, 'datetime' =&gt; time(), ) ) ); add_user_meta( $user_id, 'membership', $parameters ); </code></pre> <p>I would want to have the result for a user be something like:</p> <pre><code>membership: [0] Tag: Membership A Date: 05.03.2021 [1] Tag: Membership B Date: 17.05.2021 [2] Tag: Membership C Date: 29.07.2021 </code></pre> <p>In the <code>var_dump</code> it would look something like, where the number of sub-arrays for &quot;membership&quot; will be different per user, depending on the number of memberships they have assigned to them.</p> <pre><code>array(2) { [&quot;member_id&quot;]=&gt; string(2) &quot;12&quot; [&quot;memberships&quot;]=&gt; array(3) { [0]=&gt; array(2) { [&quot;membership&quot;]=&gt; string(5) &quot;membership A&quot; [&quot;datetime&quot;]=&gt; int(1616239233) } [1]=&gt; array(2) { [&quot;membership&quot;]=&gt; string(5) &quot;membership B &quot; [&quot;datetime&quot;]=&gt; int(1616239233) } [2]=&gt; array(2) { [&quot;membership&quot;]=&gt; string(5) &quot;membership C&quot; [&quot;datetime&quot;]=&gt; int(1616239233) } } } </code></pre> <p>I´m sure I am missing something, look forward to hearing your thoughts. Thanks</p>
[ { "answer_id": 383829, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 1, "selected": false, "text": "<p>There's no <code>is_article</code>. I assume you guessed there would be analogously to is_page, but I don't think a...
2021/02/25
[ "https://wordpress.stackexchange.com/questions/384067", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202502/" ]
Let´s say a user signs up to multiple memberships, each on a different date. User signs up to: * Membership A on 05.03.2021 * Membership B on 17.05.2021 * Membership C on 29.07.2021 I would like the dates for that user to be saved with the same meta\_key. Each saved value/date should be linked to the specific membership, so that I can run a check and get the date when the user signed up for a specific membership. I have the following so far: ```php $parameters = array( 'member_id' => $user_id, 'membership' => array ( array ( 'tags' => $tags, 'datetime' => time(), ) ) ); add_user_meta( $user_id, 'membership', $parameters ); ``` I would want to have the result for a user be something like: ``` membership: [0] Tag: Membership A Date: 05.03.2021 [1] Tag: Membership B Date: 17.05.2021 [2] Tag: Membership C Date: 29.07.2021 ``` In the `var_dump` it would look something like, where the number of sub-arrays for "membership" will be different per user, depending on the number of memberships they have assigned to them. ``` array(2) { ["member_id"]=> string(2) "12" ["memberships"]=> array(3) { [0]=> array(2) { ["membership"]=> string(5) "membership A" ["datetime"]=> int(1616239233) } [1]=> array(2) { ["membership"]=> string(5) "membership B " ["datetime"]=> int(1616239233) } [2]=> array(2) { ["membership"]=> string(5) "membership C" ["datetime"]=> int(1616239233) } } } ``` I´m sure I am missing something, look forward to hearing your thoughts. Thanks
here we go, this is the code that works, triggering an email-alert when a specific article is viewed ``` function email_alert() { global $post; if( $post->ID == 1234) { wp_mail( 'aprilia@example.net', 'Alert', 'This Site was Visited!' ); } } add_action( 'wp', 'email_alert' ); ```
384,072
<p>I have a situation where I have a function hooked to more than one custom hooks. How to check in the callback function which custom hook triggered the call?</p> <p>Or the question in code will be</p> <pre><code>add_action('my_test_hook_1','my_test_callback_function'); add_action('my_test_hook_2','my_test_callback_function'); add_action('my_test_hook_3','my_test_callback_function'); add_action('my_test_hook_4','my_test_callback_function'); function my_test_callback_function(){ $called_action_hook = ; //Some magic code that will return current called action the hook echo &quot;This function is called by action: &quot; . $called_action_hook ; } </code></pre>
[ { "answer_id": 384075, "author": "Coder At Heart", "author_id": 170574, "author_profile": "https://wordpress.stackexchange.com/users/170574", "pm_score": 0, "selected": false, "text": "<p>The solution will be to add a parameter to <code>do_action</code> and then pick that up in your <cod...
2021/02/25
[ "https://wordpress.stackexchange.com/questions/384072", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202503/" ]
I have a situation where I have a function hooked to more than one custom hooks. How to check in the callback function which custom hook triggered the call? Or the question in code will be ``` add_action('my_test_hook_1','my_test_callback_function'); add_action('my_test_hook_2','my_test_callback_function'); add_action('my_test_hook_3','my_test_callback_function'); add_action('my_test_hook_4','my_test_callback_function'); function my_test_callback_function(){ $called_action_hook = ; //Some magic code that will return current called action the hook echo "This function is called by action: " . $called_action_hook ; } ```
I found the magic code you need. Use `current_filter()`. This function will return name of the current filter or action. ``` add_action('my_test_hook_1','my_test_callback_function'); add_action('my_test_hook_2','my_test_callback_function'); add_action('my_test_hook_3','my_test_callback_function'); add_action('my_test_hook_4','my_test_callback_function'); function my_test_callback_function(){ $called_action_hook = current_filter(); // ***The magic code that will return the last called action echo "This function is called by action: " . $called_action_hook ; } ``` For reference: <https://developer.wordpress.org/reference/functions/current_filter/>
384,093
<p>Im using local by flywheel, Here are the steps i have taken so far:</p> <ol> <li>Installed local by flywheel and created a site called stage</li> <li>Downloaded the website from CPanel and also the SQL database</li> <li>Imported the database in admirer (but the links are all the same, How can i change them?)</li> <li>Deleted the 'wp_content' folder in the flywheel site and added the 'wp_content' folder from my wordpress site there instead</li> <li>Set the theme as the old one and reactivated all of the plugins</li> </ol> <p>And i still dont have any of the data showing an none of the styling either. Does anyone know what im doing wrong?</p>
[ { "answer_id": 384075, "author": "Coder At Heart", "author_id": 170574, "author_profile": "https://wordpress.stackexchange.com/users/170574", "pm_score": 0, "selected": false, "text": "<p>The solution will be to add a parameter to <code>do_action</code> and then pick that up in your <cod...
2021/02/25
[ "https://wordpress.stackexchange.com/questions/384093", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202528/" ]
Im using local by flywheel, Here are the steps i have taken so far: 1. Installed local by flywheel and created a site called stage 2. Downloaded the website from CPanel and also the SQL database 3. Imported the database in admirer (but the links are all the same, How can i change them?) 4. Deleted the 'wp\_content' folder in the flywheel site and added the 'wp\_content' folder from my wordpress site there instead 5. Set the theme as the old one and reactivated all of the plugins And i still dont have any of the data showing an none of the styling either. Does anyone know what im doing wrong?
I found the magic code you need. Use `current_filter()`. This function will return name of the current filter or action. ``` add_action('my_test_hook_1','my_test_callback_function'); add_action('my_test_hook_2','my_test_callback_function'); add_action('my_test_hook_3','my_test_callback_function'); add_action('my_test_hook_4','my_test_callback_function'); function my_test_callback_function(){ $called_action_hook = current_filter(); // ***The magic code that will return the last called action echo "This function is called by action: " . $called_action_hook ; } ``` For reference: <https://developer.wordpress.org/reference/functions/current_filter/>
384,100
<p>I just did a major update in my WordPress environment tonight to the latest version, and got an internal server error on the site. I then did a full inspection to see where the issue was coming from. I think I found the culprit...When I commented out the following line in my .htaccess file, the site came back...</p> <pre class="lang-json prettyprint-override"><code># SGO Unset Vary Header unset Vary # SGO Unset Vary END </code></pre> <p>In what situations do we ever <strong>need</strong> <code>Header unset Vary</code> in our .htaccess file?</p>
[ { "answer_id": 384119, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 2, "selected": true, "text": "<blockquote>\n<pre><code>Header unset Vary\n</code></pre>\n</blockquote>\n<p>This is probably a workaround for a su...
2021/02/26
[ "https://wordpress.stackexchange.com/questions/384100", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98671/" ]
I just did a major update in my WordPress environment tonight to the latest version, and got an internal server error on the site. I then did a full inspection to see where the issue was coming from. I think I found the culprit...When I commented out the following line in my .htaccess file, the site came back... ```json # SGO Unset Vary Header unset Vary # SGO Unset Vary END ``` In what situations do we ever **need** `Header unset Vary` in our .htaccess file?
> > > ``` > Header unset Vary > > ``` > > This is probably a workaround for a supposed [bug in Apache](https://www.jeffgeerling.com/blog/2017/stripping-vary-host-header-apache-response-using-varnish) ([#58231](https://bz.apache.org/bugzilla/show_bug.cgi?id=58231))**\*1** that could prevent certain caching proxies from caching the response when the `Vary: Host` HTTP response header is set. Apache might be setting this automatically when querying the `HTTP_HOST` server variable in a mod\_rewrite `RewriteCond` directive (or Apache Expression). **\*1** Although this is arguably a bug in the cache, not Apache. The Apache behaviour is "by design" and a `Vary: Host` header should not prevent a cache from working since this is really the default behaviour. However, if you are *varying* the HTTP response based on other elements of the request (such as the `Accept`, `Accept-Language` or `User-Agent` HTTP request headers) then the `Vary` HTTP response header should be set appropriately and should not simply be *unset*. I am surprised, however, that this directive would cause an error. It implies that mod\_headers is not installed - which is "unlikely". However, you can protect against this and surround the directive in an `<IfModule>` directive. For example: ``` # SGO Unset Vary <IfModule mod_headers.c> Header unset Vary </IfModule> # SGO Unset Vary END ``` (From the indentation of the directive in your question it almost looks like this `<IfModule>` wrapper was missing?) Now, the `Header` directive will be processed only if mod\_headers is installed.
384,131
<p>I am working on generating a JWT token for the users who log in to my site using a plugin <a href="https://wordpress.org/plugins/jwt-auth/" rel="nofollow noreferrer">JWT Auth</a> and that token will be used for a external dashboard.</p> <p>The issue that I am facing is that for generating a JWT token you need to pass <code>username</code> and <code>password</code> as <code>form-data</code> to <code>/wp-json/jwt-auth/v1/token</code> endpoint but the password that is stored in the database is hashed and cannot be decrypted so what is the solution for this? I cannot send plain text password to the endpoint.</p> <p>Looking forward to your suggestions.</p>
[ { "answer_id": 384179, "author": "FaISalBLiNK", "author_id": 68212, "author_profile": "https://wordpress.stackexchange.com/users/68212", "pm_score": 2, "selected": true, "text": "<p>For the developers who are facing the similar issue here is what I have done to achieve the desired result...
2021/02/26
[ "https://wordpress.stackexchange.com/questions/384131", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68212/" ]
I am working on generating a JWT token for the users who log in to my site using a plugin [JWT Auth](https://wordpress.org/plugins/jwt-auth/) and that token will be used for a external dashboard. The issue that I am facing is that for generating a JWT token you need to pass `username` and `password` as `form-data` to `/wp-json/jwt-auth/v1/token` endpoint but the password that is stored in the database is hashed and cannot be decrypted so what is the solution for this? I cannot send plain text password to the endpoint. Looking forward to your suggestions.
For the developers who are facing the similar issue here is what I have done to achieve the desired results. The best way would be to develop the functionality from scratch but due to a tight deadline I opted to modify the [JWT Auth Plugin](https://wordpress.org/plugins/jwt-auth/) I have modified the method `get_token` in the file `class-auth.php`. What I have done is that at first the method was looking for params `username` and `password` and I have modified it to receive `userID` as the param required. Why `userID` ? It is because I am running a `cURL` call to get the user data after the user sign in. Here is the code for the `get_token` method if anyone wants to use it. Although it was a small modification but it produces the required results. Thank you all for the suggestions. Happy Coding ``` public function get_token(WP_REST_Request $request) { $secret_key = defined('JWT_AUTH_SECRET_KEY') ? JWT_AUTH_SECRET_KEY : false; $userID = $request->get_param('user_id'); $custom_auth = $request->get_param('custom_auth'); // First thing, check the secret key if not exist return a error. if (!$secret_key) { return new WP_REST_Response( array( 'success' => false, 'statusCode' => 403, 'code' => 'jwt_auth_bad_config', 'message' => __('JWT is not configurated properly.', 'jwt-auth'), 'data' => array(), ) ); } // Getting data for the logged in user. $user = get_user_by('id', $userID); // If the authentication is failed return error response. if (!$user) { // $error_code = $user->get_error_code(); return new WP_REST_Response( array( 'success' => false, 'statusCode' => 403, 'code' => 404, 'message' => 'User does not exists.', 'data' => array(), ) ); } return $this->generate_token($user, false); } ```
384,135
<p>I want my WordPress website to load with https + non-www and without trailing slashes. I put the following code in <code>.htaccess</code> file:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On # Remove trailing slash from non-filepath urls RewriteCond %{REQUEST_URI} /(.+)/$ RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ https://example.com/%1 [R=301,L] # Force HTTPS and remove WWW RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR,NC] RewriteCond %{https} off RewriteRule ^(.*)$ https://example.com/$1 [R=301,L] &lt;/IfModule&gt; </code></pre> <ol> <li><p>These rules work fine but I can't remove multiple slashes after the domain. The website loads: <code>https://example.com/////</code> and I want it to redirect to <code>https://example.com</code></p> </li> <li><p>Also, these rules work if they are only in the beginning of the <code>.htaccess</code> file and when I re-save the permalinks the rules disappear...</p> </li> </ol> <p>Could you help me, please</p>
[ { "answer_id": 384145, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 3, "selected": true, "text": "<p>To reduce multiple slashes at the start of the URL-path (or in fact <em>anywhere</em> in the URL-path) to a sing...
2021/02/26
[ "https://wordpress.stackexchange.com/questions/384135", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202546/" ]
I want my WordPress website to load with https + non-www and without trailing slashes. I put the following code in `.htaccess` file: ``` <IfModule mod_rewrite.c> RewriteEngine On # Remove trailing slash from non-filepath urls RewriteCond %{REQUEST_URI} /(.+)/$ RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ https://example.com/%1 [R=301,L] # Force HTTPS and remove WWW RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR,NC] RewriteCond %{https} off RewriteRule ^(.*)$ https://example.com/$1 [R=301,L] </IfModule> ``` 1. These rules work fine but I can't remove multiple slashes after the domain. The website loads: `https://example.com/////` and I want it to redirect to `https://example.com` 2. Also, these rules work if they are only in the beginning of the `.htaccess` file and when I re-save the permalinks the rules disappear... Could you help me, please
To reduce multiple slashes at the start of the URL-path (or in fact *anywhere* in the URL-path) to a single slash (there is always at least 1 slash at the start of the URL-path, even if you can't see this is the browser's address bar) then you can use a directive like the following: ``` # Reduce multiple slashes to single slashes RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule (.*) /$1 [R=301,L] ``` This uses the fact that the URL-path matched by the `RewriteRule` *pattern* has already had multiple slashes reduced. The preceding *condition* checks that there were multiple slashes somewhere in the URL-path in the initial request. You would place the above rule second, between your existing rules. And modify your 1st rule that removes the trailing slash to also reduce multiple slashes, thus preventing an unnecessary additional redirect should a request contain both multiple slashes and a trailing slash. For example: ``` # Remove trailing slash from non-directory URLs AND reduce multiple slashes RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.+)/$ https://example.com/$1 [R=301,L] # Reduce multiple slashes to single slashes RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule (.*) https://example.com/$1 [R=301,L] # Force HTTPS and remove WWW RewriteCond %{HTTP_HOST} ^www\. [OR,NC] RewriteCond %{https} off RewriteRule (.*) https://example.com/$1 [R=301,L] ``` I just tidied the regex in the `RewriteCond` directive that checks against the `HTTP_HOST` server variable. `^www\.(.*)$` can be simplifed to `^www\.` since you are not making use of the backreference here. You do not need the `<IfModule>` wrapper. Clear your browser cache before testing and preferably test first with 302 (temporary) redirects to avoid potential caching issues. > > 2. Also, these rules work if they are only in the beginning of the .htaccess file and when I re-save the permalinks the rules disappear... > > > These rules certainly need to go near the beginning of the `.htaccess` file, *before* the WordPress front-controller. However, they must go *before* the `# BEGIN WordPress` section. Not inside this block, otherwise they will be overwritten since WP itself maintains this code block. They should not be overwritten if placed *before* the `# BEGIN WordPress` comment marker.
384,140
<p>I have a WordPress project im doing, pretty much I need to add 4 individual blog posts with background images behind the specific posts. This is the code i found and used, the only issue is they blog posts aren't clickable, not even the title. I am not sure where to go from here to make each link clickable.</p> <pre><code>By &lt;?php the_author_posts_link(); ?&gt; on &lt;?php the_time('F jS, Y'); ?&gt; in &lt;?php the_category(', '); ?&gt; &lt;?php $post_id = 1; $queried_post = get_post($post_id); ?&gt; &lt;h2&gt;&lt;?php echo $queried_post-&gt;post_title; ?&gt;&lt;/h2&gt; &lt;?php echo $queried_post-&gt;post_content; ?&gt; </code></pre>
[ { "answer_id": 384145, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 3, "selected": true, "text": "<p>To reduce multiple slashes at the start of the URL-path (or in fact <em>anywhere</em> in the URL-path) to a sing...
2021/02/26
[ "https://wordpress.stackexchange.com/questions/384140", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202557/" ]
I have a WordPress project im doing, pretty much I need to add 4 individual blog posts with background images behind the specific posts. This is the code i found and used, the only issue is they blog posts aren't clickable, not even the title. I am not sure where to go from here to make each link clickable. ``` By <?php the_author_posts_link(); ?> on <?php the_time('F jS, Y'); ?> in <?php the_category(', '); ?> <?php $post_id = 1; $queried_post = get_post($post_id); ?> <h2><?php echo $queried_post->post_title; ?></h2> <?php echo $queried_post->post_content; ?> ```
To reduce multiple slashes at the start of the URL-path (or in fact *anywhere* in the URL-path) to a single slash (there is always at least 1 slash at the start of the URL-path, even if you can't see this is the browser's address bar) then you can use a directive like the following: ``` # Reduce multiple slashes to single slashes RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule (.*) /$1 [R=301,L] ``` This uses the fact that the URL-path matched by the `RewriteRule` *pattern* has already had multiple slashes reduced. The preceding *condition* checks that there were multiple slashes somewhere in the URL-path in the initial request. You would place the above rule second, between your existing rules. And modify your 1st rule that removes the trailing slash to also reduce multiple slashes, thus preventing an unnecessary additional redirect should a request contain both multiple slashes and a trailing slash. For example: ``` # Remove trailing slash from non-directory URLs AND reduce multiple slashes RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.+)/$ https://example.com/$1 [R=301,L] # Reduce multiple slashes to single slashes RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule (.*) https://example.com/$1 [R=301,L] # Force HTTPS and remove WWW RewriteCond %{HTTP_HOST} ^www\. [OR,NC] RewriteCond %{https} off RewriteRule (.*) https://example.com/$1 [R=301,L] ``` I just tidied the regex in the `RewriteCond` directive that checks against the `HTTP_HOST` server variable. `^www\.(.*)$` can be simplifed to `^www\.` since you are not making use of the backreference here. You do not need the `<IfModule>` wrapper. Clear your browser cache before testing and preferably test first with 302 (temporary) redirects to avoid potential caching issues. > > 2. Also, these rules work if they are only in the beginning of the .htaccess file and when I re-save the permalinks the rules disappear... > > > These rules certainly need to go near the beginning of the `.htaccess` file, *before* the WordPress front-controller. However, they must go *before* the `# BEGIN WordPress` section. Not inside this block, otherwise they will be overwritten since WP itself maintains this code block. They should not be overwritten if placed *before* the `# BEGIN WordPress` comment marker.
384,168
<p>I want to count authors post count in a specific category. How do i do that? I have red this thread here but still can't fiure it out.</p> <p><a href="https://wordpress.stackexchange.com/questions/261302/count-number-of-posts-by-author-in-a-category">Count number of posts by author in a category</a></p> <p>Edit: This is what i got and tried but doesnt work at all.</p> <pre><code>$user_id = get_the_author_meta('ID') $args = array( 'author_name' =&gt; $user_id, 'category_name' =&gt; 'categoryname', }; $wp_query = new WP_Query($args); while ( $wp_query-&gt;have_posts() ) : $wp_query-&gt;the_post(); echo $my_count = $wp_query-&gt;post_count; wp_reset_postdata(); endwhile; </code></pre>
[ { "answer_id": 384145, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 3, "selected": true, "text": "<p>To reduce multiple slashes at the start of the URL-path (or in fact <em>anywhere</em> in the URL-path) to a sing...
2021/02/27
[ "https://wordpress.stackexchange.com/questions/384168", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138704/" ]
I want to count authors post count in a specific category. How do i do that? I have red this thread here but still can't fiure it out. [Count number of posts by author in a category](https://wordpress.stackexchange.com/questions/261302/count-number-of-posts-by-author-in-a-category) Edit: This is what i got and tried but doesnt work at all. ``` $user_id = get_the_author_meta('ID') $args = array( 'author_name' => $user_id, 'category_name' => 'categoryname', }; $wp_query = new WP_Query($args); while ( $wp_query->have_posts() ) : $wp_query->the_post(); echo $my_count = $wp_query->post_count; wp_reset_postdata(); endwhile; ```
To reduce multiple slashes at the start of the URL-path (or in fact *anywhere* in the URL-path) to a single slash (there is always at least 1 slash at the start of the URL-path, even if you can't see this is the browser's address bar) then you can use a directive like the following: ``` # Reduce multiple slashes to single slashes RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule (.*) /$1 [R=301,L] ``` This uses the fact that the URL-path matched by the `RewriteRule` *pattern* has already had multiple slashes reduced. The preceding *condition* checks that there were multiple slashes somewhere in the URL-path in the initial request. You would place the above rule second, between your existing rules. And modify your 1st rule that removes the trailing slash to also reduce multiple slashes, thus preventing an unnecessary additional redirect should a request contain both multiple slashes and a trailing slash. For example: ``` # Remove trailing slash from non-directory URLs AND reduce multiple slashes RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.+)/$ https://example.com/$1 [R=301,L] # Reduce multiple slashes to single slashes RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule (.*) https://example.com/$1 [R=301,L] # Force HTTPS and remove WWW RewriteCond %{HTTP_HOST} ^www\. [OR,NC] RewriteCond %{https} off RewriteRule (.*) https://example.com/$1 [R=301,L] ``` I just tidied the regex in the `RewriteCond` directive that checks against the `HTTP_HOST` server variable. `^www\.(.*)$` can be simplifed to `^www\.` since you are not making use of the backreference here. You do not need the `<IfModule>` wrapper. Clear your browser cache before testing and preferably test first with 302 (temporary) redirects to avoid potential caching issues. > > 2. Also, these rules work if they are only in the beginning of the .htaccess file and when I re-save the permalinks the rules disappear... > > > These rules certainly need to go near the beginning of the `.htaccess` file, *before* the WordPress front-controller. However, they must go *before* the `# BEGIN WordPress` section. Not inside this block, otherwise they will be overwritten since WP itself maintains this code block. They should not be overwritten if placed *before* the `# BEGIN WordPress` comment marker.
384,186
<p>I have just installed WordPress locally in my computer and run the website successfully. I want to achieve following: when logged-in user tries to access wp-login.php or register page, it should be automatically redirected to home page.</p> <p>I have spent several hours on web, but could no come up with solution neither was I able to find appropriate WordPress plugin.</p> <p>My question is: why does WordPress function this way? how can we change this behavior as natively as simply as possible?</p> <p>Thank you</p>
[ { "answer_id": 384145, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 3, "selected": true, "text": "<p>To reduce multiple slashes at the start of the URL-path (or in fact <em>anywhere</em> in the URL-path) to a sing...
2021/02/27
[ "https://wordpress.stackexchange.com/questions/384186", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202589/" ]
I have just installed WordPress locally in my computer and run the website successfully. I want to achieve following: when logged-in user tries to access wp-login.php or register page, it should be automatically redirected to home page. I have spent several hours on web, but could no come up with solution neither was I able to find appropriate WordPress plugin. My question is: why does WordPress function this way? how can we change this behavior as natively as simply as possible? Thank you
To reduce multiple slashes at the start of the URL-path (or in fact *anywhere* in the URL-path) to a single slash (there is always at least 1 slash at the start of the URL-path, even if you can't see this is the browser's address bar) then you can use a directive like the following: ``` # Reduce multiple slashes to single slashes RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule (.*) /$1 [R=301,L] ``` This uses the fact that the URL-path matched by the `RewriteRule` *pattern* has already had multiple slashes reduced. The preceding *condition* checks that there were multiple slashes somewhere in the URL-path in the initial request. You would place the above rule second, between your existing rules. And modify your 1st rule that removes the trailing slash to also reduce multiple slashes, thus preventing an unnecessary additional redirect should a request contain both multiple slashes and a trailing slash. For example: ``` # Remove trailing slash from non-directory URLs AND reduce multiple slashes RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.+)/$ https://example.com/$1 [R=301,L] # Reduce multiple slashes to single slashes RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule (.*) https://example.com/$1 [R=301,L] # Force HTTPS and remove WWW RewriteCond %{HTTP_HOST} ^www\. [OR,NC] RewriteCond %{https} off RewriteRule (.*) https://example.com/$1 [R=301,L] ``` I just tidied the regex in the `RewriteCond` directive that checks against the `HTTP_HOST` server variable. `^www\.(.*)$` can be simplifed to `^www\.` since you are not making use of the backreference here. You do not need the `<IfModule>` wrapper. Clear your browser cache before testing and preferably test first with 302 (temporary) redirects to avoid potential caching issues. > > 2. Also, these rules work if they are only in the beginning of the .htaccess file and when I re-save the permalinks the rules disappear... > > > These rules certainly need to go near the beginning of the `.htaccess` file, *before* the WordPress front-controller. However, they must go *before* the `# BEGIN WordPress` section. Not inside this block, otherwise they will be overwritten since WP itself maintains this code block. They should not be overwritten if placed *before* the `# BEGIN WordPress` comment marker.
384,212
<p>I've been looking for this method for weeks, but still can't find it. There are so many sites that discuss how to create a custom login page, but they don't cover how to block a specific id like the one I was looking for.</p> <p>The algorithm is as below:</p> <p>first I will determine the user id number that I will block via code in php.</p> <p>On the front end page, the user will input their username and password. Then when they click the login button, wordpress does not immediately check the compatibility between the user's username and password.</p> <p>Wordpress will first check the id of the username that has been entered by the user. If it turns out that the username has the same ID as the ID I blocked, an error message will appear and the user cannot log in, but if the username does not have the same ID as the ID I blocked, then the user can login.</p> <p>I hope you guys can help. Thank you in advance</p>
[ { "answer_id": 384145, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 3, "selected": true, "text": "<p>To reduce multiple slashes at the start of the URL-path (or in fact <em>anywhere</em> in the URL-path) to a sing...
2021/02/28
[ "https://wordpress.stackexchange.com/questions/384212", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202647/" ]
I've been looking for this method for weeks, but still can't find it. There are so many sites that discuss how to create a custom login page, but they don't cover how to block a specific id like the one I was looking for. The algorithm is as below: first I will determine the user id number that I will block via code in php. On the front end page, the user will input their username and password. Then when they click the login button, wordpress does not immediately check the compatibility between the user's username and password. Wordpress will first check the id of the username that has been entered by the user. If it turns out that the username has the same ID as the ID I blocked, an error message will appear and the user cannot log in, but if the username does not have the same ID as the ID I blocked, then the user can login. I hope you guys can help. Thank you in advance
To reduce multiple slashes at the start of the URL-path (or in fact *anywhere* in the URL-path) to a single slash (there is always at least 1 slash at the start of the URL-path, even if you can't see this is the browser's address bar) then you can use a directive like the following: ``` # Reduce multiple slashes to single slashes RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule (.*) /$1 [R=301,L] ``` This uses the fact that the URL-path matched by the `RewriteRule` *pattern* has already had multiple slashes reduced. The preceding *condition* checks that there were multiple slashes somewhere in the URL-path in the initial request. You would place the above rule second, between your existing rules. And modify your 1st rule that removes the trailing slash to also reduce multiple slashes, thus preventing an unnecessary additional redirect should a request contain both multiple slashes and a trailing slash. For example: ``` # Remove trailing slash from non-directory URLs AND reduce multiple slashes RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.+)/$ https://example.com/$1 [R=301,L] # Reduce multiple slashes to single slashes RewriteCond %{THE_REQUEST} \s[^?]*// RewriteRule (.*) https://example.com/$1 [R=301,L] # Force HTTPS and remove WWW RewriteCond %{HTTP_HOST} ^www\. [OR,NC] RewriteCond %{https} off RewriteRule (.*) https://example.com/$1 [R=301,L] ``` I just tidied the regex in the `RewriteCond` directive that checks against the `HTTP_HOST` server variable. `^www\.(.*)$` can be simplifed to `^www\.` since you are not making use of the backreference here. You do not need the `<IfModule>` wrapper. Clear your browser cache before testing and preferably test first with 302 (temporary) redirects to avoid potential caching issues. > > 2. Also, these rules work if they are only in the beginning of the .htaccess file and when I re-save the permalinks the rules disappear... > > > These rules certainly need to go near the beginning of the `.htaccess` file, *before* the WordPress front-controller. However, they must go *before* the `# BEGIN WordPress` section. Not inside this block, otherwise they will be overwritten since WP itself maintains this code block. They should not be overwritten if placed *before* the `# BEGIN WordPress` comment marker.
384,337
<p>I'm using social sign up buttons on my Wordpress site to register/sign in using Google, FB, TW...</p> <p>When they are logged in, this notice appear on the top of the Wordpress dashboard:</p> <blockquote> <p>Notice: You’re using the auto-generated password for your account. Would you like to change it?</p> </blockquote> <p>Is it possible to remove this notice?</p> <p>It's misleading users.</p> <p>Thank you.</p>
[ { "answer_id": 384342, "author": "robert0", "author_id": 202740, "author_profile": "https://wordpress.stackexchange.com/users/202740", "pm_score": -1, "selected": false, "text": "<p>Found the solution.</p>\n<p>This will remove all the notices for your registered WordPress users, except a...
2021/03/02
[ "https://wordpress.stackexchange.com/questions/384337", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202740/" ]
I'm using social sign up buttons on my Wordpress site to register/sign in using Google, FB, TW... When they are logged in, this notice appear on the top of the Wordpress dashboard: > > Notice: You’re using the auto-generated password for your account. Would you like to change it? > > > Is it possible to remove this notice? It's misleading users. Thank you.
Similar to @robert0's answer, you can unhook the nag from happening: ```php remove_action( 'profile_update', 'default_password_nag_edit_user', 10 ); ``` Just put that in your theme's `functions.php` and that should take care of it.
384,344
<p>I have a custom page template <code>products</code>, so i get the url <code>site.com/products</code>. I want to add a parameter (for example <code>product</code>) to this url, so that I can access this page using url <code>site.com/products/product-1</code> or <code>site.com/products/product-2</code> etc.</p> <p>How can I add this parameter and make that url accessible?</p>
[ { "answer_id": 384342, "author": "robert0", "author_id": 202740, "author_profile": "https://wordpress.stackexchange.com/users/202740", "pm_score": -1, "selected": false, "text": "<p>Found the solution.</p>\n<p>This will remove all the notices for your registered WordPress users, except a...
2021/03/02
[ "https://wordpress.stackexchange.com/questions/384344", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202743/" ]
I have a custom page template `products`, so i get the url `site.com/products`. I want to add a parameter (for example `product`) to this url, so that I can access this page using url `site.com/products/product-1` or `site.com/products/product-2` etc. How can I add this parameter and make that url accessible?
Similar to @robert0's answer, you can unhook the nag from happening: ```php remove_action( 'profile_update', 'default_password_nag_edit_user', 10 ); ``` Just put that in your theme's `functions.php` and that should take care of it.
384,372
<p>this is my code:</p> <pre><code>$terms = wp_get_post_terms( $listing_id,'job_listing_category' ); if(!empty($terms)){ $sql_terms.=&quot; AND (&quot;; foreach($terms as $term){ $sql_terms.=&quot; category LIKE '%&quot;.$term-&gt;slug.&quot;%' OR&quot;; } $sql_terms.=&quot; category IS NULL OR category=''&quot;; $sql_terms.=&quot;) &quot;; } $wpdb-&gt;get_results( $wpdb-&gt;prepare( &quot;SELECT DISTINCT user_id ,proximity, ( %s * IFNULL( acos( cos( radians(lat) ) * cos( radians( %s ) ) * cos( radians( %s ) - radians(lng) ) + sin( radians(lat) ) * sin( radians( %s ) ) ), 0 ) ) AS distance FROM &quot;.$wpdb-&gt;prefix.&quot;a_filters as f WHERE f.notify=1 AND lat!='false' AND lng!='false' AND listing_type='&quot;.$listing_type.&quot;' &quot;.($sql_terms?$sql_terms:&quot;&quot;).&quot; HAVING distance &lt; proximity ORDER BY distance ASC&quot; , $earth_radius, $lat, $lng, $lat) ); </code></pre> <p>One of the $terms is &quot;special-purpose&quot;.</p> <p>I get error wpdb::prepare was called incorrectly. The query does not contain the correct number of placeholders (5) for the number of arguments passed (4). And that is because it also counts the %s from '%special-purpose%'. How can I make it ignore the %s from '%special-purpose%' ?</p>
[ { "answer_id": 384342, "author": "robert0", "author_id": 202740, "author_profile": "https://wordpress.stackexchange.com/users/202740", "pm_score": -1, "selected": false, "text": "<p>Found the solution.</p>\n<p>This will remove all the notices for your registered WordPress users, except a...
2021/03/03
[ "https://wordpress.stackexchange.com/questions/384372", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/164443/" ]
this is my code: ``` $terms = wp_get_post_terms( $listing_id,'job_listing_category' ); if(!empty($terms)){ $sql_terms.=" AND ("; foreach($terms as $term){ $sql_terms.=" category LIKE '%".$term->slug."%' OR"; } $sql_terms.=" category IS NULL OR category=''"; $sql_terms.=") "; } $wpdb->get_results( $wpdb->prepare( "SELECT DISTINCT user_id ,proximity, ( %s * IFNULL( acos( cos( radians(lat) ) * cos( radians( %s ) ) * cos( radians( %s ) - radians(lng) ) + sin( radians(lat) ) * sin( radians( %s ) ) ), 0 ) ) AS distance FROM ".$wpdb->prefix."a_filters as f WHERE f.notify=1 AND lat!='false' AND lng!='false' AND listing_type='".$listing_type."' ".($sql_terms?$sql_terms:"")." HAVING distance < proximity ORDER BY distance ASC" , $earth_radius, $lat, $lng, $lat) ); ``` One of the $terms is "special-purpose". I get error wpdb::prepare was called incorrectly. The query does not contain the correct number of placeholders (5) for the number of arguments passed (4). And that is because it also counts the %s from '%special-purpose%'. How can I make it ignore the %s from '%special-purpose%' ?
Similar to @robert0's answer, you can unhook the nag from happening: ```php remove_action( 'profile_update', 'default_password_nag_edit_user', 10 ); ``` Just put that in your theme's `functions.php` and that should take care of it.
384,401
<p>I've been having this weird issue on a site for a few weeks now, tried everything I found by searching but still not being able to find a clue of the issue.</p> <p>Whenever I add some items to the Menu (Appearance &gt; Menus), a few items become empty. And then gets removed when I click the Save button again. Similarly, if I edit any posts, the same thing happens with the menu items.</p> <p>Here's what I've tried so far,</p> <ol> <li>Increased max_execution_time, max_input_vars, max_input_time, memory_limit, post_max_size, upload_max_filesize, max_file_uploads in PHP.ini. I set those to very high numbers but still no luck</li> <li>Then I tried copying the site to another hosting and on my localhost, but no luck. Did #1 on all the environments.</li> <li>Changed the theme to default 2021 and deactivated all plugins, still no luck</li> <li>Checked the database, wp_posts table has 4.6k rows with size of total 10.8MB, with overheads of about 300KB. So, I tried changing the storage engine of that table to innoDB from MyISAM but the problem is still happening.</li> </ol> <p>Is there anyone who faced similar condition? What could be the issue?</p>
[ { "answer_id": 384342, "author": "robert0", "author_id": 202740, "author_profile": "https://wordpress.stackexchange.com/users/202740", "pm_score": -1, "selected": false, "text": "<p>Found the solution.</p>\n<p>This will remove all the notices for your registered WordPress users, except a...
2021/03/03
[ "https://wordpress.stackexchange.com/questions/384401", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31449/" ]
I've been having this weird issue on a site for a few weeks now, tried everything I found by searching but still not being able to find a clue of the issue. Whenever I add some items to the Menu (Appearance > Menus), a few items become empty. And then gets removed when I click the Save button again. Similarly, if I edit any posts, the same thing happens with the menu items. Here's what I've tried so far, 1. Increased max\_execution\_time, max\_input\_vars, max\_input\_time, memory\_limit, post\_max\_size, upload\_max\_filesize, max\_file\_uploads in PHP.ini. I set those to very high numbers but still no luck 2. Then I tried copying the site to another hosting and on my localhost, but no luck. Did #1 on all the environments. 3. Changed the theme to default 2021 and deactivated all plugins, still no luck 4. Checked the database, wp\_posts table has 4.6k rows with size of total 10.8MB, with overheads of about 300KB. So, I tried changing the storage engine of that table to innoDB from MyISAM but the problem is still happening. Is there anyone who faced similar condition? What could be the issue?
Similar to @robert0's answer, you can unhook the nag from happening: ```php remove_action( 'profile_update', 'default_password_nag_edit_user', 10 ); ``` Just put that in your theme's `functions.php` and that should take care of it.
384,445
<p>I am trying to add a class to a checkout page if the checkout contains a subscription renewal. Woocommerce provides <a href="https://github.com/wp-premium/woocommerce-subscriptions/blob/master/includes/wcs-renewal-functions.php#L71" rel="nofollow noreferrer"><code>wcs_cart_contains_renewal()</code></a> to check. I am using this code but obviously missing something as it's not working.</p> <pre><code>$cart_items = wcs_cart_contains_renewal(); if ( ! empty( $cart_items ) ) { add_filter( 'body_class','my_body_classes' ); function my_body_classes( $classes ) { $classes[] = 'renewal-order'; return $classes; } } </code></pre> <p>Any help on how to make this work?</p>
[ { "answer_id": 384454, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>The <code>body_class</code> filter is called inside the <a href=\"https://developer.wordpress.org/reference/func...
2021/03/04
[ "https://wordpress.stackexchange.com/questions/384445", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104225/" ]
I am trying to add a class to a checkout page if the checkout contains a subscription renewal. Woocommerce provides [`wcs_cart_contains_renewal()`](https://github.com/wp-premium/woocommerce-subscriptions/blob/master/includes/wcs-renewal-functions.php#L71) to check. I am using this code but obviously missing something as it's not working. ``` $cart_items = wcs_cart_contains_renewal(); if ( ! empty( $cart_items ) ) { add_filter( 'body_class','my_body_classes' ); function my_body_classes( $classes ) { $classes[] = 'renewal-order'; return $classes; } } ``` Any help on how to make this work?
As @cjbj noted in a comment, this is probably a timing issue. This means that instead of directly adding the code to `functions.php` you need to wrap it inside a callback function and attach it to a later firing action. WordPress, themes and plugins too, [loads](https://wordpress.stackexchange.com/questions/71406/is-there-a-flowchart-for-wordpress-loading-sequence) and [does](https://codex.wordpress.org/Plugin_API/Action_Reference) things in certain order. Thus some code needs to be added with actions to make them properly. Personally, I usually add `body_class` filtering, if it depends on some data, on [`template_redirect`](https://developer.wordpress.org/reference/hooks/template_redirect/) (*Fires before determining which template to load*) action to make sure the code will have all the data it needs to determine how to filter the classes. ``` // Hook anonymous callback to template_redirect action add_action( 'template_redirect', function(){ // Get data $cart_items = wcs_cart_contains_renewal(); // Check for truthy condition if ( $cart_items ) { // Hook anonymous callback to body_class filter add_filter( 'body_class', function( $classes ) { // Add additional class $classes[] = 'renewal-order'; return $classes; } ); } } ); ``` *You can use named callback instead of anonymous ones, if you wish.*
384,453
<p>I understand my question may be a bit broad, or even easy to answer. I have been building custom blocks using the <code>--es5</code> flag of <code>@wordpress/create-block</code> (<a href="https://developer.wordpress.org/block-editor/packages/packages-create-block/" rel="nofollow noreferrer">https://developer.wordpress.org/block-editor/packages/packages-create-block/</a>), which has been fairly successful on projects.</p> <p>The reason for using this method is that during development and post-launch there are often many changes required of the block and from my past experience (over a year ago) the ES Next method effectively 'killed' the block as soon as a change was made. So you would have to go through every instance of this block and change it.</p> <p>Have WP's developers come up with a workable solution for this which enables developers to use the ES Next method in a project safely? I'd prefer to be using the methods as intended. The documentation since it's release has not been great so I thought it would be better to ask the wider community.</p> <p>To try and explain better what I mean:</p> <p>Building a custom block using the following method (<a href="https://github.com/WordPress/gutenberg-examples/blob/master/03-editable/block.js" rel="nofollow noreferrer">https://github.com/WordPress/gutenberg-examples/blob/master/03-editable/block.js</a>) of attributes with the --es5 flag appears to be more stable in terms of backwards compatibility. If I were to make changes to the render template (<a href="https://github.com/WordPress/gutenberg-examples/blob/master/03-editable/index.php" rel="nofollow noreferrer">https://github.com/WordPress/gutenberg-examples/blob/master/03-editable/index.php</a>) it wouldn't break the block.</p> <p>Using the 'React' method (<a href="https://github.com/WordPress/gutenberg-examples/blob/master/03-editable-esnext/src/index.js" rel="nofollow noreferrer">https://github.com/WordPress/gutenberg-examples/blob/master/03-editable-esnext/src/index.js</a>), in my past experience, has caused issues. If I build a custom block using this method and a change has been made to the block's code, it 'kills' the block. There is no backwards compatibility from what I can tell.</p> <p>I'm wondering if this is just something that has actually been resolved since the block editor was first introduced. Or is the way to continue building custom blocks is using the ES5 method</p> <p><strong>One important bit I have missed out</strong> What I was originally alluding to is that I am using server side rendered blocks (excuse my terminology here, its not exactly a clear subject to those unfamiliar with it) that gets around the 'change anything in the block code and you have to add that block again in the editor' problem. Not Ideal for client handover.</p> <pre><code>register_block_type( 'create-block/perk', array( 'editor_script' =&gt; 'create-block-perk-block-editor', 'editor_style' =&gt; 'create-block-perk-block-editor', 'style' =&gt; 'create-block-perk-block', 'render_callback' =&gt; 'perk_block_render', ) ); function perk_block_render($attr, $content) { $str = ''; if(isset($attr['mediaID'])) { $mediaID = $attr['mediaID']; $src = wp_get_attachment_image_src($mediaID, 'perk'); if($src &amp;&amp; is_array($src) &amp;&amp; isset($src[0])) { $srcset = wp_get_attachment_image_srcset($mediaID); $sizes = wp_get_attachment_image_sizes($mediaID, 'perk'); $alt = get_post_meta($mediaID, '_wp_attachment_image_alt', true); if(!$alt) { $alt = 'Perk icon'; } } } if(isset($attr['titleContent'])) { $title = $attr['titleContent']; } if(isset($attr['subContent'])) { $subtitle = $attr['subContent']; } $str = &quot;&lt;div class='perks__item animate'&gt;&quot;; if($mediaID) { $str .= &quot;&lt;img loading='lazy' width='170' height='170' src='{$src[0]}' alt='{$alt}'/&gt;&quot;; } if($title) { $str .= &quot;&lt;h2&gt;{$title}&lt;/h2&gt;&quot;; } if($subtitle) { $str .= &quot;&lt;p&gt;{$subtitle}&lt;/p&gt;&quot;; } $str .= &quot;&lt;/div&gt;&quot;; return $str; </code></pre> <p>}</p> <p>I see now that it is not ES5/ESNext related, however, after looking through recent videos it seems like it is still an issue with developing custom blocks using WordPress's 'preferred' method. And also, judging by the answers using server-side-rendered blocks is the only way away this. Is my code going to experience issues if I continue to use server-side rendered blocks?</p>
[ { "answer_id": 384463, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Whatever issues you had that caused a block to be &quot;killed&quot; after editing was entirely unrelat...
2021/03/04
[ "https://wordpress.stackexchange.com/questions/384453", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114814/" ]
I understand my question may be a bit broad, or even easy to answer. I have been building custom blocks using the `--es5` flag of `@wordpress/create-block` (<https://developer.wordpress.org/block-editor/packages/packages-create-block/>), which has been fairly successful on projects. The reason for using this method is that during development and post-launch there are often many changes required of the block and from my past experience (over a year ago) the ES Next method effectively 'killed' the block as soon as a change was made. So you would have to go through every instance of this block and change it. Have WP's developers come up with a workable solution for this which enables developers to use the ES Next method in a project safely? I'd prefer to be using the methods as intended. The documentation since it's release has not been great so I thought it would be better to ask the wider community. To try and explain better what I mean: Building a custom block using the following method (<https://github.com/WordPress/gutenberg-examples/blob/master/03-editable/block.js>) of attributes with the --es5 flag appears to be more stable in terms of backwards compatibility. If I were to make changes to the render template (<https://github.com/WordPress/gutenberg-examples/blob/master/03-editable/index.php>) it wouldn't break the block. Using the 'React' method (<https://github.com/WordPress/gutenberg-examples/blob/master/03-editable-esnext/src/index.js>), in my past experience, has caused issues. If I build a custom block using this method and a change has been made to the block's code, it 'kills' the block. There is no backwards compatibility from what I can tell. I'm wondering if this is just something that has actually been resolved since the block editor was first introduced. Or is the way to continue building custom blocks is using the ES5 method **One important bit I have missed out** What I was originally alluding to is that I am using server side rendered blocks (excuse my terminology here, its not exactly a clear subject to those unfamiliar with it) that gets around the 'change anything in the block code and you have to add that block again in the editor' problem. Not Ideal for client handover. ``` register_block_type( 'create-block/perk', array( 'editor_script' => 'create-block-perk-block-editor', 'editor_style' => 'create-block-perk-block-editor', 'style' => 'create-block-perk-block', 'render_callback' => 'perk_block_render', ) ); function perk_block_render($attr, $content) { $str = ''; if(isset($attr['mediaID'])) { $mediaID = $attr['mediaID']; $src = wp_get_attachment_image_src($mediaID, 'perk'); if($src && is_array($src) && isset($src[0])) { $srcset = wp_get_attachment_image_srcset($mediaID); $sizes = wp_get_attachment_image_sizes($mediaID, 'perk'); $alt = get_post_meta($mediaID, '_wp_attachment_image_alt', true); if(!$alt) { $alt = 'Perk icon'; } } } if(isset($attr['titleContent'])) { $title = $attr['titleContent']; } if(isset($attr['subContent'])) { $subtitle = $attr['subContent']; } $str = "<div class='perks__item animate'>"; if($mediaID) { $str .= "<img loading='lazy' width='170' height='170' src='{$src[0]}' alt='{$alt}'/>"; } if($title) { $str .= "<h2>{$title}</h2>"; } if($subtitle) { $str .= "<p>{$subtitle}</p>"; } $str .= "</div>"; return $str; ``` } I see now that it is not ES5/ESNext related, however, after looking through recent videos it seems like it is still an issue with developing custom blocks using WordPress's 'preferred' method. And also, judging by the answers using server-side-rendered blocks is the only way away this. Is my code going to experience issues if I continue to use server-side rendered blocks?
Whatever issues you had that caused a block to be "killed" after editing was entirely unrelated to the two different methods of writing the block that you have outlined. > > Building a custom block using the following method > (<https://github.com/WordPress/gutenberg-examples/blob/master/03-editable/block.js>) > of attributes with the --es5 flag appears to be more stable in terms > of backwards compatibility. If I were to make changes to the render > template > (<https://github.com/WordPress/gutenberg-examples/blob/master/03-editable/index.php>) > it wouldn't break the block. > > > Using the 'React' method > (<https://github.com/WordPress/gutenberg-examples/blob/master/03-editable-esnext/src/index.js>), > in my past experience, has caused issues. If I build a custom block > using this method and a change has been made to the block's code, it > 'kills' the block. There is no backwards compatibility from what I can > tell. > > > The code in those two method is, for all intents and purposes, the same. They are just using different syntax. The 'React' method (they're actually both React) is using some newer JavaScript features, but those are just nicer ways of writing the same code that work in newer browsers. That method also uses JSX for the render functions. This is just a different way of writing those functions which can be turned into functions exactly like the first example by a build process. The issue you're describing is going to be a challenge of developing blocks regardless of which method you use. When a post built with the block editor is saved, the final output of your block is just saved into the post content as HTML. When the post is loaded back into the editor, your block needs to be able to parse that HTML and reconstruct the block data so that it can be edited again. If your block has changed since that HTML was published, it may not be able to do this and there will be an error. This is the expected behaviour. The proper method for handling block updates without breaking existing posts is to 'deprecate' the block. The official documentation, with code examples, for that process is [here](https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/). If you encountered this issue when using ESNext, but not ES5, then that is more than likely a coincidence. It would have had more to do with *what* you were doing than which method you were doing it with, as this behaviour is a consequence of how block data is stored, and nothing to do with the JavaScript version used to write the block. It's worth pointing out that this is not a unique problem for the block editor. If I write a bunch of code in any system that works with data in a certain format, and then I update that code in a way that changes the format, I can't expect the code to just automatically work with data in the old format. You need to think of the HTML your block outputs as a format, and approach developing your block accordingly.
384,485
<p>I would like to hide the image title tag when hovering an image as they aren't needed on my website. I have tried this code below and added it above the closing <code>&lt;/head&gt;</code> in header.php but it doesn't work.</p> <p>I don't have to download a plugin to achieve this. The title tag doesn't have an impact on SEO so there shouldn't be an issue with hiding it.</p> <p>Would someone be able to tell me why my script isn't working and what I can do to make it work please?</p> <p>This is the code I have tried in my header.php above the closing <code>&lt;/head&gt;</code></p> <pre><code>&lt;script&gt; jQuery(document).ready(function($) { $('img').hover(function() { $(this).removeAttr('title'); }); }); &lt;/script&gt; </code></pre>
[ { "answer_id": 384463, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Whatever issues you had that caused a block to be &quot;killed&quot; after editing was entirely unrelat...
2021/03/04
[ "https://wordpress.stackexchange.com/questions/384485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192974/" ]
I would like to hide the image title tag when hovering an image as they aren't needed on my website. I have tried this code below and added it above the closing `</head>` in header.php but it doesn't work. I don't have to download a plugin to achieve this. The title tag doesn't have an impact on SEO so there shouldn't be an issue with hiding it. Would someone be able to tell me why my script isn't working and what I can do to make it work please? This is the code I have tried in my header.php above the closing `</head>` ``` <script> jQuery(document).ready(function($) { $('img').hover(function() { $(this).removeAttr('title'); }); }); </script> ```
Whatever issues you had that caused a block to be "killed" after editing was entirely unrelated to the two different methods of writing the block that you have outlined. > > Building a custom block using the following method > (<https://github.com/WordPress/gutenberg-examples/blob/master/03-editable/block.js>) > of attributes with the --es5 flag appears to be more stable in terms > of backwards compatibility. If I were to make changes to the render > template > (<https://github.com/WordPress/gutenberg-examples/blob/master/03-editable/index.php>) > it wouldn't break the block. > > > Using the 'React' method > (<https://github.com/WordPress/gutenberg-examples/blob/master/03-editable-esnext/src/index.js>), > in my past experience, has caused issues. If I build a custom block > using this method and a change has been made to the block's code, it > 'kills' the block. There is no backwards compatibility from what I can > tell. > > > The code in those two method is, for all intents and purposes, the same. They are just using different syntax. The 'React' method (they're actually both React) is using some newer JavaScript features, but those are just nicer ways of writing the same code that work in newer browsers. That method also uses JSX for the render functions. This is just a different way of writing those functions which can be turned into functions exactly like the first example by a build process. The issue you're describing is going to be a challenge of developing blocks regardless of which method you use. When a post built with the block editor is saved, the final output of your block is just saved into the post content as HTML. When the post is loaded back into the editor, your block needs to be able to parse that HTML and reconstruct the block data so that it can be edited again. If your block has changed since that HTML was published, it may not be able to do this and there will be an error. This is the expected behaviour. The proper method for handling block updates without breaking existing posts is to 'deprecate' the block. The official documentation, with code examples, for that process is [here](https://developer.wordpress.org/block-editor/developers/block-api/block-deprecation/). If you encountered this issue when using ESNext, but not ES5, then that is more than likely a coincidence. It would have had more to do with *what* you were doing than which method you were doing it with, as this behaviour is a consequence of how block data is stored, and nothing to do with the JavaScript version used to write the block. It's worth pointing out that this is not a unique problem for the block editor. If I write a bunch of code in any system that works with data in a certain format, and then I update that code in a way that changes the format, I can't expect the code to just automatically work with data in the old format. You need to think of the HTML your block outputs as a format, and approach developing your block accordingly.
384,506
<p>I'm just having trouble figuring out why I'm getting an error at the &quot;}&quot; after the &quot;$attachment_image&quot; line, just before &quot;&quot;. I'm probably just too tired to see it.</p> <pre><code>&lt;?php if($term) { $args = array( 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'posts_per_page' =&gt; 1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'mediacat', 'terms' =&gt; $term-&gt;term_id, ) ), 'orderby' =&gt; 'rand', 'post_status' =&gt; 'inherit', ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); $item = get_the_id(); $attachment_image = wp_get_attachment_image_url( $item, 'square' ); } ?&gt; &lt;figure class=&quot;cblNavMenu--icon__imgwrap&quot;&gt; &lt;div class=&quot;navimage&quot; style=&quot;background-image: url('&lt;?php if($term) { echo $attachment_image; } if($menu_link){ the_permalink(); } ?&gt;');&quot;&gt;&lt;/div&gt; &lt;/figure&gt; &lt;?php if($term) { endwhile; wp_reset_postdata(); } ?&gt; &lt;/div&gt; &lt;span class=&quot;cblNavMenu--label&quot;&gt;&lt;?php if($term) { if($cat_label) { echo $cat_label; } else { echo $current_term_name; } } if($menu_link){ if($cat_label) { echo $cat_label; } else { the_title(); } } ?&gt;&lt;/span&gt; </code></pre>
[ { "answer_id": 384508, "author": "Patriot", "author_id": 202596, "author_profile": "https://wordpress.stackexchange.com/users/202596", "pm_score": 1, "selected": false, "text": "<p><strong>UPDATE:</strong> Ah, there's a little more to it. I didn't see the <code>endwhile</code> further on...
2021/03/04
[ "https://wordpress.stackexchange.com/questions/384506", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88351/" ]
I'm just having trouble figuring out why I'm getting an error at the "}" after the "$attachment\_image" line, just before "". I'm probably just too tired to see it. ``` <?php if($term) { $args = array( 'post_type' => 'attachment', 'post_mime_type' => 'image', 'posts_per_page' => 1, 'tax_query' => array( array( 'taxonomy' => 'mediacat', 'terms' => $term->term_id, ) ), 'orderby' => 'rand', 'post_status' => 'inherit', ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); $item = get_the_id(); $attachment_image = wp_get_attachment_image_url( $item, 'square' ); } ?> <figure class="cblNavMenu--icon__imgwrap"> <div class="navimage" style="background-image: url('<?php if($term) { echo $attachment_image; } if($menu_link){ the_permalink(); } ?>');"></div> </figure> <?php if($term) { endwhile; wp_reset_postdata(); } ?> </div> <span class="cblNavMenu--label"><?php if($term) { if($cat_label) { echo $cat_label; } else { echo $current_term_name; } } if($menu_link){ if($cat_label) { echo $cat_label; } else { the_title(); } } ?></span> ```
You've wrapped the opening and closing of the `while` in separate `if` statements. This is the structure of your code. ``` if( $term ) { // etc. while ( $loop->have_posts() ) : } // etc. if( $term ) { endwhile; } ``` This is not valid PHP. You need to structure it like this: ``` if( $term ) { // etc. while ( $loop->have_posts() ) : // etc. endwhile; } ```
384,513
<p>In a custom shortcode function, I'm grabbing the featured image URL:</p> <pre><code>$text_slider_testimonial_img = get_the_post_thumbnail_url($single-&gt;ID); </code></pre> <p>If I echo <code>$text_slider_testimonial_img</code> immediately I see the correct image URL: <code>//localhost:3000/wp-content/uploads/2021/03/splitbanner1.jpg</code></p> <p>When I pass this variable to a function, and that function uses:</p> <pre><code>$text_slider_content .= &quot;&lt;div class='text_slider_testimonial' style='background-size: cover; background-image: url('&quot;. $text_slider_testimonial_img .&quot;')&gt;&quot;; return $text_slider_content; </code></pre> <p>the style component of the above is output as:</p> <pre><code>style=&quot;background-size: cover; background-image: url(&quot; localhost:3000=&quot;&quot; wp-content=&quot;&quot; uploads=&quot;&quot; 2021=&quot;&quot; 03=&quot;&quot; splitbanner1.jpg')=&quot;&quot;&gt; </code></pre> <p>Why are the slashes being stripped out, and the <code>=&quot;&quot;</code> being added?</p> <p>Help appreciated.</p> <p><a href="https://pastebin.com/d0NxW40K" rel="nofollow noreferrer">Here is the wider code context (pastebin.com)</a>.</p>
[ { "answer_id": 384508, "author": "Patriot", "author_id": 202596, "author_profile": "https://wordpress.stackexchange.com/users/202596", "pm_score": 1, "selected": false, "text": "<p><strong>UPDATE:</strong> Ah, there's a little more to it. I didn't see the <code>endwhile</code> further on...
2021/03/04
[ "https://wordpress.stackexchange.com/questions/384513", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/201824/" ]
In a custom shortcode function, I'm grabbing the featured image URL: ``` $text_slider_testimonial_img = get_the_post_thumbnail_url($single->ID); ``` If I echo `$text_slider_testimonial_img` immediately I see the correct image URL: `//localhost:3000/wp-content/uploads/2021/03/splitbanner1.jpg` When I pass this variable to a function, and that function uses: ``` $text_slider_content .= "<div class='text_slider_testimonial' style='background-size: cover; background-image: url('". $text_slider_testimonial_img ."')>"; return $text_slider_content; ``` the style component of the above is output as: ``` style="background-size: cover; background-image: url(" localhost:3000="" wp-content="" uploads="" 2021="" 03="" splitbanner1.jpg')=""> ``` Why are the slashes being stripped out, and the `=""` being added? Help appreciated. [Here is the wider code context (pastebin.com)](https://pastebin.com/d0NxW40K).
You've wrapped the opening and closing of the `while` in separate `if` statements. This is the structure of your code. ``` if( $term ) { // etc. while ( $loop->have_posts() ) : } // etc. if( $term ) { endwhile; } ``` This is not valid PHP. You need to structure it like this: ``` if( $term ) { // etc. while ( $loop->have_posts() ) : // etc. endwhile; } ```
384,522
<p>I'm looking for a way to insert &quot;THIS ARTICLE MAY CONTAIN COMPENSATED LINKS. PLEASE READ DISCLAIMER FOR MORE INFO.&quot; after the H1 in all my blog posts (not pages).</p> <p>Is there a way to do it without plugins?</p> <p>Thanks</p>
[ { "answer_id": 384508, "author": "Patriot", "author_id": 202596, "author_profile": "https://wordpress.stackexchange.com/users/202596", "pm_score": 1, "selected": false, "text": "<p><strong>UPDATE:</strong> Ah, there's a little more to it. I didn't see the <code>endwhile</code> further on...
2021/03/05
[ "https://wordpress.stackexchange.com/questions/384522", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202870/" ]
I'm looking for a way to insert "THIS ARTICLE MAY CONTAIN COMPENSATED LINKS. PLEASE READ DISCLAIMER FOR MORE INFO." after the H1 in all my blog posts (not pages). Is there a way to do it without plugins? Thanks
You've wrapped the opening and closing of the `while` in separate `if` statements. This is the structure of your code. ``` if( $term ) { // etc. while ( $loop->have_posts() ) : } // etc. if( $term ) { endwhile; } ``` This is not valid PHP. You need to structure it like this: ``` if( $term ) { // etc. while ( $loop->have_posts() ) : // etc. endwhile; } ```
384,526
<p>I using plugin advanced custom fields to show recommended posts in my sidebar (posts that authors select as recommended using radio buttons (yes or no)). And it is all working well.</p> <p>Now, i will need to show that same recommended posts in my mobile application via json.</p> <p>I found this amazing plugin: <a href="https://wordpress.org/plugins/acf-to-rest-api/" rel="nofollow noreferrer">https://wordpress.org/plugins/acf-to-rest-api/</a></p> <p>Now when i open json at /wp-json/wp/v2/posts i can see field ACF</p> <p>And there i can see fields recommended_sidebar: yes or recommended_sidebar: no</p> <p>But this JSON will show all posts (latest posts). Is it possible to make some filter for posts? I will like to show only posts that have recommended_sidebar: yes ? Something like: <a href="https://www.domain.com/wp-json/wp/v2/posts?filter%5Brecommended_sidebar%5D=yes" rel="nofollow noreferrer">https://www.domain.com/wp-json/wp/v2/posts?filter[recommended_sidebar]=yes</a></p> <p>If is not possible to create that filter via url, then only option is to create custom endpoint. So i create this:</p> <pre class="lang-php prettyprint-override"><code>add_action( 'rest_api_init', 'api_hooks' ); function api_hooks() { register_rest_route( 'get-post-sidebar/v1', '/go', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'get_post_sidebar', ) ); } function get_post_sidebar($request_data){ // $data = $request_data-&gt;get_params(); $data = array(); $args = array( 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'orderby' =&gt; 'id', 'order' =&gt; 'DESC', 'meta_query' =&gt; array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'recommended_sidebar', 'value' =&gt; 'yes', 'compare' =&gt; '=', ), ), 'paged' =&gt; 1, 'posts_per_page' =&gt; 2, ); $the_query = new WP_Query( $args ); while ( $the_query-&gt;have_posts() ) { $the_query-&gt;the_post(); array_push($data, array( 'title' =&gt; get_the_title(), 'content' =&gt; get_the_content(), 'date' =&gt; get_the_date(), 'number_of_comments' =&gt; get_comments_number(), 'thumbnail' =&gt; get_the_post_thumbnail_url() ) ); } wp_reset_postdata(); $response = new \WP_REST_Response( $data ); $response-&gt;set_status( 200 ); return $response; } </code></pre> <p>This this endpoint will show only sticky posts. Also, it is set to:</p> <pre class="lang-php prettyprint-override"><code> 'paged' =&gt; 1, 'posts_per_page' =&gt; 2, </code></pre> <p>But all sticky posts will show up in endpoint.</p> <ul> <li>if i change this value to:</li> </ul> <pre class="lang-php prettyprint-override"><code> 'paged' =&gt; 2, 'posts_per_page' =&gt; 2, </code></pre> <p>Then it will show 2 posts, but that 2 posts are sticky posts :(</p> <ul> <li>if i change this value to:</li> </ul> <pre class="lang-php prettyprint-override"><code> 'paged' =&gt; 2, 'posts_per_page' =&gt; 8, </code></pre> <p>Then it will show 8 that are not recommended_sidebar: yes, but there are not sticky too, it is very very strange.</p> <p>I will like to show only 8 latest posts that have recommended_sidebar: yes</p> <p>Best Regards Thank you!</p>
[ { "answer_id": 384541, "author": "Stevo", "author_id": 202881, "author_profile": "https://wordpress.stackexchange.com/users/202881", "pm_score": 0, "selected": false, "text": "<p>Maybe try amending the query to something like this (i havent test this but cant hurt to try) maybe get rid o...
2021/03/05
[ "https://wordpress.stackexchange.com/questions/384526", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138487/" ]
I using plugin advanced custom fields to show recommended posts in my sidebar (posts that authors select as recommended using radio buttons (yes or no)). And it is all working well. Now, i will need to show that same recommended posts in my mobile application via json. I found this amazing plugin: <https://wordpress.org/plugins/acf-to-rest-api/> Now when i open json at /wp-json/wp/v2/posts i can see field ACF And there i can see fields recommended\_sidebar: yes or recommended\_sidebar: no But this JSON will show all posts (latest posts). Is it possible to make some filter for posts? I will like to show only posts that have recommended\_sidebar: yes ? Something like: [https://www.domain.com/wp-json/wp/v2/posts?filter[recommended\_sidebar]=yes](https://www.domain.com/wp-json/wp/v2/posts?filter%5Brecommended_sidebar%5D=yes) If is not possible to create that filter via url, then only option is to create custom endpoint. So i create this: ```php add_action( 'rest_api_init', 'api_hooks' ); function api_hooks() { register_rest_route( 'get-post-sidebar/v1', '/go', array( 'methods' => 'GET', 'callback' => 'get_post_sidebar', ) ); } function get_post_sidebar($request_data){ // $data = $request_data->get_params(); $data = array(); $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'orderby' => 'id', 'order' => 'DESC', 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'recommended_sidebar', 'value' => 'yes', 'compare' => '=', ), ), 'paged' => 1, 'posts_per_page' => 2, ); $the_query = new WP_Query( $args ); while ( $the_query->have_posts() ) { $the_query->the_post(); array_push($data, array( 'title' => get_the_title(), 'content' => get_the_content(), 'date' => get_the_date(), 'number_of_comments' => get_comments_number(), 'thumbnail' => get_the_post_thumbnail_url() ) ); } wp_reset_postdata(); $response = new \WP_REST_Response( $data ); $response->set_status( 200 ); return $response; } ``` This this endpoint will show only sticky posts. Also, it is set to: ```php 'paged' => 1, 'posts_per_page' => 2, ``` But all sticky posts will show up in endpoint. * if i change this value to: ```php 'paged' => 2, 'posts_per_page' => 2, ``` Then it will show 2 posts, but that 2 posts are sticky posts :( * if i change this value to: ```php 'paged' => 2, 'posts_per_page' => 8, ``` Then it will show 8 that are not recommended\_sidebar: yes, but there are not sticky too, it is very very strange. I will like to show only 8 latest posts that have recommended\_sidebar: yes Best Regards Thank you!
TL;DR - ACF now has support for the WP REST API Hey all, Iain the Product Manager for Advanced Custom Fields here As part of the [ACF 5.11](https://www.advancedcustomfields.com/blog/acf-5-11-release-rest-api/) release we added native support for ACF fields in the WordPress REST API. Read more about that [here](https://www.advancedcustomfields.com/resources/rest-api/).
384,570
<p>I want to set WordPress Transient via Variable Value.</p> <p>This is an example code with what I'm trying to achieve.</p> <pre><code>&lt;?php if ( false === get_transient( 'special_query_results' ) ) { $ExpiryInterval = &quot;24 * HOUR_IN_SECONDS&quot;; // &lt;--- Storing in Variable $RandPostQuery = new WP_Query(array('post_type'=&gt;array('tip'),'posts_per_page' =&gt; 1,'orderby'=&gt;'rand')); set_transient( 'special_query_results', $RandPostQuery , $ExpiryInterval ); // &lt;-- Retriving from Variable } ?&gt; </code></pre> <p>I don't know why it's not working. If I try setting directly without variable it's working perfectly. Not sure why it's not working this way.</p>
[ { "answer_id": 384573, "author": "vancoder", "author_id": 26778, "author_profile": "https://wordpress.stackexchange.com/users/26778", "pm_score": 1, "selected": false, "text": "<p><code>HOUR_IN_SECONDS</code> is a <a href=\"https://codex.wordpress.org/Easier_Expression_of_Time_Constants\...
2021/03/05
[ "https://wordpress.stackexchange.com/questions/384570", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/195903/" ]
I want to set WordPress Transient via Variable Value. This is an example code with what I'm trying to achieve. ``` <?php if ( false === get_transient( 'special_query_results' ) ) { $ExpiryInterval = "24 * HOUR_IN_SECONDS"; // <--- Storing in Variable $RandPostQuery = new WP_Query(array('post_type'=>array('tip'),'posts_per_page' => 1,'orderby'=>'rand')); set_transient( 'special_query_results', $RandPostQuery , $ExpiryInterval ); // <-- Retriving from Variable } ?> ``` I don't know why it's not working. If I try setting directly without variable it's working perfectly. Not sure why it's not working this way.
```php $ExpiryInterval = "24 * HOUR_IN_SECONDS"; ``` `$ExpiryInterval` is being assigned a string, but you need a number. Consider this example: ```php $foo = 5 * 10; $bar = "5 * 10"; ``` The value of `$foo` is `50`. The value of `$bar` is `"5 * 10"`. `set_transient` expects a number, not a string, `"24 * HOUR_IN_SECONDS"` is text/string, `24 * HOUR_IN_SECONDS` is a number. `HOUR_IN_SECONDS` is a constant equal to the number of seconds in an hour.
384,614
<p>I've been playing a little bit with the woocommerce storefront theme and woocommerce, and I wanted to display the &quot;Add to basket&quot; and &quot;Read more&quot; at the same time on the shop page for each product when possible. <strong>I came out with a solution, but I wonder if there is a different way to do this</strong> so I don't have to use CSS to hide a &quot;Read more&quot; button next to another &quot;Read more&quot;. Ideally, I wouldn't need CSS and there would be only one &quot;Read more&quot; button when it's not possible to add to the cart.</p> <p>Here is the code I used:</p> <pre><code>add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 ); function woocommerce_template_loop_add_to_cart() { global $product; $link = apply_filters( 'woocommerce_loop_product_link', get_the_permalink(), $product ); echo '&lt;div class=&quot;woocommerce-LoopProduct-buttons-container&quot;&gt;'; echo '&lt;a href=&quot;' . esc_url( $link ) . '&quot; class=&quot;button button--read-more&quot;&gt;'.__( 'Read more', 'woocommerce' ).'&lt;/a&gt;'; echo apply_filters( 'woocommerce_loop_add_to_cart_link', // WPCS: XSS ok. sprintf( '&lt;a href=&quot;%s&quot; data-quantity=&quot;%s&quot; class=&quot;%s&quot; %s&gt;%s&lt;/a&gt;', esc_url( $product-&gt;add_to_cart_url() ), esc_attr( isset( $args['quantity'] ) ? $args['quantity'] : 1 ), esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ), isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '', esc_html( $product-&gt;add_to_cart_text() ) ), $product, $args ); echo '&lt;/div&gt;'; } </code></pre> <p>And some CSS (SCSS) that does the trick:</p> <pre><code>... .button { margin: 5px 15px; &amp; ~ a[href^=&quot;http&quot;] { display: none; } } ... </code></pre> <p>Here is how it looks like and hopefully helps to better understand what I want to optimize:</p> <p><a href="https://i.stack.imgur.com/7rT0Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7rT0Y.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/hHlfM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hHlfM.png" alt="enter image description here" /></a></p>
[ { "answer_id": 384573, "author": "vancoder", "author_id": 26778, "author_profile": "https://wordpress.stackexchange.com/users/26778", "pm_score": 1, "selected": false, "text": "<p><code>HOUR_IN_SECONDS</code> is a <a href=\"https://codex.wordpress.org/Easier_Expression_of_Time_Constants\...
2021/03/06
[ "https://wordpress.stackexchange.com/questions/384614", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128713/" ]
I've been playing a little bit with the woocommerce storefront theme and woocommerce, and I wanted to display the "Add to basket" and "Read more" at the same time on the shop page for each product when possible. **I came out with a solution, but I wonder if there is a different way to do this** so I don't have to use CSS to hide a "Read more" button next to another "Read more". Ideally, I wouldn't need CSS and there would be only one "Read more" button when it's not possible to add to the cart. Here is the code I used: ``` add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 ); function woocommerce_template_loop_add_to_cart() { global $product; $link = apply_filters( 'woocommerce_loop_product_link', get_the_permalink(), $product ); echo '<div class="woocommerce-LoopProduct-buttons-container">'; echo '<a href="' . esc_url( $link ) . '" class="button button--read-more">'.__( 'Read more', 'woocommerce' ).'</a>'; echo apply_filters( 'woocommerce_loop_add_to_cart_link', // WPCS: XSS ok. sprintf( '<a href="%s" data-quantity="%s" class="%s" %s>%s</a>', esc_url( $product->add_to_cart_url() ), esc_attr( isset( $args['quantity'] ) ? $args['quantity'] : 1 ), esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ), isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '', esc_html( $product->add_to_cart_text() ) ), $product, $args ); echo '</div>'; } ``` And some CSS (SCSS) that does the trick: ``` ... .button { margin: 5px 15px; & ~ a[href^="http"] { display: none; } } ... ``` Here is how it looks like and hopefully helps to better understand what I want to optimize: [![enter image description here](https://i.stack.imgur.com/7rT0Y.png)](https://i.stack.imgur.com/7rT0Y.png) [![enter image description here](https://i.stack.imgur.com/hHlfM.png)](https://i.stack.imgur.com/hHlfM.png)
```php $ExpiryInterval = "24 * HOUR_IN_SECONDS"; ``` `$ExpiryInterval` is being assigned a string, but you need a number. Consider this example: ```php $foo = 5 * 10; $bar = "5 * 10"; ``` The value of `$foo` is `50`. The value of `$bar` is `"5 * 10"`. `set_transient` expects a number, not a string, `"24 * HOUR_IN_SECONDS"` is text/string, `24 * HOUR_IN_SECONDS` is a number. `HOUR_IN_SECONDS` is a constant equal to the number of seconds in an hour.
384,680
<p>I am using WordPress and I have to show the related blog by category. I have created a custom-type post. I tried the below code but the code is displaying the last category of the post.</p> <p>Would you help me out with this issue?</p> <pre><code>function relatedBlogPost($atts){ global $post; $custom_terms = get_terms('blogs_cat'); foreach($custom_terms as $custom_term) { $args = array( 'post_type' =&gt; 'blog', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; 6, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'blogs_cat', 'field' =&gt; 'slug', 'terms' =&gt; $custom_term-&gt;slug ), ), 'post__not_in' =&gt; array ($post-&gt;ID), //'order' =&gt; 'DEC' ); $loop = new WP_Query($args); if($loop-&gt;have_posts()) { $data=''; $data .= '&lt;ul&gt;'; while($loop-&gt;have_posts()){ $loop-&gt;the_post(); /*get category name*/ $terms = get_the_terms( $loop-&gt;ID , 'blogs_cat' ); foreach ( $terms as $term ) { $catname=$term-&gt;name; } $data.= '&lt;li&gt; &lt;a href=&quot;'.get_permalink().'&quot;&gt; &lt;div class=&quot;main-blogBoxwrapper&quot;&gt; &lt;img src=&quot;'.get_the_post_thumbnail_url().'&quot;&gt; &lt;div class=&quot;blogCatname&quot;&gt; &lt;h6&gt;&lt;span&gt;'.$catname.'&lt;/span&gt;&lt;/h6&gt; &lt;h4&gt;'.wp_trim_words(get_the_title(), 14, '...').'&lt;/h4&gt; &lt;p&gt;'.wp_trim_words(get_the_excerpt(), 20, '...').'&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt;&lt;/li&gt;'; } $data.='&lt;/ul&gt;'; return $data; wp_reset_postdata(); } } } add_shortcode( 'related-blog-post', 'relatedBlogPost'); </code></pre> <p>Would you help me out with this issue?</p>
[ { "answer_id": 384573, "author": "vancoder", "author_id": 26778, "author_profile": "https://wordpress.stackexchange.com/users/26778", "pm_score": 1, "selected": false, "text": "<p><code>HOUR_IN_SECONDS</code> is a <a href=\"https://codex.wordpress.org/Easier_Expression_of_Time_Constants\...
2021/03/08
[ "https://wordpress.stackexchange.com/questions/384680", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/177715/" ]
I am using WordPress and I have to show the related blog by category. I have created a custom-type post. I tried the below code but the code is displaying the last category of the post. Would you help me out with this issue? ``` function relatedBlogPost($atts){ global $post; $custom_terms = get_terms('blogs_cat'); foreach($custom_terms as $custom_term) { $args = array( 'post_type' => 'blog', 'post_status' => 'publish', 'posts_per_page' => 6, 'tax_query' => array( array( 'taxonomy' => 'blogs_cat', 'field' => 'slug', 'terms' => $custom_term->slug ), ), 'post__not_in' => array ($post->ID), //'order' => 'DEC' ); $loop = new WP_Query($args); if($loop->have_posts()) { $data=''; $data .= '<ul>'; while($loop->have_posts()){ $loop->the_post(); /*get category name*/ $terms = get_the_terms( $loop->ID , 'blogs_cat' ); foreach ( $terms as $term ) { $catname=$term->name; } $data.= '<li> <a href="'.get_permalink().'"> <div class="main-blogBoxwrapper"> <img src="'.get_the_post_thumbnail_url().'"> <div class="blogCatname"> <h6><span>'.$catname.'</span></h6> <h4>'.wp_trim_words(get_the_title(), 14, '...').'</h4> <p>'.wp_trim_words(get_the_excerpt(), 20, '...').'</p> </div> </div> </a></li>'; } $data.='</ul>'; return $data; wp_reset_postdata(); } } } add_shortcode( 'related-blog-post', 'relatedBlogPost'); ``` Would you help me out with this issue?
```php $ExpiryInterval = "24 * HOUR_IN_SECONDS"; ``` `$ExpiryInterval` is being assigned a string, but you need a number. Consider this example: ```php $foo = 5 * 10; $bar = "5 * 10"; ``` The value of `$foo` is `50`. The value of `$bar` is `"5 * 10"`. `set_transient` expects a number, not a string, `"24 * HOUR_IN_SECONDS"` is text/string, `24 * HOUR_IN_SECONDS` is a number. `HOUR_IN_SECONDS` is a constant equal to the number of seconds in an hour.
384,917
<p>i want to get a post embedded images but the only methods i see over the internet are</p> <pre><code> $attachments = get_posts(array( 'post_parent' =&gt; get_the_ID(), 'post_type' =&gt; 'attachment', 'posts_per_page' =&gt; $n, 'post_mime_type' =&gt; 'image' )); $attachments = get_children(array( 'post_parent' =&gt; get_the_ID(), 'post_type' =&gt; 'attachment', 'posts_per_page' =&gt; $n, 'post_mime_type' =&gt; 'image' )); $attachments = get_attached_media('image', get_the_ID()); </code></pre> <p>but this gives only the attached images i want all the images in a post even if they are not attached to that post <code>'post_parent' =&gt; get_the_ID()</code></p> <p>i think this is the wordpress way of attaching images it sounds like a one-to-many relationship an image can only be attached to one post</p> <p>any idea ? thanks in advance</p>
[ { "answer_id": 384928, "author": "Álvaro García", "author_id": 201928, "author_profile": "https://wordpress.stackexchange.com/users/201928", "pm_score": 0, "selected": false, "text": "<p>You can use DOMDocument to get every image from any page:</p>\n<pre><code>function testingdom(){\n\n ...
2021/03/11
[ "https://wordpress.stackexchange.com/questions/384917", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/201279/" ]
i want to get a post embedded images but the only methods i see over the internet are ``` $attachments = get_posts(array( 'post_parent' => get_the_ID(), 'post_type' => 'attachment', 'posts_per_page' => $n, 'post_mime_type' => 'image' )); $attachments = get_children(array( 'post_parent' => get_the_ID(), 'post_type' => 'attachment', 'posts_per_page' => $n, 'post_mime_type' => 'image' )); $attachments = get_attached_media('image', get_the_ID()); ``` but this gives only the attached images i want all the images in a post even if they are not attached to that post `'post_parent' => get_the_ID()` i think this is the wordpress way of attaching images it sounds like a one-to-many relationship an image can only be attached to one post any idea ? thanks in advance
i think if WordPress doesn't provide such a function then this is the shortest way ``` function my_get_embeded_media() { $content = apply_filters('the_content', get_the_content()); $arr = preg_match_all("/<img[^>]* src=\"([^\"]*)\"[^>]*>/", $content, $matches); return $arr ? $matches[1] : array(); } ``` but we still can't control the images size!
384,980
<p>im about to install wordpress trought my cpanel, and it asks me do I want to install it on HTTP or https, I checked, and my domain has valid SSL certificate? what should I do? install It on https or HTTP?</p>
[ { "answer_id": 384928, "author": "Álvaro García", "author_id": 201928, "author_profile": "https://wordpress.stackexchange.com/users/201928", "pm_score": 0, "selected": false, "text": "<p>You can use DOMDocument to get every image from any page:</p>\n<pre><code>function testingdom(){\n\n ...
2021/03/12
[ "https://wordpress.stackexchange.com/questions/384980", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203265/" ]
im about to install wordpress trought my cpanel, and it asks me do I want to install it on HTTP or https, I checked, and my domain has valid SSL certificate? what should I do? install It on https or HTTP?
i think if WordPress doesn't provide such a function then this is the shortest way ``` function my_get_embeded_media() { $content = apply_filters('the_content', get_the_content()); $arr = preg_match_all("/<img[^>]* src=\"([^\"]*)\"[^>]*>/", $content, $matches); return $arr ? $matches[1] : array(); } ``` but we still can't control the images size!
385,007
<p>I want to create a shortcode that pulls value from a custom field of a post and parses that value on Post title, post content.</p> <p>So if the custom field value is <strong>Icecream</strong> for Post 1.</p> <p>On the admin side the post title will be <strong>Favorite [geo_name]</strong>, it will be displayed as <strong>Favorite Icecream</strong>.</p> <p>Here is my code so far:</p> <pre><code>function geo_name_function( $atts ) { $atts = shortcode_atts( array( 'post_id' =&gt; get_the_ID(), ), $atts, 'geo_name' ); return get_post_meta( $atts['post_id'], 'field_name', true ); } add_shortcode('geo_name', 'geo_name_function'); add_filter( 'the_title', function( $geo_name_function ) { return do_shortcode( $geo_name_function ); }); </code></pre> <p>I keep having one issue.</p> <p>If Recent Posts Widget is on one of the posts it displays the same value for all post titles.</p> <p>For example:</p> <p>Article 1</p> <p>[geo name] value = Geo 1</p> <p>Admin title: [geo_name] title Rendered title: Geo 1 title</p> <p>Article 2</p> <p>[geo name] value = Geo 2</p> <p>Admin title: [geo_name] title Rendered title: Geo 2 title</p> <p>If I am on an Article 1 page my Recent Post Widget looks like:</p> <p>Recent Posts</p> <p>Geo 1 title -&gt; url to article 1</p> <p>Geo 1 title -&gt; url to article 2</p> <p>If I am on an Article 2 page my Recent Post Widget looks like:</p> <p>Recent Posts</p> <p>Geo 2 title -&gt; url to article 1</p> <p>Geo 2 title -&gt; url to article 2</p> <p>My PHP knowledge is very limited, Please assist!</p>
[ { "answer_id": 384928, "author": "Álvaro García", "author_id": 201928, "author_profile": "https://wordpress.stackexchange.com/users/201928", "pm_score": 0, "selected": false, "text": "<p>You can use DOMDocument to get every image from any page:</p>\n<pre><code>function testingdom(){\n\n ...
2021/03/12
[ "https://wordpress.stackexchange.com/questions/385007", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/164186/" ]
I want to create a shortcode that pulls value from a custom field of a post and parses that value on Post title, post content. So if the custom field value is **Icecream** for Post 1. On the admin side the post title will be **Favorite [geo\_name]**, it will be displayed as **Favorite Icecream**. Here is my code so far: ``` function geo_name_function( $atts ) { $atts = shortcode_atts( array( 'post_id' => get_the_ID(), ), $atts, 'geo_name' ); return get_post_meta( $atts['post_id'], 'field_name', true ); } add_shortcode('geo_name', 'geo_name_function'); add_filter( 'the_title', function( $geo_name_function ) { return do_shortcode( $geo_name_function ); }); ``` I keep having one issue. If Recent Posts Widget is on one of the posts it displays the same value for all post titles. For example: Article 1 [geo name] value = Geo 1 Admin title: [geo\_name] title Rendered title: Geo 1 title Article 2 [geo name] value = Geo 2 Admin title: [geo\_name] title Rendered title: Geo 2 title If I am on an Article 1 page my Recent Post Widget looks like: Recent Posts Geo 1 title -> url to article 1 Geo 1 title -> url to article 2 If I am on an Article 2 page my Recent Post Widget looks like: Recent Posts Geo 2 title -> url to article 1 Geo 2 title -> url to article 2 My PHP knowledge is very limited, Please assist!
i think if WordPress doesn't provide such a function then this is the shortest way ``` function my_get_embeded_media() { $content = apply_filters('the_content', get_the_content()); $arr = preg_match_all("/<img[^>]* src=\"([^\"]*)\"[^>]*>/", $content, $matches); return $arr ? $matches[1] : array(); } ``` but we still can't control the images size!
385,029
<p>I hope everyone is well!</p> <p>I am looking for a possibility to load different galleries, background images etc for the phone and desktop. For example, I set my hero background image like this:</p> <pre><code> &lt;section class=&quot;hero&quot; style=&quot;background-image: url(&lt;?php echo esc_url(wp_get_attachment_image_src(get_field('advanced_custom_fields_field'), 'full')[0]); ?&gt;)&quot;&gt; </code></pre> <p>When the window is resized (or website is opened on the phone), I would like to get the image from another <strong>advanced custom field entry</strong> (for example get_field('advanced_custom_fields_field <strong>_mobile</strong>') )</p> <p>Is there a way to do it in php without js and ajax or is it the best way to do it with js?</p> <p>Is there maybe a way to include advanced custom fields in a styles.php sheet with the header</p> <pre><code>header('Content-Type: text/css; charset:UTF-8'); </code></pre> <p>If this was possible I could just write media queries here and include different images with get_field() function, but I didn't find a way to access get_field() function in style.php</p> <p>Of course, this all can be achieved with js, but I am curious if there is a WP way of doing this. Thank you so much for your help!</p>
[ { "answer_id": 385058, "author": "Matthew Brown aka Lord Matt", "author_id": 109240, "author_profile": "https://wordpress.stackexchange.com/users/109240", "pm_score": 0, "selected": false, "text": "<p>It sounds like you are after the srcset feature of HTML. IT allows you to define differ...
2021/03/13
[ "https://wordpress.stackexchange.com/questions/385029", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203297/" ]
I hope everyone is well! I am looking for a possibility to load different galleries, background images etc for the phone and desktop. For example, I set my hero background image like this: ``` <section class="hero" style="background-image: url(<?php echo esc_url(wp_get_attachment_image_src(get_field('advanced_custom_fields_field'), 'full')[0]); ?>)"> ``` When the window is resized (or website is opened on the phone), I would like to get the image from another **advanced custom field entry** (for example get\_field('advanced\_custom\_fields\_field **\_mobile**') ) Is there a way to do it in php without js and ajax or is it the best way to do it with js? Is there maybe a way to include advanced custom fields in a styles.php sheet with the header ``` header('Content-Type: text/css; charset:UTF-8'); ``` If this was possible I could just write media queries here and include different images with get\_field() function, but I didn't find a way to access get\_field() function in style.php Of course, this all can be achieved with js, but I am curious if there is a WP way of doing this. Thank you so much for your help!
You can display the selected image when using the `Image ID` return type `<?php $image = get_field('image'); $size = 'full'; // (thumbnail, medium, large, full or custom size) if( $image ) { echo wp_get_attachment_image( $image, $size ); }` This function also generates the srcset attribute allowing for **responsive images**!
385,054
<p>Can a non-javascript person fix this error? any advice? thank you for help?</p> <p>console shows:</p> <p><a href="https://i.stack.imgur.com/pEdmj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pEdmj.jpg" alt="Uncaught ReferenceError: jQuery is not defined" /></a></p> <p>code is:</p> <pre><code> &lt;script async src=&quot;https://cdn.filmpuls.info/jquery/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot;&gt; function insertBefore(e, t) { t.parentNode.insertBefore(e, t), e.classList.add(&quot;entry-content&quot;) } var intocontent = document.getElementsByClassName(&quot;intro&quot;) , intocontentheading = document.getElementsByClassName(&quot;mh-meta&quot;); insertBefore(intocontent[0], intocontentheading[0]); var postId = &quot;55687&quot; , postIdClass = &quot;.post-&quot; + postId; console.log(postIdClass), jQuery(document).ready(function() { jQuery(&quot;body.single .mh-widget&quot;).each(function(e) { jQuery(this).find(postIdClass).length &amp;&amp; jQuery(this).find(postIdClass).hide() }) }); &lt;/script&gt; </code></pre>
[ { "answer_id": 385060, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>It's a very bad idea to deregister jQuery and re-register it to a CDN, and it does not improve performance. ...
2021/03/14
[ "https://wordpress.stackexchange.com/questions/385054", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202302/" ]
Can a non-javascript person fix this error? any advice? thank you for help? console shows: [![Uncaught ReferenceError: jQuery is not defined](https://i.stack.imgur.com/pEdmj.jpg)](https://i.stack.imgur.com/pEdmj.jpg) code is: ``` <script async src="https://cdn.filmpuls.info/jquery/jquery.min.js"></script> <script type="text/javascript"> function insertBefore(e, t) { t.parentNode.insertBefore(e, t), e.classList.add("entry-content") } var intocontent = document.getElementsByClassName("intro") , intocontentheading = document.getElementsByClassName("mh-meta"); insertBefore(intocontent[0], intocontentheading[0]); var postId = "55687" , postIdClass = ".post-" + postId; console.log(postIdClass), jQuery(document).ready(function() { jQuery("body.single .mh-widget").each(function(e) { jQuery(this).find(postIdClass).length && jQuery(this).find(postIdClass).hide() }) }); </script> ```
thanks to the inputs of two great members of this community, I could solve the matter without touching any code, applying the follow fixes: * exclude jquery.min.js from "CDN Enabler" plugin * exclude jquery.min.js in plugin "Async JavaScript" * exclude jquery.min.js in plugin "Autoptimize" in the section JavaScript-options
385,059
<p>In Ubuntu 20.04 wp-env is giving me error once i have installed it and while trying to start it with <code>wp-env start</code> .The error showing is <code>mysqlcheck: Got error: 1130: Host '172.29.0.5' is not allowed to connect to this MariaDB server when trying to connect</code>.</p> <p>I have tried....... <code>CREATE USER 'wp'@'%' IDENTIFIED BY 'newpass'; </code> <code>GRANT ALL PRIVILEGES ON *.* TO 'wp'@'%';</code></p> <p><code>sudo service mysql restart </code>.</p> <p>Changed the <code>wp-config</code> with new user and password keeping the DB_HOST same as earlier ( ie; <code>localhost</code>)</p> <p>Still i am getting the same error . Can somebody please let me know what i have done wrong ?</p>
[ { "answer_id": 385079, "author": "Greys", "author_id": 194559, "author_profile": "https://wordpress.stackexchange.com/users/194559", "pm_score": 2, "selected": false, "text": "<p>Step 1: Find the name of your wp-env container</p>\n<p>First, you need to locate the name of the container cr...
2021/03/14
[ "https://wordpress.stackexchange.com/questions/385059", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9673/" ]
In Ubuntu 20.04 wp-env is giving me error once i have installed it and while trying to start it with `wp-env start` .The error showing is `mysqlcheck: Got error: 1130: Host '172.29.0.5' is not allowed to connect to this MariaDB server when trying to connect`. I have tried....... `CREATE USER 'wp'@'%' IDENTIFIED BY 'newpass';` `GRANT ALL PRIVILEGES ON *.* TO 'wp'@'%';` `sudo service mysql restart` . Changed the `wp-config` with new user and password keeping the DB\_HOST same as earlier ( ie; `localhost`) Still i am getting the same error . Can somebody please let me know what i have done wrong ?
Step 1: Find the name of your wp-env container First, you need to locate the name of the container created by wp-env. To do this, in the directory of your project containing .wp-env.json, you must run the following command: ``` docker ps ``` This should give you a list of containers. In the Names column, you’ll see the following information: ``` 7b3099bc856ae9db898a196c0465cadb_wordpress_1 7b3099bc856ae9db898a196c0465cadb_tests-wordpress_1 7b3099bc856ae9db898a196c0465cadb_mysql_1 ``` In this example, “7b3099bc856ae9db898a196c0465cadb” is the name of the container created by wp-env. Step 2: Access the directory containing your docker-compose file Once you have the name of your wp-env container, you can use it to access the directory containing the docker-compose file created by wp-env. To do so, run the following command in your terminal: ``` cd ~/.wp-env/7b3099bc856ae9db898a196c0465cadb docker-compose down -v docker-compose up -d ``` This should create a fresh environment. Step 3: Restart wp-env Finally, go back to your project folder and run: ``` wp-env start ``` You should then receive a message informing you that your WordPress dev environment is ready. Source: How to Fix MariaDB Error 1130 with wp-env and Docker <https://greys.co/how-to-fix-mariadb-error-1130-wp-env-docker/>
385,084
<h1>How to change taxonomy urls in wordpress?</h1> <p>Following along with <a href="https://wordpress.stackexchange.com/questions/296510/divi-change-project-slug-based-on-category">this question</a> and <a href="https://wordpress.stackexchange.com/questions/212455/change-the-url-of-projects-in-divi-theme">this one</a></p> <p>But can not get the desired outcome.</p> <p><strong>The default is:</strong></p> <pre><code>example.com/project_category/%category%/ </code></pre> <p><strong>What I want is:</strong></p> <pre><code>example.com/stainless-steel-products/%category%/ </code></pre> <p>I have changed the slug of the project archive so that <code>example.com/stainless-steel-products/</code> is the project archive.</p> <p>Below is the code used to achieve that.</p> <pre><code>// Change peralinks projects function custom_project_slug () { return array( 'feeds' =&gt; true, 'slug' =&gt; 'stainless-steel-products', 'with_front' =&gt; false, ); } add_filter( 'et_project_posttype_rewrite_args', 'custom_project_slug' ); ?&gt; </code></pre> <p>How do I change the slug of the project categories so that it is a child of the project archive? Thanks for any help in advance!</p>
[ { "answer_id": 386592, "author": "jasmines", "author_id": 173126, "author_profile": "https://wordpress.stackexchange.com/users/173126", "pm_score": 3, "selected": true, "text": "<pre><code>add_filter( 'register_taxonomy_args', 'change_taxonomies_slug', 10, 2 );\nfunction change_taxonomie...
2021/03/15
[ "https://wordpress.stackexchange.com/questions/385084", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192994/" ]
How to change taxonomy urls in wordpress? ========================================= Following along with [this question](https://wordpress.stackexchange.com/questions/296510/divi-change-project-slug-based-on-category) and [this one](https://wordpress.stackexchange.com/questions/212455/change-the-url-of-projects-in-divi-theme) But can not get the desired outcome. **The default is:** ``` example.com/project_category/%category%/ ``` **What I want is:** ``` example.com/stainless-steel-products/%category%/ ``` I have changed the slug of the project archive so that `example.com/stainless-steel-products/` is the project archive. Below is the code used to achieve that. ``` // Change peralinks projects function custom_project_slug () { return array( 'feeds' => true, 'slug' => 'stainless-steel-products', 'with_front' => false, ); } add_filter( 'et_project_posttype_rewrite_args', 'custom_project_slug' ); ?> ``` How do I change the slug of the project categories so that it is a child of the project archive? Thanks for any help in advance!
``` add_filter( 'register_taxonomy_args', 'change_taxonomies_slug', 10, 2 ); function change_taxonomies_slug( $args, $taxonomy ) { if ( 'project_category' === $taxonomy ) { $args['rewrite']['slug'] = 'stainless-steel-products'; } return $args; } ```
385,186
<p>I would like to show an archive of posts that have two taxonomy terms in common. So for example, I'd like to show all posts that have <em>both</em> the terms &quot;sauce&quot; and &quot;cheese&quot; in the custom <code>food</code> taxonomy.</p> <p>The trick is that I'd like to do this using the url. The closest I've come is with:</p> <pre><code>example.com?food[]=sauce&amp;food[]=cheese </code></pre> <p>Upon inspecting the $query from the <code>pre_get_posts</code> filter, I can see that:</p> <pre><code>WP_Tax_Query::__set_state(array( 'queries' =&gt; array ( 0 =&gt; array ( 'taxonomy' =&gt; 'food', 'terms' =&gt; array ( 0 =&gt; 'sauce', 1 =&gt; 'cheese', ), 'field' =&gt; 'slug', 'operator' =&gt; 'IN', 'include_children' =&gt; true, ), ), </code></pre> <p>So then I change the <code>operator</code> to <code>AND</code> like so:</p> <pre><code>add_action('pre_get_posts', function($query) { $query-&gt;tax_query-&gt;queries[0]['operator'] = 'AND'; }); </code></pre> <p>But my results are always including posts that have <em>at least</em> one term instead of posts that have <em>all</em> terms.</p> <p>According to Query Monitor, the main query is as such (and you can see that it's looking for posts that have <em>either</em> of the two term IDs.</p> <pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (6,9) ) </code></pre> <p>So, how can I formulate a url to get only posts with <em>both</em> taxonomy-terms?</p>
[ { "answer_id": 385251, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 2, "selected": false, "text": "<p>Looks like you can define the <code>AND</code> logical operator with the URL parameters, specifically adding ...
2021/03/16
[ "https://wordpress.stackexchange.com/questions/385186", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2044/" ]
I would like to show an archive of posts that have two taxonomy terms in common. So for example, I'd like to show all posts that have *both* the terms "sauce" and "cheese" in the custom `food` taxonomy. The trick is that I'd like to do this using the url. The closest I've come is with: ``` example.com?food[]=sauce&food[]=cheese ``` Upon inspecting the $query from the `pre_get_posts` filter, I can see that: ``` WP_Tax_Query::__set_state(array( 'queries' => array ( 0 => array ( 'taxonomy' => 'food', 'terms' => array ( 0 => 'sauce', 1 => 'cheese', ), 'field' => 'slug', 'operator' => 'IN', 'include_children' => true, ), ), ``` So then I change the `operator` to `AND` like so: ``` add_action('pre_get_posts', function($query) { $query->tax_query->queries[0]['operator'] = 'AND'; }); ``` But my results are always including posts that have *at least* one term instead of posts that have *all* terms. According to Query Monitor, the main query is as such (and you can see that it's looking for posts that have *either* of the two term IDs. ``` SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (6,9) ) ``` So, how can I formulate a url to get only posts with *both* taxonomy-terms?
When I registered my taxonomy, I left out the argument for 'rewrite', which then defaulted to `true`. So by default, WordPress wanted to rewrite the url as `/food/whatever/`. The tricky thing was that it *did* accept the format `?food=whatever` , but wouldn't accept two different terms in that format when joined with a plus. The solution was to specify the rewrite arg of `register_taxonomy()` like so: ``` register_taxonomy( 'food', 'post', [ ... 'rewrite' => [ 'slug' => 'filter', 'with_front' => false, ], ... ]); ``` And then I can use `/food/sauce+cheese` like @jdm2112 and the docs specify.
385,209
<p>I am trying to let a user change their password via the API. What it looks like here is that I can send a POST request to the users endpoint with their user ID at the end, sending the new password in the request body as JSON. So,</p> <p>POST to : <code>https://example.com/wp-json/wp/v2/users/123</code></p> <p>And in the body:</p> <pre><code>{ &quot;password&quot;: &quot;mySecretPassword&quot; } </code></pre> <p>In this case, the user is authenticated via JWT and needs to send the token in the header of the request.</p> <p>When I tried this in postman, the request hangs for a really long time but finally seems to go through and the password is updated.</p> <p>I wanted to know if I am doing this correctly, and if so why does it take so long?</p>
[ { "answer_id": 385251, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 2, "selected": false, "text": "<p>Looks like you can define the <code>AND</code> logical operator with the URL parameters, specifically adding ...
2021/03/17
[ "https://wordpress.stackexchange.com/questions/385209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140276/" ]
I am trying to let a user change their password via the API. What it looks like here is that I can send a POST request to the users endpoint with their user ID at the end, sending the new password in the request body as JSON. So, POST to : `https://example.com/wp-json/wp/v2/users/123` And in the body: ``` { "password": "mySecretPassword" } ``` In this case, the user is authenticated via JWT and needs to send the token in the header of the request. When I tried this in postman, the request hangs for a really long time but finally seems to go through and the password is updated. I wanted to know if I am doing this correctly, and if so why does it take so long?
When I registered my taxonomy, I left out the argument for 'rewrite', which then defaulted to `true`. So by default, WordPress wanted to rewrite the url as `/food/whatever/`. The tricky thing was that it *did* accept the format `?food=whatever` , but wouldn't accept two different terms in that format when joined with a plus. The solution was to specify the rewrite arg of `register_taxonomy()` like so: ``` register_taxonomy( 'food', 'post', [ ... 'rewrite' => [ 'slug' => 'filter', 'with_front' => false, ], ... ]); ``` And then I can use `/food/sauce+cheese` like @jdm2112 and the docs specify.
385,245
<p>I am trying to redirect user roles to a specific page. If their role is <strong>contributor</strong> and is trying to access the <strong>Users Admin Page</strong> they should be redirected. Not sure if I am doing this correctly as it isn't working. Please help</p> <pre><code>function mwd_redirect_if_on_page() { $mwd_current_user = wp_get_current_user(); if ( user_can( $mwd_current_user, 'contributor') &amp;&amp; is_page('wp-admin/users.php') ) { return home_url('specific-page'); } } add_filter( 'login_redirect', 'mwd_redirect_if_on_page' ); </code></pre>
[ { "answer_id": 385251, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 2, "selected": false, "text": "<p>Looks like you can define the <code>AND</code> logical operator with the URL parameters, specifically adding ...
2021/03/17
[ "https://wordpress.stackexchange.com/questions/385245", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/96830/" ]
I am trying to redirect user roles to a specific page. If their role is **contributor** and is trying to access the **Users Admin Page** they should be redirected. Not sure if I am doing this correctly as it isn't working. Please help ``` function mwd_redirect_if_on_page() { $mwd_current_user = wp_get_current_user(); if ( user_can( $mwd_current_user, 'contributor') && is_page('wp-admin/users.php') ) { return home_url('specific-page'); } } add_filter( 'login_redirect', 'mwd_redirect_if_on_page' ); ```
When I registered my taxonomy, I left out the argument for 'rewrite', which then defaulted to `true`. So by default, WordPress wanted to rewrite the url as `/food/whatever/`. The tricky thing was that it *did* accept the format `?food=whatever` , but wouldn't accept two different terms in that format when joined with a plus. The solution was to specify the rewrite arg of `register_taxonomy()` like so: ``` register_taxonomy( 'food', 'post', [ ... 'rewrite' => [ 'slug' => 'filter', 'with_front' => false, ], ... ]); ``` And then I can use `/food/sauce+cheese` like @jdm2112 and the docs specify.
385,266
<p>Using WordPress PHP code, how to bulk delete ONLY 100 subscribers at a time from thousands of users?</p> <p>(The following code tries to delete all 50k users at once and my server hangs. If I can delete only 100 users at a time then I can use a Cron job every 5 minutes.)</p> <pre><code>&lt;?php $blogusers = get_users( ‘role=subscriber’ ); // Array of WP_User objects. foreach ( $blogusers as $user ) { $user_id = $user-&gt;ID; wp_delete_user( $user_id ); } </code></pre> <p>Thanks.</p>
[ { "answer_id": 385251, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 2, "selected": false, "text": "<p>Looks like you can define the <code>AND</code> logical operator with the URL parameters, specifically adding ...
2021/03/18
[ "https://wordpress.stackexchange.com/questions/385266", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203522/" ]
Using WordPress PHP code, how to bulk delete ONLY 100 subscribers at a time from thousands of users? (The following code tries to delete all 50k users at once and my server hangs. If I can delete only 100 users at a time then I can use a Cron job every 5 minutes.) ``` <?php $blogusers = get_users( ‘role=subscriber’ ); // Array of WP_User objects. foreach ( $blogusers as $user ) { $user_id = $user->ID; wp_delete_user( $user_id ); } ``` Thanks.
When I registered my taxonomy, I left out the argument for 'rewrite', which then defaulted to `true`. So by default, WordPress wanted to rewrite the url as `/food/whatever/`. The tricky thing was that it *did* accept the format `?food=whatever` , but wouldn't accept two different terms in that format when joined with a plus. The solution was to specify the rewrite arg of `register_taxonomy()` like so: ``` register_taxonomy( 'food', 'post', [ ... 'rewrite' => [ 'slug' => 'filter', 'with_front' => false, ], ... ]); ``` And then I can use `/food/sauce+cheese` like @jdm2112 and the docs specify.
385,303
<p>I want to create a button on the front end and when user click, the value &quot;user-meta&quot; change 'validate'</p> <pre><code>function func_change_validate() { if (is_user_logged_in()) { $current_user = wp_get_current_user(); $new_value = 'validate'; $updated = update_user_meta( $user_id, 'User_meta_change', $new_value ); return 'here i want create bootom to updated ?? &lt;button type=&quot;submit&quot;&gt;Validate&lt;/button&gt;'; } } add_shortcode('change_validate','func_change_validate'); </code></pre>
[ { "answer_id": 385306, "author": "Nour Edin Al-Habal", "author_id": 97257, "author_profile": "https://wordpress.stackexchange.com/users/97257", "pm_score": 3, "selected": true, "text": "<p>Basically, you can't show the button and update the meta at the same moment. This has to be done in...
2021/03/18
[ "https://wordpress.stackexchange.com/questions/385303", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192355/" ]
I want to create a button on the front end and when user click, the value "user-meta" change 'validate' ``` function func_change_validate() { if (is_user_logged_in()) { $current_user = wp_get_current_user(); $new_value = 'validate'; $updated = update_user_meta( $user_id, 'User_meta_change', $new_value ); return 'here i want create bootom to updated ?? <button type="submit">Validate</button>'; } } add_shortcode('change_validate','func_change_validate'); ```
Basically, you can't show the button and update the meta at the same moment. This has to be done in two separate requests as follows: 1. Show the button whereever you want. It needs to be a form that submits to the same page (or an ajax call to another URL, but let's keep it simple for now). 2. Read the value posted from the form. Here is a simple implementation to make this work, but it can be way improved. ``` function wpses_385303_change_validate() { if (is_user_logged_in()) { $user_id = get_current_user_id(); //If the form was posted (ie. the button was clicked) in a previous request if (isset($_POST['validate_user'])) { if ($_POST['validate_user'] == $user_id) {//A little bit of security if (update_user_meta( $user_id, 'User_meta_change', 'validated' )) { return "<div class='user_updated'>Updated!</div>"; } else { return "<div class='user_updated error'>Not Updated!</div>"; } } } //Show the form return "<form method='post'> <input type='hidden' name='validate_user' value='$user_id' /> <input type='submit' value='Validate' /> </form>"; } } add_shortcode('change_validate','wpses_385303_change_validate'); ```
385,333
<p>I'm looking for a way to prevent the automatic login after registration (i.e. by logging him out after registration) <strong>and</strong> redirect him to a custom URL. So far I'm only able to do both of them individually, but the combination of it is not working. For redirect after registration I'm using the following:</p> <pre><code> add_filter( 'woocommerce_registration_redirect', 'custom_redirection_after_registration', 10, 1 ); function custom_redirection_after_registration( $redirection_url ){ // Change the redirection Url $redirection_url = &quot;https://...&quot;; return $redirection_url; } </code></pre> <p>When including the wp_logout() function within the function above, I think that the redirect after logout is being triggered. If that assumption is correct, I unfortunately don't know how I can redirect only that logout that's being triggered directly after the registration.</p> <p>I hope that anyone can help me out? It's greatly appreciated! Best regards</p>
[ { "answer_id": 385365, "author": "Kirtan", "author_id": 203555, "author_profile": "https://wordpress.stackexchange.com/users/203555", "pm_score": 2, "selected": false, "text": "<p>Try this, It may helpful.</p>\n<pre><code>function wc_custom_registration_redirect() {\n wp_logout();\n ...
2021/03/18
[ "https://wordpress.stackexchange.com/questions/385333", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176724/" ]
I'm looking for a way to prevent the automatic login after registration (i.e. by logging him out after registration) **and** redirect him to a custom URL. So far I'm only able to do both of them individually, but the combination of it is not working. For redirect after registration I'm using the following: ``` add_filter( 'woocommerce_registration_redirect', 'custom_redirection_after_registration', 10, 1 ); function custom_redirection_after_registration( $redirection_url ){ // Change the redirection Url $redirection_url = "https://..."; return $redirection_url; } ``` When including the wp\_logout() function within the function above, I think that the redirect after logout is being triggered. If that assumption is correct, I unfortunately don't know how I can redirect only that logout that's being triggered directly after the registration. I hope that anyone can help me out? It's greatly appreciated! Best regards
Whoever has also the same question as I had: This is how I got it to work: ``` add_filter('woocommerce_registration_redirect', 'custom_redirection_after_registration', 1); function custom_redirection_after_registration( $redirection_url ){ // Change the redirection Url add_action('wp_logout','only_redirect_unverfied_users_after_registration',1); wp_logout(); wp_destroy_current_session(); $redirection_url = "https://..."; return $redirection_url; } function only_redirect_unverfied_users_after_registration(){ $redirection_url = "https://"; wp_redirect( $redirection_url); exit(); } ```
385,334
<p>I want to show a popup to the first time visitor of a Wordpress site. I tried to check the visit state using <code>$_SESSION</code>. Something like this in the <em>footer.php</em>:</p> <pre><code>&lt;?php if(!isset($_SESSION['pxpop'])) $_SESSION['pxpop']= true; if(($_SESSION['pxpop']) &amp;&amp; (!is_user_logged_in())) { ?&gt; &lt;div class=&quot;open_initpop&quot;&gt; &lt;?php if(is_active_sidebar('msg-pop')): ?&gt; &lt;?php dynamic_sidebar('msg-pop'); ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php $_SESSION['pxpop']= false; } ?&gt; </code></pre> <p>with <code>session_start();</code> in the <code>init</code> hook of the functions.php.</p> <p>But this is not working. <code>$_SESSION['pxpop']</code> remains <code>true</code> on each page load. So the popup opens on each page.</p> <p>With a little r&amp;d I have found that due to some 'statelessness' issue wordpress does not use sessions. From the site health section, it also says:</p> <blockquote> <p>&quot;PHP sessions created by a session_start() function call may interfere with REST API and loopback requests. An active session should be closed by session_write_close() before making any HTTP requests.&quot;</p> </blockquote> <p>Then I tried implementing <code>$_COOKIE</code> too (in the <code>init</code> hook) as:</p> <pre><code>&lt;?php function pop_event() { if(!isset($_COOKIE['pxpop'])) { setcookie('pxpop', true, 0); //$_COOKIE['pxpop']= true; } if(($_COOKIE['pxpop']) &amp;&amp; (!is_user_logged_in())) { ?&gt; &lt;div class=&quot;open_initpop&quot;&gt; &lt;?php if(is_active_sidebar('msg-pop')): ?&gt; &lt;?php dynamic_sidebar('msg-pop'); ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php //unset($_COOKIE['pxpop']); //$_COOKIE['pxpop']= false; setcookie('pxpop', false, 0); } } ?&gt; </code></pre> <p>But this is not working too...</p> <p>What is wrong with my approach? What is the correct way to carry forward a value in Wordpress like PHP session without actually using it? Or using $_SESSION is the only resort?</p>
[ { "answer_id": 385365, "author": "Kirtan", "author_id": 203555, "author_profile": "https://wordpress.stackexchange.com/users/203555", "pm_score": 2, "selected": false, "text": "<p>Try this, It may helpful.</p>\n<pre><code>function wc_custom_registration_redirect() {\n wp_logout();\n ...
2021/03/18
[ "https://wordpress.stackexchange.com/questions/385334", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92425/" ]
I want to show a popup to the first time visitor of a Wordpress site. I tried to check the visit state using `$_SESSION`. Something like this in the *footer.php*: ``` <?php if(!isset($_SESSION['pxpop'])) $_SESSION['pxpop']= true; if(($_SESSION['pxpop']) && (!is_user_logged_in())) { ?> <div class="open_initpop"> <?php if(is_active_sidebar('msg-pop')): ?> <?php dynamic_sidebar('msg-pop'); ?> <?php endif; ?> </div> <?php $_SESSION['pxpop']= false; } ?> ``` with `session_start();` in the `init` hook of the functions.php. But this is not working. `$_SESSION['pxpop']` remains `true` on each page load. So the popup opens on each page. With a little r&d I have found that due to some 'statelessness' issue wordpress does not use sessions. From the site health section, it also says: > > "PHP sessions created by a session\_start() function call may interfere > with REST API and loopback requests. An active session should be > closed by session\_write\_close() before making any HTTP requests." > > > Then I tried implementing `$_COOKIE` too (in the `init` hook) as: ``` <?php function pop_event() { if(!isset($_COOKIE['pxpop'])) { setcookie('pxpop', true, 0); //$_COOKIE['pxpop']= true; } if(($_COOKIE['pxpop']) && (!is_user_logged_in())) { ?> <div class="open_initpop"> <?php if(is_active_sidebar('msg-pop')): ?> <?php dynamic_sidebar('msg-pop'); ?> <?php endif; ?> </div> <?php //unset($_COOKIE['pxpop']); //$_COOKIE['pxpop']= false; setcookie('pxpop', false, 0); } } ?> ``` But this is not working too... What is wrong with my approach? What is the correct way to carry forward a value in Wordpress like PHP session without actually using it? Or using $\_SESSION is the only resort?
Whoever has also the same question as I had: This is how I got it to work: ``` add_filter('woocommerce_registration_redirect', 'custom_redirection_after_registration', 1); function custom_redirection_after_registration( $redirection_url ){ // Change the redirection Url add_action('wp_logout','only_redirect_unverfied_users_after_registration',1); wp_logout(); wp_destroy_current_session(); $redirection_url = "https://..."; return $redirection_url; } function only_redirect_unverfied_users_after_registration(){ $redirection_url = "https://"; wp_redirect( $redirection_url); exit(); } ```
385,377
<p>Here's the situation:</p> <p>I've created a child theme that enhances a popular parent theme. The enhancements include CSS, JS, and php. I want to use this child theme on multiple sites, and I want to allow for additional customization on each site without editing the child theme I created.</p> <p>A few requirements:</p> <ul> <li>Each site uses the same base theme and a standard set of customizations (my child theme), but each site can have its own additional customizations (CSS, JS, and php).</li> <li>I don't want to create my own base theme because I want to avoid that level of maintenance (security updates, compatibility, etc).</li> <li>I'd like to avoid customizing the child theme for each site. That way I can continue to develop my child theme and easily deploy updates without overwriting site-specific customizations.</li> </ul> <p>My current solution is to create a directory outside the child theme that includes the CSS, JS, and php files for customizations, and then reference those in the child theme. But this is <a href="https://wordpress.stackexchange.com/questions/385255/is-it-unsafe-to-put-php-in-the-wp-content-uploads-directory">non-standard at best and possibly a security risk</a>.</p> <p>So what would be the best approach for this situation?</p> <p><strong>Edit:</strong> I don't now ahead of time what customizations are needed. So the system needs to be very flexible and open-ended.</p>
[ { "answer_id": 385379, "author": "vancoder", "author_id": 26778, "author_profile": "https://wordpress.stackexchange.com/users/26778", "pm_score": 2, "selected": false, "text": "<p>Firstly, I would ensure that your child theme is well equipped with hooks to accommodate the potential custo...
2021/03/19
[ "https://wordpress.stackexchange.com/questions/385377", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203510/" ]
Here's the situation: I've created a child theme that enhances a popular parent theme. The enhancements include CSS, JS, and php. I want to use this child theme on multiple sites, and I want to allow for additional customization on each site without editing the child theme I created. A few requirements: * Each site uses the same base theme and a standard set of customizations (my child theme), but each site can have its own additional customizations (CSS, JS, and php). * I don't want to create my own base theme because I want to avoid that level of maintenance (security updates, compatibility, etc). * I'd like to avoid customizing the child theme for each site. That way I can continue to develop my child theme and easily deploy updates without overwriting site-specific customizations. My current solution is to create a directory outside the child theme that includes the CSS, JS, and php files for customizations, and then reference those in the child theme. But this is [non-standard at best and possibly a security risk](https://wordpress.stackexchange.com/questions/385255/is-it-unsafe-to-put-php-in-the-wp-content-uploads-directory). So what would be the best approach for this situation? **Edit:** I don't now ahead of time what customizations are needed. So the system needs to be very flexible and open-ended.
> > My current solution is to create a directory outside the child theme that includes the CSS, JS, and php files for customizations > > > This is a plugin, a folder containing PHP/JS/CSS, with a comment at the top of one of the PHP files that has `/** Plugin Name: XYZ` at the top of the file. ```php <?php /** * Plugin Name: XYZ */ ``` > > and then reference those in the child theme. > > > **This isn't needed**. You can provide a hook/action/filter or use the existing hooks and filters WP provides. Including files directly from outside of the themes folder is bad practice and should never be necessary. In the long run it causes maintenance problems. > > Edit: I don't now ahead of time what customizations are needed. So the system needs to be very flexible and open-ended. > > > If you don't know then you can't know what to do, but that's okay. At some point you will need to update the child theme, and adding hooks is always good. The parent theme might do this too. Otherwise it's an unreasonable requirement, you can't know what you don't know. ### Custom JS and CSS If you want to add extra javascript files and stylesheets to a theme without modifying the theme, you can do that in a plugin. Just enqueue the styles and scripts as you normally would. WordPress doesn't see any difference between a style enqueued by a parent theme or a plugin, or itself. It's all just code that has been loaded into memmory. There is no such thing as a *plugin script*, or *theme style*, and no sandboxing, so nothing prevents you adding extra styles and scripts this way. Perhaps if you wanted to add inline code tags I could understand, but there are APIs for this, e.g. `wp_add_inline_script`. If you really had to add it directly, there's hooks such as `wp_head` of `wp_footer` etc to do it on. Custom PHP ---------- A plugin is by definition custom PHP. You can execute any custom PHP using a plugin. If you wanted to replace a template with a new template from your plugin, you can do that too with the right filter. WooCommerce does it, lots of plugins do it, overiding specific templates or adding subfolders. --- So use a plugin!
385,447
<p><code>get_queried_object</code> returns <code>NULL</code> inside a function hooked to <code>wp_enqueue_scripts</code> action hook when going to an nonexistent category URL on my website. If the category exists, the error is not shown and I think it does not exist.</p> <p>I need it to conditionally load a CSS file for better modularization, not in the admin area but for the end-user.</p> <p>What is the correct way to do this?</p> <p>The error shown in the HTML:</p> <blockquote> <p>Notice: Trying to get property 'term_id' of non-object in /var/www/html/wp-content/themes/custom-theme/functions.php on line 193</p> </blockquote> <p>The code starting at line 193:</p> <pre class="lang-php prettyprint-override"><code>if (get_queried_object()-&gt;term_id === 3 || (count(get_the_category()) &gt; 0 &amp;&amp; get_the_category()[0]-&gt;slug == 'arta')) { wp_enqueue_style( 'twentytwenty-style-2', get_stylesheet_directory_uri() . '/style-arta.css', array(), $theme_version ); } </code></pre>
[ { "answer_id": 385449, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 1, "selected": false, "text": "<p>According to the documentation, <code>get_queried_object()</code> is a wrapper for <a href=\"https://developer....
2021/03/21
[ "https://wordpress.stackexchange.com/questions/385447", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182585/" ]
`get_queried_object` returns `NULL` inside a function hooked to `wp_enqueue_scripts` action hook when going to an nonexistent category URL on my website. If the category exists, the error is not shown and I think it does not exist. I need it to conditionally load a CSS file for better modularization, not in the admin area but for the end-user. What is the correct way to do this? The error shown in the HTML: > > Notice: Trying to get property 'term\_id' of non-object in /var/www/html/wp-content/themes/custom-theme/functions.php on line 193 > > > The code starting at line 193: ```php if (get_queried_object()->term_id === 3 || (count(get_the_category()) > 0 && get_the_category()[0]->slug == 'arta')) { wp_enqueue_style( 'twentytwenty-style-2', get_stylesheet_directory_uri() . '/style-arta.css', array(), $theme_version ); } ```
I agreed with [@PatJ](https://wordpress.stackexchange.com/users/16121/pat-j) — you should check if [`get_queried_object()`](https://developer.wordpress.org/reference/functions/get_queried_object/) returns an object or not. But you could *simplify* your code by simply using [`is_category()`](https://developer.wordpress.org/reference/functions/is_category/) and [`in_category()`](https://developer.wordpress.org/reference/functions/in_category/) which are [conditional tags](https://developer.wordpress.org/themes/basics/conditional-tags/#a-category-page) in WordPress: ```php if ( is_category( 3 ) || in_category( 'arta' ) ) { wp_enqueue_style( 'twentytwenty-style-2', get_stylesheet_directory_uri() . '/style-arta.css', array(), $theme_version ); } ```
385,458
<p>I'm trying to register a GET REST API route with multiple parameters with the following code:</p> <pre><code>register_rest_route( 'myplugin/v1', '/posts/?number=(?P&lt;number&gt;[\d]+)&amp;amp;offset=(?P&lt;offset&gt;[\d]+)&amp;amp;total=(?P&lt;total&gt;[\d]+)', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'my_rest_function', 'permission_callback' =&gt; '__return_true', 'args' =&gt; array( 'number' =&gt; array( 'validate_callback' =&gt; function( $param, $request, $key ) { return is_numeric( $param ); } ), 'offset' =&gt; array( 'validate_callback' =&gt; function( $param, $request, $key ) { return is_numeric( $param ); } ), 'total' =&gt; array( 'validate_callback' =&gt; function( $param, $request, $key ) { return is_numeric( $param ); } ), ), ) ); </code></pre> <p>But, when I call it using for example:</p> <p><a href="https://example.com/wp-json/myplugin/v1/posts/?number=3&amp;offset=0&amp;total=3" rel="nofollow noreferrer">https://example.com/wp-json/myplugin/v1/posts/?number=3&amp;offset=0&amp;total=3</a></p> <p>I'm getting a <code>No route was found matching the URL and request method.</code> error.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 385459, "author": "rexkogitans", "author_id": 196282, "author_profile": "https://wordpress.stackexchange.com/users/196282", "pm_score": 0, "selected": false, "text": "<p>The request should be a regular expression, but not HTML encoded. So, instead of <code>&amp;amp;</code...
2021/03/21
[ "https://wordpress.stackexchange.com/questions/385458", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33049/" ]
I'm trying to register a GET REST API route with multiple parameters with the following code: ``` register_rest_route( 'myplugin/v1', '/posts/?number=(?P<number>[\d]+)&amp;offset=(?P<offset>[\d]+)&amp;total=(?P<total>[\d]+)', array( 'methods' => 'GET', 'callback' => 'my_rest_function', 'permission_callback' => '__return_true', 'args' => array( 'number' => array( 'validate_callback' => function( $param, $request, $key ) { return is_numeric( $param ); } ), 'offset' => array( 'validate_callback' => function( $param, $request, $key ) { return is_numeric( $param ); } ), 'total' => array( 'validate_callback' => function( $param, $request, $key ) { return is_numeric( $param ); } ), ), ) ); ``` But, when I call it using for example: <https://example.com/wp-json/myplugin/v1/posts/?number=3&offset=0&total=3> I'm getting a `No route was found matching the URL and request method.` error. What am I doing wrong?
You don't need to include query parameters in the endpoint. Just the path: ``` register_rest_route( 'myplugin/v1', '/posts', array( 'methods' => 'GET', 'callback' => 'my_rest_function', 'permission_callback' => '__return_true', 'args' => array( 'number' => array( 'validate_callback' => function( $param, $request, $key ) { return is_numeric( $param ); } ), 'offset' => array( 'validate_callback' => function( $param, $request, $key ) { return is_numeric( $param ); } ), 'total' => array( 'validate_callback' => function( $param, $request, $key ) { return is_numeric( $param ); } ), ), ) ); ```
385,490
<p>I have a line of code in my template I would like to add the css class &quot;has-video&quot; to if the post is within a certain category.</p> <p>I am trying to do this inline with <code>' . ( if (in_category(42)) echo 'has-video') ? '</code> but I get a syntax error, unexpected 'if' (T_IF)</p> <p>I'm not great with my PHP and know this is close but not great :/</p> <p>Here is the whole echo code:</p> <pre><code>echo '&lt;section id=&quot;cooked-recipe-list-' . $list_id_counter . '&quot; class=&quot;cooked-clearfix cooked-recipe-' . $list_style . ' cooked-recipe-loader' . ( in_array( $list_style, $masonry_layouts ) ? ' cooked-masonry' : '' ) . ( isset($atts['columns']) &amp;&amp; $atts['columns'] ? ' cooked-columns-' . $atts['columns'] : '' ) . ' ' . ( if (in_category(42)) echo 'has-video') ? '&quot;&gt;'; </code></pre>
[ { "answer_id": 385495, "author": "Kirtan", "author_id": 203555, "author_profile": "https://wordpress.stackexchange.com/users/203555", "pm_score": 1, "selected": false, "text": "<p>It may helpful to you...</p>\n<pre><code>$video = (in_category ( 42 )) ? 'has-video' : '';\n\necho '&lt;sect...
2021/03/22
[ "https://wordpress.stackexchange.com/questions/385490", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196309/" ]
I have a line of code in my template I would like to add the css class "has-video" to if the post is within a certain category. I am trying to do this inline with `' . ( if (in_category(42)) echo 'has-video') ? '` but I get a syntax error, unexpected 'if' (T\_IF) I'm not great with my PHP and know this is close but not great :/ Here is the whole echo code: ``` echo '<section id="cooked-recipe-list-' . $list_id_counter . '" class="cooked-clearfix cooked-recipe-' . $list_style . ' cooked-recipe-loader' . ( in_array( $list_style, $masonry_layouts ) ? ' cooked-masonry' : '' ) . ( isset($atts['columns']) && $atts['columns'] ? ' cooked-columns-' . $atts['columns'] : '' ) . ' ' . ( if (in_category(42)) echo 'has-video') ? '">'; ```
It may helpful to you... ``` $video = (in_category ( 42 )) ? 'has-video' : ''; echo '<section id="cooked-recipe-list-' . $list_id_counter . '" class="cooked-clearfix cooked-recipe-' . $list_style . ' cooked-recipe-loader' . ( in_array( $list_style, $masonry_layouts ) ? ' cooked-masonry' : '' ) . ( isset($atts['columns']) && $atts['columns'] ? ' cooked-columns-' . $atts['columns'] : '' ) . ' ' . $video. '">'; ``` Try this and let me know..
385,544
<p>I am currently developing my first WordPress plugin and am currently a bit confused on how to change a record in a database.</p> <p>So far I have solved it using the $wpdb::update() function:</p> <pre><code>public function toggle_status() { global $wpdb; $id = (int) $_POST[&quot;id&quot;]; $active = (int) $_POST[&quot;active&quot;]; $tablename = $wpdb-&gt;prefix . 'myplugin_table'; $wpdb-&gt;update($tablename, array(&quot;active&quot; =&gt; $active), array(&quot;id&quot; =&gt; $id)); // Update record } </code></pre> <p>Now I have learned that the way I change the database is not safe regarding SQL injection. I should rather use the $wpml::prepare() function:</p> <pre><code>$wpdb-&gt;query($wpdb-&gt;prepare(&quot;UPDATE $tablename SET active = '%s' WHERE id = '%d'&quot;, array($active, $id))); </code></pre> <p>Is the $wpdb::update() function really not safe?</p> <p>According to the documentation, this is not necessary for the $wpdb functions: &quot;$data should be unescaped (the function will escape them for you). Keys are columns, Values are values.&quot; (<a href="https://codex.wordpress.org/Data_Validation#Database" rel="nofollow noreferrer">https://codex.wordpress.org/Data_Validation#Database</a>).</p>
[ { "answer_id": 385495, "author": "Kirtan", "author_id": 203555, "author_profile": "https://wordpress.stackexchange.com/users/203555", "pm_score": 1, "selected": false, "text": "<p>It may helpful to you...</p>\n<pre><code>$video = (in_category ( 42 )) ? 'has-video' : '';\n\necho '&lt;sect...
2021/03/23
[ "https://wordpress.stackexchange.com/questions/385544", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103972/" ]
I am currently developing my first WordPress plugin and am currently a bit confused on how to change a record in a database. So far I have solved it using the $wpdb::update() function: ``` public function toggle_status() { global $wpdb; $id = (int) $_POST["id"]; $active = (int) $_POST["active"]; $tablename = $wpdb->prefix . 'myplugin_table'; $wpdb->update($tablename, array("active" => $active), array("id" => $id)); // Update record } ``` Now I have learned that the way I change the database is not safe regarding SQL injection. I should rather use the $wpml::prepare() function: ``` $wpdb->query($wpdb->prepare("UPDATE $tablename SET active = '%s' WHERE id = '%d'", array($active, $id))); ``` Is the $wpdb::update() function really not safe? According to the documentation, this is not necessary for the $wpdb functions: "$data should be unescaped (the function will escape them for you). Keys are columns, Values are values." (<https://codex.wordpress.org/Data_Validation#Database>).
It may helpful to you... ``` $video = (in_category ( 42 )) ? 'has-video' : ''; echo '<section id="cooked-recipe-list-' . $list_id_counter . '" class="cooked-clearfix cooked-recipe-' . $list_style . ' cooked-recipe-loader' . ( in_array( $list_style, $masonry_layouts ) ? ' cooked-masonry' : '' ) . ( isset($atts['columns']) && $atts['columns'] ? ' cooked-columns-' . $atts['columns'] : '' ) . ' ' . $video. '">'; ``` Try this and let me know..
385,617
<p>I'm using the <code>rest_photo_query</code> filter to manipulate the arguments of <code>WP_Query</code> through the use of my own <code>GET</code> parameters. It's working perfectly and fast, with one exception.</p> <p>I can adjust the <code>orderby</code> parameter using <code>rest_sht_photo_collection_params</code>, and it's easy to sort the results by <code>meta_value</code>.</p> <p>The <strong>photo</strong> Custom Post Type entries are connected to a second Custom Post Type <strong>species</strong> by means of the <code>species_id</code>.</p> <p>I need to be able to sort the <strong>photo</strong> posts by <strong>species</strong> title.</p> <p>Does anyone have a good idea how to achieve this? As I'm modifying the <code>WP_Query</code> in a standard endpoint, my preference would be to modify the <code>WP_Query</code> arguments somehow.</p> <p>I've tried building my own query in a custom endpoint and then modifying the resultant array by looping through it, but this makes the request about 100x slower.</p> <p>Here's a partial example of a simpler field, where the custom orderby <code>my_custom_meta_field</code> is added as a <code>meta_value</code> comparison:</p> <pre><code>switch ($args['orderby']) { case 'my_custom_meta_field': $args['orderby'] = 'meta_value'; $args['meta_key'] = 'my_custom_meta_field'; break; </code></pre>
[ { "answer_id": 385495, "author": "Kirtan", "author_id": 203555, "author_profile": "https://wordpress.stackexchange.com/users/203555", "pm_score": 1, "selected": false, "text": "<p>It may helpful to you...</p>\n<pre><code>$video = (in_category ( 42 )) ? 'has-video' : '';\n\necho '&lt;sect...
2021/03/24
[ "https://wordpress.stackexchange.com/questions/385617", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83412/" ]
I'm using the `rest_photo_query` filter to manipulate the arguments of `WP_Query` through the use of my own `GET` parameters. It's working perfectly and fast, with one exception. I can adjust the `orderby` parameter using `rest_sht_photo_collection_params`, and it's easy to sort the results by `meta_value`. The **photo** Custom Post Type entries are connected to a second Custom Post Type **species** by means of the `species_id`. I need to be able to sort the **photo** posts by **species** title. Does anyone have a good idea how to achieve this? As I'm modifying the `WP_Query` in a standard endpoint, my preference would be to modify the `WP_Query` arguments somehow. I've tried building my own query in a custom endpoint and then modifying the resultant array by looping through it, but this makes the request about 100x slower. Here's a partial example of a simpler field, where the custom orderby `my_custom_meta_field` is added as a `meta_value` comparison: ``` switch ($args['orderby']) { case 'my_custom_meta_field': $args['orderby'] = 'meta_value'; $args['meta_key'] = 'my_custom_meta_field'; break; ```
It may helpful to you... ``` $video = (in_category ( 42 )) ? 'has-video' : ''; echo '<section id="cooked-recipe-list-' . $list_id_counter . '" class="cooked-clearfix cooked-recipe-' . $list_style . ' cooked-recipe-loader' . ( in_array( $list_style, $masonry_layouts ) ? ' cooked-masonry' : '' ) . ( isset($atts['columns']) && $atts['columns'] ? ' cooked-columns-' . $atts['columns'] : '' ) . ' ' . $video. '">'; ``` Try this and let me know..
385,643
<p>So sorry if this have been answered - but in that case, I surely do not know what to ask.</p> <p>Anyway, I have built an image slider which changes the image and the description of the image on click of a button. Point be, I dynamically change the source of the img tag using javascript. But the images do not actually appear on the page.</p> <p>The code holding the images is a simple array and I just iterate over each one Ie: <code>&quot;images/work1.png&quot;</code>, which works offline, but not via php and or wordpress.</p> <p>This did not work, so I tried putting it in the php function instead: The javascript looks like:</p> <pre><code>let imgArray = [ &quot;&lt;?php echo get_theme_file_uri('images/work1.png') ?&gt;&quot;, &quot;&lt;?php echo get_theme_file_uri('images/work2.png') ?&gt;&quot;, ... etc ]; </code></pre> <p>So the html looks like : <code>&lt;img src=&quot;&lt;?php echo get_theme_file_uri('images/work1') ?&gt;&quot;&gt;</code></p> <p>The src tag's content is what changes but it does not take effect.</p> <p>Any knowledge on why neither of those will actually work? The code works because the associated text for each image still changes via click of the button. Just, the image refuses to display.</p> <p>functions.php looks like this:</p> <pre class="lang-php prettyprint-override"><code>function lcc_style_files() { wp_enqueue_style('lcc_main_styles', get_stylesheet_uri()); } function lcc_script_files() { wp_enqueue_script('main-lcc-js', get_theme_file_uri('/js/scripts-bundled.js'), NULL, '1.0', true); } add_action('wp_enqueue_scripts', 'lcc_style_files'); add_action('wp_enqueue_scripts', 'lcc_script_files'); function lcc_features() { add_theme_support('title-tag'); } add_action('after_setup_theme', 'lcc_features'); </code></pre>
[ { "answer_id": 385668, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>The problem is that you are trying to use PHP inside a javascript file. <strong>PHP only works inside <code>...
2021/03/24
[ "https://wordpress.stackexchange.com/questions/385643", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203890/" ]
So sorry if this have been answered - but in that case, I surely do not know what to ask. Anyway, I have built an image slider which changes the image and the description of the image on click of a button. Point be, I dynamically change the source of the img tag using javascript. But the images do not actually appear on the page. The code holding the images is a simple array and I just iterate over each one Ie: `"images/work1.png"`, which works offline, but not via php and or wordpress. This did not work, so I tried putting it in the php function instead: The javascript looks like: ``` let imgArray = [ "<?php echo get_theme_file_uri('images/work1.png') ?>", "<?php echo get_theme_file_uri('images/work2.png') ?>", ... etc ]; ``` So the html looks like : `<img src="<?php echo get_theme_file_uri('images/work1') ?>">` The src tag's content is what changes but it does not take effect. Any knowledge on why neither of those will actually work? The code works because the associated text for each image still changes via click of the button. Just, the image refuses to display. functions.php looks like this: ```php function lcc_style_files() { wp_enqueue_style('lcc_main_styles', get_stylesheet_uri()); } function lcc_script_files() { wp_enqueue_script('main-lcc-js', get_theme_file_uri('/js/scripts-bundled.js'), NULL, '1.0', true); } add_action('wp_enqueue_scripts', 'lcc_style_files'); add_action('wp_enqueue_scripts', 'lcc_script_files'); function lcc_features() { add_theme_support('title-tag'); } add_action('after_setup_theme', 'lcc_features'); ```
The problem is that you are trying to use PHP inside a javascript file. **PHP only works inside `.php` files.** If you want to pass information to your javascript file from PHP, use `wp_localize_script` to store it in a variable, e.g. in a PHP file: ```php $values = array( 'foo' => 'bar', ); wp_localize_script( 'yourscripthandle', 'objectname', $values ); ``` Now whenever the `yourscripthandle` script is enqueued, it will put those values at `window.objectname`. You can accesss them like this in javascript: ```js const values = window.objectname; console.log( values.foo ); // prints 'bar' ``` <https://developer.wordpress.org/reference/functions/wp_localize_script/>
385,646
<p>I'm using the following code to add a panel to the admin menu screen, so the users are able to add a Cart link to their menus:</p> <pre><code>function my_add_meta_box() { add_meta_box( 'custom-meta-box', __( 'Cart' ), 'my_nav_menu_item_link_meta_box', 'nav-menus', 'side', 'default' ); } add_action( 'admin_init', 'my_add_meta_box' ); function my_nav_menu_item_link_meta_box() { global $_nav_menu_placeholder, $nav_menu_selected_id; $_nav_menu_placeholder = 0 &gt; $_nav_menu_placeholder ? $_nav_menu_placeholder - 1 : -1; ?&gt; &lt;div id=&quot;posttype-cart&quot; class=&quot;posttypediv&quot;&gt; &lt;div id=&quot;tabs-panel-cart&quot; class=&quot;tabs-panel tabs-panel-active&quot;&gt; &lt;ul id=&quot;cart-checklist&quot; class=&quot;categorychecklist form-no-clear&quot;&gt; &lt;li&gt; &lt;label class=&quot;menu-item-title&quot;&gt; &lt;input type=&quot;checkbox&quot; class=&quot;menu-item-checkbox&quot; name=&quot;menu-item[&lt;?php echo (int) $_nav_menu_placeholder; ?&gt;][menu-item-object-id]&quot; value=&quot;-1&quot;&gt; &lt;?php esc_html_e( 'Cart' ); ?&gt; &lt;/label&gt; &lt;input type=&quot;hidden&quot; class=&quot;menu-item-type&quot; name=&quot;menu-item[&lt;?php echo (int) $_nav_menu_placeholder; ?&gt;][menu-item-type]&quot; value=&quot;post_type&quot;&gt; &lt;input type=&quot;hidden&quot; class=&quot;menu-item-object&quot; name=&quot;menu-item[&lt;?php echo (int) $_nav_menu_placeholder; ?&gt;][menu-item-object]&quot; value=&quot;page&quot;&gt; &lt;input type=&quot;hidden&quot; class=&quot;menu-item-object-id&quot; name=&quot;menu-item[&lt;?php echo (int) $_nav_menu_placeholder; ?&gt;][menu-item-object-id]&quot; value=&quot;&lt;?php echo get_option( 'woocommerce_cart_page_id' ); ?&gt;&quot;&gt; &lt;input type=&quot;hidden&quot; class=&quot;menu-item-title&quot; name=&quot;menu-item[&lt;?php echo (int) $_nav_menu_placeholder; ?&gt;][menu-item-title]&quot; value=&quot;&lt;?php esc_html_e( 'Cart' ); ?&gt;&quot;&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;p class=&quot;button-controls&quot;&gt; &lt;span class=&quot;add-to-menu&quot;&gt; &lt;input type=&quot;submit&quot; &lt;?php disabled( $nav_menu_selected_id, 0 ); ?&gt; class=&quot;button-secondary submit-add-to-menu right&quot; value=&quot;&lt;?php esc_attr_e( 'Add to Menu' ); ?&gt;&quot; name=&quot;add-post-type-menu-item&quot; id=&quot;submit-posttype-cart&quot;&gt; &lt;span class=&quot;spinner&quot;&gt;&lt;/span&gt; &lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;?php } </code></pre> <p>My question is, is it possible to dynamically add a counter that shows the number of items in cart beside the Cart menu item label in the frontend? If so, how? I think that the <code>wp_get_nav_menu_items</code> filter might be useful for this, but how can I identify the Cart menu item in there to be able to modify its label in the frontend on the fly?</p> <pre><code>function my_get_nav_menu_items( $items ) { foreach ( $items as $item ) { if ( is_cart_menu_item( $item ) ) { // add a counter beside the Cart menu item label } } return $items; } add_filter( 'wp_get_nav_menu_items', 'my_get_nav_menu_items', 20 ); </code></pre>
[ { "answer_id": 385655, "author": "Bhautik", "author_id": 127648, "author_profile": "https://wordpress.stackexchange.com/users/127648", "pm_score": 1, "selected": false, "text": "<p>You can <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu_objects/\" rel=\"nofollow nor...
2021/03/24
[ "https://wordpress.stackexchange.com/questions/385646", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33049/" ]
I'm using the following code to add a panel to the admin menu screen, so the users are able to add a Cart link to their menus: ``` function my_add_meta_box() { add_meta_box( 'custom-meta-box', __( 'Cart' ), 'my_nav_menu_item_link_meta_box', 'nav-menus', 'side', 'default' ); } add_action( 'admin_init', 'my_add_meta_box' ); function my_nav_menu_item_link_meta_box() { global $_nav_menu_placeholder, $nav_menu_selected_id; $_nav_menu_placeholder = 0 > $_nav_menu_placeholder ? $_nav_menu_placeholder - 1 : -1; ?> <div id="posttype-cart" class="posttypediv"> <div id="tabs-panel-cart" class="tabs-panel tabs-panel-active"> <ul id="cart-checklist" class="categorychecklist form-no-clear"> <li> <label class="menu-item-title"> <input type="checkbox" class="menu-item-checkbox" name="menu-item[<?php echo (int) $_nav_menu_placeholder; ?>][menu-item-object-id]" value="-1"> <?php esc_html_e( 'Cart' ); ?> </label> <input type="hidden" class="menu-item-type" name="menu-item[<?php echo (int) $_nav_menu_placeholder; ?>][menu-item-type]" value="post_type"> <input type="hidden" class="menu-item-object" name="menu-item[<?php echo (int) $_nav_menu_placeholder; ?>][menu-item-object]" value="page"> <input type="hidden" class="menu-item-object-id" name="menu-item[<?php echo (int) $_nav_menu_placeholder; ?>][menu-item-object-id]" value="<?php echo get_option( 'woocommerce_cart_page_id' ); ?>"> <input type="hidden" class="menu-item-title" name="menu-item[<?php echo (int) $_nav_menu_placeholder; ?>][menu-item-title]" value="<?php esc_html_e( 'Cart' ); ?>"> </li> </ul> </div> <p class="button-controls"> <span class="add-to-menu"> <input type="submit" <?php disabled( $nav_menu_selected_id, 0 ); ?> class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu' ); ?>" name="add-post-type-menu-item" id="submit-posttype-cart"> <span class="spinner"></span> </span> </p> </div> <?php } ``` My question is, is it possible to dynamically add a counter that shows the number of items in cart beside the Cart menu item label in the frontend? If so, how? I think that the `wp_get_nav_menu_items` filter might be useful for this, but how can I identify the Cart menu item in there to be able to modify its label in the frontend on the fly? ``` function my_get_nav_menu_items( $items ) { foreach ( $items as $item ) { if ( is_cart_menu_item( $item ) ) { // add a counter beside the Cart menu item label } } return $items; } add_filter( 'wp_get_nav_menu_items', 'my_get_nav_menu_items', 20 ); ```
Based on Bhautik answer, I've found a solution to identify the cart menu link using the `woocommerce_cart_page_id` option: ``` function modify_cart_label_in_nav_menu_objects( $items, $args ) { foreach ( $items as $key => $item ) { if ( $item->object_id == (int) get_option( 'woocommerce_cart_page_id' ) ) { if ( WC()->cart->get_cart_contents_count() > 0 ) { $item->title .= ' ('. WC()->cart->get_cart_contents_count() . ')'; } } } return $items; } add_filter( 'wp_nav_menu_objects', 'modify_cart_label_in_nav_menu_objects', 10, 2 ); ```
385,666
<p>I've been tasked with managing a WordPress site that was developed and configured by some other team. During a basic security scan, I've realized that the following end-point <code>https://www.mywordpress.com/wp-json</code> does not restrict the Origin for some reason.</p> <pre><code>curl -H &quot;Origin: https://www.thewrongorigin.com&quot; -I https://www.mywordpress.com/wp-json HTTP/2 200 server: nginx date: Mon, 22 Mar 2021 11:02:54 GMT content-type: application/json; charset=UTF-8 vary: Accept-Encoding access-control-expose-headers: X-WP-Total, X-WP-TotalPages, Link access-control-allow-headers: Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type allow: GET access-control-allow-origin: https://www.thewrongorigin.com access-control-allow-methods: OPTIONS, GET, POST, PUT, PATCH, DELETE access-control-allow-credentials: true … other headers here… </code></pre> <p>Looking at the response, and using different URLs as origin, it looks like that my WordPress installation is setting the header <code>access-control-allow-origin</code> to whatever the origin of the request is. I was expecting a response with the following header:</p> <pre><code>curl -H &quot;Origin: https://www.thewrongorigin.com&quot; -I https://www.mywordpress.com/wp-json HTTP/2 200 ... access-control-allow-origin: https://www.mywordpress.com </code></pre> <p>What I want to do is modify my WordPress and set the header <code>Access-Control-Allow-Origin: https://www.mywordpress.com</code> for the URL <code>https://www.mywordpress.com/wp-json</code>.</p> <p>My questions are:</p> <ul> <li>Is it okay to set restrict the origin in this way?</li> <li>What might be the consequences of doing it? Maybe plugins that rely on a header like <code>access-control-allow-origin: *</code> could stop working? Are there such plugins?</li> </ul> <p>I've experience coding and working as a system administrator, but I'm fairly new to WordPress.</p>
[ { "answer_id": 385687, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>First of all, this is intentional behaviour, as relayed in a Slack discussion described in <a href=\"htt...
2021/03/25
[ "https://wordpress.stackexchange.com/questions/385666", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24635/" ]
I've been tasked with managing a WordPress site that was developed and configured by some other team. During a basic security scan, I've realized that the following end-point `https://www.mywordpress.com/wp-json` does not restrict the Origin for some reason. ``` curl -H "Origin: https://www.thewrongorigin.com" -I https://www.mywordpress.com/wp-json HTTP/2 200 server: nginx date: Mon, 22 Mar 2021 11:02:54 GMT content-type: application/json; charset=UTF-8 vary: Accept-Encoding access-control-expose-headers: X-WP-Total, X-WP-TotalPages, Link access-control-allow-headers: Authorization, X-WP-Nonce, Content-Disposition, Content-MD5, Content-Type allow: GET access-control-allow-origin: https://www.thewrongorigin.com access-control-allow-methods: OPTIONS, GET, POST, PUT, PATCH, DELETE access-control-allow-credentials: true … other headers here… ``` Looking at the response, and using different URLs as origin, it looks like that my WordPress installation is setting the header `access-control-allow-origin` to whatever the origin of the request is. I was expecting a response with the following header: ``` curl -H "Origin: https://www.thewrongorigin.com" -I https://www.mywordpress.com/wp-json HTTP/2 200 ... access-control-allow-origin: https://www.mywordpress.com ``` What I want to do is modify my WordPress and set the header `Access-Control-Allow-Origin: https://www.mywordpress.com` for the URL `https://www.mywordpress.com/wp-json`. My questions are: * Is it okay to set restrict the origin in this way? * What might be the consequences of doing it? Maybe plugins that rely on a header like `access-control-allow-origin: *` could stop working? Are there such plugins? I've experience coding and working as a system administrator, but I'm fairly new to WordPress.
First of all, this is intentional behaviour, as relayed in a Slack discussion described in [this ticket](https://core.trac.wordpress.org/ticket/45477) (this has likely been discussed in other places, but that's the first I found): > > tl;dr: CORS is built for CSRF protection, but WordPress already has a > system for that (nonces), so we "disable" CORS as it gets in the way > of alternative authentication schemes > > > ... > > > it's a design decision to expose data from the REST API to all > origins; you should be able to override in plugins easily > > > So it should be noted that it's perfectly normal for `wp-json/` to be accessible from all origins, and it's not inherently insecure. As for your questions: > > Is it okay to set restrict the origin in this way? > > > By modifying your WordPress install itself? ***Absolutely not.*** You should never edit WordPress core files. Any changes you make will be overwritten any time WordPress updates, forcing you to make the change again every time, possibly leading you into the very bad practice of maintaining your own fork of WordPress. If you want to modify core WordPress behaviour yourself, you need to create a [plugin](https://developer.wordpress.org/plugins/), and use the [Hooks API](https://developer.wordpress.org/plugins/hooks/) to make your changes by removing and replacing actions, or filtering values. In this case, you'll notice that the header is sent in the `rest_send_cors_headers()` function. This function is run by WordPress by hooking it with this line: ``` add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' ); ``` Which, according to inline documentation is inside a function that is: ``` Attached to the {@see 'rest_api_init'} action to make testing and disabling these filters easier. ``` So, if you want to modify `rest_send_cors_headers()` what you need to to is create a plugin, and inside that plugin copy the `rest_send_cors_headers()` function to a new function with a different name. Then you want to replace WordPress' version with yours: ``` add_action( 'rest_api_init', function() { remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' ); add_filter( 'rest_pre_serve_request', 'my_new_rest_send_cors_headers' ); } ); ``` Where `my_new_rest_send_cors_headers()` is the name of your new modified version of the function. > > What might be the consequences of doing it? Maybe plugins that rely on a header like `access-control-allow-origin: *` could stop working? Are there such plugins? > > > Most plugins are unlikely to have issues, as they will be making the requests from the same origin, however you will have issues with two types of plugins that I can think of: 1. Plugins that work with an external service. That service may want to connect to your website via the REST API, and will be unable to do so if you are only allowing requests from one origin. 2. Plugins that make requests to your site's REST API from the server, using curl, or the [WordPress HTTP API](https://developer.wordpress.org/plugins/http-api/), without setting the Origin header to your site's URL. This is pretty unusual and rare, but not impossible. That last point brings up an important issue: Setting `Access-Control-Allow-Origin` is not going to protect your data. It is trivial for a server to spoof the origin and make a request to the API and get that data. This header is *not* an authentication security measure, so if you want to lock down your API from the outside world, this header is not the way to do it.
385,681
<p>I created a query with arguments see blow. On the page I see an error in a loop</p> <ul> <li><p>Notice undefined offset 1</p> </li> <li><p>Notice undefined offset 2</p> </li> <li><p>Notice undefined offset 3 and so on...</p> <pre><code>$args = array ( 'post_type' =&gt; 'catalog', 'post_status' =&gt; 'publish', ); $loop = new WP_Query( $args ); if ( $loop-&gt;have_posts() ) { while ( $loop-&gt;have_posts() ) { the_post(); echo get_the_title(); } } </code></pre> </li> </ul> <p>I tried other arguments but this does not work.</p> <ul> <li>'posts_per_page' =&gt; 4</li> </ul> <p>Please who can help me?</p>
[ { "answer_id": 385682, "author": "Kaif Ahmad", "author_id": 203686, "author_profile": "https://wordpress.stackexchange.com/users/203686", "pm_score": -1, "selected": false, "text": "<p>There are five default Post Types readily available to users or internally used by the WordPress instal...
2021/03/25
[ "https://wordpress.stackexchange.com/questions/385681", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203763/" ]
I created a query with arguments see blow. On the page I see an error in a loop * Notice undefined offset 1 * Notice undefined offset 2 * Notice undefined offset 3 and so on... ``` $args = array ( 'post_type' => 'catalog', 'post_status' => 'publish', ); $loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) { the_post(); echo get_the_title(); } } ``` I tried other arguments but this does not work. * 'posts\_per\_page' => 4 Please who can help me?
There might be other causes to the issue in question, but one issue I noticed in your code is that because you are looping through a custom `WP_Query` instance, i.e. `$loop`, then you need to use `$loop->the_post()` instead of just `the_post()`: ```php while ( $loop->have_posts() ) { $loop->the_post(); the_title(); } ``` And you could see that I simply called `the_title()` and not doing `echo get_the_title()`, so you should also do the same.
385,691
<p>I'm using this function right now</p> <pre><code>wp_link_pages( array('before' =&gt; '&lt;div class=&quot;page-links&quot;&gt;','after' =&gt; '&lt;/div&gt;',) ); </code></pre> <p>The post pagination is showing like this:</p> <blockquote> <p>1 2 3 4 5 6 7 8 9 10 11</p> </blockquote> <p>But I want it to be like this in that there's too many pages</p> <blockquote> <p>1 2 3 ..9 10 11</p> </blockquote> <p>However, There's no <code>mid_size</code> or <code>end_size</code> like function <code>paginate_links()</code></p> <p>I've been searching for answer all day, Is there anyone could help?</p>
[ { "answer_id": 385682, "author": "Kaif Ahmad", "author_id": 203686, "author_profile": "https://wordpress.stackexchange.com/users/203686", "pm_score": -1, "selected": false, "text": "<p>There are five default Post Types readily available to users or internally used by the WordPress instal...
2021/03/25
[ "https://wordpress.stackexchange.com/questions/385691", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203936/" ]
I'm using this function right now ``` wp_link_pages( array('before' => '<div class="page-links">','after' => '</div>',) ); ``` The post pagination is showing like this: > > 1 2 3 4 5 6 7 8 9 10 11 > > > But I want it to be like this in that there's too many pages > > 1 2 3 ..9 10 11 > > > However, There's no `mid_size` or `end_size` like function `paginate_links()` I've been searching for answer all day, Is there anyone could help?
There might be other causes to the issue in question, but one issue I noticed in your code is that because you are looping through a custom `WP_Query` instance, i.e. `$loop`, then you need to use `$loop->the_post()` instead of just `the_post()`: ```php while ( $loop->have_posts() ) { $loop->the_post(); the_title(); } ``` And you could see that I simply called `the_title()` and not doing `echo get_the_title()`, so you should also do the same.
385,705
<p>I could not get to work. When published the content the attribute innerContent didn't save. Here is what I tried.</p> <p><strong>block.js</strong></p> <pre><code>// Import CSS. import './style.scss'; import './editor.scss'; const { __ } = wp.i18n; const { registerBlockType } = wp.blocks; const { RichText } = wp.editor; registerBlockType( 'hall/block-server-side-render', { title: __( 'Server Side Rendering' ), icon: 'shield', category: 'common', keywords: [ __( 'Server Side Rendering' ) ], attributes: { innerContent: { type: 'array', source: 'children', selector: 'p' } }, edit: function( props ) { function onChangeContent( content ) { props.setAttributes( { innerContent: content } ); } return ( &lt;div className={ props.className }&gt; &lt;div class=&quot;gray-bg&quot;&gt; &lt;RichText tagName=&quot;p&quot; role=&quot;textbox&quot; aria-multiline=&quot;true&quot; value={props.attributes.innerContent} onChange={onChangeContent} /&gt; &lt;/div&gt; &lt;/div&gt; ); }, save: function( props ) { return null; }, } ); </code></pre> <p><strong>init.php</strong></p> <pre><code>register_block_type( 'hall/block-server-side-render', array( 'render_callback' =&gt; 'hall_render_inner_content', 'attributes' =&gt; array( 'innerContent' =&gt; array( 'type' =&gt; 'array' ) ) )); function hall_render_inner_content( $attributes ) { $innerContent = $attributes['innerContent']; return '&lt;div class=&quot;inner-content&quot;&gt;' . $innerContent . '&lt;/div&gt;'; } </code></pre>
[ { "answer_id": 385682, "author": "Kaif Ahmad", "author_id": 203686, "author_profile": "https://wordpress.stackexchange.com/users/203686", "pm_score": -1, "selected": false, "text": "<p>There are five default Post Types readily available to users or internally used by the WordPress instal...
2021/03/25
[ "https://wordpress.stackexchange.com/questions/385705", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/198218/" ]
I could not get to work. When published the content the attribute innerContent didn't save. Here is what I tried. **block.js** ``` // Import CSS. import './style.scss'; import './editor.scss'; const { __ } = wp.i18n; const { registerBlockType } = wp.blocks; const { RichText } = wp.editor; registerBlockType( 'hall/block-server-side-render', { title: __( 'Server Side Rendering' ), icon: 'shield', category: 'common', keywords: [ __( 'Server Side Rendering' ) ], attributes: { innerContent: { type: 'array', source: 'children', selector: 'p' } }, edit: function( props ) { function onChangeContent( content ) { props.setAttributes( { innerContent: content } ); } return ( <div className={ props.className }> <div class="gray-bg"> <RichText tagName="p" role="textbox" aria-multiline="true" value={props.attributes.innerContent} onChange={onChangeContent} /> </div> </div> ); }, save: function( props ) { return null; }, } ); ``` **init.php** ``` register_block_type( 'hall/block-server-side-render', array( 'render_callback' => 'hall_render_inner_content', 'attributes' => array( 'innerContent' => array( 'type' => 'array' ) ) )); function hall_render_inner_content( $attributes ) { $innerContent = $attributes['innerContent']; return '<div class="inner-content">' . $innerContent . '</div>'; } ```
There might be other causes to the issue in question, but one issue I noticed in your code is that because you are looping through a custom `WP_Query` instance, i.e. `$loop`, then you need to use `$loop->the_post()` instead of just `the_post()`: ```php while ( $loop->have_posts() ) { $loop->the_post(); the_title(); } ``` And you could see that I simply called `the_title()` and not doing `echo get_the_title()`, so you should also do the same.
385,716
<p>I think I'm missing obvious here, but here's the issue:</p> <p>I used the current @wordpress/create-block to create a block plugin.</p> <p>I'm looking to create three blocks in this plugin, so I setup the first one and it's working great in the editor and saving. The block details are all coming from the block.json, as it's setup by default in create-block.</p> <p>So I added a folder called 'label' under src, moved the index.js, save.js, edit.js, and stylesheets into the folder. I setup an index.js in the root and import that file. The block continues to work, even after the folder change with NPM running.</p> <p>With the block working, both the plugin PHP file with register_block_type_from_metadata() and the block.json are still in the root directory. With NPM running, the block continues to work fine. I have the attributes only defined in block.json, and content is saving to those attributes, so I know it's 100% working.</p> <p>However...when I move the block.json to the 'label' folder - like I see in core blocks and elsewhere, and as it makes sense so I can define more blocks - it breaks. I followed the docs of adding the path to the directory:</p> <pre><code>function create_block_nutrition_facts_stacked_block_init() { register_block_type_from_metadata( __DIR__ . '/src/label' ); } </code></pre> <p>Now the block isn't registered at all. I had renamed the label folder, so just as a test I moved the block.json to the root of the src folder and adjusted the path. Still not working. I took <strong>DIR</strong> out and gave it a direct path, I put the full file in (/src/label/block.json), I added and removed slashes and ./ and ../ and all kinds of things in case I'm just tired and was typing something wrong and it doesn't recognize it.</p> <p>If I change it back to just <strong>DIR</strong> and move block.json back to the root, it works again fine. Attributes save. I've started and restarted NPM, I dug through tons of other plugins on Github, I dug through core plugins...I cannot find anyone using the new way of registering multiple blocks in a single plugin. Considering the &quot;old way&quot; will be depreciated according to the github pull request that merged block.json into the @wordpress/create-block...I'd really like to do it the &quot;right&quot; way here, but I'm stumped.</p> <p>Any help is appreciated.</p>
[ { "answer_id": 385757, "author": "llysa ", "author_id": 152943, "author_profile": "https://wordpress.stackexchange.com/users/152943", "pm_score": 3, "selected": false, "text": "<p>Figured it out, in the block.json script needs a new relative location to the build directory, so new code:<...
2021/03/25
[ "https://wordpress.stackexchange.com/questions/385716", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/152943/" ]
I think I'm missing obvious here, but here's the issue: I used the current @wordpress/create-block to create a block plugin. I'm looking to create three blocks in this plugin, so I setup the first one and it's working great in the editor and saving. The block details are all coming from the block.json, as it's setup by default in create-block. So I added a folder called 'label' under src, moved the index.js, save.js, edit.js, and stylesheets into the folder. I setup an index.js in the root and import that file. The block continues to work, even after the folder change with NPM running. With the block working, both the plugin PHP file with register\_block\_type\_from\_metadata() and the block.json are still in the root directory. With NPM running, the block continues to work fine. I have the attributes only defined in block.json, and content is saving to those attributes, so I know it's 100% working. However...when I move the block.json to the 'label' folder - like I see in core blocks and elsewhere, and as it makes sense so I can define more blocks - it breaks. I followed the docs of adding the path to the directory: ``` function create_block_nutrition_facts_stacked_block_init() { register_block_type_from_metadata( __DIR__ . '/src/label' ); } ``` Now the block isn't registered at all. I had renamed the label folder, so just as a test I moved the block.json to the root of the src folder and adjusted the path. Still not working. I took **DIR** out and gave it a direct path, I put the full file in (/src/label/block.json), I added and removed slashes and ./ and ../ and all kinds of things in case I'm just tired and was typing something wrong and it doesn't recognize it. If I change it back to just **DIR** and move block.json back to the root, it works again fine. Attributes save. I've started and restarted NPM, I dug through tons of other plugins on Github, I dug through core plugins...I cannot find anyone using the new way of registering multiple blocks in a single plugin. Considering the "old way" will be depreciated according to the github pull request that merged block.json into the @wordpress/create-block...I'd really like to do it the "right" way here, but I'm stumped. Any help is appreciated.
Figured it out, in the block.json script needs a new relative location to the build directory, so new code: ``` "editorScript": "file:../../build/index.js", "editorStyle": "file:../../build/index.css", "style": "file:../../build/style-index.css" ```
385,752
<p>as a matter of performance for the entire system, how to do it correctly, if there is a way, to make the code of my plugin read or interpreted only when the user will login, as it is only and exclusively to work when the user is logged in.</p> <p>In this way, I decrease the load on the site, not having to run or read everything every request on the site.</p> <p>I was thinking of doing something similar to that, but I still haven't found a more viable way</p> <pre><code>$pluginPath = 'myPlugin/myPlugin.php'; if (is_plugin_active($pluginPath) &amp;&amp; stripos($_SERVER['SCRIPT_NAME'], 'wp-admin') == true) { ... } </code></pre>
[ { "answer_id": 385753, "author": "PVee Marketing", "author_id": 203744, "author_profile": "https://wordpress.stackexchange.com/users/203744", "pm_score": 0, "selected": false, "text": "<p>is_user_logged_in() Would do it. So let's assume you're loading scripts only when the user is logged...
2021/03/26
[ "https://wordpress.stackexchange.com/questions/385752", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/201813/" ]
as a matter of performance for the entire system, how to do it correctly, if there is a way, to make the code of my plugin read or interpreted only when the user will login, as it is only and exclusively to work when the user is logged in. In this way, I decrease the load on the site, not having to run or read everything every request on the site. I was thinking of doing something similar to that, but I still haven't found a more viable way ``` $pluginPath = 'myPlugin/myPlugin.php'; if (is_plugin_active($pluginPath) && stripos($_SERVER['SCRIPT_NAME'], 'wp-admin') == true) { ... } ```
When I create custom plugins I tend to add a single init function, which includes other plugin files, attached functions from these files to actions and hooks, etc. This way I have centralized place where the plugin is bootstrapped. This init function is then hooked to the `plugins_loaded` action in case I need to do some dependecy checking - i.e. some other plugin needs to be installed and active too. ``` // your-main-plugin-file.php add_action('plugins_loaded', 'my_plugin_init'); function my_plugin_init() { // check dependencies // include files // hook plugin function to actions and filters // etc... } ``` But the `plugins_loaded` action fires too early, if you also need to check for a logged in user. In that case a good action to hook your main init function to would be `init` as the user is authenticated by the time it is fired. ``` add_action('init', 'my_plugin_init_logged_in_users'); function my_plugin_init_logged_in_users() { if ( is_user_logged_in() ) { my_plugin_init(); } } ``` You can find more information about the different WP actions, their order and what data is available to them when they fire, in the [Action reference](https://codex.wordpress.org/Plugin_API/Action_Reference).
385,763
<p>I am trying to enqueue a hover function in my functios.php of my child theme, so that when hovering over a title, a div with a text will be visible. The code I am using is this:</p> <pre><code>&lt;?php add_action( 'wp_enqueue_scripts', 'home_game', 20); function home_game(){ ?&gt; &lt;script&gt; let title1 = document.getElementById(&quot;home-title1&quot;); title1.addEventListener('mouseover', mouseOver); title1.addEventListener('mouseout', mouseOut); function mouseOver(){ document.getElementById('title-box').style.display = 'none'; document.getElementById('home-box1').style.display = 'block'; } function mouseOut(){ document.getElementById('title-box').style.display = 'block'; document.getElementById('home-box1').style.display = 'none'; } &lt;/script&gt; &lt;?php } </code></pre> <p>It works in my fiddle so I guess the problem is in my php, I am fairly new with it... Any help or clue will be very appreciated!</p> <p>fiddle link: <a href="https://jsfiddle.net/rvoLc3ph/" rel="nofollow noreferrer">https://jsfiddle.net/rvoLc3ph/</a></p>
[ { "answer_id": 385753, "author": "PVee Marketing", "author_id": 203744, "author_profile": "https://wordpress.stackexchange.com/users/203744", "pm_score": 0, "selected": false, "text": "<p>is_user_logged_in() Would do it. So let's assume you're loading scripts only when the user is logged...
2021/03/26
[ "https://wordpress.stackexchange.com/questions/385763", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203994/" ]
I am trying to enqueue a hover function in my functios.php of my child theme, so that when hovering over a title, a div with a text will be visible. The code I am using is this: ``` <?php add_action( 'wp_enqueue_scripts', 'home_game', 20); function home_game(){ ?> <script> let title1 = document.getElementById("home-title1"); title1.addEventListener('mouseover', mouseOver); title1.addEventListener('mouseout', mouseOut); function mouseOver(){ document.getElementById('title-box').style.display = 'none'; document.getElementById('home-box1').style.display = 'block'; } function mouseOut(){ document.getElementById('title-box').style.display = 'block'; document.getElementById('home-box1').style.display = 'none'; } </script> <?php } ``` It works in my fiddle so I guess the problem is in my php, I am fairly new with it... Any help or clue will be very appreciated! fiddle link: <https://jsfiddle.net/rvoLc3ph/>
When I create custom plugins I tend to add a single init function, which includes other plugin files, attached functions from these files to actions and hooks, etc. This way I have centralized place where the plugin is bootstrapped. This init function is then hooked to the `plugins_loaded` action in case I need to do some dependecy checking - i.e. some other plugin needs to be installed and active too. ``` // your-main-plugin-file.php add_action('plugins_loaded', 'my_plugin_init'); function my_plugin_init() { // check dependencies // include files // hook plugin function to actions and filters // etc... } ``` But the `plugins_loaded` action fires too early, if you also need to check for a logged in user. In that case a good action to hook your main init function to would be `init` as the user is authenticated by the time it is fired. ``` add_action('init', 'my_plugin_init_logged_in_users'); function my_plugin_init_logged_in_users() { if ( is_user_logged_in() ) { my_plugin_init(); } } ``` You can find more information about the different WP actions, their order and what data is available to them when they fire, in the [Action reference](https://codex.wordpress.org/Plugin_API/Action_Reference).
385,812
<p>I am using Modula Plugin to speedup the galleries creation process. It works wonderfully but I don't understand how to render it correctly on the ajax call. I read through the available posts on rendering shortcodes via ajax, but so far I struggle to implement it in my code. Here is the code I use:</p> <pre><code>add_action('wp_ajax_nopriv_getHistory', 'getHistory_ajax'); add_action('wp_ajax_getHistory', 'getHistory_ajax'); function getHistory_ajax(){ $args = array( 'post_type' =&gt; 'gallery', 'posts_per_page' =&gt; -1, 'meta_query' =&gt; array( array( 'key' =&gt; 'post_gallery_gallery_year', 'value' =&gt; $festivalQueryYear, 'compare' =&gt; 'LIKE' ) ), 'meta_key' =&gt; 'post_gallery_gallery_year', 'orderby' =&gt; 'meta_value_num', 'order' =&gt; 'DESC', ); $gallery= new WP_Query($args); if($gallery-&gt;have_posts()) : while($gallery-&gt;have_posts()): $gallery-&gt;the_post(); $shortcode = get_field('gallery_shortcode'); echo do_shortcode($shortcode); endwhile; wp_reset_postdata(); endif; } </code></pre> <p>in <strong>ajax.js</strong></p> <pre><code> $(&quot;.festival-year-toggler-js-ajax&quot;).on(&quot;click&quot;, function (e) { $.ajax({ url: wpAjax.ajaxUrl, data: { action: &quot;getHistory&quot;, festivalQueryYear }, type: &quot;POST&quot;, success: function (data) { $('.target-div').html(data); }, error: function (error) { console.warn(error); }, }); }) </code></pre> <p>The result is, the images from the gallery are rendered but without the specified layout, obviously, because the shortcode is not running through its default environment. How can I run this shortcode so that it renders on the ajax call in the same way as on normal page loading?</p> <p>Thank you so much for your help!!!</p>
[ { "answer_id": 385753, "author": "PVee Marketing", "author_id": 203744, "author_profile": "https://wordpress.stackexchange.com/users/203744", "pm_score": 0, "selected": false, "text": "<p>is_user_logged_in() Would do it. So let's assume you're loading scripts only when the user is logged...
2021/03/28
[ "https://wordpress.stackexchange.com/questions/385812", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/203297/" ]
I am using Modula Plugin to speedup the galleries creation process. It works wonderfully but I don't understand how to render it correctly on the ajax call. I read through the available posts on rendering shortcodes via ajax, but so far I struggle to implement it in my code. Here is the code I use: ``` add_action('wp_ajax_nopriv_getHistory', 'getHistory_ajax'); add_action('wp_ajax_getHistory', 'getHistory_ajax'); function getHistory_ajax(){ $args = array( 'post_type' => 'gallery', 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'post_gallery_gallery_year', 'value' => $festivalQueryYear, 'compare' => 'LIKE' ) ), 'meta_key' => 'post_gallery_gallery_year', 'orderby' => 'meta_value_num', 'order' => 'DESC', ); $gallery= new WP_Query($args); if($gallery->have_posts()) : while($gallery->have_posts()): $gallery->the_post(); $shortcode = get_field('gallery_shortcode'); echo do_shortcode($shortcode); endwhile; wp_reset_postdata(); endif; } ``` in **ajax.js** ``` $(".festival-year-toggler-js-ajax").on("click", function (e) { $.ajax({ url: wpAjax.ajaxUrl, data: { action: "getHistory", festivalQueryYear }, type: "POST", success: function (data) { $('.target-div').html(data); }, error: function (error) { console.warn(error); }, }); }) ``` The result is, the images from the gallery are rendered but without the specified layout, obviously, because the shortcode is not running through its default environment. How can I run this shortcode so that it renders on the ajax call in the same way as on normal page loading? Thank you so much for your help!!!
When I create custom plugins I tend to add a single init function, which includes other plugin files, attached functions from these files to actions and hooks, etc. This way I have centralized place where the plugin is bootstrapped. This init function is then hooked to the `plugins_loaded` action in case I need to do some dependecy checking - i.e. some other plugin needs to be installed and active too. ``` // your-main-plugin-file.php add_action('plugins_loaded', 'my_plugin_init'); function my_plugin_init() { // check dependencies // include files // hook plugin function to actions and filters // etc... } ``` But the `plugins_loaded` action fires too early, if you also need to check for a logged in user. In that case a good action to hook your main init function to would be `init` as the user is authenticated by the time it is fired. ``` add_action('init', 'my_plugin_init_logged_in_users'); function my_plugin_init_logged_in_users() { if ( is_user_logged_in() ) { my_plugin_init(); } } ``` You can find more information about the different WP actions, their order and what data is available to them when they fire, in the [Action reference](https://codex.wordpress.org/Plugin_API/Action_Reference).
385,827
<p>I have a nav menu in footer. I just want to display it side by a <code>&lt;p&gt;</code> tag, I mean something like this</p> <pre><code>&lt;ul&gt; &lt;li&gt; &lt;p&gt;copyright C 2021&lt;/p&gt; &lt;/li&gt; &lt;li&gt; contact &lt;/li&gt; &lt;li&gt; blog &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>this is my menu function</p> <pre><code>if ( function_exists( 'register_nav_menus' ) ) { register_nav_menus( array( 'top_nav_menu' =&gt; 'My Footer Menu' ) ); </code></pre> <p>and I'm calling it in footer</p> <pre><code>&lt;?php if ( has_nav_menu( 'top_nav_menu' ) ) { ?&gt; &lt;?php wp_nav_menu( array( 'menu' =&gt; 'Footer Navigation Menu', 'theme_location' =&gt; 'top_nav_menu', 'menu_class' =&gt; 'footer-links' )); ?&gt; &lt;?php } else {?&gt; &lt;ul class=&quot;sf-menu&quot;&gt; &lt;?php wp_list_pages( array('title_li' =&gt; '','sort_column' =&gt; 'menu_order')); ?&gt; &lt;/ul&gt; &lt;?php } ?&gt; </code></pre> <p>How can I insert an extra <strong><code>&lt;li&gt;</code></strong> element just before its first <strong><code>&lt;li&gt;</code></strong> and add a <strong><code>&lt;p&gt;</code></strong> tag between that later added <strong><code>&lt;li&gt;</code></strong> element?</p>
[ { "answer_id": 385829, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 1, "selected": false, "text": "<p>You can filter the HTML output with the <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu/\...
2021/03/28
[ "https://wordpress.stackexchange.com/questions/385827", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113723/" ]
I have a nav menu in footer. I just want to display it side by a `<p>` tag, I mean something like this ``` <ul> <li> <p>copyright C 2021</p> </li> <li> contact </li> <li> blog </li> </ul> ``` this is my menu function ``` if ( function_exists( 'register_nav_menus' ) ) { register_nav_menus( array( 'top_nav_menu' => 'My Footer Menu' ) ); ``` and I'm calling it in footer ``` <?php if ( has_nav_menu( 'top_nav_menu' ) ) { ?> <?php wp_nav_menu( array( 'menu' => 'Footer Navigation Menu', 'theme_location' => 'top_nav_menu', 'menu_class' => 'footer-links' )); ?> <?php } else {?> <ul class="sf-menu"> <?php wp_list_pages( array('title_li' => '','sort_column' => 'menu_order')); ?> </ul> <?php } ?> ``` How can I insert an extra **`<li>`** element just before its first **`<li>`** and add a **`<p>`** tag between that later added **`<li>`** element?
When using `wp_nav_menu()` you can exclude the `<ul>` tag by setting the `items_wrap` to only include the list items (`%3$s`), then you can add your own `<li>` before or after that, and wrap it with `<ul>` yourself: ``` <ul class="footer-links"> <li> <p>copyright C 2021</p> </li> <?php wp_nav_menu( array( 'menu' => 'Footer Navigation Menu', 'theme_location' => 'top_nav_menu', 'items_wrap' => '%3$s', ) ); ?> </ul> ```
385,849
<p>I have configured the <code>upload_max_filesize</code> directive to <strong>64 MB</strong> in my localhost <code>php.ini</code> and have my Apache restarted.</p> <p>But why the Media section in my WordPress still showing 2 MB below?</p> <pre><code>Maximum upload file size: 2 MB. </code></pre> <p>So any file is more than 2 MB, I get this error below:</p> <blockquote> <p>The uploaded file exceeds the upload_max_filesize directive in php.ini.</p> </blockquote> <p>Any ideas what else I have to configure?</p> <p><strong>EDIT 1:</strong></p> <p>I also have set <code>post_max_size = 64M</code> to match <code>upload_max_filesize = 64M</code> in <code>php.ini</code> and have my Apache restarted.</p> <p><strong>EDIT 2:</strong></p> <p>Found the problem. I am running on a <strong>PHP Development Server</strong>. And probably because of this, WordPress cannot read my <code>php.ini</code>. It is fine on my production server.</p> <p>So that's no why to increase the <code>upload_max_filesize</code> on a PHP Development Server then?</p>
[ { "answer_id": 385829, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 1, "selected": false, "text": "<p>You can filter the HTML output with the <a href=\"https://developer.wordpress.org/reference/hooks/wp_nav_menu/\...
2021/03/29
[ "https://wordpress.stackexchange.com/questions/385849", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89898/" ]
I have configured the `upload_max_filesize` directive to **64 MB** in my localhost `php.ini` and have my Apache restarted. But why the Media section in my WordPress still showing 2 MB below? ``` Maximum upload file size: 2 MB. ``` So any file is more than 2 MB, I get this error below: > > The uploaded file exceeds the upload\_max\_filesize directive in php.ini. > > > Any ideas what else I have to configure? **EDIT 1:** I also have set `post_max_size = 64M` to match `upload_max_filesize = 64M` in `php.ini` and have my Apache restarted. **EDIT 2:** Found the problem. I am running on a **PHP Development Server**. And probably because of this, WordPress cannot read my `php.ini`. It is fine on my production server. So that's no why to increase the `upload_max_filesize` on a PHP Development Server then?
When using `wp_nav_menu()` you can exclude the `<ul>` tag by setting the `items_wrap` to only include the list items (`%3$s`), then you can add your own `<li>` before or after that, and wrap it with `<ul>` yourself: ``` <ul class="footer-links"> <li> <p>copyright C 2021</p> </li> <?php wp_nav_menu( array( 'menu' => 'Footer Navigation Menu', 'theme_location' => 'top_nav_menu', 'items_wrap' => '%3$s', ) ); ?> </ul> ```
385,852
<p>I want to display a page with ID=1149 in a particular place on another page. For that I've tried with this:</p> <pre><code> &lt;div class=&quot;col-md-4 sidebarl&quot;&gt; &lt;?php $args = array( 'post_type' =&gt; 'page', 'post__in' =&gt; array(1149) ); $query = new WP_Query($args); while ($query-&gt;have_posts()) { $query-&gt;the_post(); } ?&gt; &lt;/div&gt; </code></pre> <p>But I am not getting anything, an empty page. Am I missing something?</p>
[ { "answer_id": 385858, "author": "Dejan Dozet", "author_id": 134358, "author_profile": "https://wordpress.stackexchange.com/users/134358", "pm_score": 0, "selected": false, "text": "<p>I am not sure if this is the correct answer, but I did it this way:</p>\n<pre><code> &lt;div class=&...
2021/03/29
[ "https://wordpress.stackexchange.com/questions/385852", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134358/" ]
I want to display a page with ID=1149 in a particular place on another page. For that I've tried with this: ``` <div class="col-md-4 sidebarl"> <?php $args = array( 'post_type' => 'page', 'post__in' => array(1149) ); $query = new WP_Query($args); while ($query->have_posts()) { $query->the_post(); } ?> </div> ``` But I am not getting anything, an empty page. Am I missing something?
> > I am not getting anything, an empty page. Am I missing something? > > > Yes, you are. [`$query->the_post()`](https://developer.wordpress.org/reference/classes/wp_query/the_post/) does *not* display anything — it just moves the pointer/key in the posts array (`$query->posts`) to the next one, and setups the global post data (`$GLOBALS['post']`). So yes, in response to your answer, [`the_content()`](https://developer.wordpress.org/reference/functions/the_content/) would be what you would use to display the content of the current post in the loop. But actually, you could simply use the [`page_id` parameter](https://developer.wordpress.org/reference/classes/wp_query/#post-page-parameters) like so, to query a post of the `page` type and having a specific ID: ```php $args = array( // Instead of using post_type and post__in, you could simply do: 'page_id' => 1149, ); ``` Also, you should call [`wp_reset_postdata()`](https://developer.wordpress.org/reference/functions/wp_reset_postdata/) after your loop ends so that template tags (e.g. `the_content()` and `the_title()`) would use the main query’s current post again. ```php while ($query->have_posts()) { $query->the_post(); the_content(); } wp_reset_postdata(); ``` And just so that you know, you could also use [`get_post()`](https://developer.wordpress.org/reference/functions/get_post/) and [`setup_postdata()`](https://developer.wordpress.org/reference/functions/setup_postdata/) like so, without having to use the `new WP_Query()` way: ```php //global $post; // uncomment if necessary $post = get_post( 1149 ); setup_postdata( $post ); the_title(); the_content(); // ... etc. wp_reset_postdata(); ```
385,982
<p>I'm programming the integration with external API (real estate). I have one CRON job which is planned for at 1 o'clock am. It's running very well because I'm using server CRON initialize instead WP CRON standard so It's running at the right time.</p> <p>It's my scheduled job function:</p> <pre><code>function wcs_cron_system_update() { wcs_cron_start_update(); $wcs_cron_actions = new WCS_Cron_Actions(); $wcs_cron_helpers = new WCS_Cron_Helpers(); $wcs_cron_actions-&gt;real_estate_cleaning(); $wcs_cron_helpers-&gt;remove_unused_images(); $wcs_cron_actions-&gt;investments_insert_sql(); $wcs_cron_actions-&gt;apartments_insert_sql(); $wcs_cron_actions-&gt;commerce_insert_sql(); $wcs_cron_actions-&gt;investments_insert(); $wcs_cron_actions-&gt;real_estate_insert(); $wcs_cron_actions-&gt;investment_update_by_single_real_easte(); $wcs_cron_actions-&gt;real_estate_update_by_single_investment(); $wcs_cron_actions-&gt;investment_update_by_all_real_easte(); $wcs_cron_actions-&gt;search_index_update(); } </code></pre> <p>I'm doing a few functions one by one because I need some data before I'm doing the next function. I can't schedule (I don't know how I should do it) separately CRON jobs because I had a few situations when some function was run before I have necessary data (because some functions were run before it should be)</p> <p>My function contains a sequence of tasks (functions).</p> <p>Question: is it the correct way to do it? maybe I should do it another way? how?</p> <p>Thanks!</p>
[ { "answer_id": 385983, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>Question: is it the correct way to do it? maybe I should do it another way? how?</p>\n</blockq...
2021/03/31
[ "https://wordpress.stackexchange.com/questions/385982", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/204224/" ]
I'm programming the integration with external API (real estate). I have one CRON job which is planned for at 1 o'clock am. It's running very well because I'm using server CRON initialize instead WP CRON standard so It's running at the right time. It's my scheduled job function: ``` function wcs_cron_system_update() { wcs_cron_start_update(); $wcs_cron_actions = new WCS_Cron_Actions(); $wcs_cron_helpers = new WCS_Cron_Helpers(); $wcs_cron_actions->real_estate_cleaning(); $wcs_cron_helpers->remove_unused_images(); $wcs_cron_actions->investments_insert_sql(); $wcs_cron_actions->apartments_insert_sql(); $wcs_cron_actions->commerce_insert_sql(); $wcs_cron_actions->investments_insert(); $wcs_cron_actions->real_estate_insert(); $wcs_cron_actions->investment_update_by_single_real_easte(); $wcs_cron_actions->real_estate_update_by_single_investment(); $wcs_cron_actions->investment_update_by_all_real_easte(); $wcs_cron_actions->search_index_update(); } ``` I'm doing a few functions one by one because I need some data before I'm doing the next function. I can't schedule (I don't know how I should do it) separately CRON jobs because I had a few situations when some function was run before I have necessary data (because some functions were run before it should be) My function contains a sequence of tasks (functions). Question: is it the correct way to do it? maybe I should do it another way? how? Thanks!
> > I can't schedule (I don't know how I should do it) separately CRON jobs because I had a few situations when some function was run before I have necessary data > > > The key to doing this is scheduling the first job to run daily at the required time, and have that event create all of the other ones after it is done. ``` function wcs_cron_system_update($step = 0) { switch ($step) { case 0: // do what has to be done first break; case 1: // second step break; case 2: // etc break; } } ``` If you start like this, you can pass the `$step` as an argument to it. So on the daily cron it executes step 0. After the first step is done, what you can do is call [`wp_schedule_single_event()`](https://developer.wordpress.org/reference/functions/wp_schedule_single_event/) like so ``` \wp_schedule_single_event( // start in 5min \current_time('timestamp') + (5 * 60), 'same_hook_as_daily_cron', [1] ); ``` This will create an event for your second step. When that is done, just create a single event for your third step. Make sure [your `add_action` code allows for arguments](https://developer.wordpress.org/reference/functions/wp_schedule_single_event/#comment-1042).
385,988
<p>I am wondering how to add meta box in WordPress specific page admin, I mean when I create meta_box with code snippet below provided from source tutorial is really perfect and effective but one thing that I need to control is display that meta_box only in specific page for instance: pretend I have two page in my WordPress project named Home and About.</p> <p>When I create meta_box by default the meta_box that I add will display on the same page admin back end, imagined when I clicked edit button to Home and About page my meta box will appear in both page. What I want is make a meta_box only show in “Home” admin backend page when I click the edit page.</p> <p>My goal is set different meta_box in every different page, meaning the users specially the blog editor expect different meta_box_field in different page when they click edit button in each page, That is the thing I can’t figure out can you help me to solve that problem</p> <pre><code>/* Plugin Name: Meta Box Example Description: Example demonstrating how to add Meta Boxes. Plugin URI: https://plugin-planet.com/ Author: Jeff Starr Version: 1.0 */ // register meta box function myplugin_add_meta_box() { $post_types = array( 'post', 'page' ); foreach ( $post_types as $post_type ) { add_meta_box( 'myplugin_meta_box', // Unique ID of meta box 'MyPlugin Meta Box', // Title of meta box 'myplugin_display_meta_box', // Callback function $post_type // Post type ); } } add_action( 'add_meta_boxes', 'myplugin_add_meta_box' ); // display meta box function myplugin_display_meta_box( $post ) { $value = get_post_meta( $post-&gt;ID, '_myplugin_meta_key', true ); wp_nonce_field( basename( __FILE__ ), 'myplugin_meta_box_nonce' ); ?&gt; &lt;label for=&quot;myplugin-meta-box&quot;&gt;Field Description&lt;/label&gt; &lt;select id=&quot;myplugin-meta-box&quot; name=&quot;myplugin-meta-box&quot;&gt; &lt;option value=&quot;&quot;&gt;Select option...&lt;/option&gt; &lt;option value=&quot;option-1&quot; &lt;?php selected( $value, 'option-1' ); ?&gt;&gt;Option 1&lt;/option&gt; &lt;option value=&quot;option-2&quot; &lt;?php selected( $value, 'option-2' ); ?&gt;&gt;Option 2&lt;/option&gt; &lt;option value=&quot;option-3&quot; &lt;?php selected( $value, 'option-3' ); ?&gt;&gt;Option 3&lt;/option&gt; &lt;/select&gt; &lt;?php } // save meta box function myplugin_save_meta_box( $post_id ) { $is_autosave = wp_is_post_autosave( $post_id ); $is_revision = wp_is_post_revision( $post_id ); $is_valid_nonce = false; if ( isset( $_POST[ 'myplugin_meta_box_nonce' ] ) ) { if ( wp_verify_nonce( $_POST[ 'myplugin_meta_box_nonce' ], basename( __FILE__ ) ) ) { $is_valid_nonce = true; } } if ( $is_autosave || $is_revision || !$is_valid_nonce ) return; if ( array_key_exists( 'myplugin-meta-box', $_POST ) ) { update_post_meta( $post_id, // Post ID '_myplugin_meta_key', // Meta key sanitize_text_field( $_POST[ 'myplugin-meta-box' ] ) // Meta value ); } } add_action( 'save_post', 'myplugin_save_meta_box' ); </code></pre> <p>Is there any condition or function to do that you will recommend?</p>
[ { "answer_id": 385991, "author": "Kirtan", "author_id": 203555, "author_profile": "https://wordpress.stackexchange.com/users/203555", "pm_score": 1, "selected": false, "text": "<pre><code>**check via post ID for a specific page or post**\n\n\n$post_id = $_GET['post'] ? $_GET['post'] : $_...
2021/04/01
[ "https://wordpress.stackexchange.com/questions/385988", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/171613/" ]
I am wondering how to add meta box in WordPress specific page admin, I mean when I create meta\_box with code snippet below provided from source tutorial is really perfect and effective but one thing that I need to control is display that meta\_box only in specific page for instance: pretend I have two page in my WordPress project named Home and About. When I create meta\_box by default the meta\_box that I add will display on the same page admin back end, imagined when I clicked edit button to Home and About page my meta box will appear in both page. What I want is make a meta\_box only show in “Home” admin backend page when I click the edit page. My goal is set different meta\_box in every different page, meaning the users specially the blog editor expect different meta\_box\_field in different page when they click edit button in each page, That is the thing I can’t figure out can you help me to solve that problem ``` /* Plugin Name: Meta Box Example Description: Example demonstrating how to add Meta Boxes. Plugin URI: https://plugin-planet.com/ Author: Jeff Starr Version: 1.0 */ // register meta box function myplugin_add_meta_box() { $post_types = array( 'post', 'page' ); foreach ( $post_types as $post_type ) { add_meta_box( 'myplugin_meta_box', // Unique ID of meta box 'MyPlugin Meta Box', // Title of meta box 'myplugin_display_meta_box', // Callback function $post_type // Post type ); } } add_action( 'add_meta_boxes', 'myplugin_add_meta_box' ); // display meta box function myplugin_display_meta_box( $post ) { $value = get_post_meta( $post->ID, '_myplugin_meta_key', true ); wp_nonce_field( basename( __FILE__ ), 'myplugin_meta_box_nonce' ); ?> <label for="myplugin-meta-box">Field Description</label> <select id="myplugin-meta-box" name="myplugin-meta-box"> <option value="">Select option...</option> <option value="option-1" <?php selected( $value, 'option-1' ); ?>>Option 1</option> <option value="option-2" <?php selected( $value, 'option-2' ); ?>>Option 2</option> <option value="option-3" <?php selected( $value, 'option-3' ); ?>>Option 3</option> </select> <?php } // save meta box function myplugin_save_meta_box( $post_id ) { $is_autosave = wp_is_post_autosave( $post_id ); $is_revision = wp_is_post_revision( $post_id ); $is_valid_nonce = false; if ( isset( $_POST[ 'myplugin_meta_box_nonce' ] ) ) { if ( wp_verify_nonce( $_POST[ 'myplugin_meta_box_nonce' ], basename( __FILE__ ) ) ) { $is_valid_nonce = true; } } if ( $is_autosave || $is_revision || !$is_valid_nonce ) return; if ( array_key_exists( 'myplugin-meta-box', $_POST ) ) { update_post_meta( $post_id, // Post ID '_myplugin_meta_key', // Meta key sanitize_text_field( $_POST[ 'myplugin-meta-box' ] ) // Meta value ); } } add_action( 'save_post', 'myplugin_save_meta_box' ); ``` Is there any condition or function to do that you will recommend?
``` /* Add meta boxs for particular pages */ function meta_set_particular_page() { $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID']; $current_page_title = get_the_title($post_id); if ($current_page_title == 'home') { add_meta_box('Home_page', 'Home Name:', 'only_home', 'page', 'side', 'core'); } if($current_page_title == 'about'){ add_meta_box('About_page', 'About Name:', 'only_about', 'page', 'side', 'core'); } } add_action('add_meta_boxes', 'meta_set_particular_page'); /* Add custom meta box for home page */ function only_home($post) { $home_page = esc_html(get_post_meta($post->ID, 'home_page', true)); ?> <table style="width:100%;"> <tr> <td style="width: 20%">Name</td> <td style="width: 40%"> <input type="text" size="70" name="home_page" placeholder="Home Name" value="<?php echo $home_page; ?>"> </td> </tr> </table> <?php } /*Add custom meta box for about page*/ function only_about($post) { $about_page = esc_html(get_post_meta($post->ID, 'about_page', true)); ?> <table style="width:100%;"> <tr> <td style="width: 20%">Name</td> <td style="width: 40%"> <input type="text" size="50" name="about_page" placeholder="About Name" value="<?php echo $about_page; ?>"> </td> </tr> </table> <?php } /*Save custom post meta values*/ function custom_metabox_fields($custom_metabox_id) { if (isset($_POST['home_page'])) { update_post_meta($custom_metabox_id, 'home_page', $_POST['home_page']); } if (isset($_POST['about_page'])) { update_post_meta($custom_metabox_id, 'about_page', $_POST['about_page']); } } add_action('save_post', 'custom_metabox_fields', 10, 2); ```
386,039
<p>As the title, I would like to save the post with the specific image as the featured image, when it is new published. Also I would like to save different images which is filtered by categories.</p> <p>I have wrote the code below, it does not work as I wish to.</p> <pre><code>add_action('save_post', 'wp_force_featured_image', 20, 2); function wp_force_featured_image($post_id, $post) { if( $post-&gt;post_type == 'post' &amp;&amp; $post-&gt;post_status == 'publish' ) { if(!isset($_POST['_thumbnail_id'])) { $categories = get_the_category( $post-&gt;slug ); if ( $categories = 'news' ) { add_post_meta( $post_id, '_thumbnail_id', '3135' ); } elseif ($categories = 'bi' ) { add_post_meta( $post_id, '_thumbnail_id', '3138' ); } } } } </code></pre> <p>I tried to get the category slug for comparing.</p> <p>Any advises will help me a lot.</p> <p>Thank you for your support in advance.</p>
[ { "answer_id": 386067, "author": "drdogbot7", "author_id": 105124, "author_profile": "https://wordpress.stackexchange.com/users/105124", "pm_score": 0, "selected": false, "text": "<p>If you're building a custom theme and you just want to have some fallback images, an easier approach migh...
2021/04/01
[ "https://wordpress.stackexchange.com/questions/386039", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/204287/" ]
As the title, I would like to save the post with the specific image as the featured image, when it is new published. Also I would like to save different images which is filtered by categories. I have wrote the code below, it does not work as I wish to. ``` add_action('save_post', 'wp_force_featured_image', 20, 2); function wp_force_featured_image($post_id, $post) { if( $post->post_type == 'post' && $post->post_status == 'publish' ) { if(!isset($_POST['_thumbnail_id'])) { $categories = get_the_category( $post->slug ); if ( $categories = 'news' ) { add_post_meta( $post_id, '_thumbnail_id', '3135' ); } elseif ($categories = 'bi' ) { add_post_meta( $post_id, '_thumbnail_id', '3138' ); } } } } ``` I tried to get the category slug for comparing. Any advises will help me a lot. Thank you for your support in advance.
Your conditional is in trouble. `get_the_category()` returns an **object**, use foreach to find the specific category. In addition, you assigned a value to the `$categories` variable, to compare you must use the [**comparison operators**](https://www.php.net/manual/en/language.operators.comparison.php) ( Ex: == or === ) I refactored the code and adapted it to your case, I hope it helps. ``` add_action( 'save_post', 'wp_force_featured_image', 10, 3 ); function wp_force_featured_image( $post_id, $post, $update ) { if ( $update ) { return; } if ( $post->post_type !== 'post' ) { return; } if ( $post->post_status !== 'publish' ) { return; } $has_post_thumbnail = get_post_thumbnail_id( $post_id ); if ( ! empty( $has_post_thumbnail ) ) { return; } $categories = get_the_category( $post_id ); $thumbnail_id = false; foreach ( $categories as $category ) { if ( $category->slug === 'news' ) { $thumbnail_id = 3135; break; } if ( $category->slug === 'bi' ) { $thumbnail_id = 3138; break; } } if( $thumbnail_id ) { add_post_meta( $post_id, '_thumbnail_id', $thumbnail_id, true ); } } ```
386,059
<p>I try to use the hook wp_head on a template page but this does not work</p> <pre><code>add_action('wp_head', 'to_head'); function to_head(){ //do stuff } </code></pre> <p>I placed this code on a template part what is called by <code>get_template_part( 'temp-parts/content/pages/catalog' );</code></p> <p>Can you use the hook only on the functions.php or is there a way to use this on any page</p>
[ { "answer_id": 386067, "author": "drdogbot7", "author_id": 105124, "author_profile": "https://wordpress.stackexchange.com/users/105124", "pm_score": 0, "selected": false, "text": "<p>If you're building a custom theme and you just want to have some fallback images, an easier approach migh...
2021/04/02
[ "https://wordpress.stackexchange.com/questions/386059", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/162095/" ]
I try to use the hook wp\_head on a template page but this does not work ``` add_action('wp_head', 'to_head'); function to_head(){ //do stuff } ``` I placed this code on a template part what is called by `get_template_part( 'temp-parts/content/pages/catalog' );` Can you use the hook only on the functions.php or is there a way to use this on any page
Your conditional is in trouble. `get_the_category()` returns an **object**, use foreach to find the specific category. In addition, you assigned a value to the `$categories` variable, to compare you must use the [**comparison operators**](https://www.php.net/manual/en/language.operators.comparison.php) ( Ex: == or === ) I refactored the code and adapted it to your case, I hope it helps. ``` add_action( 'save_post', 'wp_force_featured_image', 10, 3 ); function wp_force_featured_image( $post_id, $post, $update ) { if ( $update ) { return; } if ( $post->post_type !== 'post' ) { return; } if ( $post->post_status !== 'publish' ) { return; } $has_post_thumbnail = get_post_thumbnail_id( $post_id ); if ( ! empty( $has_post_thumbnail ) ) { return; } $categories = get_the_category( $post_id ); $thumbnail_id = false; foreach ( $categories as $category ) { if ( $category->slug === 'news' ) { $thumbnail_id = 3135; break; } if ( $category->slug === 'bi' ) { $thumbnail_id = 3138; break; } } if( $thumbnail_id ) { add_post_meta( $post_id, '_thumbnail_id', $thumbnail_id, true ); } } ```
386,069
<p>I wrote a WordPress theme for a non-profit where I use templates to style individual pages. I select the template for an individual page in the editor on the right:</p> <p><a href="https://i.stack.imgur.com/znMdl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/znMdl.png" alt="Template selection in editor" /></a></p> <p>For styling of a template page, I simply add a css class to the outer most element in the template and style the rest based on the presence of this class - in this example <code>layout-krankenbett-gruen</code>:</p> <p><strong>templates/KrankenbettGruen.php</strong>:</p> <pre><code>&lt;?php /* Template Name: Krankenbett grün */ ?&gt; &lt;?php get_header(); ?&gt; &lt;main class=&quot;layout-krankenbett-gruen&quot;&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'content', get_post_format() ); endwhile; endif; ?&gt; &lt;/main&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>I can style the page similar to the display in the editor using this code in <code>functions.php</code></p> <pre><code>// enable style sheet for normal page display also in editor add_theme_support('editor-styles'); add_editor_style('style.css'); </code></pre> <p>such that all styles that get applied to the page get also applied in the editor.</p> <p>I want to have the editor also show the templates as they look on the page later. But somehow the css tag which I add for the template is not present in the editor and therefor the display of the template in the editor is not correct.</p> <p>How can I recognize a template in the editor such that I can display it in the editor in the same style as on the page?</p> <p><strong>Update:</strong></p> <p>I saw that the Twenty Twenty Theme also has Templates (Standard-Template, Cover-Template and Template for wide pages). If I change the template in this Theme, the page in the editor does not change, but the page itself does. Is that intended behavior? I feel like the user would like to see how a template looks (in the editor) before he applies it. Am I getting it wrong?</p>
[ { "answer_id": 386215, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 1, "selected": false, "text": "<p>welcome to this forum. :-)</p>\n<p>I'm not an expert, BUT I did do something similar by following the instruct...
2021/04/02
[ "https://wordpress.stackexchange.com/questions/386069", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/198618/" ]
I wrote a WordPress theme for a non-profit where I use templates to style individual pages. I select the template for an individual page in the editor on the right: [![Template selection in editor](https://i.stack.imgur.com/znMdl.png)](https://i.stack.imgur.com/znMdl.png) For styling of a template page, I simply add a css class to the outer most element in the template and style the rest based on the presence of this class - in this example `layout-krankenbett-gruen`: **templates/KrankenbettGruen.php**: ``` <?php /* Template Name: Krankenbett grün */ ?> <?php get_header(); ?> <main class="layout-krankenbett-gruen"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'content', get_post_format() ); endwhile; endif; ?> </main> <?php get_footer(); ?> ``` I can style the page similar to the display in the editor using this code in `functions.php` ``` // enable style sheet for normal page display also in editor add_theme_support('editor-styles'); add_editor_style('style.css'); ``` such that all styles that get applied to the page get also applied in the editor. I want to have the editor also show the templates as they look on the page later. But somehow the css tag which I add for the template is not present in the editor and therefor the display of the template in the editor is not correct. How can I recognize a template in the editor such that I can display it in the editor in the same style as on the page? **Update:** I saw that the Twenty Twenty Theme also has Templates (Standard-Template, Cover-Template and Template for wide pages). If I change the template in this Theme, the page in the editor does not change, but the page itself does. Is that intended behavior? I feel like the user would like to see how a template looks (in the editor) before he applies it. Am I getting it wrong?
welcome to this forum. :-) I'm not an expert, BUT I did do something similar by following the instructions and tutorials I found at these links below, hopefully these will help guide you. In a nutshell, you have to go beyond just enabling the stylesheet in the editor, you have actually add a stylesheet specifically for the editor (editor-styles.css) and declare your styles in that (being sure to keep them the same as your front-facing style.css file). Also, way below I put my own code if it also helps to serve as an example. Good luck!! Tutorials: <https://codex.wordpress.org/TinyMCE_Custom_Styles> <https://developer.wordpress.org/reference/functions/add_editor_style/> <http://wplift.com/how-to-add-custom-styles-to-the-wordpress-visual-post-editor> *(note this last link is a great tutorial but adding the style declarations that way didn’t work, I had to use the code below)* More tutorials: <https://www.wpkube.com/add-dropdown-css-style-selector-visual-editor/> <http://www.wpbeginner.com/wp-tutorials/how-to-add-custom-styles-to-wordpress-visual-editor/> My use: ``` // Unhides the Styles drop down selector in the 2nd toolbar in Visual Editor function bai_tinymce_buttons( $buttons ) { //Add style selector to the beginning of the toolbar array_unshift( $buttons, 'styleselect' ); return $buttons; } add_filter( 'mce_buttons_2', 'bai_tinymce_buttons' ); // Adds some styles to the visual editor formats (styles) dropdown, styles are in editor-style.css function bai_mce_before_init_insert_formats( $init_array ) { // Define the style_formats array $style_formats = array( // Each array child is a format with it's own settings array( 'title' => '.pull-right', 'block' => 'blockquote', 'classes' => 'pull-right', 'wrapper' => true, ), array( 'title' => '.tips', 'block' => 'blockquote', 'classes' => 'tips', 'wrapper' => true, ), array( 'title' => '.nutshell', 'block' => 'div', 'classes' => 'nutshell', 'wrapper' => true, ), ); // Insert the array, JSON ENCODED, into 'style_formats' $init_array['style_formats'] = json_encode( $style_formats ); return $init_array; } add_filter( 'tiny_mce_before_init', 'bai_mce_before_init_insert_formats' ); ```
386,140
<p>I used the snippet below to lock out all administrators and editors except myself</p> <pre><code>if ( is_user_logged_in() ){ $current_user = wp_get_current_user() ; if ( in_array( 'administrator', (array) $current_user-&gt;roles ) || in_array( 'editor', (array) $current_user-&gt;roles )) { if ($current_user-&gt;user_login != 'sheila' ){ wp_logout(); return new WP_Error( 'login_again_please', 'Please log in again' ); } } } </code></pre> <p>When I try to add a second user in the second if statement we are both locked out:</p> <pre><code>if ( is_user_logged_in() ){ $current_user = wp_get_current_user() ; if ( in_array( 'administrator', (array) $current_user-&gt;roles ) || in_array( 'editor', (array) $current_user-&gt;roles )) { if (($current_user-&gt;user_login != 'john' ) || ($current_user-&gt;user_login != 'sheila' )){ wp_logout(); return new WP_Error( 'login_again_please', 'Please log in again' ); } } } </code></pre> <p>How do I fix the above snippet to allow two administrators/editors with specific usernames to login or can I have an alternative with the same outcome?</p>
[ { "answer_id": 386215, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 1, "selected": false, "text": "<p>welcome to this forum. :-)</p>\n<p>I'm not an expert, BUT I did do something similar by following the instruct...
2021/04/04
[ "https://wordpress.stackexchange.com/questions/386140", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106290/" ]
I used the snippet below to lock out all administrators and editors except myself ``` if ( is_user_logged_in() ){ $current_user = wp_get_current_user() ; if ( in_array( 'administrator', (array) $current_user->roles ) || in_array( 'editor', (array) $current_user->roles )) { if ($current_user->user_login != 'sheila' ){ wp_logout(); return new WP_Error( 'login_again_please', 'Please log in again' ); } } } ``` When I try to add a second user in the second if statement we are both locked out: ``` if ( is_user_logged_in() ){ $current_user = wp_get_current_user() ; if ( in_array( 'administrator', (array) $current_user->roles ) || in_array( 'editor', (array) $current_user->roles )) { if (($current_user->user_login != 'john' ) || ($current_user->user_login != 'sheila' )){ wp_logout(); return new WP_Error( 'login_again_please', 'Please log in again' ); } } } ``` How do I fix the above snippet to allow two administrators/editors with specific usernames to login or can I have an alternative with the same outcome?
welcome to this forum. :-) I'm not an expert, BUT I did do something similar by following the instructions and tutorials I found at these links below, hopefully these will help guide you. In a nutshell, you have to go beyond just enabling the stylesheet in the editor, you have actually add a stylesheet specifically for the editor (editor-styles.css) and declare your styles in that (being sure to keep them the same as your front-facing style.css file). Also, way below I put my own code if it also helps to serve as an example. Good luck!! Tutorials: <https://codex.wordpress.org/TinyMCE_Custom_Styles> <https://developer.wordpress.org/reference/functions/add_editor_style/> <http://wplift.com/how-to-add-custom-styles-to-the-wordpress-visual-post-editor> *(note this last link is a great tutorial but adding the style declarations that way didn’t work, I had to use the code below)* More tutorials: <https://www.wpkube.com/add-dropdown-css-style-selector-visual-editor/> <http://www.wpbeginner.com/wp-tutorials/how-to-add-custom-styles-to-wordpress-visual-editor/> My use: ``` // Unhides the Styles drop down selector in the 2nd toolbar in Visual Editor function bai_tinymce_buttons( $buttons ) { //Add style selector to the beginning of the toolbar array_unshift( $buttons, 'styleselect' ); return $buttons; } add_filter( 'mce_buttons_2', 'bai_tinymce_buttons' ); // Adds some styles to the visual editor formats (styles) dropdown, styles are in editor-style.css function bai_mce_before_init_insert_formats( $init_array ) { // Define the style_formats array $style_formats = array( // Each array child is a format with it's own settings array( 'title' => '.pull-right', 'block' => 'blockquote', 'classes' => 'pull-right', 'wrapper' => true, ), array( 'title' => '.tips', 'block' => 'blockquote', 'classes' => 'tips', 'wrapper' => true, ), array( 'title' => '.nutshell', 'block' => 'div', 'classes' => 'nutshell', 'wrapper' => true, ), ); // Insert the array, JSON ENCODED, into 'style_formats' $init_array['style_formats'] = json_encode( $style_formats ); return $init_array; } add_filter( 'tiny_mce_before_init', 'bai_mce_before_init_insert_formats' ); ```
386,280
<p>I need some guidance on making a wordpress posts query responsive to user meta data, and whether it’s possible to do what I want within the query itself, or if further work is needed in the database first?</p> <p>Every user on my site has a meta field with the meta key <strong>language_level</strong>. These broadly correspond to beginner, intermediate, advanced.</p> <p>The post-login homepage of my site has a feed of recommended content. This is composed of posts tagged with a custom taxonomy, <strong>Recommended Resource</strong>, with tags that correspond to those user levels. Ie Beginner recommendations, Intermediate recommendations etc.</p> <p>The goal is to have a posts listing where:</p> <ul> <li>Beginner users see posts tagged as beginner</li> <li>Intermediate users see posts tagged as intermediate</li> <li>Advanced users see posts tagged as advanced</li> </ul> <p>I’m currently using the query below in my functions to pull through all posts….</p> <pre><code>add_action( 'elementor/query/article_video_together', function( $query ) { $query-&gt;set( 'post_type', [ 'article', 'video' ] ); } ); </code></pre> <p>… can I achieve my goal through a single query, adapted from above or does there need to be a relationship between the meta field and the taxonomy first?</p> <p>I've asked this question in several places without getting a clear response, so I'm wondering if it's more complicated than it appears? Any guidance much appreciated.</p>
[ { "answer_id": 386193, "author": "Daniel Loureiro", "author_id": 149505, "author_profile": "https://wordpress.stackexchange.com/users/149505", "pm_score": 1, "selected": false, "text": "<p>The HTML of a WordPress page is a mix of many sources. Parts of it come from plugins, other parts f...
2021/04/07
[ "https://wordpress.stackexchange.com/questions/386280", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/204530/" ]
I need some guidance on making a wordpress posts query responsive to user meta data, and whether it’s possible to do what I want within the query itself, or if further work is needed in the database first? Every user on my site has a meta field with the meta key **language\_level**. These broadly correspond to beginner, intermediate, advanced. The post-login homepage of my site has a feed of recommended content. This is composed of posts tagged with a custom taxonomy, **Recommended Resource**, with tags that correspond to those user levels. Ie Beginner recommendations, Intermediate recommendations etc. The goal is to have a posts listing where: * Beginner users see posts tagged as beginner * Intermediate users see posts tagged as intermediate * Advanced users see posts tagged as advanced I’m currently using the query below in my functions to pull through all posts…. ``` add_action( 'elementor/query/article_video_together', function( $query ) { $query->set( 'post_type', [ 'article', 'video' ] ); } ); ``` … can I achieve my goal through a single query, adapted from above or does there need to be a relationship between the meta field and the taxonomy first? I've asked this question in several places without getting a clear response, so I'm wondering if it's more complicated than it appears? Any guidance much appreciated.
The HTML of a WordPress page is a mix of many sources. Parts of it come from plugins, other parts from the main template, others from the database, others from the core. They can also come from widgets, template options, and so on. Unfortunately, WordPress pages are not on specific files that you can open and edit their HTML. In most cases, the pages are Frankensteins' monsters built from many different sources programmatically. And that's not a bad thing - the power of WordPress comes from its extensibility, which is a consequence of this design. To change an HTML on WordPress, you need to track what is generating that HTML. Then, you modify it - either via the admin dashboard or programmatically (not by writing a bunch of HTML, but by calling PHP functions and methods). If you are lucky, you may be able to change what you want on the admin dashboard with no code. If the content you want to change is not changeable through the admin dashboard, you will need to do some coding. As you pointed, it would be best if you use child themes to avoid updates to overwrite your changes. But if you got to this point, you need to understand how to code for WordPress first. You need to understand hooks, actions, filters, and so on. A good recommendation is the book "Professional WordPress Plugin Development" by Ozh Richard. He is famous in the community and even referred to on the official WordPress documentation. But be aware that the learning curve can take some time.
386,514
<p>I've written a custom plugin, <code>ta-intentclicks</code> which is used as a shortcode:</p> <pre><code>[ta-intentclicks count=&quot;3&quot; category=&quot;SEC-EDR&quot;...] </code></pre> <p>Within this shortcode I'd like to use another shortcode that I can use as a helper. For example; in one of the PHP templates within my plugin.</p> <pre><code>[ta-intentclicks-link url=&quot;$list_item['link']&quot;]Visit website[/ta-intentclicks-link] [ta-intentclicks-link url=&quot;$list_item['link']&quot;]&lt;img src=&quot;foo&quot; /&gt;[/ta-intentclicks-link] </code></pre> <p>Which would output this:</p> <pre><code>&lt;a href=&quot;&lt;the URL&gt;&quot; rel=&quot;sponsored&quot; target=&quot;_blank&quot; class=&quot;icp-list-link&quot;&gt;Visit website&lt;/a&gt; &lt;a href=&quot;&lt;the URL&gt;&quot; rel=&quot;sponsored&quot; target=&quot;_blank&quot; class=&quot;icp-list-link&quot;&gt;&lt;img src=&quot;foo&quot; /&gt;&lt;/a&gt; </code></pre> <p>Here's a quick directory snapshot to help illustrate my question. <a href="https://i.stack.imgur.com/kAV1b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kAV1b.png" alt="enter image description here" /></a></p> <p>The plugin entry point is <code>includes/class-ta-intentclicks.php</code> which defines the shortcode and runs it, calling the Layout class along the way.</p> <pre><code>class TaIntentClicks { function __construct() { add_shortcode('ta-intentclicks', array($this, 'run')); } function run($attributes = []) { ... do some stuff return $this-&gt;layout-&gt;render($response, $layoutAttributes, $dataAttributes); } } class TAIntentClicksLayout { function parse($stuff, $template) { ob_start(); $output = ''; include $template; $output = ob_get_contents(); ob_end_clean(); return $output; } function render($response, $layoutAttributes, $dataAttributes) { return $this-&gt;parse( $response, $layoutAttributes, $this-&gt;getTemplate($layoutAttributes), $dataAttributes ); } } </code></pre> <p>I've seen examples of people calling &quot;do_shortcode&quot; to execute a shortcode, but I'm unclear where the shortcode function goes in my case, OR where to place the &quot;do_shortcode&quot; call.</p> <p>Can anyone offer guidance here? This is my first plugin and I'm a bit lost as to how and implement this functionality. Thanks in advance.</p>
[ { "answer_id": 386700, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<p>If I understand it correctly, inside the <em>shortcode template</em>, you could do something like this:</p...
2021/04/12
[ "https://wordpress.stackexchange.com/questions/386514", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/185653/" ]
I've written a custom plugin, `ta-intentclicks` which is used as a shortcode: ``` [ta-intentclicks count="3" category="SEC-EDR"...] ``` Within this shortcode I'd like to use another shortcode that I can use as a helper. For example; in one of the PHP templates within my plugin. ``` [ta-intentclicks-link url="$list_item['link']"]Visit website[/ta-intentclicks-link] [ta-intentclicks-link url="$list_item['link']"]<img src="foo" />[/ta-intentclicks-link] ``` Which would output this: ``` <a href="<the URL>" rel="sponsored" target="_blank" class="icp-list-link">Visit website</a> <a href="<the URL>" rel="sponsored" target="_blank" class="icp-list-link"><img src="foo" /></a> ``` Here's a quick directory snapshot to help illustrate my question. [![enter image description here](https://i.stack.imgur.com/kAV1b.png)](https://i.stack.imgur.com/kAV1b.png) The plugin entry point is `includes/class-ta-intentclicks.php` which defines the shortcode and runs it, calling the Layout class along the way. ``` class TaIntentClicks { function __construct() { add_shortcode('ta-intentclicks', array($this, 'run')); } function run($attributes = []) { ... do some stuff return $this->layout->render($response, $layoutAttributes, $dataAttributes); } } class TAIntentClicksLayout { function parse($stuff, $template) { ob_start(); $output = ''; include $template; $output = ob_get_contents(); ob_end_clean(); return $output; } function render($response, $layoutAttributes, $dataAttributes) { return $this->parse( $response, $layoutAttributes, $this->getTemplate($layoutAttributes), $dataAttributes ); } } ``` I've seen examples of people calling "do\_shortcode" to execute a shortcode, but I'm unclear where the shortcode function goes in my case, OR where to place the "do\_shortcode" call. Can anyone offer guidance here? This is my first plugin and I'm a bit lost as to how and implement this functionality. Thanks in advance.
If I understand it correctly, inside the *shortcode template*, you could do something like this: ```php echo do_shortcode( '[ta-intentclicks-link url="' . esc_url( $list_item['link'] ) . '"]Visit website[/ta-intentclicks-link]' ); ``` But then, **instead of having to use [`do_shortcode()`](https://developer.wordpress.org/reference/functions/do_shortcode/)**, you could actually simply call the shortcode callback from the (shortcode) template ( which then eliminates the need to find and parse shortcodes in the content or the first parameter for `do_shortcode()` ): * If you registered the shortcode like so: ```php add_shortcode( 'ta-intentclicks-link', 'my_shortcode' ); function my_shortcode( $atts = array(), $content = null ) { $atts = shortcode_atts( array( 'url' => '', ), $atts ); if ( ! empty( $atts['url'] ) ) { return sprintf( '<a href="%s" target="_blank">%s</a>', esc_url( $atts['url'] ), esc_html( $content ? $content : $atts['url'] ) ); } return ''; } ``` * Then in the shortcode template, you could simply call the `my_shortcode()` function above: ```php echo my_shortcode( array( 'url' => $list_item['link'], ), 'Visit website' ); ``` But if that's not what you meant, or if you had a shortcode in a shortcode like `[caption]Caption: [myshortcode][/caption]`, then as said in the [Shortcode API on the WordPress Codex website](https://codex.wordpress.org/Shortcode_API#Enclosing_vs_self-closing_shortcodes): > > If the enclosing shortcode is intended to permit other shortcodes in > its output, the handler function can call > [`do_shortcode()`](https://developer.wordpress.org/reference/functions/do_shortcode/) > recursively: > > > > ``` > function caption_shortcode( $atts, $content = null ) { > return '<span class="caption">' . do_shortcode($content) . '</span>'; > } > > ``` > > ... your `run()` function (or the shortcode callback) would need to capture the second parameter passed to the function, i.e. `$content` as you could see above, and once you have that parameter (or its value), you can then call `do_shortcode()`. (With the above "caption" shortcode example, the `$content` is the `Caption: [myshortcode]`.) So for example, your `run()` function be written like so… ```php // 1. Define the $content variable. function run( $attributes = [], $content = null ) { // ... your code (define $response, $layoutAttributes, $dataAttributes, etc.) // 2. Then do something like so: return $this->layout->render( $response, $layoutAttributes, $dataAttributes ) . do_shortcode( $content ); } ``` But if you need further help with that, do let me know in the comments (and preferably, please show the code in your template and explain the variables like the `$response` and `$layoutAttributes`).
386,665
<p>Ok, so I have been using <code>wp plugin update --all</code> in the past with a tee command. There has been no problem in the past, but after I ran an update on my system, everytime I run the command through a pipe, the formatting is messed up. So this is the gist of the command used: <code>wp plugin update --all|awk '/Success/,EOF'| tee &gt;(convert -font Courier -pointsize 14 label:@- img.png)</code> Previously it would produce a flawless output: <a href="https://i.stack.imgur.com/Wv0PP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wv0PP.png" alt="enter image description here" /></a></p> <p>However, now when I pipe, even if I leave out the convert command, say something like this: `wp plugin update --all | tee test.txt' the output is messed up.... <a href="https://i.stack.imgur.com/PSLei.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PSLei.png" alt="enter image description here" /></a></p> <p>or</p> <p><a href="https://i.stack.imgur.com/1BAUP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1BAUP.png" alt="enter image description here" /></a></p> <p>Has anyone got any ideas....driving me a bit crazy...</p>
[ { "answer_id": 386667, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>WP CLI needs to know some things about the terminal it's running in to format the table, aka the TTY.</p>\n<p...
2021/04/15
[ "https://wordpress.stackexchange.com/questions/386665", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/204949/" ]
Ok, so I have been using `wp plugin update --all` in the past with a tee command. There has been no problem in the past, but after I ran an update on my system, everytime I run the command through a pipe, the formatting is messed up. So this is the gist of the command used: `wp plugin update --all|awk '/Success/,EOF'| tee >(convert -font Courier -pointsize 14 label:@- img.png)` Previously it would produce a flawless output: [![enter image description here](https://i.stack.imgur.com/Wv0PP.png)](https://i.stack.imgur.com/Wv0PP.png) However, now when I pipe, even if I leave out the convert command, say something like this: `wp plugin update --all | tee test.txt' the output is messed up.... [![enter image description here](https://i.stack.imgur.com/PSLei.png)](https://i.stack.imgur.com/PSLei.png) or [![enter image description here](https://i.stack.imgur.com/1BAUP.png)](https://i.stack.imgur.com/1BAUP.png) Has anyone got any ideas....driving me a bit crazy...
WP CLI needs to know some things about the terminal it's running in to format the table, aka the TTY. But when you pipe, there is no TTY! But you can trick it into thinking there is if you use this bash function: ```sh faketty() { 0</dev/null script --quiet --flush --return --command "$(printf "%q " "$@")" /dev/null } ``` then you can run WP CLI commands and it will think it’s running in an interactive shell, not a pipe, e.g.: ```sh faketty wp post list | more ```
386,689
<p>I need to show history of post changes (post revisions) at the end of post content.</p> <p>I saw tips about &quot;Last modified by/date&quot; feature but I need to <strong>show the table of all changes (revisions) done on post (Date/author/content- if possible).</strong></p> <p>It's formally required for public institutions and I'm bit surprised there are nothing on Google. Is there a way to do that?</p>
[ { "answer_id": 386707, "author": "Dave White", "author_id": 175096, "author_profile": "https://wordpress.stackexchange.com/users/175096", "pm_score": 0, "selected": false, "text": "<p>WordPress does not natively do that. You may want to try plugins such as Simple History.</p>\n<p>Check t...
2021/04/15
[ "https://wordpress.stackexchange.com/questions/386689", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/204978/" ]
I need to show history of post changes (post revisions) at the end of post content. I saw tips about "Last modified by/date" feature but I need to **show the table of all changes (revisions) done on post (Date/author/content- if possible).** It's formally required for public institutions and I'm bit surprised there are nothing on Google. Is there a way to do that?
There are many ways to do it, without third party plugins: Shortcode --------- **Cons**: shortcode has to be created, and added to all posts. Child theme template -------------------- **Cons**: theme dependent, and right template has to be modified. Child theme functions.php ------------------------- **Cons**: theme dependent. Plugin in mu-plugins -------------------- **Cons**: none. **Pros**: not theme dependent, easiest to implement. ### Implementation Create file `post-with-revisions.php`, with the following content, and place it in `wp-content/mu-plugins`: ``` <?php function wpse_single_post_with_revisions( $content ) { // Check if we're inside the main loop in a single Post. if ( is_singular() && in_the_loop() && is_main_query() ) { $content .= '<h2>Revisions</h2>'; $revisions = wp_get_post_revisions(); foreach ( $revisions as $rev ) { $date = $rev->post_date; $author = get_author_name( $auth_id = $rev->post_author ); $content .= '<h4>' . $date . ' by ' . $author . '</h4>'; $content .= $rev->post_content; } } return $content; } add_filter( 'the_content', 'wpse_single_post_with_revisions' ); ``` **Note**: revisions will be visible in single post only, not in archives. UPDATE ------ For easier identification of changes between revisions, instead of displaying the content of revisions, we can display differences between them. The modified code follows: ``` <?php function wpse_single_post_with_revisions( $content ) { global $post; // Check if we're inside the main loop in a single Post. if ( is_singular() && in_the_loop() && is_main_query() ) { $content .= '<h2>Revisions</h2>'; $revisions = wp_get_post_revisions(); $ids_to_compare = array(); foreach ( $revisions as $rev ) { $date = $rev->post_date; $author = get_author_name( $auth_id = $rev->post_author ); $id = $rev->ID; array_push( $ids_to_compare, (int) $id ); $content .= '<strong>ID: ' . $id .' - ' . $date . ' by ' . $author . '</strong><br>'; //$content .= $rev->post_content; } $content .= '<h2>Diffs</h2>'; require 'wp-admin/includes/revision.php'; for ( $i = 0; $i <= count( $ids_to_compare ) - 2; $i++ ) { $diffs = wp_get_revision_ui_diff( $post, $ids_to_compare[$i], $ids_to_compare[$i + 1] ); $content .= '<h3>' . $ids_to_compare[$i] . ' to ' . $ids_to_compare[$i + 1] . '</h3>'; if ( is_array( $diffs ) ) { foreach ( $diffs as $diff ) { $content .= $diff['diff']; } } $content .= '<hr>'; } } return $content; } add_filter( 'the_content', 'wpse_single_post_with_revisions' ); ```
386,757
<p>I try to create and run a custom hook on my Wordpress site.</p> <p>In the header.php file I used</p> <pre><code>do_action('somestuff'); </code></pre> <p>On my home.php and page.php I does the add_action like</p> <pre><code>add_action('somestuff', 'testfunc'); function testfunc(){ echo 'hello'; } </code></pre> <p>But the text is not showing? What I am doing wrong?</p>
[ { "answer_id": 386758, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>The problem is the order of execution. <strong>The order things run matters.</strong></p>\n<p>For your code ...
2021/04/16
[ "https://wordpress.stackexchange.com/questions/386757", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/201091/" ]
I try to create and run a custom hook on my Wordpress site. In the header.php file I used ``` do_action('somestuff'); ``` On my home.php and page.php I does the add\_action like ``` add_action('somestuff', 'testfunc'); function testfunc(){ echo 'hello'; } ``` But the text is not showing? What I am doing wrong?
The problem is the order of execution. **The order things run matters.** For your code to function, it would require either `add_action` to implement time travel several microseconds into the past so that it can add the hook before it ran, or it would require `do_action` to implement precognition so that it knows about `add_action` calls in the future that have not happened yet. By putting your `add_action` call in `home.php` or other templates that occur *after* the `header.php` runs, you are telling WordPress to execute code when a hook fires that has already fired. It is the equivalent to arriving at an airport and trying to board a flight that has already left. You need to add the actions *before* the action runs. A useful mental model is to think of actions as events. When you specify `add_action` of `add_filter` it is the same as saying *"from now on, when this action runs, do this"*. This is also why you do not see themes add filters and actions inside template files. These go in plugins and `functions.php` because those files are loaded earlier.
386,966
<p>1st post on this forum so sorry if not enough detail passed.</p> <p>I am trying to use WP_Query to gather CPT that have an Advanced Custom Field (WP Plugin) of &quot;End Date&quot;, the field is a date picker. I want the Query to return all posts that are before their individual &quot;End Date&quot; and all posts that don't have an &quot;End Date&quot; incase the user doesn't know/want to add one. Basically, I don't want posts to make it through the query if the &quot;End Date&quot; has passed.</p> <p>Below is what I have tried so far with little success</p> <pre><code> $meta_query = array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'vacancy_end_date', 'value' =&gt; date('Ymd'), 'type' =&gt; 'DATE', 'compare' =&gt; '&gt;=' ), array( 'key' =&gt; 'vacancy_end_date', 'value' =&gt; '', 'type' =&gt; 'DATE', 'compare' =&gt; '=' ) ); $args = [ 'post_type' =&gt; 'vacancy', // origionally 9 'posts_per_page' =&gt; -1, 'meta_key' =&gt; 'vacancy_end_date', 'meta_query' =&gt; $meta_query, ]; $posts = new \WP_Query($args); </code></pre>
[ { "answer_id": 386758, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>The problem is the order of execution. <strong>The order things run matters.</strong></p>\n<p>For your code ...
2021/04/21
[ "https://wordpress.stackexchange.com/questions/386966", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/205247/" ]
1st post on this forum so sorry if not enough detail passed. I am trying to use WP\_Query to gather CPT that have an Advanced Custom Field (WP Plugin) of "End Date", the field is a date picker. I want the Query to return all posts that are before their individual "End Date" and all posts that don't have an "End Date" incase the user doesn't know/want to add one. Basically, I don't want posts to make it through the query if the "End Date" has passed. Below is what I have tried so far with little success ``` $meta_query = array( 'relation' => 'OR', array( 'key' => 'vacancy_end_date', 'value' => date('Ymd'), 'type' => 'DATE', 'compare' => '>=' ), array( 'key' => 'vacancy_end_date', 'value' => '', 'type' => 'DATE', 'compare' => '=' ) ); $args = [ 'post_type' => 'vacancy', // origionally 9 'posts_per_page' => -1, 'meta_key' => 'vacancy_end_date', 'meta_query' => $meta_query, ]; $posts = new \WP_Query($args); ```
The problem is the order of execution. **The order things run matters.** For your code to function, it would require either `add_action` to implement time travel several microseconds into the past so that it can add the hook before it ran, or it would require `do_action` to implement precognition so that it knows about `add_action` calls in the future that have not happened yet. By putting your `add_action` call in `home.php` or other templates that occur *after* the `header.php` runs, you are telling WordPress to execute code when a hook fires that has already fired. It is the equivalent to arriving at an airport and trying to board a flight that has already left. You need to add the actions *before* the action runs. A useful mental model is to think of actions as events. When you specify `add_action` of `add_filter` it is the same as saying *"from now on, when this action runs, do this"*. This is also why you do not see themes add filters and actions inside template files. These go in plugins and `functions.php` because those files are loaded earlier.
386,994
<p>In order to have two blogs on one website, I was able to put in the menu two categories: DOCUMENTATION and ACTUALITES. My problem is in the header. The titles are displayed well however for both categories, the titles correspond to the title of the last article of the page... You can see an example in the picture (You will see that the CONTACT page is OK but for the DOCUMENTATION and ACTUALITES pages the titles are those of the last article). I would like to replace these article titles with those of the DOCUMENTATION and ACTUALITES categories. I think I have found the problem code but I don't know how to solve it.</p> <pre><code>&lt;?php if ( is_front_page() ) { ?&gt; &lt;div class=&quot;bloc-header-home&quot;&gt; &lt;span class=&quot;decouvrez&quot;&gt;Découvrez&lt;/span&gt; &lt;h1&gt;La chasse&lt;/h1&gt; &lt;span class=&quot;avantages&quot;&gt;Text description&lt;/span&gt; &lt;a href=&quot;&lt;?php echo get_page_link(221); ?&gt;&quot;&gt;&lt;button class=&quot;header__see-more&quot;&gt;en savoir plus&lt;/button&gt;&lt;/a&gt; &lt;/div&gt; &lt;?php } elseif ( is_home() ) { ?&gt; &lt;h1&gt;Actualités&lt;/h1&gt; &lt;?php } else { ?&gt; &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;?php } ?&gt; </code></pre> <p>Could someone help me? Thanks in advance for your help! Els</p>
[ { "answer_id": 386758, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>The problem is the order of execution. <strong>The order things run matters.</strong></p>\n<p>For your code ...
2021/04/22
[ "https://wordpress.stackexchange.com/questions/386994", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/205282/" ]
In order to have two blogs on one website, I was able to put in the menu two categories: DOCUMENTATION and ACTUALITES. My problem is in the header. The titles are displayed well however for both categories, the titles correspond to the title of the last article of the page... You can see an example in the picture (You will see that the CONTACT page is OK but for the DOCUMENTATION and ACTUALITES pages the titles are those of the last article). I would like to replace these article titles with those of the DOCUMENTATION and ACTUALITES categories. I think I have found the problem code but I don't know how to solve it. ``` <?php if ( is_front_page() ) { ?> <div class="bloc-header-home"> <span class="decouvrez">Découvrez</span> <h1>La chasse</h1> <span class="avantages">Text description</span> <a href="<?php echo get_page_link(221); ?>"><button class="header__see-more">en savoir plus</button></a> </div> <?php } elseif ( is_home() ) { ?> <h1>Actualités</h1> <?php } else { ?> <h1><?php the_title(); ?></h1> <?php } ?> ``` Could someone help me? Thanks in advance for your help! Els
The problem is the order of execution. **The order things run matters.** For your code to function, it would require either `add_action` to implement time travel several microseconds into the past so that it can add the hook before it ran, or it would require `do_action` to implement precognition so that it knows about `add_action` calls in the future that have not happened yet. By putting your `add_action` call in `home.php` or other templates that occur *after* the `header.php` runs, you are telling WordPress to execute code when a hook fires that has already fired. It is the equivalent to arriving at an airport and trying to board a flight that has already left. You need to add the actions *before* the action runs. A useful mental model is to think of actions as events. When you specify `add_action` of `add_filter` it is the same as saying *"from now on, when this action runs, do this"*. This is also why you do not see themes add filters and actions inside template files. These go in plugins and `functions.php` because those files are loaded earlier.
387,040
<p>how to get all capabilities regardless of user roles? so far I am only seeing tutorial of how to get capabilities per user. I want to list all available capabilities in one page.</p>
[ { "answer_id": 387046, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 1, "selected": true, "text": "<p>First, create <code>[all-capabilities]</code> shortcode. Put this code in your theme's <code>fu...
2021/04/22
[ "https://wordpress.stackexchange.com/questions/387040", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/205278/" ]
how to get all capabilities regardless of user roles? so far I am only seeing tutorial of how to get capabilities per user. I want to list all available capabilities in one page.
First, create `[all-capabilities]` shortcode. Put this code in your theme's `functions.php`: ``` function wpse_all_capabilities() { $out = '<style> .flex-columns { column-count: 4; column-gap: 3em; column-rule: 1px solid #000; } </style>'; $out .= '<p class="flex-columns">'; $users = get_users(); foreach ( $users as $user ) { if ( $user->caps['administrator'] ) { $allcaps = array_keys( $user->allcaps ); foreach ( $allcaps as $cap ) { $out .= $cap . '<br>'; } $out .= '</p>'; return $out; } } } add_shortcode( 'all-capabilities', 'wpse_all_capabilities' ); ``` **Update**: it is possible that `Administrator` has some capabilities removed, so we need to scan all users. Modified code follows: ``` function wpse_all_capabilities() { $allcaps = array(); $out = '<style> .flex-columns { column-count: 3; column-gap: 3em; column-rule: 1px solid #000; } h2 { text-align: center; column-span: all; } </style>'; $out .= '<div class="flex-columns">'; $out .= "<h2>All Possible Users' Capabilities<hr></h2><p>"; $users = get_users(); foreach ( $users as $user ) { $caps = array_keys( $user->allcaps ); foreach ( $caps as $cap ) { if ( !in_array( $cap, $allcaps, true ) ) { $num = array_push( $allcaps, $cap ); } } } foreach ( $allcaps as $capability ) { $out .= $capability . '<br>'; } $out .= '</p></div>'; return $out; } add_shortcode( 'all-capabilities', 'wpse_all_capabilities' ); ``` Now, you can use `[all-capabilities]` shortcode on your page.
387,041
<p>I bought woocommerce compare plugin. Unfortunately I can't understand how to apply some filters.</p> <p>For example I want to increase compare limit tom 10. How ı can use below filte?</p> <p>apply_filters( ‘woocommerce_products_compare_max_products’, int ) – sets how many products can be compared at one time. Default is 5.</p> <p>What I tried but not working;</p> <pre><code> function comparelimit($location){ $location = 10; } apply_filters( ‘woocommerce_products_compare_max_products’, 'comparelimit'); </code></pre> <p><a href="https://docs.woocommerce.com/document/woocommerce-products-compare/" rel="nofollow noreferrer">https://docs.woocommerce.com/document/woocommerce-products-compare/</a></p>
[ { "answer_id": 387042, "author": "cameronjonesweb", "author_id": 65582, "author_profile": "https://wordpress.stackexchange.com/users/65582", "pm_score": 2, "selected": false, "text": "<p>You need to return the value in the function for it to be accessible outside that function</p>\n<pre>...
2021/04/22
[ "https://wordpress.stackexchange.com/questions/387041", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/205323/" ]
I bought woocommerce compare plugin. Unfortunately I can't understand how to apply some filters. For example I want to increase compare limit tom 10. How ı can use below filte? apply\_filters( ‘woocommerce\_products\_compare\_max\_products’, int ) – sets how many products can be compared at one time. Default is 5. What I tried but not working; ``` function comparelimit($location){ $location = 10; } apply_filters( ‘woocommerce_products_compare_max_products’, 'comparelimit'); ``` <https://docs.woocommerce.com/document/woocommerce-products-compare/>
You need to return the value in the function for it to be accessible outside that function ``` function comparelimit( $location ) { $location = 10; return $location; } add_filter( 'woocommerce_products_compare_max_products', 'comparelimit' ); ```
387,288
<p>I have this function in my theme's functions.php file:</p> <pre><code>remove_theme_support( 'core-block-patterns' ); </code></pre> <p>which works great but does not remove the Query patterns. How can I include those to be removed in this function?</p> <p><a href="https://i.stack.imgur.com/TgEoa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TgEoa.png" alt="enter image description here" /></a></p>
[ { "answer_id": 387856, "author": "divided", "author_id": 191673, "author_profile": "https://wordpress.stackexchange.com/users/191673", "pm_score": -1, "selected": true, "text": "<p>My fix for this issue is editing the Gutenberg plugin and removing the blocks there. I have not found a wa...
2021/04/27
[ "https://wordpress.stackexchange.com/questions/387288", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/191673/" ]
I have this function in my theme's functions.php file: ``` remove_theme_support( 'core-block-patterns' ); ``` which works great but does not remove the Query patterns. How can I include those to be removed in this function? [![enter image description here](https://i.stack.imgur.com/TgEoa.png)](https://i.stack.imgur.com/TgEoa.png)
My fix for this issue is editing the Gutenberg plugin and removing the blocks there. I have not found a way to cleanly remove them through functions.php.
387,297
<h2>Update:</h2> <p>I got this working with a different hook <code>user_register</code>. It looks like <code>wpmu_activate_user</code> was never triggering.</p> <p><strong>I would still like to have this happen after the user verifies and sets a password though. Can anyone help?</strong></p> <p><strong>Current Code:</strong></p> <blockquote> <pre><code>function xxx_whmcs_signup($user_id) { //Get User Fields $user_info2 = get_userdata($user_id); $id = $user_info2-&gt;ID; //Get Custom Fields $first_name = get_field('first_name_c', 'user_'. $id ); $last_name = get_field('last_name_c', 'user_'. $id ); $address1 = get_field('address_1', 'user_'. $id ); $city = get_field('city', 'user_'. $id ); $state = get_field('state', 'user_'. $id ); $postcode = get_field('postcode', 'user_'. $id ); $country = get_field('country', 'user_'. $id ); $phonenum = get_field('phone_number', 'user_'. $id ); $email = $user_info2-&gt;user_email; $password = $user_info2-&gt;user_pass; // Set WHMCS API Details $whmcsUrl = &quot;xxx&quot;; $apiusername = &quot;xxx&quot;; $apipassword = &quot;xxx&quot;; //Return Fields $postfields = array( 'username' =&gt; $apiusername, //WHMCS Username 'password' =&gt; $apipassword, //WHMCS Password 'action' =&gt; 'AddClient', //WHMCS Action 'firstname' =&gt; $first_name, 'lastname' =&gt; $last_name, 'password2' =&gt; $password, 'email' =&gt; $email, 'address1' =&gt; $address1, 'city' =&gt; $city, 'state' =&gt; $state, 'postcode' =&gt; $postcode, 'country' =&gt; $country, 'phonenumber' =&gt; $phonenum, 'responsetype' =&gt; 'json' ); // Call the API $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $whmcsUrl . 'includes/api.php'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields)); $response = curl_exec($ch); if (curl_error($ch)) { die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch)); } curl_close($ch); // Decode response $jsonData = json_decode($response, true); // Dump array structure for inspection var_dump($jsonData); $file = fopen(&quot;wp-content/plugins/integrations/curloutput.txt&quot;, 'w+'); fwrite($file, $response); fclose($file); } add_action('user_register',&quot;xxx_whmcs_signup&quot;,10,1); </code></pre> </blockquote> <h2>Original post:</h2> <p>I am currently trying to get fields that are populated during the Wordpress Signup process and post them to another API.</p> <p>The fields that I need to get hold of are:</p> <ul> <li>First Name</li> <li>Last Name</li> <li>Email address</li> <li>Password (Hash)</li> <li>and a few other Advanced Custom Fields</li> </ul> <p>When I created the original code, I managed to get it to work perfectly if the user was already logged in and went to a specific page, but I can't seem to get the code to work during the sign up process (probably would have to happen after the activation as that is when the password is set).</p> <p>The entire code is currently:</p> <blockquote> <pre><code>pruned </code></pre> </blockquote> <p>Because the fields are in Advanced Custom Fields, I have also tried:</p> <blockquote> <pre><code>pruned </code></pre> </blockquote> <p>This worked perfectly when the script was running from a shortcode on a page, but of course there are extra hurdles thrown in due to the user not being logged in during the sign up process. I assume this depends on what information I can pass through to my function from a hook.</p> <p>I don't fully understand passing variables through to a function or how I would return the output of $meta so I can see what I'm working with, so it is potentially quite an easy task (fingers crossed). It is also possible that I am not using the correct/best hook?</p> <p>Thanks in advance!</p>
[ { "answer_id": 387856, "author": "divided", "author_id": 191673, "author_profile": "https://wordpress.stackexchange.com/users/191673", "pm_score": -1, "selected": true, "text": "<p>My fix for this issue is editing the Gutenberg plugin and removing the blocks there. I have not found a wa...
2021/04/27
[ "https://wordpress.stackexchange.com/questions/387297", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/205549/" ]
Update: ------- I got this working with a different hook `user_register`. It looks like `wpmu_activate_user` was never triggering. **I would still like to have this happen after the user verifies and sets a password though. Can anyone help?** **Current Code:** > > > ``` > function xxx_whmcs_signup($user_id) { > > //Get User Fields > $user_info2 = get_userdata($user_id); > $id = $user_info2->ID; > > //Get Custom Fields > $first_name = get_field('first_name_c', 'user_'. $id ); > $last_name = get_field('last_name_c', 'user_'. $id ); > $address1 = get_field('address_1', 'user_'. $id ); > $city = get_field('city', 'user_'. $id ); > $state = get_field('state', 'user_'. $id ); > $postcode = get_field('postcode', 'user_'. $id ); > $country = get_field('country', 'user_'. $id ); > $phonenum = get_field('phone_number', 'user_'. $id ); > $email = $user_info2->user_email; > $password = $user_info2->user_pass; > > > // Set WHMCS API Details > $whmcsUrl = "xxx"; > $apiusername = "xxx"; > $apipassword = "xxx"; > > //Return Fields > $postfields = array( > 'username' => $apiusername, //WHMCS Username > 'password' => $apipassword, //WHMCS Password > 'action' => 'AddClient', //WHMCS Action > 'firstname' => $first_name, > 'lastname' => $last_name, > 'password2' => $password, > 'email' => $email, > 'address1' => $address1, > 'city' => $city, > 'state' => $state, > 'postcode' => $postcode, > 'country' => $country, > 'phonenumber' => $phonenum, > 'responsetype' => 'json' > ); > > // Call the API > $ch = curl_init(); > curl_setopt($ch, CURLOPT_URL, $whmcsUrl . 'includes/api.php'); > curl_setopt($ch, CURLOPT_POST, 1); > curl_setopt($ch, CURLOPT_TIMEOUT, 30); > curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); > curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); > curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); > curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields)); > $response = curl_exec($ch); > if (curl_error($ch)) { > die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch)); > } > curl_close($ch); > > // Decode response > $jsonData = json_decode($response, true); > > > // Dump array structure for inspection > var_dump($jsonData); > > $file = fopen("wp-content/plugins/integrations/curloutput.txt", 'w+'); > fwrite($file, $response); > fclose($file); > } > > add_action('user_register',"xxx_whmcs_signup",10,1); > > ``` > > Original post: -------------- I am currently trying to get fields that are populated during the Wordpress Signup process and post them to another API. The fields that I need to get hold of are: * First Name * Last Name * Email address * Password (Hash) * and a few other Advanced Custom Fields When I created the original code, I managed to get it to work perfectly if the user was already logged in and went to a specific page, but I can't seem to get the code to work during the sign up process (probably would have to happen after the activation as that is when the password is set). The entire code is currently: > > > ``` > pruned > > ``` > > Because the fields are in Advanced Custom Fields, I have also tried: > > > ``` > pruned > > ``` > > This worked perfectly when the script was running from a shortcode on a page, but of course there are extra hurdles thrown in due to the user not being logged in during the sign up process. I assume this depends on what information I can pass through to my function from a hook. I don't fully understand passing variables through to a function or how I would return the output of $meta so I can see what I'm working with, so it is potentially quite an easy task (fingers crossed). It is also possible that I am not using the correct/best hook? Thanks in advance!
My fix for this issue is editing the Gutenberg plugin and removing the blocks there. I have not found a way to cleanly remove them through functions.php.
387,414
<p>I am looking for a way not to show the site logo in my homepage (but on all other pages). I can manage to do this only in the nasty way, using css and display none - however, I would like to avoid that the logo is not loaded on the homepage? functions.php?</p> <p>best, Aprilia</p>
[ { "answer_id": 387438, "author": "Aprilia Parrino", "author_id": 202302, "author_profile": "https://wordpress.stackexchange.com/users/202302", "pm_score": 1, "selected": false, "text": "<p>solved it like this, it works, but seems not very elegant?</p>\n<pre><code>function change_logo_on_...
2021/04/29
[ "https://wordpress.stackexchange.com/questions/387414", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/202302/" ]
I am looking for a way not to show the site logo in my homepage (but on all other pages). I can manage to do this only in the nasty way, using css and display none - however, I would like to avoid that the logo is not loaded on the homepage? functions.php? best, Aprilia
I had a quick look at the [site-branding template part](https://themes.trac.wordpress.org/browser/twentytwentyone/1.3/template-parts/header/site-branding.php) which handles the rendering of the custom logo on the site header. There's a conditional check on two lines against `has_custom_logo()`, along show title theme mod, which determines, if the custom logo should be rendered or not. Internally `has_custom_logo()` calls `get_theme_mod( 'custom_logo' )` to figure out, if a custom logo has been set. This means, you can use the [theme\_mod\_{$name}](https://developer.wordpress.org/reference/hooks/theme_mod_name/) filter to change 1) the value of the theme mod and 2) the result of `has_custom_logo()`. As code the above would be something like this, ``` function prefix_disable_logo_on_front_page( $value ) { return is_front_page() ? false : $value; } add_filter('theme_mod_custom_logo', 'prefix_disable_logo_on_front_page'); ```
387,496
<p>Is it possible to programmatically change the plugin descriptions otherwise provided by the plugin author? The text I've highlighted below is what I'm talking about wanting to change: <a href="https://i.stack.imgur.com/UndMY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UndMY.png" alt="Plugin description" /></a></p> <p>I often find most plugins have fairly useless descriptions, and it would be useful to use this area to actually describe what we're using the plugin for. None of the plugins (I've tried) that allow you to write notes for other plugins deliver a satisfactory solution.</p> <p>Any ideas?</p>
[ { "answer_id": 387498, "author": "Eigirdas Skruolis", "author_id": 183717, "author_profile": "https://wordpress.stackexchange.com/users/183717", "pm_score": -1, "selected": false, "text": "<p>It is possible by opening plugin directory , in there find file name <em>plugin-name</em>.php , ...
2021/05/01
[ "https://wordpress.stackexchange.com/questions/387496", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/198566/" ]
Is it possible to programmatically change the plugin descriptions otherwise provided by the plugin author? The text I've highlighted below is what I'm talking about wanting to change: [![Plugin description](https://i.stack.imgur.com/UndMY.png)](https://i.stack.imgur.com/UndMY.png) I often find most plugins have fairly useless descriptions, and it would be useful to use this area to actually describe what we're using the plugin for. None of the plugins (I've tried) that allow you to write notes for other plugins deliver a satisfactory solution. Any ideas?
Yes, there is a filter you can use — [`all_plugins`](https://developer.wordpress.org/reference/hooks/all_plugins/): > > `apply_filters( 'all_plugins', array $all_plugins )` > > > Filters the full array of plugins to list in the Plugins list table. > > > And here's an example which changes the description of the Akismet plugin: ```php add_filter( 'all_plugins', 'my_all_plugins' ); function my_all_plugins( $all_plugins ) { // the & means we're modifying the original $all_plugins array foreach ( $all_plugins as $plugin_file => &$plugin_data ) { if ( 'Akismet Anti-Spam' === $plugin_data['Name'] ) { $plugin_data['Description'] = 'My awesome description'; } } return $all_plugins; } ``` But yes, the above hook runs on the Plugins *list table* only.. \**my\_all\_plugins* is just an example name. You should use a better one..
387,501
<p>I moved <code>get_sidebar();</code> from <code>header.php</code> to <code>footer.php</code> but it <s>simply does not appear</s> is being placed after the last post in the page body instead of after the footer. There are no errors displayed. What do I need to do to get this working?</p> <p>functions.php</p> <pre><code>/** * Register widget area. * * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar */ function isometricland_widgets_init() { register_sidebar( array( 'name' =&gt; esc_html__( 'Sidebar', 'isometricland' ), 'id' =&gt; 'sidebar-1', 'description' =&gt; esc_html__( 'Add widgets here.', 'isometricland' ), 'before_widget' =&gt; '&lt;section id=&quot;%1$s&quot; class=&quot;widget %2$s&quot;&gt;', 'after_widget' =&gt; '&lt;/section&gt;', 'before_title' =&gt; '&lt;h2 class=&quot;widget-title&quot;&gt;', 'after_title' =&gt; '&lt;/h2&gt;', ) ); } add_action( 'widgets_init', 'isometricland_widgets_init' ); </code></pre> <p>footer.php</p> <pre><code>&lt;?php global $path_root, $page_title, $path_img, $path_ssi, $path_css, $path_jav; include_once($path_ssi . 'plugin-paypal.php'); include_once($path_ssi . 'plugin-sitesearch.php'); include_once($path_ssi . 'plugin-socialicons.php'); include_once($path_ssi . 'plugin-norml.php'); ?&gt; &lt;/main&gt; &lt;!-- END PAGE CONTENTS --&gt; &lt;!-- START FOOTERS --&gt; &lt;footer&gt; &lt;div id=&quot;footframe&quot;&gt; &lt;small class=&quot;blk&quot;&gt;&lt;?php printf( __( 'Proudly powered by %s.', 'isometricland' ), 'WordPress' ); ?&gt; &lt;?php printf( __( 'Theme: %1$s by Michael Horvath based on %2$s GPLv2 or later.', 'isometricland' ), 'isometricland', '&lt;a href=&quot;http://underscores.me/&quot; rel=&quot;designer&quot;&gt;Underscores.me&lt;/a&gt;' ); ?&gt;&lt;/small&gt; &lt;small class=&quot;blk&quot;&gt;This page &amp;copy; Copyright 2009 Michael Horvath. Last modified: &lt;?php echo date(&quot;F d Y H:i:s&quot;, getlastmod()) ?&gt;.&lt;/small&gt; &lt;/div&gt; &lt;?php wp_footer(); //Crucial footer hook! ?&gt; &lt;/footer&gt; &lt;!-- END FOOTERS --&gt; &lt;/div&gt; &lt;!-- END MIDDLE PANE --&gt; &lt;!-- START SIDEBAR --&gt; &lt;div id=&quot;leftframe&quot;&gt; &lt;div id=&quot;sidebarframetop&quot;&gt; &lt;div id=&quot;sidebar_widget&quot;&gt; &lt;?php get_sidebar('sidebar-1'); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;sidebarframebot&quot;&gt; &lt;div id=&quot;file_paypal&quot;&gt; &lt;?php //echo writePaypalDonate(); ?&gt; &lt;/div&gt; &lt;div id=&quot;file_search&quot;&gt; &lt;?php //echo writeSiteSearchForm(); ?&gt; &lt;/div&gt; &lt;div id=&quot;file_social&quot;&gt; &lt;?php echo writeSocialIcons(); ?&gt; &lt;/div&gt; &lt;div id=&quot;file_norml&quot;&gt; &lt;?php //echo writeNormlLogo(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- END SIDEBAR --&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The rendered HTML:</p> <pre><code> &lt;/main&gt; &lt;!-- END PAGE CONTENTS --&gt; &lt;!-- START FOOTERS --&gt; &lt;footer&gt; &lt;div id=&quot;footframe&quot;&gt; &lt;small class=&quot;blk&quot;&gt;Proudly powered by WordPress. Theme: isometricland by Michael Horvath based on &lt;a href=&quot;http://underscores.me/&quot; rel=&quot;designer&quot;&gt;Underscores.me&lt;/a&gt; GPLv2 or later.&lt;/small&gt; &lt;small class=&quot;blk&quot;&gt;This page &amp;copy; Copyright 2009 Michael Horvath. Last modified: February 06 2020 17:03:12.&lt;/small&gt; &lt;/div&gt; &lt;script type=&quot;text/javascript&quot;&gt;(function(a,d){if(a._nsl===d){a._nsl=[];var c=function(){if(a.jQuery===d)setTimeout(c,33);else{for(var b=0;b&lt;a._nsl.length;b++)a._nsl[b].call(a,a.jQuery);a._nsl={push:function(b){b.call(a,a.jQuery)}}}};c()}})(window);&lt;/script&gt;&lt;script type='text/javascript' src='https://isometricland.net/blog/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/scripts/shCore.js?ver=3.0.9b' id='syntaxhighlighter-core-js'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='https://isometricland.net/blog/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/scripts/shBrushCss.js?ver=3.0.9b' id='syntaxhighlighter-brush-css-js'&gt;&lt;/script&gt; &lt;script type='text/javascript'&gt; (function(){ var corecss = document.createElement('link'); var themecss = document.createElement('link'); var corecssurl = &quot;https://isometricland.net/blog/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shCore.css?ver=3.0.9b&quot;; if ( corecss.setAttribute ) { corecss.setAttribute( &quot;rel&quot;, &quot;stylesheet&quot; ); corecss.setAttribute( &quot;type&quot;, &quot;text/css&quot; ); corecss.setAttribute( &quot;href&quot;, corecssurl ); } else { corecss.rel = &quot;stylesheet&quot;; corecss.href = corecssurl; } document.head.appendChild( corecss ); var themecssurl = &quot;https://isometricland.net/blog/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shThemeFadeToGrey.css?ver=3.0.9b&quot;; if ( themecss.setAttribute ) { themecss.setAttribute( &quot;rel&quot;, &quot;stylesheet&quot; ); themecss.setAttribute( &quot;type&quot;, &quot;text/css&quot; ); themecss.setAttribute( &quot;href&quot;, themecssurl ); } else { themecss.rel = &quot;stylesheet&quot;; themecss.href = themecssurl; } document.head.appendChild( themecss ); })(); SyntaxHighlighter.config.strings.expandSource = '+ expand source'; SyntaxHighlighter.config.strings.help = '?'; SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n'; SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: '; SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: '; SyntaxHighlighter.defaults['class-name'] = 'syntax'; SyntaxHighlighter.defaults['pad-line-numbers'] = true; SyntaxHighlighter.all(); // Infinite scroll support if ( typeof( jQuery ) !== 'undefined' ) { jQuery( function( $ ) { $( document.body ).on( 'post-load', function() { SyntaxHighlighter.highlight(); } ); } ); } &lt;/script&gt; &lt;script type='text/javascript' src='https://isometricland.net/blog/wp-content/themes/isometricland/js/navigation.js?ver=20151215' id='isometricland-navigation-js'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='https://isometricland.net/blog/wp-content/themes/isometricland/js/skip-link-focus-fix.js?ver=20151215' id='isometricland-skip-link-focus-fix-js'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='https://isometricland.net/blog/wp-includes/js/wp-embed.min.js?ver=5.7.1' id='wp-embed-js'&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot;&gt;(function (undefined) {var _targetWindow =&quot;prefer-popup&quot;; window.NSLPopup = function (url, title, w, h) { var userAgent = navigator.userAgent, mobile = function () { return /\b(iPhone|iP[ao]d)/.test(userAgent) || /\b(iP[ao]d)/.test(userAgent) || /Android/i.test(userAgent) || /Mobile/i.test(userAgent); }, screenX = window.screenX !== undefined ? window.screenX : window.screenLeft, screenY = window.screenY !== undefined ? window.screenY : window.screenTop, outerWidth = window.outerWidth !== undefined ? window.outerWidth : document.documentElement.clientWidth, outerHeight = window.outerHeight !== undefined ? window.outerHeight : document.documentElement.clientHeight - 22, targetWidth = mobile() ? null : w, targetHeight = mobile() ? null : h, V = screenX &lt; 0 ? window.screen.width + screenX : screenX, left = parseInt(V + (outerWidth - targetWidth) / 2, 10), right = parseInt(screenY + (outerHeight - targetHeight) / 2.5, 10), features = []; if (targetWidth !== null) { features.push('width=' + targetWidth); } if (targetHeight !== null) { features.push('height=' + targetHeight); } features.push('left=' + left); features.push('top=' + right); features.push('scrollbars=1'); var newWindow = window.open(url, title, features.join(',')); if (window.focus) { newWindow.focus(); } return newWindow; }; var isWebView = null; function checkWebView() { if (isWebView === null) { function _detectOS(ua) { if (/Android/.test(ua)) { return &quot;Android&quot;; } else if (/iPhone|iPad|iPod/.test(ua)) { return &quot;iOS&quot;; } else if (/Windows/.test(ua)) { return &quot;Windows&quot;; } else if (/Mac OS X/.test(ua)) { return &quot;Mac&quot;; } else if (/CrOS/.test(ua)) { return &quot;Chrome OS&quot;; } else if (/Firefox/.test(ua)) { return &quot;Firefox OS&quot;; } return &quot;&quot;; } function _detectBrowser(ua) { var android = /Android/.test(ua); if (/CriOS/.test(ua)) { return &quot;Chrome for iOS&quot;; } else if (/Edge/.test(ua)) { return &quot;Edge&quot;; } else if (android &amp;&amp; /Silk\//.test(ua)) { return &quot;Silk&quot;; } else if (/Chrome/.test(ua)) { return &quot;Chrome&quot;; } else if (/Firefox/.test(ua)) { return &quot;Firefox&quot;; } else if (android) { return &quot;AOSP&quot;; } else if (/MSIE|Trident/.test(ua)) { return &quot;IE&quot;; } else if (/Safari\//.test(ua)) { return &quot;Safari&quot;; } else if (/AppleWebKit/.test(ua)) { return &quot;WebKit&quot;; } return &quot;&quot;; } function _detectBrowserVersion(ua, browser) { if (browser === &quot;Chrome for iOS&quot;) { return _getVersion(ua, &quot;CriOS/&quot;); } else if (browser === &quot;Edge&quot;) { return _getVersion(ua, &quot;Edge/&quot;); } else if (browser === &quot;Chrome&quot;) { return _getVersion(ua, &quot;Chrome/&quot;); } else if (browser === &quot;Firefox&quot;) { return _getVersion(ua, &quot;Firefox/&quot;); } else if (browser === &quot;Silk&quot;) { return _getVersion(ua, &quot;Silk/&quot;); } else if (browser === &quot;AOSP&quot;) { return _getVersion(ua, &quot;Version/&quot;); } else if (browser === &quot;IE&quot;) { return /IEMobile/.test(ua) ? _getVersion(ua, &quot;IEMobile/&quot;) : /MSIE/.test(ua) ? _getVersion(ua, &quot;MSIE &quot;) : _getVersion(ua, &quot;rv:&quot;); } else if (browser === &quot;Safari&quot;) { return _getVersion(ua, &quot;Version/&quot;); } else if (browser === &quot;WebKit&quot;) { return _getVersion(ua, &quot;WebKit/&quot;); } return &quot;0.0.0&quot;; } function _getVersion(ua, token) { try { return _normalizeSemverString(ua.split(token)[1].trim().split(/[^\w\.]/)[0]); } catch (o_O) { } return &quot;0.0.0&quot;; } function _normalizeSemverString(version) { var ary = version.split(/[\._]/); return (parseInt(ary[0], 10) || 0) + &quot;.&quot; + (parseInt(ary[1], 10) || 0) + &quot;.&quot; + (parseInt(ary[2], 10) || 0); } function _isWebView(ua, os, browser, version, options) { switch (os + browser) { case &quot;iOSSafari&quot;: return false; case &quot;iOSWebKit&quot;: return _isWebView_iOS(options); case &quot;AndroidAOSP&quot;: return false; case &quot;AndroidChrome&quot;: return parseFloat(version) &gt;= 42 ? /; wv/.test(ua) : /\d{2}\.0\.0/.test(version) ? true : _isWebView_Android(options); } return false; } function _isWebView_iOS(options) { var document = (window[&quot;document&quot;] || {}); if (&quot;WEB_VIEW&quot; in options) { return options[&quot;WEB_VIEW&quot;]; } return !(&quot;fullscreenEnabled&quot; in document || &quot;webkitFullscreenEnabled&quot; in document || false); } function _isWebView_Android(options) { if (&quot;WEB_VIEW&quot; in options) { return options[&quot;WEB_VIEW&quot;]; } return !(&quot;requestFileSystem&quot; in window || &quot;webkitRequestFileSystem&quot; in window || false); } var options = {}; var nav = window.navigator || {}; var ua = nav.userAgent || &quot;&quot;; var os = _detectOS(ua); var browser = _detectBrowser(ua); var browserVersion = _detectBrowserVersion(ua, browser); isWebView = _isWebView(ua, os, browser, browserVersion, options); } return isWebView; } function isAllowedWebViewForUserAgent() { var nav = window.navigator || {}; var ua = nav.userAgent || &quot;&quot;; if (/Instagram/.test(ua)) { /*Instagram WebView*/ return true; } else if (/FBAV/.test(ua) || /FBAN/.test(ua)) { /*Facebook WebView*/ return true; } return false; } window._nsl.push(function ($) { window.nslRedirect = function (url) { $('&lt;div style=&quot;position:fixed;z-index:1000000;left:0;top:0;width:100%;height:100%;&quot;&gt;&lt;/div&gt;').appendTo('body'); window.location = url; }; var targetWindow = _targetWindow || 'prefer-popup', lastPopup = false; $(document.body).on('click', 'a[data-plugin=&quot;nsl&quot;][data-action=&quot;connect&quot;],a[data-plugin=&quot;nsl&quot;][data-action=&quot;link&quot;]', function (e) { if (lastPopup &amp;&amp; !lastPopup.closed) { e.preventDefault(); lastPopup.focus(); } else { var $target = $(this), href = $target.attr('href'), success = false; if (href.indexOf('?') !== -1) { href += '&amp;'; } else { href += '?'; } var redirectTo = $target.data('redirect'); if (redirectTo === 'current') { href += 'redirect=' + encodeURIComponent(window.location.href) + '&amp;'; } else if (redirectTo &amp;&amp; redirectTo !== '') { href += 'redirect=' + encodeURIComponent(redirectTo) + '&amp;'; } if (targetWindow !== 'prefer-same-window' &amp;&amp; checkWebView()) { targetWindow = 'prefer-same-window'; } if (targetWindow === 'prefer-popup') { lastPopup = NSLPopup(href + 'display=popup', 'nsl-social-connect', $target.data('popupwidth'), $target.data('popupheight')); if (lastPopup) { success = true; e.preventDefault(); } } else if (targetWindow === 'prefer-new-tab') { var newTab = window.open(href + 'display=popup', '_blank'); if (newTab) { if (window.focus) { newTab.focus(); } success = true; e.preventDefault(); } } if (!success) { window.location = href; e.preventDefault(); } } }); var googleLoginButton = $('a[data-plugin=&quot;nsl&quot;][data-provider=&quot;google&quot;]'); if (googleLoginButton.length &amp;&amp; checkWebView() &amp;&amp; !isAllowedWebViewForUserAgent()) { googleLoginButton.remove(); } });})();&lt;/script&gt; &lt;/footer&gt; &lt;!-- END FOOTERS --&gt; &lt;/div&gt; &lt;!-- END MIDDLE PANE --&gt; &lt;!-- START SIDEBAR --&gt; &lt;div id=&quot;leftframe&quot;&gt; &lt;div id=&quot;sidebarframetop&quot;&gt; &lt;div id=&quot;sidebar_widget&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;sidebarframebot&quot;&gt; &lt;div id=&quot;file_paypal&quot;&gt; &lt;/div&gt; &lt;div id=&quot;file_search&quot;&gt; &lt;/div&gt; &lt;div id=&quot;file_social&quot;&gt; &lt;div class=&quot;social&quot; title=&quot;DeviantArt&quot; &gt;&lt;a href=&quot;https://posfan12.deviantart.com/&quot; target=&quot;_blank&quot;&gt;&lt;img class=&quot;nomagnify&quot; style=&quot;margin:0px;&quot; src=&quot;https://isometricland.net/images/icon_deviantart.png&quot; alt=&quot;DeviantArt&quot; /&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;social&quot; title=&quot;Facebook&quot; &gt;&lt;a href=&quot;https://www.facebook.com/michael.horvath.35&quot; target=&quot;_blank&quot;&gt;&lt;img class=&quot;nomagnify&quot; style=&quot;margin:0px;&quot; src=&quot;https://isometricland.net/images/icon_facebook.png&quot; alt=&quot;Facebook&quot; /&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;social&quot; title=&quot;Flickr&quot; &gt;&lt;a href=&quot;https://www.flickr.com/photos/108839565@N04/&quot; target=&quot;_blank&quot;&gt;&lt;img class=&quot;nomagnify&quot; style=&quot;margin:0px;&quot; src=&quot;https://isometricland.net/images/icon_flickr.png&quot; alt=&quot;Flickr&quot; /&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;social&quot; title=&quot;GitHub&quot; &gt;&lt;a href=&quot;https://github.com/mjhorvath&quot; target=&quot;_blank&quot;&gt;&lt;img class=&quot;nomagnify&quot; style=&quot;margin:0px;&quot; src=&quot;https://isometricland.net/images/icon_github.png&quot; alt=&quot;GitHub&quot; /&gt;&lt;/a&gt;&lt;/div&gt; &lt;br/&gt; &lt;div class=&quot;social&quot; title=&quot;Goodreads&quot; &gt;&lt;a href=&quot;https://www.goodreads.com/user/show/67971043-michael-horvath&quot; target=&quot;_blank&quot;&gt;&lt;img class=&quot;nomagnify&quot; style=&quot;margin:0px;&quot; src=&quot;https://isometricland.net/images/icon_goodreads.png&quot; alt=&quot;Goodreads&quot; /&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;social&quot; title=&quot;LinkedIn&quot; &gt;&lt;a href=&quot;https://www.linkedin.com/in/michael-horvath-45547a116/&quot; target=&quot;_blank&quot;&gt;&lt;img class=&quot;nomagnify&quot; style=&quot;margin:0px;&quot; src=&quot;https://isometricland.net/images/icon_linkedin.png&quot; alt=&quot;LinkedIn&quot; /&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;social&quot; title=&quot;Spotify&quot; &gt;&lt;a href=&quot;https://open.spotify.com/user/f1703yjwz5hxcrndycvbjfwbl&quot; target=&quot;_blank&quot;&gt;&lt;img class=&quot;nomagnify&quot; style=&quot;margin:0px;&quot; src=&quot;https://isometricland.net/images/icon_spotify.png&quot; alt=&quot;Spotify&quot; /&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class=&quot;social&quot; title=&quot;Wikipedia&quot; &gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/User:Datumizer&quot; target=&quot;_blank&quot;&gt;&lt;img class=&quot;nomagnify&quot; style=&quot;margin:0px;&quot; src=&quot;https://isometricland.net/images/icon_wikipedia.png&quot; alt=&quot;Wikipedia&quot; /&gt;&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;file_norml&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- END SIDEBAR --&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 387515, "author": "Pixelsmith", "author_id": 66368, "author_profile": "https://wordpress.stackexchange.com/users/66368", "pm_score": 0, "selected": false, "text": "<p>If you want it in the footer, just put it in the footer.</p>\n<pre><code> &lt;/main&gt;\n ...
2021/05/01
[ "https://wordpress.stackexchange.com/questions/387501", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148991/" ]
I moved `get_sidebar();` from `header.php` to `footer.php` but it ~~simply does not appear~~ is being placed after the last post in the page body instead of after the footer. There are no errors displayed. What do I need to do to get this working? functions.php ``` /** * Register widget area. * * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar */ function isometricland_widgets_init() { register_sidebar( array( 'name' => esc_html__( 'Sidebar', 'isometricland' ), 'id' => 'sidebar-1', 'description' => esc_html__( 'Add widgets here.', 'isometricland' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); } add_action( 'widgets_init', 'isometricland_widgets_init' ); ``` footer.php ``` <?php global $path_root, $page_title, $path_img, $path_ssi, $path_css, $path_jav; include_once($path_ssi . 'plugin-paypal.php'); include_once($path_ssi . 'plugin-sitesearch.php'); include_once($path_ssi . 'plugin-socialicons.php'); include_once($path_ssi . 'plugin-norml.php'); ?> </main> <!-- END PAGE CONTENTS --> <!-- START FOOTERS --> <footer> <div id="footframe"> <small class="blk"><?php printf( __( 'Proudly powered by %s.', 'isometricland' ), 'WordPress' ); ?> <?php printf( __( 'Theme: %1$s by Michael Horvath based on %2$s GPLv2 or later.', 'isometricland' ), 'isometricland', '<a href="http://underscores.me/" rel="designer">Underscores.me</a>' ); ?></small> <small class="blk">This page &copy; Copyright 2009 Michael Horvath. Last modified: <?php echo date("F d Y H:i:s", getlastmod()) ?>.</small> </div> <?php wp_footer(); //Crucial footer hook! ?> </footer> <!-- END FOOTERS --> </div> <!-- END MIDDLE PANE --> <!-- START SIDEBAR --> <div id="leftframe"> <div id="sidebarframetop"> <div id="sidebar_widget"> <?php get_sidebar('sidebar-1'); ?> </div> </div> <div id="sidebarframebot"> <div id="file_paypal"> <?php //echo writePaypalDonate(); ?> </div> <div id="file_search"> <?php //echo writeSiteSearchForm(); ?> </div> <div id="file_social"> <?php echo writeSocialIcons(); ?> </div> <div id="file_norml"> <?php //echo writeNormlLogo(); ?> </div> </div> </div> <!-- END SIDEBAR --> </div> </body> </html> ``` The rendered HTML: ``` </main> <!-- END PAGE CONTENTS --> <!-- START FOOTERS --> <footer> <div id="footframe"> <small class="blk">Proudly powered by WordPress. Theme: isometricland by Michael Horvath based on <a href="http://underscores.me/" rel="designer">Underscores.me</a> GPLv2 or later.</small> <small class="blk">This page &copy; Copyright 2009 Michael Horvath. Last modified: February 06 2020 17:03:12.</small> </div> <script type="text/javascript">(function(a,d){if(a._nsl===d){a._nsl=[];var c=function(){if(a.jQuery===d)setTimeout(c,33);else{for(var b=0;b<a._nsl.length;b++)a._nsl[b].call(a,a.jQuery);a._nsl={push:function(b){b.call(a,a.jQuery)}}}};c()}})(window);</script><script type='text/javascript' src='https://isometricland.net/blog/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/scripts/shCore.js?ver=3.0.9b' id='syntaxhighlighter-core-js'></script> <script type='text/javascript' src='https://isometricland.net/blog/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/scripts/shBrushCss.js?ver=3.0.9b' id='syntaxhighlighter-brush-css-js'></script> <script type='text/javascript'> (function(){ var corecss = document.createElement('link'); var themecss = document.createElement('link'); var corecssurl = "https://isometricland.net/blog/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shCore.css?ver=3.0.9b"; if ( corecss.setAttribute ) { corecss.setAttribute( "rel", "stylesheet" ); corecss.setAttribute( "type", "text/css" ); corecss.setAttribute( "href", corecssurl ); } else { corecss.rel = "stylesheet"; corecss.href = corecssurl; } document.head.appendChild( corecss ); var themecssurl = "https://isometricland.net/blog/wp-content/plugins/syntaxhighlighter/syntaxhighlighter3/styles/shThemeFadeToGrey.css?ver=3.0.9b"; if ( themecss.setAttribute ) { themecss.setAttribute( "rel", "stylesheet" ); themecss.setAttribute( "type", "text/css" ); themecss.setAttribute( "href", themecssurl ); } else { themecss.rel = "stylesheet"; themecss.href = themecssurl; } document.head.appendChild( themecss ); })(); SyntaxHighlighter.config.strings.expandSource = '+ expand source'; SyntaxHighlighter.config.strings.help = '?'; SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n'; SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: '; SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: '; SyntaxHighlighter.defaults['class-name'] = 'syntax'; SyntaxHighlighter.defaults['pad-line-numbers'] = true; SyntaxHighlighter.all(); // Infinite scroll support if ( typeof( jQuery ) !== 'undefined' ) { jQuery( function( $ ) { $( document.body ).on( 'post-load', function() { SyntaxHighlighter.highlight(); } ); } ); } </script> <script type='text/javascript' src='https://isometricland.net/blog/wp-content/themes/isometricland/js/navigation.js?ver=20151215' id='isometricland-navigation-js'></script> <script type='text/javascript' src='https://isometricland.net/blog/wp-content/themes/isometricland/js/skip-link-focus-fix.js?ver=20151215' id='isometricland-skip-link-focus-fix-js'></script> <script type='text/javascript' src='https://isometricland.net/blog/wp-includes/js/wp-embed.min.js?ver=5.7.1' id='wp-embed-js'></script> <script type="text/javascript">(function (undefined) {var _targetWindow ="prefer-popup"; window.NSLPopup = function (url, title, w, h) { var userAgent = navigator.userAgent, mobile = function () { return /\b(iPhone|iP[ao]d)/.test(userAgent) || /\b(iP[ao]d)/.test(userAgent) || /Android/i.test(userAgent) || /Mobile/i.test(userAgent); }, screenX = window.screenX !== undefined ? window.screenX : window.screenLeft, screenY = window.screenY !== undefined ? window.screenY : window.screenTop, outerWidth = window.outerWidth !== undefined ? window.outerWidth : document.documentElement.clientWidth, outerHeight = window.outerHeight !== undefined ? window.outerHeight : document.documentElement.clientHeight - 22, targetWidth = mobile() ? null : w, targetHeight = mobile() ? null : h, V = screenX < 0 ? window.screen.width + screenX : screenX, left = parseInt(V + (outerWidth - targetWidth) / 2, 10), right = parseInt(screenY + (outerHeight - targetHeight) / 2.5, 10), features = []; if (targetWidth !== null) { features.push('width=' + targetWidth); } if (targetHeight !== null) { features.push('height=' + targetHeight); } features.push('left=' + left); features.push('top=' + right); features.push('scrollbars=1'); var newWindow = window.open(url, title, features.join(',')); if (window.focus) { newWindow.focus(); } return newWindow; }; var isWebView = null; function checkWebView() { if (isWebView === null) { function _detectOS(ua) { if (/Android/.test(ua)) { return "Android"; } else if (/iPhone|iPad|iPod/.test(ua)) { return "iOS"; } else if (/Windows/.test(ua)) { return "Windows"; } else if (/Mac OS X/.test(ua)) { return "Mac"; } else if (/CrOS/.test(ua)) { return "Chrome OS"; } else if (/Firefox/.test(ua)) { return "Firefox OS"; } return ""; } function _detectBrowser(ua) { var android = /Android/.test(ua); if (/CriOS/.test(ua)) { return "Chrome for iOS"; } else if (/Edge/.test(ua)) { return "Edge"; } else if (android && /Silk\//.test(ua)) { return "Silk"; } else if (/Chrome/.test(ua)) { return "Chrome"; } else if (/Firefox/.test(ua)) { return "Firefox"; } else if (android) { return "AOSP"; } else if (/MSIE|Trident/.test(ua)) { return "IE"; } else if (/Safari\//.test(ua)) { return "Safari"; } else if (/AppleWebKit/.test(ua)) { return "WebKit"; } return ""; } function _detectBrowserVersion(ua, browser) { if (browser === "Chrome for iOS") { return _getVersion(ua, "CriOS/"); } else if (browser === "Edge") { return _getVersion(ua, "Edge/"); } else if (browser === "Chrome") { return _getVersion(ua, "Chrome/"); } else if (browser === "Firefox") { return _getVersion(ua, "Firefox/"); } else if (browser === "Silk") { return _getVersion(ua, "Silk/"); } else if (browser === "AOSP") { return _getVersion(ua, "Version/"); } else if (browser === "IE") { return /IEMobile/.test(ua) ? _getVersion(ua, "IEMobile/") : /MSIE/.test(ua) ? _getVersion(ua, "MSIE ") : _getVersion(ua, "rv:"); } else if (browser === "Safari") { return _getVersion(ua, "Version/"); } else if (browser === "WebKit") { return _getVersion(ua, "WebKit/"); } return "0.0.0"; } function _getVersion(ua, token) { try { return _normalizeSemverString(ua.split(token)[1].trim().split(/[^\w\.]/)[0]); } catch (o_O) { } return "0.0.0"; } function _normalizeSemverString(version) { var ary = version.split(/[\._]/); return (parseInt(ary[0], 10) || 0) + "." + (parseInt(ary[1], 10) || 0) + "." + (parseInt(ary[2], 10) || 0); } function _isWebView(ua, os, browser, version, options) { switch (os + browser) { case "iOSSafari": return false; case "iOSWebKit": return _isWebView_iOS(options); case "AndroidAOSP": return false; case "AndroidChrome": return parseFloat(version) >= 42 ? /; wv/.test(ua) : /\d{2}\.0\.0/.test(version) ? true : _isWebView_Android(options); } return false; } function _isWebView_iOS(options) { var document = (window["document"] || {}); if ("WEB_VIEW" in options) { return options["WEB_VIEW"]; } return !("fullscreenEnabled" in document || "webkitFullscreenEnabled" in document || false); } function _isWebView_Android(options) { if ("WEB_VIEW" in options) { return options["WEB_VIEW"]; } return !("requestFileSystem" in window || "webkitRequestFileSystem" in window || false); } var options = {}; var nav = window.navigator || {}; var ua = nav.userAgent || ""; var os = _detectOS(ua); var browser = _detectBrowser(ua); var browserVersion = _detectBrowserVersion(ua, browser); isWebView = _isWebView(ua, os, browser, browserVersion, options); } return isWebView; } function isAllowedWebViewForUserAgent() { var nav = window.navigator || {}; var ua = nav.userAgent || ""; if (/Instagram/.test(ua)) { /*Instagram WebView*/ return true; } else if (/FBAV/.test(ua) || /FBAN/.test(ua)) { /*Facebook WebView*/ return true; } return false; } window._nsl.push(function ($) { window.nslRedirect = function (url) { $('<div style="position:fixed;z-index:1000000;left:0;top:0;width:100%;height:100%;"></div>').appendTo('body'); window.location = url; }; var targetWindow = _targetWindow || 'prefer-popup', lastPopup = false; $(document.body).on('click', 'a[data-plugin="nsl"][data-action="connect"],a[data-plugin="nsl"][data-action="link"]', function (e) { if (lastPopup && !lastPopup.closed) { e.preventDefault(); lastPopup.focus(); } else { var $target = $(this), href = $target.attr('href'), success = false; if (href.indexOf('?') !== -1) { href += '&'; } else { href += '?'; } var redirectTo = $target.data('redirect'); if (redirectTo === 'current') { href += 'redirect=' + encodeURIComponent(window.location.href) + '&'; } else if (redirectTo && redirectTo !== '') { href += 'redirect=' + encodeURIComponent(redirectTo) + '&'; } if (targetWindow !== 'prefer-same-window' && checkWebView()) { targetWindow = 'prefer-same-window'; } if (targetWindow === 'prefer-popup') { lastPopup = NSLPopup(href + 'display=popup', 'nsl-social-connect', $target.data('popupwidth'), $target.data('popupheight')); if (lastPopup) { success = true; e.preventDefault(); } } else if (targetWindow === 'prefer-new-tab') { var newTab = window.open(href + 'display=popup', '_blank'); if (newTab) { if (window.focus) { newTab.focus(); } success = true; e.preventDefault(); } } if (!success) { window.location = href; e.preventDefault(); } } }); var googleLoginButton = $('a[data-plugin="nsl"][data-provider="google"]'); if (googleLoginButton.length && checkWebView() && !isAllowedWebViewForUserAgent()) { googleLoginButton.remove(); } });})();</script> </footer> <!-- END FOOTERS --> </div> <!-- END MIDDLE PANE --> <!-- START SIDEBAR --> <div id="leftframe"> <div id="sidebarframetop"> <div id="sidebar_widget"> </div> </div> <div id="sidebarframebot"> <div id="file_paypal"> </div> <div id="file_search"> </div> <div id="file_social"> <div class="social" title="DeviantArt" ><a href="https://posfan12.deviantart.com/" target="_blank"><img class="nomagnify" style="margin:0px;" src="https://isometricland.net/images/icon_deviantart.png" alt="DeviantArt" /></a></div> <div class="social" title="Facebook" ><a href="https://www.facebook.com/michael.horvath.35" target="_blank"><img class="nomagnify" style="margin:0px;" src="https://isometricland.net/images/icon_facebook.png" alt="Facebook" /></a></div> <div class="social" title="Flickr" ><a href="https://www.flickr.com/photos/108839565@N04/" target="_blank"><img class="nomagnify" style="margin:0px;" src="https://isometricland.net/images/icon_flickr.png" alt="Flickr" /></a></div> <div class="social" title="GitHub" ><a href="https://github.com/mjhorvath" target="_blank"><img class="nomagnify" style="margin:0px;" src="https://isometricland.net/images/icon_github.png" alt="GitHub" /></a></div> <br/> <div class="social" title="Goodreads" ><a href="https://www.goodreads.com/user/show/67971043-michael-horvath" target="_blank"><img class="nomagnify" style="margin:0px;" src="https://isometricland.net/images/icon_goodreads.png" alt="Goodreads" /></a></div> <div class="social" title="LinkedIn" ><a href="https://www.linkedin.com/in/michael-horvath-45547a116/" target="_blank"><img class="nomagnify" style="margin:0px;" src="https://isometricland.net/images/icon_linkedin.png" alt="LinkedIn" /></a></div> <div class="social" title="Spotify" ><a href="https://open.spotify.com/user/f1703yjwz5hxcrndycvbjfwbl" target="_blank"><img class="nomagnify" style="margin:0px;" src="https://isometricland.net/images/icon_spotify.png" alt="Spotify" /></a></div> <div class="social" title="Wikipedia" ><a href="https://en.wikipedia.org/wiki/User:Datumizer" target="_blank"><img class="nomagnify" style="margin:0px;" src="https://isometricland.net/images/icon_wikipedia.png" alt="Wikipedia" /></a></div> </div> <div id="file_norml"> </div> </div> </div> <!-- END SIDEBAR --> </div> </body> </html> ```
You need to read the documentation, [`get_sidebar()`](https://developer.wordpress.org/reference/functions/get_sidebar/): > > Includes the sidebar template for a theme or if a name is specified then a specialised sidebar will be included. > > > Its purpose is to load `sidebar.php`. It does not output widgets. To output widgets you need to use `dynamic_sidebar()`: ``` <?php dynamic_sidebar( 'sidebar-1' ); ?> ``` That will output the widgets added to that widget area. This is clearly outlined in [the documentation](https://developer.wordpress.org/themes/functionality/sidebars/#displaying-sidebars-in-your-theme).
387,599
<p>First, is it even <em>possible</em> to change the page title from a plugin (specifically, from a shortcode defined in a plugin)? <a href="https://wordpress.stackexchange.com/questions/46921/filter-title-from-shortcode">This answer</a> says no, but there are certainly reasonable use cases for it. Like, say, my use case (the shortcode displays detail page content for an item of a collection ... so, I put the shortcode on a page; what's the page title supposed to be? It depends on the detail item.).</p> <p>I have tried every method I can find:</p> <pre><code>$_SESSION['custom_page_title'] = $eventData['eventtitle']; //attempt 1 add_filter('document_title_parts', 'my_custom_title'); function my_custom_title( $title ) { // $title is an array of title parts, including one called `title` $title['title'] = stripslashes($_SESSION['custom_page_title']); return $title; } //attempt 2 add_filter(&quot;pre_get_document_title&quot;, &quot;my_callback&quot;); function my_callback($old_title){ return stripslashes($_SESSION['custom_page_title']); } //attempt 3 add_filter('the_title','some_callback'); function some_callback($data){ return stripslashes($_SESSION['custom_page_title']); } //attempt 4 add_filter( 'wp_title', 'custom_titles', 10, 2 ); function custom_titles( $title, $sep ) { //Check if custom titles are enabled from your option framework if ( ot_get_option( 'enable_custom_titles' ) === 'on' || (1 == 1)) { $title = stripslashes($_SESSION['custom_page_title']); } return $title; } </code></pre> <p>But none of them work (with default twentytwentyone theme).</p> <p>The plugin is a custom one made by me. The use case is simply to change the page title, based on data that the plugin knows. It's pretty simple in concept. Not really another way to do it.</p> <p>The shortcode defined in the plugin is displaying the detail for one specific entity (something like /individual_display?id=5 ) and the page should be titled accordingly. The page shouldn't be titled &quot;Individual Display&quot; or whatever, it should be titled &quot;Actual Name of The Individual Thing That Happens to Have ID #5&quot;</p> <p>Is it possible, and if so, how?</p>
[ { "answer_id": 397904, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 3, "selected": true, "text": "<p>You can do it like so:</p>\n<pre><code>function filterDocumentTitle(string $title): string\n{\n // don't cha...
2021/05/03
[ "https://wordpress.stackexchange.com/questions/387599", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91121/" ]
First, is it even *possible* to change the page title from a plugin (specifically, from a shortcode defined in a plugin)? [This answer](https://wordpress.stackexchange.com/questions/46921/filter-title-from-shortcode) says no, but there are certainly reasonable use cases for it. Like, say, my use case (the shortcode displays detail page content for an item of a collection ... so, I put the shortcode on a page; what's the page title supposed to be? It depends on the detail item.). I have tried every method I can find: ``` $_SESSION['custom_page_title'] = $eventData['eventtitle']; //attempt 1 add_filter('document_title_parts', 'my_custom_title'); function my_custom_title( $title ) { // $title is an array of title parts, including one called `title` $title['title'] = stripslashes($_SESSION['custom_page_title']); return $title; } //attempt 2 add_filter("pre_get_document_title", "my_callback"); function my_callback($old_title){ return stripslashes($_SESSION['custom_page_title']); } //attempt 3 add_filter('the_title','some_callback'); function some_callback($data){ return stripslashes($_SESSION['custom_page_title']); } //attempt 4 add_filter( 'wp_title', 'custom_titles', 10, 2 ); function custom_titles( $title, $sep ) { //Check if custom titles are enabled from your option framework if ( ot_get_option( 'enable_custom_titles' ) === 'on' || (1 == 1)) { $title = stripslashes($_SESSION['custom_page_title']); } return $title; } ``` But none of them work (with default twentytwentyone theme). The plugin is a custom one made by me. The use case is simply to change the page title, based on data that the plugin knows. It's pretty simple in concept. Not really another way to do it. The shortcode defined in the plugin is displaying the detail for one specific entity (something like /individual\_display?id=5 ) and the page should be titled accordingly. The page shouldn't be titled "Individual Display" or whatever, it should be titled "Actual Name of The Individual Thing That Happens to Have ID #5" Is it possible, and if so, how?
You can do it like so: ``` function filterDocumentTitle(string $title): string { // don't change title on admin pages or when global $post is not loaded if (is_admin() || get_the_ID() === false) { return $title; } // don't change title if shortcode is not present in content if (!has_shortcode(get_the_content(), 'caption')) { return $title; } return 'special title'; } add_filter('pre_get_document_title', 'filterDocumentTitle'); ``` If you're using Yoast's SEO plugin, you'll also need `add_filter('wpseo_title', 'filterDocumentTitle');`, since the plugin doesn't play nicely with `pre_get_document_title` alone. Other SEO plugins might need similar fixes. In the above code I check for `[caption]` shortcode, which I used locally to test it, replace this with your real shortcode name (without `[` and `]`). With this you'll know when your shortcode is part of a page or not. Now what is left to do, is getting the value you want for your title. For lack of more information I'll assume that your shortcode looks something like this ``` add_shortcode('myshortcode', function () { $id = intval($_GET['item']); $eventData = /* .. get event data via ID */; return 'some contents depending on $eventData'; }); ``` So that you don't have to duplicate your code, let's refactor this a bit to the following ``` function gholmesGetEventData(): array { if (empty($_GET['item'])) { throw new Exception('Only supported when item is provided.'); } $id = intval($_GET['item']); $eventData = /* .. get event data via ID, throw Exception if not found */; return $eventData; } add_shortcode('myshortcode', function (): ?string { try { $eventData = gholmesGetEventData(); return 'some contents depending on $eventData'; } catch (Exception $e) { // do something with the exception return null; } }); function gholmesFilterDocumentTitle(string $title): string { // don't change title on admin pages or when global $post is not loaded if (is_admin() || get_the_ID() === false) { return $title; } // don't change title if shortcode is not present in content if (!has_shortcode(get_the_content(), 'caption')) { return $title; } try { $eventData = gholmesGetEventData(); return $eventData['eventtitle']; } catch (Exception $e) { return $title; } } add_filter('pre_get_document_title', 'gholmesFilterDocumentTitle'); ``` With this setup you'll call `gholmesGetEventData()` twice. Once in the title once in the shortcode body. To optimize this, you can use WordPress' object cache's [set](https://developer.wordpress.org/reference/classes/wp_object_cache/set/) and [get](https://developer.wordpress.org/reference/classes/wp_object_cache/get/) methods inside `gholmesGetEventData()` to minimize DB requests. (So the second call would just return the cached result.)
387,651
<p>I have about 2000 titles. How can I automatically delete posts with these titles?</p> <p>For example</p> <p><a href="https://i.stack.imgur.com/bwVZ1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bwVZ1.png" alt="My list" /></a></p>
[ { "answer_id": 397904, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 3, "selected": true, "text": "<p>You can do it like so:</p>\n<pre><code>function filterDocumentTitle(string $title): string\n{\n // don't cha...
2021/05/04
[ "https://wordpress.stackexchange.com/questions/387651", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/160866/" ]
I have about 2000 titles. How can I automatically delete posts with these titles? For example [![My list](https://i.stack.imgur.com/bwVZ1.png)](https://i.stack.imgur.com/bwVZ1.png)
You can do it like so: ``` function filterDocumentTitle(string $title): string { // don't change title on admin pages or when global $post is not loaded if (is_admin() || get_the_ID() === false) { return $title; } // don't change title if shortcode is not present in content if (!has_shortcode(get_the_content(), 'caption')) { return $title; } return 'special title'; } add_filter('pre_get_document_title', 'filterDocumentTitle'); ``` If you're using Yoast's SEO plugin, you'll also need `add_filter('wpseo_title', 'filterDocumentTitle');`, since the plugin doesn't play nicely with `pre_get_document_title` alone. Other SEO plugins might need similar fixes. In the above code I check for `[caption]` shortcode, which I used locally to test it, replace this with your real shortcode name (without `[` and `]`). With this you'll know when your shortcode is part of a page or not. Now what is left to do, is getting the value you want for your title. For lack of more information I'll assume that your shortcode looks something like this ``` add_shortcode('myshortcode', function () { $id = intval($_GET['item']); $eventData = /* .. get event data via ID */; return 'some contents depending on $eventData'; }); ``` So that you don't have to duplicate your code, let's refactor this a bit to the following ``` function gholmesGetEventData(): array { if (empty($_GET['item'])) { throw new Exception('Only supported when item is provided.'); } $id = intval($_GET['item']); $eventData = /* .. get event data via ID, throw Exception if not found */; return $eventData; } add_shortcode('myshortcode', function (): ?string { try { $eventData = gholmesGetEventData(); return 'some contents depending on $eventData'; } catch (Exception $e) { // do something with the exception return null; } }); function gholmesFilterDocumentTitle(string $title): string { // don't change title on admin pages or when global $post is not loaded if (is_admin() || get_the_ID() === false) { return $title; } // don't change title if shortcode is not present in content if (!has_shortcode(get_the_content(), 'caption')) { return $title; } try { $eventData = gholmesGetEventData(); return $eventData['eventtitle']; } catch (Exception $e) { return $title; } } add_filter('pre_get_document_title', 'gholmesFilterDocumentTitle'); ``` With this setup you'll call `gholmesGetEventData()` twice. Once in the title once in the shortcode body. To optimize this, you can use WordPress' object cache's [set](https://developer.wordpress.org/reference/classes/wp_object_cache/set/) and [get](https://developer.wordpress.org/reference/classes/wp_object_cache/get/) methods inside `gholmesGetEventData()` to minimize DB requests. (So the second call would just return the cached result.)
387,658
<p>This is a very straight-forward question, but it's important and I can't find anything definitive in the docs.</p> <p><a href="https://wordpress.stackexchange.com/questions/63664/do-i-need-to-sanitize-wordpress-search-query">This question</a> asks a similar question for the <code>'s'</code> parameter, specifically. I want to know if WordPress validates/sanitizes parameters for <strong>any</strong> of the other parameters. For example, do the terms in a <code>tax_query</code> get sanitized automatically?</p> <p><strong>Clarification:</strong> This is a technical / engineering question about specifically what the WP_Query class does with particular parameters. Several recent answers offer philosophical advice and general best practices regarding validation/sanitization. But that's not what this question is about. My goal is compile facts rather than opinions.</p>
[ { "answer_id": 387924, "author": "Cas Dekkers", "author_id": 153884, "author_profile": "https://wordpress.stackexchange.com/users/153884", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>I want to know if I have to sanitize user input for <strong>any</strong> of the other par...
2021/05/04
[ "https://wordpress.stackexchange.com/questions/387658", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11363/" ]
This is a very straight-forward question, but it's important and I can't find anything definitive in the docs. [This question](https://wordpress.stackexchange.com/questions/63664/do-i-need-to-sanitize-wordpress-search-query) asks a similar question for the `'s'` parameter, specifically. I want to know if WordPress validates/sanitizes parameters for **any** of the other parameters. For example, do the terms in a `tax_query` get sanitized automatically? **Clarification:** This is a technical / engineering question about specifically what the WP\_Query class does with particular parameters. Several recent answers offer philosophical advice and general best practices regarding validation/sanitization. But that's not what this question is about. My goal is compile facts rather than opinions.
It's actually a good question. Of course user input cannot be trusted, but also sanitizing the same value twice "just in case" isn't the best solution for a problem. The only real answer to this question can be given by looking at the code and following what goes on. And after reading it for a few hours, here is what I can say about it: > > WP Query sanitizes the values but it doesn't do it all in one place. Values are being sanitized before they are actually used. It's a very organic and *on the go* approach. Also, not all of the values are sanitized, but in those cases a prepared statement is used for the SQL query. > > > Let's get into detail --------------------- So, what happens when we do: ``` $query = new WP_Query($args); ``` The WP\_Query class constructor checks if the `$args` is an empty array or not. And if it's not, it will run its `query()` method passing the `$args` array (which is at this point called `$query` array). ``` $this->query($query); ``` The `query()` method calls the `init()` method which unsets possible previous values and sets new defaults. Then it runs [wp\_parse\_args()](https://developer.wordpress.org/reference/functions/wp_parse_args/) on the `$args` array. This function does not sanitize anything, it serves like a bridge between default data and input data. The next call is for the `get_posts()` method, which is in charge of retrieving the posts based on the given query variables. The first thing that is called inside the `get_posts()` method is the `parse_query()` method, which starts by calling the `fill_query_vars()` method (this one makes sure that a list of default keys are set. The ones that are not, get set with an empty string or empty array depending on the case). Then, still inside the `parse_query()` method, the first santization takes place. `p` is checked against [is\_scalar()](https://www.php.net/manual/en/function.is-scalar.php) and cleaned with [intval()](https://www.php.net/manual/en/function.intval.php) Also [absint()](https://developer.wordpress.org/reference/functions/absint/) is used on the following values: ``` page_id year monthnum day w paged hour minute second attachment_id ``` Also, a `preg_replace('|[^0-9]|'...)` is run on `m`, `cat`, `author` to only allow comma separated list of positive or negative integers on these. For other values at this point, only the trim() function is used. This is the case for: ``` pagename name title ``` After this, the method starts checking what type of query we are running. Is it a search? An attachment? A page? A single post? ... If a `pagename` is set then we call (without sanitizing the value) `get_page_by_path($qv['pagename'])`. But checking that function source we can see that the value is sanitized with [esc\_sql()](https://developer.wordpress.org/reference/functions/esc_sql/) **before it's used for a database request**. After that, we can see that when the keys `post_type` or `post_status` are used, they are both sanitized with [sanitize\_key()](https://developer.wordpress.org/reference/functions/sanitize_key/) (Only lowercase alphanumeric characters, dashes, and underscores are allowed). For the taxonomy related parameters, the `parse_tax_query()` method is called. `category__and`, `category__in`, `category__not_in`, `tag_id`, `tag__in`, `tag__not_in`, `tag__and` are sanitized with [absint()](https://developer.wordpress.org/reference/functions/absint/) `tag_slug__in` and `tag_slug__and` are sanitized with [sanitize\_title\_for\_query()](https://developer.wordpress.org/reference/functions/sanitize_title_for_query/) At this point the `parse_query()` method is over, but we still are inside the `get_posts()` method. `posts_per_page` is sanitized. `title` is being used unsanitized but with a [prepared statement](https://www.php.net/manual/en/mysqli.prepare.php). You may find this question interesting: [Are prepared statements enough to prevent SQL injection?](https://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection) Then we have `post__in` and `post__not_in` that are being sanitized with [absint()](https://developer.wordpress.org/reference/functions/absint/). And if you keep reading the code and pay attention, you will see that all the keys are actually being sanitized before they get to touch a SQL statement or a prepared statement is used instead. So, to answer your original question: **Does WordPress sanitize arguments to WP\_Query?** It does sanitize most of them but not all. For example, `pagename`, `name` and `title` are only "cleaned" with the [trim()](https://www.php.net/manual/en/function.trim.php) function (does not return SQL safe values!). But for the values that are not sanitized, a prepared statement is used to perform the database request. Should you trust this? ---------------------- Well, in this specific case I would prefer to go for the possibly **redundant** just presanitize everything approach before you throw it into the query. Me too, as an engineering student, I would love a solid yes or no answer. But note that the WordPress codebase has evolved in a natural way so it's just like nature: *messy*. It does not mean it's bad. But messy means that there could be an unseen edge-case where somebody could potentially sneak in with a bomb. And you can prevent that by just doubling your guards!
387,683
<p>Anyone know how to sanitize the $_POST for wordpress?</p> <pre><code>$args = array( 's' =&gt; esc_attr( $_POST['keyword'] ), ); </code></pre>
[ { "answer_id": 387924, "author": "Cas Dekkers", "author_id": 153884, "author_profile": "https://wordpress.stackexchange.com/users/153884", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>I want to know if I have to sanitize user input for <strong>any</strong> of the other par...
2021/05/05
[ "https://wordpress.stackexchange.com/questions/387683", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/205932/" ]
Anyone know how to sanitize the $\_POST for wordpress? ``` $args = array( 's' => esc_attr( $_POST['keyword'] ), ); ```
It's actually a good question. Of course user input cannot be trusted, but also sanitizing the same value twice "just in case" isn't the best solution for a problem. The only real answer to this question can be given by looking at the code and following what goes on. And after reading it for a few hours, here is what I can say about it: > > WP Query sanitizes the values but it doesn't do it all in one place. Values are being sanitized before they are actually used. It's a very organic and *on the go* approach. Also, not all of the values are sanitized, but in those cases a prepared statement is used for the SQL query. > > > Let's get into detail --------------------- So, what happens when we do: ``` $query = new WP_Query($args); ``` The WP\_Query class constructor checks if the `$args` is an empty array or not. And if it's not, it will run its `query()` method passing the `$args` array (which is at this point called `$query` array). ``` $this->query($query); ``` The `query()` method calls the `init()` method which unsets possible previous values and sets new defaults. Then it runs [wp\_parse\_args()](https://developer.wordpress.org/reference/functions/wp_parse_args/) on the `$args` array. This function does not sanitize anything, it serves like a bridge between default data and input data. The next call is for the `get_posts()` method, which is in charge of retrieving the posts based on the given query variables. The first thing that is called inside the `get_posts()` method is the `parse_query()` method, which starts by calling the `fill_query_vars()` method (this one makes sure that a list of default keys are set. The ones that are not, get set with an empty string or empty array depending on the case). Then, still inside the `parse_query()` method, the first santization takes place. `p` is checked against [is\_scalar()](https://www.php.net/manual/en/function.is-scalar.php) and cleaned with [intval()](https://www.php.net/manual/en/function.intval.php) Also [absint()](https://developer.wordpress.org/reference/functions/absint/) is used on the following values: ``` page_id year monthnum day w paged hour minute second attachment_id ``` Also, a `preg_replace('|[^0-9]|'...)` is run on `m`, `cat`, `author` to only allow comma separated list of positive or negative integers on these. For other values at this point, only the trim() function is used. This is the case for: ``` pagename name title ``` After this, the method starts checking what type of query we are running. Is it a search? An attachment? A page? A single post? ... If a `pagename` is set then we call (without sanitizing the value) `get_page_by_path($qv['pagename'])`. But checking that function source we can see that the value is sanitized with [esc\_sql()](https://developer.wordpress.org/reference/functions/esc_sql/) **before it's used for a database request**. After that, we can see that when the keys `post_type` or `post_status` are used, they are both sanitized with [sanitize\_key()](https://developer.wordpress.org/reference/functions/sanitize_key/) (Only lowercase alphanumeric characters, dashes, and underscores are allowed). For the taxonomy related parameters, the `parse_tax_query()` method is called. `category__and`, `category__in`, `category__not_in`, `tag_id`, `tag__in`, `tag__not_in`, `tag__and` are sanitized with [absint()](https://developer.wordpress.org/reference/functions/absint/) `tag_slug__in` and `tag_slug__and` are sanitized with [sanitize\_title\_for\_query()](https://developer.wordpress.org/reference/functions/sanitize_title_for_query/) At this point the `parse_query()` method is over, but we still are inside the `get_posts()` method. `posts_per_page` is sanitized. `title` is being used unsanitized but with a [prepared statement](https://www.php.net/manual/en/mysqli.prepare.php). You may find this question interesting: [Are prepared statements enough to prevent SQL injection?](https://stackoverflow.com/questions/134099/are-pdo-prepared-statements-sufficient-to-prevent-sql-injection) Then we have `post__in` and `post__not_in` that are being sanitized with [absint()](https://developer.wordpress.org/reference/functions/absint/). And if you keep reading the code and pay attention, you will see that all the keys are actually being sanitized before they get to touch a SQL statement or a prepared statement is used instead. So, to answer your original question: **Does WordPress sanitize arguments to WP\_Query?** It does sanitize most of them but not all. For example, `pagename`, `name` and `title` are only "cleaned" with the [trim()](https://www.php.net/manual/en/function.trim.php) function (does not return SQL safe values!). But for the values that are not sanitized, a prepared statement is used to perform the database request. Should you trust this? ---------------------- Well, in this specific case I would prefer to go for the possibly **redundant** just presanitize everything approach before you throw it into the query. Me too, as an engineering student, I would love a solid yes or no answer. But note that the WordPress codebase has evolved in a natural way so it's just like nature: *messy*. It does not mean it's bad. But messy means that there could be an unseen edge-case where somebody could potentially sneak in with a bomb. And you can prevent that by just doubling your guards!
387,722
<p>i have to create a specifif form ta register data into the database and send a mail without refreshing the page</p> <p>so i create a script.js file :</p> <pre><code> (function ($) { $(document).ready(function () { jQuery('form[name=&quot;form_result&quot;]').on('submit', function() { var form_data = jQuery(this).serializeArray(); console.log('hello'); form_data.push({&quot;name&quot; : &quot;security&quot;, &quot;value&quot; : ajax_nonce }); console.log(form_data); // Here is the ajax petition jQuery.ajax({ url : ajax_url, type : 'post', data : form_data, success : function( response ) { // You can craft something here to handle the message return alert(response); }, fail : function( err ) { alert(&quot;there was an error: &quot; + err ); } }); // This return prevents the submit event to refresh the page. return false; }); }); })(jQuery); </code></pre> <p>in my function.php file i declare has follow :</p> <pre><code>function javascript_variables(){ ?&gt; &lt;script type=&quot;text/javascript&quot;&gt; var ajax_url = '&lt;?php echo admin_url( &quot;admin-ajax.php&quot; ); ?&gt;'; var ajax_nonce = '&lt;?php echo wp_create_nonce( &quot;secure_nonce_name&quot; ); ?&gt;'; &lt;/script&gt;&lt;?php } add_action ( 'wp_head', 'javascript_variables' ); //AJAX REQUEST function twentytwentychild_asset() { // ... wp_enqueue_script('jquery'); // Charger notre script wp_enqueue_script( 'twentytwentychild', get_stylesheet_directory_uri(). '/assets/js/script.js', array('jquery'), '1.0', true ); // Envoyer une variable de PHP à JS proprement wp_localize_script('twentytwentychild', 'ajaxurl', admin_url('admin-ajax.php')); } add_action('wp_enqueue_scripts', 'twentytwentychild_asset'); add_action('wp_ajax_send_form', 'send_form'); // This is for authenticated users add_action('wp_ajax_nopriv_send_form', 'send_form'); function send_form(){ // This is a secure process to validate if this request comes from a valid source. check_ajax_referer( 'secure-nonce-name', 'security' ); /** * First we make some validations, * I think you are able to put better validations and sanitizations. =) */ if ( empty( $_POST[&quot;name&quot;] ) ) { echo &quot;Insert your name please&quot;; wp_die(); } if ( ! filter_var( $_POST[&quot;email&quot;], FILTER_VALIDATE_EMAIL ) ) { echo 'Insert your email please'; wp_die(); } if ( empty( $_POST[&quot;fcPhone&quot;] ) ) { echo &quot;Insert your phone please&quot;; wp_die(); } $to = 'test@gmail.com'; $subject = 'Un potentiel consultant viens de faire une simulation!'; $body = 'From: ' . $_POST['name'] . '\n'; $body .= 'Email: ' . $_POST['email'] . '\n'; $body .= 'Message: ' . $_POST['fcPhone'] . '\n'; $headers = array('Content-Type: text/html; charset=UTF-8'); wp_mail( $to, $subject, $body, $headers ); echo 'Done!'; wp_die(); } </code></pre> <p>and my template page it's a simple form :</p> <pre><code>&lt;form action=&quot;&quot; method=&quot;post&quot; name=&quot;form_result&quot;&gt; &lt;div id=&quot;simulation_form&quot;&gt; &lt;div style=&quot;margin-bottom: 2rem; display: flex;&quot;&gt; &lt;div class=&quot;vc_col-sm-4&quot;&gt; &lt;div class=&quot;simulation_form_q&quot;&gt;Votre name:*&lt;/div&gt; &lt;div class=&quot;simulation_form_r&quot;&gt; &lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot; required&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;vc_col-sm-8&quot;&gt; &lt;div class=&quot;simulation_form_q&quot;&gt;Votre email:*&lt;/div&gt; &lt;div class=&quot;simulation_form_r&quot;&gt; &lt;input type=&quot;email&quot; name=&quot;email&quot; id=&quot;email&quot; required&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;vc_col-sm-8&quot;&gt; &lt;div class=&quot;simulation_form_q&quot;&gt;Votre numero de telephone:*&lt;/div&gt; &lt;div class=&quot;simulation_form_r&quot;&gt; &lt;input type=&quot;text&quot; name=&quot;fcPhone&quot; id=&quot;telephone&quot; required&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;input type=&quot;hidden&quot; name=&quot;action&quot; value=&quot;send_form&quot; style=&quot;display: none; visibility: hidden; opacity: 0;&quot;/&gt; &lt;div class=&quot;simulation_form_btn&quot;&gt; &lt;input type=&quot;submit&quot; value=&quot;calculez vos revenus&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>but when i send the Ajax request i have 403 error forbidden I don't know why i clear the cache and the cookie i use console log to debug the ajax request and it send all the data yet i have still that 403 ERROR and i don't know how to solve it</p>
[ { "answer_id": 387724, "author": "Rajilesh Panoli", "author_id": 68892, "author_profile": "https://wordpress.stackexchange.com/users/68892", "pm_score": 0, "selected": false, "text": "<pre><code>check_ajax_referer( 'secure-nonce-name', 'security' );\n</code></pre>\n<p>Try this instead a...
2021/05/05
[ "https://wordpress.stackexchange.com/questions/387722", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/153966/" ]
i have to create a specifif form ta register data into the database and send a mail without refreshing the page so i create a script.js file : ``` (function ($) { $(document).ready(function () { jQuery('form[name="form_result"]').on('submit', function() { var form_data = jQuery(this).serializeArray(); console.log('hello'); form_data.push({"name" : "security", "value" : ajax_nonce }); console.log(form_data); // Here is the ajax petition jQuery.ajax({ url : ajax_url, type : 'post', data : form_data, success : function( response ) { // You can craft something here to handle the message return alert(response); }, fail : function( err ) { alert("there was an error: " + err ); } }); // This return prevents the submit event to refresh the page. return false; }); }); })(jQuery); ``` in my function.php file i declare has follow : ``` function javascript_variables(){ ?> <script type="text/javascript"> var ajax_url = '<?php echo admin_url( "admin-ajax.php" ); ?>'; var ajax_nonce = '<?php echo wp_create_nonce( "secure_nonce_name" ); ?>'; </script><?php } add_action ( 'wp_head', 'javascript_variables' ); //AJAX REQUEST function twentytwentychild_asset() { // ... wp_enqueue_script('jquery'); // Charger notre script wp_enqueue_script( 'twentytwentychild', get_stylesheet_directory_uri(). '/assets/js/script.js', array('jquery'), '1.0', true ); // Envoyer une variable de PHP à JS proprement wp_localize_script('twentytwentychild', 'ajaxurl', admin_url('admin-ajax.php')); } add_action('wp_enqueue_scripts', 'twentytwentychild_asset'); add_action('wp_ajax_send_form', 'send_form'); // This is for authenticated users add_action('wp_ajax_nopriv_send_form', 'send_form'); function send_form(){ // This is a secure process to validate if this request comes from a valid source. check_ajax_referer( 'secure-nonce-name', 'security' ); /** * First we make some validations, * I think you are able to put better validations and sanitizations. =) */ if ( empty( $_POST["name"] ) ) { echo "Insert your name please"; wp_die(); } if ( ! filter_var( $_POST["email"], FILTER_VALIDATE_EMAIL ) ) { echo 'Insert your email please'; wp_die(); } if ( empty( $_POST["fcPhone"] ) ) { echo "Insert your phone please"; wp_die(); } $to = 'test@gmail.com'; $subject = 'Un potentiel consultant viens de faire une simulation!'; $body = 'From: ' . $_POST['name'] . '\n'; $body .= 'Email: ' . $_POST['email'] . '\n'; $body .= 'Message: ' . $_POST['fcPhone'] . '\n'; $headers = array('Content-Type: text/html; charset=UTF-8'); wp_mail( $to, $subject, $body, $headers ); echo 'Done!'; wp_die(); } ``` and my template page it's a simple form : ``` <form action="" method="post" name="form_result"> <div id="simulation_form"> <div style="margin-bottom: 2rem; display: flex;"> <div class="vc_col-sm-4"> <div class="simulation_form_q">Votre name:*</div> <div class="simulation_form_r"> <input type="text" id="name" name="name" required> </div> </div> <div class="vc_col-sm-8"> <div class="simulation_form_q">Votre email:*</div> <div class="simulation_form_r"> <input type="email" name="email" id="email" required> </div> </div> <div class="vc_col-sm-8"> <div class="simulation_form_q">Votre numero de telephone:*</div> <div class="simulation_form_r"> <input type="text" name="fcPhone" id="telephone" required> </div> </div> </div> <input type="hidden" name="action" value="send_form" style="display: none; visibility: hidden; opacity: 0;"/> <div class="simulation_form_btn"> <input type="submit" value="calculez vos revenus"> </div> </div> </form> ``` but when i send the Ajax request i have 403 error forbidden I don't know why i clear the cache and the cookie i use console log to debug the ajax request and it send all the data yet i have still that 403 ERROR and i don't know how to solve it
**Short answer — how can you solve the problem:** When you call [`check_ajax_referer()`](https://developer.wordpress.org/reference/functions/check_ajax_referer/), use `secure_nonce_name` as the first parameter, i.e. `check_ajax_referer( 'secure_nonce_name', 'security' )`. A Longer Answer --------------- The first parameter (which is the nonce action) for `check_ajax_referer()` needs to match the first parameter for [`wp_create_nonce()`](https://developer.wordpress.org/reference/functions/wp_create_nonce/), but in your code, they are `secure-nonce-name` and `secure_nonce_name` respectively, hence that would result in the error 403 which basically means "invalid nonce". So make sure the names are equal or that the nonce action is correct, e.g. use `secure_nonce_name` with both the above functions: ```php // In the script in javascript_variables(): var ajax_nonce = '<?php echo wp_create_nonce( "secure_nonce_name" ); ?>'; // Then in the AJAX callback (send_form()): check_ajax_referer( 'secure_nonce_name', 'security' ); ``` Additional Notes ---------------- * You should consider using the [REST API](https://developer.wordpress.org/rest-api/) which, unlike the `admin-ajax.php`, gives a better, human-friendly message when an error is encountered while processing the request.
387,743
<p>I'm trying to create a custom shortcode that will allow me to input custom order field data into an auto generated outbound email template via the <a href="https://www.tychesoftwares.com/store/premium-plugins/custom-order-status-woocommerce/" rel="nofollow noreferrer">Custom Order Status for WooCommerce</a> plugin.</p> <p>My understanding of PHP is limited at best but I came up with is a modified version of the below code that came from a similar question previously answered by Krzysiek Dróżdż:</p> <pre><code>function wcal_abandoned_cart_id_shortcode_callback( $atts ) { $atts = shortcode_atts( array( 'post_id' =&gt; get_the_ID(), ), $atts, 'wcal_abandoned_cart_id' ); return get_post_meta( $atts['post_id'], 'wcal_abandoned_cart_id', true ); } add_shortcode( 'wcal_abandoned_cart_id', 'wcal_abandoned_cart_id_shortcode_callback' ); </code></pre> <p>Wordpress and the plugin seem to recognize the shortcode [wcal_abandoned_cart_id] however the output value is blank. The value that should return for this specific order is &quot;428&quot;. I'm hoping someone can help point me in the right direction.</p> <p>Thanks in advance.</p>
[ { "answer_id": 387724, "author": "Rajilesh Panoli", "author_id": 68892, "author_profile": "https://wordpress.stackexchange.com/users/68892", "pm_score": 0, "selected": false, "text": "<pre><code>check_ajax_referer( 'secure-nonce-name', 'security' );\n</code></pre>\n<p>Try this instead a...
2021/05/06
[ "https://wordpress.stackexchange.com/questions/387743", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/205994/" ]
I'm trying to create a custom shortcode that will allow me to input custom order field data into an auto generated outbound email template via the [Custom Order Status for WooCommerce](https://www.tychesoftwares.com/store/premium-plugins/custom-order-status-woocommerce/) plugin. My understanding of PHP is limited at best but I came up with is a modified version of the below code that came from a similar question previously answered by Krzysiek Dróżdż: ``` function wcal_abandoned_cart_id_shortcode_callback( $atts ) { $atts = shortcode_atts( array( 'post_id' => get_the_ID(), ), $atts, 'wcal_abandoned_cart_id' ); return get_post_meta( $atts['post_id'], 'wcal_abandoned_cart_id', true ); } add_shortcode( 'wcal_abandoned_cart_id', 'wcal_abandoned_cart_id_shortcode_callback' ); ``` Wordpress and the plugin seem to recognize the shortcode [wcal\_abandoned\_cart\_id] however the output value is blank. The value that should return for this specific order is "428". I'm hoping someone can help point me in the right direction. Thanks in advance.
**Short answer — how can you solve the problem:** When you call [`check_ajax_referer()`](https://developer.wordpress.org/reference/functions/check_ajax_referer/), use `secure_nonce_name` as the first parameter, i.e. `check_ajax_referer( 'secure_nonce_name', 'security' )`. A Longer Answer --------------- The first parameter (which is the nonce action) for `check_ajax_referer()` needs to match the first parameter for [`wp_create_nonce()`](https://developer.wordpress.org/reference/functions/wp_create_nonce/), but in your code, they are `secure-nonce-name` and `secure_nonce_name` respectively, hence that would result in the error 403 which basically means "invalid nonce". So make sure the names are equal or that the nonce action is correct, e.g. use `secure_nonce_name` with both the above functions: ```php // In the script in javascript_variables(): var ajax_nonce = '<?php echo wp_create_nonce( "secure_nonce_name" ); ?>'; // Then in the AJAX callback (send_form()): check_ajax_referer( 'secure_nonce_name', 'security' ); ``` Additional Notes ---------------- * You should consider using the [REST API](https://developer.wordpress.org/rest-api/) which, unlike the `admin-ajax.php`, gives a better, human-friendly message when an error is encountered while processing the request.
387,767
<p>I am using get_users() to return a list of users with specified roles. The purpose of this is to generate a dropdown on the front end to mention other users in comments, very similar to the functionality of <a href="https://wordpress.org/plugins/comment-mention/" rel="nofollow noreferrer">https://wordpress.org/plugins/comment-mention/</a>.</p> <p>The problem is that if the current user is in a lower role, such as an author, get_users() does not return higher roles, such as an administrator. In other words, I need a lower user to be able to return users of higher roles as well.</p> <p>I realised that get_users() prevents return higher role users from here: <a href="https://wordpress.stackexchange.com/questions/354939/get-users-wp-user-query-returns-empty-when-logged-out">get_users / WP_User_Query returns empty when logged out</a></p> <p>But I wondered if there was a way around this. This is how I am getting the list of users at the moment</p> <pre><code>&lt;?php // Set arguments. $args = array( 'fields' =&gt; array('user_login'), 'role__in' =&gt; array('administrator','editor','author'), ); // Get usernames. $results = get_users( $args ); ?&gt; </code></pre> <p><em>Just a note here, the desired final result is to return an array of all usernames.</em></p>
[ { "answer_id": 387724, "author": "Rajilesh Panoli", "author_id": 68892, "author_profile": "https://wordpress.stackexchange.com/users/68892", "pm_score": 0, "selected": false, "text": "<pre><code>check_ajax_referer( 'secure-nonce-name', 'security' );\n</code></pre>\n<p>Try this instead a...
2021/05/06
[ "https://wordpress.stackexchange.com/questions/387767", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120722/" ]
I am using get\_users() to return a list of users with specified roles. The purpose of this is to generate a dropdown on the front end to mention other users in comments, very similar to the functionality of <https://wordpress.org/plugins/comment-mention/>. The problem is that if the current user is in a lower role, such as an author, get\_users() does not return higher roles, such as an administrator. In other words, I need a lower user to be able to return users of higher roles as well. I realised that get\_users() prevents return higher role users from here: [get\_users / WP\_User\_Query returns empty when logged out](https://wordpress.stackexchange.com/questions/354939/get-users-wp-user-query-returns-empty-when-logged-out) But I wondered if there was a way around this. This is how I am getting the list of users at the moment ``` <?php // Set arguments. $args = array( 'fields' => array('user_login'), 'role__in' => array('administrator','editor','author'), ); // Get usernames. $results = get_users( $args ); ?> ``` *Just a note here, the desired final result is to return an array of all usernames.*
**Short answer — how can you solve the problem:** When you call [`check_ajax_referer()`](https://developer.wordpress.org/reference/functions/check_ajax_referer/), use `secure_nonce_name` as the first parameter, i.e. `check_ajax_referer( 'secure_nonce_name', 'security' )`. A Longer Answer --------------- The first parameter (which is the nonce action) for `check_ajax_referer()` needs to match the first parameter for [`wp_create_nonce()`](https://developer.wordpress.org/reference/functions/wp_create_nonce/), but in your code, they are `secure-nonce-name` and `secure_nonce_name` respectively, hence that would result in the error 403 which basically means "invalid nonce". So make sure the names are equal or that the nonce action is correct, e.g. use `secure_nonce_name` with both the above functions: ```php // In the script in javascript_variables(): var ajax_nonce = '<?php echo wp_create_nonce( "secure_nonce_name" ); ?>'; // Then in the AJAX callback (send_form()): check_ajax_referer( 'secure_nonce_name', 'security' ); ``` Additional Notes ---------------- * You should consider using the [REST API](https://developer.wordpress.org/rest-api/) which, unlike the `admin-ajax.php`, gives a better, human-friendly message when an error is encountered while processing the request.
387,793
<p>I have looked at a couple of different ways to check when a user, of a particular role, has logged out. The call is made within a plugin.</p> <p>In the main loop I have the following:</p> <pre><code>add_action( 'wp_logout', mmd_JudgeLogoutCheck, 10,0); function mmd_JudgeLogoutCheck() { $current_user = wp_get_current_user(); if ( in_array( 'judge', (array) $current_user-&gt;roles ) ) { mmd_StoreJudgeStatus($current_user-&gt;user_email, JUDGE_LOGGED_OUT, 0); } } </code></pre> <p>Each time the call to the wp_get_current_user returns a blank. That email is key to my functionality. I also tried</p> <pre><code> add_action( 'wp_logout', function() { $user = wp_get_current_user(); mmd_JudgeLogoutCheck($user); // ... }, 10, 0); function mmd_JudgeLogoutCheck($current_user ) { if ( in_array( 'judge', (array) $current_user-&gt;roles ) ) { mmd_StoreJudgeStatus($current_user-&gt;user_email, JUDGE_LOGGED_OUT, 0); } } </code></pre> <p>Same results. Calls that happen earlier do not appear to have user information. Any assistance with how to get which particular user is logging out, would be helpful.</p>
[ { "answer_id": 387796, "author": "Debbie Kurth", "author_id": 119560, "author_profile": "https://wordpress.stackexchange.com/users/119560", "pm_score": -1, "selected": false, "text": "<p>Would you not know it, the minute I wrote the question, I thought of another idea and it worked. Her...
2021/05/06
[ "https://wordpress.stackexchange.com/questions/387793", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119560/" ]
I have looked at a couple of different ways to check when a user, of a particular role, has logged out. The call is made within a plugin. In the main loop I have the following: ``` add_action( 'wp_logout', mmd_JudgeLogoutCheck, 10,0); function mmd_JudgeLogoutCheck() { $current_user = wp_get_current_user(); if ( in_array( 'judge', (array) $current_user->roles ) ) { mmd_StoreJudgeStatus($current_user->user_email, JUDGE_LOGGED_OUT, 0); } } ``` Each time the call to the wp\_get\_current\_user returns a blank. That email is key to my functionality. I also tried ``` add_action( 'wp_logout', function() { $user = wp_get_current_user(); mmd_JudgeLogoutCheck($user); // ... }, 10, 0); function mmd_JudgeLogoutCheck($current_user ) { if ( in_array( 'judge', (array) $current_user->roles ) ) { mmd_StoreJudgeStatus($current_user->user_email, JUDGE_LOGGED_OUT, 0); } } ``` Same results. Calls that happen earlier do not appear to have user information. Any assistance with how to get which particular user is logging out, would be helpful.
**wp\_get\_current\_user()** will never work in this hook, because, `wp_logout` action fires after user is logged out: session destroyed, cookies cleared and current user is set to 0. But `wp_logout` action recieves $user\_id. I will give you a working example, because I do not familiar with your custom functions. ``` //pass $user_id as argument function mmd_JudgeLogoutCheck($user_id) { $user = get_userdata($user_id); if ( $user instanceof WP_User ) { //user email available here die($user->user_email); } } //here last argument should be one add_action( 'wp_logout', 'mmd_JudgeLogoutCheck', 10,1); ```
387,818
<p>I've been struggling to find a solution for this and I don't know if it's the Gutenberg editor or if it's the hook <code>publish_post</code>.</p> <p>Hook:</p> <pre class="lang-php prettyprint-override"><code>function api_method($post_id) { // If this is just a revision, don't send request if ( wp_is_post_revision( $post_id ) ) { return; } // Get Post Object $post = get_post($post_id); open_log($post); $postData = array( 'unit' =&gt; get_post_meta($post_id, 'open_unit', true), 'abstract' =&gt; get_post_meta($post_id, 'open_abstract', true), 'image' =&gt; get_the_post_thumbnail_url($post, 'full'), 'title' =&gt; get_the_title($post), 'url' =&gt; get_the_permalink($post), ); open_log($postData); $auth = base64_encode(get_option('open_up_username') . ':' . get_option('open_up_api_key')); $status = get_post_meta($post_id, 'open_active', true) ? 'active':'paused'; $openUnit = get_post_meta($post_id, 'open_unit', true); // $postMeta = get_post_meta($post_id); // open_log($postMeta); $responseApi = wp_remote_post(OPEN_REMOTE_POST, array( 'headers' =&gt; array('Authorization' =&gt; 'Basic ' . $auth), 'body' =&gt; 'unit='.$openUnit.'&amp;status='.$status.'&amp;abstract='.get_post_meta($post_id, 'open_abstract', true).'&amp;image='.get_the_post_thumbnail_url($post_id, 'full').'&amp;title='.get_the_title($post).'&amp;url='.get_the_permalink($post) ) ); $response = new WP_REST_Response($responseApi, 200); $body = wp_remote_retrieve_body($responseApi); $responseBody = ( ! is_wp_error( $response ) ) ? json_decode( $body, true ) : null; $unit = isset($responseBody['unit']) ? $responseBody['unit'] : ''; open_log($responseBody); open_log($unit); $update = update_post_meta($post_id, 'open_unit', $unit); open_log($update); } </code></pre> <p>I'm using the post meta, featured image and title to post to a third party API. The API verifies the data and then returns a unit hash which I store in the post meta <code>open_unit</code>.</p> <p>I'm also logging the data and responses in a log.txt file, and I'm getting this on initial publish:</p> <pre><code>object(WP_Post)#4421 (24) { [&quot;ID&quot;]=&gt; int(240) [&quot;post_author&quot;]=&gt; string(1) &quot;3&quot; [&quot;post_date&quot;]=&gt; string(19) &quot;2021-05-07 09:57:28&quot; [&quot;post_date_gmt&quot;]=&gt; string(19) &quot;2021-05-07 07:57:28&quot; [&quot;post_content&quot;]=&gt; string(0) &quot;&quot; [&quot;post_title&quot;]=&gt; string(11) &quot;New post v3&quot; [&quot;post_excerpt&quot;]=&gt; string(0) &quot;&quot; [&quot;post_status&quot;]=&gt; string(7) &quot;publish&quot; [&quot;comment_status&quot;]=&gt; string(4) &quot;open&quot; [&quot;ping_status&quot;]=&gt; string(4) &quot;open&quot; [&quot;post_password&quot;]=&gt; string(0) &quot;&quot; [&quot;post_name&quot;]=&gt; string(11) &quot;new-post-v3&quot; [&quot;to_ping&quot;]=&gt; string(0) &quot;&quot; [&quot;pinged&quot;]=&gt; string(0) &quot;&quot; [&quot;post_modified&quot;]=&gt; string(19) &quot;2021-05-07 09:57:28&quot; [&quot;post_modified_gmt&quot;]=&gt; string(19) &quot;2021-05-07 07:57:28&quot; [&quot;post_content_filtered&quot;]=&gt; string(0) &quot;&quot; [&quot;post_parent&quot;]=&gt; int(0) [&quot;guid&quot;]=&gt; string(31) &quot;https://grace.open-up.it/?p=240&quot; [&quot;menu_order&quot;]=&gt; int(0) [&quot;post_type&quot;]=&gt; string(4) &quot;post&quot; [&quot;post_mime_type&quot;]=&gt; string(0) &quot;&quot; [&quot;comment_count&quot;]=&gt; string(1) &quot;0&quot; [&quot;filter&quot;]=&gt; string(3) &quot;raw&quot; } array(5) { [&quot;unit&quot;]=&gt; string(0) &quot;&quot; [&quot;abstract&quot;]=&gt; string(0) &quot;&quot; [&quot;image&quot;]=&gt; bool(false) [&quot;title&quot;]=&gt; string(11) &quot;New post v3&quot; [&quot;url&quot;]=&gt; string(45) &quot;https://grace.open-up.it/recipes/new-post-v3/&quot; } array(2) { [&quot;success&quot;]=&gt; bool(false) [&quot;message&quot;]=&gt; string(83) &quot;Open Up - Si è verificato un problema con l'elaborazione dell'immagine in evidenza&quot; } string(0) &quot;&quot; int(1256) </code></pre> <p>The API is returning and saying that the image is invalid which is true because the image url is not showing in the <code>$postData</code> array.</p> <p>After I edit the title and save, it logs below:</p> <pre><code>object(WP_Post)#4420 (24) { [&quot;ID&quot;]=&gt; int(240) [&quot;post_author&quot;]=&gt; string(1) &quot;3&quot; [&quot;post_date&quot;]=&gt; string(19) &quot;2021-05-07 09:57:28&quot; [&quot;post_date_gmt&quot;]=&gt; string(19) &quot;2021-05-07 07:57:28&quot; [&quot;post_content&quot;]=&gt; string(0) &quot;&quot; [&quot;post_title&quot;]=&gt; string(12) &quot;Edit post v3&quot; [&quot;post_excerpt&quot;]=&gt; string(0) &quot;&quot; [&quot;post_status&quot;]=&gt; string(7) &quot;publish&quot; [&quot;comment_status&quot;]=&gt; string(4) &quot;open&quot; [&quot;ping_status&quot;]=&gt; string(4) &quot;open&quot; [&quot;post_password&quot;]=&gt; string(0) &quot;&quot; [&quot;post_name&quot;]=&gt; string(11) &quot;new-post-v3&quot; [&quot;to_ping&quot;]=&gt; string(0) &quot;&quot; [&quot;pinged&quot;]=&gt; string(0) &quot;&quot; [&quot;post_modified&quot;]=&gt; string(19) &quot;2021-05-07 09:57:40&quot; [&quot;post_modified_gmt&quot;]=&gt; string(19) &quot;2021-05-07 07:57:40&quot; [&quot;post_content_filtered&quot;]=&gt; string(0) &quot;&quot; [&quot;post_parent&quot;]=&gt; int(0) [&quot;guid&quot;]=&gt; string(31) &quot;https://grace.open-up.it/?p=240&quot; [&quot;menu_order&quot;]=&gt; int(0) [&quot;post_type&quot;]=&gt; string(4) &quot;post&quot; [&quot;post_mime_type&quot;]=&gt; string(0) &quot;&quot; [&quot;comment_count&quot;]=&gt; string(1) &quot;0&quot; [&quot;filter&quot;]=&gt; string(3) &quot;raw&quot; } array(5) { [&quot;unit&quot;]=&gt; string(0) &quot;&quot; [&quot;abstract&quot;]=&gt; string(213) &quot;Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&quot; [&quot;image&quot;]=&gt; string(79) &quot;https://grace.open-up.it/wp-content/uploads/2020/10/7540312530_37e709d2f4_b.jpg&quot; [&quot;title&quot;]=&gt; string(12) &quot;Edit post v3&quot; [&quot;url&quot;]=&gt; string(45) &quot;https://grace.open-up.it/recipes/new-post-v3/&quot; } array(2) { [&quot;success&quot;]=&gt; bool(true) [&quot;unit&quot;]=&gt; string(36) &quot;e12213d3-058b-40f9-b487-a1776470f37b&quot; } string(36) &quot;e12213d3-058b-40f9-b487-a1776470f37b&quot; bool(true) </code></pre> <p>I really am confused about how the Wordpress editor handles the state for publishing and confused why it's not returning the meta and featured image. I found this user having the same issue(I think) with the same hook and isn't resolved either <a href="https://stackoverflow.com/questions/35666305/get-featured-image-url-after-publishing">https://stackoverflow.com/questions/35666305/get-featured-image-url-after-publishing</a></p> <p>I have also done a recording of this <a href="https://share.getcloudapp.com/eDujbqJp" rel="nofollow noreferrer">https://share.getcloudapp.com/eDujbqJp</a></p> <p>I hope someone can advise or give direction regarding this. Thank you in advance</p>
[ { "answer_id": 387850, "author": "anton", "author_id": 97934, "author_profile": "https://wordpress.stackexchange.com/users/97934", "pm_score": 0, "selected": false, "text": "<p><code>{$new_status}_{$post-&gt;post_type}</code> hook or <code>publish_post</code> fires when a post is transit...
2021/05/07
[ "https://wordpress.stackexchange.com/questions/387818", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54323/" ]
I've been struggling to find a solution for this and I don't know if it's the Gutenberg editor or if it's the hook `publish_post`. Hook: ```php function api_method($post_id) { // If this is just a revision, don't send request if ( wp_is_post_revision( $post_id ) ) { return; } // Get Post Object $post = get_post($post_id); open_log($post); $postData = array( 'unit' => get_post_meta($post_id, 'open_unit', true), 'abstract' => get_post_meta($post_id, 'open_abstract', true), 'image' => get_the_post_thumbnail_url($post, 'full'), 'title' => get_the_title($post), 'url' => get_the_permalink($post), ); open_log($postData); $auth = base64_encode(get_option('open_up_username') . ':' . get_option('open_up_api_key')); $status = get_post_meta($post_id, 'open_active', true) ? 'active':'paused'; $openUnit = get_post_meta($post_id, 'open_unit', true); // $postMeta = get_post_meta($post_id); // open_log($postMeta); $responseApi = wp_remote_post(OPEN_REMOTE_POST, array( 'headers' => array('Authorization' => 'Basic ' . $auth), 'body' => 'unit='.$openUnit.'&status='.$status.'&abstract='.get_post_meta($post_id, 'open_abstract', true).'&image='.get_the_post_thumbnail_url($post_id, 'full').'&title='.get_the_title($post).'&url='.get_the_permalink($post) ) ); $response = new WP_REST_Response($responseApi, 200); $body = wp_remote_retrieve_body($responseApi); $responseBody = ( ! is_wp_error( $response ) ) ? json_decode( $body, true ) : null; $unit = isset($responseBody['unit']) ? $responseBody['unit'] : ''; open_log($responseBody); open_log($unit); $update = update_post_meta($post_id, 'open_unit', $unit); open_log($update); } ``` I'm using the post meta, featured image and title to post to a third party API. The API verifies the data and then returns a unit hash which I store in the post meta `open_unit`. I'm also logging the data and responses in a log.txt file, and I'm getting this on initial publish: ``` object(WP_Post)#4421 (24) { ["ID"]=> int(240) ["post_author"]=> string(1) "3" ["post_date"]=> string(19) "2021-05-07 09:57:28" ["post_date_gmt"]=> string(19) "2021-05-07 07:57:28" ["post_content"]=> string(0) "" ["post_title"]=> string(11) "New post v3" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(4) "open" ["post_password"]=> string(0) "" ["post_name"]=> string(11) "new-post-v3" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2021-05-07 09:57:28" ["post_modified_gmt"]=> string(19) "2021-05-07 07:57:28" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(31) "https://grace.open-up.it/?p=240" ["menu_order"]=> int(0) ["post_type"]=> string(4) "post" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["filter"]=> string(3) "raw" } array(5) { ["unit"]=> string(0) "" ["abstract"]=> string(0) "" ["image"]=> bool(false) ["title"]=> string(11) "New post v3" ["url"]=> string(45) "https://grace.open-up.it/recipes/new-post-v3/" } array(2) { ["success"]=> bool(false) ["message"]=> string(83) "Open Up - Si è verificato un problema con l'elaborazione dell'immagine in evidenza" } string(0) "" int(1256) ``` The API is returning and saying that the image is invalid which is true because the image url is not showing in the `$postData` array. After I edit the title and save, it logs below: ``` object(WP_Post)#4420 (24) { ["ID"]=> int(240) ["post_author"]=> string(1) "3" ["post_date"]=> string(19) "2021-05-07 09:57:28" ["post_date_gmt"]=> string(19) "2021-05-07 07:57:28" ["post_content"]=> string(0) "" ["post_title"]=> string(12) "Edit post v3" ["post_excerpt"]=> string(0) "" ["post_status"]=> string(7) "publish" ["comment_status"]=> string(4) "open" ["ping_status"]=> string(4) "open" ["post_password"]=> string(0) "" ["post_name"]=> string(11) "new-post-v3" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) "" ["post_modified"]=> string(19) "2021-05-07 09:57:40" ["post_modified_gmt"]=> string(19) "2021-05-07 07:57:40" ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0) ["guid"]=> string(31) "https://grace.open-up.it/?p=240" ["menu_order"]=> int(0) ["post_type"]=> string(4) "post" ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0" ["filter"]=> string(3) "raw" } array(5) { ["unit"]=> string(0) "" ["abstract"]=> string(213) "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ["image"]=> string(79) "https://grace.open-up.it/wp-content/uploads/2020/10/7540312530_37e709d2f4_b.jpg" ["title"]=> string(12) "Edit post v3" ["url"]=> string(45) "https://grace.open-up.it/recipes/new-post-v3/" } array(2) { ["success"]=> bool(true) ["unit"]=> string(36) "e12213d3-058b-40f9-b487-a1776470f37b" } string(36) "e12213d3-058b-40f9-b487-a1776470f37b" bool(true) ``` I really am confused about how the Wordpress editor handles the state for publishing and confused why it's not returning the meta and featured image. I found this user having the same issue(I think) with the same hook and isn't resolved either <https://stackoverflow.com/questions/35666305/get-featured-image-url-after-publishing> I have also done a recording of this <https://share.getcloudapp.com/eDujbqJp> I hope someone can advise or give direction regarding this. Thank you in advance
> > I don't know if it's the Gutenberg editor or if it's the hook > `publish_post` > > > The hook itself works, and if you used the old WordPress post editor, then the issue in question would **not** happen. So you can say that it's the Gutenberg/block editor. > > why it's not returning the meta and featured image > > > Because Gutenberg uses the REST API, and by the time the `publish_post` hook is fired (when `wp_update_post()` is called — see [source](https://core.trac.wordpress.org/browser/tags/5.7.1/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php#L808)), the post's featured image and other meta data have not yet been saved/processed. How to fix the issue -------------------- *If you're using WordPress **5.6** or later*, then for what you're trying to do, you would want to use the [`wp_after_insert_post` hook](https://developer.wordpress.org/reference/hooks/wp_after_insert_post/) which works well with the old/classic editor and the Gutenberg/block editor. Excerpt from <https://make.wordpress.org/core/2020/11/20/new-action-wp_after_insert_post-in-wordpress-5-6/>: > > New action wp\_after\_insert\_post in WordPress 5.6. > ==================================================== > > > The new action `wp_after_insert_post` has been added to WordPress > 5.6 to allow theme and plugin developers to run custom code after a post and its terms and meta data have been updated. > > > The `save_post` and related actions have commonly been used for this > purpose but these hooks can fire *before* terms and meta data are > updated outside of the classic editor. (For example in the REST API, > via the block editor, within the Customizer and when an auto-draft > is created.) > > > The new action sends up to four parameters: > > > * `$post_id` The post ID has been updated, an `integer`. > * `$post` The full post object in its updated form, a `WP_Post` object. > * `$updated` Whether the post has been updated or not, a `boolean`. > * `$post_before` The full post object prior to the update, a `WP_Post` object. For new posts this is `null`. > > > And here's an example which mimics the `publish_post` hook, i.e. the `// your code here` part below would only run if the post is being published and is *not* already published (the post status is not already `publish`): ```php add_action( 'wp_after_insert_post', 'my_wp_after_insert_post', 10, 4 ); // Note: As of writing, the third parameter is actually named $update and not $updated. function my_wp_after_insert_post( $post_id, $post, $update, $post_before ) { if ( 'publish' !== $post->post_status || ( $post_before && 'publish' === $post_before->post_status ) || wp_is_post_revision( $post_id ) ) { return; } // your code here } ```
387,840
<p>I'm trying to add pagination through function.php. No Output! What I'm missing?</p> <pre><code>function simpleblog() { $query = 'posts_per_page=6'; $queryObject = new WP_Query($query); // The Loop... if ($queryObject-&gt;have_posts()) { while ($queryObject-&gt;have_posts()) { $queryObject-&gt;the_post(); //the_title(); //the_content(); get_template_part( 'content' ); echo '&lt;hr class=&quot;empty-space-hr&quot;&gt;'; } } else { //no post found } echo'&lt;div class=&quot;pagination&quot;&gt;'; echo paginate_links( array( 'base' =&gt; str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ), 'total' =&gt; $query-&gt;max_num_pages, 'current' =&gt; max( 1, get_query_var( 'paged' ) ), 'format' =&gt; '?paged=%#%', 'show_all' =&gt; false, 'type' =&gt; 'plain', 'end_size' =&gt; 2, 'mid_size' =&gt; 1, 'prev_next' =&gt; true, 'prev_text' =&gt; sprintf( '&lt;i&gt;&lt;/i&gt; %1$s', __( 'Newer Posts', 'text-domain' ) ), 'next_text' =&gt; sprintf( '%1$s &lt;i&gt;&lt;/i&gt;', __( 'Older Posts', 'text-domain' ) ), 'add_args' =&gt; false, 'add_fragment' =&gt; '', ) ); echo '&lt;/div&gt;'; /* Restore original Post Data */ wp_reset_postdata(); } add_shortcode( 'simpleblog', 'simpleblog' ); </code></pre>
[ { "answer_id": 387850, "author": "anton", "author_id": 97934, "author_profile": "https://wordpress.stackexchange.com/users/97934", "pm_score": 0, "selected": false, "text": "<p><code>{$new_status}_{$post-&gt;post_type}</code> hook or <code>publish_post</code> fires when a post is transit...
2021/05/07
[ "https://wordpress.stackexchange.com/questions/387840", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60272/" ]
I'm trying to add pagination through function.php. No Output! What I'm missing? ``` function simpleblog() { $query = 'posts_per_page=6'; $queryObject = new WP_Query($query); // The Loop... if ($queryObject->have_posts()) { while ($queryObject->have_posts()) { $queryObject->the_post(); //the_title(); //the_content(); get_template_part( 'content' ); echo '<hr class="empty-space-hr">'; } } else { //no post found } echo'<div class="pagination">'; echo paginate_links( array( 'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ), 'total' => $query->max_num_pages, 'current' => max( 1, get_query_var( 'paged' ) ), 'format' => '?paged=%#%', 'show_all' => false, 'type' => 'plain', 'end_size' => 2, 'mid_size' => 1, 'prev_next' => true, 'prev_text' => sprintf( '<i></i> %1$s', __( 'Newer Posts', 'text-domain' ) ), 'next_text' => sprintf( '%1$s <i></i>', __( 'Older Posts', 'text-domain' ) ), 'add_args' => false, 'add_fragment' => '', ) ); echo '</div>'; /* Restore original Post Data */ wp_reset_postdata(); } add_shortcode( 'simpleblog', 'simpleblog' ); ```
> > I don't know if it's the Gutenberg editor or if it's the hook > `publish_post` > > > The hook itself works, and if you used the old WordPress post editor, then the issue in question would **not** happen. So you can say that it's the Gutenberg/block editor. > > why it's not returning the meta and featured image > > > Because Gutenberg uses the REST API, and by the time the `publish_post` hook is fired (when `wp_update_post()` is called — see [source](https://core.trac.wordpress.org/browser/tags/5.7.1/src/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php#L808)), the post's featured image and other meta data have not yet been saved/processed. How to fix the issue -------------------- *If you're using WordPress **5.6** or later*, then for what you're trying to do, you would want to use the [`wp_after_insert_post` hook](https://developer.wordpress.org/reference/hooks/wp_after_insert_post/) which works well with the old/classic editor and the Gutenberg/block editor. Excerpt from <https://make.wordpress.org/core/2020/11/20/new-action-wp_after_insert_post-in-wordpress-5-6/>: > > New action wp\_after\_insert\_post in WordPress 5.6. > ==================================================== > > > The new action `wp_after_insert_post` has been added to WordPress > 5.6 to allow theme and plugin developers to run custom code after a post and its terms and meta data have been updated. > > > The `save_post` and related actions have commonly been used for this > purpose but these hooks can fire *before* terms and meta data are > updated outside of the classic editor. (For example in the REST API, > via the block editor, within the Customizer and when an auto-draft > is created.) > > > The new action sends up to four parameters: > > > * `$post_id` The post ID has been updated, an `integer`. > * `$post` The full post object in its updated form, a `WP_Post` object. > * `$updated` Whether the post has been updated or not, a `boolean`. > * `$post_before` The full post object prior to the update, a `WP_Post` object. For new posts this is `null`. > > > And here's an example which mimics the `publish_post` hook, i.e. the `// your code here` part below would only run if the post is being published and is *not* already published (the post status is not already `publish`): ```php add_action( 'wp_after_insert_post', 'my_wp_after_insert_post', 10, 4 ); // Note: As of writing, the third parameter is actually named $update and not $updated. function my_wp_after_insert_post( $post_id, $post, $update, $post_before ) { if ( 'publish' !== $post->post_status || ( $post_before && 'publish' === $post_before->post_status ) || wp_is_post_revision( $post_id ) ) { return; } // your code here } ```