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
400,841
<p>I have bought a wordpress template but the developers say they cannot help me with what I need.</p> <p>The theme has a hotel reservation system integrated, and the form brings a field to “place” the user email, however this option is disabled, only a Text appears that says “Need to be logged in” but when I click over there nothing happens.</p> <p>I guess that email field should at least take me to a page (maybe user registration), or at least that's what I wish to happen.</p> <p>I've been reviewing the PHP code of that form, but I really don't know what to do because I don't handle PHP, I don't know how I could solve this issue.</p> <p>I tried several times to fix that by adding an a href= but nothing happens.</p> <p>Is there someone who could please help me or tell me what to do?</p> <p>This is the code of that php field on the form:</p> <pre><code>&lt;span class=&quot;mkdf-input-email&quot;&gt; &lt;label&gt;&lt;?php esc_html_e( 'Email:', 'mkdf-hotel' ) ?&gt;&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;mkdf-res-email&quot; name=&quot;user_email&quot; placeholder=&quot;&lt;?php esc_attr_e( 'Need to be logged in', 'mkdf-hotel' ) ?&gt;&quot; disabled value=&quot;&lt;?php echo esc_attr($email) ?&gt;&quot; /&gt; &lt;/span&gt; </code></pre> <p>I would like to add this url link (<a href="https://www.mayanhills.com/cuenta-de-usuario" rel="nofollow noreferrer">https://www.mayanhills.com/cuenta-de-usuario</a>) on the `Need to be logged in’ text field.</p> <p>Here is the page link to see the form if you want to do that:</p> <p><a href="http://www.mayanhills.com/hotel-room/habitacion-sencilla/" rel="nofollow noreferrer">http://www.mayanhills.com/hotel-room/habitacion-sencilla/</a></p> <p>Sorry about my english, hope somebody can understand and help me please.</p> <p>Thank you so much</p>
[ { "answer_id": 400821, "author": "Maytha8", "author_id": 200755, "author_profile": "https://wordpress.stackexchange.com/users/200755", "pm_score": 0, "selected": false, "text": "<p>Use <code>user_can( wp_get_current_user(), 'administrator' )</code> to determine if the user is logged in a...
2022/01/02
[ "https://wordpress.stackexchange.com/questions/400841", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/217483/" ]
I have bought a wordpress template but the developers say they cannot help me with what I need. The theme has a hotel reservation system integrated, and the form brings a field to “place” the user email, however this option is disabled, only a Text appears that says “Need to be logged in” but when I click over there nothing happens. I guess that email field should at least take me to a page (maybe user registration), or at least that's what I wish to happen. I've been reviewing the PHP code of that form, but I really don't know what to do because I don't handle PHP, I don't know how I could solve this issue. I tried several times to fix that by adding an a href= but nothing happens. Is there someone who could please help me or tell me what to do? This is the code of that php field on the form: ``` <span class="mkdf-input-email"> <label><?php esc_html_e( 'Email:', 'mkdf-hotel' ) ?></label> <input type="text" class="mkdf-res-email" name="user_email" placeholder="<?php esc_attr_e( 'Need to be logged in', 'mkdf-hotel' ) ?>" disabled value="<?php echo esc_attr($email) ?>" /> </span> ``` I would like to add this url link (<https://www.mayanhills.com/cuenta-de-usuario>) on the `Need to be logged in’ text field. Here is the page link to see the form if you want to do that: <http://www.mayanhills.com/hotel-room/habitacion-sencilla/> Sorry about my english, hope somebody can understand and help me please. Thank you so much
I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted `remove_action` on it. What Maythan8 answered will work but it can be done with fewer functions. ```php add_action('template_redirect', 'bt_maintenance_redirect'); function bt_maintenance_redirect () { if (is_page(4848) || current_user_can('administrator')) return; if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit; } ``` You used `esc_url_raw` but this function is used for escaping url before DB storage, if your url is just for output use `esc_url`. Also better to use `wp_safe_redirect` if you are redirecting from and to the same host.
400,872
<p>I have extracted the reply emails. The original emails are saved as CPT and work as Tickets in my plugin. I want the reply email to go as a comment to the original email.</p> <pre><code> for($j = 1; $j &lt;= $total; $j++){ $mail = $emails-&gt;get($j); //This checks if the email is reply or not and if the email is reply make it comment to its original post. if ((!empty($mail['header']-&gt;references )) &amp;&amp; ($mail['header']-&gt;references ) == ($mail['header']-&gt;message_id ) { $comment_array = array( 'comment_content' =&gt; $mail['body'], 'comment_post_ID' =&gt; , ) wp_insert_comment($comment_array); } } </code></pre> <p>I have distinguished the reply email and original email but I don't how to keep those emails as comments to the original email. This is how my <code>wp_insert_post</code> looks like:</p> <pre><code>$post_array = array( 'post_content' =&gt; $mail['body'], 'post_title' =&gt; $mail['header']-&gt;subject, 'post_type' =&gt; 'faqpress-tickets', 'post_author' =&gt; ucwords(strstr($mail['header']-&gt;fromaddress, '&lt;',true)), 'post_status' =&gt; 'publish', 'meta_input' =&gt; array( 'User' =&gt; ucwords(strstr($mail['header']-&gt;fromaddress, '&lt;',true)), 'From' =&gt; preg_replace('~[&lt;&gt;]~', '', strstr($mail['header']-&gt;fromaddress, '&lt;')), 'Email' =&gt; $mail['header']-&gt;Date, 'ticket_id' =&gt; $mail['header']-&gt;message_id, ), ); //wp_insert_post( $post_array ); </code></pre> <p>If anyone knows how to do it. It will be a great help.</p>
[ { "answer_id": 400821, "author": "Maytha8", "author_id": 200755, "author_profile": "https://wordpress.stackexchange.com/users/200755", "pm_score": 0, "selected": false, "text": "<p>Use <code>user_can( wp_get_current_user(), 'administrator' )</code> to determine if the user is logged in a...
2022/01/03
[ "https://wordpress.stackexchange.com/questions/400872", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190661/" ]
I have extracted the reply emails. The original emails are saved as CPT and work as Tickets in my plugin. I want the reply email to go as a comment to the original email. ``` for($j = 1; $j <= $total; $j++){ $mail = $emails->get($j); //This checks if the email is reply or not and if the email is reply make it comment to its original post. if ((!empty($mail['header']->references )) && ($mail['header']->references ) == ($mail['header']->message_id ) { $comment_array = array( 'comment_content' => $mail['body'], 'comment_post_ID' => , ) wp_insert_comment($comment_array); } } ``` I have distinguished the reply email and original email but I don't how to keep those emails as comments to the original email. This is how my `wp_insert_post` looks like: ``` $post_array = array( 'post_content' => $mail['body'], 'post_title' => $mail['header']->subject, 'post_type' => 'faqpress-tickets', 'post_author' => ucwords(strstr($mail['header']->fromaddress, '<',true)), 'post_status' => 'publish', 'meta_input' => array( 'User' => ucwords(strstr($mail['header']->fromaddress, '<',true)), 'From' => preg_replace('~[<>]~', '', strstr($mail['header']->fromaddress, '<')), 'Email' => $mail['header']->Date, 'ticket_id' => $mail['header']->message_id, ), ); //wp_insert_post( $post_array ); ``` If anyone knows how to do it. It will be a great help.
I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted `remove_action` on it. What Maythan8 answered will work but it can be done with fewer functions. ```php add_action('template_redirect', 'bt_maintenance_redirect'); function bt_maintenance_redirect () { if (is_page(4848) || current_user_can('administrator')) return; if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit; } ``` You used `esc_url_raw` but this function is used for escaping url before DB storage, if your url is just for output use `esc_url`. Also better to use `wp_safe_redirect` if you are redirecting from and to the same host.
400,876
<p>In admin, I need to fire the <code>save_post</code> action before firing the <code>transition_post_status</code> hook. But according to <a href="http://rachievee.com/the-wordpress-hooks-firing-sequence/" rel="nofollow noreferrer">this</a>, the <code>transition_post_status</code> fires first before the post is saved.</p> <p>How can I reverse it? I tried changing the priority order below, but I don't think it works cos it's for different functions firing for the same action.</p> <pre><code>$this-&gt;loader-&gt;add_action( 'save_post', $plugin_admin_listings, 'save_meta_data', 9, 2 ); $this-&gt;loader-&gt;add_action( 'transition_post_status', $plugin_admin_listings, 'transition_post_status', 10, 3 ); </code></pre>
[ { "answer_id": 400821, "author": "Maytha8", "author_id": 200755, "author_profile": "https://wordpress.stackexchange.com/users/200755", "pm_score": 0, "selected": false, "text": "<p>Use <code>user_can( wp_get_current_user(), 'administrator' )</code> to determine if the user is logged in a...
2022/01/03
[ "https://wordpress.stackexchange.com/questions/400876", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/217284/" ]
In admin, I need to fire the `save_post` action before firing the `transition_post_status` hook. But according to [this](http://rachievee.com/the-wordpress-hooks-firing-sequence/), the `transition_post_status` fires first before the post is saved. How can I reverse it? I tried changing the priority order below, but I don't think it works cos it's for different functions firing for the same action. ``` $this->loader->add_action( 'save_post', $plugin_admin_listings, 'save_meta_data', 9, 2 ); $this->loader->add_action( 'transition_post_status', $plugin_admin_listings, 'transition_post_status', 10, 3 ); ```
I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted `remove_action` on it. What Maythan8 answered will work but it can be done with fewer functions. ```php add_action('template_redirect', 'bt_maintenance_redirect'); function bt_maintenance_redirect () { if (is_page(4848) || current_user_can('administrator')) return; if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit; } ``` You used `esc_url_raw` but this function is used for escaping url before DB storage, if your url is just for output use `esc_url`. Also better to use `wp_safe_redirect` if you are redirecting from and to the same host.
400,885
<p>I have WordPress code like below.</p> <pre><code>function get_preselect_values() { $volunteers = get_post_meta($_POST['element_id'], &quot;volunteers&quot;, false); $users = array(); foreach ($volunteers as $volunteer) { foreach ($volunteer as $volun) { $users = $volun['ID']; } } echo json_encode($users); die; } add_action('wp_ajax_get_preselect_values', 'get_preselect_values'); add_action('wp_ajax_nopriv_get_preselect_values', 'get_preselect_values'); </code></pre> <p>I am getting only the <strong>First</strong> value.</p> <p>How can I get all values ?</p>
[ { "answer_id": 400821, "author": "Maytha8", "author_id": 200755, "author_profile": "https://wordpress.stackexchange.com/users/200755", "pm_score": 0, "selected": false, "text": "<p>Use <code>user_can( wp_get_current_user(), 'administrator' )</code> to determine if the user is logged in a...
2022/01/03
[ "https://wordpress.stackexchange.com/questions/400885", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65189/" ]
I have WordPress code like below. ``` function get_preselect_values() { $volunteers = get_post_meta($_POST['element_id'], "volunteers", false); $users = array(); foreach ($volunteers as $volunteer) { foreach ($volunteer as $volun) { $users = $volun['ID']; } } echo json_encode($users); die; } add_action('wp_ajax_get_preselect_values', 'get_preselect_values'); add_action('wp_ajax_nopriv_get_preselect_values', 'get_preselect_values'); ``` I am getting only the **First** value. How can I get all values ?
I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted `remove_action` on it. What Maythan8 answered will work but it can be done with fewer functions. ```php add_action('template_redirect', 'bt_maintenance_redirect'); function bt_maintenance_redirect () { if (is_page(4848) || current_user_can('administrator')) return; if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit; } ``` You used `esc_url_raw` but this function is used for escaping url before DB storage, if your url is just for output use `esc_url`. Also better to use `wp_safe_redirect` if you are redirecting from and to the same host.
400,886
<p>Based on my test, get_bloginfo('url') will not return backslash, so it will return URL like this:</p> <pre><code>https://www.example.com/blogs </code></pre> <p>In this post <a href="https://wordpress.stackexchange.com/questions/16161/what-is-difference-between-get-bloginfourl-and-get-site-url">What is difference between get_bloginfo(&#39;url&#39;) and get_site_url()?</a>, it is said get_bloginfo('url') calls home_url().</p> <p>And, in this post <a href="https://stackoverflow.com/questions/31086865/why-does-the-trailing-slash-appear-after-url-when-using-home-url-in-wordpress">https://stackoverflow.com/questions/31086865/why-does-the-trailing-slash-appear-after-url-when-using-home-url-in-wordpress</a>, it is said home_url() will return URL with backslash.</p> <p>So, I am confused. Anyway, I want to find a function to return URL <strong>with</strong> backslash.</p>
[ { "answer_id": 400888, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>it is said get_bloginfo('url') calls home_url().</p>\n</blockquote>\n<p><strong>Correct</strong>...
2022/01/03
[ "https://wordpress.stackexchange.com/questions/400886", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182824/" ]
Based on my test, get\_bloginfo('url') will not return backslash, so it will return URL like this: ``` https://www.example.com/blogs ``` In this post [What is difference between get\_bloginfo('url') and get\_site\_url()?](https://wordpress.stackexchange.com/questions/16161/what-is-difference-between-get-bloginfourl-and-get-site-url), it is said get\_bloginfo('url') calls home\_url(). And, in this post <https://stackoverflow.com/questions/31086865/why-does-the-trailing-slash-appear-after-url-when-using-home-url-in-wordpress>, it is said home\_url() will return URL with backslash. So, I am confused. Anyway, I want to find a function to return URL **with** backslash.
[The Codex example for home\_url()](https://developer.wordpress.org/reference/functions/home_url/#comment-428) says you want `home_url( '/' )` to get the blog's URL with a trailing slash. Alternatively you could use `trailingslashit( home_url() )`. That may be safer if your site's home option somehow ends up stored with a trailing slash, since it looks like get\_home\_url() assumes it isn't, but that ought not happen.
400,914
<p>This is a strange task but I really faced with it. On the home page there is loop for showing all custom post type. And I need to have oportunity when user click to the cpt link from the home page display one type of the single page. And if user go to the custom post type from inner page show other single custom post type template. I found old answer about this on the <a href="https://stackoverflow.com/questions/33301877/multiple-templates-for-single-custom-post-type">stackoverflow</a> But it does not work properly. The code from stackoverflow:</p> <p>On the home page I added to the link something like this:</p> <pre><code>&lt;a href=&quot;&lt;php the_permalink();?&gt;?template=gallery&quot;&gt; Gallery Page &lt;/a&gt; </code></pre> <p>And in the custom post type single page add this chunk of code:</p> <pre><code>if($_POST['template'] == 'gallery') { get_template_part('single', 'gallery'); // the file for this one is single-gallery.php }elseif($_POST['template'] == 'other'){ get_template_part('single', 'other'); // the file for this one is single-other.php } </code></pre> <p>At first glance, this makes sense, but it doesn't work. Please help to solve this.</p>
[ { "answer_id": 400915, "author": "Sébastien Serre", "author_id": 62892, "author_profile": "https://wordpress.stackexchange.com/users/62892", "pm_score": 2, "selected": true, "text": "<p>I think you need to work on the<code>template_include</code> hook. <a href=\"https://developer.wordpre...
2022/01/04
[ "https://wordpress.stackexchange.com/questions/400914", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/201628/" ]
This is a strange task but I really faced with it. On the home page there is loop for showing all custom post type. And I need to have oportunity when user click to the cpt link from the home page display one type of the single page. And if user go to the custom post type from inner page show other single custom post type template. I found old answer about this on the [stackoverflow](https://stackoverflow.com/questions/33301877/multiple-templates-for-single-custom-post-type) But it does not work properly. The code from stackoverflow: On the home page I added to the link something like this: ``` <a href="<php the_permalink();?>?template=gallery"> Gallery Page </a> ``` And in the custom post type single page add this chunk of code: ``` if($_POST['template'] == 'gallery') { get_template_part('single', 'gallery'); // the file for this one is single-gallery.php }elseif($_POST['template'] == 'other'){ get_template_part('single', 'other'); // the file for this one is single-other.php } ``` At first glance, this makes sense, but it doesn't work. Please help to solve this.
I think you need to work on the`template_include` hook. <https://developer.wordpress.org/reference/hooks/template_include> At this point you can add a condition and returning the correct template path ``` add_filter( 'template_include', 'redirect_single' ); function redirect_single( $template ){ if($_POST['template'] == 'gallery') { $template = path/to/your/template; }elseif($_POST['template'] == 'other'){ $template = path/to/your/template; } return $template; } ```
400,997
<p>I am trying to run a function that executes only on the first page of any post. So, if a post is paginated because you have used the <code>&lt;!--nextpage--&gt;</code> tag and you are on page 2 or greater of that article, then the function should not run.</p> <p><a href="https://codex.wordpress.org/Conditional_Tags#A_Paged_Page" rel="nofollow noreferrer">Even the Wordpress documentation</a> is confused how to do this:</p> <blockquote> <p>When the page being displayed is &quot;paged&quot;. This refers to an archive or the main page being split up over several pages and will return true on 2nd and subsequent pages of posts. This does not refer to a Post or Page whose content has been divided into pages using the nextpage QuickTag. To check if a Post or Page has been divided into pages using the nextpage QuickTag, see <a href="https://codex.wordpress.org/Conditional_Tags#A_Paged_Page" rel="nofollow noreferrer">A_Paged_Page</a> section.</p> </blockquote> <p>Further details:</p> <p>I currently use the following code in my functions.php to move my featured image within posts from the default position above the first paragraph and below the title, to underneath the first paragraph.</p> <p>The problem is that it also shows the featured image, in the same spot, on pages 2, 3, 4, etc of the same article (when I have used <code>&lt;!--nextpage--&gt;</code>). The featured image should only show on the first page of any article.</p> <pre><code>add_filter( 'the_content', 'insert_feat_image', 20 ); function insert_feat_image( $content ) { if (!is_single(array(xxxxx))) { global $post; if (has_post_thumbnail($post-&gt;ID)) { $caption = 'xxxx'; $img = 'xxx'; $content = xxx; } return $content; } else { $contentnormal = preg_replace('#(&lt;p&gt;.*?&lt;/p&gt;)#','$1'.$img . $caption, $content, 1);} return $contentnormal; } </code></pre> <p>I removed some potentially identifying code that is not relevant to this question (xxx).</p>
[ { "answer_id": 400998, "author": "joshmoto", "author_id": 111152, "author_profile": "https://wordpress.stackexchange.com/users/111152", "pm_score": -1, "selected": false, "text": "<p>If you are trying to determine if a singular <code>single.php</code> post page is on a <code>paged()</cod...
2022/01/06
[ "https://wordpress.stackexchange.com/questions/400997", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103103/" ]
I am trying to run a function that executes only on the first page of any post. So, if a post is paginated because you have used the `<!--nextpage-->` tag and you are on page 2 or greater of that article, then the function should not run. [Even the Wordpress documentation](https://codex.wordpress.org/Conditional_Tags#A_Paged_Page) is confused how to do this: > > When the page being displayed is "paged". This refers to an archive or > the main page being split up over several pages and will return true > on 2nd and subsequent pages of posts. This does not refer to a Post or > Page whose content has been divided into pages using the > nextpage QuickTag. To check if a Post or Page has been divided > into pages using the nextpage QuickTag, see [A\_Paged\_Page](https://codex.wordpress.org/Conditional_Tags#A_Paged_Page) > section. > > > Further details: I currently use the following code in my functions.php to move my featured image within posts from the default position above the first paragraph and below the title, to underneath the first paragraph. The problem is that it also shows the featured image, in the same spot, on pages 2, 3, 4, etc of the same article (when I have used `<!--nextpage-->`). The featured image should only show on the first page of any article. ``` add_filter( 'the_content', 'insert_feat_image', 20 ); function insert_feat_image( $content ) { if (!is_single(array(xxxxx))) { global $post; if (has_post_thumbnail($post->ID)) { $caption = 'xxxx'; $img = 'xxx'; $content = xxx; } return $content; } else { $contentnormal = preg_replace('#(<p>.*?</p>)#','$1'.$img . $caption, $content, 1);} return $contentnormal; } ``` I removed some potentially identifying code that is not relevant to this question (xxx).
> > The problem is that it also shows the featured image, in the same > spot, on pages 2, 3, 4, etc of the same article (when I have used > `<!--nextpage-->`). The featured image should only show on the first > page of any article. > > > In that case, then this might work for you: ```php function insert_feat_image( $content ) { global $page, $multipage; if ( $multipage && $page <= 1 ) { // it's the 1st page, so run your code here. } // else, it's not paginated or not the 1st page return $content; } ``` Explanation about the global variables above: 1. `$multipage` is a boolean flag indicating whether the page/post is paginated using the `<!--nextpage-->` tag (or the [Page Break block](https://wordpress.org/support/article/page-break-block/) in Gutenberg), and the flag would be a *true*, as long as the post contains the `<!--nextpage-->` tag and that the global post data has already been setup, e.g. [`the_post()`](https://developer.wordpress.org/reference/functions/the_post/) or [`setup_postdata()`](https://developer.wordpress.org/reference/functions/setup_postdata/) has been called. (which is true when inside The Loop) 2. The page number is stored in `$page`, but the number can also be retrieved using `get_query_var( 'page' )`. (yes, it's `page` and *not* `paged`) Alternate Solution ------------------ If you just wanted to know whether it's the first page or not, regardless how the page/post was paginated (and **only if** it was paginated or in the case of archives, it means there are more than one page of results), you can try this instead which should work on *any pages* (single Post/Page/CPT, category archives, search results pages, etc.): ```php function insert_feat_image( $content ) { global $page, $multipage, $paged, $wp_query; $page_num = max( 1, $page, $paged ); /* Or you can use: $page_num = max( 1, get_query_var( 'page' ), get_query_var( 'paged' ) ); */ if ( ( $multipage || $wp_query->max_num_pages > 1 ) && $page_num <= 1 ) { // it's the 1st page, so run your code here. } // else, it's not paginated or not the 1st page return $content; } ```
401,070
<p>I'm querying posts using the following wp query:</p> <pre><code>function custom_retrieve_posts_function() { $paged = get_query_var( &quot;paged&quot; ) ? get_query_var( &quot;paged&quot; ) : 1; $args = array( 'post_type' =&gt; 'my_post_type', 'posts_per_page' =&gt; 7, 'paged' =&gt; $paged ); $query = new \WP_Query( $args ); $output = &quot;&quot;; if ( $query-&gt;have_posts() ) { while ( $query-&gt;have_posts() ) { // Iterate next post of query result $query-&gt;the_post(); $output .= get_the_content(); } // Only display arrows if links have been obtained, so do it in this way $previous_link = get_previous_posts_link( esc_html__( 'Zurück', 'custom-text-domain' ) ); $next_link = get_next_posts_link( esc_html__( 'Weiter', 'custom-text-domain' ), $query-&gt;max_num_pages ); $nav_links = &quot;&lt;div id=\&quot;navigation-links\&quot;&gt;&quot;. &quot;&lt;span id=\&quot;previous-link\&quot;&gt;&quot;. ( $previous_link ? &quot;&amp;#8678 {$previous_link}&quot; : &quot;&quot; ). &quot;&lt;/span&gt;&quot;. &quot;&lt;span id=\&quot;next-link\&quot;&gt;&quot;. ( $next_link ? &quot;{$next_link} &amp;#8680&quot; : &quot;&quot; ). &quot;&lt;/span&gt;&quot;. &quot;&lt;/div&gt;&quot;; $output .= $nav_links; // Reset the wp_query loop wp_reset_postdata(); } else { $output = &quot;&lt;p class=\&quot;no-results\&quot;&gt;Oops!&lt;/p&gt;&quot;; } echo $output; } </code></pre> <p>Problem is that certain posts of page n are seemingly randomly repeated on page(s) m, with m &gt; n.</p> <p>The amount / limit of posts to be shown in feeds and blogs is 7, I've set that in the wp admin options. Still, same problem persists.</p> <p>Any idea why this is happening?</p> <p><em><strong>UPDATE</strong></em></p> <p>The function <code>custom_retrieve_posts_function()</code> (defined in a namespace within a class etc., but all of this is omitted here for simplicity) is called within a PHP script bound to the AJAX hook responsible for executing a custom filtered query via ajax.</p> <p>So the script is called like this:</p> <p>Main Plugin File holds this:</p> <pre><code>add_action( 'wp_ajax_myplugin_search_custom', function() { require MYPLUGIN_AJAX_DIR.'/custom_search.php'; wp_die(); } ); add_action( 'wp_ajax_nopriv_myplugin_search_custom', function() { require MYPLUGIN_AJAX_DIR.'/custom_search.php'; wp_die(); } ); </code></pre> <p>With the content of <code>AJAX_DIR.'/custom_search.php'</code> being (again simplified, all naming conflicts are 100% avoided, so all classnames / namespaces are again omitted):</p> <pre><code>check_ajax_referer( 'ajax-nonce-content' ); require MYPLUGIN.'/custom_search_function.php'; custom_retrieve_posts_function(); </code></pre> <p>I then also have a page template defined in my <code>themes/mycustomtheme/templates</code> directory, and within that page template, I simply call</p> <pre><code>require MYPLUGIN.'/custom_search_function.php'; custom_retrieve_posts_function(); </code></pre> <p>Note that all of this works perfectly, expect from the problem that already displayed posts are re-displayed on subsequently paginated pages.</p> <p><em><strong>UPDATE 2</strong></em></p> <p>Sadly, I'm not able to make it working after making the commented adaptations via js (additionally pass the number of the page of the pagination to query). Like when I do this query via AJAX:</p> <pre><code>$args = array( 'post_type' =&gt; 'my_post_type', 'tax_query' =&gt; $tax_query_array, 'orderby' =&gt; 'meta_value_num', 'meta_key' =&gt; 'my_metas_key', 'order' =&gt; 'ASC', 'posts_per_page' =&gt; 7, 'paged' =&gt; 2 ); </code></pre> <p>I still get one of the posts already shown on page 1 (a random one).</p> <p>Same if I add <code>$args['offset'] = 7</code> and / or <code>$args['page'] = 2</code>, so I'm confused; what am I still not properly understanding here??</p>
[ { "answer_id": 401075, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<p>Because of this line:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$paged = get_query_var( &quot;p...
2022/01/07
[ "https://wordpress.stackexchange.com/questions/401070", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/188571/" ]
I'm querying posts using the following wp query: ``` function custom_retrieve_posts_function() { $paged = get_query_var( "paged" ) ? get_query_var( "paged" ) : 1; $args = array( 'post_type' => 'my_post_type', 'posts_per_page' => 7, 'paged' => $paged ); $query = new \WP_Query( $args ); $output = ""; if ( $query->have_posts() ) { while ( $query->have_posts() ) { // Iterate next post of query result $query->the_post(); $output .= get_the_content(); } // Only display arrows if links have been obtained, so do it in this way $previous_link = get_previous_posts_link( esc_html__( 'Zurück', 'custom-text-domain' ) ); $next_link = get_next_posts_link( esc_html__( 'Weiter', 'custom-text-domain' ), $query->max_num_pages ); $nav_links = "<div id=\"navigation-links\">". "<span id=\"previous-link\">". ( $previous_link ? "&#8678 {$previous_link}" : "" ). "</span>". "<span id=\"next-link\">". ( $next_link ? "{$next_link} &#8680" : "" ). "</span>". "</div>"; $output .= $nav_links; // Reset the wp_query loop wp_reset_postdata(); } else { $output = "<p class=\"no-results\">Oops!</p>"; } echo $output; } ``` Problem is that certain posts of page n are seemingly randomly repeated on page(s) m, with m > n. The amount / limit of posts to be shown in feeds and blogs is 7, I've set that in the wp admin options. Still, same problem persists. Any idea why this is happening? ***UPDATE*** The function `custom_retrieve_posts_function()` (defined in a namespace within a class etc., but all of this is omitted here for simplicity) is called within a PHP script bound to the AJAX hook responsible for executing a custom filtered query via ajax. So the script is called like this: Main Plugin File holds this: ``` add_action( 'wp_ajax_myplugin_search_custom', function() { require MYPLUGIN_AJAX_DIR.'/custom_search.php'; wp_die(); } ); add_action( 'wp_ajax_nopriv_myplugin_search_custom', function() { require MYPLUGIN_AJAX_DIR.'/custom_search.php'; wp_die(); } ); ``` With the content of `AJAX_DIR.'/custom_search.php'` being (again simplified, all naming conflicts are 100% avoided, so all classnames / namespaces are again omitted): ``` check_ajax_referer( 'ajax-nonce-content' ); require MYPLUGIN.'/custom_search_function.php'; custom_retrieve_posts_function(); ``` I then also have a page template defined in my `themes/mycustomtheme/templates` directory, and within that page template, I simply call ``` require MYPLUGIN.'/custom_search_function.php'; custom_retrieve_posts_function(); ``` Note that all of this works perfectly, expect from the problem that already displayed posts are re-displayed on subsequently paginated pages. ***UPDATE 2*** Sadly, I'm not able to make it working after making the commented adaptations via js (additionally pass the number of the page of the pagination to query). Like when I do this query via AJAX: ``` $args = array( 'post_type' => 'my_post_type', 'tax_query' => $tax_query_array, 'orderby' => 'meta_value_num', 'meta_key' => 'my_metas_key', 'order' => 'ASC', 'posts_per_page' => 7, 'paged' => 2 ); ``` I still get one of the posts already shown on page 1 (a random one). Same if I add `$args['offset'] = 7` and / or `$args['page'] = 2`, so I'm confused; what am I still not properly understanding here??
Because of this line: ```php $paged = get_query_var( "paged" ) ? get_query_var( "paged" ) : 1; ``` This is inside a function that is used on both an AJAX handler, and on a page request. `get_query_var` pulls the parameters from the main query ( aka the primary `WP_Query` that powers functions such as `the_post`, `have_posts()` etc ). But this will **never** work in an AJAX request. For this reason, when you request the next page from AJAX it will always result in page `1`. If you want something other than page 1 then you need to include the number of the page you want in the javascript that sends the AJAX request, pass it along, then read it and put it in the `WP_Query` parameters directly. Even if there was a main query it would not be the same main query. Remember, every request to the server loads WordPress from a blank slate, AJAX request handlers share nothing with the page that your browser has open unless you explicitly send them the data you want to share along with the request as POST/GET variables. There is no shared pagination state behind the scenes or magic that glues it together. Additionally, because you included the pagination HTML in the AJAX response you'll now have a next page link that leads to page 2, but triggers AJAX that loads page 1 ( why would it know to load page 2? `get_query_var` won't work, there is no main query to get a query var from! ). --- What's more, I have a strong suspicion that you're either unaware of `archive-mycustompost.php`, the `pre_get_posts` filter, or the ability to change the URL of the CPT archive when registering the CPT, or that query parameters for the main query come from the URL and you can add extra parameters e.g. `example.com/?s=test&posts_per_page=7&paged=2` gets the second page of a search query for "Test" that has 7 posts per page. In the majority of cases a secondary query and a custom page template are completely unnecessary.
401,091
<p>I just want to add a class if li is parent class should be level-0 and if li is the child then level-1 etc. I am using the following loop.</p> <pre><code> &lt;?php $categories = get_categories(); foreach($categories as $category) { echo '&lt;li class=&quot;here-i-want-to-add&quot;&gt;&lt;a href=&quot;' . get_category_link($category-&gt;term_id) . '&quot;&gt;' . $category-&gt;name . '&lt;/a&gt;&lt;/li&gt;'; } ?&gt; </code></pre>
[ { "answer_id": 401095, "author": "Sabry Suleiman", "author_id": 174580, "author_profile": "https://wordpress.stackexchange.com/users/174580", "pm_score": 1, "selected": false, "text": "<p>The category object stores the parent ID like this: <code>$category-&gt;parent</code></p>\n<p>In the...
2022/01/08
[ "https://wordpress.stackexchange.com/questions/401091", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/200785/" ]
I just want to add a class if li is parent class should be level-0 and if li is the child then level-1 etc. I am using the following loop. ``` <?php $categories = get_categories(); foreach($categories as $category) { echo '<li class="here-i-want-to-add"><a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a></li>'; } ?> ```
The category object stores the parent ID like this: `$category->parent` In the event that there is no parent it's equal to `0`. In this way, it is possible to create a variable equal to the parent class or the child parent according to the value of `$category->parent`: ```php $categories = get_categories(); if ( ! is_wp_error( $categories ) ) { foreach ( $categories as $category ) { $htmlclass = ( $category->parent === 0 ) ? "level-0" : "level-1"; echo '<li class="' . esc_attr( $htmlclass ).'">'; echo '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">'; echo esc_html( $category->name ); echo '</a></li>'; } } ```
401,108
<p>I am building my own WordPress theme. I have the front page working. However, when I try to view a test post full of Lorem Ipsum, I get the &quot;No matching template found&quot; error.</p> <p>I have the following code in single.php</p> <pre><code>&lt;?php get_header(); if( have_posts()){ while( have_posts() ){ the_post(); the_content(); } } get_footer(); ?&gt; </code></pre> <p>single.php is under directly my custom theme's root folder.</p> <p>From what I understand, the page should just display the content, albeit without much styling. I navigated to the post using the &quot;view post&quot; link on the post edit page if that matters.</p> <p>Just to be sure, I also placed the same code in page.php, index.php, and page.php</p> <p>No success. No matter what I try, I still get &quot;No matching template found&quot; when navigating to the test post.</p> <p>What am I missing here? Is there a way to troubleshoot the template hierarchy?</p> <p>Thanks in advance.</p>
[ { "answer_id": 401095, "author": "Sabry Suleiman", "author_id": 174580, "author_profile": "https://wordpress.stackexchange.com/users/174580", "pm_score": 1, "selected": false, "text": "<p>The category object stores the parent ID like this: <code>$category-&gt;parent</code></p>\n<p>In the...
2022/01/09
[ "https://wordpress.stackexchange.com/questions/401108", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/213315/" ]
I am building my own WordPress theme. I have the front page working. However, when I try to view a test post full of Lorem Ipsum, I get the "No matching template found" error. I have the following code in single.php ``` <?php get_header(); if( have_posts()){ while( have_posts() ){ the_post(); the_content(); } } get_footer(); ?> ``` single.php is under directly my custom theme's root folder. From what I understand, the page should just display the content, albeit without much styling. I navigated to the post using the "view post" link on the post edit page if that matters. Just to be sure, I also placed the same code in page.php, index.php, and page.php No success. No matter what I try, I still get "No matching template found" when navigating to the test post. What am I missing here? Is there a way to troubleshoot the template hierarchy? Thanks in advance.
The category object stores the parent ID like this: `$category->parent` In the event that there is no parent it's equal to `0`. In this way, it is possible to create a variable equal to the parent class or the child parent according to the value of `$category->parent`: ```php $categories = get_categories(); if ( ! is_wp_error( $categories ) ) { foreach ( $categories as $category ) { $htmlclass = ( $category->parent === 0 ) ? "level-0" : "level-1"; echo '<li class="' . esc_attr( $htmlclass ).'">'; echo '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">'; echo esc_html( $category->name ); echo '</a></li>'; } } ```
401,129
<p>I've been working on WP since a week so far i've seen bunch of tutorials and videos about wp but i feel stuck and since i'm a wp noob i cant find or think any solution for a simple problem. i have created custom field using plug-in for a custom post type, my problem is i want to hide the -div- when there is nothing written in the field.</p> <p>So far i tried bunch of entries from this site and SO but i havent complished anything. all i need is a basic structure for hiding the -div- in case if there is no entry for the related post field..</p> <p>below my single.php's -div- part that i want to hide... since im new and watched so much stuff i feel extremely confused and cant develop any solution..</p> <pre><code>&lt;div class=&quot;card-header&quot; role=&quot;tab&quot; id=&quot;headingOne1&quot;&gt; &lt;a data-toggle=&quot;collapse&quot; data-parent=&quot;#accordionEx&quot; href=&quot;#collapseOne1&quot; aria-expanded=&quot;true&quot; aria-controls=&quot;collapseOne1&quot;&gt; &lt;h5 class=&quot;mb-0&quot;&gt; &lt;?php the_field('button1-mi-s1-b'); ?&gt; &lt;i class=&quot;fas fa-angle-down rotate-icon&quot;&gt;&lt;/i&gt; &lt;/h5&gt; &lt;/a&gt; &lt;/div&gt; &lt;!-- Card body --&gt; &lt;div id=&quot;collapseOne1&quot; class=&quot;collapse&quot; role=&quot;tabpanel&quot; aria-labelledby=&quot;headingOne1&quot; data-parent=&quot;#accordionEx&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;?php the_field('button1-mi-s1-yazi'); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>thanks for your time.. best regards WP_NOOB</p>
[ { "answer_id": 401132, "author": "wp_noob", "author_id": 217723, "author_profile": "https://wordpress.stackexchange.com/users/217723", "pm_score": 1, "selected": false, "text": "<p>So i resolved that noob question... here is a recipe step by step;</p>\n<ol>\n<li>get some sleep</li>\n<li>...
2022/01/09
[ "https://wordpress.stackexchange.com/questions/401129", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/217723/" ]
I've been working on WP since a week so far i've seen bunch of tutorials and videos about wp but i feel stuck and since i'm a wp noob i cant find or think any solution for a simple problem. i have created custom field using plug-in for a custom post type, my problem is i want to hide the -div- when there is nothing written in the field. So far i tried bunch of entries from this site and SO but i havent complished anything. all i need is a basic structure for hiding the -div- in case if there is no entry for the related post field.. below my single.php's -div- part that i want to hide... since im new and watched so much stuff i feel extremely confused and cant develop any solution.. ``` <div class="card-header" role="tab" id="headingOne1"> <a data-toggle="collapse" data-parent="#accordionEx" href="#collapseOne1" aria-expanded="true" aria-controls="collapseOne1"> <h5 class="mb-0"> <?php the_field('button1-mi-s1-b'); ?> <i class="fas fa-angle-down rotate-icon"></i> </h5> </a> </div> <!-- Card body --> <div id="collapseOne1" class="collapse" role="tabpanel" aria-labelledby="headingOne1" data-parent="#accordionEx"> <div class="card-body"> <?php the_field('button1-mi-s1-yazi'); ?> </div> </div> </div> ``` thanks for your time.. best regards WP\_NOOB
So i resolved that noob question... here is a recipe step by step; 1. get some sleep 2. repeat what you leaned with a fresh mind 3. apply the structure: ``` <?php if( get_field('field_name') ): ?> <p>My field value: <?php the_field('field_name'); ?></p> <?php endif; ?> ```
401,161
<p>Hello every one i am new to wordpress development. i am working on a plugin in which i have created a custom post type with the name of application when the user submits a form from the frontend a new application is created with the user data. i have a custom taxonomy in it with the name of application_status. I want to send an email to the user when the admin change the status of the taxonomy like from pending to accepted. I have a general idea how to do it like i can get the new updated value and compare it with the previous value(which is saved in database) and if it is changed i can send the email. So can anybody guide me how can i get the new changed taxonomy value before it is stored so that i can compare it with the previous value.</p> <p>from some references i have seen the hook</p> <pre class="lang-php prettyprint-override"><code> $this-&gt;loader-&gt;add_filter( 'transition_post_status', $plugin_admin, 'send_mail_when_status_changed', 10, 3); </code></pre> <p>and the function is</p> <pre class="lang-php prettyprint-override"><code>function send_mail_when_status_changed($new_status, $old_status, $post ) { if ( 'publish' !== $new_status || $new_status === $old_status || 'application' !== get_post_type( $post ) ) { return; } // Get the post author data. if ( ! $user = get_userdata( $post-&gt;post_author ) ) { return; } //check if the taxonomy is changed $appstatus='Pending'; $terms = wp_get_object_terms( $post-&gt;ID, 'application_status'); foreach ( $terms as $term ) { $appstatus=$term-&gt;name; } //donot know how to get compare the value with the changed value // Compose the email message. // $body = sprintf( 'Hey %s, your awesome post has been published! See , // esc_html( $user-&gt;display_name ), // get_permalink( $post ) // ); // // Now send to the post author. // wp_mail( $user-&gt;user_email, 'Your post published!', $body ); } </code></pre>
[ { "answer_id": 401132, "author": "wp_noob", "author_id": 217723, "author_profile": "https://wordpress.stackexchange.com/users/217723", "pm_score": 1, "selected": false, "text": "<p>So i resolved that noob question... here is a recipe step by step;</p>\n<ol>\n<li>get some sleep</li>\n<li>...
2022/01/10
[ "https://wordpress.stackexchange.com/questions/401161", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/217763/" ]
Hello every one i am new to wordpress development. i am working on a plugin in which i have created a custom post type with the name of application when the user submits a form from the frontend a new application is created with the user data. i have a custom taxonomy in it with the name of application\_status. I want to send an email to the user when the admin change the status of the taxonomy like from pending to accepted. I have a general idea how to do it like i can get the new updated value and compare it with the previous value(which is saved in database) and if it is changed i can send the email. So can anybody guide me how can i get the new changed taxonomy value before it is stored so that i can compare it with the previous value. from some references i have seen the hook ```php $this->loader->add_filter( 'transition_post_status', $plugin_admin, 'send_mail_when_status_changed', 10, 3); ``` and the function is ```php function send_mail_when_status_changed($new_status, $old_status, $post ) { if ( 'publish' !== $new_status || $new_status === $old_status || 'application' !== get_post_type( $post ) ) { return; } // Get the post author data. if ( ! $user = get_userdata( $post->post_author ) ) { return; } //check if the taxonomy is changed $appstatus='Pending'; $terms = wp_get_object_terms( $post->ID, 'application_status'); foreach ( $terms as $term ) { $appstatus=$term->name; } //donot know how to get compare the value with the changed value // Compose the email message. // $body = sprintf( 'Hey %s, your awesome post has been published! See , // esc_html( $user->display_name ), // get_permalink( $post ) // ); // // Now send to the post author. // wp_mail( $user->user_email, 'Your post published!', $body ); } ```
So i resolved that noob question... here is a recipe step by step; 1. get some sleep 2. repeat what you leaned with a fresh mind 3. apply the structure: ``` <?php if( get_field('field_name') ): ?> <p>My field value: <?php the_field('field_name'); ?></p> <?php endif; ?> ```
401,221
<p>I add this code (modify from <a href="https://developer.wordpress.org/reference/hooks/the_content/#comment-5125" rel="nofollow noreferrer">this comment</a>) into my plugin:</p> <pre class="lang-php prettyprint-override"><code>function wpdocs_replace_content( $text_content ) { if ( is_page() ) { $text = array( 'chamber' =&gt; '&lt;strong&gt;chamber&lt;/strong&gt;', ); $text_content = str_ireplace( array_keys( $text ), $text, $text_content ); } return $text_content; } add_filter( 'the_content', 'wpdocs_replace_content' ); </code></pre> <p>But it doesn't work. What can I do to debug it?</p>
[ { "answer_id": 401222, "author": "Ooker", "author_id": 64282, "author_profile": "https://wordpress.stackexchange.com/users/64282", "pm_score": 2, "selected": false, "text": "<p>Notice the <code>if ( is_page() </code> line. It's to indicate that the snippet only works with pages, not post...
2022/01/11
[ "https://wordpress.stackexchange.com/questions/401221", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64282/" ]
I add this code (modify from [this comment](https://developer.wordpress.org/reference/hooks/the_content/#comment-5125)) into my plugin: ```php function wpdocs_replace_content( $text_content ) { if ( is_page() ) { $text = array( 'chamber' => '<strong>chamber</strong>', ); $text_content = str_ireplace( array_keys( $text ), $text, $text_content ); } return $text_content; } add_filter( 'the_content', 'wpdocs_replace_content' ); ``` But it doesn't work. What can I do to debug it?
Notice the `if ( is_page()` line. It's to indicate that the snippet only works with pages, not posts. Pull it out of the if condition if you want to apply it site-wide. ```php function wpdocs_replace_content( $text_content ) { $text = array( 'chamber' => '<strong>chamber</strong>', ); $text_content = str_ireplace( array_keys( $text ), $text, $text_content ); return $text_content; } add_filter( 'the_content', 'wpdocs_replace_content' ); ```
401,261
<p>I have a piece of code for creating video passes after someone buys a product with the ID 1136. For some reason, the order_status_completed is not doing anything. I tried hooking the function to woocommerce_thankyou and woocommerce_payment_complete. I am at a loss. I ran the code without hooking it to an action and it works fine. No bugs in my error log.. nothing.</p> <pre><code>add_action('woocommerce_order_status_completed','create_video_passes',10,1); function create_video_passes($orderId){ $order = wc_get_order($orderId); $orderData = $order-&gt;get_data(); foreach( $order-&gt;get_items() as $item ): $item = $item-&gt;get_data(); if($item['id'] == 1136){ foreach(range(1,$item['quantity']) as $index) { $passArray = array( 'post_title' =&gt; generateRandomString(), 'post_type' =&gt; 'videopass', 'post_status' =&gt; 'publish', 'post_author' =&gt; 1 ); // Insert the post into the database $passId = wp_insert_post( $passArray ); update_post_meta( $passId, 'gebruikt','nee'); update_post_meta( $passId, 'email',$orderData['billing']['email']); } } endforeach; } </code></pre>
[ { "answer_id": 401263, "author": "Kevsterino", "author_id": 138461, "author_profile": "https://wordpress.stackexchange.com/users/138461", "pm_score": 0, "selected": false, "text": "<p>$item['id'] should be $item['product_id']</p>\n" }, { "answer_id": 401269, "author": "RamMoh...
2022/01/12
[ "https://wordpress.stackexchange.com/questions/401261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138461/" ]
I have a piece of code for creating video passes after someone buys a product with the ID 1136. For some reason, the order\_status\_completed is not doing anything. I tried hooking the function to woocommerce\_thankyou and woocommerce\_payment\_complete. I am at a loss. I ran the code without hooking it to an action and it works fine. No bugs in my error log.. nothing. ``` add_action('woocommerce_order_status_completed','create_video_passes',10,1); function create_video_passes($orderId){ $order = wc_get_order($orderId); $orderData = $order->get_data(); foreach( $order->get_items() as $item ): $item = $item->get_data(); if($item['id'] == 1136){ foreach(range(1,$item['quantity']) as $index) { $passArray = array( 'post_title' => generateRandomString(), 'post_type' => 'videopass', 'post_status' => 'publish', 'post_author' => 1 ); // Insert the post into the database $passId = wp_insert_post( $passArray ); update_post_meta( $passId, 'gebruikt','nee'); update_post_meta( $passId, 'email',$orderData['billing']['email']); } } endforeach; } ```
I think you must try changing $item['id'] to this ``` foreach ( $order->get_items() as $item ) { $product = $item->get_data(); $item_id = $item->get_product_id(); if( $item_id == 1136 ) { // Keep Your code here. } } ``` Keep Posted.
401,279
<p>What is the best way of using WordPress's core classes in the context of an <em>object-oriented design</em>?</p> <p>I am trying to use <strong>$wp_admin_bar</strong> to remove a couple of the default WordPress designs but I am not able to find where to add $wp_admin_bar that does not trigger an error.</p> <p>Below is my code. <em><strong>The comments should help to understand what I have tried</strong></em>, and what my thought process was:</p> <pre><code>&lt;?php defined( 'ABSPATH' ) or die('Nothing to see here'); // Since wp_admin_bar is a class I probably need to extend to it but I am unsure what //file needs to be required to achieve this class adminPanel { //I tried adding it here //protected $wp_admin_bar; //I also tried public $wp_admin_bar //resgister() function is treated as something like a __construct and is called by a //Init class so $wp_admin_bar can't be declared global before the class is //instantiated public function register(){ //Remove wordpress logo from top nav add_action( 'wp_before_admin_bar_render', array( $this, 'remove_wp_logo' ), 0 ); } function remove_wp_logo() { //As pointed out in one of the answers &quot;global $wp_admin_bar;&quot; might //be added here but this causes: Parse error: syntax error, //unexpected 'global' (T_GLOBAL) $wp_admin_bar-&gt;remove_menu( 'wp-logo' ); } } </code></pre> <p>I even tried to add it as a global before the class that creates an object of this class is called.</p> <pre><code>if ( function_exists('add_action') &amp;&amp; class_exists('Init')){ global $wp_admin_bar; Init::register_services(); } </code></pre> <p>The error I am getting is:</p> <pre><code>Fatal error: Uncaught Error: Call to a member function remove_menu() on null </code></pre> <p>I have a feeling that I am not calling $wp_admin_bar correctly but I could also by wrong about what the actual cause of the error is.</p> <p>I have tried other solutions from other questions on this site but everything so far is returning the same error.</p>
[ { "answer_id": 401280, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<blockquote>\n<p>I am trying to use <strong>$wp_admin_bar</strong> to remove a couple of the default\nWordPres...
2022/01/13
[ "https://wordpress.stackexchange.com/questions/401279", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/217212/" ]
What is the best way of using WordPress's core classes in the context of an *object-oriented design*? I am trying to use **$wp\_admin\_bar** to remove a couple of the default WordPress designs but I am not able to find where to add $wp\_admin\_bar that does not trigger an error. Below is my code. ***The comments should help to understand what I have tried***, and what my thought process was: ``` <?php defined( 'ABSPATH' ) or die('Nothing to see here'); // Since wp_admin_bar is a class I probably need to extend to it but I am unsure what //file needs to be required to achieve this class adminPanel { //I tried adding it here //protected $wp_admin_bar; //I also tried public $wp_admin_bar //resgister() function is treated as something like a __construct and is called by a //Init class so $wp_admin_bar can't be declared global before the class is //instantiated public function register(){ //Remove wordpress logo from top nav add_action( 'wp_before_admin_bar_render', array( $this, 'remove_wp_logo' ), 0 ); } function remove_wp_logo() { //As pointed out in one of the answers "global $wp_admin_bar;" might //be added here but this causes: Parse error: syntax error, //unexpected 'global' (T_GLOBAL) $wp_admin_bar->remove_menu( 'wp-logo' ); } } ``` I even tried to add it as a global before the class that creates an object of this class is called. ``` if ( function_exists('add_action') && class_exists('Init')){ global $wp_admin_bar; Init::register_services(); } ``` The error I am getting is: ``` Fatal error: Uncaught Error: Call to a member function remove_menu() on null ``` I have a feeling that I am not calling $wp\_admin\_bar correctly but I could also by wrong about what the actual cause of the error is. I have tried other solutions from other questions on this site but everything so far is returning the same error.
> > I am trying to use **$wp\_admin\_bar** to remove a couple of the default > WordPress designs but I am not able to find where to add $wp\_admin\_bar > that does not trigger an error. > > > The [`wp_before_admin_bar_render` hook](https://developer.wordpress.org/reference/hooks/wp_before_admin_bar_render/) doesn't pass the admin bar object, but you can access it manually (from within a function or a class method) using `global` like so, just like the Codex example [here](https://developer.wordpress.org/reference/hooks/wp_before_admin_bar_render/#comment-4502): ```php function remove_wp_logo() { global $wp_admin_bar; $wp_admin_bar->remove_menu( 'wp-logo' ); } ```
401,318
<p>Some posts have a more &quot;readable value&quot; even though they are free to read. To highlight their increased reader value, I've managed to get together this piece of code.</p> <p>&quot;Problem&quot; is, for some reason when navigation through the blog pages, the menu items gets the &quot;Worth Reading&quot; label as well - which is not the idea.</p> <p><strong>My question is this;</strong> am I doing this wrong or do I need to somehow include a &quot;is_menu()&quot; kind of conditional that I am not aware of?</p> <pre><code>add_filter('the_title', 'label_after_post_title', 10, 1); function label_after_post_title($title){ if (is_admin()) return $title; if (is_single() || is_category('worth-reading') || is_search()) return $title; $label = ''; if (has_category('worth-reading')){ $label = '&lt;span class=&quot;worth-reading&quot;&gt;Worth Reading&lt;/span&gt;'; $title = $title . '&amp;nbsp;&amp;nbsp;' . $label; } return $title; } </code></pre>
[ { "answer_id": 401290, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 1, "selected": false, "text": "<p>What you're seeing are probably calls from <a href=\"https://wordpress.org/support/article/trackbacks-and-pi...
2022/01/14
[ "https://wordpress.stackexchange.com/questions/401318", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/217540/" ]
Some posts have a more "readable value" even though they are free to read. To highlight their increased reader value, I've managed to get together this piece of code. "Problem" is, for some reason when navigation through the blog pages, the menu items gets the "Worth Reading" label as well - which is not the idea. **My question is this;** am I doing this wrong or do I need to somehow include a "is\_menu()" kind of conditional that I am not aware of? ``` add_filter('the_title', 'label_after_post_title', 10, 1); function label_after_post_title($title){ if (is_admin()) return $title; if (is_single() || is_category('worth-reading') || is_search()) return $title; $label = ''; if (has_category('worth-reading')){ $label = '<span class="worth-reading">Worth Reading</span>'; $title = $title . '&nbsp;&nbsp;' . $label; } return $title; } ```
What you're seeing are probably calls from [Pingbacks](https://wordpress.org/support/article/trackbacks-and-pingbacks/). If you don't want them you can either disable them [globally in the settings](https://wordpress.org/support/article/settings-discussion-screen/#default-article-setting) or just for a specific post in the "Discussion" metabox in the sidebar of that post.
401,335
<p>I added my block to an article and the new full site editing. The block renders an tag. When I select the block in the editor I click on the tag and I get a &quot;Cannot destructure property 'frameElement' of 'r' as it is null.&quot; and reloads itself.</p> <pre><code>export default function Edit( { attributes, setAttributes } ) { return ( &lt;div { ...blockProps } &gt; &lt;InspectorControls&gt; &lt;Panel&gt; &lt;PanelBody&gt; &lt;PanelRow&gt; &lt;MyFontSizePicker /&gt; &lt;/PanelRow&gt; &lt;PanelRow&gt; &lt;/PanelBody&gt; &lt;/Panel&gt; &lt;/InspectorControls&gt; &lt;ServerSideRender block=&quot;game-review/random-game&quot; attributes={ attributes } /&gt; &lt;/div&gt; ); } </code></pre> <p>The callback does something like this:</p> <pre><code>function render_random_game(){ $link = '&lt;a ' . $fontsizeattr . ' href=&quot;' . $url . '&quot;&gt;' . $game_title . '&lt;/a&gt;'; return &quot;&lt;p&gt;&quot; . $link . &quot;&lt;/p&gt;&quot;; } </code></pre> <p>Any idea why this happens? Other blocks from my other plugins run fine. Here is the full source code for context: <a href="https://github.com/mtoensing/game-review-block/tree/main/blocks/random-game" rel="nofollow noreferrer">https://github.com/mtoensing/game-review-block/tree/main/blocks/random-game</a></p>
[ { "answer_id": 401290, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 1, "selected": false, "text": "<p>What you're seeing are probably calls from <a href=\"https://wordpress.org/support/article/trackbacks-and-pi...
2022/01/14
[ "https://wordpress.stackexchange.com/questions/401335", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33797/" ]
I added my block to an article and the new full site editing. The block renders an tag. When I select the block in the editor I click on the tag and I get a "Cannot destructure property 'frameElement' of 'r' as it is null." and reloads itself. ``` export default function Edit( { attributes, setAttributes } ) { return ( <div { ...blockProps } > <InspectorControls> <Panel> <PanelBody> <PanelRow> <MyFontSizePicker /> </PanelRow> <PanelRow> </PanelBody> </Panel> </InspectorControls> <ServerSideRender block="game-review/random-game" attributes={ attributes } /> </div> ); } ``` The callback does something like this: ``` function render_random_game(){ $link = '<a ' . $fontsizeattr . ' href="' . $url . '">' . $game_title . '</a>'; return "<p>" . $link . "</p>"; } ``` Any idea why this happens? Other blocks from my other plugins run fine. Here is the full source code for context: <https://github.com/mtoensing/game-review-block/tree/main/blocks/random-game>
What you're seeing are probably calls from [Pingbacks](https://wordpress.org/support/article/trackbacks-and-pingbacks/). If you don't want them you can either disable them [globally in the settings](https://wordpress.org/support/article/settings-discussion-screen/#default-article-setting) or just for a specific post in the "Discussion" metabox in the sidebar of that post.
401,437
<p>I made a custom plugin for inserting staging / production versions of a Google Tag Manager container based on the server's IP address.</p> <p>How do I make it compatible with WP-CLI so it will update when I run the <code>wp plugin update --all</code> command?</p>
[ { "answer_id": 401439, "author": "jdm2112", "author_id": 45202, "author_profile": "https://wordpress.stackexchange.com/users/45202", "pm_score": 0, "selected": false, "text": "<p>Support for plugins that do not reside on wordpress.org appears to be supported by <code>wp plugin install</c...
2022/01/17
[ "https://wordpress.stackexchange.com/questions/401437", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78660/" ]
I made a custom plugin for inserting staging / production versions of a Google Tag Manager container based on the server's IP address. How do I make it compatible with WP-CLI so it will update when I run the `wp plugin update --all` command?
You would implement this: <https://make.wordpress.org/core/2021/06/29/introducing-update-uri-plugin-header-in-wordpress-5-8/> First you would add a `Update URI:` header to your plugin with a custom domain. Second, you would add a filter to your plugin, using the filter name `update_plugins_{$hostname}` where `{$hostname}` is the value you gave your `Update URI:` . E.g. `Update URI: example.com` would have the filter `update_plugins_example.com`. In this filter, you would then run some code that checks if there is an update for your plugin. When your code is finished running, it will return the answer. <https://developer.wordpress.org/reference/hooks/update_plugins_hostname/> The value you return will need to be an array containing the values in the parameter section. Or it can return `false` to indicate there are not updates. The second and third parameters can be used to figure out which plugin WP is asking for update information. There are very few examples of this filter being used, it's very new and the documentation describes how to use it instead of demonstrating. Here's some untested pseudocode of what I think such a filter might look like: ```php add_filter( 'update_plugins_example.com', function( $update, array $plugin_data, string $plugin_file, $locales ) { // only check this plugin if ( $plugin_file !== 'myplugin.php' ) { return $update; } // already done update check elsewhere if ( ! empty( $update ) ) { return $update; } // CODE GOES HERE TO FIND UPDATE, maybe ask a server what // the latest version number is and call `version_compare`? $is_update_available = true; // no updates found if ( ! $is_update_available ) { return false; } // Update found? return [ 'slug' => 'myplugin', 'version' => '9000', 'url' => 'example.com/myplugin/', 'package' => 'example.com/newversion.zip', ]; }, 10, 4 ); ``` As for the actual checking of the update, that depends entirely on you, there is no canonical correct way to do that. For example, you could toss a coin and return gibberish values. You could make a HTTP request to a file on a server to fetch the latest version number and compare it to the version installed. You could implement a license key check, or ping Githubs API for release versions, etc. It is entirely up to you.
401,440
<p>I have a category page, how do i display this category sibling categories on this page as well? I know how to display children categories:</p> <pre><code>&lt;ul class=&quot;slider-container-list sub-categories-block front-categories-block front-categories-scroll&quot;&gt; &lt;?php $term = get_queried_object(); $children = get_terms( $term-&gt;taxonomy, array( 'parent' =&gt; $term-&gt;term_id, 'hide_empty' =&gt; false ) ); if ( $children ) { foreach( $children as $subcat ){ echo '&lt;li class=&quot;category-thumbnail-item&quot;&gt;&lt;a class=&quot;category-thumbnail&quot; href=&quot;' . esc_url(get_term_link($subcat, $subcat-&gt;taxonomy)) . '&quot;&gt;'; echo '&lt;div class=&quot;category-thumbnail-image&quot;&gt;&lt;img src=&quot;' . z_taxonomy_image_url($subcat-&gt;term_id, 'medium'). '&quot; data-pin-nopin=&quot;true&quot; alt=&quot;'. $subcat-&gt;name .' Sub Category Image&quot;&gt; &lt;/div&gt;'; echo '&lt;div class=&quot;category-title&quot;&gt;' . $subcat-&gt;name . '&lt;/div&gt;&lt;/a&gt;&lt;/li&gt;'; } } ?&gt; &lt;/ul&gt; </code></pre> <p>Now i am trying to figure out how to display siblings... Should i call parent ID and children after? I think i need to get term_id somehow, i am sure i am missing something:(</p> <pre><code> &lt;ul class=&quot;slider-container-list sub-categories-block front-categories-block front-categories-scroll&quot;&gt; &lt;?php $term_id = 10; $taxonomy_name = 'products'; $termchildren = get_term_children( $term_id, $taxonomy_name ); if ( $termchildren ) { foreach ( $termchildren as $child ){ echo '&lt;li class=&quot;category-thumbnail-item&quot;&gt;&lt;a class=&quot;category-thumbnail&quot; href=&quot;' . esc_url(get_term_link($child, $child-&gt;taxonomy)) . '&quot;&gt;'; echo '&lt;div class=&quot;category-thumbnail-image&quot;&gt;&lt;img src=&quot;' . z_taxonomy_image_url($child-&gt;term_id, 'medium'). '&quot; data-pin-nopin=&quot;true&quot; alt=&quot;'. $child-&gt;name .' Sub Category Image&quot;&gt; &lt;/div&gt;'; echo '&lt;div class=&quot;category-title&quot;&gt;' . $child-&gt;name . '&lt;/div&gt;&lt;/a&gt;&lt;/li&gt;'; } } ?&gt; &lt;/ul&gt; </code></pre> <p>i assume, but how i exclude existing category i am on from this list. Hope it makes sense:) Please help anyone?</p> <p><strong>UPDATE:</strong> So i found the solution:</p> <pre><code>&lt;ul class=&quot;slider-container-list sub-categories-block front-categories-block front-categories-scroll&quot;&gt; &lt;?php $term = get_queried_object(); $children = get_terms( $term-&gt;taxonomy, array( 'parent' =&gt; $term-&gt;term_id, 'hide_empty' =&gt; false ) ); if ( $children ) { foreach( $children as $subcat ){ echo '&lt;li class=&quot;category-thumbnail-item&quot;&gt;&lt;a class=&quot;category-thumbnail&quot; href=&quot;' . esc_url(get_term_link($subcat, $subcat-&gt;taxonomy)) . '&quot;&gt;'; echo '&lt;div class=&quot;category-thumbnail-image&quot;&gt;&lt;img src=&quot;' . z_taxonomy_image_url($subcat-&gt;term_id, 'medium'). '&quot; data-pin-nopin=&quot;true&quot; alt=&quot;'. $subcat-&gt;name .' Sub Category Image&quot;&gt; &lt;/div&gt;'; echo '&lt;div class=&quot;category-title&quot;&gt;' . $subcat-&gt;name . '&lt;/div&gt;&lt;/a&gt;&lt;/li&gt;'; } } ?&gt; &lt;/ul&gt; &lt;ul class=&quot;slider-container-list sub-categories-block front-categories-block front-categories-scroll&quot;&gt; &lt;?php $term = get_queried_object(); $siblings = get_terms( $term-&gt;taxonomy, array( 'parent' =&gt; $term-&gt;parent, 'taxonomy' =&gt; $taxonomy_name, 'exclude' =&gt; array( $current_term-&gt;term_id ), 'hide_empty' =&gt; false, ) ); if ( $siblings ) { foreach( $siblings as $sibling ){ echo '&lt;li class=&quot;category-thumbnail-item&quot;&gt;&lt;a class=&quot;category-thumbnail&quot; href=&quot;' . esc_url(get_term_link($sibling, $sibling-&gt;taxonomy)) . '&quot;&gt;'; echo '&lt;div class=&quot;category-thumbnail-image&quot;&gt;&lt;img src=&quot;' . z_taxonomy_image_url($sibling-&gt;term_id, 'medium'). '&quot; data-pin-nopin=&quot;true&quot; alt=&quot;'. $sibling-&gt;name .' Sub Category Image&quot;&gt; &lt;/div&gt;'; echo '&lt;div class=&quot;category-title&quot;&gt;' . $sibling-&gt;name . '&lt;/div&gt;&lt;/a&gt;&lt;/li&gt;'; } } ?&gt; &lt;/ul&gt; </code></pre> <p>I am able to display siblings here, but now my challenge is to</p> <ol> <li>Exclude the existing category, that i am on.</li> <li>And not to display siblings for the top parent categories</li> </ol> <p>Fun fun!</p>
[ { "answer_id": 401450, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<blockquote>\n<p>I have a category page, how do i display this category sibling\ncategories on this page as we...
2022/01/18
[ "https://wordpress.stackexchange.com/questions/401440", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76850/" ]
I have a category page, how do i display this category sibling categories on this page as well? I know how to display children categories: ``` <ul class="slider-container-list sub-categories-block front-categories-block front-categories-scroll"> <?php $term = get_queried_object(); $children = get_terms( $term->taxonomy, array( 'parent' => $term->term_id, 'hide_empty' => false ) ); if ( $children ) { foreach( $children as $subcat ){ echo '<li class="category-thumbnail-item"><a class="category-thumbnail" href="' . esc_url(get_term_link($subcat, $subcat->taxonomy)) . '">'; echo '<div class="category-thumbnail-image"><img src="' . z_taxonomy_image_url($subcat->term_id, 'medium'). '" data-pin-nopin="true" alt="'. $subcat->name .' Sub Category Image"> </div>'; echo '<div class="category-title">' . $subcat->name . '</div></a></li>'; } } ?> </ul> ``` Now i am trying to figure out how to display siblings... Should i call parent ID and children after? I think i need to get term\_id somehow, i am sure i am missing something:( ``` <ul class="slider-container-list sub-categories-block front-categories-block front-categories-scroll"> <?php $term_id = 10; $taxonomy_name = 'products'; $termchildren = get_term_children( $term_id, $taxonomy_name ); if ( $termchildren ) { foreach ( $termchildren as $child ){ echo '<li class="category-thumbnail-item"><a class="category-thumbnail" href="' . esc_url(get_term_link($child, $child->taxonomy)) . '">'; echo '<div class="category-thumbnail-image"><img src="' . z_taxonomy_image_url($child->term_id, 'medium'). '" data-pin-nopin="true" alt="'. $child->name .' Sub Category Image"> </div>'; echo '<div class="category-title">' . $child->name . '</div></a></li>'; } } ?> </ul> ``` i assume, but how i exclude existing category i am on from this list. Hope it makes sense:) Please help anyone? **UPDATE:** So i found the solution: ``` <ul class="slider-container-list sub-categories-block front-categories-block front-categories-scroll"> <?php $term = get_queried_object(); $children = get_terms( $term->taxonomy, array( 'parent' => $term->term_id, 'hide_empty' => false ) ); if ( $children ) { foreach( $children as $subcat ){ echo '<li class="category-thumbnail-item"><a class="category-thumbnail" href="' . esc_url(get_term_link($subcat, $subcat->taxonomy)) . '">'; echo '<div class="category-thumbnail-image"><img src="' . z_taxonomy_image_url($subcat->term_id, 'medium'). '" data-pin-nopin="true" alt="'. $subcat->name .' Sub Category Image"> </div>'; echo '<div class="category-title">' . $subcat->name . '</div></a></li>'; } } ?> </ul> <ul class="slider-container-list sub-categories-block front-categories-block front-categories-scroll"> <?php $term = get_queried_object(); $siblings = get_terms( $term->taxonomy, array( 'parent' => $term->parent, 'taxonomy' => $taxonomy_name, 'exclude' => array( $current_term->term_id ), 'hide_empty' => false, ) ); if ( $siblings ) { foreach( $siblings as $sibling ){ echo '<li class="category-thumbnail-item"><a class="category-thumbnail" href="' . esc_url(get_term_link($sibling, $sibling->taxonomy)) . '">'; echo '<div class="category-thumbnail-image"><img src="' . z_taxonomy_image_url($sibling->term_id, 'medium'). '" data-pin-nopin="true" alt="'. $sibling->name .' Sub Category Image"> </div>'; echo '<div class="category-title">' . $sibling->name . '</div></a></li>'; } } ?> </ul> ``` I am able to display siblings here, but now my challenge is to 1. Exclude the existing category, that i am on. 2. And not to display siblings for the top parent categories Fun fun!
> > I have a category page, how do i display this category sibling > categories on this page as well? I know how to display children > categories > > > > > I think i need to get term\_id somehow > > > On a term archive page, e.g. at `example.com/category/foo/` (for the default `category` taxonomy), 1. You can use [`get_queried_object()`](https://developer.wordpress.org/reference/functions/get_queried_object/) to retrieve the term *object* for the term being queried (`foo` in the above sample URL). ```php $term = get_queried_object(); $term_id = $term->term_id; ``` 2. You can use [`get_queried_object_id()`](https://developer.wordpress.org/reference/functions/get_queried_object_id/) to retrieve just the term *ID* of the term being queried. ```php $term_id = get_queried_object_id(); ``` Now as for retrieving term's siblings, you can use [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) just like you did when retrieving the term's children. So for example, for the term being queried (or simply put, the current term), ```php $taxonomy_name = 'products'; // Get the full term object/data. $current_term = get_queried_object(); // Get the term's direct children. // **Use 'child_of' instead of 'parent' to retrieve direct and non-direct children. $children = get_terms( array( 'taxonomy' => $taxonomy_name, 'parent' => $current_term->term_id, 'hide_empty' => false, ) ); // Display the children. if ( ! empty( $children ) ) { echo "<h3>Children of $current_term->name</h3>"; echo '<ul>'; foreach ( $children as $child ) { echo "<li>$child->name</li>"; } echo '</ul>'; } // Get the term's direct siblings. $siblings = get_terms( array( 'taxonomy' => $taxonomy_name, 'parent' => $current_term->parent, 'exclude' => array( $current_term->term_id ), 'hide_empty' => false, ) ); // Display the siblings. if ( ! empty( $siblings ) ) { echo "<h3>Siblings of $current_term->name</h3>"; echo '<ul>'; foreach ( $siblings as $sibling ) { echo "<li>$sibling->name</li>"; } echo '</ul>'; } ``` And if you want to use [`get_term_children()`](https://developer.wordpress.org/reference/functions/get_term_children/), note that it retrieves all *direct and non-direct* children (just like `get_terms()` if `child_of` is used), and the function returns an *array of term **ID***s, hence in your `foreach`, you can use [`get_term()`](https://developer.wordpress.org/reference/functions/get_term/) to get the full term object/data. ```php $term_id = get_queried_object_id(); // or just use a specific term ID, if you want to $termchildren = get_term_children( $term_id, $taxonomy_name ); foreach ( $termchildren as $child_id ) { $child = get_term( $child_id ); // ... your code. } ``` > > how i exclude existing category i am on from this list > > > * If you use `get_terms()`, you can use the `exclude` arg like you can see in my example above. * If you use `get_term_children()`, then you can use `continue` like so: (but that's just an example; you can use `array_filter()` to filter the `$termchildren` array *before* looping through the items, if you want to) ```php foreach ( $termchildren as $child_id ) { if ( (int) $child_id === (int) $term_id ) { continue; } $child = get_term( $child_id ); // ... your code. } ```
401,463
<pre><code>foreach( $posts as $post ) { // Search for images and fill the missing dimensions in the current post content $post_content = $this-&gt;add_image_dimensions( $post-&gt;post_content ); // Update the post content in the database only if the new $post_content it is not the same // as the current $post-&gt;post_content if( $post_content != $post-&gt;post_content ) { $query = &quot;UPDATE &quot; . $wpdb-&gt;prefix . &quot;posts SET post_content = '&quot; . $post_content . &quot;' WHERE ID = &quot; . $post-&gt;ID; $wpdb-&gt;query( $query ); } // Add a post meta to the current post to mark it as doone update_post_meta( $post-&gt;ID, 'image_dimensions_filled', 1 ); </code></pre> <p>If there is a <code>\</code> character in the text of the post, then it disappears. How to fix it?</p> <p>Would that be correct?</p> <pre><code>... if( $post_content != $post-&gt;post_content ) { $post_content = wp_slash($post_content); $query = &quot;UPDATE &quot; . $wpdb-&gt;prefix . &quot;posts SET post_content = '&quot; . $post_content . &quot;' WHERE ID = &quot; . $post-&gt;ID; ... </code></pre> <p>This variant not work.</p> <pre><code>$wpdb-&gt;query( $wpdb-&gt;prepare( $query )); </code></pre> <p>Sorry for my English.</p>
[ { "answer_id": 401450, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<blockquote>\n<p>I have a category page, how do i display this category sibling\ncategories on this page as we...
2022/01/18
[ "https://wordpress.stackexchange.com/questions/401463", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151498/" ]
``` foreach( $posts as $post ) { // Search for images and fill the missing dimensions in the current post content $post_content = $this->add_image_dimensions( $post->post_content ); // Update the post content in the database only if the new $post_content it is not the same // as the current $post->post_content if( $post_content != $post->post_content ) { $query = "UPDATE " . $wpdb->prefix . "posts SET post_content = '" . $post_content . "' WHERE ID = " . $post->ID; $wpdb->query( $query ); } // Add a post meta to the current post to mark it as doone update_post_meta( $post->ID, 'image_dimensions_filled', 1 ); ``` If there is a `\` character in the text of the post, then it disappears. How to fix it? Would that be correct? ``` ... if( $post_content != $post->post_content ) { $post_content = wp_slash($post_content); $query = "UPDATE " . $wpdb->prefix . "posts SET post_content = '" . $post_content . "' WHERE ID = " . $post->ID; ... ``` This variant not work. ``` $wpdb->query( $wpdb->prepare( $query )); ``` Sorry for my English.
> > I have a category page, how do i display this category sibling > categories on this page as well? I know how to display children > categories > > > > > I think i need to get term\_id somehow > > > On a term archive page, e.g. at `example.com/category/foo/` (for the default `category` taxonomy), 1. You can use [`get_queried_object()`](https://developer.wordpress.org/reference/functions/get_queried_object/) to retrieve the term *object* for the term being queried (`foo` in the above sample URL). ```php $term = get_queried_object(); $term_id = $term->term_id; ``` 2. You can use [`get_queried_object_id()`](https://developer.wordpress.org/reference/functions/get_queried_object_id/) to retrieve just the term *ID* of the term being queried. ```php $term_id = get_queried_object_id(); ``` Now as for retrieving term's siblings, you can use [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) just like you did when retrieving the term's children. So for example, for the term being queried (or simply put, the current term), ```php $taxonomy_name = 'products'; // Get the full term object/data. $current_term = get_queried_object(); // Get the term's direct children. // **Use 'child_of' instead of 'parent' to retrieve direct and non-direct children. $children = get_terms( array( 'taxonomy' => $taxonomy_name, 'parent' => $current_term->term_id, 'hide_empty' => false, ) ); // Display the children. if ( ! empty( $children ) ) { echo "<h3>Children of $current_term->name</h3>"; echo '<ul>'; foreach ( $children as $child ) { echo "<li>$child->name</li>"; } echo '</ul>'; } // Get the term's direct siblings. $siblings = get_terms( array( 'taxonomy' => $taxonomy_name, 'parent' => $current_term->parent, 'exclude' => array( $current_term->term_id ), 'hide_empty' => false, ) ); // Display the siblings. if ( ! empty( $siblings ) ) { echo "<h3>Siblings of $current_term->name</h3>"; echo '<ul>'; foreach ( $siblings as $sibling ) { echo "<li>$sibling->name</li>"; } echo '</ul>'; } ``` And if you want to use [`get_term_children()`](https://developer.wordpress.org/reference/functions/get_term_children/), note that it retrieves all *direct and non-direct* children (just like `get_terms()` if `child_of` is used), and the function returns an *array of term **ID***s, hence in your `foreach`, you can use [`get_term()`](https://developer.wordpress.org/reference/functions/get_term/) to get the full term object/data. ```php $term_id = get_queried_object_id(); // or just use a specific term ID, if you want to $termchildren = get_term_children( $term_id, $taxonomy_name ); foreach ( $termchildren as $child_id ) { $child = get_term( $child_id ); // ... your code. } ``` > > how i exclude existing category i am on from this list > > > * If you use `get_terms()`, you can use the `exclude` arg like you can see in my example above. * If you use `get_term_children()`, then you can use `continue` like so: (but that's just an example; you can use `array_filter()` to filter the `$termchildren` array *before* looping through the items, if you want to) ```php foreach ( $termchildren as $child_id ) { if ( (int) $child_id === (int) $term_id ) { continue; } $child = get_term( $child_id ); // ... your code. } ```
401,470
<p>I see a lot of these in premium themes/plugins.</p> <p><strong>#1 - Why would you escape this? It's your own data. For consistency?</strong></p> <pre><code>function prefix_a() { $class_attr = 'a b c'; // Some more code. return '&lt;div class=&quot;' . esc_attr( $class_attr ) . '&quot;&gt;Content&lt;/div&gt;'; } // Called somewhere. prefix_a(); </code></pre> <p><strong>#2 - Again, why? The data doesn't come from the DB.</strong></p> <pre><code>function prefix_b( $class ) { // Some code. return '&lt;div class=&quot;' . esc_attr( $class ) . '&quot;&gt;Content&lt;/div&gt;'; } // Called by a developer from the team. prefix_b( 'developer adds a class' ); </code></pre> <p>Yes, a child theme developer might call the function above, but he/she is already in control.</p> <p><strong>#3 - Why? If someone can add filters, it can do a lot more.</strong></p> <pre><code>function prefix_c() { $class_attr = apply_filters( 'prefix_c', 'foo bar' ); // Some code. return '&lt;div class=&quot;' . esc_attr( $class_attr ) . '&quot;&gt;Content&lt;/div&gt;'; } // Called somewhere. prefix_c(); </code></pre> <p>I can only think about consistency and to be safe if someone uses untrusted data (excluding the #1 case).</p>
[ { "answer_id": 401483, "author": "Sébastien Serre", "author_id": 62892, "author_profile": "https://wordpress.stackexchange.com/users/62892", "pm_score": 0, "selected": false, "text": "<p>I think the best answer is in the official doc: <a href=\"https://developer.wordpress.org/plugins/sec...
2022/01/18
[ "https://wordpress.stackexchange.com/questions/401470", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/49286/" ]
I see a lot of these in premium themes/plugins. **#1 - Why would you escape this? It's your own data. For consistency?** ``` function prefix_a() { $class_attr = 'a b c'; // Some more code. return '<div class="' . esc_attr( $class_attr ) . '">Content</div>'; } // Called somewhere. prefix_a(); ``` **#2 - Again, why? The data doesn't come from the DB.** ``` function prefix_b( $class ) { // Some code. return '<div class="' . esc_attr( $class ) . '">Content</div>'; } // Called by a developer from the team. prefix_b( 'developer adds a class' ); ``` Yes, a child theme developer might call the function above, but he/she is already in control. **#3 - Why? If someone can add filters, it can do a lot more.** ``` function prefix_c() { $class_attr = apply_filters( 'prefix_c', 'foo bar' ); // Some code. return '<div class="' . esc_attr( $class_attr ) . '">Content</div>'; } // Called somewhere. prefix_c(); ``` I can only think about consistency and to be safe if someone uses untrusted data (excluding the #1 case).
1. You probably wouldn't. If you did it would be to make sure it was in place already if in future you decided to make the variable dynamic or filterable. 2. In this case I would suggest it for similar reasons to #1. You may know where `$class` is coming from now, but this may change in future, and it prepares the function for potential use in different contexts where `$class` may not be controlled. 3. You need to escape here because you know for certain that your code has no control over what the value of `$class` may be, and you should make sure that your code does not break if an improper value is passed. This is not solely a security concern. As you will learn from following questions on this site, many developers who use filters do not necessarily know what they are doing. They may write code that takes a dynamic value and adds it as a class using your filter. Most of the time this might be fine, but what if they are automatically pulling something in like a post title? Eventually there may be a post title with a `"` character, and this will break the markup of their site if you do not escape the values from that filter. An experienced developer would know what the problem is and escape it themselves, but not all developers who might use your filter are quite as experienced.
401,476
<p>I have the following custom search active in our WP admin for only administrators</p> <pre><code>add_action('pre_get_posts', 'query_custom_admin_search', 21 ); function query_custom_admin_search( $wp_query ) { global $current_user; if( is_admin() ) { if (get_current_user_role()==&quot;administrator&quot;){ if ( $wp_query-&gt;query['post_type'] != &quot;apartments&quot; ){ return; }else{ $custom_fields = array(&quot;city&quot;,&quot;state_county&quot;,); $search_term = $wp_query-&gt;query_vars['s']; if ( $search_term != '' ) { $meta_query = array( 'relation' =&gt; 'OR' ); foreach( $custom_fields as $custom_field ) { array_push( $meta_query, array( 'key' =&gt; $custom_field, 'value' =&gt; $search_term, 'compare' =&gt; 'LIKE' )); } $wp_query-&gt;set( 'meta_query', $meta_query ); }; return; } }else{ return; } }else{ return; } } </code></pre> <p>This searches custom meta keys that we need to check and it works great. The only problem is that the default search columns in the wp_posts table such as post_title seem to no longer be searched.</p> <p>How can I do both in this query ?</p>
[ { "answer_id": 401639, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": 0, "selected": false, "text": "<p>try to return the $wp_query when is not admin</p>\n<pre class=\"lang-php prettyprint-override\"><code>...
2022/01/18
[ "https://wordpress.stackexchange.com/questions/401476", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28543/" ]
I have the following custom search active in our WP admin for only administrators ``` add_action('pre_get_posts', 'query_custom_admin_search', 21 ); function query_custom_admin_search( $wp_query ) { global $current_user; if( is_admin() ) { if (get_current_user_role()=="administrator"){ if ( $wp_query->query['post_type'] != "apartments" ){ return; }else{ $custom_fields = array("city","state_county",); $search_term = $wp_query->query_vars['s']; if ( $search_term != '' ) { $meta_query = array( 'relation' => 'OR' ); foreach( $custom_fields as $custom_field ) { array_push( $meta_query, array( 'key' => $custom_field, 'value' => $search_term, 'compare' => 'LIKE' )); } $wp_query->set( 'meta_query', $meta_query ); }; return; } }else{ return; } }else{ return; } } ``` This searches custom meta keys that we need to check and it works great. The only problem is that the default search columns in the wp\_posts table such as post\_title seem to no longer be searched. How can I do both in this query ?
> > The only problem is that the default search columns in the wp\_posts > table such as post\_title seem to no longer be searched. > > > They're actually being searched, but the operator used is `AND` instead of `OR` as in `WHERE ( <search query> AND <meta query> )`, hence if for example one searched for `foo`, then WordPress will search for posts which.. * Contain `foo` in the post title/content/excerpt *and* * Contain `foo` in the meta `city` or `state_county` So if you want the operator be changed to `OR`, i.e. search in the post title/content/excerpt **or** your custom fields, then you can try the following which simply repositions the default search query in the `WHERE` clause: 1. This snippet modifies the meta queries (to add your custom fields) and also sets a private arg used as a flag which if true, then we'll reposition the search query. ```php add_action( 'pre_get_posts', 'query_custom_admin_search', 21 ); function query_custom_admin_search( $query ) { // Check if the current user has the 'administrator' role. if ( ! in_array( 'administrator', (array) wp_get_current_user()->roles ) ) { return; } // Check if we're on the "Posts" page at wp-admin/edit.php?post_type=apartments // and that a search keyword is set. if ( ! is_admin() || ! $query->is_main_query() || 'edit-apartments' !== get_current_screen()->id || ! strlen( $query->get( 's' ) ) ) { return; } // Retrieve existing meta queries, if any. $meta_query = (array) $query->get( 'meta_query' ); // Define your custom fields (meta keys). $custom_fields = array( 'city', 'state_county' ); // This is for your custom fields above. $meta_query2 = array( 'relation' => 'OR' ); $s = $query->get( 's' ); foreach ( $custom_fields as $meta_key ) { $meta_query2[] = array( 'key' => $meta_key, 'value' => $s, 'compare' => 'LIKE', ); } // Add your meta query to the existing ones in $meta_query. $meta_query[] = $meta_query2; $query->set( 'meta_query', $meta_query ); // Set a custom flag for the posts_search and posts_where. $query->set( '_search_OR', true ); } ``` 2. This snippet uses the [`posts_search` hook](https://developer.wordpress.org/reference/hooks/posts_search/) to "empty" the search query, after storing it in a private arg which we'll use in the [`posts_where` hook](https://developer.wordpress.org/reference/hooks/posts_where/) where we reposition the search query. ```php add_filter( 'posts_search', 'wpse_401476_admin_posts_search', 21, 2 ); function wpse_401476_admin_posts_search( $search, $query ) { if ( $query->get( '_search_OR' ) ) { $query->set( '_search_SQL', $search ); $search = ''; } return $search; } ``` 3. Now this snippet is the one that repositions the search query. It uses [`WP_Meta_Query::get_sql()`](https://developer.wordpress.org/reference/classes/wp_meta_query/get_sql/) to retrieve the meta query's (SQL) clauses (`join` and `where`) used in the current query. ```php add_filter( 'posts_where', 'wpse_401476_admin_posts_where', 21, 2 ); function wpse_401476_admin_posts_where( $where, $query ) { if ( $query->get( '_search_OR' ) && $search = $query->get( '_search_SQL' ) ) { global $wpdb; $clauses = $query->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $query ); if ( ! empty( $clauses['where'] ) ) { $where2 = "( 1 $search ) OR ( 1 {$clauses['where']} )"; $where = str_replace( $clauses['where'], " AND ( $where2 )", $where ); $query->set( '_search_SQL', false ); $query->set( '_search_OR', false ); } } return $where; } ``` So with the above, we'd get a condition that looks like `( ( 1 AND <search query> ) OR ( 1 AND <meta query> ) )` which is equivalent to the `( <search query> OR <meta query> )`. Tried & tested working on WordPress v5.8.3. Notes: ------ 1. Use the above snippets instead of what you have in the question. 2. The operator would only be changed if the current user has the `administrator` *role* and that the current page is the admin page for managing posts in the `apartments` post type, and that the search keyword is set, and I also checked if the current query/`WP_Query` is the *main* query. 3. I used `21` as the priority, hence you might want to use a greater number (e.g. `100`) to make the filters apply properly (i.e. not overwritten by plugins or the active theme).
401,525
<p>Looking for the filter hook for the admin/comments/reply to process (where you use 'reply to' in the comments administration screen). This will be used in a custom plugin.</p> <p>(The plugin adds a hidden field to a front-end entered comment to reduce bot-entered comments. The extra field is inserted properly on the front end, but not in the admin comment list page.)</p> <p>I need to</p> <ul> <li>add a hidden field to the comment drop-down on the comments admin list (the comment field that shows when you click the 'reply' link for a comment).</li> <li>add some pre-processing to the comment drop-down when it is submitted and before WP processes the comment.</li> </ul> <p>Not sure where to start on this, although I think it is in <a href="https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/</a> .</p> <p>Am I on the right track? Is there a filter for the adding of fields to the comment box form that is on the admin/comments page?</p> <p>(Note: had posted this question in StackExchange main area by mistake. And got a down-vote and close vote without explanation for my efforts. So duplicating the question here - where I meant to put it.)</p> <p><strong>Added</strong></p> <p>The hidden field is added to the comment form on the front end with the 'add_meta_boxes_comment' action hook, which uses the 'add_meta_box' function to specify the field and the callback function for that inserted/hidden field.</p> <p>The hidden/added field is processed via the 'edit_comment' hook. If the hidden field is not there, then the comment is not saved.</p> <p>This works fine in the front-end, but the hidden/added field is not added to the comment form in the back-end's &quot;Reply&quot; on the comment list page.</p>
[ { "answer_id": 401586, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<blockquote>\n<p>Is there a filter for the adding of fields to the comment box form\nthat is on the admin/com...
2022/01/19
[ "https://wordpress.stackexchange.com/questions/401525", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29416/" ]
Looking for the filter hook for the admin/comments/reply to process (where you use 'reply to' in the comments administration screen). This will be used in a custom plugin. (The plugin adds a hidden field to a front-end entered comment to reduce bot-entered comments. The extra field is inserted properly on the front end, but not in the admin comment list page.) I need to * add a hidden field to the comment drop-down on the comments admin list (the comment field that shows when you click the 'reply' link for a comment). * add some pre-processing to the comment drop-down when it is submitted and before WP processes the comment. Not sure where to start on this, although I think it is in <https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/> . Am I on the right track? Is there a filter for the adding of fields to the comment box form that is on the admin/comments page? (Note: had posted this question in StackExchange main area by mistake. And got a down-vote and close vote without explanation for my efforts. So duplicating the question here - where I meant to put it.) **Added** The hidden field is added to the comment form on the front end with the 'add\_meta\_boxes\_comment' action hook, which uses the 'add\_meta\_box' function to specify the field and the callback function for that inserted/hidden field. The hidden/added field is processed via the 'edit\_comment' hook. If the hidden field is not there, then the comment is not saved. This works fine in the front-end, but the hidden/added field is not added to the comment form in the back-end's "Reply" on the comment list page.
Although @SallyCJ's answer might work, and is probably good information, I went in a different direction that worked for my application. My application needs a hidden field in the comment form. Although you can easily add the hidden field to the front-end comment form, the back-end doesn't use that process. But my application needs the POST of that hidden value for a verification process. Since the hidden field isn't easily insertable in the back-end drop-down comment form (that you get when you hit the reply button), I reasoned that only an authorized admin can get to the admin/comment list, so my application doesn't need to check if it is a bot accessing the comment form. (My plugin senses bot comment submissions.) If you are logged in as an admin, then you are not a bot. So, in the section that checks for the hidden field, I added this to add the GUID value to 'the\_hidden\_field' that is shown on the front-end comment form: ``` if (current_user_can( 'moderate_comments' ) ) { // forces the guid on admin/comment replies without needing // to add a hidden field to the dropdown form. $_POST['the_hidden_field'] = wp_generate_uuid4(); return $commentdata; } ``` The 'if' statement will be true for the admin/editor/author roles only, so the hidden field is sort of added to the comment POST. Note that others have said that you can use is\_admin() to see if you are in an admin page, but that returns false in some instances - like if you are in the admin/list comments page, and you hit the 'reply' button for a comment. An is\_admin() check there returns false. So that didn't work. Adding the code above resolved my issue. Might not work for all - you may need the code suggested by @SallyCJ . But it worked for me.
401,568
<p>.Net developer here trying to learn some of the basics of wordpress. I have a basic question but I guess there's so much that I don't know that I can't even get a relevant result when searching here or via Google.</p> <p>If I create a plugin and activate it, and run <code>flush_rewrite_rules();</code> in my activation code, should I be able to put the path to a page in my plugin into the address bar of a browser and get the results of the script in my plugin page?</p> <p>For example, say my plugin is named my-plugin. The path to my-plugin is of course <code>wp-content/plugins/my-plugin</code>. I create the file <code>wp-content/plugins/my-plugin/my-page.php</code>.</p> <p>The contents of my-page.php are:</p> <pre><code>&lt;?php if (!isset($returnVal)) $returnVal = new stdClass(); $returnVal-&gt;status = &quot;success&quot;; $returnVal-&gt;info = &quot;seems to work&quot;; echo json_encode($returnVal); </code></pre> <p>Should I be able to access that by entering this in the browser:</p> <pre><code>https://my-site/wp-content/plugins/my-plugin/my-page.php </code></pre> <p>I'm asking this b/c I always get a 404 when I do that.</p> <p>I've been beating my head against this for awhile now and I've come to the conclusion that there's just something I'm missing about the way wordpress works.</p> <p>More details: I'm using the Avada theme (v7.6.1) Form builder. It has an option to POST to a url when the user clicks a submit button. I need it to POST the form data to the page in my plugin. Then my plugin page needs to return success or error to the frontend page.</p> <p>I figured I would start at the bottom and work my way up to accomplish this, so I decided to see if I can even get my plugin to return the success/error object. This is what I'm stuck on.</p> <p>If I get this to work then then next step would be putting the url to my plugin page in the Avada Form Builder options for what happens when the user clicks the submit button. I haven't got to that point b/c I'm stuck on the above.</p> <p><a href="https://stackoverflow.com/questions/70779734/how-to-post-to-admin-post-php-from-avada-formbuilder-form">Here's a post on s/o</a> I made regarding the bigger picture.</p> <p>UPDATE: SOME PROGRESS MADE @kero's comment pointed me in the direction of custom REST endpoints and I was able to make a GET request work in the browser to <a href="https://my-site.com/wp-json/my-plugin/v1/my-endpoint" rel="nofollow noreferrer">https://my-site.com/wp-json/my-plugin/v1/my-endpoint</a> and it returns this:</p> <pre><code>{&quot;status&quot;:&quot;success&quot;,&quot;info&quot;:&quot;seems to work&quot;} </code></pre> <p>Now I'm stuck trying to get the Avada form to call that endpoint. I'v tried the following urls:</p> <ol> <li>wp-json/my-plugin/v1/my-endpoint</li> <li>/wp-json/my-plugin/v1/my-endpoint</li> <li><a href="https://my-site.com/wp-json/my-plugin/v1/my-endpoint" rel="nofollow noreferrer">https://my-site.com/wp-json/my-plugin/v1/my-endpoint</a></li> </ol> <p>Both 1 &amp; 2 result in this:</p> <pre><code>{&quot;status&quot;:&quot;error&quot;,&quot;info&quot;:&quot;url_failed&quot;} </code></pre> <p>#3 returns simply a -1</p> <p><a href="https://i.stack.imgur.com/mvawI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mvawI.png" alt="return message" /></a></p> <p>Any ideas on how to get the Avada form to call that endpoint and get the result?</p> <p>UDPATE: Requested details provided:</p> <p>Here's the REST endpoint code from my main plugin file:</p> <pre><code>add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'my_awesome_func', )); }); function my_awesome_func() { if (!isset($returnVal)) $returnVal = new stdClass(); $returnVal-&gt;status = &quot;success&quot;; $returnVal-&gt;info = &quot;seems to work&quot;; return $returnVal; } </code></pre> <p>The methods in the snippet above is set to &quot;GET&quot; but I also tried it set to &quot;POST&quot; and the Avada form has a setting where you choose GET/POST and I tested it both ways. Neither the GET nor the POST would work for me.</p> <p>The Avada form is POSTing to <code>wp-admin/admin-ajax.php</code> with the following key:values. Interestingly it gets a 200 from the POST but still returns the same values mentioned above.</p> <pre><code>action:fusion_form_submit_form_to_url fusionAction: wp-json/my-plugin/v1/my-page formData: email=&amp;main_license_number=&amp;credit_card_last_four=&amp;fusion_privacy_store_ip_ua=false&amp;fusion_privacy_expiration_interval=48&amp;privacy_expiration_action=anonymize&amp;fusion-form-nonce-1808=3d676aef78&amp;fusion-fields-hold-private-data= </code></pre>
[ { "answer_id": 401569, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Welcome to WordPress and WPSE!</p>\n<p>Plugins are meant to alter or add functionality to what is already...
2022/01/20
[ "https://wordpress.stackexchange.com/questions/401568", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/218133/" ]
.Net developer here trying to learn some of the basics of wordpress. I have a basic question but I guess there's so much that I don't know that I can't even get a relevant result when searching here or via Google. If I create a plugin and activate it, and run `flush_rewrite_rules();` in my activation code, should I be able to put the path to a page in my plugin into the address bar of a browser and get the results of the script in my plugin page? For example, say my plugin is named my-plugin. The path to my-plugin is of course `wp-content/plugins/my-plugin`. I create the file `wp-content/plugins/my-plugin/my-page.php`. The contents of my-page.php are: ``` <?php if (!isset($returnVal)) $returnVal = new stdClass(); $returnVal->status = "success"; $returnVal->info = "seems to work"; echo json_encode($returnVal); ``` Should I be able to access that by entering this in the browser: ``` https://my-site/wp-content/plugins/my-plugin/my-page.php ``` I'm asking this b/c I always get a 404 when I do that. I've been beating my head against this for awhile now and I've come to the conclusion that there's just something I'm missing about the way wordpress works. More details: I'm using the Avada theme (v7.6.1) Form builder. It has an option to POST to a url when the user clicks a submit button. I need it to POST the form data to the page in my plugin. Then my plugin page needs to return success or error to the frontend page. I figured I would start at the bottom and work my way up to accomplish this, so I decided to see if I can even get my plugin to return the success/error object. This is what I'm stuck on. If I get this to work then then next step would be putting the url to my plugin page in the Avada Form Builder options for what happens when the user clicks the submit button. I haven't got to that point b/c I'm stuck on the above. [Here's a post on s/o](https://stackoverflow.com/questions/70779734/how-to-post-to-admin-post-php-from-avada-formbuilder-form) I made regarding the bigger picture. UPDATE: SOME PROGRESS MADE @kero's comment pointed me in the direction of custom REST endpoints and I was able to make a GET request work in the browser to <https://my-site.com/wp-json/my-plugin/v1/my-endpoint> and it returns this: ``` {"status":"success","info":"seems to work"} ``` Now I'm stuck trying to get the Avada form to call that endpoint. I'v tried the following urls: 1. wp-json/my-plugin/v1/my-endpoint 2. /wp-json/my-plugin/v1/my-endpoint 3. <https://my-site.com/wp-json/my-plugin/v1/my-endpoint> Both 1 & 2 result in this: ``` {"status":"error","info":"url_failed"} ``` #3 returns simply a -1 [![return message](https://i.stack.imgur.com/mvawI.png)](https://i.stack.imgur.com/mvawI.png) Any ideas on how to get the Avada form to call that endpoint and get the result? UDPATE: Requested details provided: Here's the REST endpoint code from my main plugin file: ``` add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', )); }); function my_awesome_func() { if (!isset($returnVal)) $returnVal = new stdClass(); $returnVal->status = "success"; $returnVal->info = "seems to work"; return $returnVal; } ``` The methods in the snippet above is set to "GET" but I also tried it set to "POST" and the Avada form has a setting where you choose GET/POST and I tested it both ways. Neither the GET nor the POST would work for me. The Avada form is POSTing to `wp-admin/admin-ajax.php` with the following key:values. Interestingly it gets a 200 from the POST but still returns the same values mentioned above. ``` action:fusion_form_submit_form_to_url fusionAction: wp-json/my-plugin/v1/my-page formData: email=&main_license_number=&credit_card_last_four=&fusion_privacy_store_ip_ua=false&fusion_privacy_expiration_interval=48&privacy_expiration_action=anonymize&fusion-form-nonce-1808=3d676aef78&fusion-fields-hold-private-data= ```
Generally you do not want to access your PHP files directly within WordPress because you lose a lot of "juice", meaning all WP functionality would have to be re-imported (and might break). WP is setup in a way that all requests to the CMS get routed to *index.php* and some mechanisms then decide what to do with the request. From what you write, it sounds like a [custom REST endpoint](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/) might serve you well. Expanding your code to the following should already show some results: ``` add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', [ 'methods' => [\Requests::POST], 'callback' => 'my_awesome_func', ]); }); function my_awesome_func() { if (!isset($returnVal)) $returnVal = new stdClass(); $returnVal->status = "success"; $returnVal->info = "seems to work"; return $returnVal; } ``` (using [short array syntax](https://befused.com/php/short-array/) and) changed ``` 'methods' => 'GET', ``` to ``` 'methods' => [\Requests::POST], ``` which references the [Requests' class const](https://developer.wordpress.org/reference/classes/requests/) (my preferred style - you can also use `'POST'` directly). Most likely you want to do something with the form data, so change your `my_awesome_func()` to something like this ``` function my_awesome_func(\WP_REST_Request $request) { if ($request->get_param('main_license_number') !== 'something') { return new WP_Error('Invalid license number!'); } return [ 'status' => 'success', 'info' => 'hello', ]; } ``` Now there is only one problem left: everybody can call this endpoint, they don't have to come through the form. Your request contains a `fusion-form-nonce-1808` and I assume this can be used to verify that it was indeed submitted from the form - but seems very Avada/FusionForm/some third party plugin specific - which I have no knowledge of and is out of scope for this site. But you should try contacting them and ask how to verify it, something along the lines of: ``` add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', [ 'methods' => [\Requests::POST], 'callback' => 'my_awesome_func', 'permission_callback' => function () { return magic_validate_my_nonce_please(); }, ]); }); ``` or with the [fancy arrow function added in PHP 7.4](https://stitcher.io/blog/short-closures-in-php): ``` add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', [ 'methods' => [\Requests::POST], 'callback' => 'my_awesome_func', 'permission_callback' => fn () => magic_validate_my_nonce_please(), ]); }); ```
401,607
<p>In my WordPress installation every User has an Organization. I am fetching user data using <code>get_user_meta ($user-&gt;ID)</code>. With these data I can fetch Organization ID.</p> <p>Organizations are saved as Custom Post.</p> <p>How can I fetch Organization name ?</p>
[ { "answer_id": 401569, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Welcome to WordPress and WPSE!</p>\n<p>Plugins are meant to alter or add functionality to what is already...
2022/01/21
[ "https://wordpress.stackexchange.com/questions/401607", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65189/" ]
In my WordPress installation every User has an Organization. I am fetching user data using `get_user_meta ($user->ID)`. With these data I can fetch Organization ID. Organizations are saved as Custom Post. How can I fetch Organization name ?
Generally you do not want to access your PHP files directly within WordPress because you lose a lot of "juice", meaning all WP functionality would have to be re-imported (and might break). WP is setup in a way that all requests to the CMS get routed to *index.php* and some mechanisms then decide what to do with the request. From what you write, it sounds like a [custom REST endpoint](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/) might serve you well. Expanding your code to the following should already show some results: ``` add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', [ 'methods' => [\Requests::POST], 'callback' => 'my_awesome_func', ]); }); function my_awesome_func() { if (!isset($returnVal)) $returnVal = new stdClass(); $returnVal->status = "success"; $returnVal->info = "seems to work"; return $returnVal; } ``` (using [short array syntax](https://befused.com/php/short-array/) and) changed ``` 'methods' => 'GET', ``` to ``` 'methods' => [\Requests::POST], ``` which references the [Requests' class const](https://developer.wordpress.org/reference/classes/requests/) (my preferred style - you can also use `'POST'` directly). Most likely you want to do something with the form data, so change your `my_awesome_func()` to something like this ``` function my_awesome_func(\WP_REST_Request $request) { if ($request->get_param('main_license_number') !== 'something') { return new WP_Error('Invalid license number!'); } return [ 'status' => 'success', 'info' => 'hello', ]; } ``` Now there is only one problem left: everybody can call this endpoint, they don't have to come through the form. Your request contains a `fusion-form-nonce-1808` and I assume this can be used to verify that it was indeed submitted from the form - but seems very Avada/FusionForm/some third party plugin specific - which I have no knowledge of and is out of scope for this site. But you should try contacting them and ask how to verify it, something along the lines of: ``` add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', [ 'methods' => [\Requests::POST], 'callback' => 'my_awesome_func', 'permission_callback' => function () { return magic_validate_my_nonce_please(); }, ]); }); ``` or with the [fancy arrow function added in PHP 7.4](https://stitcher.io/blog/short-closures-in-php): ``` add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', [ 'methods' => [\Requests::POST], 'callback' => 'my_awesome_func', 'permission_callback' => fn () => magic_validate_my_nonce_please(), ]); }); ```
401,617
<p>I'm not exactly sure how to explain this, but I have a slider I built using ACF that I placed on my home page. After this code, I want to use a WP block I built, and after that I want to put another slider. So it would look like this:</p> <pre><code> &lt;div class=&quot;col-lg-9 col-sm-12&quot;&gt; &lt;div class=&quot;row slide-area&quot;&gt; &lt;!-- // * Slider starts --&gt; &lt;section class=&quot;slider_container_top_main&quot;&gt; &lt;!-- all slides container starts --&gt; &lt;ul class=&quot;slider_container_top&quot;&gt; &lt;?php // get slider data if (have_rows('slider')) : while (have_rows('slider')) : the_row(); $slider_image = get_sub_field('slider_image'); $slider_headline = get_sub_field('slider_headline'); ?&gt; &lt;!-- slide starts --&gt; &lt;li&gt; &lt;div class=&quot;slider_container_top_img_container&quot;&gt; &lt;img src=&quot;&lt;?php echo $slider_image['url'] ?&gt;&quot; alt=&quot;slider image&quot; class=&quot;slider_container_top_img&quot; loading=&quot;lazy&quot;&gt; &lt;div class=&quot;row align-items-center justify-content-center top-navigation-div&quot;&gt; &lt;div class=&quot;col-lg-9 offset-lg-3 col-sm-12 col-12 black-s top-navigation-controls&quot;&gt;&lt;?php echo $slider_headline; ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;!-- slide ends --&gt; &lt;?php endwhile; endif; ?&gt; &lt;/ul&gt; &lt;!-- all slides container ends --&gt; &lt;/section&gt; &lt;!-- // * Slider ends --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ** WP block would go here ** // And here's another slider &lt;div class=&quot;col-lg-9 col-sm-12&quot;&gt; &lt;div class=&quot;row slide-area&quot;&gt; &lt;!-- // * Slider starts --&gt; &lt;section class=&quot;slider_container_top_main&quot;&gt; &lt;!-- all slides container starts --&gt; &lt;ul class=&quot;slider_container_top&quot;&gt; &lt;?php // get slider data if (have_rows('slider')) : while (have_rows('slider')) : the_row(); $slider_image = get_sub_field('slider_image'); $slider_headline = get_sub_field('slider_headline'); ?&gt; &lt;!-- slide starts --&gt; &lt;li&gt; &lt;div class=&quot;slider_container_top_img_container&quot;&gt; &lt;img src=&quot;&lt;?php echo $slider_image['url'] ?&gt;&quot; alt=&quot;slider image&quot; class=&quot;slider_container_top_img&quot; loading=&quot;lazy&quot;&gt; &lt;div class=&quot;row align-items-center justify-content-center top-navigation-div&quot;&gt; &lt;div class=&quot;col-lg-9 offset-lg-3 col-sm-12 col-12 black-s top-navigation-controls&quot;&gt;&lt;?php echo $slider_headline; ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/li&gt; &lt;!-- slide ends --&gt; &lt;?php endwhile; endif; ?&gt; &lt;/ul&gt; &lt;!-- all slides container ends --&gt; &lt;/section&gt; &lt;!-- // * Slider ends --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Is there a way to do something like this? Put WP blocks between code in a template?</p>
[ { "answer_id": 401569, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>Welcome to WordPress and WPSE!</p>\n<p>Plugins are meant to alter or add functionality to what is already...
2022/01/21
[ "https://wordpress.stackexchange.com/questions/401617", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/208199/" ]
I'm not exactly sure how to explain this, but I have a slider I built using ACF that I placed on my home page. After this code, I want to use a WP block I built, and after that I want to put another slider. So it would look like this: ``` <div class="col-lg-9 col-sm-12"> <div class="row slide-area"> <!-- // * Slider starts --> <section class="slider_container_top_main"> <!-- all slides container starts --> <ul class="slider_container_top"> <?php // get slider data if (have_rows('slider')) : while (have_rows('slider')) : the_row(); $slider_image = get_sub_field('slider_image'); $slider_headline = get_sub_field('slider_headline'); ?> <!-- slide starts --> <li> <div class="slider_container_top_img_container"> <img src="<?php echo $slider_image['url'] ?>" alt="slider image" class="slider_container_top_img" loading="lazy"> <div class="row align-items-center justify-content-center top-navigation-div"> <div class="col-lg-9 offset-lg-3 col-sm-12 col-12 black-s top-navigation-controls"><?php echo $slider_headline; ?></div> </div> </div> </li> <!-- slide ends --> <?php endwhile; endif; ?> </ul> <!-- all slides container ends --> </section> <!-- // * Slider ends --> </div> </div> </div> ** WP block would go here ** // And here's another slider <div class="col-lg-9 col-sm-12"> <div class="row slide-area"> <!-- // * Slider starts --> <section class="slider_container_top_main"> <!-- all slides container starts --> <ul class="slider_container_top"> <?php // get slider data if (have_rows('slider')) : while (have_rows('slider')) : the_row(); $slider_image = get_sub_field('slider_image'); $slider_headline = get_sub_field('slider_headline'); ?> <!-- slide starts --> <li> <div class="slider_container_top_img_container"> <img src="<?php echo $slider_image['url'] ?>" alt="slider image" class="slider_container_top_img" loading="lazy"> <div class="row align-items-center justify-content-center top-navigation-div"> <div class="col-lg-9 offset-lg-3 col-sm-12 col-12 black-s top-navigation-controls"><?php echo $slider_headline; ?></div> </div> </div> </li> <!-- slide ends --> <?php endwhile; endif; ?> </ul> <!-- all slides container ends --> </section> <!-- // * Slider ends --> </div> </div> </div> ``` Is there a way to do something like this? Put WP blocks between code in a template?
Generally you do not want to access your PHP files directly within WordPress because you lose a lot of "juice", meaning all WP functionality would have to be re-imported (and might break). WP is setup in a way that all requests to the CMS get routed to *index.php* and some mechanisms then decide what to do with the request. From what you write, it sounds like a [custom REST endpoint](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/) might serve you well. Expanding your code to the following should already show some results: ``` add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', [ 'methods' => [\Requests::POST], 'callback' => 'my_awesome_func', ]); }); function my_awesome_func() { if (!isset($returnVal)) $returnVal = new stdClass(); $returnVal->status = "success"; $returnVal->info = "seems to work"; return $returnVal; } ``` (using [short array syntax](https://befused.com/php/short-array/) and) changed ``` 'methods' => 'GET', ``` to ``` 'methods' => [\Requests::POST], ``` which references the [Requests' class const](https://developer.wordpress.org/reference/classes/requests/) (my preferred style - you can also use `'POST'` directly). Most likely you want to do something with the form data, so change your `my_awesome_func()` to something like this ``` function my_awesome_func(\WP_REST_Request $request) { if ($request->get_param('main_license_number') !== 'something') { return new WP_Error('Invalid license number!'); } return [ 'status' => 'success', 'info' => 'hello', ]; } ``` Now there is only one problem left: everybody can call this endpoint, they don't have to come through the form. Your request contains a `fusion-form-nonce-1808` and I assume this can be used to verify that it was indeed submitted from the form - but seems very Avada/FusionForm/some third party plugin specific - which I have no knowledge of and is out of scope for this site. But you should try contacting them and ask how to verify it, something along the lines of: ``` add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', [ 'methods' => [\Requests::POST], 'callback' => 'my_awesome_func', 'permission_callback' => function () { return magic_validate_my_nonce_please(); }, ]); }); ``` or with the [fancy arrow function added in PHP 7.4](https://stitcher.io/blog/short-closures-in-php): ``` add_action('rest_api_init', function () { register_rest_route('my-plugin/v1', '/my-page', [ 'methods' => [\Requests::POST], 'callback' => 'my_awesome_func', 'permission_callback' => fn () => magic_validate_my_nonce_please(), ]); }); ```
401,620
<p>I have a function that expires posts after a certain amount of time. It also sets a custom post status of <code>'expired'</code>. I would like it to function like a <code>'draft'</code> post in that the URL is no longer accessible to the public. At the moment, once the post is set to <code>'expired'</code>, the full permalink is still visible. Here is my code:</p> <pre><code>function hrl_custom_status_creation(){ register_post_status( 'expired', array( 'label' =&gt; _x( 'Expired', 'post_type_listings' ), 'label_count' =&gt; _n_noop( 'Expired &lt;span class=&quot;count&quot;&gt;(%s)&lt;/span&gt;', 'Expired &lt;span class=&quot;count&quot;&gt;(%s)&lt;/span&gt;'), 'public' =&gt; true, 'exclude_from_search' =&gt; false, 'show_in_admin_all_list' =&gt; true, 'show_in_admin_status_list' =&gt; true, 'protected' =&gt; true, '_builtin' =&gt; true )); } add_action( 'init', 'hrl_custom_status_creation' ); // change post status to 'expired' $postdata = array( 'ID' =&gt; $post_id, 'post_status' =&gt; 'expired', ); // Update post data wp_update_post($postdata); </code></pre>
[ { "answer_id": 401633, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": -1, "selected": false, "text": "<p>this function changes the post to draft, you only have to call it and pass the post id where you want...
2022/01/21
[ "https://wordpress.stackexchange.com/questions/401620", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57571/" ]
I have a function that expires posts after a certain amount of time. It also sets a custom post status of `'expired'`. I would like it to function like a `'draft'` post in that the URL is no longer accessible to the public. At the moment, once the post is set to `'expired'`, the full permalink is still visible. Here is my code: ``` function hrl_custom_status_creation(){ register_post_status( 'expired', array( 'label' => _x( 'Expired', 'post_type_listings' ), 'label_count' => _n_noop( 'Expired <span class="count">(%s)</span>', 'Expired <span class="count">(%s)</span>'), 'public' => true, 'exclude_from_search' => false, 'show_in_admin_all_list' => true, 'show_in_admin_status_list' => true, 'protected' => true, '_builtin' => true )); } add_action( 'init', 'hrl_custom_status_creation' ); // change post status to 'expired' $postdata = array( 'ID' => $post_id, 'post_status' => 'expired', ); // Update post data wp_update_post($postdata); ```
This line of code: `'public' => true,` change to `'public' => false,`
401,740
<p>TLDR: My custom post type items are sorting differently on a local environment and a live server. Can't figure out why!</p> <p>I have a local install (MAMP) and an online dev install (GoDaddy shared, for the client to view) of a site with pages of Custom Post Type posts. The CPT posts are real estate properties. The CPT posts have meta info added using Advanced Custom Fields. The ACF fields include the state each property is in and the type of property.</p> <p>Here is a relevant page <a href="http://sar2021.devrsandk.com/wisconsin/" rel="nofollow noreferrer">CPT page for Wisconsin posts</a></p> <p>The CPT posts are divided into three pages by state. Within each state page, the properties are sorted by type of property. That is it - they are sorted into their states and then sorted by type of property.</p> <p>I used a WP_query to do this for each page. Here is the query for the Wisconsin page:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php $args = array( 'post_type' =&gt; 'properties', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'meta_query' =&gt; array( 'state_clause' =&gt; array( 'key' =&gt; 'state', 'value' =&gt; 'WI' ), 'prop_type' =&gt; array( 'key' =&gt; 'property_type' ), ), 'orderby' =&gt; array( 'prop_type' =&gt; 'ASC' ) ); $wiQuery = new WP_Query($args); ?&gt; &lt;?php if( $wiQuery-&gt;have_posts() ) { while ($wiQuery-&gt;have_posts()) : $wiQuery-&gt;the_post(); </code></pre> <p>The sort is working fine for the state pages. In other words, all the Wisconsin properties appear on the right page, and they are grouped property in order of the ACF meta field for Property Type.</p> <p>However, within those groups the properties appear in a different order on the local MAMP site than they do on the dev install. For example, on the local install, 1501 Paramount Drive appears before 1209 Deming Way. Which seems really odd to me!</p> <p>The dev site and the local site are both the same version of WordPress and the exact same custom theme I’m working on. They are using the same version of ACF. 95% of the posts were added to the local site before it was uploaded to the dev location.</p> <p>Could it be differences with PHP versions (seems unlikely) or something about the mysql version?</p> <p>The Properties custom post type itself has a weird origin. A developer set it up many years ago using the Easy Custom Post Type plugin, which no longer works. I deactivated that plugin and added the CPT to the functions file and I was able to use all the properties that were added with ECPT. I just had to redo all the meta data.</p> <p>This is not an urgent issue, it’s just baffling. If anyone has any ideas of why the sort would be different on different servers I’d be grateful to hear them.</p>
[ { "answer_id": 401745, "author": "joshmoto", "author_id": 111152, "author_profile": "https://wordpress.stackexchange.com/users/111152", "pm_score": 1, "selected": false, "text": "<p>A php issue retuning different results on 2 or more synced environments (if each env db data is the same a...
2022/01/25
[ "https://wordpress.stackexchange.com/questions/401740", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80029/" ]
TLDR: My custom post type items are sorting differently on a local environment and a live server. Can't figure out why! I have a local install (MAMP) and an online dev install (GoDaddy shared, for the client to view) of a site with pages of Custom Post Type posts. The CPT posts are real estate properties. The CPT posts have meta info added using Advanced Custom Fields. The ACF fields include the state each property is in and the type of property. Here is a relevant page [CPT page for Wisconsin posts](http://sar2021.devrsandk.com/wisconsin/) The CPT posts are divided into three pages by state. Within each state page, the properties are sorted by type of property. That is it - they are sorted into their states and then sorted by type of property. I used a WP\_query to do this for each page. Here is the query for the Wisconsin page: ```php <?php $args = array( 'post_type' => 'properties', 'post_status' => 'publish', 'posts_per_page' => -1, 'meta_query' => array( 'state_clause' => array( 'key' => 'state', 'value' => 'WI' ), 'prop_type' => array( 'key' => 'property_type' ), ), 'orderby' => array( 'prop_type' => 'ASC' ) ); $wiQuery = new WP_Query($args); ?> <?php if( $wiQuery->have_posts() ) { while ($wiQuery->have_posts()) : $wiQuery->the_post(); ``` The sort is working fine for the state pages. In other words, all the Wisconsin properties appear on the right page, and they are grouped property in order of the ACF meta field for Property Type. However, within those groups the properties appear in a different order on the local MAMP site than they do on the dev install. For example, on the local install, 1501 Paramount Drive appears before 1209 Deming Way. Which seems really odd to me! The dev site and the local site are both the same version of WordPress and the exact same custom theme I’m working on. They are using the same version of ACF. 95% of the posts were added to the local site before it was uploaded to the dev location. Could it be differences with PHP versions (seems unlikely) or something about the mysql version? The Properties custom post type itself has a weird origin. A developer set it up many years ago using the Easy Custom Post Type plugin, which no longer works. I deactivated that plugin and added the CPT to the functions file and I was able to use all the properties that were added with ECPT. I just had to redo all the meta data. This is not an urgent issue, it’s just baffling. If anyone has any ideas of why the sort would be different on different servers I’d be grateful to hear them.
A php issue retuning different results on 2 or more synced environments (if each env db data is the same and any passed data is the same)... that could be tricky. The only other thing I noticed is your `meta_query` arg does not contain a child array containing `state_clause` and `prop_type`. Your code is... ```php 'meta_query' => array( 'state_clause' => array( 'key' => 'state', 'value' => 'WI' ), 'prop_type' => array( 'key' => 'property_type' ) ), ``` You might need to wrap both inner `meta_query` args arrays into another array, see example below... *...and possibly you may need to include a `relation` argument/key... see the end of the [orderby WP\_Query](https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters) docs* ```php 'meta_query' => array( array( 'state_clause' => array( 'key' => 'state', 'value' => 'WI' ), 'prop_type' => array( 'key' => 'property_type' ) ) ), ```
401,781
<p>I've created a custom shortcode to add pop-up definitions to selected vocabulary terms. The shortcode looks like this:</p> <pre><code>[glossary term=&quot;data breach&quot;]data breaches[/glossary] </code></pre> <p>The function searches posts in a custom post type called 'glossary-term' for the term's definition, prints it in a div, and turns the enclosed text into a link to that div:</p> <pre><code>function glossary_shortcode( $atts = array(), $shortcode_content = null ) { // parameters extract(shortcode_atts(array( 'term' =&gt; null ), $atts)); $glossary_term_object = get_page_by_title($term, 'OBJECT', 'glossary-term'); // print definition in popup div echo '&lt;div id=&quot;glossary-popup-' . $glossary_term_object-&gt;post_name . '&quot; class=&quot;glossary_popup&quot;&gt;&lt;h4&gt;' . $glossary_term_object-&gt;post_title . '&lt;/h4&gt;' . wpautop( $glossary_term_object-&gt;post_content ) . '&lt;div class=&quot;ctas&quot;&gt;&lt;a href=&quot;&quot;&gt;Visit Glossary&lt;/a&gt;&lt;a href=&quot;#&quot;&gt;Close&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;'; // return link to definition popup return '&lt;a href=&quot;#glossary-popup-' . $glossary_term_object-&gt;post_name . '&quot;&gt;' . $shortcode_content . '&lt;/a&gt;'; } add_shortcode('glossary', 'glossary_shortcode'); </code></pre> <p>Rather than echo the definition pop-up, I'd like to have all the definitions created by this shortcode (which may be used several times on a page) collected into their own div at the end of the main page content.</p> <p>Any ideas how to accomplish this?</p>
[ { "answer_id": 401745, "author": "joshmoto", "author_id": 111152, "author_profile": "https://wordpress.stackexchange.com/users/111152", "pm_score": 1, "selected": false, "text": "<p>A php issue retuning different results on 2 or more synced environments (if each env db data is the same a...
2022/01/25
[ "https://wordpress.stackexchange.com/questions/401781", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/218387/" ]
I've created a custom shortcode to add pop-up definitions to selected vocabulary terms. The shortcode looks like this: ``` [glossary term="data breach"]data breaches[/glossary] ``` The function searches posts in a custom post type called 'glossary-term' for the term's definition, prints it in a div, and turns the enclosed text into a link to that div: ``` function glossary_shortcode( $atts = array(), $shortcode_content = null ) { // parameters extract(shortcode_atts(array( 'term' => null ), $atts)); $glossary_term_object = get_page_by_title($term, 'OBJECT', 'glossary-term'); // print definition in popup div echo '<div id="glossary-popup-' . $glossary_term_object->post_name . '" class="glossary_popup"><h4>' . $glossary_term_object->post_title . '</h4>' . wpautop( $glossary_term_object->post_content ) . '<div class="ctas"><a href="">Visit Glossary</a><a href="#">Close</a></div></div>'; // return link to definition popup return '<a href="#glossary-popup-' . $glossary_term_object->post_name . '">' . $shortcode_content . '</a>'; } add_shortcode('glossary', 'glossary_shortcode'); ``` Rather than echo the definition pop-up, I'd like to have all the definitions created by this shortcode (which may be used several times on a page) collected into their own div at the end of the main page content. Any ideas how to accomplish this?
A php issue retuning different results on 2 or more synced environments (if each env db data is the same and any passed data is the same)... that could be tricky. The only other thing I noticed is your `meta_query` arg does not contain a child array containing `state_clause` and `prop_type`. Your code is... ```php 'meta_query' => array( 'state_clause' => array( 'key' => 'state', 'value' => 'WI' ), 'prop_type' => array( 'key' => 'property_type' ) ), ``` You might need to wrap both inner `meta_query` args arrays into another array, see example below... *...and possibly you may need to include a `relation` argument/key... see the end of the [orderby WP\_Query](https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters) docs* ```php 'meta_query' => array( array( 'state_clause' => array( 'key' => 'state', 'value' => 'WI' ), 'prop_type' => array( 'key' => 'property_type' ) ) ), ```
401,785
<p>I'm looking for a way on how to display only a few posts on a first page of my archive. This is my archive template — <code>page-archive.php</code>, which I am using as a template to display all my posts/recipes:</p> <pre><code>&lt;?php get_header('archive'); ?&gt; &lt;div id=&quot;primary&quot; class=&quot;content-area blog-archive col-md-9&quot;&gt; &lt;main id=&quot;main&quot; class=&quot;site-main&quot;&gt; &lt;div class=&quot;breadcrumbs-block&quot;&gt;&lt;?php if ( function_exists('yoast_breadcrumb') ) { yoast_breadcrumb( '&lt;p id=&quot;breadcrumbs&quot;&gt;','&lt;/p&gt;' ); } ?&gt; &lt;/div&gt; &lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=24&amp;paged='. get_query_var('paged')); ?&gt; &lt;?php if( have_posts() ): ?&gt; &lt;div class=&quot;row all-recipes-block&quot;&gt; &lt;?php while( have_posts() ): the_post(); ?&gt; &lt;article id=&quot;post-&lt;?php the_ID(); ?&gt;&quot; &lt;?php post_class('col-md-4'); ?&gt;&gt; &lt;?php if ( has_post_thumbnail() ) : ?&gt; &lt;a class=&quot;post-teaser&quot; href=&quot;&lt;?php the_permalink() ?&gt;&quot; title=&quot;&lt;?php the_title(); ?&gt;&quot;&gt; &lt;div class=&quot;thumbnail-block&quot;&gt;&lt;?php the_post_thumbnail('regular-post-thumbnail'); ?&gt;&lt;/div&gt; &lt;div class=&quot;title-block&quot;&gt;&lt;span class=&quot;h3 title-for-widget&quot;&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;/div&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;/article&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; &lt;div class=&quot;pagination-block row&quot;&gt; &lt;?php numeric_posts_nav(); ?&gt; &lt;/div&gt; &lt;?php else: ?&gt; &lt;div id=&quot;post-404&quot; class=&quot;noposts&quot;&gt; &lt;p&gt;&lt;?php _e('None found.','example'); ?&gt;&lt;/p&gt; &lt;/div&gt;&lt;!-- /#post-404 --&gt; &lt;?php endif; wp_reset_query(); ?&gt; &lt;/main&gt; &lt;/div&gt; &lt;?php get_footer(); </code></pre> <p>Currently I have 24 posts per page and pagination, and I would love to show only 12 posts on the first page!</p> <p>This is my post navigation function:</p> <pre class="lang-php prettyprint-override"><code>// numeric posts navigation function numeric_posts_nav() { if( is_singular() ) return; global $wp_query; /** Stop execution if there's only 1 page */ if( $wp_query-&gt;max_num_pages &lt;= 1 ) return; $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1; $max = intval( $wp_query-&gt;max_num_pages ); /** Add current page to the array */ if ( $paged &gt;= 1 ) $links[] = $paged; /** Add the pages around the current page to the array */ if ( $paged &gt;= 3 ) { $links[] = $paged - 1; $links[] = $paged - 2; } if ( ( $paged + 2 ) &lt;= $max ) { $links[] = $paged + 2; $links[] = $paged + 1; } echo '&lt;div class=&quot;pagination-navigation col-md-12&quot;&gt;&lt;ul class=&quot;d-flex justify-content-center&quot;&gt;' . &quot;\n&quot;; </code></pre> <p>Please help!</p> <p>Thank you in advance!</p>
[ { "answer_id": 401789, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": 0, "selected": false, "text": "<p>let's say you want to keep your html, its possible to put this in the function and save this function ...
2022/01/25
[ "https://wordpress.stackexchange.com/questions/401785", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76850/" ]
I'm looking for a way on how to display only a few posts on a first page of my archive. This is my archive template — `page-archive.php`, which I am using as a template to display all my posts/recipes: ``` <?php get_header('archive'); ?> <div id="primary" class="content-area blog-archive col-md-9"> <main id="main" class="site-main"> <div class="breadcrumbs-block"><?php if ( function_exists('yoast_breadcrumb') ) { yoast_breadcrumb( '<p id="breadcrumbs">','</p>' ); } ?> </div> <?php query_posts('post_type=post&post_status=publish&posts_per_page=24&paged='. get_query_var('paged')); ?> <?php if( have_posts() ): ?> <div class="row all-recipes-block"> <?php while( have_posts() ): the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class('col-md-4'); ?>> <?php if ( has_post_thumbnail() ) : ?> <a class="post-teaser" href="<?php the_permalink() ?>" title="<?php the_title(); ?>"> <div class="thumbnail-block"><?php the_post_thumbnail('regular-post-thumbnail'); ?></div> <div class="title-block"><span class="h3 title-for-widget"><?php the_title(); ?></span></div> </a> <?php endif; ?> </article> <?php endwhile; ?> </div> <div class="pagination-block row"> <?php numeric_posts_nav(); ?> </div> <?php else: ?> <div id="post-404" class="noposts"> <p><?php _e('None found.','example'); ?></p> </div><!-- /#post-404 --> <?php endif; wp_reset_query(); ?> </main> </div> <?php get_footer(); ``` Currently I have 24 posts per page and pagination, and I would love to show only 12 posts on the first page! This is my post navigation function: ```php // numeric posts navigation function numeric_posts_nav() { if( is_singular() ) return; global $wp_query; /** Stop execution if there's only 1 page */ if( $wp_query->max_num_pages <= 1 ) return; $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1; $max = intval( $wp_query->max_num_pages ); /** Add current page to the array */ if ( $paged >= 1 ) $links[] = $paged; /** Add the pages around the current page to the array */ if ( $paged >= 3 ) { $links[] = $paged - 1; $links[] = $paged - 2; } if ( ( $paged + 2 ) <= $max ) { $links[] = $paged + 2; $links[] = $paged + 1; } echo '<div class="pagination-navigation col-md-12"><ul class="d-flex justify-content-center">' . "\n"; ``` Please help! Thank you in advance!
> > This is my archive template — `page-archive.php`, which I am using as > a template to display all my posts/recipes > > > So if you're using a [Page (post of the `page` type)](https://wordpress.org/support/article/pages-screen/) with a custom/specific [Page Template](https://developer.wordpress.org/themes/template-files-section/page-template-files/), then you should [create a *secondary query and loop*](https://developer.wordpress.org/themes/basics/the-loop/#creating-secondary-queries-and-loops) for retrieving and displaying your recipes/posts. But even with a default archive template such as the `archive.php` file, you should ***not*** use `query_posts()` in the template! And here's why: (bold and italic formatting was added by me) > > This function will **completely override the main query and isn’t > intended for use by plugins or themes**. Its overly-simplistic > approach to modifying the main query can be problematic and should be > avoided wherever possible. In most cases, there are *better, more > performant options* for modifying the main query such as via the > [‘pre\_get\_posts’](https://developer.wordpress.org/reference/hooks/pre_get_posts/) > action within > [WP\_Query](https://developer.wordpress.org/reference/classes/wp_query/). > > > > > It should be noted that using this to replace the main query on a page > can increase page loading times, in worst case scenarios more than > doubling the amount of work needed or more. While easy to use, the > function is also prone to confusion and problems later on. See the > note further below on caveats for details. > > > — See <https://developer.wordpress.org/reference/functions/query_posts/> for the caveats mentioned above and other details. And here's how can you convert your `query_posts()` code to using a secondary query/`WP_Query` and loop instead: 1. Replace the `<?php query_posts('post_type=post&post_status=publish&posts_per_page=24&paged='. get_query_var('paged')); ?>` with this: ```php <?php // you could also do $query = new WP_Query( 'your args here' ), but I thought // using array is better or more readable :) $query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 24, 'paged' => get_query_var( 'paged' ), ) ); ?> ``` 2. Replace the `have_posts()` with `$query->have_posts()`, **and** the `the_post()` with `$query->the_post()`. I.e. Use the `$query` variable created above. 3. And finally, replace the `wp_reset_query()` with `wp_reset_postdata()`. **Now, as for displaying only a few posts on the first page, i.e. different than your `posts_per_page` value..** The proper solution would be to **use an `offset`**, like so: 1. Replace the snippet in step 1 above with this, or use this instead of that snippet: ```php <?php // Define the number of posts per page. $per_page = 12; // for the 1st page $per_page2 = 24; // for page 2, 3, etc. // Get the current page number. $paged = max( 1, get_query_var( 'paged' ) ); // This is used as the posts_per_page value. $per_page3 = ( $paged > 1 ) ? $per_page2 : $per_page; // Calculate the offset. $offset = ( $paged - 1 ) * $per_page2; $diff = $per_page2 - $per_page; $minus = ( $paged > 1 ) ? $diff : 0; $query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => $per_page3, 'offset' => $offset - $minus, ) ); // Recalculate the total number of pages. $query->max_num_pages = ceil( ( $query->found_posts + $diff ) / max( $per_page, $per_page2 ) ); ?> ``` 2. Replace the `<?php numeric_posts_nav(); ?>` with `<?php numeric_posts_nav( $query ); ?>`. 3. Edit your *pagination function* — replace this part (which is lines 775 - 787 [here](https://pastebin.com/jQA3cgCx)): ```php function numeric_posts_nav() { if( is_singular() ) return; global $wp_query; /** Stop execution if there's only 1 page */ if( $wp_query->max_num_pages <= 1 ) return; $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1; $max = intval( $wp_query->max_num_pages ); ``` with this: ```php function numeric_posts_nav( WP_Query $query = null ) { global $wp_query; if ( ! $query ) { $query =& $wp_query; } if( $query->is_singular() || $query->max_num_pages <= 1 ) { return; } $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1; $max = intval( $query->max_num_pages ); ``` That's all and now check if it works for you! :)
401,909
<p>I was trying to translate some plugin when I see in their .po file there are two &quot;Sign in&quot;s. I believe Wordpress uses <code>__</code> to parse text that needs to be translated.</p> <p>So when codes like</p> <pre><code>__('Sign in', 'buddyboss-theme') </code></pre> <p>is executed, how does it know which &quot;Sign in&quot; entry in the .po file is the one to look for?</p>
[ { "answer_id": 401789, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": 0, "selected": false, "text": "<p>let's say you want to keep your html, its possible to put this in the function and save this function ...
2022/01/28
[ "https://wordpress.stackexchange.com/questions/401909", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125207/" ]
I was trying to translate some plugin when I see in their .po file there are two "Sign in"s. I believe Wordpress uses `__` to parse text that needs to be translated. So when codes like ``` __('Sign in', 'buddyboss-theme') ``` is executed, how does it know which "Sign in" entry in the .po file is the one to look for?
> > This is my archive template — `page-archive.php`, which I am using as > a template to display all my posts/recipes > > > So if you're using a [Page (post of the `page` type)](https://wordpress.org/support/article/pages-screen/) with a custom/specific [Page Template](https://developer.wordpress.org/themes/template-files-section/page-template-files/), then you should [create a *secondary query and loop*](https://developer.wordpress.org/themes/basics/the-loop/#creating-secondary-queries-and-loops) for retrieving and displaying your recipes/posts. But even with a default archive template such as the `archive.php` file, you should ***not*** use `query_posts()` in the template! And here's why: (bold and italic formatting was added by me) > > This function will **completely override the main query and isn’t > intended for use by plugins or themes**. Its overly-simplistic > approach to modifying the main query can be problematic and should be > avoided wherever possible. In most cases, there are *better, more > performant options* for modifying the main query such as via the > [‘pre\_get\_posts’](https://developer.wordpress.org/reference/hooks/pre_get_posts/) > action within > [WP\_Query](https://developer.wordpress.org/reference/classes/wp_query/). > > > > > It should be noted that using this to replace the main query on a page > can increase page loading times, in worst case scenarios more than > doubling the amount of work needed or more. While easy to use, the > function is also prone to confusion and problems later on. See the > note further below on caveats for details. > > > — See <https://developer.wordpress.org/reference/functions/query_posts/> for the caveats mentioned above and other details. And here's how can you convert your `query_posts()` code to using a secondary query/`WP_Query` and loop instead: 1. Replace the `<?php query_posts('post_type=post&post_status=publish&posts_per_page=24&paged='. get_query_var('paged')); ?>` with this: ```php <?php // you could also do $query = new WP_Query( 'your args here' ), but I thought // using array is better or more readable :) $query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 24, 'paged' => get_query_var( 'paged' ), ) ); ?> ``` 2. Replace the `have_posts()` with `$query->have_posts()`, **and** the `the_post()` with `$query->the_post()`. I.e. Use the `$query` variable created above. 3. And finally, replace the `wp_reset_query()` with `wp_reset_postdata()`. **Now, as for displaying only a few posts on the first page, i.e. different than your `posts_per_page` value..** The proper solution would be to **use an `offset`**, like so: 1. Replace the snippet in step 1 above with this, or use this instead of that snippet: ```php <?php // Define the number of posts per page. $per_page = 12; // for the 1st page $per_page2 = 24; // for page 2, 3, etc. // Get the current page number. $paged = max( 1, get_query_var( 'paged' ) ); // This is used as the posts_per_page value. $per_page3 = ( $paged > 1 ) ? $per_page2 : $per_page; // Calculate the offset. $offset = ( $paged - 1 ) * $per_page2; $diff = $per_page2 - $per_page; $minus = ( $paged > 1 ) ? $diff : 0; $query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => $per_page3, 'offset' => $offset - $minus, ) ); // Recalculate the total number of pages. $query->max_num_pages = ceil( ( $query->found_posts + $diff ) / max( $per_page, $per_page2 ) ); ?> ``` 2. Replace the `<?php numeric_posts_nav(); ?>` with `<?php numeric_posts_nav( $query ); ?>`. 3. Edit your *pagination function* — replace this part (which is lines 775 - 787 [here](https://pastebin.com/jQA3cgCx)): ```php function numeric_posts_nav() { if( is_singular() ) return; global $wp_query; /** Stop execution if there's only 1 page */ if( $wp_query->max_num_pages <= 1 ) return; $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1; $max = intval( $wp_query->max_num_pages ); ``` with this: ```php function numeric_posts_nav( WP_Query $query = null ) { global $wp_query; if ( ! $query ) { $query =& $wp_query; } if( $query->is_singular() || $query->max_num_pages <= 1 ) { return; } $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1; $max = intval( $query->max_num_pages ); ``` That's all and now check if it works for you! :)
401,984
<p>I'm working on a plugin with a custom post type called &quot;important_dates&quot;</p> <p>I want to delete the Wordpress admin notification when a new custom post is created.</p> <p>Here is my code - it deletes the notifications for all post types. How do I make it work for only my &quot;important_dates&quot; custom post type?</p> <pre><code>add_filter( 'post_updated_messages', 'post_published' ); function post_published( $messages ) { unset($messages['posts'][6]); return $messages; } } </code></pre>
[ { "answer_id": 401789, "author": "tiago calado", "author_id": 198152, "author_profile": "https://wordpress.stackexchange.com/users/198152", "pm_score": 0, "selected": false, "text": "<p>let's say you want to keep your html, its possible to put this in the function and save this function ...
2022/01/29
[ "https://wordpress.stackexchange.com/questions/401984", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/189596/" ]
I'm working on a plugin with a custom post type called "important\_dates" I want to delete the Wordpress admin notification when a new custom post is created. Here is my code - it deletes the notifications for all post types. How do I make it work for only my "important\_dates" custom post type? ``` add_filter( 'post_updated_messages', 'post_published' ); function post_published( $messages ) { unset($messages['posts'][6]); return $messages; } } ```
> > This is my archive template — `page-archive.php`, which I am using as > a template to display all my posts/recipes > > > So if you're using a [Page (post of the `page` type)](https://wordpress.org/support/article/pages-screen/) with a custom/specific [Page Template](https://developer.wordpress.org/themes/template-files-section/page-template-files/), then you should [create a *secondary query and loop*](https://developer.wordpress.org/themes/basics/the-loop/#creating-secondary-queries-and-loops) for retrieving and displaying your recipes/posts. But even with a default archive template such as the `archive.php` file, you should ***not*** use `query_posts()` in the template! And here's why: (bold and italic formatting was added by me) > > This function will **completely override the main query and isn’t > intended for use by plugins or themes**. Its overly-simplistic > approach to modifying the main query can be problematic and should be > avoided wherever possible. In most cases, there are *better, more > performant options* for modifying the main query such as via the > [‘pre\_get\_posts’](https://developer.wordpress.org/reference/hooks/pre_get_posts/) > action within > [WP\_Query](https://developer.wordpress.org/reference/classes/wp_query/). > > > > > It should be noted that using this to replace the main query on a page > can increase page loading times, in worst case scenarios more than > doubling the amount of work needed or more. While easy to use, the > function is also prone to confusion and problems later on. See the > note further below on caveats for details. > > > — See <https://developer.wordpress.org/reference/functions/query_posts/> for the caveats mentioned above and other details. And here's how can you convert your `query_posts()` code to using a secondary query/`WP_Query` and loop instead: 1. Replace the `<?php query_posts('post_type=post&post_status=publish&posts_per_page=24&paged='. get_query_var('paged')); ?>` with this: ```php <?php // you could also do $query = new WP_Query( 'your args here' ), but I thought // using array is better or more readable :) $query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 24, 'paged' => get_query_var( 'paged' ), ) ); ?> ``` 2. Replace the `have_posts()` with `$query->have_posts()`, **and** the `the_post()` with `$query->the_post()`. I.e. Use the `$query` variable created above. 3. And finally, replace the `wp_reset_query()` with `wp_reset_postdata()`. **Now, as for displaying only a few posts on the first page, i.e. different than your `posts_per_page` value..** The proper solution would be to **use an `offset`**, like so: 1. Replace the snippet in step 1 above with this, or use this instead of that snippet: ```php <?php // Define the number of posts per page. $per_page = 12; // for the 1st page $per_page2 = 24; // for page 2, 3, etc. // Get the current page number. $paged = max( 1, get_query_var( 'paged' ) ); // This is used as the posts_per_page value. $per_page3 = ( $paged > 1 ) ? $per_page2 : $per_page; // Calculate the offset. $offset = ( $paged - 1 ) * $per_page2; $diff = $per_page2 - $per_page; $minus = ( $paged > 1 ) ? $diff : 0; $query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => $per_page3, 'offset' => $offset - $minus, ) ); // Recalculate the total number of pages. $query->max_num_pages = ceil( ( $query->found_posts + $diff ) / max( $per_page, $per_page2 ) ); ?> ``` 2. Replace the `<?php numeric_posts_nav(); ?>` with `<?php numeric_posts_nav( $query ); ?>`. 3. Edit your *pagination function* — replace this part (which is lines 775 - 787 [here](https://pastebin.com/jQA3cgCx)): ```php function numeric_posts_nav() { if( is_singular() ) return; global $wp_query; /** Stop execution if there's only 1 page */ if( $wp_query->max_num_pages <= 1 ) return; $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1; $max = intval( $wp_query->max_num_pages ); ``` with this: ```php function numeric_posts_nav( WP_Query $query = null ) { global $wp_query; if ( ! $query ) { $query =& $wp_query; } if( $query->is_singular() || $query->max_num_pages <= 1 ) { return; } $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1; $max = intval( $query->max_num_pages ); ``` That's all and now check if it works for you! :)
401,995
<p>By constant options I mean properties of the theme that don't change during every day use in production, but are changeable by the developer primarily for reusability purposes. Things like custom posts, sidebars, forms, custom features, etc.</p> <p>There's really two ways that I see as viable and both of them are used in WordPress core and base themes. Edit: added a third way</p> <h4>Arguments inside functions</h4> <p>This is the way that I've been using for custom posts and such, and also the method WordPress uses for defining defaults for functions that take arguments, like <code>wp_login_form()</code> or <code>wp_nav_menu()</code>. It's either a variable defined inside the function being hooked or the values defined right inside the function call.</p> <pre class="lang-php prettyprint-override"><code>add_action( 'init', 'register_my_post_type' ); function register_my_post_type() { $labels = array( 'name' =&gt; __( 'my_post_type' ), 'singular_name' =&gt; __( 'My Post Type' ), ... ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, ... ); register_post_type( 'my_post_type', $args ); } </code></pre> <h4>Globals</h4> <p>The <code>register_{anything}</code> works by adding an instance to the global scope. For instance</p> <pre class="lang-php prettyprint-override"><code>function register_post_type( $post_type, $args = array() ) { global $wp_post_types; ... // validation $post_type_object = new WP_Post_Type( $post_type, $args ); ... $wp_post_types[ $post_type ] = $post_type_object; </code></pre> <h4>Constants</h4> <p>The most obvious example of this is the settings in <code>wp-config.php</code>. WordPress uses these for mostly small and really basic definitions, such as the database configuration credentials and things like<br /> <code>define( 'ABSPATH', __DIR__ . '/' );</code> or <code>define( 'WPINC', 'wp-includes' );</code>.</p> <p>PHP supports defining arrays as constants since 5.6, so it could be possible to define these arguments. I think it would be nice if many of these options could be set in a separate file for simplicity.</p> <p>Other methods, such as static variables or singleton classes seem inefficient, so they're off the table, but I'm not sure about constants.</p> <p>So, would using constants like</p> <pre class="lang-php prettyprint-override"><code>define( 'MY_OPTION1', array( 'key' =&gt; 'value' ... )); </code></pre> <p>then using them like</p> <pre class="lang-php prettyprint-override"><code>add_action('init', 'my_function'); function my_function() { some_function_that_takes_args( MY_OPTION1 ); ... } </code></pre> <p>be a bad idea? If yes, what is the correct/better way?</p> <p>I have an impression that using constants might be a bad idea, though I'm not sure why or how bad. So what are some considerations in performance, usability, anomalies or other coding principles to consider?</p>
[ { "answer_id": 401999, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>You should look at wordpress options page:</p>\n<p><a href=\"https://codex.wordpress.org/Creating_Options_Page...
2022/01/30
[ "https://wordpress.stackexchange.com/questions/401995", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/161042/" ]
By constant options I mean properties of the theme that don't change during every day use in production, but are changeable by the developer primarily for reusability purposes. Things like custom posts, sidebars, forms, custom features, etc. There's really two ways that I see as viable and both of them are used in WordPress core and base themes. Edit: added a third way #### Arguments inside functions This is the way that I've been using for custom posts and such, and also the method WordPress uses for defining defaults for functions that take arguments, like `wp_login_form()` or `wp_nav_menu()`. It's either a variable defined inside the function being hooked or the values defined right inside the function call. ```php add_action( 'init', 'register_my_post_type' ); function register_my_post_type() { $labels = array( 'name' => __( 'my_post_type' ), 'singular_name' => __( 'My Post Type' ), ... ); $args = array( 'labels' => $labels, 'public' => true, ... ); register_post_type( 'my_post_type', $args ); } ``` #### Globals The `register_{anything}` works by adding an instance to the global scope. For instance ```php function register_post_type( $post_type, $args = array() ) { global $wp_post_types; ... // validation $post_type_object = new WP_Post_Type( $post_type, $args ); ... $wp_post_types[ $post_type ] = $post_type_object; ``` #### Constants The most obvious example of this is the settings in `wp-config.php`. WordPress uses these for mostly small and really basic definitions, such as the database configuration credentials and things like `define( 'ABSPATH', __DIR__ . '/' );` or `define( 'WPINC', 'wp-includes' );`. PHP supports defining arrays as constants since 5.6, so it could be possible to define these arguments. I think it would be nice if many of these options could be set in a separate file for simplicity. Other methods, such as static variables or singleton classes seem inefficient, so they're off the table, but I'm not sure about constants. So, would using constants like ```php define( 'MY_OPTION1', array( 'key' => 'value' ... )); ``` then using them like ```php add_action('init', 'my_function'); function my_function() { some_function_that_takes_args( MY_OPTION1 ); ... } ``` be a bad idea? If yes, what is the correct/better way? I have an impression that using constants might be a bad idea, though I'm not sure why or how bad. So what are some considerations in performance, usability, anomalies or other coding principles to consider?
Generally you should try to keep the amount of global variables/constants to a minimum. The third (constant) option might be a good idea if you don't have too many options, but it can get messy with time as you add more and more options. What I usually do, is scope the constant to the corresponding classes as `const` or methods returning the settings values. For example, if I have a custom post type called Book, I would create a class that takes care of all the related functionality, such as registering the post type. Additionally all theme classes can be namespaced to avoid class name collisions, but I'll show the example without namespacing for simplicity: ```php class BookPost{ const POST_TYPE = 'book'; public static function register(){ register_post_type(self::POST_TYPE, array('labels' => self::get_labels())); } public static function get_labels(){ return array( 'name' => __('Book', 'MyTheme'), //... ); } } ``` Then you can call register from outside or inside of the class without worrying about the parameters, for example: ```php add_action( 'init', 'BookPost::register' ); ``` and if you need to access the post type (or other args) from anywhere else in the code, you can just use: ```php BookPost::POST_TYPE; BookPost::get_labels(); ``` There are a couple of things to mention here: 1. Since you can't use expressions (such as calling the `__()` method) in constants, you will have to use methods for retrieving the more dynamic values like label. 2. Here I'm using static methods because this particular example doesn't require storing state, and also it's easier to call the methods statically. But of course, based on your requirements you might prefer instantiating an object and using standard non-static methods. I'm not saying that this is the best approach, but this is what I usually do and it's been working well for me. The additional advantage is that you can add more helper methods to this class as your code grows and you won't need to worry about passing the post type, etc. For example, you can have something like: ```php BookPost::get_latest(); BookPost::get_all(); BookPost::get_by_genre(); ``` Also in terms of performance, registering a constant in a class vs using an array constant with options shouldn't make any meaningful difference in scenarios like this one.
402,011
<p>I am building a word-press website, and I have changed my domain name from <code>websiteold.com</code> to <code>websitenew.com</code>.</p> <p>The domain transfer was done by the web server host.</p> <p>However, I am not able to use the rest API since I changed to the new domain name. This is the error I am getting from postman.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;status&quot;: &quot;error&quot;, &quot;error&quot;: &quot;UNAUTHORIZED&quot;, &quot;error_description&quot;: &quot;Sorry, you are not allowed to access REST API.&quot; } </code></pre> <p>I have generated a new API key using the application passwords plugin, however whether I use the generated API key or a random/false API key, I get the same response.</p> <p>Any suggestions as to why this is happening. It might have to do with configurations being associated with old domain name. Please advise what to do.</p>
[ { "answer_id": 402202, "author": "Lovor", "author_id": 135704, "author_profile": "https://wordpress.stackexchange.com/users/135704", "pm_score": 0, "selected": false, "text": "<p>Did you change all strings in the WordPress database from old domain to new domain? You can use some plugins ...
2022/01/30
[ "https://wordpress.stackexchange.com/questions/402011", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/217604/" ]
I am building a word-press website, and I have changed my domain name from `websiteold.com` to `websitenew.com`. The domain transfer was done by the web server host. However, I am not able to use the rest API since I changed to the new domain name. This is the error I am getting from postman. ```json { "status": "error", "error": "UNAUTHORIZED", "error_description": "Sorry, you are not allowed to access REST API." } ``` I have generated a new API key using the application passwords plugin, however whether I use the generated API key or a random/false API key, I get the same response. Any suggestions as to why this is happening. It might have to do with configurations being associated with old domain name. Please advise what to do.
WordPress stores the domain of the installation in several places of the database. So you have to change them in numerous tables. In the case of working, look at the `options` table, entries `siteurl` and `homeurl`. It is also possible to set this via `wp-config.php`: ``` // Home URL of your WordPress. define( 'WP_SITEURL', 'https:/example.com' ); // URL to the WordPress root dir. define( 'WP_HOME', 'https://example.com' ); ``` Look also inside the `wp-config.php` for the domain, because it is possible to set this via constant. The `.htaccess`, if it is an Apache server, should also validate, because the Permalink rules need the domain, especially in the 'Multisite' mode. You should also active the [debug mode](https://codex.wordpress.org/WP_DEBUG), constant `WP_DEBUG` set to true in your `wp-config.php` to get more information about your installation, your problem. It should also help to find the issue with the REST API after domain change. If it works fine, check also the whole database for the old domain. Because WordPress stores in various tables. A change for them is possible via SQL statement or a plugin, like 'Serach Replace'. More notes for a changing of the URL are also inside the codex - <https://wordpress.org/support/article/changing-the-site-url/>
402,029
<p>I know I'm bad with coding, but I tried whatever I could find on the internet, and I ended up with this, which is not giving an error, but also when using the shortcode [my_playlist] in a post, only a part is showing &quot;Listen to the full score songs playlist frompostname&quot;</p> <p>Can you please tell me what am I doing wrong, how should I make the rest of the html after the_title(); display? thank you so much</p> <pre><code> // function that runs when shortcode is called function wpb_playlist_shortcode() { // Things that you want to do. $string .= '&lt;center&gt;' . _e(' Listen to the full score songs playlist from', 'wpml_theme') . '&lt;strong&gt;' . the_title(); ' &lt;/strong&gt; &lt;br/&gt; &lt;span class=&quot;playlist&quot;&gt;&lt;img class=&quot;middle&quot; src=&quot;https://example.com/images/play-this-song.png&quot; /&gt; YouTube&lt;/span&gt; &lt;br/&gt; &lt;span class=&quot;playlist2&quot;&gt;&lt;img class=&quot;middle&quot; src=&quot;https://exampl.com/images/play-this-song.png&quot; /&gt; Deezer&lt;/span&gt; &lt;br/&gt;&lt;span class=&quot;playlist3&quot;&gt;&lt;img class=&quot;middle&quot; src=&quot;https://exampl.com/images/play-this-song.png&quot; /&gt; Spotify&lt;/span&gt;&lt;/center&gt;'; // Output needs to be return return $string; } // Register shortcode add_shortcode('my_playlist', 'wpb_playlist_shortcode'); </code></pre>
[ { "answer_id": 402202, "author": "Lovor", "author_id": 135704, "author_profile": "https://wordpress.stackexchange.com/users/135704", "pm_score": 0, "selected": false, "text": "<p>Did you change all strings in the WordPress database from old domain to new domain? You can use some plugins ...
2022/01/30
[ "https://wordpress.stackexchange.com/questions/402029", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/6927/" ]
I know I'm bad with coding, but I tried whatever I could find on the internet, and I ended up with this, which is not giving an error, but also when using the shortcode [my\_playlist] in a post, only a part is showing "Listen to the full score songs playlist frompostname" Can you please tell me what am I doing wrong, how should I make the rest of the html after the\_title(); display? thank you so much ``` // function that runs when shortcode is called function wpb_playlist_shortcode() { // Things that you want to do. $string .= '<center>' . _e(' Listen to the full score songs playlist from', 'wpml_theme') . '<strong>' . the_title(); ' </strong> <br/> <span class="playlist"><img class="middle" src="https://example.com/images/play-this-song.png" /> YouTube</span> <br/> <span class="playlist2"><img class="middle" src="https://exampl.com/images/play-this-song.png" /> Deezer</span> <br/><span class="playlist3"><img class="middle" src="https://exampl.com/images/play-this-song.png" /> Spotify</span></center>'; // Output needs to be return return $string; } // Register shortcode add_shortcode('my_playlist', 'wpb_playlist_shortcode'); ```
WordPress stores the domain of the installation in several places of the database. So you have to change them in numerous tables. In the case of working, look at the `options` table, entries `siteurl` and `homeurl`. It is also possible to set this via `wp-config.php`: ``` // Home URL of your WordPress. define( 'WP_SITEURL', 'https:/example.com' ); // URL to the WordPress root dir. define( 'WP_HOME', 'https://example.com' ); ``` Look also inside the `wp-config.php` for the domain, because it is possible to set this via constant. The `.htaccess`, if it is an Apache server, should also validate, because the Permalink rules need the domain, especially in the 'Multisite' mode. You should also active the [debug mode](https://codex.wordpress.org/WP_DEBUG), constant `WP_DEBUG` set to true in your `wp-config.php` to get more information about your installation, your problem. It should also help to find the issue with the REST API after domain change. If it works fine, check also the whole database for the old domain. Because WordPress stores in various tables. A change for them is possible via SQL statement or a plugin, like 'Serach Replace'. More notes for a changing of the URL are also inside the codex - <https://wordpress.org/support/article/changing-the-site-url/>
402,072
<p>In a plugin I am currently coding, I want to use the Simple HTML DOM Parser library. However, when I include it</p> <pre><code>require(CPS_PLUGIN_PATH . '/vendor/simple_html_dom.php'); </code></pre> <p>I get this error:</p> <pre><code>Fatal error: Cannot redeclare file_get_html() (previously declared in /www/htdocs/12345/mydomain.com/wp-content/plugins/custom-post-snippets/vendor/simple_html_dom.php:48) in /www/htdocs/12345/mydomain.com/wp-content/plugins/fast-velocity-minify/libs/simplehtmldom/simple_html_dom.php on line 54 </code></pre> <p>So obviously the Fast Velocity Minify plugin is already using it. What do I do here, if I don't want to mess around in the library itself? What's the best practice in a case like this?</p>
[ { "answer_id": 402202, "author": "Lovor", "author_id": 135704, "author_profile": "https://wordpress.stackexchange.com/users/135704", "pm_score": 0, "selected": false, "text": "<p>Did you change all strings in the WordPress database from old domain to new domain? You can use some plugins ...
2022/02/01
[ "https://wordpress.stackexchange.com/questions/402072", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118091/" ]
In a plugin I am currently coding, I want to use the Simple HTML DOM Parser library. However, when I include it ``` require(CPS_PLUGIN_PATH . '/vendor/simple_html_dom.php'); ``` I get this error: ``` Fatal error: Cannot redeclare file_get_html() (previously declared in /www/htdocs/12345/mydomain.com/wp-content/plugins/custom-post-snippets/vendor/simple_html_dom.php:48) in /www/htdocs/12345/mydomain.com/wp-content/plugins/fast-velocity-minify/libs/simplehtmldom/simple_html_dom.php on line 54 ``` So obviously the Fast Velocity Minify plugin is already using it. What do I do here, if I don't want to mess around in the library itself? What's the best practice in a case like this?
WordPress stores the domain of the installation in several places of the database. So you have to change them in numerous tables. In the case of working, look at the `options` table, entries `siteurl` and `homeurl`. It is also possible to set this via `wp-config.php`: ``` // Home URL of your WordPress. define( 'WP_SITEURL', 'https:/example.com' ); // URL to the WordPress root dir. define( 'WP_HOME', 'https://example.com' ); ``` Look also inside the `wp-config.php` for the domain, because it is possible to set this via constant. The `.htaccess`, if it is an Apache server, should also validate, because the Permalink rules need the domain, especially in the 'Multisite' mode. You should also active the [debug mode](https://codex.wordpress.org/WP_DEBUG), constant `WP_DEBUG` set to true in your `wp-config.php` to get more information about your installation, your problem. It should also help to find the issue with the REST API after domain change. If it works fine, check also the whole database for the old domain. Because WordPress stores in various tables. A change for them is possible via SQL statement or a plugin, like 'Serach Replace'. More notes for a changing of the URL are also inside the codex - <https://wordpress.org/support/article/changing-the-site-url/>
402,122
<p>i am building a template for the search page (in full site editing, therefore html and no php), and i want to have a search results heading. i have this:</p> <pre><code> &lt;!-- wp:group {&quot;layout&quot;:{&quot;inherit&quot;:true}} --&gt; &lt;div class=&quot;wp-block-group&quot;&gt; &lt;!-- wp:heading {&quot;level&quot;:1} --&gt; &lt;h1&gt;Search Results&lt;/h1&gt; &lt;!-- /wp:heading --&gt; &lt;/div&gt; &lt;!-- /wp:group --&gt; </code></pre> <p>now i have 2 issues:</p> <p>1- how do i get the search term to display it?</p> <p>2- how can i translate the &quot;Search Results&quot; string?</p>
[ { "answer_id": 402202, "author": "Lovor", "author_id": 135704, "author_profile": "https://wordpress.stackexchange.com/users/135704", "pm_score": 0, "selected": false, "text": "<p>Did you change all strings in the WordPress database from old domain to new domain? You can use some plugins ...
2022/02/02
[ "https://wordpress.stackexchange.com/questions/402122", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/210642/" ]
i am building a template for the search page (in full site editing, therefore html and no php), and i want to have a search results heading. i have this: ``` <!-- wp:group {"layout":{"inherit":true}} --> <div class="wp-block-group"> <!-- wp:heading {"level":1} --> <h1>Search Results</h1> <!-- /wp:heading --> </div> <!-- /wp:group --> ``` now i have 2 issues: 1- how do i get the search term to display it? 2- how can i translate the "Search Results" string?
WordPress stores the domain of the installation in several places of the database. So you have to change them in numerous tables. In the case of working, look at the `options` table, entries `siteurl` and `homeurl`. It is also possible to set this via `wp-config.php`: ``` // Home URL of your WordPress. define( 'WP_SITEURL', 'https:/example.com' ); // URL to the WordPress root dir. define( 'WP_HOME', 'https://example.com' ); ``` Look also inside the `wp-config.php` for the domain, because it is possible to set this via constant. The `.htaccess`, if it is an Apache server, should also validate, because the Permalink rules need the domain, especially in the 'Multisite' mode. You should also active the [debug mode](https://codex.wordpress.org/WP_DEBUG), constant `WP_DEBUG` set to true in your `wp-config.php` to get more information about your installation, your problem. It should also help to find the issue with the REST API after domain change. If it works fine, check also the whole database for the old domain. Because WordPress stores in various tables. A change for them is possible via SQL statement or a plugin, like 'Serach Replace'. More notes for a changing of the URL are also inside the codex - <https://wordpress.org/support/article/changing-the-site-url/>
402,164
<p>Is there any <strong>plugin or alternative method</strong> to hide featured images of all the posts falling under the same category? Please guide.</p> <p>For example:</p> <p>There's a website category:</p> <p>abc.net/category/fruits Under this category the following posts are published Apple, Mango, Cherry, Orange</p> <p>All the posts under fruits category have featured images, <strong>I want featured images of posts not to appear when someone visits this &quot;category link&quot;.</strong> Please note that on my homepage I want the images to appear but not in category link.</p>
[ { "answer_id": 402202, "author": "Lovor", "author_id": 135704, "author_profile": "https://wordpress.stackexchange.com/users/135704", "pm_score": 0, "selected": false, "text": "<p>Did you change all strings in the WordPress database from old domain to new domain? You can use some plugins ...
2022/02/03
[ "https://wordpress.stackexchange.com/questions/402164", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/218718/" ]
Is there any **plugin or alternative method** to hide featured images of all the posts falling under the same category? Please guide. For example: There's a website category: abc.net/category/fruits Under this category the following posts are published Apple, Mango, Cherry, Orange All the posts under fruits category have featured images, **I want featured images of posts not to appear when someone visits this "category link".** Please note that on my homepage I want the images to appear but not in category link.
WordPress stores the domain of the installation in several places of the database. So you have to change them in numerous tables. In the case of working, look at the `options` table, entries `siteurl` and `homeurl`. It is also possible to set this via `wp-config.php`: ``` // Home URL of your WordPress. define( 'WP_SITEURL', 'https:/example.com' ); // URL to the WordPress root dir. define( 'WP_HOME', 'https://example.com' ); ``` Look also inside the `wp-config.php` for the domain, because it is possible to set this via constant. The `.htaccess`, if it is an Apache server, should also validate, because the Permalink rules need the domain, especially in the 'Multisite' mode. You should also active the [debug mode](https://codex.wordpress.org/WP_DEBUG), constant `WP_DEBUG` set to true in your `wp-config.php` to get more information about your installation, your problem. It should also help to find the issue with the REST API after domain change. If it works fine, check also the whole database for the old domain. Because WordPress stores in various tables. A change for them is possible via SQL statement or a plugin, like 'Serach Replace'. More notes for a changing of the URL are also inside the codex - <https://wordpress.org/support/article/changing-the-site-url/>
402,275
<p>Got a mac development machine with PHP installed via brew. I'm trying to get testing tools set up. I successfully set up test scaffolding with <code>wp</code> cli and managed to get <code>bin/install-wp-tests.sh</code> to do its thing.</p> <p>But I get an error with <code>phpunit tests/test-sample.php</code>:</p> <pre><code>Error: The PHPUnit Polyfills library is a requirement for running the WP test suite. If you are trying to run plugin/theme integration tests, make sure the PHPUnit Polyfills library (https://github.com/Yoast/PHPUnit-Polyfills) is available and either load the autoload file of this library in your own test bootstrap before calling the WP Core test bootstrap file; or set the absolute path to the PHPUnit Polyfills library in a &quot;WP_TESTS_PHPUNIT_POLYFILLS_PATH&quot; constant to allow the WP Core bootstrap to load the Polyfills. If you are trying to run the WP Core tests, make sure to set the &quot;WP_RUN_CORE_TESTS&quot; constant to 1 and run `composer update -W` before running the tests. Once the dependencies are installed, you can run the tests using the Composer-installed version of PHPUnit or using a PHPUnit phar file, but the dependencies do need to be installed whichever way the tests are run. </code></pre> <p>So I ran <code>composer require --dev yoast/phpunit-polyfills</code> and opened a new terminal window but still get the same error. Running <code>brew doctor</code> doesn't show anything related to php or composer.</p> <p>I don't develop with PHP much so I'm at a loss as to what else to try.</p>
[ { "answer_id": 402277, "author": "StevieD", "author_id": 86700, "author_profile": "https://wordpress.stackexchange.com/users/86700", "pm_score": 1, "selected": false, "text": "<p>OK, I was reading from an outdated tutorial. Command for running tests is now:</p>\n<p><code>vendor/bin/phpun...
2022/02/06
[ "https://wordpress.stackexchange.com/questions/402275", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86700/" ]
Got a mac development machine with PHP installed via brew. I'm trying to get testing tools set up. I successfully set up test scaffolding with `wp` cli and managed to get `bin/install-wp-tests.sh` to do its thing. But I get an error with `phpunit tests/test-sample.php`: ``` Error: The PHPUnit Polyfills library is a requirement for running the WP test suite. If you are trying to run plugin/theme integration tests, make sure the PHPUnit Polyfills library (https://github.com/Yoast/PHPUnit-Polyfills) is available and either load the autoload file of this library in your own test bootstrap before calling the WP Core test bootstrap file; or set the absolute path to the PHPUnit Polyfills library in a "WP_TESTS_PHPUNIT_POLYFILLS_PATH" constant to allow the WP Core bootstrap to load the Polyfills. If you are trying to run the WP Core tests, make sure to set the "WP_RUN_CORE_TESTS" constant to 1 and run `composer update -W` before running the tests. Once the dependencies are installed, you can run the tests using the Composer-installed version of PHPUnit or using a PHPUnit phar file, but the dependencies do need to be installed whichever way the tests are run. ``` So I ran `composer require --dev yoast/phpunit-polyfills` and opened a new terminal window but still get the same error. Running `brew doctor` doesn't show anything related to php or composer. I don't develop with PHP much so I'm at a loss as to what else to try.
OK, I was reading from an outdated tutorial. Command for running tests is now: `vendor/bin/phpunit <path_to_file>` This command should be Run from root directory of wordpress.
402,292
<p>Our custom post type posts have an extra feed in their source code:</p> <p><code>www.example/post-type/post/feed/</code></p> <p>I want to remove the extra <code>/feed/</code> from our CPTs, as they generate 404s.</p> <p>From the <a href="https://developer.wordpress.org/reference/functions/register_post_type/" rel="nofollow noreferrer">register_post_type</a> function reference, I've tried adding <code>'rewrite' =&gt; array('feeds' =&gt; false),</code> to:</p> <pre><code>register_post_type('templates', array( 'labels' =&gt; array( 'name' =&gt; __( 'Templates' ), 'singular_name' =&gt; __( 'Template' ), 'add_new' =&gt; __( 'Add New' ), 'add_new_item' =&gt; __( 'Add New Template' ), 'edit' =&gt; __( 'Edit' ), 'edit_item' =&gt; __( 'Edit Template' ), 'new_item' =&gt; __( 'New Template' ), 'view' =&gt; __( 'View Template' ), 'view_item' =&gt; __( 'View Template' ), 'search_items' =&gt; __( 'Search Templates' ), 'not_found' =&gt; __( 'No Templates found' ), 'not_found_in_trash' =&gt; __( 'No Templates found in Trash' ), 'parent' =&gt; __( 'Parent Templates' ), ), 'public' =&gt; true, 'show_ui' =&gt; true, 'exclude_from_search' =&gt; true, 'hierarchical' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'thumbnail','page-attributes' ), 'rewrite' =&gt; array('feeds' =&gt; false), 'query_var' =&gt; true ) ); } </code></pre> <p>but this has not resolved the issue.</p> <p>Help appreciated.</p>
[ { "answer_id": 402340, "author": "KNT111_WP", "author_id": 218905, "author_profile": "https://wordpress.stackexchange.com/users/218905", "pm_score": -1, "selected": false, "text": "<p>Paste this in your functions.php and replace your-cpt slug.</p>\n<pre><code>function wpse_191804_pre_get...
2022/02/07
[ "https://wordpress.stackexchange.com/questions/402292", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3206/" ]
Our custom post type posts have an extra feed in their source code: `www.example/post-type/post/feed/` I want to remove the extra `/feed/` from our CPTs, as they generate 404s. From the [register\_post\_type](https://developer.wordpress.org/reference/functions/register_post_type/) function reference, I've tried adding `'rewrite' => array('feeds' => false),` to: ``` register_post_type('templates', array( 'labels' => array( 'name' => __( 'Templates' ), 'singular_name' => __( 'Template' ), 'add_new' => __( 'Add New' ), 'add_new_item' => __( 'Add New Template' ), 'edit' => __( 'Edit' ), 'edit_item' => __( 'Edit Template' ), 'new_item' => __( 'New Template' ), 'view' => __( 'View Template' ), 'view_item' => __( 'View Template' ), 'search_items' => __( 'Search Templates' ), 'not_found' => __( 'No Templates found' ), 'not_found_in_trash' => __( 'No Templates found in Trash' ), 'parent' => __( 'Parent Templates' ), ), 'public' => true, 'show_ui' => true, 'exclude_from_search' => true, 'hierarchical' => true, 'supports' => array( 'title', 'editor', 'thumbnail','page-attributes' ), 'rewrite' => array('feeds' => false), 'query_var' => true ) ); } ``` but this has not resolved the issue. Help appreciated.
From [this post](https://kinsta.com/knowledgebase/wordpress-disable-rss-feed/), I added ``` remove_action( 'wp_head', 'feed_links_extra', 3 ); ``` to our child theme's `functions.php`. Our SEO manager was okay with the fact this would remove feeds for categories as well.
402,327
<p>This is my first time posting a question here. I have this problem that I feel that I am soooo close to solve, but can't manage to do it.</p> <p>I have a custom taxonomy called &quot;aplication&quot; and another called &quot;segment&quot;. Each &quot;aplication&quot; term has an &quot;segment&quot; term associated with it trought a custom field (ACF).</p> <p>What I'm trying to do is to sort the &quot;aplication&quot; terms alphabetically by their associated &quot;segment&quot; term in the edit-tag?taxonomy=aplication page.</p> <p>I managed to add the sortable &quot;segment&quot; column into the page through the code below:</p> <pre class="lang-php prettyprint-override"><code>// Add the &quot;segment&quot; column to the list of &quot;aplication&quot; terms add_filter('manage_edit-aplication_columns', function( $columns ) { $columns['aplication_segment'] = __( 'Segment', 'textdomain' ); return $columns; }); // Add data to the &quot;segment&quot; column created above add_action( 'manage_aplication_custom_column', function( $value, $column, $aplication_id ) { if ( $column == 'aplication_segment') { $segment_ID = get_field( 'aplication_segment', get_term($aplication_id, 'aplication') ); // The custom field for the aplications returns the segment ID $segment = get_term( $segment_ID, 'segment' ); $value = $segment -&gt; name; echo $segment-&gt;name; } }, 10, 3); // Make the &quot;segment&quot; column sortable add_filter('manage_edit-aplication_sortable_columns', function( $columns ) { $columns['aplication_segment'] = 'aplication_segment'; return $columns; }); </code></pre> <p>Now, to sort the &quot;aplication&quot; terms I did this:</p> <pre class="lang-php prettyprint-override"><code>add_action('pre_get_terms', function( $term_query ) { global $current_screen; global $wpdb; if ( ($current_screen) &amp;&amp; $current_screen-&gt;id === 'edit-aplication' ) { if ( $term_query -&gt; query_vars['orderby'] === 'aplication_segment' ) { $sql = &quot;SELECT ttm.term_id, ttm.name, ttm.slug, ttm.term_group, ttm.term_order FROM (SELECT wp_terms.term_id, wp_terms.name, wp_term_taxonomy.taxonomy FROM wp_terms INNER JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id AND wp_term_taxonomy.taxonomy = 'segment' ORDER BY wp_terms.name) as ttt INNER JOIN (SELECT wp_terms.*, wp_termmeta.meta_value FROM wp_terms INNER JOIN wp_termmeta ON wp_terms.term_id = wp_termmeta.term_id AND wp_termmeta.meta_key = 'aplication_segment' ORDER BY wp_terms.name) as ttm ON ttt.term_id = ttm.meta_value ORDER BY ttt.name {$term_query-&gt;query_vars['order']}&quot;; return $wpdb -&gt; get_results( $sql ); }; } }, 10, 1); </code></pre> <p>This query works, it gives me the result that I need (I didn't translated those to english):</p> <pre class="lang-php prettyprint-override"><code>Array ( [0] =&gt; stdClass Object ( [term_id] =&gt; 147 [name] =&gt; Puxadores [slug] =&gt; puxadores-moveleiros [term_group] =&gt; 0 [term_order] =&gt; 0 ) [1] =&gt; stdClass Object ( [term_id] =&gt; 3391 [name] =&gt; Cantoneiras [slug] =&gt; cantoneiras [term_group] =&gt; 0 [term_order] =&gt; 0 ) [2] =&gt; stdClass Object ( [term_id] =&gt; 150 [name] =&gt; Automotivo [slug] =&gt; automotivo [term_group] =&gt; 0 [term_order] =&gt; 0 ) [3] =&gt; stdClass Object ( [term_id] =&gt; 149 [name] =&gt; Dissipadores [slug] =&gt; dissipadores [term_group] =&gt; 0 [term_order] =&gt; 0 ) [4] =&gt; stdClass Object ( [term_id] =&gt; 3393 [name] =&gt; Luminárias [slug] =&gt; luminarias [term_group] =&gt; 0 [term_order] =&gt; 0 ) [5] =&gt; stdClass Object ( [term_id] =&gt; 148 [name] =&gt; Base Divisória [slug] =&gt; base-divisoria [term_group] =&gt; 0 [term_order] =&gt; 0 ) [6] =&gt; stdClass Object ( [term_id] =&gt; 3392 [name] =&gt; Esquadrias [slug] =&gt; esquadrias [term_group] =&gt; 0 [term_order] =&gt; 0 ) ) </code></pre> <p>The only problem is that I can't manage to show the result in the &quot;aplication&quot; terms table. It keeps sorting by the &quot;aplication&quot; term name.</p> <p><a href="https://i.stack.imgur.com/VPlBF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VPlBF.png" alt="enter image description here" /></a></p> <p>I appreciate anyone who can try and help me with this.</p>
[ { "answer_id": 402363, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p><strong>You would not use SQL to do this</strong>, and that filter has nothing to do with SQL queries. This ...
2022/02/07
[ "https://wordpress.stackexchange.com/questions/402327", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/218755/" ]
This is my first time posting a question here. I have this problem that I feel that I am soooo close to solve, but can't manage to do it. I have a custom taxonomy called "aplication" and another called "segment". Each "aplication" term has an "segment" term associated with it trought a custom field (ACF). What I'm trying to do is to sort the "aplication" terms alphabetically by their associated "segment" term in the edit-tag?taxonomy=aplication page. I managed to add the sortable "segment" column into the page through the code below: ```php // Add the "segment" column to the list of "aplication" terms add_filter('manage_edit-aplication_columns', function( $columns ) { $columns['aplication_segment'] = __( 'Segment', 'textdomain' ); return $columns; }); // Add data to the "segment" column created above add_action( 'manage_aplication_custom_column', function( $value, $column, $aplication_id ) { if ( $column == 'aplication_segment') { $segment_ID = get_field( 'aplication_segment', get_term($aplication_id, 'aplication') ); // The custom field for the aplications returns the segment ID $segment = get_term( $segment_ID, 'segment' ); $value = $segment -> name; echo $segment->name; } }, 10, 3); // Make the "segment" column sortable add_filter('manage_edit-aplication_sortable_columns', function( $columns ) { $columns['aplication_segment'] = 'aplication_segment'; return $columns; }); ``` Now, to sort the "aplication" terms I did this: ```php add_action('pre_get_terms', function( $term_query ) { global $current_screen; global $wpdb; if ( ($current_screen) && $current_screen->id === 'edit-aplication' ) { if ( $term_query -> query_vars['orderby'] === 'aplication_segment' ) { $sql = "SELECT ttm.term_id, ttm.name, ttm.slug, ttm.term_group, ttm.term_order FROM (SELECT wp_terms.term_id, wp_terms.name, wp_term_taxonomy.taxonomy FROM wp_terms INNER JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id AND wp_term_taxonomy.taxonomy = 'segment' ORDER BY wp_terms.name) as ttt INNER JOIN (SELECT wp_terms.*, wp_termmeta.meta_value FROM wp_terms INNER JOIN wp_termmeta ON wp_terms.term_id = wp_termmeta.term_id AND wp_termmeta.meta_key = 'aplication_segment' ORDER BY wp_terms.name) as ttm ON ttt.term_id = ttm.meta_value ORDER BY ttt.name {$term_query->query_vars['order']}"; return $wpdb -> get_results( $sql ); }; } }, 10, 1); ``` This query works, it gives me the result that I need (I didn't translated those to english): ```php Array ( [0] => stdClass Object ( [term_id] => 147 [name] => Puxadores [slug] => puxadores-moveleiros [term_group] => 0 [term_order] => 0 ) [1] => stdClass Object ( [term_id] => 3391 [name] => Cantoneiras [slug] => cantoneiras [term_group] => 0 [term_order] => 0 ) [2] => stdClass Object ( [term_id] => 150 [name] => Automotivo [slug] => automotivo [term_group] => 0 [term_order] => 0 ) [3] => stdClass Object ( [term_id] => 149 [name] => Dissipadores [slug] => dissipadores [term_group] => 0 [term_order] => 0 ) [4] => stdClass Object ( [term_id] => 3393 [name] => Luminárias [slug] => luminarias [term_group] => 0 [term_order] => 0 ) [5] => stdClass Object ( [term_id] => 148 [name] => Base Divisória [slug] => base-divisoria [term_group] => 0 [term_order] => 0 ) [6] => stdClass Object ( [term_id] => 3392 [name] => Esquadrias [slug] => esquadrias [term_group] => 0 [term_order] => 0 ) ) ``` The only problem is that I can't manage to show the result in the "aplication" terms table. It keeps sorting by the "aplication" term name. [![enter image description here](https://i.stack.imgur.com/VPlBF.png)](https://i.stack.imgur.com/VPlBF.png) I appreciate anyone who can try and help me with this.
Following @TomJNowell advices I descarted the usage of SQL query and aimed at the meta\_value sorting. I'll describe the scenario from the beggining with the solution. I have a custom taxonomy called "aplication" and another called "segment", and every application term has a custom field (ACF) for a segment term. What I needed was to sort the aplication terms by their associated segment term's name at the edit-tags.php?taxonomy page, but the problem was that the custom field value withhold the ID of the segment term and not it's name. So, to workaround this problem, I added another custom field to the aplications, a text field that receives the slug of the segment. This field is automatically updated with the segment's slug every time that the aplication term is saved. ``` add_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3); function update_aplication_segment_name( $term_id, $tt_id, $update ) { $aplication = get_term( $term_id, 'aplication' ); //Gets the object of the current aplication $segment_ID = get_field( 'aplication_segment', $aplication ); //The segment is associated to the aplication through a custom field that returns the segment term's ID $segment = get_term( $segment_ID, 'segment' ); //Gets the segment associated with the current aplication //Remove the hook to avoid loop remove_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3); //Updates the value of the 'aplication_segment_name' field of the current aplication update_term_meta( $term_id, 'aplication_segment_name', $segment->slug); //Add the hook back add_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3); } ``` With the code above, every time that the red field changes, the value of the blue field will change too (the blue field will be hidden from the final user). [![enter image description here](https://i.stack.imgur.com/bua2D.png)](https://i.stack.imgur.com/bua2D.png) Now, to sort the application terms by their segment's name I adapted the code from this answer: <https://wordpress.stackexchange.com/a/277755/218755> ``` add_filter('pre_get_terms', function( $term_query ) { global $current_screen; if ( is_admin() && $current_screen->id == 'edit-aplication' && ( !isset($_GET['orderby']) || $_GET['orderby'] == 'aplication_segment')) { // set orderby to the named clause in the meta_query $term_query -> query_vars['orderby'] = 'order_clause'; $term_query -> query_vars['order'] = isset($_GET['order']) ? $_GET['order'] : "DESC"; // the OR relation and the NOT EXISTS clause allow for terms without a meta_value at all $args = array('relation' => 'OR', 'order_clause' => array('key' => 'aplication_segment_name', 'type' => 'STRING' ), array('key' => 'aplication_segment_name', 'compare' => 'NOT EXISTS' ) ); $term_query -> meta_query = new WP_Meta_Query( $args ); } return $term_query; }); ``` Now the aplication terms can be sorted by their associated segment term's name! [![enter image description here](https://i.stack.imgur.com/GJcHR.png)](https://i.stack.imgur.com/GJcHR.png)
402,636
<p>I've been trying to redirect users to the profile page when accessing profiles of users and self. Currently it's redirecting to activity page by default.</p> <blockquote> <p>Eg: example.com/members/username</p> </blockquote> <p>is showing the activity page as default.</p> <p>I've tried setting the below line in wp-config.php as suggested in <a href="https://codex.buddypress.org/getting-started/guides/change-members-profile-landing-tab/" rel="nofollow noreferrer">Buddypress forum</a>. But doesn't seem to be working.</p> <blockquote> <p>define('BP_DEFAULT_COMPONENT', 'profile');</p> </blockquote> <p>Is there any workaround to implement this, instead of profile all the other links(friends, groups, notifications etc.) are working when setting in <strong>BP_DEFAULT_COMPONENT</strong>.</p>
[ { "answer_id": 402363, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p><strong>You would not use SQL to do this</strong>, and that filter has nothing to do with SQL queries. This ...
2022/02/14
[ "https://wordpress.stackexchange.com/questions/402636", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89569/" ]
I've been trying to redirect users to the profile page when accessing profiles of users and self. Currently it's redirecting to activity page by default. > > Eg: example.com/members/username > > > is showing the activity page as default. I've tried setting the below line in wp-config.php as suggested in [Buddypress forum](https://codex.buddypress.org/getting-started/guides/change-members-profile-landing-tab/). But doesn't seem to be working. > > define('BP\_DEFAULT\_COMPONENT', 'profile'); > > > Is there any workaround to implement this, instead of profile all the other links(friends, groups, notifications etc.) are working when setting in **BP\_DEFAULT\_COMPONENT**.
Following @TomJNowell advices I descarted the usage of SQL query and aimed at the meta\_value sorting. I'll describe the scenario from the beggining with the solution. I have a custom taxonomy called "aplication" and another called "segment", and every application term has a custom field (ACF) for a segment term. What I needed was to sort the aplication terms by their associated segment term's name at the edit-tags.php?taxonomy page, but the problem was that the custom field value withhold the ID of the segment term and not it's name. So, to workaround this problem, I added another custom field to the aplications, a text field that receives the slug of the segment. This field is automatically updated with the segment's slug every time that the aplication term is saved. ``` add_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3); function update_aplication_segment_name( $term_id, $tt_id, $update ) { $aplication = get_term( $term_id, 'aplication' ); //Gets the object of the current aplication $segment_ID = get_field( 'aplication_segment', $aplication ); //The segment is associated to the aplication through a custom field that returns the segment term's ID $segment = get_term( $segment_ID, 'segment' ); //Gets the segment associated with the current aplication //Remove the hook to avoid loop remove_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3); //Updates the value of the 'aplication_segment_name' field of the current aplication update_term_meta( $term_id, 'aplication_segment_name', $segment->slug); //Add the hook back add_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3); } ``` With the code above, every time that the red field changes, the value of the blue field will change too (the blue field will be hidden from the final user). [![enter image description here](https://i.stack.imgur.com/bua2D.png)](https://i.stack.imgur.com/bua2D.png) Now, to sort the application terms by their segment's name I adapted the code from this answer: <https://wordpress.stackexchange.com/a/277755/218755> ``` add_filter('pre_get_terms', function( $term_query ) { global $current_screen; if ( is_admin() && $current_screen->id == 'edit-aplication' && ( !isset($_GET['orderby']) || $_GET['orderby'] == 'aplication_segment')) { // set orderby to the named clause in the meta_query $term_query -> query_vars['orderby'] = 'order_clause'; $term_query -> query_vars['order'] = isset($_GET['order']) ? $_GET['order'] : "DESC"; // the OR relation and the NOT EXISTS clause allow for terms without a meta_value at all $args = array('relation' => 'OR', 'order_clause' => array('key' => 'aplication_segment_name', 'type' => 'STRING' ), array('key' => 'aplication_segment_name', 'compare' => 'NOT EXISTS' ) ); $term_query -> meta_query = new WP_Meta_Query( $args ); } return $term_query; }); ``` Now the aplication terms can be sorted by their associated segment term's name! [![enter image description here](https://i.stack.imgur.com/GJcHR.png)](https://i.stack.imgur.com/GJcHR.png)
402,749
<p>I have a program that can run standalone (outside WP) or inside WP. If the program is running 'inside' WP (via a custom template using appropriate enqueue scripts and add_actions), then there is a constant that the program needs to be defined - an email address that the standalone program will use.</p> <p>If the program is running on a WP site (inside WP), then the program needs to use the WP admin email address (via the <code>get_option( 'admin_email' )</code> function.</p> <p>If the program is standalone (on a non-WP site), then there is a different process that is used to set the email address used by the program.</p> <p>There are many constants defined within <code>wp-config.php</code> and <code>wp-settings.php</code>. What is a good constant to use to check if WP is running? For instance, an option is ABSPATH.</p> <p>I am looking for a 'best practice' of which WP constant to check - and ideally would be a constant that is not likely to be used in a non-WP site (although I understand that this is impossible to guarantee).</p>
[ { "answer_id": 402757, "author": "Sébastien Serre", "author_id": 62892, "author_profile": "https://wordpress.stackexchange.com/users/62892", "pm_score": 2, "selected": false, "text": "<p>I don't know if others CMS or system may use ABSPATH or not but it's seems to be a generic words.\nI ...
2022/02/16
[ "https://wordpress.stackexchange.com/questions/402749", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29416/" ]
I have a program that can run standalone (outside WP) or inside WP. If the program is running 'inside' WP (via a custom template using appropriate enqueue scripts and add\_actions), then there is a constant that the program needs to be defined - an email address that the standalone program will use. If the program is running on a WP site (inside WP), then the program needs to use the WP admin email address (via the `get_option( 'admin_email' )` function. If the program is standalone (on a non-WP site), then there is a different process that is used to set the email address used by the program. There are many constants defined within `wp-config.php` and `wp-settings.php`. What is a good constant to use to check if WP is running? For instance, an option is ABSPATH. I am looking for a 'best practice' of which WP constant to check - and ideally would be a constant that is not likely to be used in a non-WP site (although I understand that this is impossible to guarantee).
Based on the other answer, I decided that looking for a specific WP function is the best approach to determine if my code is running in WP or not. I used this code block: ``` if (function_exists('get_bloginfo')) { // most likely a WordPress function if (get_bloginfo('admin_email')) { // set it only if there is a value (a double-check) $admin_email = get_bloginfo('admin_email'); } } ``` It first checks if the `get_bloginfo` function exists, because I need to let a prior setting of $admin\_email 'stand' if not running withing WP. The second line checks for a value for the 'admin\_email', which will be set in any WP installation. This is to handle any chance that there is a `get_bloginfo()` in a non-WP site. There might be a `get_bloginfo()` in the non-WP site, but even less a possibility that there is a 'admin\_email' setting that will be available on a non-WP site. The next line sets that variable. This is probably not a perfect solution, but I think it handles enough possibilities that it is 'good enough'. With this code, I can get the WP site's admin-email, if the application is running on a WP site. Otherwise, I use the value previously set in the program.
402,750
<p>I have a wordpress install where I want to serve a static page/template for anyone arriving at a child of a certain page, e.g.</p> <pre><code>https://example.com/products/* </code></pre> <p>Would all serve a php template from within Wordpress (or even just a static file) without changing the slug, so the following:</p> <pre><code>https://example.com/products/some-product-slug https://example.com/products/another-product-slug </code></pre> <p>Would both serve the same file without changing/redirecting the URL.</p> <p>This template would also handle 404s internally, so a slug like:</p> <pre><code>https://example.com/products/does-not-exist </code></pre> <p>Would still serve the same static template.</p> <p>Is this possible to configure within wordpress?</p> <p>Imagine that the page/template being redirected to is completely unrelated to a post type or hierarchy, as it is serving external resources based on the slug.</p>
[ { "answer_id": 402753, "author": "jmcgrory", "author_id": 219284, "author_profile": "https://wordpress.stackexchange.com/users/219284", "pm_score": 1, "selected": true, "text": "<p>Okay so I have resolved this by combining several different wordpress functionalities:</p>\n<ol>\n<li>Catch...
2022/02/16
[ "https://wordpress.stackexchange.com/questions/402750", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/219284/" ]
I have a wordpress install where I want to serve a static page/template for anyone arriving at a child of a certain page, e.g. ``` https://example.com/products/* ``` Would all serve a php template from within Wordpress (or even just a static file) without changing the slug, so the following: ``` https://example.com/products/some-product-slug https://example.com/products/another-product-slug ``` Would both serve the same file without changing/redirecting the URL. This template would also handle 404s internally, so a slug like: ``` https://example.com/products/does-not-exist ``` Would still serve the same static template. Is this possible to configure within wordpress? Imagine that the page/template being redirected to is completely unrelated to a post type or hierarchy, as it is serving external resources based on the slug.
Okay so I have resolved this by combining several different wordpress functionalities: 1. Catches the template include conditionally `add_filter( 'template_include', '...' );`, in my case based on a regex match of the expected URI pattern 2. `locate_template('example-template.php')` to then resolve my (essentially) static template 3. A query within my `example-template.php` that externally retrieves the resource 4. This must handle 404s interally as the response will always assume the post can't be found, I am always setting the header response (before `get_header` in the template to `202` where the resource is found. 5. Example; `if ($resource) { @header($_SERVER['SERVER_PROTOCOL'] . ' 202 Accepted', true, 202); }` Bit convoluted, but really not too much work for what I required.
402,786
<p>I am trying to fetch <code>users</code> All information by using below code.</p> <pre><code>if($_POST['orga_id']) { $users_query = new WP_User_Query(array( 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'first_name', 'value' =&gt; $_POST['search'], 'compare' =&gt; 'LIKE' ), array( 'key' =&gt; 'last_name', 'value' =&gt; $_POST['search'], 'compare' =&gt; 'LIKE', ), ), array( 'key' =&gt; 'organisation', 'value' =&gt; $_POST['orga_id'], 'compare' =&gt; 'LIKE', ), array( 'key' =&gt; 'available', 'value' =&gt; 1, 'compare' =&gt; '=', ), ) )); } else { $users_query = new WP_User_Query(array( 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'first_name', 'value' =&gt; $_POST['search'], 'compare' =&gt; 'LIKE' ), array( 'key' =&gt; 'last_name', 'value' =&gt; $_POST['search'], 'compare' =&gt; 'LIKE', ), ), array( 'key' =&gt; 'available', 'value' =&gt; 1, 'compare' =&gt; '=', ), ) )); } //$users_found = $users-&gt;get_results(); $args = array( 'fields' =&gt; 'all', 'orderby' =&gt; array( 'last_name' =&gt; 'asc', 'first_name' =&gt; 'asc' ), 'meta_query' =&gt; $users_query, ); $users2 = get_users($args); </code></pre> <p>But I am getting only few information like below.</p> <pre><code>ID: &quot;548&quot; ​​​​ display_name: &quot;AaronKew&quot; ​​​​ user_activation_key: &quot;&quot; ​​​​ user_email: &quot;aaron.kew@nsw.scouts.com.au&quot; ​​​​ user_login: &quot;AaronKew&quot; ​​​​ user_nicename: &quot;aaronkew&quot; ​​​​ user_pass: &quot;$P$BauZua136ZxKPY9Nu2FpmZT1LRmOLr1&quot; ​​​​ user_registered: &quot;2022-02-06 03:17:50&quot; ​​​​ user_status: &quot;0&quot; ​​​​ user_url: &quot;&quot; </code></pre> <p><a href="https://i.stack.imgur.com/JVYyb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JVYyb.png" alt="enter image description here" /></a></p> <p>I am not getting <code>first_name</code> and <code>last_name</code> of users.</p>
[ { "answer_id": 402787, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>There's been a fundamental misunderstanding of how <code>meta_query</code> works. <code>meta_query</code> is...
2022/02/17
[ "https://wordpress.stackexchange.com/questions/402786", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65189/" ]
I am trying to fetch `users` All information by using below code. ``` if($_POST['orga_id']) { $users_query = new WP_User_Query(array( 'meta_query' => array( 'relation' => 'AND', array( 'relation' => 'OR', array( 'key' => 'first_name', 'value' => $_POST['search'], 'compare' => 'LIKE' ), array( 'key' => 'last_name', 'value' => $_POST['search'], 'compare' => 'LIKE', ), ), array( 'key' => 'organisation', 'value' => $_POST['orga_id'], 'compare' => 'LIKE', ), array( 'key' => 'available', 'value' => 1, 'compare' => '=', ), ) )); } else { $users_query = new WP_User_Query(array( 'meta_query' => array( 'relation' => 'AND', array( 'relation' => 'OR', array( 'key' => 'first_name', 'value' => $_POST['search'], 'compare' => 'LIKE' ), array( 'key' => 'last_name', 'value' => $_POST['search'], 'compare' => 'LIKE', ), ), array( 'key' => 'available', 'value' => 1, 'compare' => '=', ), ) )); } //$users_found = $users->get_results(); $args = array( 'fields' => 'all', 'orderby' => array( 'last_name' => 'asc', 'first_name' => 'asc' ), 'meta_query' => $users_query, ); $users2 = get_users($args); ``` But I am getting only few information like below. ``` ID: "548" ​​​​ display_name: "AaronKew" ​​​​ user_activation_key: "" ​​​​ user_email: "aaron.kew@nsw.scouts.com.au" ​​​​ user_login: "AaronKew" ​​​​ user_nicename: "aaronkew" ​​​​ user_pass: "$P$BauZua136ZxKPY9Nu2FpmZT1LRmOLr1" ​​​​ user_registered: "2022-02-06 03:17:50" ​​​​ user_status: "0" ​​​​ user_url: "" ``` [![enter image description here](https://i.stack.imgur.com/JVYyb.png)](https://i.stack.imgur.com/JVYyb.png) I am not getting `first_name` and `last_name` of users.
Actually since you already have the ID you could just loop through and get the meta. <https://developer.wordpress.org/reference/functions/get_user_meta/> ``` get_user_meta(ID) ```
402,836
<p>This is a follow-up to my previous post regarding multiple categories/posts on one page.</p> <p>Currently, I have a page filled with multiple loops of each category of a custom post type. The problem is that the code is becoming a bit much to edit and organize. Here's a small example of the multiple categories I have:</p> <pre><code>$stratocaster_args = array( 'post_type' =&gt; 'diagram', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'diagram-category', // Taxonomy slug 'terms' =&gt; 'stratocaster-wiring-diagrams', // Taxonomy term slug 'field' =&gt; 'slug', // Taxonomy field ) ) ); $telecaster_args = array( 'post_type' =&gt; 'diagram', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'diagram-category', // Taxonomy slug 'terms' =&gt; 'telecaster-wiring-diagrams', // Taxonomy term slug 'field' =&gt; 'slug', // Taxonomy field ) ) ); $misc_fender_args = array( 'post_type' =&gt; 'diagram', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'diagram-category', // Taxonomy slug 'terms' =&gt; 'misc-fender-wiring-diagrams', // Taxonomy term slug 'field' =&gt; 'slug', // Taxonomy field ) ) ); $stratocaster_query = new WP_Query($stratocaster_args); $telecaster_query = new WP_Query($telecaster_args); $misc_fender_query = new WP_Query($misc_fender_args); ?&gt; &lt;div class=&quot;blog-archive&quot;&gt; &lt;?php get_template_part('template-parts/page', 'header'); ?&gt; &lt;?php page_wrapper_open('wiring-diagrams'); ?&gt; &lt;?php /**Begin Wiring Diagram Results */ /**Strat */ if ($stratocaster_query-&gt;have_posts()) : echo '&lt;h2 class=&quot;main-heading gold-line&quot;&gt;STRATOCASTER WIRING DIAGRAMS:&lt;/h2&gt;'; echo '&lt;div class=&quot;wiring-diagram-results grid-4&quot;&gt;'; while ($stratocaster_query-&gt;have_posts()) : $stratocaster_query-&gt;the_post(); get_template_part('template-parts/content', 'wiring-diagram'); endwhile; echo '&lt;/div&gt;'; wp_reset_postdata(); endif; /**Telecaster */ if ($telecaster_query-&gt;have_posts()) : echo '&lt;h2 class=&quot;main-heading gold-line&quot;&gt;TELECASTER WIRING DIAGRAMS:&lt;/h2&gt;'; echo '&lt;div class=&quot;wiring-diagram-results grid-4&quot;&gt;'; while ($telecaster_query-&gt;have_posts()) : $telecaster_query-&gt;the_post(); get_template_part('template-parts/content', 'wiring-diagram'); endwhile; echo '&lt;/div&gt;'; wp_reset_postdata(); endif; /**Misc Fender */ if ($misc_fender_query-&gt;have_posts()) : echo '&lt;h2 class=&quot;main-heading gold-line&quot;&gt;MISC. FENDER WIRING DIAGRAMS:&lt;/h2&gt;'; echo '&lt;div class=&quot;wiring-diagram-results grid-4&quot;&gt;'; while ($misc_fender_query-&gt;have_posts()) : $misc_fender_query-&gt;the_post(); get_template_part('template-parts/content', 'wiring-diagram'); endwhile; echo '&lt;/div&gt;'; wp_reset_postdata(); endif; ........etc. </code></pre> <p>Is there a more efficient way to write this to manage the code a little better? Sorry for the noob question.</p>
[ { "answer_id": 402854, "author": "Artemy Kaydash", "author_id": 191232, "author_profile": "https://wordpress.stackexchange.com/users/191232", "pm_score": 2, "selected": false, "text": "<p>Split your code into smaller parts. For example, you can use a separate template part for each loop....
2022/02/18
[ "https://wordpress.stackexchange.com/questions/402836", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/200652/" ]
This is a follow-up to my previous post regarding multiple categories/posts on one page. Currently, I have a page filled with multiple loops of each category of a custom post type. The problem is that the code is becoming a bit much to edit and organize. Here's a small example of the multiple categories I have: ``` $stratocaster_args = array( 'post_type' => 'diagram', 'tax_query' => array( array( 'taxonomy' => 'diagram-category', // Taxonomy slug 'terms' => 'stratocaster-wiring-diagrams', // Taxonomy term slug 'field' => 'slug', // Taxonomy field ) ) ); $telecaster_args = array( 'post_type' => 'diagram', 'tax_query' => array( array( 'taxonomy' => 'diagram-category', // Taxonomy slug 'terms' => 'telecaster-wiring-diagrams', // Taxonomy term slug 'field' => 'slug', // Taxonomy field ) ) ); $misc_fender_args = array( 'post_type' => 'diagram', 'tax_query' => array( array( 'taxonomy' => 'diagram-category', // Taxonomy slug 'terms' => 'misc-fender-wiring-diagrams', // Taxonomy term slug 'field' => 'slug', // Taxonomy field ) ) ); $stratocaster_query = new WP_Query($stratocaster_args); $telecaster_query = new WP_Query($telecaster_args); $misc_fender_query = new WP_Query($misc_fender_args); ?> <div class="blog-archive"> <?php get_template_part('template-parts/page', 'header'); ?> <?php page_wrapper_open('wiring-diagrams'); ?> <?php /**Begin Wiring Diagram Results */ /**Strat */ if ($stratocaster_query->have_posts()) : echo '<h2 class="main-heading gold-line">STRATOCASTER WIRING DIAGRAMS:</h2>'; echo '<div class="wiring-diagram-results grid-4">'; while ($stratocaster_query->have_posts()) : $stratocaster_query->the_post(); get_template_part('template-parts/content', 'wiring-diagram'); endwhile; echo '</div>'; wp_reset_postdata(); endif; /**Telecaster */ if ($telecaster_query->have_posts()) : echo '<h2 class="main-heading gold-line">TELECASTER WIRING DIAGRAMS:</h2>'; echo '<div class="wiring-diagram-results grid-4">'; while ($telecaster_query->have_posts()) : $telecaster_query->the_post(); get_template_part('template-parts/content', 'wiring-diagram'); endwhile; echo '</div>'; wp_reset_postdata(); endif; /**Misc Fender */ if ($misc_fender_query->have_posts()) : echo '<h2 class="main-heading gold-line">MISC. FENDER WIRING DIAGRAMS:</h2>'; echo '<div class="wiring-diagram-results grid-4">'; while ($misc_fender_query->have_posts()) : $misc_fender_query->the_post(); get_template_part('template-parts/content', 'wiring-diagram'); endwhile; echo '</div>'; wp_reset_postdata(); endif; ........etc. ``` Is there a more efficient way to write this to manage the code a little better? Sorry for the noob question.
You could move the query configs into one config array and loop that for querying the posts and rendering the content sections. Inside the content section partial you'd have another loop for the posts. The magic ingredient here is the third `$args` parameter you can use with `get_template_part()`. Use it to pass data to the partial file. ``` $configs = array( array( 'query' => array( 'post_type' => 'diagram', 'tax_query' => array( array( 'taxonomy' => 'diagram-category', 'terms' => 'stratocaster-wiring-diagrams', 'field' => 'slug', ) ) ), 'template_name' => 'wiring-diagram', 'heading' => 'Some heading text', ), // more configs... ); foreach ( $configs as $config ) { $config['query'] = new WP_Query( $config['query'] ); if ( ! $config['query']->posts ) { continue; } get_template_part( 'template-parts/content-section', null, $config ); } ``` Section partial, ``` <h2 class="main-heading gold-line"><?php echo esc_html( $args['heading'] ); ?></h2> <div class="wiring-diagram-results grid-4"> <?php while( $args['query']->have_posts() ) { $args['query']->the_post(); get_template_part( 'template-parts/content', $args['template_name'] ); } wp_reset_postdata(); ?> </div> ``` The config array could also be placed into a separate file or function and not to have it hard-coded on the template file.
402,862
<p>I use the following code to add a custom option in the Gutenberg-sidebar. Its visible and saving the Checkbox-value works.</p> <p>But: if I click on the CheckboxControl nothing visible changes on it. If it is not checked and I want to check it, it does not go checked. The &quot;Update&quot;-button goes active and I see the checked Checkbox after it.</p> <p>Why?</p> <pre><code>import { CheckboxControl } from '@wordpress/components'; import { dispatch, select } from '@wordpress/data'; import { PluginDocumentSettingPanel } from '@wordpress/edit-post'; import { Component } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; export default class Sidebar extends Component { render() { const meta = select( 'core/editor' ).getEditedPostAttribute( 'meta' ); const toggleState = meta['code']; return ( &lt;PluginDocumentSettingPanel name=&quot;code&quot; title={ __( 'Display Settings', 'myplugin' ) } &gt; &lt;CheckboxControl checked={ toggleState } help={ __( 'My help.', 'myplugin' ) } label={ __( 'My Label', 'myplugin' ) } onChange={ ( value ) =&gt; { dispatch( 'core/editor' ).editPost( { meta: { 'code': value, }, } ); } } /&gt; &lt;/PluginDocumentSettingPanel&gt; ); } } </code></pre>
[ { "answer_id": 402872, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p>Because React is unaware that anything changed, all the props are the same, and so is the state, so no updat...
2022/02/18
[ "https://wordpress.stackexchange.com/questions/402862", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/219391/" ]
I use the following code to add a custom option in the Gutenberg-sidebar. Its visible and saving the Checkbox-value works. But: if I click on the CheckboxControl nothing visible changes on it. If it is not checked and I want to check it, it does not go checked. The "Update"-button goes active and I see the checked Checkbox after it. Why? ``` import { CheckboxControl } from '@wordpress/components'; import { dispatch, select } from '@wordpress/data'; import { PluginDocumentSettingPanel } from '@wordpress/edit-post'; import { Component } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; export default class Sidebar extends Component { render() { const meta = select( 'core/editor' ).getEditedPostAttribute( 'meta' ); const toggleState = meta['code']; return ( <PluginDocumentSettingPanel name="code" title={ __( 'Display Settings', 'myplugin' ) } > <CheckboxControl checked={ toggleState } help={ __( 'My help.', 'myplugin' ) } label={ __( 'My Label', 'myplugin' ) } onChange={ ( value ) => { dispatch( 'core/editor' ).editPost( { meta: { 'code': value, }, } ); } } /> </PluginDocumentSettingPanel> ); } } ```
**Solution found:** ``` const { __ } = wp.i18n; const { useSelect, useDispatch } = wp.data; const { PluginDocumentSettingPanel } = wp.editPost; const { CheckboxControl, PanelRow } = wp.components; const Sidebar = () => { const { postMeta } = useSelect( ( select ) => { return { postMeta: select( 'core/editor' ).getEditedPostAttribute( 'meta' ), }; } ); const { editPost } = useDispatch( 'core/editor', [ postMeta.code ] ); return( <PluginDocumentSettingPanel title={ __( 'Display Settings', 'myplugin') }> <PanelRow> <CheckboxControl label={ __( 'My Label', 'myplugin' ) } checked={ postMeta.code } onChange={ ( value ) => editPost( { meta: { code: value } } ) } /> </PanelRow> </PluginDocumentSettingPanel> ); } export default Sidebar; ```
402,874
<p>I have developed a custom taxonomy post type. I have displayed categories &amp; inside categories posts/(products).</p> <p>I am getting the Post title &amp; Image as they should be (which I add), but the descriptions of all the posts are same.</p> <p>I have no idea why same desc keeps displaying,even though everything else is dynamic.</p> <p>Here is the code I am using:</p> <pre><code>$taxID = get_queried_object()-&gt;term_id; $args = array( 'post_type' =&gt; 'industrial_product', 'fields' =&gt; 'ids', 'posts_per_page' =&gt; -1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'industrial_product_cat', 'terms' =&gt; $taxID, 'field' =&gt; 'term_id', 'operator' =&gt; 'IN' ) ), ); $query = new WP_Query($args); if ($query-&gt;have_posts()): $i=1; foreach( $query-&gt;posts as $id ):?&gt; &lt;div class=&quot;row mb-4&quot;&gt; &lt;div class=&quot;col-md-4 col-12&quot;&gt; &lt;?php $image_palette = wp_get_attachment_image_src( get_post_thumbnail_id( $id ), 'single-post-thumbnail' ); ?&gt; &lt;img src=&quot;&lt;?php echo $image_palette[0]; ?&gt;&quot; alt=&quot;&quot; class=&quot;img-fluid&quot; style=&quot;max-width:100%;&quot;&gt; &lt;/div&gt; &lt;div class=&quot;col-md-8 col-12&quot;&gt; &lt;ul class=&quot;nav nav-tabs&quot; id=&quot;myTab&quot; role=&quot;tablist&quot;&gt; &lt;li class=&quot;nav-item m-0&quot; role=&quot;presentation&quot;&gt; &lt;a class=&quot;nav-link active c-2&quot; id=&quot;productInfo&lt;?php echo $i;?&gt;-tab&quot; data-toggle=&quot;tab&quot; href=&quot;#productInfo&lt;?php echo $i;?&gt;&quot; role=&quot;tab&quot; aria-controls=&quot;productInfo&lt;?php echo $i;?&gt;&quot; aria-selected=&quot;true&quot;&gt;Product Information&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item m-0&quot; role=&quot;presentation&quot;&gt; &lt;a class=&quot;nav-link c-2&quot; id=&quot;std_tds&lt;?php echo $i;?&gt;-tab&quot; data-toggle=&quot;tab&quot; href=&quot;#std_tds&lt;?php echo $i;?&gt;&quot; role=&quot;tab&quot; aria-controls=&quot;std_tds&lt;?php echo $i;?&gt;&quot; aria-selected=&quot;false&quot;&gt;STD / TDS&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div class=&quot;tab-content p-3&quot; id=&quot;myTabContent&lt;?php echo $i;?&gt;&quot;&gt; &lt;div class=&quot;tab-pane fade show active&quot; id=&quot;productInfo&lt;?php echo $i;?&gt;&quot; role=&quot;tabpanel&quot; aria-labelledby=&quot;productInfo&lt;?php echo $i;?&gt;-tab&quot;&gt; &lt;h5&gt;&lt;?php echo get_the_title($id); ?&gt;&lt;/h5&gt; &lt;p&gt;&lt;?php echo get_the_content($id); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;tab-pane fade&quot; id=&quot;std_tds&lt;?php echo $i;?&gt;&quot; role=&quot;tabpanel&quot; aria-labelledby=&quot;std_tds&lt;?php echo $i;?&gt;-tab&quot;&gt; &lt;?php if(get_field('std_tds_description', $id)){ the_field('std_tds_description', $id); } else{ echo &quot;No, Content.&quot;; } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $i++; endforeach; endif; // } ?&gt; </code></pre> <p><strong>Here is a screenshot of the result:</strong></p> <p><a href="https://i.stack.imgur.com/Ku1k0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ku1k0.png" alt="enter image description here" /></a></p> <p>Can somebody point out what is the problem here. I've tried all sort of stuff but It still shows same desc. Thanks &amp; Sorry If I'm doing something stupid, still learning!</p>
[ { "answer_id": 402872, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p>Because React is unaware that anything changed, all the props are the same, and so is the state, so no updat...
2022/02/19
[ "https://wordpress.stackexchange.com/questions/402874", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/179815/" ]
I have developed a custom taxonomy post type. I have displayed categories & inside categories posts/(products). I am getting the Post title & Image as they should be (which I add), but the descriptions of all the posts are same. I have no idea why same desc keeps displaying,even though everything else is dynamic. Here is the code I am using: ``` $taxID = get_queried_object()->term_id; $args = array( 'post_type' => 'industrial_product', 'fields' => 'ids', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'industrial_product_cat', 'terms' => $taxID, 'field' => 'term_id', 'operator' => 'IN' ) ), ); $query = new WP_Query($args); if ($query->have_posts()): $i=1; foreach( $query->posts as $id ):?> <div class="row mb-4"> <div class="col-md-4 col-12"> <?php $image_palette = wp_get_attachment_image_src( get_post_thumbnail_id( $id ), 'single-post-thumbnail' ); ?> <img src="<?php echo $image_palette[0]; ?>" alt="" class="img-fluid" style="max-width:100%;"> </div> <div class="col-md-8 col-12"> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item m-0" role="presentation"> <a class="nav-link active c-2" id="productInfo<?php echo $i;?>-tab" data-toggle="tab" href="#productInfo<?php echo $i;?>" role="tab" aria-controls="productInfo<?php echo $i;?>" aria-selected="true">Product Information</a> </li> <li class="nav-item m-0" role="presentation"> <a class="nav-link c-2" id="std_tds<?php echo $i;?>-tab" data-toggle="tab" href="#std_tds<?php echo $i;?>" role="tab" aria-controls="std_tds<?php echo $i;?>" aria-selected="false">STD / TDS</a> </li> </ul> <div class="tab-content p-3" id="myTabContent<?php echo $i;?>"> <div class="tab-pane fade show active" id="productInfo<?php echo $i;?>" role="tabpanel" aria-labelledby="productInfo<?php echo $i;?>-tab"> <h5><?php echo get_the_title($id); ?></h5> <p><?php echo get_the_content($id); ?></p> </div> <div class="tab-pane fade" id="std_tds<?php echo $i;?>" role="tabpanel" aria-labelledby="std_tds<?php echo $i;?>-tab"> <?php if(get_field('std_tds_description', $id)){ the_field('std_tds_description', $id); } else{ echo "No, Content."; } ?> </div> </div> </div> </div> <?php $i++; endforeach; endif; // } ?> ``` **Here is a screenshot of the result:** [![enter image description here](https://i.stack.imgur.com/Ku1k0.png)](https://i.stack.imgur.com/Ku1k0.png) Can somebody point out what is the problem here. I've tried all sort of stuff but It still shows same desc. Thanks & Sorry If I'm doing something stupid, still learning!
**Solution found:** ``` const { __ } = wp.i18n; const { useSelect, useDispatch } = wp.data; const { PluginDocumentSettingPanel } = wp.editPost; const { CheckboxControl, PanelRow } = wp.components; const Sidebar = () => { const { postMeta } = useSelect( ( select ) => { return { postMeta: select( 'core/editor' ).getEditedPostAttribute( 'meta' ), }; } ); const { editPost } = useDispatch( 'core/editor', [ postMeta.code ] ); return( <PluginDocumentSettingPanel title={ __( 'Display Settings', 'myplugin') }> <PanelRow> <CheckboxControl label={ __( 'My Label', 'myplugin' ) } checked={ postMeta.code } onChange={ ( value ) => editPost( { meta: { code: value } } ) } /> </PanelRow> </PluginDocumentSettingPanel> ); } export default Sidebar; ```
402,946
<p>If I have declared, <code>viewScript</code> in my block.json file. Do I need to enqueue the script manually within my <code>register_block_type();</code> function also? (I didn't think it was necessary for 5.9?)</p> <p><strong>My Block.json</strong></p> <pre><code>&quot;textdomain&quot;: &quot;postcode-pricing-wizard&quot;, &quot;editorScript&quot;: &quot;file:./index.js&quot;, &quot;viewScript&quot;: &quot;file:./view.js&quot;, &quot;style&quot;: &quot;file:./style-index.css&quot; </code></pre> <p><strong>My Problem</strong></p> <p>I've enqueued the script, as shown above, I can see a completed build directory and I can also see my block within the editor.</p> <p><code>view.js</code> However, isn't loading for me on my front-end? I'm not too sure why?</p> <p>Unless I've misinterpreted the doc's <a href="https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#view-script" rel="nofollow noreferrer">Block Editor Handbook - Metadata</a></p> <pre><code>{ &quot;viewScript&quot;: &quot;file:./build/view.js&quot; } // Block type frontend script definition. // It will be enqueued only when viewing the content on the front of the site. // Since WordPress 5.9.0 (My WP Version - 5.9) </code></pre> <p>--</p> <p>Here's my <code>register_block_type()</code> function just in case it's needed.</p> <pre><code>register_block_type( PPW_DIR_PATH . '/build/pricing-wizard-block/', array( 'render_callback' =&gt; function( $attributes, $content ) { if(!is_admin()) { wp_localize_script( 'wp-block-ppw-postcode-pricing-wizard-js', 'data', ['ajax_url' =&gt; admin_url('admin-ajax.php')]); } ob_start(); include_once plugin_dir_path( __FILE__ ) . '/includes/block-editor/pricing-wizard-block/views' . '/block.php'; return ob_get_clean(); }, ) ); </code></pre>
[ { "answer_id": 402981, "author": "Lewis", "author_id": 105112, "author_profile": "https://wordpress.stackexchange.com/users/105112", "pm_score": 4, "selected": true, "text": "<p><strong>Note to self, rest-up and re-read the docs.</strong></p>\n<p>So it turns out that the answer <strong>i...
2022/02/21
[ "https://wordpress.stackexchange.com/questions/402946", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105112/" ]
If I have declared, `viewScript` in my block.json file. Do I need to enqueue the script manually within my `register_block_type();` function also? (I didn't think it was necessary for 5.9?) **My Block.json** ``` "textdomain": "postcode-pricing-wizard", "editorScript": "file:./index.js", "viewScript": "file:./view.js", "style": "file:./style-index.css" ``` **My Problem** I've enqueued the script, as shown above, I can see a completed build directory and I can also see my block within the editor. `view.js` However, isn't loading for me on my front-end? I'm not too sure why? Unless I've misinterpreted the doc's [Block Editor Handbook - Metadata](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#view-script) ``` { "viewScript": "file:./build/view.js" } // Block type frontend script definition. // It will be enqueued only when viewing the content on the front of the site. // Since WordPress 5.9.0 (My WP Version - 5.9) ``` -- Here's my `register_block_type()` function just in case it's needed. ``` register_block_type( PPW_DIR_PATH . '/build/pricing-wizard-block/', array( 'render_callback' => function( $attributes, $content ) { if(!is_admin()) { wp_localize_script( 'wp-block-ppw-postcode-pricing-wizard-js', 'data', ['ajax_url' => admin_url('admin-ajax.php')]); } ob_start(); include_once plugin_dir_path( __FILE__ ) . '/includes/block-editor/pricing-wizard-block/views' . '/block.php'; return ob_get_clean(); }, ) ); ```
**Note to self, rest-up and re-read the docs.** So it turns out that the answer **is written in the docs**, but rather obscurely. If you check out the [Frontend Enqueueing](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#frontend-enqueueing) section of the Block Editor Handbook, you'll see this statement. ``` Frontend Enqueueing #Frontend Enqueueing Starting in the WordPress 5.8 release, it is possible to instruct WordPress to enqueue scripts and styles for a block type only when rendered on the frontend. It applies to the following asset fields in the block.json file: - script - viewScript (when the block defines render_callback during registration in PHP, then the block author is responsible for enqueuing the script) - style ``` As it turns out I have defined a `render_callback` so I do need to manually enqueue my `view.js` script. You know when you're just that tired you get tunnel vision. Yeah, this was one of those times. Anyway, thanks for reading. Figured I'd answer for anyone else that came along with a similar issue.
402,999
<p>I'm trying to move my wordpress site in to different server and url. How ever i seem to have a persistent redirect loop problem. I think this is not a cache, cookie or plugin problem and I am suspecting incorrect/missing settings in .htaccess file might be the culprit. The server where i am doing the moving from, uses nginx web server and does not have .htaccess file. The hosting provider that i am trying to move into uses apache2 and does have following .htaccess file in html folder:</p> <pre><code>RewriteEngine On RewriteCond %{HTTPS} off RewriteCond %{HTTP:X-LB-Forwarded-Proto} !https RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] AddHandler application/x-httpd-php73 .php </code></pre> <p>Can somebody interpret if this .htaccess file is causing the redirect loop and/or what should be in the .htaccess file when using wordpress?</p>
[ { "answer_id": 403003, "author": "Anass", "author_id": 77227, "author_profile": "https://wordpress.stackexchange.com/users/77227", "pm_score": 1, "selected": false, "text": "<p>As WordPress documentation says about <code>.htaccess</code> file:</p>\n<blockquote>\n<p>WordPress uses this fi...
2022/02/22
[ "https://wordpress.stackexchange.com/questions/402999", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/219553/" ]
I'm trying to move my wordpress site in to different server and url. How ever i seem to have a persistent redirect loop problem. I think this is not a cache, cookie or plugin problem and I am suspecting incorrect/missing settings in .htaccess file might be the culprit. The server where i am doing the moving from, uses nginx web server and does not have .htaccess file. The hosting provider that i am trying to move into uses apache2 and does have following .htaccess file in html folder: ``` RewriteEngine On RewriteCond %{HTTPS} off RewriteCond %{HTTP:X-LB-Forwarded-Proto} !https RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] AddHandler application/x-httpd-php73 .php ``` Can somebody interpret if this .htaccess file is causing the redirect loop and/or what should be in the .htaccess file when using wordpress?
As WordPress documentation says about `.htaccess` file: > > WordPress uses this file to manipulate how Apache serves files from > its root directory, and subdirectories thereof. Most notably, WP > modifies this file to be able to handle pretty permalinks. > > > And a basic .htaccess file content will looks like this: ``` # BEGIN WordPress RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END WordPress ``` If that .htaccess that you says is inside your WordPress directory, you can rename it, and try to access you WP admin panel, go to your permalinks settings dashboard, hit without any change *Save changes* button at the bottom of that page, to regenerate a new `.htaccess` file on you installation directory automatically, with your current rewrite files rules, that matches with your website configuration. Make sure to take a backup of your previous website installation if you made some changes to that file in the past, and copy the rules in the new generated files to preserve your old changes.
403,052
<pre><code>$loop3 = new WP_Query( array( 'posts_per_page' =&gt; 10000, 'post_type' =&gt; 'volunteers', 'meta_key' =&gt; 'state', 'meta_value' =&gt; $stateselect, 'meta_compare' =&gt; '=', 'meta_key' =&gt; 'volunteer_type', 'meta_value' =&gt; 'painter', 'meta_compare' =&gt; '=', ) ); </code></pre> <p>Hello. I'm new to PHP and WordPress. I'm having trouble understanding how WP_Query works. I'm trying to get a dataset that looks like this pseudocode:</p> <p>state=$stateselect AND volunteer_type=painter</p> <p>The code above seems to be rewriting 'meta_key' and returning results from all 'states', since 'volunteer_type' appears to be overwriting. How do I ...</p> <ul> <li>Retrieve the results of two different criteria,</li> <li>do equivalent of AND between the two different meta_key criterias?</li> </ul> <p>Also, I want to sort the results by a meta_key that is not in the arguments. e.g. There's a field called 'Section' which is alpanumerical. How is sort ASC or DESC done on a field that is not part of the arguments?</p> <p>Thanks</p>
[ { "answer_id": 403003, "author": "Anass", "author_id": 77227, "author_profile": "https://wordpress.stackexchange.com/users/77227", "pm_score": 1, "selected": false, "text": "<p>As WordPress documentation says about <code>.htaccess</code> file:</p>\n<blockquote>\n<p>WordPress uses this fi...
2022/02/23
[ "https://wordpress.stackexchange.com/questions/403052", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/219604/" ]
``` $loop3 = new WP_Query( array( 'posts_per_page' => 10000, 'post_type' => 'volunteers', 'meta_key' => 'state', 'meta_value' => $stateselect, 'meta_compare' => '=', 'meta_key' => 'volunteer_type', 'meta_value' => 'painter', 'meta_compare' => '=', ) ); ``` Hello. I'm new to PHP and WordPress. I'm having trouble understanding how WP\_Query works. I'm trying to get a dataset that looks like this pseudocode: state=$stateselect AND volunteer\_type=painter The code above seems to be rewriting 'meta\_key' and returning results from all 'states', since 'volunteer\_type' appears to be overwriting. How do I ... * Retrieve the results of two different criteria, * do equivalent of AND between the two different meta\_key criterias? Also, I want to sort the results by a meta\_key that is not in the arguments. e.g. There's a field called 'Section' which is alpanumerical. How is sort ASC or DESC done on a field that is not part of the arguments? Thanks
As WordPress documentation says about `.htaccess` file: > > WordPress uses this file to manipulate how Apache serves files from > its root directory, and subdirectories thereof. Most notably, WP > modifies this file to be able to handle pretty permalinks. > > > And a basic .htaccess file content will looks like this: ``` # BEGIN WordPress RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END WordPress ``` If that .htaccess that you says is inside your WordPress directory, you can rename it, and try to access you WP admin panel, go to your permalinks settings dashboard, hit without any change *Save changes* button at the bottom of that page, to regenerate a new `.htaccess` file on you installation directory automatically, with your current rewrite files rules, that matches with your website configuration. Make sure to take a backup of your previous website installation if you made some changes to that file in the past, and copy the rules in the new generated files to preserve your old changes.
403,103
<p>I'm aware that this is a well discussed question, nevertheless I did not find any answer for my issue. I have the following code on a Wordpress page (inline, necessary for this project):</p> <pre><code>&lt;script&gt; (function ($) { $(document).ready(function () { $('.choosekurs').on('click', function() { $('textarea[name=&quot;textarea&quot;]').text($(this).attr('data-attr-package')); }); })(jQuery); &lt;/script&gt; </code></pre> <p>I also tried it the other way around:</p> <pre><code>&lt;script&gt; jQuery(document).ready( function($){ $('.choosekurs').on('click', function() { $('textarea[name=&quot;textarea&quot;]').text($(this).attr('data-attr-package')); }); }); &lt;/script&gt; </code></pre> <p>Unfortunately I still get the same error. I can see jQuery being loaded in the footer (v3.6.0 as well as 3.3.2 migrate version), so I'm not really sure what I'm doing wrong. Any help is greatly appreciated!</p>
[ { "answer_id": 403117, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 0, "selected": false, "text": "<p>If the inline <code>&lt;script&gt;</code> is in the <code>&lt;head&gt;</code> or <code>&lt;body&gt;</code> of y...
2022/02/24
[ "https://wordpress.stackexchange.com/questions/403103", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135201/" ]
I'm aware that this is a well discussed question, nevertheless I did not find any answer for my issue. I have the following code on a Wordpress page (inline, necessary for this project): ``` <script> (function ($) { $(document).ready(function () { $('.choosekurs').on('click', function() { $('textarea[name="textarea"]').text($(this).attr('data-attr-package')); }); })(jQuery); </script> ``` I also tried it the other way around: ``` <script> jQuery(document).ready( function($){ $('.choosekurs').on('click', function() { $('textarea[name="textarea"]').text($(this).attr('data-attr-package')); }); }); </script> ``` Unfortunately I still get the same error. I can see jQuery being loaded in the footer (v3.6.0 as well as 3.3.2 migrate version), so I'm not really sure what I'm doing wrong. Any help is greatly appreciated!
The error is self-explanatory. When you insert your code, jQuery has not been defined. You have to put that `script` after jQuery is loaded. If you can't change where jQuery is defined, as you say in your comment to [Pat J's answer](https://wordpress.stackexchange.com/a/403117/208483), then insert your script in the `<footer>`.
403,191
<p>I'm trying to append a query string to the end of every URL for logged in users for cache busting purposes. Here is the code I have but it doesn't seem to work. Any ideas?</p> <pre class="lang-php prettyprint-override"><code>function add_admin_qs($url){ if ( is_user_logged_in() ) { return add_query_arg('nocfcache', 'true', $url); } } if ( is_user_logged_in() ) { add_filter( 'home_url', 'add_admin_qs', 11, 1); add_filter( 'post_link', 'add_admin_qs', 10, 1); add_filter( 'page_link', 'add_admin_qs', 10, 1); add_filter( 'post_type_link', 'add_admin_qs', 10, 1); add_filter( 'category_link', 'add_admin_qs', 11, 1); add_filter( 'tag_link', 'add_admin_qs', 10, 1); add_filter( 'author_link', 'add_admin_qs', 11, 1); add_filter( 'day_link', 'add_admin_qs', 11, 1); add_filter( 'month_link', 'add_admin_qs', 11, 1); add_filter( 'year_link', 'add_admin_qs', 11, 1); } </code></pre>
[ { "answer_id": 403201, "author": "Sébastien Serre", "author_id": 62892, "author_profile": "https://wordpress.stackexchange.com/users/62892", "pm_score": 0, "selected": false, "text": "<p>Does</p>\n<pre><code>function add_admin_qs($url){\n if ( is_user_logged_in() ) {\n return a...
2022/02/27
[ "https://wordpress.stackexchange.com/questions/403191", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/219741/" ]
I'm trying to append a query string to the end of every URL for logged in users for cache busting purposes. Here is the code I have but it doesn't seem to work. Any ideas? ```php function add_admin_qs($url){ if ( is_user_logged_in() ) { return add_query_arg('nocfcache', 'true', $url); } } if ( is_user_logged_in() ) { add_filter( 'home_url', 'add_admin_qs', 11, 1); add_filter( 'post_link', 'add_admin_qs', 10, 1); add_filter( 'page_link', 'add_admin_qs', 10, 1); add_filter( 'post_type_link', 'add_admin_qs', 10, 1); add_filter( 'category_link', 'add_admin_qs', 11, 1); add_filter( 'tag_link', 'add_admin_qs', 10, 1); add_filter( 'author_link', 'add_admin_qs', 11, 1); add_filter( 'day_link', 'add_admin_qs', 11, 1); add_filter( 'month_link', 'add_admin_qs', 11, 1); add_filter( 'year_link', 'add_admin_qs', 11, 1); } ```
The problem is that I used the wrong type of quote marks. You cannot see it in my first post because apparently they were changed when I pasted in the code. [![enter image description here](https://i.stack.imgur.com/U0RNv.png)](https://i.stack.imgur.com/U0RNv.png)
403,278
<p>in a child theme of WP theme &quot;twenty-twenty-one&quot; I like to remove the original style.css of the parent theme - based in the link-tag id='twenty-twenty-one-style-css' - from the header.</p> <p>Here is the code</p> <pre><code> &lt;link rel='stylesheet' id='twenty-twenty-one-style-css' href='http://localhost/ml_wp_220228/wp-content/themes/twentytwentyone/style.css?ver=6.1.1.1646164756' media='all' /&gt; &lt;link rel='stylesheet' id='chld_thm_cfg_separate-css' href='http://localhost/ml_wp_220228/wp-content/themes/cpeach_theme_21/ctc-style.css?ver=6.1.1.1646164756' media='all' /&gt; </code></pre> <p>The first css-link-tag - id &quot;twenty-twenty-one-style-css&quot; - should be removed, only the second - my own css - should stay.</p> <p>I tried it with some coding in the function.php of the child theme.</p> <pre><code> function dequeue_css() { wp_dequeue_style('twenty-twenty-one-style'); wp_deregister_style('twenty-twenty-one-style'); } add_action('wp_enqueue_scripts','dequeue_css'); </code></pre> <p>When I tried the function with a style, I created by myself before - for instance id &quot;css-link chld_thm_cfg_separate-css&quot; - everything worked fine.</p> <p>Trying the same with the style.css of the parent - id='twenty-twenty-one-style-css' - didn't work.</p> <p>Please, can you give me a hint.</p> <p>Thanks</p> <p>Frank</p>
[ { "answer_id": 403307, "author": "FDue", "author_id": 219857, "author_profile": "https://wordpress.stackexchange.com/users/219857", "pm_score": 0, "selected": false, "text": "<p>For the moment I solved it the brutal way: I removed the link-tag with the parent-css ( &lt;link rel='styleshe...
2022/03/01
[ "https://wordpress.stackexchange.com/questions/403278", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/219827/" ]
in a child theme of WP theme "twenty-twenty-one" I like to remove the original style.css of the parent theme - based in the link-tag id='twenty-twenty-one-style-css' - from the header. Here is the code ``` <link rel='stylesheet' id='twenty-twenty-one-style-css' href='http://localhost/ml_wp_220228/wp-content/themes/twentytwentyone/style.css?ver=6.1.1.1646164756' media='all' /> <link rel='stylesheet' id='chld_thm_cfg_separate-css' href='http://localhost/ml_wp_220228/wp-content/themes/cpeach_theme_21/ctc-style.css?ver=6.1.1.1646164756' media='all' /> ``` The first css-link-tag - id "twenty-twenty-one-style-css" - should be removed, only the second - my own css - should stay. I tried it with some coding in the function.php of the child theme. ``` function dequeue_css() { wp_dequeue_style('twenty-twenty-one-style'); wp_deregister_style('twenty-twenty-one-style'); } add_action('wp_enqueue_scripts','dequeue_css'); ``` When I tried the function with a style, I created by myself before - for instance id "css-link chld\_thm\_cfg\_separate-css" - everything worked fine. Trying the same with the style.css of the parent - id='twenty-twenty-one-style-css' - didn't work. Please, can you give me a hint. Thanks Frank
The file 'style.css' is integrated via function 'twenty\_twenty\_one\_scripts' in the parent themes functions.php. ``` function twenty_twenty_one_scripts() { // Note, the is_IE global variable is defined by WordPress and is used // to detect if the current browser is internet explorer. global $is_IE, $wp_scripts; if ( $is_IE ) { // If IE 11 or below, use a flattened stylesheet with static values replacing CSS Variables. wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/assets/css/ie.css', array(), wp_get_theme()->get( 'Version' ) ); } else { // If not IE, use the standard stylesheet. wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/style.css', array(), wp_get_theme()->get( 'Version' ) ); } // RTL styles. wp_style_add_data( 'twenty-twenty-one-style', 'rtl', 'replace' ); // Print styles. wp_enqueue_style( 'twenty-twenty-one-print-style', get_template_directory_uri() . '/assets/css/print.css', array(), wp_get_theme()->get( 'Version' ), 'print' ); ... ``` To change this, disable function 'twenty\_twenty\_one\_scripts' in the child themes function.php ``` function remove_my_action() { remove_action( 'wp_enqueue_scripts', 'twenty_twenty_one_scripts' ); } add_action( 'wp_head', 'remove_my_action' ); ``` Copy the Code of function 'twenty\_twenty\_one\_scripts' into the child themes function.php, rename it and remove (or comment out) the first section of the function: ``` function my_twenty_twenty_one_scripts() { // Note, the is_IE global variable is defined by WordPress and is used // to detect if the current browser is internet explorer. global $is_IE, $wp_scripts; /* if ( $is_IE ) { // If IE 11 or below, use a flattened stylesheet with static values replacing CSS Variables. wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/assets/css/ie.css', array(), wp_get_theme()->get( 'Version' ) ); } else { // If not IE, use the standard stylesheet. wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/style.css', array(), wp_get_theme()->get( 'Version' ) ); } */ // RTL styles. wp_style_add_data( 'twenty-twenty-one-style', 'rtl', 'replace' ); // Print styles. wp_enqueue_style( 'twenty-twenty-one-print-style', get_template_directory_uri() . '/assets/css/print.css', array(), wp_get_theme()->get( 'Version' ), 'print' ); ... ``` Activate the new function 'my\_twenty\_twenty\_one\_scripts' in child themes function.php ``` add_action( 'wp_enqueue_scripts', 'my_twenty_twenty_one_scripts' ); ```
403,327
<p>In gutenberg/block-editor, how can I check whether I've already registered a block type? Is there a function I can use? Searching through the Block Editor Handbook I couldn't see a function to check this.</p> <p>An example of what I am trying to do is below:</p> <pre><code>class My_Block { public function __construct() { if ( ! SOME_FUNCTION_block_exists('foo/column') ) { register_block_type( 'foo/column', my_args ); } } } </code></pre>
[ { "answer_id": 403399, "author": "Welcher", "author_id": 27210, "author_profile": "https://wordpress.stackexchange.com/users/27210", "pm_score": 2, "selected": false, "text": "<p><strong><strong>EDIT</strong></strong></p>\n<p>I just realized you're doing this on the PHP side. There is a ...
2022/03/03
[ "https://wordpress.stackexchange.com/questions/403327", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75260/" ]
In gutenberg/block-editor, how can I check whether I've already registered a block type? Is there a function I can use? Searching through the Block Editor Handbook I couldn't see a function to check this. An example of what I am trying to do is below: ``` class My_Block { public function __construct() { if ( ! SOME_FUNCTION_block_exists('foo/column') ) { register_block_type( 'foo/column', my_args ); } } } ```
****EDIT**** I just realized you're doing this on the PHP side. There is a class called `WP_Block_Type_Registry` that you can use to see what is already registered: ``` $registry = WP_Block_Type_Registry::get_instance(); if ( ! $registry->get_registered( 'foo/column' ) ) { // YOUR CODE } ``` Gutenberg should fire a console error if a block has already been registered. See the `registerBlockType` src [here](https://github.com/WordPress/gutenberg/blob/trunk/packages/blocks/src/api/registration.js#L247).
403,342
<p>I would like to ask if there is a way to automatically delay emails after completion?</p> <p>I want these emails to arrive 1-2 hours later.</p> <p>Is there a snippet of code for this?</p> <p>Thank you!</p>
[ { "answer_id": 403343, "author": "tieum", "author_id": 171342, "author_profile": "https://wordpress.stackexchange.com/users/171342", "pm_score": 0, "selected": false, "text": "<p>not tested but maybe you could simply use sleep using wpcf7_before_send_email</p>\n<p>something like this:</p...
2022/03/03
[ "https://wordpress.stackexchange.com/questions/403342", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/218233/" ]
I would like to ask if there is a way to automatically delay emails after completion? I want these emails to arrive 1-2 hours later. Is there a snippet of code for this? Thank you!
not tested but maybe you could simply use sleep using wpcf7\_before\_send\_email something like this: ``` add_action("wpcf7_before_send_mail", "wpcf7_pause_send"); function wpcf7_pause_send($cf7) { sleep(3600); } ```
403,379
<p>I am trying to workout the best way to do a slightly abnormal orderby.</p> <p>I have a query that returns 2 types (Post and Event). As expected by default it orders both, together, by publish date.</p> <p>What I want is, posts to be ordered by publish date, events by <code>event-&gt;start_date</code></p> <p>I could just get them, loop over them and manually sort myself, but that seems counter intuitive.</p> <p>Any help much appreceiated.</p> <p>Cheers</p> <p>Drogo</p>
[ { "answer_id": 403343, "author": "tieum", "author_id": 171342, "author_profile": "https://wordpress.stackexchange.com/users/171342", "pm_score": 0, "selected": false, "text": "<p>not tested but maybe you could simply use sleep using wpcf7_before_send_email</p>\n<p>something like this:</p...
2022/03/04
[ "https://wordpress.stackexchange.com/questions/403379", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/194372/" ]
I am trying to workout the best way to do a slightly abnormal orderby. I have a query that returns 2 types (Post and Event). As expected by default it orders both, together, by publish date. What I want is, posts to be ordered by publish date, events by `event->start_date` I could just get them, loop over them and manually sort myself, but that seems counter intuitive. Any help much appreceiated. Cheers Drogo
not tested but maybe you could simply use sleep using wpcf7\_before\_send\_email something like this: ``` add_action("wpcf7_before_send_mail", "wpcf7_pause_send"); function wpcf7_pause_send($cf7) { sleep(3600); } ```
403,447
<p>I have made checkboxes to every post in post list.</p> <p><strong>Question:</strong><br> How can I change the the position for the new column.<br> Now it`s at the right side of the post list. After &quot;Date&quot;.<br> How can I move it example before the title column ?<br><br></p> <p>The files for the plugin is here, if you would take a look.<br> <a href="https://github.com/bjovaar/terplugin" rel="nofollow noreferrer">https://github.com/bjovaar/terplugin</a></p> <p><br><br></p> <p><a href="https://i.stack.imgur.com/C5DuE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C5DuE.jpg" alt="Admin post list" /></a></p>
[ { "answer_id": 403343, "author": "tieum", "author_id": 171342, "author_profile": "https://wordpress.stackexchange.com/users/171342", "pm_score": 0, "selected": false, "text": "<p>not tested but maybe you could simply use sleep using wpcf7_before_send_email</p>\n<p>something like this:</p...
2022/03/06
[ "https://wordpress.stackexchange.com/questions/403447", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/219954/" ]
I have made checkboxes to every post in post list. **Question:** How can I change the the position for the new column. Now it`s at the right side of the post list. After "Date". How can I move it example before the title column ? The files for the plugin is here, if you would take a look. <https://github.com/bjovaar/terplugin> [![Admin post list](https://i.stack.imgur.com/C5DuE.jpg)](https://i.stack.imgur.com/C5DuE.jpg)
not tested but maybe you could simply use sleep using wpcf7\_before\_send\_email something like this: ``` add_action("wpcf7_before_send_mail", "wpcf7_pause_send"); function wpcf7_pause_send($cf7) { sleep(3600); } ```
403,572
<p>I want to apply following 2 case :</p> <p>If User not logged in and cart has product: Then redirect user to login and after login redirect to checkout page. I have used a code but it redirecting to the current page i.e if we check out from home page it will redirect to home page itself after login, if it is from shop page it will redirect to shop page. I want to redirect to checkout page only. My code</p> <pre><code>add_action('template_redirect','check_if_logged_in'); function check_if_logged_in() { $pageid = get_option( 'woocommerce_checkout_page_id' ); if(!is_user_logged_in() &amp;&amp; is_page($pageid)) { $url = add_query_arg( 'redirect_to', get_permalink($pagid), site_url('/my-account/') // your my account url ); wp_redirect($url); exit; } if(is_user_logged_in()) { if(is_page(get_option( 'woocommerce_myaccount_page_id' ))) { $redirect = $_GET['redirect_to']; if (isset($redirect)) { echo '&lt;script&gt;window.location.href = &quot;'.$redirect.'&quot;;&lt;/script&gt;'; } } } } </code></pre>
[ { "answer_id": 403343, "author": "tieum", "author_id": 171342, "author_profile": "https://wordpress.stackexchange.com/users/171342", "pm_score": 0, "selected": false, "text": "<p>not tested but maybe you could simply use sleep using wpcf7_before_send_email</p>\n<p>something like this:</p...
2022/03/10
[ "https://wordpress.stackexchange.com/questions/403572", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/220122/" ]
I want to apply following 2 case : If User not logged in and cart has product: Then redirect user to login and after login redirect to checkout page. I have used a code but it redirecting to the current page i.e if we check out from home page it will redirect to home page itself after login, if it is from shop page it will redirect to shop page. I want to redirect to checkout page only. My code ``` add_action('template_redirect','check_if_logged_in'); function check_if_logged_in() { $pageid = get_option( 'woocommerce_checkout_page_id' ); if(!is_user_logged_in() && is_page($pageid)) { $url = add_query_arg( 'redirect_to', get_permalink($pagid), site_url('/my-account/') // your my account url ); wp_redirect($url); exit; } if(is_user_logged_in()) { if(is_page(get_option( 'woocommerce_myaccount_page_id' ))) { $redirect = $_GET['redirect_to']; if (isset($redirect)) { echo '<script>window.location.href = "'.$redirect.'";</script>'; } } } } ```
not tested but maybe you could simply use sleep using wpcf7\_before\_send\_email something like this: ``` add_action("wpcf7_before_send_mail", "wpcf7_pause_send"); function wpcf7_pause_send($cf7) { sleep(3600); } ```
403,573
<p>I have created a new page on my WordPress site to test the paypal payment flow. I have subscription based products. Attached code is for the paypal subscription button code.</p> <pre><code> &lt;div id=&quot;paypal-button-container-P-91F08612M1573283BMIUWMOA&quot;&gt;&lt;/div&gt; &lt;script src=&quot;https://www.paypal.com/sdk/js?client-id=AfGWAPJxdGbCj7b51a2mpoZQYI5y63txxxxxxxxIe1UDh2Vxcr05AFJxxxxNSCNDf8y-xopaJ6&amp;vault=true&amp;intent=subscription&quot; data-sdk-integration-source=&quot;button-factory&quot;&gt;&lt;/script&gt; &lt;script&gt; paypal.Buttons({ style: { shape: 'rect', color: 'gold', layout: 'vertical', label: 'subscribe' }, createSubscription: function(data, actions) { return actions.subscription.create({ /* Creates the subscription */ plan_id: 'P-91xxxxxxxxxxxxxxx' }); }, onApprove: function(data, actions) { alert(data.subscriptionID); // You can add optional success message for the subscriber here } }).render('#paypal-button-container-P-91F08612M1573283BMIUWMOA'); // Renders the PayPal button &lt;/script&gt; </code></pre> <p>My outcome was success and it shows this message. <a href="https://i.stack.imgur.com/CdanL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CdanL.png" alt="Click here for the image" /></a></p> <p>On completion, I just get an order number pop-up and then it stays on the same page. (check the image) What I want now is to redirect my user to a specific page after successful payment. I already set the URL auto return path from paypal but it won't working. See my paypal configuration from the below image. <a href="https://i.stack.imgur.com/koNcx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/koNcx.png" alt="Paypal config" /></a></p> <p>How can I redirect user by adjusting the code? Will I be able to make that change?</p>
[ { "answer_id": 403343, "author": "tieum", "author_id": 171342, "author_profile": "https://wordpress.stackexchange.com/users/171342", "pm_score": 0, "selected": false, "text": "<p>not tested but maybe you could simply use sleep using wpcf7_before_send_email</p>\n<p>something like this:</p...
2022/03/10
[ "https://wordpress.stackexchange.com/questions/403573", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/218901/" ]
I have created a new page on my WordPress site to test the paypal payment flow. I have subscription based products. Attached code is for the paypal subscription button code. ``` <div id="paypal-button-container-P-91F08612M1573283BMIUWMOA"></div> <script src="https://www.paypal.com/sdk/js?client-id=AfGWAPJxdGbCj7b51a2mpoZQYI5y63txxxxxxxxIe1UDh2Vxcr05AFJxxxxNSCNDf8y-xopaJ6&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script> <script> paypal.Buttons({ style: { shape: 'rect', color: 'gold', layout: 'vertical', label: 'subscribe' }, createSubscription: function(data, actions) { return actions.subscription.create({ /* Creates the subscription */ plan_id: 'P-91xxxxxxxxxxxxxxx' }); }, onApprove: function(data, actions) { alert(data.subscriptionID); // You can add optional success message for the subscriber here } }).render('#paypal-button-container-P-91F08612M1573283BMIUWMOA'); // Renders the PayPal button </script> ``` My outcome was success and it shows this message. [![Click here for the image](https://i.stack.imgur.com/CdanL.png)](https://i.stack.imgur.com/CdanL.png) On completion, I just get an order number pop-up and then it stays on the same page. (check the image) What I want now is to redirect my user to a specific page after successful payment. I already set the URL auto return path from paypal but it won't working. See my paypal configuration from the below image. [![Paypal config](https://i.stack.imgur.com/koNcx.png)](https://i.stack.imgur.com/koNcx.png) How can I redirect user by adjusting the code? Will I be able to make that change?
not tested but maybe you could simply use sleep using wpcf7\_before\_send\_email something like this: ``` add_action("wpcf7_before_send_mail", "wpcf7_pause_send"); function wpcf7_pause_send($cf7) { sleep(3600); } ```
403,666
<p>I add on my wordpress a function to save a json file , when a post is saved on admin. Basically i get the title ( that will be a json string ) and convert it to JSON. From that JSON i need to extract the id , to use like a name of the file created. But when i try to get the id , i have an empty value.</p> <pre><code> add_action('save_post', function($ID, $post) { // The $ID of post is different from ID that i have in post_title string $encoded_post = wp_json_encode( $post-&gt;post_title ); $post_decode = json_decode( $encoded_post, true ); // Get the id from decoded data, converted from string to json $data = json_decode( $post-&gt;post_title ); // ID of json given $ID = $data-&gt;id; // Dir to save the file $dir = plugin_dir_path( __DIR__ ); // Post name and ext $file_path = $ID .'.json'; //&quot;$post_name'.json'&quot;; file_put_contents($dir.$file_path, $post_decode); }, 10, 2); </code></pre>
[ { "answer_id": 403667, "author": "Raja Aman Ullah", "author_id": 172088, "author_profile": "https://wordpress.stackexchange.com/users/172088", "pm_score": -1, "selected": false, "text": "<pre class=\"lang-php prettyprint-override\"><code>add_action('save_post', function($ID, $post) {\n ...
2022/03/12
[ "https://wordpress.stackexchange.com/questions/403666", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128870/" ]
I add on my wordpress a function to save a json file , when a post is saved on admin. Basically i get the title ( that will be a json string ) and convert it to JSON. From that JSON i need to extract the id , to use like a name of the file created. But when i try to get the id , i have an empty value. ``` add_action('save_post', function($ID, $post) { // The $ID of post is different from ID that i have in post_title string $encoded_post = wp_json_encode( $post->post_title ); $post_decode = json_decode( $encoded_post, true ); // Get the id from decoded data, converted from string to json $data = json_decode( $post->post_title ); // ID of json given $ID = $data->id; // Dir to save the file $dir = plugin_dir_path( __DIR__ ); // Post name and ext $file_path = $ID .'.json'; //"$post_name'.json'"; file_put_contents($dir.$file_path, $post_decode); }, 10, 2); ```
`json_encode` takes an array/object and turns it into a JSON string. `json_decode` takes a JSON string and turns it into a PHP array/object/etc With this in mind, we can see some critical mistakes are made in the code, caused by muddling up the two. 1. You're taking a string of JSON and JSON encoding it, aka double JSON encoding it, which doesn't make sense. Think of it like doing this: `json_encode( json_encode( ['ID' => 2] ) )` 2. You're then immediatley decoding it, so `$post_decode` and `$post->title` are the same, it's like turning on the light switch then turning it off everytime you go past, it's a non-operation, nothing is achieved 3. Then, for some reason `json_encode` is called, but it's called on a nonexistant value. Remember, `$post_decode` is not an array/object, it's a JSON string that hasn't been decoded, what you're doing is the same as `$foo = 'bar'; echo $foo->ID;`. Expect this to generate huge amounts of PHP notices and warnings in your PHP error log. This is all very confusing and unnecessary. Instead take your post title and decode it from JSON into an object: ```php $data = json_decode( $post->post_title ); ``` Then use it: ```php $ID = $data->id; ```
403,740
<p>I wrote a little custom shortcode and when I try to use it in a custom post it won't take into account the parameter I set up.</p> <p><strong>What it's supposed to do</strong></p> <p>The shortcode is supposed to take a custom post ID into parameter and display a div that use the thumbnail of this post as a background if there's one, and then display the title of the post inside that DIV. Pretty simple stuff.</p> <p><strong>What it does</strong></p> <p>In front the shortcode appears to work as intended but don't take ID parameter into account and use current post ID to execute the function instead. The weird thing is that when I put a default value &quot;4075&quot; for $ID in the array it works fine. It just won't take the parameter into account when I set it with <code>[lire-aussi ID=&quot;4075&quot;]</code></p> <p><strong>The code</strong></p> <pre class="lang-php prettyprint-override"><code>function shortcode_lire_aussi( $atts ){ extract( shortcode_atts( array( 'ID' =&gt; '', ), $atts)); $title= get_the_title($ID); $linkURL= get_permalink($ID); if(has_post_thumbnail($ID)){ $background = get_the_post_thumbnail_url( $ID ); $output= ' &lt;div style = &quot;background-image : url('.$background.');&quot;&gt; &lt;p&gt; &lt;a href=&quot;'.$linkURL.'&quot;&gt;'.$title.'&lt;/a&gt; &lt;/p&gt; &lt;/div&gt;'; } else{ $output= ' &lt;div style = &quot;background-color : black;&quot;&gt; &lt;p&gt; &lt;a href=&quot;'.$linkURL.'&quot;&gt;'.$title.'&lt;/a&gt; &lt;/p&gt; &lt;/div&gt;'; } return $output; } add_shortcode('lire-aussi', 'shortcode_lire_aussi'); </code></pre> <p>I'm not really familiar with PHP and my knowledge of that language is very limited, I'm clearly missing something but can't figure what.</p>
[ { "answer_id": 403667, "author": "Raja Aman Ullah", "author_id": 172088, "author_profile": "https://wordpress.stackexchange.com/users/172088", "pm_score": -1, "selected": false, "text": "<pre class=\"lang-php prettyprint-override\"><code>add_action('save_post', function($ID, $post) {\n ...
2022/03/15
[ "https://wordpress.stackexchange.com/questions/403740", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/220306/" ]
I wrote a little custom shortcode and when I try to use it in a custom post it won't take into account the parameter I set up. **What it's supposed to do** The shortcode is supposed to take a custom post ID into parameter and display a div that use the thumbnail of this post as a background if there's one, and then display the title of the post inside that DIV. Pretty simple stuff. **What it does** In front the shortcode appears to work as intended but don't take ID parameter into account and use current post ID to execute the function instead. The weird thing is that when I put a default value "4075" for $ID in the array it works fine. It just won't take the parameter into account when I set it with `[lire-aussi ID="4075"]` **The code** ```php function shortcode_lire_aussi( $atts ){ extract( shortcode_atts( array( 'ID' => '', ), $atts)); $title= get_the_title($ID); $linkURL= get_permalink($ID); if(has_post_thumbnail($ID)){ $background = get_the_post_thumbnail_url( $ID ); $output= ' <div style = "background-image : url('.$background.');"> <p> <a href="'.$linkURL.'">'.$title.'</a> </p> </div>'; } else{ $output= ' <div style = "background-color : black;"> <p> <a href="'.$linkURL.'">'.$title.'</a> </p> </div>'; } return $output; } add_shortcode('lire-aussi', 'shortcode_lire_aussi'); ``` I'm not really familiar with PHP and my knowledge of that language is very limited, I'm clearly missing something but can't figure what.
`json_encode` takes an array/object and turns it into a JSON string. `json_decode` takes a JSON string and turns it into a PHP array/object/etc With this in mind, we can see some critical mistakes are made in the code, caused by muddling up the two. 1. You're taking a string of JSON and JSON encoding it, aka double JSON encoding it, which doesn't make sense. Think of it like doing this: `json_encode( json_encode( ['ID' => 2] ) )` 2. You're then immediatley decoding it, so `$post_decode` and `$post->title` are the same, it's like turning on the light switch then turning it off everytime you go past, it's a non-operation, nothing is achieved 3. Then, for some reason `json_encode` is called, but it's called on a nonexistant value. Remember, `$post_decode` is not an array/object, it's a JSON string that hasn't been decoded, what you're doing is the same as `$foo = 'bar'; echo $foo->ID;`. Expect this to generate huge amounts of PHP notices and warnings in your PHP error log. This is all very confusing and unnecessary. Instead take your post title and decode it from JSON into an object: ```php $data = json_decode( $post->post_title ); ``` Then use it: ```php $ID = $data->id; ```
403,753
<p>This is happening with a fresh, new WordPress install. But all you need to do is look at the crazy <a href="https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/functions.php#L1671" rel="nofollow noreferrer">do_robots()</a> function, which outputs the following...</p> <pre><code>User-agent: * Disallow: /wp-admin/ Allow: /wp-admin/admin-ajax.php Sitemap: https://knowingart.com/wp-sitemap.xml </code></pre> <p>Sending robots to &quot;wp-admin&quot; (by default) makes no sense:</p> <ol> <li>Why would I send random robots into my admin directory?! The admin directory is for me, and me alone. Robots/crawlers should not be in my admin directory doing anything.</li> <li>Why would I DOS attack myself by sending robots to an admin script?</li> <li>If I was a bot developer, I might (wrongly) interpret this &quot;allow&quot; as negation of the disallow, because the allow comes after the disallow and it's the same directory. Why does robots.txt contradict itself here?</li> <li>This weird (default) robots.txt seems to break DuckDuckGo. <a href="https://duckduckgo.com/?q=ferodynamics&amp;ia=web" rel="nofollow noreferrer">For example</a> the top search result is my wp-admin directory?! It appears DuckDuckGo read my robots.txt, went into wp-admin because robots.txt told it to go there, and that is the wrong directory. Was DDG's crawler confused by the weird robots.txt file? Now I'm thinking DDG crawled my blog before any content was available, and just hasn't updated yet, that seems to be a more likely explanation.</li> </ol> <p>Why does WordPress send robot crawlers to an admin directory that has no content?! It makes no sense to me, which is why I am here trying to figure it out. I can only imagine the author of this do_robots() code doesn't understand the purpose of robots.txt</p>
[ { "answer_id": 403758, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>First: have a read-up on <a href=\"https://blog.hubspot.com/website/robots-txt-wordpress\" rel=\"nofollow noref...
2022/03/15
[ "https://wordpress.stackexchange.com/questions/403753", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3453/" ]
This is happening with a fresh, new WordPress install. But all you need to do is look at the crazy [do\_robots()](https://core.trac.wordpress.org/browser/tags/5.9/src/wp-includes/functions.php#L1671) function, which outputs the following... ``` User-agent: * Disallow: /wp-admin/ Allow: /wp-admin/admin-ajax.php Sitemap: https://knowingart.com/wp-sitemap.xml ``` Sending robots to "wp-admin" (by default) makes no sense: 1. Why would I send random robots into my admin directory?! The admin directory is for me, and me alone. Robots/crawlers should not be in my admin directory doing anything. 2. Why would I DOS attack myself by sending robots to an admin script? 3. If I was a bot developer, I might (wrongly) interpret this "allow" as negation of the disallow, because the allow comes after the disallow and it's the same directory. Why does robots.txt contradict itself here? 4. This weird (default) robots.txt seems to break DuckDuckGo. [For example](https://duckduckgo.com/?q=ferodynamics&ia=web) the top search result is my wp-admin directory?! It appears DuckDuckGo read my robots.txt, went into wp-admin because robots.txt told it to go there, and that is the wrong directory. Was DDG's crawler confused by the weird robots.txt file? Now I'm thinking DDG crawled my blog before any content was available, and just hasn't updated yet, that seems to be a more likely explanation. Why does WordPress send robot crawlers to an admin directory that has no content?! It makes no sense to me, which is why I am here trying to figure it out. I can only imagine the author of this do\_robots() code doesn't understand the purpose of robots.txt
First: have a read-up on [robots.txt](https://blog.hubspot.com/website/robots-txt-wordpress), if you haven't. Another good reference is [this one from Yoast](https://yoast.com/ultimate-guide-robots-txt/). The sample you posted: ``` User-agent: * Disallow: /wp-admin/ Allow: /wp-admin/admin-ajax.php Sitemap: https://knowingart.com/wp-sitemap.xml ``` ...tells all user-agents (ie, all crawlers) that they are *not allowed* to crawl *anything* in your `wp-admin` directory *except* `/wp-admin/admin-ajax.php`, [which is required by WordPress for properly-functioning AJAX](https://developer.wordpress.org/plugins/javascript/ajax/#url). It's *not* telling robots to go to your `/wp-admin/` directory; it's telling them they're unwelcome there (except for the AJAX requirement). As for your question #4, I'm afraid I don't have an answer to that one.
403,759
<p>I'm on wordpress 5.9+ and creating CPT's has become relatively easy. But having a landing page for a CPT is new grounds for me.</p> <ul> <li>I have successfully created a custom post type called Career Finders</li> <li>I have created an archive template for this CPT, named <code>archive-career-finders.php</code></li> <li>I can see that template being used from the browser when I go to my local URL <code>my-site.com/career-finders</code></li> </ul> <p>But how do we create either a page or post from WP-admin, that connects to this archive template, and &quot;is&quot; this landing page for the CPT?</p> <p>I want editors to be able to add content to this landing page through wp-admin. This is where I am stuck...</p> <p><strong>My initial thought:</strong> On this new archive template, do I use the WP-Query loop to get that &quot;1&quot; page or post that represents the content needed to be displayed here, and also have that page set to Private? Is that the way to go?</p> <p>Many thanks!</p>
[ { "answer_id": 403758, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>First: have a read-up on <a href=\"https://blog.hubspot.com/website/robots-txt-wordpress\" rel=\"nofollow noref...
2022/03/15
[ "https://wordpress.stackexchange.com/questions/403759", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98671/" ]
I'm on wordpress 5.9+ and creating CPT's has become relatively easy. But having a landing page for a CPT is new grounds for me. * I have successfully created a custom post type called Career Finders * I have created an archive template for this CPT, named `archive-career-finders.php` * I can see that template being used from the browser when I go to my local URL `my-site.com/career-finders` But how do we create either a page or post from WP-admin, that connects to this archive template, and "is" this landing page for the CPT? I want editors to be able to add content to this landing page through wp-admin. This is where I am stuck... **My initial thought:** On this new archive template, do I use the WP-Query loop to get that "1" page or post that represents the content needed to be displayed here, and also have that page set to Private? Is that the way to go? Many thanks!
First: have a read-up on [robots.txt](https://blog.hubspot.com/website/robots-txt-wordpress), if you haven't. Another good reference is [this one from Yoast](https://yoast.com/ultimate-guide-robots-txt/). The sample you posted: ``` User-agent: * Disallow: /wp-admin/ Allow: /wp-admin/admin-ajax.php Sitemap: https://knowingart.com/wp-sitemap.xml ``` ...tells all user-agents (ie, all crawlers) that they are *not allowed* to crawl *anything* in your `wp-admin` directory *except* `/wp-admin/admin-ajax.php`, [which is required by WordPress for properly-functioning AJAX](https://developer.wordpress.org/plugins/javascript/ajax/#url). It's *not* telling robots to go to your `/wp-admin/` directory; it's telling them they're unwelcome there (except for the AJAX requirement). As for your question #4, I'm afraid I don't have an answer to that one.
403,781
<p>In WordPress I make SQL-requests to the database but LIKE request doesn't work correctly.</p> <p>Actial value of <code>meta_value</code> field in the database is such string:</p> <pre><code>a:1:{i:0;s:9:&quot;full-time&quot;;} </code></pre> <p>if I make this request all works fine:</p> <pre><code>$query = $wpdb-&gt;prepare(&quot;SELECT meta_value FROM wp_postmeta WHERE meta_key = 'job_bm_job_type' AND meta_value LIKE '%a%' LIMIT 1&quot;); </code></pre> <p>But if try to use other text in LIKE part I don't get any results</p> <pre><code>$query = $wpdb-&gt;prepare(&quot;SELECT meta_value FROM wp_postmeta WHERE meta_key = 'job_bm_job_type' AND meta_value LIKE '%full%' LIMIT 1&quot;); </code></pre> <p>Ideally, LIKE request should search through data of all the string. But it seems like it doesn't search inside the content of square brackets <code>{ }</code></p> <p>What I miss here? How to search through any elements in this field?</p>
[ { "answer_id": 403758, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>First: have a read-up on <a href=\"https://blog.hubspot.com/website/robots-txt-wordpress\" rel=\"nofollow noref...
2022/03/16
[ "https://wordpress.stackexchange.com/questions/403781", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128503/" ]
In WordPress I make SQL-requests to the database but LIKE request doesn't work correctly. Actial value of `meta_value` field in the database is such string: ``` a:1:{i:0;s:9:"full-time";} ``` if I make this request all works fine: ``` $query = $wpdb->prepare("SELECT meta_value FROM wp_postmeta WHERE meta_key = 'job_bm_job_type' AND meta_value LIKE '%a%' LIMIT 1"); ``` But if try to use other text in LIKE part I don't get any results ``` $query = $wpdb->prepare("SELECT meta_value FROM wp_postmeta WHERE meta_key = 'job_bm_job_type' AND meta_value LIKE '%full%' LIMIT 1"); ``` Ideally, LIKE request should search through data of all the string. But it seems like it doesn't search inside the content of square brackets `{ }` What I miss here? How to search through any elements in this field?
First: have a read-up on [robots.txt](https://blog.hubspot.com/website/robots-txt-wordpress), if you haven't. Another good reference is [this one from Yoast](https://yoast.com/ultimate-guide-robots-txt/). The sample you posted: ``` User-agent: * Disallow: /wp-admin/ Allow: /wp-admin/admin-ajax.php Sitemap: https://knowingart.com/wp-sitemap.xml ``` ...tells all user-agents (ie, all crawlers) that they are *not allowed* to crawl *anything* in your `wp-admin` directory *except* `/wp-admin/admin-ajax.php`, [which is required by WordPress for properly-functioning AJAX](https://developer.wordpress.org/plugins/javascript/ajax/#url). It's *not* telling robots to go to your `/wp-admin/` directory; it's telling them they're unwelcome there (except for the AJAX requirement). As for your question #4, I'm afraid I don't have an answer to that one.
403,800
<p>There are loads of articles out there on how to completely disable Wordpress RSS feeds, my configuration (<code>functions.php</code>) is:</p> <pre><code>function disable_feed() { wp_die( 'You Died' , 200 ); } add_action('do_feed', 'disable_feed', 1); add_action('do_feed_rdf', 'disable_feed', 1); add_action('do_feed_rss', 'disable_feed', 1); add_action('do_feed_rss2', 'disable_feed', 1); add_action('do_feed_atom', 'disable_feed', 1); add_action('do_feed_rss2_comments', 'disable_feed', 1); add_action('do_feed_atom_comments', 'disable_feed', 1); </code></pre> <p>But instead of getting a nice-looking HTML page with the bordered content normally associated with the <code>wp_die()</code> function, when browsing to https://website/feed/ I'm getting this knarley page back:</p> <p><a href="https://i.stack.imgur.com/RkkIg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RkkIg.png" alt="enter image description here" /></a></p> <p>Anyone know what I'm doing wrong?</p> <p>David.</p>
[ { "answer_id": 403758, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>First: have a read-up on <a href=\"https://blog.hubspot.com/website/robots-txt-wordpress\" rel=\"nofollow noref...
2022/03/16
[ "https://wordpress.stackexchange.com/questions/403800", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167472/" ]
There are loads of articles out there on how to completely disable Wordpress RSS feeds, my configuration (`functions.php`) is: ``` function disable_feed() { wp_die( 'You Died' , 200 ); } add_action('do_feed', 'disable_feed', 1); add_action('do_feed_rdf', 'disable_feed', 1); add_action('do_feed_rss', 'disable_feed', 1); add_action('do_feed_rss2', 'disable_feed', 1); add_action('do_feed_atom', 'disable_feed', 1); add_action('do_feed_rss2_comments', 'disable_feed', 1); add_action('do_feed_atom_comments', 'disable_feed', 1); ``` But instead of getting a nice-looking HTML page with the bordered content normally associated with the `wp_die()` function, when browsing to https://website/feed/ I'm getting this knarley page back: [![enter image description here](https://i.stack.imgur.com/RkkIg.png)](https://i.stack.imgur.com/RkkIg.png) Anyone know what I'm doing wrong? David.
First: have a read-up on [robots.txt](https://blog.hubspot.com/website/robots-txt-wordpress), if you haven't. Another good reference is [this one from Yoast](https://yoast.com/ultimate-guide-robots-txt/). The sample you posted: ``` User-agent: * Disallow: /wp-admin/ Allow: /wp-admin/admin-ajax.php Sitemap: https://knowingart.com/wp-sitemap.xml ``` ...tells all user-agents (ie, all crawlers) that they are *not allowed* to crawl *anything* in your `wp-admin` directory *except* `/wp-admin/admin-ajax.php`, [which is required by WordPress for properly-functioning AJAX](https://developer.wordpress.org/plugins/javascript/ajax/#url). It's *not* telling robots to go to your `/wp-admin/` directory; it's telling them they're unwelcome there (except for the AJAX requirement). As for your question #4, I'm afraid I don't have an answer to that one.
403,838
<p>I created a custom post:</p> <pre><code>/*= Add Custom Post Type: Board Members /****************************************************/ add_action( 'init', 'create_board_posttype' ); function create_board_posttype() { register_post_type( 'board', array( 'labels' =&gt; array( 'name' =&gt; __( 'Board Members' ), 'singular_name' =&gt; __( 'Board Member' ), 'add_new_item' =&gt; __( 'Add New Board Member' ), 'edit_item' =&gt; __( 'Edit Board Member' ), 'new_item' =&gt; __( 'New Board Member' ), 'view_item' =&gt; __( 'View Board Member' ), 'search_items' =&gt; __( 'Search Board Members' ), 'not_found' =&gt; __( 'No Board Members Found' ), 'archives' =&gt; __( 'Board Members Archives' ), 'insert_into_item' =&gt; __( 'Insert into Board Member' ), ), 'public' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'custom-fields', 'thumbnail', 'page-attributes' ), 'has_archive' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'board'), ) ); } </code></pre> <p>I then went and added 10 posts successfully and they are displaying on the frontend fine.</p> <p>Fast forward 4 weeks and I went in to edit a post but I am seeing &quot;No board members found&quot;.</p> <p>It shows that there are 10 Board Members published by actually displays none in the list:</p> <pre><code>All (10) | Published (10) No Board Members Found </code></pre> <p>Clearly WP knows there are board members (All (10)) but it wont show them... I don't know where to start?</p> <p>Ok, I found the issue but I don't understand why.</p> <p>I have another custom_post_type: <code>jobs</code></p> <p>On the frontend I try to filter jobs within last x days. When I remove this code, the Board Members re-appear:</p> <pre><code>add_action( 'pre_get_posts', 'custom_query_vars' ); function custom_query_vars( $query ) { if ( $query-&gt;is_main_query() ) { if ( is_archive('job') ) { $days = get_field('job_expiry_days', 'option'); $query-&gt;set( 'date_query', array( 'column' =&gt; 'post_date', 'after' =&gt; '- '.$days.' days' ) ); } } return $query; } </code></pre>
[ { "answer_id": 403758, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>First: have a read-up on <a href=\"https://blog.hubspot.com/website/robots-txt-wordpress\" rel=\"nofollow noref...
2022/03/17
[ "https://wordpress.stackexchange.com/questions/403838", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10368/" ]
I created a custom post: ``` /*= Add Custom Post Type: Board Members /****************************************************/ add_action( 'init', 'create_board_posttype' ); function create_board_posttype() { register_post_type( 'board', array( 'labels' => array( 'name' => __( 'Board Members' ), 'singular_name' => __( 'Board Member' ), 'add_new_item' => __( 'Add New Board Member' ), 'edit_item' => __( 'Edit Board Member' ), 'new_item' => __( 'New Board Member' ), 'view_item' => __( 'View Board Member' ), 'search_items' => __( 'Search Board Members' ), 'not_found' => __( 'No Board Members Found' ), 'archives' => __( 'Board Members Archives' ), 'insert_into_item' => __( 'Insert into Board Member' ), ), 'public' => true, 'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail', 'page-attributes' ), 'has_archive' => true, 'rewrite' => array('slug' => 'board'), ) ); } ``` I then went and added 10 posts successfully and they are displaying on the frontend fine. Fast forward 4 weeks and I went in to edit a post but I am seeing "No board members found". It shows that there are 10 Board Members published by actually displays none in the list: ``` All (10) | Published (10) No Board Members Found ``` Clearly WP knows there are board members (All (10)) but it wont show them... I don't know where to start? Ok, I found the issue but I don't understand why. I have another custom\_post\_type: `jobs` On the frontend I try to filter jobs within last x days. When I remove this code, the Board Members re-appear: ``` add_action( 'pre_get_posts', 'custom_query_vars' ); function custom_query_vars( $query ) { if ( $query->is_main_query() ) { if ( is_archive('job') ) { $days = get_field('job_expiry_days', 'option'); $query->set( 'date_query', array( 'column' => 'post_date', 'after' => '- '.$days.' days' ) ); } } return $query; } ```
First: have a read-up on [robots.txt](https://blog.hubspot.com/website/robots-txt-wordpress), if you haven't. Another good reference is [this one from Yoast](https://yoast.com/ultimate-guide-robots-txt/). The sample you posted: ``` User-agent: * Disallow: /wp-admin/ Allow: /wp-admin/admin-ajax.php Sitemap: https://knowingart.com/wp-sitemap.xml ``` ...tells all user-agents (ie, all crawlers) that they are *not allowed* to crawl *anything* in your `wp-admin` directory *except* `/wp-admin/admin-ajax.php`, [which is required by WordPress for properly-functioning AJAX](https://developer.wordpress.org/plugins/javascript/ajax/#url). It's *not* telling robots to go to your `/wp-admin/` directory; it's telling them they're unwelcome there (except for the AJAX requirement). As for your question #4, I'm afraid I don't have an answer to that one.
403,911
<p>In a local wordpress installation, when I install a plugin it only offers me installation via FTP, even if I load the plugin .zip file from my pc. Why does this happen? I use Ubuntu linux and apache 2 as web server. Thank you.</p>
[ { "answer_id": 403758, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>First: have a read-up on <a href=\"https://blog.hubspot.com/website/robots-txt-wordpress\" rel=\"nofollow noref...
2022/03/20
[ "https://wordpress.stackexchange.com/questions/403911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/220467/" ]
In a local wordpress installation, when I install a plugin it only offers me installation via FTP, even if I load the plugin .zip file from my pc. Why does this happen? I use Ubuntu linux and apache 2 as web server. Thank you.
First: have a read-up on [robots.txt](https://blog.hubspot.com/website/robots-txt-wordpress), if you haven't. Another good reference is [this one from Yoast](https://yoast.com/ultimate-guide-robots-txt/). The sample you posted: ``` User-agent: * Disallow: /wp-admin/ Allow: /wp-admin/admin-ajax.php Sitemap: https://knowingart.com/wp-sitemap.xml ``` ...tells all user-agents (ie, all crawlers) that they are *not allowed* to crawl *anything* in your `wp-admin` directory *except* `/wp-admin/admin-ajax.php`, [which is required by WordPress for properly-functioning AJAX](https://developer.wordpress.org/plugins/javascript/ajax/#url). It's *not* telling robots to go to your `/wp-admin/` directory; it's telling them they're unwelcome there (except for the AJAX requirement). As for your question #4, I'm afraid I don't have an answer to that one.
403,956
<p>I am trying to allow visitors to seek specific times on the embed rumble video inside the wordpress post by clicking to timestamp links. I can do it for youtube videos using Skip to Timestamp plugin or methods like <a href="https://wickydesign.com/how-to-add-timestamps-to-embedded-youtube-videos/" rel="nofollow noreferrer">this one</a> however, I cannot make it work for embed rumble videos.</p> <p>I desperately need to make this work for a rumble video. Any help would be greatly appreciated.</p> <p>Cheers.</p>
[ { "answer_id": 403758, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>First: have a read-up on <a href=\"https://blog.hubspot.com/website/robots-txt-wordpress\" rel=\"nofollow noref...
2022/03/21
[ "https://wordpress.stackexchange.com/questions/403956", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/220514/" ]
I am trying to allow visitors to seek specific times on the embed rumble video inside the wordpress post by clicking to timestamp links. I can do it for youtube videos using Skip to Timestamp plugin or methods like [this one](https://wickydesign.com/how-to-add-timestamps-to-embedded-youtube-videos/) however, I cannot make it work for embed rumble videos. I desperately need to make this work for a rumble video. Any help would be greatly appreciated. Cheers.
First: have a read-up on [robots.txt](https://blog.hubspot.com/website/robots-txt-wordpress), if you haven't. Another good reference is [this one from Yoast](https://yoast.com/ultimate-guide-robots-txt/). The sample you posted: ``` User-agent: * Disallow: /wp-admin/ Allow: /wp-admin/admin-ajax.php Sitemap: https://knowingart.com/wp-sitemap.xml ``` ...tells all user-agents (ie, all crawlers) that they are *not allowed* to crawl *anything* in your `wp-admin` directory *except* `/wp-admin/admin-ajax.php`, [which is required by WordPress for properly-functioning AJAX](https://developer.wordpress.org/plugins/javascript/ajax/#url). It's *not* telling robots to go to your `/wp-admin/` directory; it's telling them they're unwelcome there (except for the AJAX requirement). As for your question #4, I'm afraid I don't have an answer to that one.
404,009
<p>I have a custom register form page, and I want to create a 301 redirect to force people to use this form (and not the original URL of WordPress)</p> <p>I try to do a redirect 301 like this in my <code>.htaccess</code>, but it doesn't work.</p> <pre><code>Redirect 301 /wp-login.php?action=register https://monsite.com/register/ </code></pre> <p>What's wrong here?</p>
[ { "answer_id": 404013, "author": "DeltaG", "author_id": 168537, "author_profile": "https://wordpress.stackexchange.com/users/168537", "pm_score": 2, "selected": false, "text": "<p>I would advice you to not use the htaccess for this, but to use a WordPress hook instead.</p>\n<p>Check out ...
2022/03/23
[ "https://wordpress.stackexchange.com/questions/404009", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130804/" ]
I have a custom register form page, and I want to create a 301 redirect to force people to use this form (and not the original URL of WordPress) I try to do a redirect 301 like this in my `.htaccess`, but it doesn't work. ``` Redirect 301 /wp-login.php?action=register https://monsite.com/register/ ``` What's wrong here?
I would advice you to not use the htaccess for this, but to use a WordPress hook instead. Check out <https://developer.wordpress.org/reference/hooks/login_url/>
404,065
<p>I Need to filter content for posts. If the user is not logged in, then the post content should display &quot;please log in....&quot;. If he is logged in, then he can see the post content. I wrote the filter:</p> <pre><code>add_filter('the_content', 'check_user_logedin',10); function check_user_logedin($content){ global $post; if ( $post-&gt;post_type == 'do_pobrania' &amp;&amp; has_term( 'zabezpieczony','rodzaj_plikow' ) &amp;&amp; !is_user_logged_in() ) { return $content ='My text'; }else{ return $content; } } </code></pre> <p>And here comes my problem, because the plugin I use uses get_the_content() and my filter doesn't work on it. It still displays all content for each user. Is it possible to filter content for get_the_content()? Maybe there is another way to solve this issue?</p>
[ { "answer_id": 404070, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 0, "selected": false, "text": "<p>Per the user-contributed comment by Hay on the <a href=\"https://developer.wordpress.org/reference/functions/ge...
2022/03/24
[ "https://wordpress.stackexchange.com/questions/404065", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/214120/" ]
I Need to filter content for posts. If the user is not logged in, then the post content should display "please log in....". If he is logged in, then he can see the post content. I wrote the filter: ``` add_filter('the_content', 'check_user_logedin',10); function check_user_logedin($content){ global $post; if ( $post->post_type == 'do_pobrania' && has_term( 'zabezpieczony','rodzaj_plikow' ) && !is_user_logged_in() ) { return $content ='My text'; }else{ return $content; } } ``` And here comes my problem, because the plugin I use uses get\_the\_content() and my filter doesn't work on it. It still displays all content for each user. Is it possible to filter content for get\_the\_content()? Maybe there is another way to solve this issue?
*tl;dr. There's probably a good way for you to do this in the specific case you describe, although WordPress does **not** allow for good, general filtering of the return value from `get_the_content()`.* ### You cannot do this directly, but ... There currently (as of WordPress 5.9.2, checked on 24 March 2022) isn't a convenient, direct and reliable filter hook for filtering the entire output of `get_the_content()` just as such. `the_content()` runs its output through a final filter before outputting it, but `get_the_content()` does not run its output through a final filter before returning it; sorry. You can review the source code for [`get_the_content()` at the WordPress Code Reference site](https://developer.wordpress.org/reference/functions/get_the_content/) to confirm; you are looking for instances of the function `apply_filters( ... )` which might be applied on the return-value variable `$output`. In the current version of WordPress, there aren't any, although there are instances of `apply_filters( ... )` being used to filter components of the output (for example the "Read More..." link element near the end of the function. ### Still, *in your specific case*, you might be able to highjack the Password-Protected Post functionality to do what you want to do ... **HOWEVER**, there is a potential solution for this, ***if*** you are willing to potentially interfere with the normal functionality of Password-Protected Posts in your installation of WordPress. (That is, posts where an editor has set a password for readers to access the content of that one particular post. If you're not using this feature and not likely to do so in the future, then this solution may work for you. If you are using that feature, or may do so in the future, the solution you adopt might need to become significantly more complex to avoid unwanted side-effects. Here's what you need to do: 1. **Set up a filter on the hook `post_password_required`** which will return `true` if the user is **not** logged in, and `false` if the user **is** logged in. For example, you could put this code in `functions.php` or another appropriate location: ``` add_filter( 'post_password_required', function ( $required, $post ) { $required = ( ! is_user_logged_in() ); return $required; }, 2, 10); ``` For your original example, you need a bit more complex behavior than this -- in particular, you apparently only want this to happen with posts within a hard-coded Custom Post Type and assigned to a particular hard-coded Term. In that case, you can use a more complex boolean expression in the assignment to `$required`: ``` add_filter( 'post_password_required', function ( $required, $post ) { $required = ( $post->post_type == 'do_pobrania' && has_term( 'zabezpieczony','rodzaj_plikow', $post ) && ! is_user_logged_in() ); return $required; }, 2, 10); ``` 2. **Set up a hook on the filter `the_password_form`** which returns the HTML that you want to display when the user is excluded from seeing the content. For example, here's how to display a paragraph including a link to log in to WordPress, and then redirect back to the page you were viewing before: ``` add_filter( 'the_password_form', function ( $output, $post ) { $login_url = wp_login_url( home_url( $_SERVER['REQUEST_URI'] ) ); $output = sprintf('<p>Please <a href="%s">log in</a> ...</p>', esc_url( $login_url ) ); return $output; }, 2, 10); ``` This procedure removes the input form that is normally used to collect the post password for password-protected posts; so, again, if you use that functionality, this solution will break it unless you do something significantly more complicated here. Once these two filters are added, any template or function that uses `get_the_content()` to retrieve post content will be blocked when users aren't logged in (or whenever the conditions you set in the first filter function, whatever those may be, are met). Note that this solution will, *in general*, cause login-gated posts to be treated the way that password-protected posts are treated -- for example, they will not have excerpts displayed, their content will not appear in RSS/Atom feeds, etc. etc. Given what you are trying to do here, it seems likely that these side-effects may be acceptable; but if not, then be careful. ### Some Technical Notes on Why This Works The relevant part of `get_the_content()` is on lines 313-316 of [`wp-includes/post-template.php`](https://developer.wordpress.org/reference/files/wp-includes/post-template.php/): ``` function get_the_content( $more_link_text = null, $strip_teaser = false, $post = null ) { /* [...] */ // If post password required and it doesn't match the cookie. if ( post_password_required( $_post ) ) { return get_the_password_form( $_post ); } /* [...] */ } ``` So **IF** [`post_password_required()`](https://developer.wordpress.org/reference/functions/post_password_required/) returns `true`, **THEN** `get_the_content()` will just return the value returned by [`get_the_password_form()`](https://developer.wordpress.org/reference/functions/get_the_password_form/) in place of the post content. *These* functions can both be filtered using simple filter hooks: ``` function post_password_required( $post = null ) { /** * Filters whether a post requires the user to supply a password. * * @since 4.7.0 * * @param bool $required Whether the user needs to supply a password. True if password has not been * provided or is incorrect, false if password has been supplied or is not required. * @param WP_Post $post Post object. */ return apply_filters( 'post_password_required', $required, $post ); } ``` ``` function get_the_password_form( $post = 0 ) { $post = get_post( $post ); $label = 'pwbox-' . ( empty( $post->ID ) ? rand() : $post->ID ); $output = '<form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" class="post-password-form" method="post"> <p>' . __( 'This content is password protected. To view it please enter your password below:' ) . '</p> <p><label for="' . $label . '">' . __( 'Password:' ) . ' <input name="post_password" id="' . $label . '" type="password" size="20" /></label> <input type="submit" name="Submit" value="' . esc_attr_x( 'Enter', 'post password form' ) . '" /></p></form> '; /** * Filters the HTML output for the protected post password form. * * If modifying the password field, please note that the core database schema * limits the password field to 20 characters regardless of the value of the * size attribute in the form input. * * @since 2.7.0 * @since 5.8.0 Added the `$post` parameter. * * @param string $output The password form HTML output. * @param WP_Post $post Post object. */ return apply_filters( 'the_password_form', $output, $post ); } ``` You can take advantage of these filter hooks (1) to require WordPress to block the post content in *any* context that respects Password-Protected Post security; and (2) to deliver arbitrary HTML (in this case a simple login link) in *place* of the post content in any context that displays an input field to get the post password. Hope this helps!
404,089
<p>How can we change the redirect_url for a redirect action based on the response from an API?</p> <p>I have created a custom action (extending <code>NF_Abstracts_Action </code>) that runs during submission with <code>late</code> timing and calls an external API.</p> <p>Based on that response I want to change the page being redirected to. I cam get the actions with <code>NinjaForms()-&gt;form(2)-&gt;get_actions()</code>, but changing the <code>redirect_url</code> of the redirect action in that array doesn’t alter the current flow.</p> <p>Alternatively how can I send a querystring containing data from the API to the redirected page?</p> <p>Also tried an alternate approach, of redirecting inside a <code>WP Hook action</code></p> <pre><code>function ninja_test_action($form_data) { error_log('inside wp hook action - about to redirect'); wp_redirect('https://wp.test'); } add_action('ninja_test_action', 'ninja_test_action',10,1); </code></pre> <p>This fails with a console error: <code>TypeError: Cannot read properties of undefined (reading 'nonce')</code></p> <p>This testing is being performed on a fresh and clean install of WordPress 5.9 using a clean Underscores theme and only the Ninja Forms plugin installed.</p>
[ { "answer_id": 404436, "author": "ScottM", "author_id": 185972, "author_profile": "https://wordpress.stackexchange.com/users/185972", "pm_score": 0, "selected": false, "text": "<p>I recommend deleting the redirect action for the form, then in your code for the custom action that is run a...
2022/03/25
[ "https://wordpress.stackexchange.com/questions/404089", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/490/" ]
How can we change the redirect\_url for a redirect action based on the response from an API? I have created a custom action (extending `NF_Abstracts_Action` ) that runs during submission with `late` timing and calls an external API. Based on that response I want to change the page being redirected to. I cam get the actions with `NinjaForms()->form(2)->get_actions()`, but changing the `redirect_url` of the redirect action in that array doesn’t alter the current flow. Alternatively how can I send a querystring containing data from the API to the redirected page? Also tried an alternate approach, of redirecting inside a `WP Hook action` ``` function ninja_test_action($form_data) { error_log('inside wp hook action - about to redirect'); wp_redirect('https://wp.test'); } add_action('ninja_test_action', 'ninja_test_action',10,1); ``` This fails with a console error: `TypeError: Cannot read properties of undefined (reading 'nonce')` This testing is being performed on a fresh and clean install of WordPress 5.9 using a clean Underscores theme and only the Ninja Forms plugin installed.
So, the way I've ended up doing this is as follows. It's probably not the optimal way but I can't find a way to change the submission data during the submission workflow (the redirect action always seems to read the original entered data). Basically, the key hook is `ninja_forms_run_action_settings` where you can filter `$action_settings` which contains the redirect url. In my Action class: ``` class CustomProcessing extends NF_Abstracts_Action { private string $_redirect_url; public function __construct() { parent::__construct(); $this->_nicename = 'Custom Process'; add_filter( 'ninja_forms_run_action_settings', [ $this, 'changeRedirectURL' ], 10, 4 ); } public function process( $action_id, $form_id, $data ) { // code to call API endpoint // set redirect url on response from API if ( 201 === $response[ 'response' ][ 'code' ] ) { $this->_redirect_url = $body_url; } return $data } public function changeRedirectURL( $action_settings, $form_id, $action_id, $form_settings ) { if ( '<redirect action name>' === $action_settings[ "label" ] ) { $action_settings[ 'redirect_url' ] = $this->_redirect_url; } return $action_settings; } } ```
404,120
<p>I have a hierarchical CPT <code>event</code> with taxonomy <code>event_category</code>. One of those categories is &quot;Recap&quot;. When a user saves a post (could be draft, publish, or edit existing), if the <code>event_category</code> is Recap and the post has a parent, I want to set the slug to &quot;recap&quot; automatically.</p> <p>The problem is, when <code>wp_insert_post()</code> fires (and all the hooks within it, like <code>wp_insert_post_data</code> and <code>save_post</code>, the taxonomy has not yet been updated, and the data sent to <code>wp_insert_post()</code> does not contain the taxonomy information. There is code in <code>wp_insert_post()</code> to handle taxonomy data if passed, (<code>$postarr['tax_input']</code>), but frustratingly WordPress does not use it. Instead, it seems to process the taxonomy separately. At the time <code>wp_insert_post()</code> runs, the taxonomy data will be equal to what it was the <em>previous</em> update (or empty if a new post).</p> <p>I can hook into <code>set_object_terms</code>, but that does not trigger during a post update when the taxonomy hasn't changed, so it misses the scenario when an existing Recap is updated as a child of another Event.</p> <p>Is there maybe a hook that fires when the update request comes in, and/or one when everything is finished?</p>
[ { "answer_id": 404436, "author": "ScottM", "author_id": 185972, "author_profile": "https://wordpress.stackexchange.com/users/185972", "pm_score": 0, "selected": false, "text": "<p>I recommend deleting the redirect action for the form, then in your code for the custom action that is run a...
2022/03/26
[ "https://wordpress.stackexchange.com/questions/404120", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63369/" ]
I have a hierarchical CPT `event` with taxonomy `event_category`. One of those categories is "Recap". When a user saves a post (could be draft, publish, or edit existing), if the `event_category` is Recap and the post has a parent, I want to set the slug to "recap" automatically. The problem is, when `wp_insert_post()` fires (and all the hooks within it, like `wp_insert_post_data` and `save_post`, the taxonomy has not yet been updated, and the data sent to `wp_insert_post()` does not contain the taxonomy information. There is code in `wp_insert_post()` to handle taxonomy data if passed, (`$postarr['tax_input']`), but frustratingly WordPress does not use it. Instead, it seems to process the taxonomy separately. At the time `wp_insert_post()` runs, the taxonomy data will be equal to what it was the *previous* update (or empty if a new post). I can hook into `set_object_terms`, but that does not trigger during a post update when the taxonomy hasn't changed, so it misses the scenario when an existing Recap is updated as a child of another Event. Is there maybe a hook that fires when the update request comes in, and/or one when everything is finished?
So, the way I've ended up doing this is as follows. It's probably not the optimal way but I can't find a way to change the submission data during the submission workflow (the redirect action always seems to read the original entered data). Basically, the key hook is `ninja_forms_run_action_settings` where you can filter `$action_settings` which contains the redirect url. In my Action class: ``` class CustomProcessing extends NF_Abstracts_Action { private string $_redirect_url; public function __construct() { parent::__construct(); $this->_nicename = 'Custom Process'; add_filter( 'ninja_forms_run_action_settings', [ $this, 'changeRedirectURL' ], 10, 4 ); } public function process( $action_id, $form_id, $data ) { // code to call API endpoint // set redirect url on response from API if ( 201 === $response[ 'response' ][ 'code' ] ) { $this->_redirect_url = $body_url; } return $data } public function changeRedirectURL( $action_settings, $form_id, $action_id, $form_settings ) { if ( '<redirect action name>' === $action_settings[ "label" ] ) { $action_settings[ 'redirect_url' ] = $this->_redirect_url; } return $action_settings; } } ```
404,399
<p>I'm trying to include more than one term_id(multiple checkboxes filter) on a single category page. I managed to recollect enough to build a tax_query with pre_get_posts, but now it seems, I have two tax_queries, one is in WP_Query-&gt;query_vars and the other is just in WP_Query(that one is of WP_Tax_Query type):</p> <pre><code>object(WP_Query)#1968 (50) { [&quot;query&quot;]=&gt; array(1) { [&quot;product_cat&quot;]=&gt; string(77) &quot;parent-category-slug/slug-of-the-category&quot; } [&quot;query_vars&quot;]=&gt; array(59) { [&quot;product_cat&quot;]=&gt; string(56) &quot;slug-of-the-category&quot; [&quot;error&quot;]=&gt; string(0) &quot;&quot; [&quot;m&quot;]=&gt; string(0) &quot;&quot; [&quot;p&quot;]=&gt; int(0) [&quot;post_parent&quot;]=&gt; string(0) &quot;&quot; [&quot;subpost&quot;]=&gt; string(0) &quot;&quot; [&quot;subpost_id&quot;]=&gt; string(0) &quot;&quot; [&quot;attachment&quot;]=&gt; string(0) &quot;&quot; [&quot;attachment_id&quot;]=&gt; int(0) [&quot;name&quot;]=&gt; string(0) &quot;&quot; [&quot;pagename&quot;]=&gt; string(0) &quot;&quot; [&quot;page_id&quot;]=&gt; int(0) [&quot;second&quot;]=&gt; string(0) &quot;&quot; [&quot;minute&quot;]=&gt; string(0) &quot;&quot; [&quot;hour&quot;]=&gt; string(0) &quot;&quot; [&quot;day&quot;]=&gt; int(0) [&quot;monthnum&quot;]=&gt; int(0) [&quot;year&quot;]=&gt; int(0) [&quot;w&quot;]=&gt; int(0) [&quot;category_name&quot;]=&gt; string(0) &quot;&quot; [&quot;tag&quot;]=&gt; string(0) &quot;&quot; [&quot;cat&quot;]=&gt; string(0) &quot;&quot; [&quot;tag_id&quot;]=&gt; string(0) &quot;&quot; [&quot;author&quot;]=&gt; string(0) &quot;&quot; [&quot;author_name&quot;]=&gt; string(0) &quot;&quot; [&quot;feed&quot;]=&gt; string(0) &quot;&quot; [&quot;tb&quot;]=&gt; string(0) &quot;&quot; [&quot;paged&quot;]=&gt; int(0) [&quot;meta_key&quot;]=&gt; string(0) &quot;&quot; [&quot;meta_value&quot;]=&gt; string(0) &quot;&quot; [&quot;preview&quot;]=&gt; string(0) &quot;&quot; [&quot;s&quot;]=&gt; string(0) &quot;&quot; [&quot;sentence&quot;]=&gt; string(0) &quot;&quot; [&quot;title&quot;]=&gt; string(0) &quot;&quot; [&quot;fields&quot;]=&gt; string(0) &quot;&quot; [&quot;menu_order&quot;]=&gt; string(0) &quot;&quot; [&quot;embed&quot;]=&gt; string(0) &quot;&quot; [&quot;category__in&quot;]=&gt; array(0) { } [&quot;category__not_in&quot;]=&gt; array(0) { } [&quot;category__and&quot;]=&gt; array(0) { } [&quot;post__in&quot;]=&gt; array(0) { } [&quot;post__not_in&quot;]=&gt; array(0) { } [&quot;post_name__in&quot;]=&gt; array(0) { } [&quot;tag__in&quot;]=&gt; array(0) { } [&quot;tag__not_in&quot;]=&gt; array(0) { } [&quot;tag__and&quot;]=&gt; array(0) { } [&quot;tag_slug__in&quot;]=&gt; array(0) { } [&quot;tag_slug__and&quot;]=&gt; array(0) { } [&quot;post_parent__in&quot;]=&gt; array(0) { } [&quot;post_parent__not_in&quot;]=&gt; array(0) { } [&quot;author__in&quot;]=&gt; array(0) { } [&quot;author__not_in&quot;]=&gt; array(0) { } [&quot;orderby&quot;]=&gt; string(16) &quot;menu_order title&quot; [&quot;order&quot;]=&gt; string(3) &quot;ASC&quot; [&quot;meta_query&quot;]=&gt; array(0) { } [&quot;tax_query&quot;]=&gt; array(1) { [0]=&gt; array(4) { [&quot;taxonomy&quot;]=&gt; string(11) &quot;product_cat&quot; [&quot;field&quot;]=&gt; string(7) &quot;term_id&quot; [&quot;terms&quot;]=&gt; array(2) { [0]=&gt; int(47) [1]=&gt; int(834) } [&quot;operator&quot;]=&gt; string(2) &quot;IN&quot; } } [&quot;wc_query&quot;]=&gt; string(13) &quot;product_query&quot; [&quot;posts_per_page&quot;]=&gt; int(12) [&quot;post_type&quot;]=&gt; string(7) &quot;product&quot; } [&quot;tax_query&quot;]=&gt; object(WP_Tax_Query)#4683 (6) { [&quot;queries&quot;]=&gt; array(1) { [0]=&gt; array(5) { [&quot;taxonomy&quot;]=&gt; string(11) &quot;product_cat&quot; [&quot;terms&quot;]=&gt; array(1) { [0]=&gt; string(56) &quot;slug-of-the-category&quot; } [&quot;field&quot;]=&gt; string(4) &quot;slug&quot; [&quot;operator&quot;]=&gt; string(2) &quot;IN&quot; [&quot;include_children&quot;]=&gt; bool(true) } } [&quot;relation&quot;]=&gt; string(3) &quot;AND&quot; [&quot;table_aliases&quot;:protected]=&gt; array(0) { } [&quot;queried_terms&quot;]=&gt; array(1) { [&quot;product_cat&quot;]=&gt; array(2) { [&quot;terms&quot;]=&gt; array(1) { [0]=&gt; string(56) &quot;slug-of-the-category&quot; } [&quot;field&quot;]=&gt; string(4) &quot;slug&quot; } } [&quot;primary_table&quot;]=&gt; NULL [&quot;primary_id_column&quot;]=&gt; NULL } [&quot;meta_query&quot;]=&gt; bool(false) [&quot;date_query&quot;]=&gt; bool(false) [&quot;queried_object&quot;]=&gt; object(WP_Term)#4649 (10) { [&quot;term_id&quot;]=&gt; int(1059) [&quot;name&quot;]=&gt; string(59) &quot;Name of the category&quot; [&quot;slug&quot;]=&gt; string(56) &quot;slug-of-the-category&quot; [&quot;term_group&quot;]=&gt; int(0) [&quot;term_taxonomy_id&quot;]=&gt; int(1059) [&quot;taxonomy&quot;]=&gt; string(11) &quot;product_cat&quot; [&quot;description&quot;]=&gt; string(0) &quot;&quot; [&quot;parent&quot;]=&gt; int(416) [&quot;count&quot;]=&gt; int(0) [&quot;filter&quot;]=&gt; string(3) &quot;raw&quot; } [&quot;queried_object_id&quot;]=&gt; int(1059) [&quot;post_count&quot;]=&gt; int(0) [&quot;current_post&quot;]=&gt; int(-1) [&quot;in_the_loop&quot;]=&gt; bool(false) [&quot;comment_count&quot;]=&gt; int(0) [&quot;current_comment&quot;]=&gt; int(-1) [&quot;found_posts&quot;]=&gt; int(0) [&quot;max_num_pages&quot;]=&gt; int(0) [&quot;max_num_comment_pages&quot;]=&gt; int(0) [&quot;is_single&quot;]=&gt; bool(false) [&quot;is_preview&quot;]=&gt; bool(false) [&quot;is_page&quot;]=&gt; bool(false) [&quot;is_archive&quot;]=&gt; bool(true) [&quot;is_date&quot;]=&gt; bool(false) [&quot;is_year&quot;]=&gt; bool(false) [&quot;is_month&quot;]=&gt; bool(false) [&quot;is_day&quot;]=&gt; bool(false) [&quot;is_time&quot;]=&gt; bool(false) [&quot;is_author&quot;]=&gt; bool(false) [&quot;is_category&quot;]=&gt; bool(false) [&quot;is_tag&quot;]=&gt; bool(false) [&quot;is_tax&quot;]=&gt; bool(true) [&quot;is_search&quot;]=&gt; bool(false) [&quot;is_feed&quot;]=&gt; bool(false) [&quot;is_comment_feed&quot;]=&gt; bool(false) [&quot;is_trackback&quot;]=&gt; bool(false) [&quot;is_home&quot;]=&gt; bool(false) [&quot;is_privacy_policy&quot;]=&gt; bool(false) [&quot;is_404&quot;]=&gt; bool(false) [&quot;is_embed&quot;]=&gt; bool(false) [&quot;is_paged&quot;]=&gt; bool(false) [&quot;is_admin&quot;]=&gt; bool(false) [&quot;is_attachment&quot;]=&gt; bool(false) [&quot;is_singular&quot;]=&gt; bool(false) [&quot;is_robots&quot;]=&gt; bool(false) [&quot;is_favicon&quot;]=&gt; bool(false) [&quot;is_posts_page&quot;]=&gt; bool(false) [&quot;is_post_type_archive&quot;]=&gt; bool(false) [&quot;query_vars_hash&quot;:&quot;WP_Query&quot;:private]=&gt; string(32) &quot;0cab94343472426f19caa925968f6373&quot; [&quot;query_vars_changed&quot;:&quot;WP_Query&quot;:private]=&gt; bool(false) [&quot;thumbnails_cached&quot;]=&gt; bool(false) [&quot;stopwords&quot;:&quot;WP_Query&quot;:private]=&gt; NULL [&quot;compat_fields&quot;:&quot;WP_Query&quot;:private]=&gt; array(2) { [0]=&gt; string(15) &quot;query_vars_hash&quot; [1]=&gt; string(18) &quot;query_vars_changed&quot; } [&quot;compat_methods&quot;:&quot;WP_Query&quot;:private]=&gt; array(2) { [0]=&gt; string(16) &quot;init_query_flags&quot; [1]=&gt; string(15) &quot;parse_tax_query&quot; } } </code></pre> <p>This is the POC filter:</p> <pre><code>function a3_include_filtered_ctgs($query) { if (!isset($_GET['filterCtg'])) return; if ($query-&gt;is_main_query() &amp;&amp; !is_admin()) { var_dump($query-&gt;get('tax_query')); $taxquery = //$query-&gt;get('tax_query'); array( array( 'taxonomy' =&gt; 'product_cat', 'field' =&gt; 'term_id', 'terms' =&gt; array_map(function ($id) { return (int) $id; }, explode(&quot;,&quot;, $_GET['filterCtg'])), 'operator' =&gt; 'IN' ) ); if ($query-&gt;get('suppress_filters')) { $query-&gt;set('suppress_filters', false); } $query-&gt;set('tax_query', $taxquery); var_dump($query); } } if (A3_DEBUG === true) { add_action('pre_get_posts', 'a3_include_filtered_ctgs'); } </code></pre>
[ { "answer_id": 404406, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<blockquote>\n<p>but now it seems, I have two tax_queries, one is in\nWP_Query-&gt;query_vars and the other i...
2022/04/04
[ "https://wordpress.stackexchange.com/questions/404399", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/32588/" ]
I'm trying to include more than one term\_id(multiple checkboxes filter) on a single category page. I managed to recollect enough to build a tax\_query with pre\_get\_posts, but now it seems, I have two tax\_queries, one is in WP\_Query->query\_vars and the other is just in WP\_Query(that one is of WP\_Tax\_Query type): ``` object(WP_Query)#1968 (50) { ["query"]=> array(1) { ["product_cat"]=> string(77) "parent-category-slug/slug-of-the-category" } ["query_vars"]=> array(59) { ["product_cat"]=> string(56) "slug-of-the-category" ["error"]=> string(0) "" ["m"]=> string(0) "" ["p"]=> int(0) ["post_parent"]=> string(0) "" ["subpost"]=> string(0) "" ["subpost_id"]=> string(0) "" ["attachment"]=> string(0) "" ["attachment_id"]=> int(0) ["name"]=> string(0) "" ["pagename"]=> string(0) "" ["page_id"]=> int(0) ["second"]=> string(0) "" ["minute"]=> string(0) "" ["hour"]=> string(0) "" ["day"]=> int(0) ["monthnum"]=> int(0) ["year"]=> int(0) ["w"]=> int(0) ["category_name"]=> string(0) "" ["tag"]=> string(0) "" ["cat"]=> string(0) "" ["tag_id"]=> string(0) "" ["author"]=> string(0) "" ["author_name"]=> string(0) "" ["feed"]=> string(0) "" ["tb"]=> string(0) "" ["paged"]=> int(0) ["meta_key"]=> string(0) "" ["meta_value"]=> string(0) "" ["preview"]=> string(0) "" ["s"]=> string(0) "" ["sentence"]=> string(0) "" ["title"]=> string(0) "" ["fields"]=> string(0) "" ["menu_order"]=> string(0) "" ["embed"]=> string(0) "" ["category__in"]=> array(0) { } ["category__not_in"]=> array(0) { } ["category__and"]=> array(0) { } ["post__in"]=> array(0) { } ["post__not_in"]=> array(0) { } ["post_name__in"]=> array(0) { } ["tag__in"]=> array(0) { } ["tag__not_in"]=> array(0) { } ["tag__and"]=> array(0) { } ["tag_slug__in"]=> array(0) { } ["tag_slug__and"]=> array(0) { } ["post_parent__in"]=> array(0) { } ["post_parent__not_in"]=> array(0) { } ["author__in"]=> array(0) { } ["author__not_in"]=> array(0) { } ["orderby"]=> string(16) "menu_order title" ["order"]=> string(3) "ASC" ["meta_query"]=> array(0) { } ["tax_query"]=> array(1) { [0]=> array(4) { ["taxonomy"]=> string(11) "product_cat" ["field"]=> string(7) "term_id" ["terms"]=> array(2) { [0]=> int(47) [1]=> int(834) } ["operator"]=> string(2) "IN" } } ["wc_query"]=> string(13) "product_query" ["posts_per_page"]=> int(12) ["post_type"]=> string(7) "product" } ["tax_query"]=> object(WP_Tax_Query)#4683 (6) { ["queries"]=> array(1) { [0]=> array(5) { ["taxonomy"]=> string(11) "product_cat" ["terms"]=> array(1) { [0]=> string(56) "slug-of-the-category" } ["field"]=> string(4) "slug" ["operator"]=> string(2) "IN" ["include_children"]=> bool(true) } } ["relation"]=> string(3) "AND" ["table_aliases":protected]=> array(0) { } ["queried_terms"]=> array(1) { ["product_cat"]=> array(2) { ["terms"]=> array(1) { [0]=> string(56) "slug-of-the-category" } ["field"]=> string(4) "slug" } } ["primary_table"]=> NULL ["primary_id_column"]=> NULL } ["meta_query"]=> bool(false) ["date_query"]=> bool(false) ["queried_object"]=> object(WP_Term)#4649 (10) { ["term_id"]=> int(1059) ["name"]=> string(59) "Name of the category" ["slug"]=> string(56) "slug-of-the-category" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(1059) ["taxonomy"]=> string(11) "product_cat" ["description"]=> string(0) "" ["parent"]=> int(416) ["count"]=> int(0) ["filter"]=> string(3) "raw" } ["queried_object_id"]=> int(1059) ["post_count"]=> int(0) ["current_post"]=> int(-1) ["in_the_loop"]=> bool(false) ["comment_count"]=> int(0) ["current_comment"]=> int(-1) ["found_posts"]=> int(0) ["max_num_pages"]=> int(0) ["max_num_comment_pages"]=> int(0) ["is_single"]=> bool(false) ["is_preview"]=> bool(false) ["is_page"]=> bool(false) ["is_archive"]=> bool(true) ["is_date"]=> bool(false) ["is_year"]=> bool(false) ["is_month"]=> bool(false) ["is_day"]=> bool(false) ["is_time"]=> bool(false) ["is_author"]=> bool(false) ["is_category"]=> bool(false) ["is_tag"]=> bool(false) ["is_tax"]=> bool(true) ["is_search"]=> bool(false) ["is_feed"]=> bool(false) ["is_comment_feed"]=> bool(false) ["is_trackback"]=> bool(false) ["is_home"]=> bool(false) ["is_privacy_policy"]=> bool(false) ["is_404"]=> bool(false) ["is_embed"]=> bool(false) ["is_paged"]=> bool(false) ["is_admin"]=> bool(false) ["is_attachment"]=> bool(false) ["is_singular"]=> bool(false) ["is_robots"]=> bool(false) ["is_favicon"]=> bool(false) ["is_posts_page"]=> bool(false) ["is_post_type_archive"]=> bool(false) ["query_vars_hash":"WP_Query":private]=> string(32) "0cab94343472426f19caa925968f6373" ["query_vars_changed":"WP_Query":private]=> bool(false) ["thumbnails_cached"]=> bool(false) ["stopwords":"WP_Query":private]=> NULL ["compat_fields":"WP_Query":private]=> array(2) { [0]=> string(15) "query_vars_hash" [1]=> string(18) "query_vars_changed" } ["compat_methods":"WP_Query":private]=> array(2) { [0]=> string(16) "init_query_flags" [1]=> string(15) "parse_tax_query" } } ``` This is the POC filter: ``` function a3_include_filtered_ctgs($query) { if (!isset($_GET['filterCtg'])) return; if ($query->is_main_query() && !is_admin()) { var_dump($query->get('tax_query')); $taxquery = //$query->get('tax_query'); array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => array_map(function ($id) { return (int) $id; }, explode(",", $_GET['filterCtg'])), 'operator' => 'IN' ) ); if ($query->get('suppress_filters')) { $query->set('suppress_filters', false); } $query->set('tax_query', $taxquery); var_dump($query); } } if (A3_DEBUG === true) { add_action('pre_get_posts', 'a3_include_filtered_ctgs'); } ```
> > but now it seems, I have two tax\_queries, one is in > WP\_Query->query\_vars and the other is just in WP\_Query > > > That is normal. * `WP_Query::$query_vars` is an array of query vars merged with the default ones for [`WP_Query`](https://developer.wordpress.org/reference/classes/wp_query/). So if you do `$query = new WP_Query( array( 'post_status' => 'publish' ) )` (or `$query = new WP_Query( 'post_status=publish' )`) and then later do `$query->set( 'tax_query', array( ... ) )`, then `$query->query_vars` would contain both `post_status` and `tax_query`, as well as other vars like `posts_per_page`, `post_type`, etc. * `WP_Query::$tax_query` is an instance of the [`WP_Tax_Query` class](https://developer.wordpress.org/reference/classes/wp_tax_query/) and is used by `WP_Query` for generating the SQL's `JOIN` and `WHERE` clauses for the taxonomy query (`tax_query`) in the `$query_vars` array.
404,665
<p>Here is summary of the problem and required solution:</p> <ul> <li><p>Access to mywebsite.com/wp-admin is blocked for subscribers [which is good]</p> </li> <li><p>However, if i enter the link manually on the browser as follows: <a href="https://mywebsite.com/wp-admin/user-edit.php?user_id=113" rel="nofollow noreferrer">https://mywebsite.com/wp-admin/user-edit.php?user_id=113</a> then the user has access to his user settings</p> </li> <li><p>Problem with that is that they can then create an API key (through application passwords plugin which is accessible from that page). This is undesirable as I dont want the users to have API keys where they can fetch/post data to server.</p> </li> <li><p>Hence, I want to block access of subscribers to all wp-admin menus/plugin pages including this link <a href="https://mywebsite.com/wp-admin/user-edit.php?user_id=113" rel="nofollow noreferrer">https://mywebsite.com/wp-admin/user-edit.php?user_id=113</a></p> </li> </ul> <p>Any suggestions?</p>
[ { "answer_id": 404687, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<blockquote>\n<p>Hence, I want to block access of subscribers to all wp-admin\nmenus/plugin pages including th...
2022/04/11
[ "https://wordpress.stackexchange.com/questions/404665", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/217604/" ]
Here is summary of the problem and required solution: * Access to mywebsite.com/wp-admin is blocked for subscribers [which is good] * However, if i enter the link manually on the browser as follows: <https://mywebsite.com/wp-admin/user-edit.php?user_id=113> then the user has access to his user settings * Problem with that is that they can then create an API key (through application passwords plugin which is accessible from that page). This is undesirable as I dont want the users to have API keys where they can fetch/post data to server. * Hence, I want to block access of subscribers to all wp-admin menus/plugin pages including this link <https://mywebsite.com/wp-admin/user-edit.php?user_id=113> Any suggestions?
> > Hence, I want to block access of subscribers to all wp-admin > menus/plugin pages including this link > `https://mywebsite.com/wp-admin/user-edit.php?user_id=113` > > > This isn't a bulletproof solution, but it should work in that non-admin users would no longer be able to access any admin pages when they're **logged-in**: ```php add_action( 'admin_init', function () { if ( wp_doing_ajax() || ! is_user_logged_in() ) { return; } $roles = (array) wp_get_current_user()->roles; if ( ! in_array( 'administrator', $roles ) ) { // allows only the Administrator role wp_die( 'Sorry, you are not allowed to access this page.' ); // or you can redirect the user to somewhere, if you want to } } ); ``` But then, you might want to change the login and registration *redirect URL* so that it doesn't send the user to an admin page upon successful login/registration — see the documentation for [`login_redirect`](https://developer.wordpress.org/reference/hooks/login_redirect/) and [`registration_redirect`](https://developer.wordpress.org/reference/hooks/registration_redirect/). > > Problem with that is that they can then create an API key (through > application passwords plugin which is accessible from that page). > > > I can't help you with that *plugin*, but unless if you're still using WordPress prior to v5.6.0, then you should not need to use a plugin anymore because application passwords has been a [core feature in WordPress since v5.6.0](https://make.wordpress.org/core/2020/11/05/application-passwords-integration-guide/). And there's actually a hook named [`wp_is_application_passwords_available_for_user`](https://developer.wordpress.org/reference/hooks/wp_is_application_passwords_available_for_user/) that you could use to disable the feature for certain users. > > This is undesirable as I dont want the users to have API keys where > they can fetch/post data to server. > > > If so, and since you said in your comment, "*The rest api is restricted for authenticated users*", then how about using the [`rest_authentication_errors` hook](https://developer.wordpress.org/reference/hooks/rest_authentication_errors/) to ensure only Administrators allowed to access the REST API? Working example: ```php add_filter( 'rest_authentication_errors', function ( $errors ) { if ( ! is_wp_error( $errors ) ) { // do nothing if there's already an error if ( $can_access = is_user_logged_in() ) { $roles = (array) wp_get_current_user()->roles; $can_access = in_array( 'administrator', $roles ); // allows only the Administrator role } if ( ! $can_access ) { return new WP_Error( 'user_not_allowed', 'Sorry, you are not allowed to access the REST API.', array( 'status' => rest_authorization_required_code() ) ); } } return $errors; } ); ```
404,725
<p>I moved a wordpress site into a subdirectory on the same folder and changed the WP address and site address to reflect this.</p> <p>I then used search-replace on the database files to replace the previous url with the subdirectory url.</p> <p>I then re-saved the permalink structure from the wp-admin control page and checked that the .htaccess file looks OK - it includes the following:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ./index.php [L] &lt;/IfModule&gt; </code></pre> <p>The old site home page loads, and I am able to access the wp-admin page, but none of the permalinks work. If I enter the url with the post/page id directly into the browser (eg. <a href="http://www.mysite.com/oldsite/?page_id=12" rel="nofollow noreferrer">www.mysite.com/oldsite/?page_id=12</a> ) I can still access the content directly.</p> <p>I threw the <a href="https://gist.github.com/yunusga/33cf0ba9e311e12df4046722e93d4123" rel="nofollow noreferrer">debugging script from here</a> into functions.php and interestingly even going to the home site triggers an error (but without the script index.php still gets displayed presumably because the rewrite is handling the 404 error). <a href="https://hamiltoncycling.com/oldsite/debug.html" rel="nofollow noreferrer">I have saved the debug script output here</a> (forum won't let me post here as it it thinks it is spam).</p>
[ { "answer_id": 404728, "author": "DeltaG", "author_id": 168537, "author_profile": "https://wordpress.stackexchange.com/users/168537", "pm_score": 0, "selected": false, "text": "<p>If your WordPress files are inside a subdirectory, your htaccess should reflect that. I don't see a subdirec...
2022/04/12
[ "https://wordpress.stackexchange.com/questions/404725", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/220425/" ]
I moved a wordpress site into a subdirectory on the same folder and changed the WP address and site address to reflect this. I then used search-replace on the database files to replace the previous url with the subdirectory url. I then re-saved the permalink structure from the wp-admin control page and checked that the .htaccess file looks OK - it includes the following: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ./index.php [L] </IfModule> ``` The old site home page loads, and I am able to access the wp-admin page, but none of the permalinks work. If I enter the url with the post/page id directly into the browser (eg. [www.mysite.com/oldsite/?page\_id=12](http://www.mysite.com/oldsite/?page_id=12) ) I can still access the content directly. I threw the [debugging script from here](https://gist.github.com/yunusga/33cf0ba9e311e12df4046722e93d4123) into functions.php and interestingly even going to the home site triggers an error (but without the script index.php still gets displayed presumably because the rewrite is handling the 404 error). [I have saved the debug script output here](https://hamiltoncycling.com/oldsite/debug.html) (forum won't let me post here as it it thinks it is spam).
OK fixed it! I had some errant lines in the .htaccess file: ``` RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # WP REWRITE LOOP END ``` This was taking precedence over the `<IfModule mod_rewrite.c>` block - and explains why it was redirecting to the parent directory. (The lesson here is if you are asking for questions about .htaccess, it is probably good to post the whole .htaccess file rather than just a snippet!)
404,776
<p>I want to output the Yoast SEO category meta-description within a custom loop. Current code (below) works if there is a meta-description present. However, if no category meta-description is set it breaks.</p> <p>Is there a better way to write this so that it fails silently if no meta-description is set</p> <pre><code>&lt;?php $popular_topics = get_field('popular_topics'); if( $popular_topics ): foreach( $popular_topics as $topic ): $id = $topic-&gt;term_id; $meta = get_option( 'wpseo_taxonomy_meta' ); $meta_desc = $meta['category'][$id]['wpseo_desc']; ?&gt; &lt;p class=&quot;my-paragraph&quot;&gt; &lt;?php echo esc_html( $meta_desc ); ?&gt; &lt;/p&gt; &lt;?php endforeach; endif; ?&gt; </code></pre> <p>Edit, wrapped in a simple <code>!empty</code> if statement</p> <pre><code>if(!empty( $meta['category'][$id]['wpseo_desc'] )) { echo $meta['category'][$id]['wpseo_desc']; } else { echo &quot;Meta not present&quot;; } </code></pre>
[ { "answer_id": 404778, "author": "DeltaG", "author_id": 168537, "author_profile": "https://wordpress.stackexchange.com/users/168537", "pm_score": 1, "selected": false, "text": "<p>You can just check if <code>$meta</code> and <code>$meta_desc</code> exist. If not, don't echo anything.</p>...
2022/04/13
[ "https://wordpress.stackexchange.com/questions/404776", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/201500/" ]
I want to output the Yoast SEO category meta-description within a custom loop. Current code (below) works if there is a meta-description present. However, if no category meta-description is set it breaks. Is there a better way to write this so that it fails silently if no meta-description is set ``` <?php $popular_topics = get_field('popular_topics'); if( $popular_topics ): foreach( $popular_topics as $topic ): $id = $topic->term_id; $meta = get_option( 'wpseo_taxonomy_meta' ); $meta_desc = $meta['category'][$id]['wpseo_desc']; ?> <p class="my-paragraph"> <?php echo esc_html( $meta_desc ); ?> </p> <?php endforeach; endif; ?> ``` Edit, wrapped in a simple `!empty` if statement ``` if(!empty( $meta['category'][$id]['wpseo_desc'] )) { echo $meta['category'][$id]['wpseo_desc']; } else { echo "Meta not present"; } ```
Wrap in a `!empty` statement ``` if(!empty( $meta['category'][$id]['wpseo_desc'] )) { echo $meta['category'][$id]['wpseo_desc']; } else { echo "Meta not present"; } ```
404,876
<p>There is an icon to open the search form on my site, and when it is clicked, the search form opens in full screen. I want the search form to be selected automatically, how can I do that?</p> <p>Here: <a href="https://wisekitten.com/" rel="nofollow noreferrer">https://wisekitten.com/</a></p> <p>I'm not using jQuery in my project.</p>
[ { "answer_id": 404778, "author": "DeltaG", "author_id": 168537, "author_profile": "https://wordpress.stackexchange.com/users/168537", "pm_score": 1, "selected": false, "text": "<p>You can just check if <code>$meta</code> and <code>$meta_desc</code> exist. If not, don't echo anything.</p>...
2022/04/17
[ "https://wordpress.stackexchange.com/questions/404876", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/161959/" ]
There is an icon to open the search form on my site, and when it is clicked, the search form opens in full screen. I want the search form to be selected automatically, how can I do that? Here: <https://wisekitten.com/> I'm not using jQuery in my project.
Wrap in a `!empty` statement ``` if(!empty( $meta['category'][$id]['wpseo_desc'] )) { echo $meta['category'][$id]['wpseo_desc']; } else { echo "Meta not present"; } ```
404,948
<p>I have an option <code>admins_settings</code> that has an array of sub-options that is stored in the <code>wp_options</code> table. Before I get its value from the table, I check if this field exists by running this code:</p> <pre class="lang-php prettyprint-override"><code>if ( !isset( get_option( 'admins_settings' )['option_name'] ) ) { return false; } else { return get_option( 'admins_settings' )['option_name']; } </code></pre> <p>Here, I'm hitting the table 2 times (if the field exists) to get its value. Is there any way to get the value of the field with one hit?</p> <p>I know that the <code>get_option</code> function accepts a default value if the option doesn't exist. But this works with the simple values:</p> <pre class="lang-php prettyprint-override"><code>get_option( 'admins_settings', false ); </code></pre> <p>But not with array values:</p> <pre class="lang-php prettyprint-override"><code>get_option( 'admins_settings' )['option_name']; </code></pre> <p>Because the option <code>admins_settings</code> could be there, but it doesn't have that item <code>option_name</code>.</p> <p>Again, is there any way to get the sub-value of the field with one hit?</p>
[ { "answer_id": 404949, "author": "ScottM", "author_id": 185972, "author_profile": "https://wordpress.stackexchange.com/users/185972", "pm_score": 1, "selected": false, "text": "<p>Upon entering the <code>if()</code> statement of your code, it will return to the calling function either wa...
2022/04/19
[ "https://wordpress.stackexchange.com/questions/404948", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/161580/" ]
I have an option `admins_settings` that has an array of sub-options that is stored in the `wp_options` table. Before I get its value from the table, I check if this field exists by running this code: ```php if ( !isset( get_option( 'admins_settings' )['option_name'] ) ) { return false; } else { return get_option( 'admins_settings' )['option_name']; } ``` Here, I'm hitting the table 2 times (if the field exists) to get its value. Is there any way to get the value of the field with one hit? I know that the `get_option` function accepts a default value if the option doesn't exist. But this works with the simple values: ```php get_option( 'admins_settings', false ); ``` But not with array values: ```php get_option( 'admins_settings' )['option_name']; ``` Because the option `admins_settings` could be there, but it doesn't have that item `option_name`. Again, is there any way to get the sub-value of the field with one hit?
> > I'm hitting the table 2 times (if the field exists) to get its value. > > > No, you aren't, and there is no evidence for this. You may not be hitting the database at all if it has autoload enabled. WordPress caches things in memory during the same request, and it bulk fetches options set to autoload for performance reasons. The same is true of other things such as post meta. WordPress will attempt to store this data in WP Cache to avoid going back to the database again. E.g. when you fetch a post, it also fetches its post meta and its terms all at once to avoid lots of small database queries. This is also why object caches have such a huge boost to performance as it allows that cache to stay alive across multiple requests. > > But this works with the simple values: > > > But not with array values: > > > They are all simple values, and they are *always* simple values. Options are strings, and have always been strings. If you try to save an array/object then WordPress will attempt to turn it into a string using PHP `serialize`, then deserialize it when you fetch it. This has security consequences. There is no such thing as "sub-options", "nested options", or "child options". There is just options. `admins_settings` is your option, and WordPress sees the entire array as the value, not a series of values, but a singular value that must be serialized. You cannot provide defaults for sub-values this way because options cannot have sub-values. That your value contains structured data is coincidental. Instead, you have 2 options 1. Store separate values as separate values, ideally with a prefix 2. Treat you array as an array and not a weird sub-option ( because there's no such thing as sub-options ) So you would check it the same way you would check an array has a value: ```php $data = []; if ( isset( $data['test'] ) ) { return $data; } else { return false; } ``` Remember, the options table uses plaintext for the value column, the idea that you can store objects and arrays is an illusion WordPress provides to make life easier, and one that would be near impossible to fix after nearly 2 decades.
404,977
<p>I have the following script added to <em>functions.php</em> in my <strong>child</strong> theme:</p> <pre><code>function getlatestfile() { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('wp-content/uploads/cams/')); foreach ($iterator as $file) { if ($file-&gt;isDir()) continue; $path = $file-&gt;getPathname(); } return &quot;&lt;img src='https://mysite.url/&quot; . $path . &quot;' /&gt;&quot;; } // register shortcode add_shortcode('getfieldimage', 'getlatestfile'); </code></pre> <p>I can save the code, insert the shortcode <code>[getfieldimage]</code> on the page, and the page <strong>indeed displays</strong> the latest image. No complains. But when trying to edit again the page containing the shortcode, WP tells me that there's a critical error, and wants me to go to <a href="https://wordpress.org/support/article/faq-troubleshooting/" rel="nofollow noreferrer">https://wordpress.org/support/article/faq-troubleshooting/</a> . Cannot get any helpful info there.</p>
[ { "answer_id": 404979, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>When you're editing the page, you're in the directory <code>wp-admin</code>, and <code>wp-admin</code> doesn't ...
2022/04/20
[ "https://wordpress.stackexchange.com/questions/404977", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150852/" ]
I have the following script added to *functions.php* in my **child** theme: ``` function getlatestfile() { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('wp-content/uploads/cams/')); foreach ($iterator as $file) { if ($file->isDir()) continue; $path = $file->getPathname(); } return "<img src='https://mysite.url/" . $path . "' />"; } // register shortcode add_shortcode('getfieldimage', 'getlatestfile'); ``` I can save the code, insert the shortcode `[getfieldimage]` on the page, and the page **indeed displays** the latest image. No complains. But when trying to edit again the page containing the shortcode, WP tells me that there's a critical error, and wants me to go to <https://wordpress.org/support/article/faq-troubleshooting/> . Cannot get any helpful info there.
ABSPATH helps to display the page in the backend in editmode. But for the frontend, the path for the `<img../>` tag needs to be modified. `cutprefix()` function (taken from [here](https://stackoverflow.com/questions/4517067/remove-a-string-from-the-beginning-of-a-string)) does the job. This is the working solution for the front- and backend: ``` function getlatestfile() { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator( ABSPATH . 'wp-content/uploads/cams' )); foreach ($iterator as $file) { if ($file->isDir()) continue; $path = $file->getPathname(); } $path = cutprefix($path, '/home/username/web/mysite.url/public_html/'); return("<img src='https://mysite.url/" . $path . "' />"); } function cutprefix($str, $prefix){ if (substr($str, 0, strlen($prefix)) == $prefix) { $str = substr($str, strlen($prefix)); } return $str; } ``` Thanks to [Pat J](https://wordpress.stackexchange.com/users/16121/pat-j) for leading me in the right direction.
405,113
<p>UPDATE: I have realised that I need to use a plugin like PHP Snipping or Insert PHP to make this work, I have updated my screen shots to reflect where Im upto from my research.</p> <p>The code is working and outputting the right User ID but the SQL is not echoing the Table data, if you have some advice on where I might of gone wrong would be great.</p> <pre><code>&lt;?php global $wpdb; $uid = get_current_user_id(); $sql = $wpdb-&gt;prepare(&quot;SELECT * FROM sr3_characters WHERE wp_id = $uid&quot; ); $results = $wpdb-&gt;get_results( $sql); ?&gt; &lt;html&gt; &lt;body&gt; &lt;table border=&quot;1&quot;&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Race&lt;/th&gt; &lt;th&gt;Gender&lt;/th&gt; &lt;th&gt;Age&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;?php foreach ($results as $value) { echo &quot;$value-&gt;char_name&lt;br&gt;&quot;; }; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php foreach ($results as $value) { echo &quot;$value-&gt;char_race&lt;br&gt;&quot;; }; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php foreach ($results as $value) { echo &quot;$value-&gt;char_gender&lt;br&gt;&quot;; }; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php foreach ($results as $value) { echo &quot;$value-&gt;char_age&lt;br&gt;&quot;; }; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><br><br> <a href="https://i.stack.imgur.com/yLzNT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yLzNT.png" alt="New output screen" /></a> <br><br> <a href="https://i.stack.imgur.com/KftkJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KftkJ.png" alt="phpmyadmin_1" /></a> <br><br> <a href="https://i.stack.imgur.com/Zjnet.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zjnet.png" alt="phpmyadmin_2" /></a></p>
[ { "answer_id": 405120, "author": "Digitalchild", "author_id": 3170, "author_profile": "https://wordpress.stackexchange.com/users/3170", "pm_score": 0, "selected": false, "text": "<p>Without seeing the values of your custom table, <code>wp_get_current_user()</code> is probably returning t...
2022/04/24
[ "https://wordpress.stackexchange.com/questions/405113", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/221583/" ]
UPDATE: I have realised that I need to use a plugin like PHP Snipping or Insert PHP to make this work, I have updated my screen shots to reflect where Im upto from my research. The code is working and outputting the right User ID but the SQL is not echoing the Table data, if you have some advice on where I might of gone wrong would be great. ``` <?php global $wpdb; $uid = get_current_user_id(); $sql = $wpdb->prepare("SELECT * FROM sr3_characters WHERE wp_id = $uid" ); $results = $wpdb->get_results( $sql); ?> <html> <body> <table border="1"> <tbody> <tr> <th>Name</th> <th>Race</th> <th>Gender</th> <th>Age</th> </tr> <tr> <td><?php foreach ($results as $value) { echo "$value->char_name<br>"; }; ?></td> <td><?php foreach ($results as $value) { echo "$value->char_race<br>"; }; ?></td> <td><?php foreach ($results as $value) { echo "$value->char_gender<br>"; }; ?></td> <td><?php foreach ($results as $value) { echo "$value->char_age<br>"; }; ?></td> </tr> </tbody> </table> </body> </html> ``` [![New output screen](https://i.stack.imgur.com/yLzNT.png)](https://i.stack.imgur.com/yLzNT.png) [![phpmyadmin_1](https://i.stack.imgur.com/KftkJ.png)](https://i.stack.imgur.com/KftkJ.png) [![phpmyadmin_2](https://i.stack.imgur.com/Zjnet.png)](https://i.stack.imgur.com/Zjnet.png)
The evolution of this question makes it difficult to succinctly answer, but in brief summary: * Using [`$wpdb->prepare()`](https://developer.wordpress.org/reference/classes/wpdb/prepare/) to construct arbitrary SQL queries to execute against the database helps to mitigate [injection vulnerabilities](https://xkcd.com/327/) by escaping inserted variables. To use it, instead of concatenating or directly inserting variables into the query, use a placeholder for the appropriate type of data, then pass the variable which be inserted in that location in a respectively indexed array as the second argument. * If this character data is input by end-users, you should also consider [sanitizing the inputs prior to inserting them into the database, and possibly escaping the values prior to displaying them on the front-end](https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/) to further mitigate the risk of injection vulnerability and to prevent end users from displaying arbitrary HTML/JavaScript when their character data is displayed. * Queries executed via [`$wpdb->get_results()`](https://developer.wordpress.org/reference/classes/wpdb/get_results/) return an array of objects, with the properties on the objects being named after the columns in the SQL table. If you prefer to work with arrays instead (either associative or numerically indexed) you can change this behavior by passing one of the predefined constants in as the second argument. * When printing a non-primative data structure such as an object, PHP won't automatically serialize the object into a string for display. `print_r()` is capable of printing most common data structures, but `var_dump()` is a invaluable development aide when you're not sure of the type of the value. All of that said, since each object in the array represents one row from your database table and since HTML tables are constructed one row at a time, you can simply use a single `foreach` loop to place the relevant values from each item into a cell: ```php <?php global $wpdb; $uid = get_current_user_id(); $sql = $wpdb->prepare( "SELECT * FROM `sr3_characters` WHERE `wp_id` = %s", array( $uid ) ); $results = $wpdb->get_results( $sql ); ?> <html> <body> <table border="1"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Race</th> <th scope="col">Gender</th> <th scope="col">Age</th> </tr> </thead> <tbody> <?php foreach( $results as $row ) { ?> <tr> <th scope="row"><?php echo esc_html( $row->char_name ); ?></th> <td><?php echo esc_html( $row->char_race ); ?></td> <td><?php echo $row->char_gender; ?></td> <td><?php echo $row->char_age; ?></td> </tr> <?php } ?> </tbody> </table> </body> </html> ```
405,207
<p>so if i have a function that gets terms from the database ( not the user ) do I need to use prepare first ( before get_results() ), or some sort of data sanitizing?</p>
[ { "answer_id": 405209, "author": "The Oracle", "author_id": 217604, "author_profile": "https://wordpress.stackexchange.com/users/217604", "pm_score": -1, "selected": false, "text": "<p>You shouldn't need to pre-sanitize, wordpress takes care of that with the wpdb class.</p>\n<pre><code> ...
2022/04/27
[ "https://wordpress.stackexchange.com/questions/405207", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192901/" ]
so if i have a function that gets terms from the database ( not the user ) do I need to use prepare first ( before get\_results() ), or some sort of data sanitizing?
> > so if i have a function that gets terms from the database ( not the user ) do I need to use prepare first ( before get\_results() ), or some sort of data sanitizing? > > > Yes, but you should be using `get_terms`/`WP_Term_Query`/`wp_get_object_terms`/etc and the other term APIs instead as they're safer and can be much faster. SQL bypasses object caches and performance plugins, as well as local caches, bulk fetches and security protections. If you're going to perform an SQL query though, don't try to escape it, use `prepare` to insert variables into the query ( never do it directly! ): ```php $safe_sql = $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", [ 'foo', 1337, '%bar' ] ); ``` **Remember, if you need to use an SQL query on the core WordPress tables, there's a high chance you've done something wrong or don't know about a function that does it for you.**
405,260
<p>I would like to show both &quot;author&quot; (one or more) and &quot;reviewed by&quot; (just one person) for Wordpress posts and pages on my website.</p> <p>This would be for example a situation where an article is written by a content producer but the information has to be reviewed by an MD or other credentialed medical expert.</p> <p>This type of functionality is in my opinion pretty much a must on YMYL (your money, your life) type websites.</p> <p>My current understanding is that there is no way to do this in a way that would be native to Wordpress and I should just use some sort of meta information plugin and add the reviewer as meta information on each page and post.</p>
[ { "answer_id": 405209, "author": "The Oracle", "author_id": 217604, "author_profile": "https://wordpress.stackexchange.com/users/217604", "pm_score": -1, "selected": false, "text": "<p>You shouldn't need to pre-sanitize, wordpress takes care of that with the wpdb class.</p>\n<pre><code> ...
2022/04/28
[ "https://wordpress.stackexchange.com/questions/405260", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97162/" ]
I would like to show both "author" (one or more) and "reviewed by" (just one person) for Wordpress posts and pages on my website. This would be for example a situation where an article is written by a content producer but the information has to be reviewed by an MD or other credentialed medical expert. This type of functionality is in my opinion pretty much a must on YMYL (your money, your life) type websites. My current understanding is that there is no way to do this in a way that would be native to Wordpress and I should just use some sort of meta information plugin and add the reviewer as meta information on each page and post.
> > so if i have a function that gets terms from the database ( not the user ) do I need to use prepare first ( before get\_results() ), or some sort of data sanitizing? > > > Yes, but you should be using `get_terms`/`WP_Term_Query`/`wp_get_object_terms`/etc and the other term APIs instead as they're safer and can be much faster. SQL bypasses object caches and performance plugins, as well as local caches, bulk fetches and security protections. If you're going to perform an SQL query though, don't try to escape it, use `prepare` to insert variables into the query ( never do it directly! ): ```php $safe_sql = $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", [ 'foo', 1337, '%bar' ] ); ``` **Remember, if you need to use an SQL query on the core WordPress tables, there's a high chance you've done something wrong or don't know about a function that does it for you.**
405,330
<p>I like to basically use a modified version of the below function.</p> <p>There is <code>pre_render_block</code> and other filters. I have not found out how to get attributes and context the exact way that function does.</p> <p><a href="https://github.com/WordPress/wordpress-develop/blob/5.9/src/wp-includes/blocks.php" rel="nofollow noreferrer">https://github.com/WordPress/wordpress-develop/blob/5.9/src/wp-includes/blocks.php</a></p> <p>I see how I can filter the context there how the file adds the global <code>$post-&gt;ID</code> to the block context, but I do not get what filter I am supposed to use to get whatever is in context. The GB functions needs <code>$block-&gt;context['queryId']</code></p> <p>Am I supposed to unregister the entire block and register it again with my own callback?</p> <pre><code>/** * Renders the `core/query-pagination-numbers` block on the server. * * @param array $attributes Block attributes. * @param string $content Block default content. * @param WP_Block $block Block instance. * * @return string Returns the pagination numbers for the Query. */ function gutenberg_render_block_core_query_pagination_numbers( $attributes, $content, $block ) { $page_key = isset( $block-&gt;context['queryId'] ) ? 'query-' . $block-&gt;context['queryId'] . '-page' : 'query-page'; $page = empty( $_GET[ $page_key ] ) ? 1 : (int) $_GET[ $page_key ]; $max_page = isset( $block-&gt;context['query']['pages'] ) ? (int) $block-&gt;context['query']['pages'] : 0; // stuff } /** * Registers the `core/query-pagination-numbers` block on the server. */ function gutenberg_register_block_core_query_pagination_numbers() { register_block_type_from_metadata( __DIR__ . '/query-pagination-numbers', array( 'render_callback' =&gt; 'gutenberg_render_block_core_query_pagination_numbers', ) ); } add_action( 'init', 'gutenberg_register_block_core_query_pagination_numbers', 20 ); </code></pre> <p>My test:</p> <pre><code>add_filter( 'pre_render_block', __NAMESPACE__ . '\replace_pagination', 10, 3 ); function replace_pagination( $pre_render, $parsed_block, $parent_block ) { if ( 'core/query-pagination-numbers' !== $parsed_block['blockName'] ) { return $pre_render; } dd($parsed_block); return $pre_render; } </code></pre> <p>dd = Kint debugger output :</p> <p><a href="https://i.stack.imgur.com/j1Z0p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j1Z0p.png" alt="enter image description here" /></a></p> <p>No context</p> <p>// OK, I got it, I can get the context from the <code>$parent_block</code>. Probably specific to this Block as it needs the pagination block as a parent. Still like to know how to just replace the callback.</p>
[ { "answer_id": 408204, "author": "Ronak J Vanpariya", "author_id": 170878, "author_profile": "https://wordpress.stackexchange.com/users/170878", "pm_score": 3, "selected": true, "text": "<p>Try This one on your <code>functions.php</code> or main Plugin file</p>\n<pre><code>add_filter('re...
2022/04/30
[ "https://wordpress.stackexchange.com/questions/405330", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38602/" ]
I like to basically use a modified version of the below function. There is `pre_render_block` and other filters. I have not found out how to get attributes and context the exact way that function does. <https://github.com/WordPress/wordpress-develop/blob/5.9/src/wp-includes/blocks.php> I see how I can filter the context there how the file adds the global `$post->ID` to the block context, but I do not get what filter I am supposed to use to get whatever is in context. The GB functions needs `$block->context['queryId']` Am I supposed to unregister the entire block and register it again with my own callback? ``` /** * Renders the `core/query-pagination-numbers` block on the server. * * @param array $attributes Block attributes. * @param string $content Block default content. * @param WP_Block $block Block instance. * * @return string Returns the pagination numbers for the Query. */ function gutenberg_render_block_core_query_pagination_numbers( $attributes, $content, $block ) { $page_key = isset( $block->context['queryId'] ) ? 'query-' . $block->context['queryId'] . '-page' : 'query-page'; $page = empty( $_GET[ $page_key ] ) ? 1 : (int) $_GET[ $page_key ]; $max_page = isset( $block->context['query']['pages'] ) ? (int) $block->context['query']['pages'] : 0; // stuff } /** * Registers the `core/query-pagination-numbers` block on the server. */ function gutenberg_register_block_core_query_pagination_numbers() { register_block_type_from_metadata( __DIR__ . '/query-pagination-numbers', array( 'render_callback' => 'gutenberg_render_block_core_query_pagination_numbers', ) ); } add_action( 'init', 'gutenberg_register_block_core_query_pagination_numbers', 20 ); ``` My test: ``` add_filter( 'pre_render_block', __NAMESPACE__ . '\replace_pagination', 10, 3 ); function replace_pagination( $pre_render, $parsed_block, $parent_block ) { if ( 'core/query-pagination-numbers' !== $parsed_block['blockName'] ) { return $pre_render; } dd($parsed_block); return $pre_render; } ``` dd = Kint debugger output : [![enter image description here](https://i.stack.imgur.com/j1Z0p.png)](https://i.stack.imgur.com/j1Z0p.png) No context // OK, I got it, I can get the context from the `$parent_block`. Probably specific to this Block as it needs the pagination block as a parent. Still like to know how to just replace the callback.
Try This one on your `functions.php` or main Plugin file ``` add_filter('register_block_type_args', function ($settings, $name) { if ($name == 'demo/content-with-sidebar') { $settings['render_callback'] = 'demo_blocks_content_with_sidebar'; } return $settings; }, null, 2); ``` replace your block name with `demo/content-with-sidebar` here demo is the block name space.
405,465
<p>I just installed this plugin and I must say it does everything I need.</p> <p>I am using a custom made popup div with a CF7 inside it.</p> <p>I need to hide response messages (error, success message) after 5 seconds. Is that possible?</p>
[ { "answer_id": 405467, "author": "Patidar Praful", "author_id": 215316, "author_profile": "https://wordpress.stackexchange.com/users/215316", "pm_score": 3, "selected": true, "text": "<p>you can use below code to hide message</p>\n<pre><code>// Contact Form 7 submit event fire\ndocument....
2022/05/06
[ "https://wordpress.stackexchange.com/questions/405465", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/196307/" ]
I just installed this plugin and I must say it does everything I need. I am using a custom made popup div with a CF7 inside it. I need to hide response messages (error, success message) after 5 seconds. Is that possible?
you can use below code to hide message ``` // Contact Form 7 submit event fire document.addEventListener('wpcf7submit', function(event) { setTimeout(function() { jQuery('form.wpcf7-form').removeClass('sent'); jQuery('form.wpcf7-form').removeClass('failed'); jQuery('form.wpcf7-form').addClass('init'); }, 1000); }, false); ```
405,562
<p>I use this function to set and get post view of post in my WordPress</p> <pre><code>function wpb_set_post_views($postID) { $count_key = 'wpb_post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); }else{ $count++; update_post_meta($postID, $count_key, $count); } } remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); function wpb_get_post_views($postID){ $count_key = 'wpb_post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return &quot;0 view&quot;; } return $count.' view'; } </code></pre> <p>Please , how can I check if an article is popular within a week or a month in archive list.</p> <p>For example, if the article in list was popular during the same week, a <code>.popular_week</code> class is added to the article.</p> <p>like :</p> <pre><code> &lt;div class=&quot;loop&quot;&gt; &lt;div class=&quot;article&quot;&gt;article1&lt;/div&gt; &lt;div class=&quot;article&quot;&gt;article2&lt;/div&gt; &lt;div class=&quot;article popular_week&quot;&gt;article3&lt;/div&gt; &lt;div class=&quot;article&quot;&gt;article4&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I hope the idea is clear</p>
[ { "answer_id": 405585, "author": "Bysander", "author_id": 47618, "author_profile": "https://wordpress.stackexchange.com/users/47618", "pm_score": 1, "selected": false, "text": "<p>Short answer:</p>\n<p>You can't from that code</p>\n<hr>\nLonger answer:\n<p>So the code above will simply i...
2022/05/09
[ "https://wordpress.stackexchange.com/questions/405562", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/222021/" ]
I use this function to set and get post view of post in my WordPress ``` function wpb_set_post_views($postID) { $count_key = 'wpb_post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); }else{ $count++; update_post_meta($postID, $count_key, $count); } } remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); function wpb_get_post_views($postID){ $count_key = 'wpb_post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0 view"; } return $count.' view'; } ``` Please , how can I check if an article is popular within a week or a month in archive list. For example, if the article in list was popular during the same week, a `.popular_week` class is added to the article. like : ``` <div class="loop"> <div class="article">article1</div> <div class="article">article2</div> <div class="article popular_week">article3</div> <div class="article">article4</div> </div> ``` I hope the idea is clear
Short answer: You can't from that code --- Longer answer: So the code above will simply increment a counter based on the last value the counter was on. There's no way to tell when that page-view or count starts from it's simply a number. You have no data on when that page view was counted or even last updated and certainly not how many of those counts occurred in the last week. I've written about this before as it's not a simple topic but in a nutshell counting post views efficiently is a nightmare - by recording views and writing data back to that same data source you are removing your read-cache from the database query, every time a page is viewed your database will need to be read from fresh as a write has just written your post-meta value with a counter. The most efficient way I've found of doing this is to use an external service like Google Analytics or Adobe Analytics then query their API periodically for your popularity data. Perhaps every 2 -3 or 6 - 12 hours (depending on your web traffic) and get your popularity data from a data source that already has it there. You're really re-inventing the wheel with page-views - big companies have already spent 000s on making this efficient. If you want to do it yourself - strap-in as you'll be looking at multiple, separate database tables, custom indexing structure, cron-jobs to process lists of timestamps against pages and Ajax calls to your counter so server-side page caching can work effectively. I've had to abandon the more popular page view counting plugins on the WP.org plugin repo as they were all dismally inefficient - adding overhead and page-load times that were unacceptable. If you're running a small site it probably won't matter - you should take something off the shelf and use that... but remember to add it to the top of the list to change when / if your site traffic grows. --- Also, a warm welcome to WPSE @jimi-del don't forget to read up on our community guidelines. [How do I ask a good question?](https://wordpress.stackexchange.com/help/how-to-ask) [Code of Conduct](https://wordpress.stackexchange.com/conduct) [What should I do when someone answers my question?](https://wordpress.stackexchange.com/help/someone-answers)
405,588
<p>I’m trying to apply the <code>pre_get_posts</code> to a specific <em>core/query</em> block, in order to programatically modify the number of posts displayed when a custom attribute is set. If I use the <code>render_block</code> hook, the block is already pre-rendered and so modifying the query using <code>pre_get_posts</code> has no effect. Is there any way to achieve this?</p> <p>(I don't need help adding the custom attribute; I've done so already using block filters.)</p>
[ { "answer_id": 405596, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p><strong>Update:</strong></p>\n<p>It's possible to use the <a href=\"https://developer.wordpress.org/reference...
2022/05/10
[ "https://wordpress.stackexchange.com/questions/405588", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83412/" ]
I’m trying to apply the `pre_get_posts` to a specific *core/query* block, in order to programatically modify the number of posts displayed when a custom attribute is set. If I use the `render_block` hook, the block is already pre-rendered and so modifying the query using `pre_get_posts` has no effect. Is there any way to achieve this? (I don't need help adding the custom attribute; I've done so already using block filters.)
**Update:** It's possible to use the [`render_block_data`](https://developer.wordpress.org/reference/hooks/render_block_data/) filter to modify the query block's data before it's rendered. Since 6.1. the [`query_loop_block_query_vars`](https://developer.wordpress.org/reference/hooks/query_loop_block_query_vars/) filter is available if one needs to modify the underlying `WP_Query` arguments (e.g. those that are still unsupported by the query block's interface) but it only works for the front-end but not the editor preview that uses the REST API (see more on that in the docs [here](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/extending-the-query-loop-block/#making-your-custom-query-work-on-the-front-end-side)). **Original answer:** There's an open ticket for such a query args filter [#54850](https://core.trac.wordpress.org/ticket/54850). In the meanwhile you can try this approach, replacing the render callback of the `core/post-template` block with a wrapper callback: ``` add_filter( 'block_type_metadata_settings', function( $settings ) { if ( $settings['parent'][0] !== 'core/query' ) { return $settings; } if ( $settings['render_callback'] !== 'render_block_core_post_template' ) { return $settings; } $settings['render_callback']= 'wpse_render_block_core_post_template'; return $settings; }); ``` with the wrapper callback as: ``` function wpse_render_block_core_post_template($attributes, $content, $block ){ $output = render_block_core_post_template( $attributes, $content, $block ); return $output; } ``` Now we have a better way to target the `WP_Query` instance within that core template. Following are two such examples. Example with `pre_get_posts` ---------------------------- Here's an example how to override the *number of posts* with the help of the `pre_get_posts` hook: ``` function wpse_render_block_core_post_template( $attributes, $content, $block ) { $cb = fn( $q ) => $q->set( 'posts_per_page', 2 ); add_action( 'pre_get_posts', $cb, 999 ); $output = render_block_core_post_template( $attributes, $content, $block ); remove_action( 'pre_get_posts', $cb, 999 ); return $output; } ``` Example with block context -------------------------- We could also change existing query arguments within [`build_query_vars_from_query_block()`](https://github.com/WordPress/WordPress/blob/7b880889bc92552cdab7b0dd700db82a3885d02d/wp-includes/blocks.php#L1097), like `perPage`, with: ``` function wpse_render_block_core_post_template( $attributes, $content, $block ) { $block->context['query']['perPage'] = 2; return render_block_core_post_template($attributes, $content, $block ); } ``` Then you can add further restrictions as needed to both approaches, from e.g. other block info, like `queryId`.
405,649
<p>We’re using WP Engine for web hosting.</p> <p>I originally manually turned on Multisite through <code>wp-config.php</code> &amp; <code>Tools &gt; Network Setup</code>.</p> <p>Since then, I've learned we need to use their <code>Enable Multisite</code> function to enable subdirectory multisite.</p> <p>When <code>WP_DEBUG</code> is on, we see a message:</p> <blockquote> <p>Notice: wp_check_site_meta_support_prefilter was called incorrectly. The wp_blogmeta table is not installed. Please run the network database upgrade.</p> </blockquote> <p>I then created <code>wp_blogmeta</code> manually using:</p> <pre><code>CREATE TABLE IF NOT EXISTS wp_blogmeta ( meta_id bigint(20) unsigned NOT NULL AUTO_INCREMENT, blog_id bigint(20) NOT NULL DEFAULT ‘0’, meta_key varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL, meta_value longtext COLLATE utf8mb4_unicode_520_ci, PRIMARY KEY (meta_id), KEY meta_key (meta_key(191)), KEY blog_id (blog_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci AUTO_INCREMENT=1; </code></pre> <p>If I run the network database upgrade, the error remains.</p> <p>How do I populate/”install” this table?</p> <p><strong>EDIT</strong>: WP Engine say they do not support issues with Multisite, so they're unable to help me resolve this.</p> <p>Our <code>wp-config.php</code> contains:</p> <pre><code>define('MULTISITE', true); define('SUBDOMAIN_INSTALL', false); define('DOMAIN_CURRENT_SITE', 'example.com'); define('PATH_CURRENT_SITE', '/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); define('ADMIN_COOKIE_PATH', '/'); define('COOKIE_DOMAIN', ''); define('COOKIEPATH', ''); define('SITECOOKIEPATH', ''); </code></pre> <p>We're using <code>WordPress 6.0</code>.</p>
[ { "answer_id": 405926, "author": "Bysander", "author_id": 47618, "author_profile": "https://wordpress.stackexchange.com/users/47618", "pm_score": 0, "selected": false, "text": "<p>The URL to access the network database update is</p>\n<p><a href=\"https://www.website.test/wp-admin/network...
2022/05/12
[ "https://wordpress.stackexchange.com/questions/405649", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3206/" ]
We’re using WP Engine for web hosting. I originally manually turned on Multisite through `wp-config.php` & `Tools > Network Setup`. Since then, I've learned we need to use their `Enable Multisite` function to enable subdirectory multisite. When `WP_DEBUG` is on, we see a message: > > Notice: wp\_check\_site\_meta\_support\_prefilter was called incorrectly. The wp\_blogmeta table is not installed. Please run the network database upgrade. > > > I then created `wp_blogmeta` manually using: ``` CREATE TABLE IF NOT EXISTS wp_blogmeta ( meta_id bigint(20) unsigned NOT NULL AUTO_INCREMENT, blog_id bigint(20) NOT NULL DEFAULT ‘0’, meta_key varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL, meta_value longtext COLLATE utf8mb4_unicode_520_ci, PRIMARY KEY (meta_id), KEY meta_key (meta_key(191)), KEY blog_id (blog_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci AUTO_INCREMENT=1; ``` If I run the network database upgrade, the error remains. How do I populate/”install” this table? **EDIT**: WP Engine say they do not support issues with Multisite, so they're unable to help me resolve this. Our `wp-config.php` contains: ``` define('MULTISITE', true); define('SUBDOMAIN_INSTALL', false); define('DOMAIN_CURRENT_SITE', 'example.com'); define('PATH_CURRENT_SITE', '/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); define('ADMIN_COOKIE_PATH', '/'); define('COOKIE_DOMAIN', ''); define('COOKIEPATH', ''); define('SITECOOKIEPATH', ''); ``` We're using `WordPress 6.0`.
This was an error on an older version of WordPress, version 5.1 ([Core Issue #46167](https://core.trac.wordpress.org/ticket/46167)). Do you use the last stable version of WordPress? But try the following options to solve the problem. Install again, Core or WP CLI ============================= Copy all files from the core again in your installation, like via sFTP, especially all files in the directories `wp-inlcudes` and `wp-admin`. Run the installation again. Alternate if you have the possibility with the usage of [WP CLI](https://wp-cli.org/) `wp core update-db --network`. Upgrade again ============= Go in your installation to the URL `wp-admin/network/upgrade.php` and perform the upgrade again. Manual ====== Create the table or check your manual steps for this creation ```sql CREATE TABLE $wpdb->blogmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, blog_id bigint(20) NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY meta_key (meta_key($max_index_length)), KEY blog_id (blog_id) ) $charset_collate; ``` Now look at the table `wp_sitemeta`, field `site_meta_supported` and set the value to 1. Background is, WP looks via `is_site_meta_supported()` for this value to use the table.
405,683
<p>I need to list all categories and their respective posts. Each taxonomy has an image created by ACF in jetengine plugin. I created the loop that returns the list of categories and posts for each category. But I can't capture the custom field from the taxonomy image. Can anyone give me some tips on how to do it?</p> <pre><code>foreach($custom_terms as $custom_term) { wp_reset_query(); $args = array('post_type' =&gt; 'post', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'custom_tax', 'field' =&gt; 'slug', 'terms' =&gt; $custom_term-&gt;slug, ), ), ); $loop = new WP_Query($args); if($loop-&gt;have_posts()) { echo '&lt;h2&gt;'.$custom_term-&gt;name.'&lt;/h2&gt;'; while($loop-&gt;have_posts()) : $loop-&gt;the_post(); echo '&lt;a href=&quot;'.get_permalink().'&quot;&gt;'.get_the_title().'&lt;/a&gt;&lt;br&gt;'; endwhile; } } } </code></pre> <p><strong>UPDATE:</strong> Following @Abhik tip, tip I was able to list the image of each category using the ACF plugin only for img.</p> <p><strong>Taxonomy</strong> IMG</p> <ul> <li>List item (CPT item)</li> <li>List item (CPT item)</li> <li>List item (CPT item)</li> <li>List item (CPT item)</li> </ul> <p><strong>Taxonomy</strong> IMG</p> <ul> <li>List item (CPT item)</li> <li>List item (CPT item)</li> <li>List item (CPT item)</li> <li>List item (CPT item)</li> </ul> <p>That way I was able to create a really efficient dynamic menu. I appreciate the contribution of those who commented! I'm still open to suggestions for improvement.</p> <p>Code:</p> <pre><code>add_shortcode( 'list_terms_post_cod', 'list_terms_post_func' ); function list_terms_post_func(){ $custom_terms = get_terms('taxonomy'); foreach($custom_terms as $custom_term) { wp_reset_query(); $args = array('post_type' =&gt; 'custom_post', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'custom_term', 'field' =&gt; 'slug', 'terms' =&gt; $custom_term-&gt;slug, ), ), ); $loop = new WP_Query($args); $image = get_field( 'cat_image', $custom_term ); //Taxonomies Loop if($loop-&gt;have_posts()) { echo '&lt;h2&gt;'.$custom_term-&gt;name.'&lt;/h2&gt;'; echo '&lt;img src=&quot;'.$image.'&quot;/&gt;'; //Post loop while($loop-&gt;have_posts()) : $loop-&gt;the_post(); echo '&lt;a href=&quot;'.get_permalink().'&quot;&gt;'.get_the_title().'&lt;/a&gt;&lt;br&gt;'; endwhile; } wp_reset_postdata(); // reset global $post; } } </code></pre>
[ { "answer_id": 405688, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>The thumbnail is probably stored in the <code>termmeta</code> table using a meta key specified the jetengin...
2022/05/13
[ "https://wordpress.stackexchange.com/questions/405683", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/191774/" ]
I need to list all categories and their respective posts. Each taxonomy has an image created by ACF in jetengine plugin. I created the loop that returns the list of categories and posts for each category. But I can't capture the custom field from the taxonomy image. Can anyone give me some tips on how to do it? ``` foreach($custom_terms as $custom_term) { wp_reset_query(); $args = array('post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'custom_tax', 'field' => 'slug', 'terms' => $custom_term->slug, ), ), ); $loop = new WP_Query($args); if($loop->have_posts()) { echo '<h2>'.$custom_term->name.'</h2>'; while($loop->have_posts()) : $loop->the_post(); echo '<a href="'.get_permalink().'">'.get_the_title().'</a><br>'; endwhile; } } } ``` **UPDATE:** Following @Abhik tip, tip I was able to list the image of each category using the ACF plugin only for img. **Taxonomy** IMG * List item (CPT item) * List item (CPT item) * List item (CPT item) * List item (CPT item) **Taxonomy** IMG * List item (CPT item) * List item (CPT item) * List item (CPT item) * List item (CPT item) That way I was able to create a really efficient dynamic menu. I appreciate the contribution of those who commented! I'm still open to suggestions for improvement. Code: ``` add_shortcode( 'list_terms_post_cod', 'list_terms_post_func' ); function list_terms_post_func(){ $custom_terms = get_terms('taxonomy'); foreach($custom_terms as $custom_term) { wp_reset_query(); $args = array('post_type' => 'custom_post', 'tax_query' => array( array( 'taxonomy' => 'custom_term', 'field' => 'slug', 'terms' => $custom_term->slug, ), ), ); $loop = new WP_Query($args); $image = get_field( 'cat_image', $custom_term ); //Taxonomies Loop if($loop->have_posts()) { echo '<h2>'.$custom_term->name.'</h2>'; echo '<img src="'.$image.'"/>'; //Post loop while($loop->have_posts()) : $loop->the_post(); echo '<a href="'.get_permalink().'">'.get_the_title().'</a><br>'; endwhile; } wp_reset_postdata(); // reset global $post; } } ```
Since you are using ACF, you can take advantage of the `get_field()` function ACF provides. You will need to pass the term object as the second parameter. ``` $image = get_field( 'field_key', $custom_term ); ```
405,747
<p>I'm trying to use <a href="https://developer.wordpress.org/reference/functions/unzip_file/" rel="nofollow noreferrer">unzip_file</a> to extract the remote archive with no success. It works only with the local path using <strong>get_template_directory()</strong> but with a remote zip archive URL I'm getting <em>Incompatible Archive.</em> message.</p> <p>Here is the stripped version of my code:</p> <pre><code>WP_Filesystem(); global $wp_filesystem; $source = 'http://downloads.wordpress.org/theme/ona-creative.1.0.0.zip'; $unzipfile = unzip_file( $source, get_theme_root() ); if ( is_wp_error( $unzipfile ) ) { wp_send_json( array( 'done' =&gt; 1, 'message' =&gt; esc_html__( $unzipfile-&gt;get_error_message() . ' There was an error unzipping the file.', 'ona' ) ) ); } </code></pre>
[ { "answer_id": 405688, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>The thumbnail is probably stored in the <code>termmeta</code> table using a meta key specified the jetengin...
2022/05/15
[ "https://wordpress.stackexchange.com/questions/405747", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112255/" ]
I'm trying to use [unzip\_file](https://developer.wordpress.org/reference/functions/unzip_file/) to extract the remote archive with no success. It works only with the local path using **get\_template\_directory()** but with a remote zip archive URL I'm getting *Incompatible Archive.* message. Here is the stripped version of my code: ``` WP_Filesystem(); global $wp_filesystem; $source = 'http://downloads.wordpress.org/theme/ona-creative.1.0.0.zip'; $unzipfile = unzip_file( $source, get_theme_root() ); if ( is_wp_error( $unzipfile ) ) { wp_send_json( array( 'done' => 1, 'message' => esc_html__( $unzipfile->get_error_message() . ' There was an error unzipping the file.', 'ona' ) ) ); } ```
Since you are using ACF, you can take advantage of the `get_field()` function ACF provides. You will need to pass the term object as the second parameter. ``` $image = get_field( 'field_key', $custom_term ); ```
405,795
<p>Is there a way to add additional first and last page links to the pagination object if it is rendere with the <code>the_posts_pagination()</code> method?</p> <p>At this point I have the following</p> <pre><code>the_posts_pagination( [ 'screen_reader_text' =&gt; ' ', 'mid_size' =&gt; 2, 'prev_text' =&gt; __( 'vorherige', 'bdb' ), 'next_text' =&gt; __( 'nächste', 'bdb' ), ]); </code></pre> <p>and I would like to after <code>prev_text</code> a first page link if is not the first page and a last page link before <code>next_text</code> if is not the last page</p>
[ { "answer_id": 405688, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>The thumbnail is probably stored in the <code>termmeta</code> table using a meta key specified the jetengin...
2022/05/17
[ "https://wordpress.stackexchange.com/questions/405795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/23759/" ]
Is there a way to add additional first and last page links to the pagination object if it is rendere with the `the_posts_pagination()` method? At this point I have the following ``` the_posts_pagination( [ 'screen_reader_text' => ' ', 'mid_size' => 2, 'prev_text' => __( 'vorherige', 'bdb' ), 'next_text' => __( 'nächste', 'bdb' ), ]); ``` and I would like to after `prev_text` a first page link if is not the first page and a last page link before `next_text` if is not the last page
Since you are using ACF, you can take advantage of the `get_field()` function ACF provides. You will need to pass the term object as the second parameter. ``` $image = get_field( 'field_key', $custom_term ); ```
405,823
<p>I would like to sort the output of my WP Query. I want the events that are coming up soon to be at the beginning. The events that have already taken place should be at the end. So the first array in my meta_query should be output first, then the second array.</p> <pre><code> $the_query = new WP_Query( array( 'post_type' =&gt; 'page', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; $posts, 'meta_key' =&gt; 'datum-von', 'orderby' =&gt; 'meta_value upcoming_events', 'order' =&gt; 'ASC', 'post__in' =&gt; array(22888,23062,23065,23348), 'meta_query' =&gt; array( 'relation' =&gt; 'OR', 'upcoming_events' =&gt; array( 'key' =&gt; 'datum-von', 'value' =&gt; date('Y-m-d'), 'compare' =&gt; '&gt;=', 'type' =&gt; 'DATE' ), 'past_events' =&gt; array( 'key' =&gt; 'datum-von', 'value' =&gt; date('Y-m-d'), 'compare' =&gt; '&lt;=', 'type' =&gt; 'DATE' ) ), ) ); </code></pre> <p>Does anyone have an idea how I can control the sorting? Thanks for reading!</p>
[ { "answer_id": 405688, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>The thumbnail is probably stored in the <code>termmeta</code> table using a meta key specified the jetengin...
2022/05/18
[ "https://wordpress.stackexchange.com/questions/405823", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/222289/" ]
I would like to sort the output of my WP Query. I want the events that are coming up soon to be at the beginning. The events that have already taken place should be at the end. So the first array in my meta\_query should be output first, then the second array. ``` $the_query = new WP_Query( array( 'post_type' => 'page', 'post_status' => 'publish', 'posts_per_page' => $posts, 'meta_key' => 'datum-von', 'orderby' => 'meta_value upcoming_events', 'order' => 'ASC', 'post__in' => array(22888,23062,23065,23348), 'meta_query' => array( 'relation' => 'OR', 'upcoming_events' => array( 'key' => 'datum-von', 'value' => date('Y-m-d'), 'compare' => '>=', 'type' => 'DATE' ), 'past_events' => array( 'key' => 'datum-von', 'value' => date('Y-m-d'), 'compare' => '<=', 'type' => 'DATE' ) ), ) ); ``` Does anyone have an idea how I can control the sorting? Thanks for reading!
Since you are using ACF, you can take advantage of the `get_field()` function ACF provides. You will need to pass the term object as the second parameter. ``` $image = get_field( 'field_key', $custom_term ); ```
405,832
<p>I'm using Cryto Plugin and want to get coin price data from plugin db.<br> <a href="https://i.stack.imgur.com/4tOn4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4tOn4.png" alt="enter image description here" /></a></p> <p>For easy practice, I'm trying to get BTC data.</p> <pre><code>&lt;?php function get_coin_price($coin_symbol) { global $wpdb; $coin_price = $wpdb-&gt;get_var($wpdb-&gt;prepare(&quot;SELECT price FROM {$wpdb-&gt;prefix}cmc_coins_v2 WHERE symbol = '%s'&quot;, $coin_symbol)); return $coin_price; }?&gt; </code></pre> <p>And if I want to get BTC price, I use this code.</p> <pre><code>&lt;?php get_coin_price(BTC); ?&gt; </code></pre> <p>However I'm getting this error <br> <strong>&quot;Use of undefined constant BTC - assumed 'BTC' (this will throw an Error in a future version of PHP)&quot;</strong> <br> Is there a problem in data type? or maybe am I not using $wpdb-&gt;get_var or wpdb-&gt;prepare correctly?</p>
[ { "answer_id": 405688, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>The thumbnail is probably stored in the <code>termmeta</code> table using a meta key specified the jetengin...
2022/05/18
[ "https://wordpress.stackexchange.com/questions/405832", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/221273/" ]
I'm using Cryto Plugin and want to get coin price data from plugin db. [![enter image description here](https://i.stack.imgur.com/4tOn4.png)](https://i.stack.imgur.com/4tOn4.png) For easy practice, I'm trying to get BTC data. ``` <?php function get_coin_price($coin_symbol) { global $wpdb; $coin_price = $wpdb->get_var($wpdb->prepare("SELECT price FROM {$wpdb->prefix}cmc_coins_v2 WHERE symbol = '%s'", $coin_symbol)); return $coin_price; }?> ``` And if I want to get BTC price, I use this code. ``` <?php get_coin_price(BTC); ?> ``` However I'm getting this error **"Use of undefined constant BTC - assumed 'BTC' (this will throw an Error in a future version of PHP)"** Is there a problem in data type? or maybe am I not using $wpdb->get\_var or wpdb->prepare correctly?
Since you are using ACF, you can take advantage of the `get_field()` function ACF provides. You will need to pass the term object as the second parameter. ``` $image = get_field( 'field_key', $custom_term ); ```
405,852
<p>I have a site with many custom queries. Some take many seconds to load a page. To solve that issue, I have been using a caching plugin. The issue is, my caching plugin does not cache a page until I click it once. I'd prefer to do this entire process without a plugin if possible. If the plugin route is the best way to go, I'd love to know that too.</p> <p>I have an idea that this is how it SHOULD work, but I'd love to be corrected if this is impossible or not the best way...</p> <p>When I upload a new post, I'd like the system to automatically cache all queries associated with the post, and save them to display to the user. If I add a new artist, I'd like their artist page to automatically be cached into the database. I'd prefer the user to never have to wait for a query, and instead to only see results of queries, printed.</p> <p>The only 'live' part of the site needs to be the discussion forums and comment sections.</p> <p>Is there a way to add to the code something like (on my side)&quot;When i add a new post, check to see if any queries are affected by this change, if not, run a new query and store the results of this, if so, update the query to include this new information.&quot;</p> <p>Then I want to display to the user only the result of the queries, filtered by the templates I have set up.</p> <p>is there a way to persistently cache custom groups of posts together? Like could I run a query called $post_object_1_results ? then instead of the user running the query, I want the information to be pulled ffrom $post_object_1_results AFTER the query is run. Does a persistent version of <code>wp_cache_set()</code> and <code>wp_cache_get()</code>, exist?</p> <p>Is a plugin the best way? Thank you</p>
[ { "answer_id": 405688, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 2, "selected": false, "text": "<p>The thumbnail is probably stored in the <code>termmeta</code> table using a meta key specified the jetengin...
2022/05/18
[ "https://wordpress.stackexchange.com/questions/405852", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/222023/" ]
I have a site with many custom queries. Some take many seconds to load a page. To solve that issue, I have been using a caching plugin. The issue is, my caching plugin does not cache a page until I click it once. I'd prefer to do this entire process without a plugin if possible. If the plugin route is the best way to go, I'd love to know that too. I have an idea that this is how it SHOULD work, but I'd love to be corrected if this is impossible or not the best way... When I upload a new post, I'd like the system to automatically cache all queries associated with the post, and save them to display to the user. If I add a new artist, I'd like their artist page to automatically be cached into the database. I'd prefer the user to never have to wait for a query, and instead to only see results of queries, printed. The only 'live' part of the site needs to be the discussion forums and comment sections. Is there a way to add to the code something like (on my side)"When i add a new post, check to see if any queries are affected by this change, if not, run a new query and store the results of this, if so, update the query to include this new information." Then I want to display to the user only the result of the queries, filtered by the templates I have set up. is there a way to persistently cache custom groups of posts together? Like could I run a query called $post\_object\_1\_results ? then instead of the user running the query, I want the information to be pulled ffrom $post\_object\_1\_results AFTER the query is run. Does a persistent version of `wp_cache_set()` and `wp_cache_get()`, exist? Is a plugin the best way? Thank you
Since you are using ACF, you can take advantage of the `get_field()` function ACF provides. You will need to pass the term object as the second parameter. ``` $image = get_field( 'field_key', $custom_term ); ```
405,886
<p>I'm wondering if it's possible to logout all users 2 times a day using the function wp_logout() ?</p> <p>I see loads of plugins who can logout idled users but we want to log out every single users twice a day at</p> <p>2PM and 10PM</p> <p>Hope someone can help me with this.</p>
[ { "answer_id": 405901, "author": "Tim", "author_id": 118534, "author_profile": "https://wordpress.stackexchange.com/users/118534", "pm_score": 2, "selected": false, "text": "<p>This should be possible, WordPress provides the <a href=\"https://developer.wordpress.org/reference/classes/wp_...
2022/05/19
[ "https://wordpress.stackexchange.com/questions/405886", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/222333/" ]
I'm wondering if it's possible to logout all users 2 times a day using the function wp\_logout() ? I see loads of plugins who can logout idled users but we want to log out every single users twice a day at 2PM and 10PM Hope someone can help me with this.
This should be possible, WordPress provides the [WP\_Session\_Tokens](https://developer.wordpress.org/reference/classes/wp_session_tokens/) class to manage logged in sessions. Then it's just a matter of connecting it to the cron. The following is a simple plugin file which I think should do it. Add it to the plugins directory and it should start working. \*not tested. ``` <?php /* Plugin Name: Logout Users Description: Forces all users to be logged out twice a day. Author: Tim Ross Version: 1.0.0 Author URI: https://timrosswebdevelopment.com */ /** * Create hook and schedule cron job on plugin activation. * Schedule recurring cron event. */ function logout_users_plugin_activate() { $timestamp2pm = strtotime( '14:00:00' ); // 2:00 PM. $timestamp10pm = strtotime( '22:00:00' ); // 10:00 PM. // check to make sure it's not already scheduled. if ( ! wp_next_scheduled( 'logout_users_plugin_cron_hook' ) ) { wp_schedule_event( $timestamp2pm, 'daily', 'logout_users_plugin_cron_hook' ); wp_schedule_event( $timestamp10pm, 'daily', 'logout_users_plugin_cron_hook' ); // use wp_schedule_single_event function for non-recurring. } } register_activation_hook( __FILE__, 'logout_users_plugin_activate' ); /** * Unset cron event on plugin deactivation. */ function logout_users_plugin_deactivate() { wp_clear_scheduled_hook( 'logout_users_plugin_cron_hook' ); // unschedule event. } register_deactivation_hook( __FILE__, 'logout_users_plugin_deactivate' ); function logout_all_users() { // Get an instance of WP_User_Meta_Session_Tokens $sessions_manager = WP_Session_Tokens::get_instance(); // Remove all the session data for all users. $sessions_manager->drop_sessions(); } // hook function logout_users_plugin_cron_hook() to the action logout_users_plugin_cron_hook. add_action( 'logout_users_plugin_cron_hook', 'logout_all_users' ); ```
405,965
<p>I have the following functions:</p> <pre><code>function test($post_id){ do_action('test_action',$post_id); echo $post_id; } add_action('test_action',function($post_id){ if ( $post_id == 2 ) //Stop test function execution } </code></pre> <p>Using the function hooked to <code>add_action</code>, how to stop the execution of <code>test()</code> function without adding any code to <code>test()</code>. In the above example, if <code>$post_id == 2</code> , the <code>echo $post_id;</code> code should not run in <code>test()</code>.</p>
[ { "answer_id": 405901, "author": "Tim", "author_id": 118534, "author_profile": "https://wordpress.stackexchange.com/users/118534", "pm_score": 2, "selected": false, "text": "<p>This should be possible, WordPress provides the <a href=\"https://developer.wordpress.org/reference/classes/wp_...
2022/05/22
[ "https://wordpress.stackexchange.com/questions/405965", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142821/" ]
I have the following functions: ``` function test($post_id){ do_action('test_action',$post_id); echo $post_id; } add_action('test_action',function($post_id){ if ( $post_id == 2 ) //Stop test function execution } ``` Using the function hooked to `add_action`, how to stop the execution of `test()` function without adding any code to `test()`. In the above example, if `$post_id == 2` , the `echo $post_id;` code should not run in `test()`.
This should be possible, WordPress provides the [WP\_Session\_Tokens](https://developer.wordpress.org/reference/classes/wp_session_tokens/) class to manage logged in sessions. Then it's just a matter of connecting it to the cron. The following is a simple plugin file which I think should do it. Add it to the plugins directory and it should start working. \*not tested. ``` <?php /* Plugin Name: Logout Users Description: Forces all users to be logged out twice a day. Author: Tim Ross Version: 1.0.0 Author URI: https://timrosswebdevelopment.com */ /** * Create hook and schedule cron job on plugin activation. * Schedule recurring cron event. */ function logout_users_plugin_activate() { $timestamp2pm = strtotime( '14:00:00' ); // 2:00 PM. $timestamp10pm = strtotime( '22:00:00' ); // 10:00 PM. // check to make sure it's not already scheduled. if ( ! wp_next_scheduled( 'logout_users_plugin_cron_hook' ) ) { wp_schedule_event( $timestamp2pm, 'daily', 'logout_users_plugin_cron_hook' ); wp_schedule_event( $timestamp10pm, 'daily', 'logout_users_plugin_cron_hook' ); // use wp_schedule_single_event function for non-recurring. } } register_activation_hook( __FILE__, 'logout_users_plugin_activate' ); /** * Unset cron event on plugin deactivation. */ function logout_users_plugin_deactivate() { wp_clear_scheduled_hook( 'logout_users_plugin_cron_hook' ); // unschedule event. } register_deactivation_hook( __FILE__, 'logout_users_plugin_deactivate' ); function logout_all_users() { // Get an instance of WP_User_Meta_Session_Tokens $sessions_manager = WP_Session_Tokens::get_instance(); // Remove all the session data for all users. $sessions_manager->drop_sessions(); } // hook function logout_users_plugin_cron_hook() to the action logout_users_plugin_cron_hook. add_action( 'logout_users_plugin_cron_hook', 'logout_all_users' ); ```
405,993
<p>I am using <code>get_pages</code> to pull the children pages from a parent and listing them in a similar way to the standard WP loop for pages. This works well using the code referenced below - however.. what I would like to be able to do is to list a page I know the ID for at the top irrespective of its publish date (I am listing the pages in date order). Is this possible? Page ID of the page I want to always be listed first is #196.</p> <p>Thanks</p> <pre><code>&lt;?php $ids = array(); $pages = get_pages(&quot;child_of=&quot;.$post-&gt;ID); if ($pages) { foreach ($pages as $page) { $ids[] = $page-&gt;ID; } } $paged = (get_query_var(&quot;paged&quot;)) ? get_query_var(&quot;paged&quot;) : 1; $args = array( &quot;paged&quot; =&gt; $paged, &quot;post__in&quot; =&gt; $ids, &quot;posts_per_page&quot; =&gt; 100, &quot;post_type&quot; =&gt; &quot;page&quot; ); query_posts($args); if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div class=&quot;feedItemWrapper wpb_animate_when_almost_visible wpb_fadeInUp fadeInUp&quot;&gt; &lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot; title=&quot;&lt;?php the_title(); ?&gt;&quot;&gt; &lt;?php echo get_the_post_thumbnail( $post_id, 'full', array() ); ?&gt; &lt;div class=&quot;feedItemContentWrapper&quot;&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;p&gt;&lt;?php the_excerpt(); ?&gt;&lt;/p&gt; &lt;p class=&quot;date&quot;&gt;&lt;?php echo get_the_date(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/a&gt; </code></pre>
[ { "answer_id": 405901, "author": "Tim", "author_id": 118534, "author_profile": "https://wordpress.stackexchange.com/users/118534", "pm_score": 2, "selected": false, "text": "<p>This should be possible, WordPress provides the <a href=\"https://developer.wordpress.org/reference/classes/wp_...
2022/05/23
[ "https://wordpress.stackexchange.com/questions/405993", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/176049/" ]
I am using `get_pages` to pull the children pages from a parent and listing them in a similar way to the standard WP loop for pages. This works well using the code referenced below - however.. what I would like to be able to do is to list a page I know the ID for at the top irrespective of its publish date (I am listing the pages in date order). Is this possible? Page ID of the page I want to always be listed first is #196. Thanks ``` <?php $ids = array(); $pages = get_pages("child_of=".$post->ID); if ($pages) { foreach ($pages as $page) { $ids[] = $page->ID; } } $paged = (get_query_var("paged")) ? get_query_var("paged") : 1; $args = array( "paged" => $paged, "post__in" => $ids, "posts_per_page" => 100, "post_type" => "page" ); query_posts($args); if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="feedItemWrapper wpb_animate_when_almost_visible wpb_fadeInUp fadeInUp"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php echo get_the_post_thumbnail( $post_id, 'full', array() ); ?> <div class="feedItemContentWrapper"> <h3><?php the_title(); ?></h3> <p><?php the_excerpt(); ?></p> <p class="date"><?php echo get_the_date(); ?></p> </div> </a> ```
This should be possible, WordPress provides the [WP\_Session\_Tokens](https://developer.wordpress.org/reference/classes/wp_session_tokens/) class to manage logged in sessions. Then it's just a matter of connecting it to the cron. The following is a simple plugin file which I think should do it. Add it to the plugins directory and it should start working. \*not tested. ``` <?php /* Plugin Name: Logout Users Description: Forces all users to be logged out twice a day. Author: Tim Ross Version: 1.0.0 Author URI: https://timrosswebdevelopment.com */ /** * Create hook and schedule cron job on plugin activation. * Schedule recurring cron event. */ function logout_users_plugin_activate() { $timestamp2pm = strtotime( '14:00:00' ); // 2:00 PM. $timestamp10pm = strtotime( '22:00:00' ); // 10:00 PM. // check to make sure it's not already scheduled. if ( ! wp_next_scheduled( 'logout_users_plugin_cron_hook' ) ) { wp_schedule_event( $timestamp2pm, 'daily', 'logout_users_plugin_cron_hook' ); wp_schedule_event( $timestamp10pm, 'daily', 'logout_users_plugin_cron_hook' ); // use wp_schedule_single_event function for non-recurring. } } register_activation_hook( __FILE__, 'logout_users_plugin_activate' ); /** * Unset cron event on plugin deactivation. */ function logout_users_plugin_deactivate() { wp_clear_scheduled_hook( 'logout_users_plugin_cron_hook' ); // unschedule event. } register_deactivation_hook( __FILE__, 'logout_users_plugin_deactivate' ); function logout_all_users() { // Get an instance of WP_User_Meta_Session_Tokens $sessions_manager = WP_Session_Tokens::get_instance(); // Remove all the session data for all users. $sessions_manager->drop_sessions(); } // hook function logout_users_plugin_cron_hook() to the action logout_users_plugin_cron_hook. add_action( 'logout_users_plugin_cron_hook', 'logout_all_users' ); ```
406,014
<p>I'm wondering if there is a way to remove the typography and custom color panels from the sidebar for <em>just</em> the paragraph block.</p> <p>I've currently written a function that I've added add_theme_support to for the typography panel and custom color picker but it's affecting every block that can utilize those things. Here is said function:</p> <pre><code> public function typography_custom_color_theme_support() { // Disable Custom Color Picker add_theme_support( 'editor-color-palette' ); add_theme_support( 'disable-custom-colors' ); // Disable Font Size and Custom Font Size Dropdowns add_theme_support( 'editor-font-sizes' ); add_theme_support( 'disable-custom-font-sizes' ); } </code></pre> <p>If possible, could I add a conditional to this along the lines of &quot;if paragraph block is selected run add_theme_support actions?&quot;</p> <p>Thank you.</p>
[ { "answer_id": 405901, "author": "Tim", "author_id": 118534, "author_profile": "https://wordpress.stackexchange.com/users/118534", "pm_score": 2, "selected": false, "text": "<p>This should be possible, WordPress provides the <a href=\"https://developer.wordpress.org/reference/classes/wp_...
2022/05/23
[ "https://wordpress.stackexchange.com/questions/406014", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/222462/" ]
I'm wondering if there is a way to remove the typography and custom color panels from the sidebar for *just* the paragraph block. I've currently written a function that I've added add\_theme\_support to for the typography panel and custom color picker but it's affecting every block that can utilize those things. Here is said function: ``` public function typography_custom_color_theme_support() { // Disable Custom Color Picker add_theme_support( 'editor-color-palette' ); add_theme_support( 'disable-custom-colors' ); // Disable Font Size and Custom Font Size Dropdowns add_theme_support( 'editor-font-sizes' ); add_theme_support( 'disable-custom-font-sizes' ); } ``` If possible, could I add a conditional to this along the lines of "if paragraph block is selected run add\_theme\_support actions?" Thank you.
This should be possible, WordPress provides the [WP\_Session\_Tokens](https://developer.wordpress.org/reference/classes/wp_session_tokens/) class to manage logged in sessions. Then it's just a matter of connecting it to the cron. The following is a simple plugin file which I think should do it. Add it to the plugins directory and it should start working. \*not tested. ``` <?php /* Plugin Name: Logout Users Description: Forces all users to be logged out twice a day. Author: Tim Ross Version: 1.0.0 Author URI: https://timrosswebdevelopment.com */ /** * Create hook and schedule cron job on plugin activation. * Schedule recurring cron event. */ function logout_users_plugin_activate() { $timestamp2pm = strtotime( '14:00:00' ); // 2:00 PM. $timestamp10pm = strtotime( '22:00:00' ); // 10:00 PM. // check to make sure it's not already scheduled. if ( ! wp_next_scheduled( 'logout_users_plugin_cron_hook' ) ) { wp_schedule_event( $timestamp2pm, 'daily', 'logout_users_plugin_cron_hook' ); wp_schedule_event( $timestamp10pm, 'daily', 'logout_users_plugin_cron_hook' ); // use wp_schedule_single_event function for non-recurring. } } register_activation_hook( __FILE__, 'logout_users_plugin_activate' ); /** * Unset cron event on plugin deactivation. */ function logout_users_plugin_deactivate() { wp_clear_scheduled_hook( 'logout_users_plugin_cron_hook' ); // unschedule event. } register_deactivation_hook( __FILE__, 'logout_users_plugin_deactivate' ); function logout_all_users() { // Get an instance of WP_User_Meta_Session_Tokens $sessions_manager = WP_Session_Tokens::get_instance(); // Remove all the session data for all users. $sessions_manager->drop_sessions(); } // hook function logout_users_plugin_cron_hook() to the action logout_users_plugin_cron_hook. add_action( 'logout_users_plugin_cron_hook', 'logout_all_users' ); ```
406,113
<p>If I need to edit a specific post then I need to click the &quot;All Posts&quot; link and then find it. It would be nice to click directly on a link from within the popup hover sub menu.</p> <p>Something like this:</p> <p><a href="https://i.stack.imgur.com/48y7s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/48y7s.png" alt="An admin sub menu with list of recent posts entries" /></a></p> <p>Disclaimer: I am going to answer my own question.</p>
[ { "answer_id": 406114, "author": "IT goldman", "author_id": 222554, "author_profile": "https://wordpress.stackexchange.com/users/222554", "pm_score": 1, "selected": false, "text": "<p>Yes you can. By hooking into the <code>admin_menu</code> hook you can add sub menu pages, and they will ...
2022/05/26
[ "https://wordpress.stackexchange.com/questions/406113", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/222554/" ]
If I need to edit a specific post then I need to click the "All Posts" link and then find it. It would be nice to click directly on a link from within the popup hover sub menu. Something like this: [![An admin sub menu with list of recent posts entries](https://i.stack.imgur.com/48y7s.png)](https://i.stack.imgur.com/48y7s.png) Disclaimer: I am going to answer my own question.
Yes you can. By hooking into the `admin_menu` hook you can add sub menu pages, and they will appear on hover by default. All you have to do is iterate the recent posts and add them one by one. ``` add_action('admin_menu', function () { $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'orderby' => 'post_date', 'sort_column' => 'post_date', 'sort_order' => 'asc', 'posts_per_page' => 10, ); $arr = get_posts($args); foreach ($arr as $item) { add_submenu_page( 'edit.php', $item->post_name, '• ' . $item->post_title, 'read', 'post.php?post=' . $item->ID . '&action=edit', '' ); } }); ``` **Update:** I wrote a [plugin](https://wordpress.org/plugins/itg-admin-hover-menus/) for this. It also shows pages and custom post types. Hope that helps.
406,123
<p>How can I disable wordpress login temporarily even for administrator users? is there any solution?</p>
[ { "answer_id": 406124, "author": "Bysander", "author_id": 47618, "author_profile": "https://wordpress.stackexchange.com/users/47618", "pm_score": 2, "selected": false, "text": "<p>You could hook into the <a href=\"https://developer.wordpress.org/reference/hooks/wp_authenticate_user/\" re...
2022/05/26
[ "https://wordpress.stackexchange.com/questions/406123", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/154510/" ]
How can I disable wordpress login temporarily even for administrator users? is there any solution?
You could hook into the [`wp_authenticate_user` filter](https://developer.wordpress.org/reference/hooks/wp_authenticate_user/) and return an error. Something like: ```php add_filter( 'wp_authenticate_user', 'wpse_406123_stop_login', -1 ); function wpse_406123_stop_login() { $message = new WP_Error( 'login_disabled', __( '<strong>ERROR</strong>: You cannot login at this time' ) ); return $message; } ``` You can then change your security keys -[the ones that look like this](https://api.wordpress.org/secret-key/1.1/salt/) to something different - that will invalidate all current logins.