qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
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 and is an administrator.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'template_redirect', function() {\n if ( is_page( 4848 ) ) {\n return;\n }\n if (!user_can( wp_get_current_user(), 'administrator' )) {\n wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\n }\n exit;\n} );\n</code></pre>\n" }, { "answer_id": 400842, "author": "Buttered_Toast", "author_id": 192133, "author_profile": "https://wordpress.stackexchange.com/users/192133", "pm_score": 2, "selected": true, "text": "<p>I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted <code>remove_action</code> on it.<br />\nWhat Maythan8 answered will work but it can be done with fewer functions.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', 'bt_maintenance_redirect');\nfunction bt_maintenance_redirect () {\n if (is_page(4848) || current_user_can('administrator')) return;\n if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\n}\n</code></pre>\n<p>You used <code>esc_url_raw</code> but this function is used for escaping url before DB storage, if your url is just for output use <code>esc_url</code>.<br />\nAlso better to use <code>wp_safe_redirect</code> if you are redirecting from and to the same host.</p>\n" } ]
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 and is an administrator.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'template_redirect', function() {\n if ( is_page( 4848 ) ) {\n return;\n }\n if (!user_can( wp_get_current_user(), 'administrator' )) {\n wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\n }\n exit;\n} );\n</code></pre>\n" }, { "answer_id": 400842, "author": "Buttered_Toast", "author_id": 192133, "author_profile": "https://wordpress.stackexchange.com/users/192133", "pm_score": 2, "selected": true, "text": "<p>I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted <code>remove_action</code> on it.<br />\nWhat Maythan8 answered will work but it can be done with fewer functions.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', 'bt_maintenance_redirect');\nfunction bt_maintenance_redirect () {\n if (is_page(4848) || current_user_can('administrator')) return;\n if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\n}\n</code></pre>\n<p>You used <code>esc_url_raw</code> but this function is used for escaping url before DB storage, if your url is just for output use <code>esc_url</code>.<br />\nAlso better to use <code>wp_safe_redirect</code> if you are redirecting from and to the same host.</p>\n" } ]
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 and is an administrator.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'template_redirect', function() {\n if ( is_page( 4848 ) ) {\n return;\n }\n if (!user_can( wp_get_current_user(), 'administrator' )) {\n wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\n }\n exit;\n} );\n</code></pre>\n" }, { "answer_id": 400842, "author": "Buttered_Toast", "author_id": 192133, "author_profile": "https://wordpress.stackexchange.com/users/192133", "pm_score": 2, "selected": true, "text": "<p>I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted <code>remove_action</code> on it.<br />\nWhat Maythan8 answered will work but it can be done with fewer functions.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', 'bt_maintenance_redirect');\nfunction bt_maintenance_redirect () {\n if (is_page(4848) || current_user_can('administrator')) return;\n if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\n}\n</code></pre>\n<p>You used <code>esc_url_raw</code> but this function is used for escaping url before DB storage, if your url is just for output use <code>esc_url</code>.<br />\nAlso better to use <code>wp_safe_redirect</code> if you are redirecting from and to the same host.</p>\n" } ]
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 and is an administrator.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'template_redirect', function() {\n if ( is_page( 4848 ) ) {\n return;\n }\n if (!user_can( wp_get_current_user(), 'administrator' )) {\n wp_redirect( esc_url_raw( home_url( 'maintenance/' ) ) );\n }\n exit;\n} );\n</code></pre>\n" }, { "answer_id": 400842, "author": "Buttered_Toast", "author_id": 192133, "author_profile": "https://wordpress.stackexchange.com/users/192133", "pm_score": 2, "selected": true, "text": "<p>I would advise againt using anonymous functions for callback (when ever you can) as you can't use a targeted <code>remove_action</code> on it.<br />\nWhat Maythan8 answered will work but it can be done with fewer functions.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('template_redirect', 'bt_maintenance_redirect');\nfunction bt_maintenance_redirect () {\n if (is_page(4848) || current_user_can('administrator')) return;\n if (wp_safe_redirect(esc_url(home_url('maintenance/')))) exit;\n}\n</code></pre>\n<p>You used <code>esc_url_raw</code> but this function is used for escaping url before DB storage, if your url is just for output use <code>esc_url</code>.<br />\nAlso better to use <code>wp_safe_redirect</code> if you are redirecting from and to the same host.</p>\n" } ]
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>, as can be <a href=\"https://github.com/WordPress/wordpress-develop/blob/5.8.1/src/wp-includes/general-template.php#L784-L786\" rel=\"nofollow noreferrer\">read in the source code</a>:</p>\n<pre><code> case 'url':\n $output = home_url();\n break;\n</code></pre>\n<blockquote>\n<p>it is said home_url() will return URL with backslash</p>\n</blockquote>\n<p><strong>Wrong</strong>. <a href=\"https://developer.wordpress.org/reference/functions/home_url/\" rel=\"nofollow noreferrer\">In the docu it says</a>, that <code>home_url()</code> will return the &quot;[h]ome URL link <strong>with optional path appended</strong>&quot; (emphasis mine).</p>\n<hr />\n<p>If you want the home URL to always have the trailing slash, you can use the <code>home_url</code> filter, because under the hood, <code>home_url()</code> will use <a href=\"https://developer.wordpress.org/reference/functions/get_home_url/\" rel=\"nofollow noreferrer\"><code>get_home_url()</code></a>:</p>\n<pre><code>add_filter('home_url', function (string $url): string {\n // already has trailing slash\n if (substr($url, -1) === '/') {\n return $url;\n }\n\n // add trailing slash\n return $url . '/';\n}, 10);\n</code></pre>\n<p>(or much less readable but a one-liner)</p>\n<pre><code>// force trailing slash\nadd_filter('home_url', fn (string $url): string =&gt; $url . (substr($url, -1) !== '/' ? '/' : ''), 10);\n</code></pre>\n<p>However, this might break some existing implementations, that rely on <code>home_url()</code> not returning the trailing slash, so use at your own risk!</p>\n" }, { "answer_id": 400891, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/home_url/#comment-428\" rel=\"nofollow noreferrer\">The Codex example for home_url()</a> says you want <code>home_url( '/' )</code> to get the blog's URL with a trailing slash.</p>\n<p>Alternatively you could use <code>trailingslashit( home_url() )</code>. 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.</p>\n" } ]
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.wordpress.org/reference/hooks/template_include\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/template_include</a></p>\n<p>At this point you can add a condition and returning the correct template path</p>\n<pre><code>add_filter( 'template_include', 'redirect_single' );\nfunction redirect_single( $template ){\nif($_POST['template'] == 'gallery') {\n $template = path/to/your/template;\n }elseif($_POST['template'] == 'other'){\n $template = path/to/your/template;\n }\nreturn $template;\n}\n</code></pre>\n" }, { "answer_id": 400918, "author": "DeltaG", "author_id": 168537, "author_profile": "https://wordpress.stackexchange.com/users/168537", "pm_score": 0, "selected": false, "text": "<p>If you're going this way, you should use <code>$_GET</code> and <strong>not</strong> <code>$_POST</code>. Because it looks like you are not making a post request.</p>\n<p>So:</p>\n<pre><code>if ( isset($_GET['template']) &amp;&amp; $_GET['template'] == 'gallery' ) {\n</code></pre>\n<p>Other than that, you should open PHP with <code>&lt;?php</code> instead of <code>&lt;php</code>.</p>\n" } ]
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()</code> page number then this will require a little more logic.</p>\n<p>But if you are simply trying execute a function if a post is on an archive page one... then this should be pretty straight forward doing this...</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?=\n// args\n$args = [\n 'post_type' =&gt; 'post',\n 'posts_per_page' =&gt; 10,\n 'paged' =&gt; get_query_var('paged') ? absint(get_query_var('paged')) : 1\n];\n\n// setup query\n$query = new WP_Query($args);\n\n</code></pre>\n<p>This will detect what page your are on with above query...</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n\n// if above query page number is 1\nif($query['paged'] === 1 ) {\n\n // do stuff\n\n}\n</code></pre>\n<p>Hopefully makes sense. Let me know if not.</p>\n" }, { "answer_id": 401017, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<blockquote>\n<p>The problem is that it also shows the featured image, in the same\nspot, on pages 2, 3, 4, etc of the same article (when I have used\n<code>&lt;!--nextpage--&gt;</code>). The featured image should only show on the first\npage of any article.</p>\n</blockquote>\n<p>In that case, then this might work for you:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function insert_feat_image( $content ) {\n global $page, $multipage;\n\n if ( $multipage &amp;&amp; $page &lt;= 1 ) {\n // it's the 1st page, so run your code here.\n } // else, it's not paginated or not the 1st page\n\n return $content;\n}\n</code></pre>\n<p>Explanation about the global variables above:</p>\n<ol>\n<li><p><code>$multipage</code> is a boolean flag indicating whether the page/post is paginated using the <code>&lt;!--nextpage--&gt;</code> tag (or the <a href=\"https://wordpress.org/support/article/page-break-block/\" rel=\"nofollow noreferrer\">Page Break block</a> in Gutenberg), and the flag would be a <em>true</em>, as long as the post contains the <code>&lt;!--nextpage--&gt;</code> tag and that the global post data has already been setup, e.g. <a href=\"https://developer.wordpress.org/reference/functions/the_post/\" rel=\"nofollow noreferrer\"><code>the_post()</code></a> or <a href=\"https://developer.wordpress.org/reference/functions/setup_postdata/\" rel=\"nofollow noreferrer\"><code>setup_postdata()</code></a> has been called. (which is true when inside The Loop)</p>\n</li>\n<li><p>The page number is stored in <code>$page</code>, but the number can also be retrieved using <code>get_query_var( 'page' )</code>. (yes, it's <code>page</code> and <em>not</em> <code>paged</code>)</p>\n</li>\n</ol>\n<h2>Alternate Solution</h2>\n<p>If you just wanted to know whether it's the first page or not, regardless how the page/post was paginated (and <strong>only if</strong> 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 <em>any pages</em> (single Post/Page/CPT, category archives, search results pages, etc.):</p>\n<pre class=\"lang-php prettyprint-override\"><code>function insert_feat_image( $content ) {\n global $page, $multipage, $paged, $wp_query;\n\n $page_num = max( 1, $page, $paged );\n /* Or you can use:\n $page_num = max( 1, get_query_var( 'page' ), get_query_var( 'paged' ) );\n */\n\n if ( ( $multipage || $wp_query-&gt;max_num_pages &gt; 1 ) &amp;&amp; $page_num &lt;= 1 ) {\n // it's the 1st page, so run your code here.\n } // else, it's not paginated or not the 1st page\n\n return $content;\n}\n</code></pre>\n" } ]
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;paged&quot; ) ? get_query_var( &quot;paged&quot; ) : 1;\n</code></pre>\n<p>This is inside a function that is used on both an AJAX handler, and on a page request. <code>get_query_var</code> pulls the parameters from the main query ( aka the primary <code>WP_Query</code> that powers functions such as <code>the_post</code>, <code>have_posts()</code> etc ). But this will <strong>never</strong> work in an AJAX request.</p>\n<p>For this reason, when you request the next page from AJAX it will always result in page <code>1</code>. 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 <code>WP_Query</code> parameters directly. Even if there was a main query it would not be the same main query.</p>\n<p>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.</p>\n<p>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? <code>get_query_var</code> won't work, there is no main query to get a query var from! ).</p>\n<hr />\n<p>What's more, I have a strong suspicion that you're either unaware of <code>archive-mycustompost.php</code>, the <code>pre_get_posts</code> 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. <code>example.com/?s=test&amp;posts_per_page=7&amp;paged=2</code> gets the second page of a search query for &quot;Test&quot; that has 7 posts per page. In the majority of cases a secondary query and a custom page template are completely unnecessary.</p>\n" }, { "answer_id": 401134, "author": "DevelJoe", "author_id": 188571, "author_profile": "https://wordpress.stackexchange.com/users/188571", "pm_score": 0, "selected": false, "text": "<p>Okay finally got this working. For reasons I will not detail here, I preferred a pagination solution which uses ONE single callback which I use everywhere where I need the pagination. In other words, I call the callback call on both upon page load of the template pages needing the query AND as well when click on a pagination link OR applying any search filter to query for the posts.</p>\n<p>In cases which do not require you to do this, of course you can refer to the discussion among @Tom J Nowell and me (in his answer above, thx again!). If possible with your design, you thus may use the WP REST API (instead of using the AP AJAX API) to create the request, an archive page + WP's main query loop + the related pagination features associated to that main query.</p>\n<p>If you prefer to create a WP pagination solution which uses exclusively WP AJAX via <code>$_POST</code>, you can easily do this by providing the additional number of the page you're requesting to your ajax handler via JS, and simply use 1 if none is provided. So my function above became:</p>\n<pre><code>function custom_retrieve_posts_function( $paged = 1 ) {\n\nif ( isset($_POST['page_to_request'] ) ) {\n $paged = intval( sanitize_text_field( isset( $_POST['page_to_request'] ) ) );\n}\n\n$args = array(\n 'post_type' =&gt; 'my_custom_post_type',\n 'tax_query' =&gt; $tax_query_array,\n 'orderby' =&gt; array(\n 'meta_value_num' =&gt; 'ASC',\n 'date' =&gt; 'DESC'\n ),\n 'meta_key' =&gt; 'my_custom_meta_key',\n 'posts_per_page' =&gt; 7,\n 'paged' =&gt; $paged\n);\n\n$query = new \\WP_Query( $args );\n$output = &quot;&quot;;\nif ( $query-&gt;have_posts() ) {\n\n while ( $query-&gt;have_posts() ) {\n\n // Iterate next post of query result\n $query-&gt;the_post();\n\n $output .= get_the_content();\n\n }\n\n // Only display arrows if links have been obtained, so do it in this way\n $max_num_pages = $query-&gt;max_num_pages;\n\n $nav_links = &quot;&lt;div id=\\&quot;navigation-links\\&quot;&gt;&quot;.\n\n // If we're not on the first page, add a link allowing to go back to\n // the one previous to the one currently requested\n &quot;&lt;span id=\\&quot;previous-link\\&quot;&quot;.(\n ( $max_num_pages !== 1 ) ?\n &quot; data-previous-page='&quot;.( $paged - 1 ).&quot;'&gt;&amp;#8678 Back&quot; :\n &quot;&gt;&quot;\n ).\n &quot;&lt;/span&gt;&quot;.\n\n // If we're not on the last page, add a link allowing to go forward to\n // the page subsequent to the one currently requested \n &quot;&lt;span id=\\&quot;next-link\\&quot;&quot;.(\n ( $max_num_pages &gt; $paged ) ?\n &quot; data-next-page='&quot;.( $paged + 1 ).&quot;'&gt;Next &amp;#8680&quot; :\n &quot;&gt;&quot;\n ).\n &quot;&lt;/span&gt;&quot;.\n\n &quot;&lt;/div&gt;&quot;;\n\n $output .= $nav_links;\n\n // Reset the wp_query loop\n wp_reset_postdata();\n \n } else {\n\n $output = &quot;&lt;p class=\\&quot;no-results\\&quot;&gt;Oops!&lt;/p&gt;&quot;;\n\n}\n\necho $output;\n\n}\n</code></pre>\n<p>Note that I've added <code>date</code> into my <code>order</code> clause, additionally to what's been specified in my question above. This is because I've found out that page n of your pagination may show posts of previous pages m where m &lt; n, if you have many posts which have the same meta value. Even using the offset parameter of the wp query etc. will not eliminate this problem. So I thought of first using the ordering I need in my case (the meta key), and then subsequently according to another value which is unique to posts, such as the posts' date. My thought was that like this I can assure that the posts will always be retrieved in exactly the same order, even if their meta value is the same. And well, to have the same order is crucial for proper pagination, no matter the context in which the function is called.</p>\n<p>As I imagine, WP transforms this WP_Query array into a SQL query to query for the according data. So, when using a data field which is unique to a post, but not a date but sth like a primary key in the DB, this may result in faster query times. Hence, instead of the <code>date</code> order key, you may use <code>ID</code>.</p>\n" } ]
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 event that there is no parent it's equal to <code>0</code>.</p>\n<p>In this way, it is possible to create a variable equal to the parent class or the child parent according to the value of <code>$category-&gt;parent</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$categories = get_categories();\nif ( ! is_wp_error( $categories ) ) {\n foreach ( $categories as $category ) {\n $htmlclass = ( $category-&gt;parent === 0 ) ? &quot;level-0&quot; : &quot;level-1&quot;;\n echo '&lt;li class=&quot;' . esc_attr( $htmlclass ).'&quot;&gt;';\n echo '&lt;a href=&quot;' . esc_url( get_category_link( $category-&gt;term_id ) ) . '&quot;&gt;';\n echo esc_html( $category-&gt;name );\n echo '&lt;/a&gt;&lt;/li&gt;';\n }\n}\n</code></pre>\n" }, { "answer_id": 401140, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": -1, "selected": false, "text": "<p>Greatly inspired by @Sabry's answer.</p>\n<p>Term nesting depth is taken into consideration. Also it is one-size-fits-all to work with any taxonomy.</p>\n<pre><code>&lt;?php\n$taxonomy = 'category'; // your requred\n\n$terms = get_terms(\n array(\n 'taxonomy' =&gt; $taxonomy,\n )\n);\n\nif ( ! is_wp_error( $terms ) ) {\n foreach ( $terms as $term ) {\n $term_ancestors = get_ancestors( $term-&gt;term_id, $taxonomy, 'taxonomy' );\n\n $term_nesting_depth = count( $term_ancestors );\n\n $htmlclass = 'level-' . $term_nesting_depth;\n\n echo '&lt;li class=&quot;' . esc_attr( $htmlclass ) . '&quot;&gt;';\n echo '&lt;a href=&quot;' . esc_url( get_term_link( $term, $taxonomy ) ) . '&quot;&gt;';\n echo esc_html( $term-&gt;name );\n echo '&lt;/a&gt;&lt;/li&gt;';\n }\n}\n</code></pre>\n" } ]
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 event that there is no parent it's equal to <code>0</code>.</p>\n<p>In this way, it is possible to create a variable equal to the parent class or the child parent according to the value of <code>$category-&gt;parent</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$categories = get_categories();\nif ( ! is_wp_error( $categories ) ) {\n foreach ( $categories as $category ) {\n $htmlclass = ( $category-&gt;parent === 0 ) ? &quot;level-0&quot; : &quot;level-1&quot;;\n echo '&lt;li class=&quot;' . esc_attr( $htmlclass ).'&quot;&gt;';\n echo '&lt;a href=&quot;' . esc_url( get_category_link( $category-&gt;term_id ) ) . '&quot;&gt;';\n echo esc_html( $category-&gt;name );\n echo '&lt;/a&gt;&lt;/li&gt;';\n }\n}\n</code></pre>\n" }, { "answer_id": 401140, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": -1, "selected": false, "text": "<p>Greatly inspired by @Sabry's answer.</p>\n<p>Term nesting depth is taken into consideration. Also it is one-size-fits-all to work with any taxonomy.</p>\n<pre><code>&lt;?php\n$taxonomy = 'category'; // your requred\n\n$terms = get_terms(\n array(\n 'taxonomy' =&gt; $taxonomy,\n )\n);\n\nif ( ! is_wp_error( $terms ) ) {\n foreach ( $terms as $term ) {\n $term_ancestors = get_ancestors( $term-&gt;term_id, $taxonomy, 'taxonomy' );\n\n $term_nesting_depth = count( $term_ancestors );\n\n $htmlclass = 'level-' . $term_nesting_depth;\n\n echo '&lt;li class=&quot;' . esc_attr( $htmlclass ) . '&quot;&gt;';\n echo '&lt;a href=&quot;' . esc_url( get_term_link( $term, $taxonomy ) ) . '&quot;&gt;';\n echo esc_html( $term-&gt;name );\n echo '&lt;/a&gt;&lt;/li&gt;';\n }\n}\n</code></pre>\n" } ]
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>repeat what you leaned with a fresh mind</li>\n<li>apply the structure:</li>\n</ol>\n<pre><code>&lt;?php if( get_field('field_name') ): ?&gt;\n &lt;p&gt;My field value: &lt;?php the_field('field_name'); ?&gt;&lt;/p&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 401135, "author": "RamMohanSharma", "author_id": 76286, "author_profile": "https://wordpress.stackexchange.com/users/76286", "pm_score": 0, "selected": false, "text": "<p>You should try following to show a specific piece of code if there is something in it.</p>\n<pre><code>if( get_field('field_name') != '' )\n {\n // All Conditional HTML must be kept here.\n the_field('field_name');\n }\n</code></pre>\n<p>As the Variable <strong>get_field('field_name')</strong> will always be there , you just need of check if it holds a blank or Some Real piece of Value.\nThis is the reason behind that !empty doesn't work here.</p>\n" } ]
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>repeat what you leaned with a fresh mind</li>\n<li>apply the structure:</li>\n</ol>\n<pre><code>&lt;?php if( get_field('field_name') ): ?&gt;\n &lt;p&gt;My field value: &lt;?php the_field('field_name'); ?&gt;&lt;/p&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 401135, "author": "RamMohanSharma", "author_id": 76286, "author_profile": "https://wordpress.stackexchange.com/users/76286", "pm_score": 0, "selected": false, "text": "<p>You should try following to show a specific piece of code if there is something in it.</p>\n<pre><code>if( get_field('field_name') != '' )\n {\n // All Conditional HTML must be kept here.\n the_field('field_name');\n }\n</code></pre>\n<p>As the Variable <strong>get_field('field_name')</strong> will always be there , you just need of check if it holds a blank or Some Real piece of Value.\nThis is the reason behind that !empty doesn't work here.</p>\n" } ]
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 posts. Pull it out of the if condition if you want to apply it site-wide.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function wpdocs_replace_content( $text_content ) {\n $text = array(\n 'chamber' =&gt; '&lt;strong&gt;chamber&lt;/strong&gt;',\n );\n $text_content = str_ireplace( array_keys( $text ), $text, $text_content );\n return $text_content;\n}\nadd_filter( 'the_content', 'wpdocs_replace_content' );\n</code></pre>\n" }, { "answer_id": 401224, "author": "RamMohanSharma", "author_id": 76286, "author_profile": "https://wordpress.stackexchange.com/users/76286", "pm_score": 1, "selected": false, "text": "<p>To debug the aforesaid issue you might need to keep these things in mind.</p>\n<ul>\n<li>Review your function <code>add_filter('the_content', 'wpdocs_replace_content' );</code></li>\n<li>It's filtering the output returned by <code>the_content()</code> wordpress function. Which is working quite fine.</li>\n<li>Possible Questions arise that why is this not working in your theme. So the answer to that is your theme is not calling the content via <code>the_content()</code> function.</li>\n<li>Check in your template if there is this function called to display your content <code>echo get_the_content();</code> Just change it to <code>the_content()</code></li>\n</ul>\n<p>Thanks &amp; Keep posted</p>\n" } ]
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": "RamMohanSharma", "author_id": 76286, "author_profile": "https://wordpress.stackexchange.com/users/76286", "pm_score": 1, "selected": false, "text": "<p>I think you must try changing $item['id'] to this</p>\n<pre><code>foreach ( $order-&gt;get_items() as $item )\n{\n$product = $item-&gt;get_data();\n$item_id = $item-&gt;get_product_id();\n if( $item_id == 1136 )\n {\n // Keep Your code here. \n }\n}\n</code></pre>\n<p>Keep Posted.</p>\n" } ]
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\nWordPress designs but I am not able to find where to add $wp_admin_bar\nthat does not trigger an error.</p>\n</blockquote>\n<p>The <a href=\"https://developer.wordpress.org/reference/hooks/wp_before_admin_bar_render/\" rel=\"nofollow noreferrer\"><code>wp_before_admin_bar_render</code> hook</a> doesn't pass the admin bar object, but you can access it manually (from within a function or a class method) using <code>global</code> like so, just like the Codex example <a href=\"https://developer.wordpress.org/reference/hooks/wp_before_admin_bar_render/#comment-4502\" rel=\"nofollow noreferrer\">here</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function remove_wp_logo() {\n global $wp_admin_bar;\n\n $wp_admin_bar-&gt;remove_menu( 'wp-logo' );\n}\n</code></pre>\n" }, { "answer_id": 401284, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 1, "selected": false, "text": "<p>As Sally pointed out, you can use the global variable. However, that makes your code a bit harder to test and to understand. The better way is using the proper hook <code>admin_bar_menu</code>. Like this:</p>\n<pre><code>add_action( 'admin_bar_menu', function( \\WP_Admin_Bar $wp_admin_bar ) {\n new adminPanel( $wp_admin_bar ); \n});\n</code></pre>\n<p>And then take this object in your constructor:</p>\n<pre><code>class adminPanel \n{\n private $admin_bar;\n \n public function __construct( \\WP_Admin_Bar $wp_admin_bar )\n {\n $this-admin_bar = $wp_admin_bar;\n }\n}\n</code></pre>\n<p>Then you can access this object in all your methods, and you can mock it in your unit tests.</p>\n" } ]
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-pingbacks/\" rel=\"nofollow noreferrer\">Pingbacks</a>.</p>\n<p>If you don't want them you can either disable them <a href=\"https://wordpress.org/support/article/settings-discussion-screen/#default-article-setting\" rel=\"nofollow noreferrer\">globally in the settings</a> or just for a specific post in the &quot;Discussion&quot; metabox in the sidebar of that post.</p>\n" }, { "answer_id": 401309, "author": "mathse", "author_id": 216984, "author_profile": "https://wordpress.stackexchange.com/users/216984", "pm_score": 0, "selected": false, "text": "<p>I have now done the &quot;trick&quot; of <a href=\"https://wp-mix.com/wordpress-clean-up-do_pings/\" rel=\"nofollow noreferrer\">this blog post</a> and added the following code:</p>\n<pre><code>if (isset($_GET['doing_wp_cron'])) {\n remove_action('do_pings', 'do_all_pings');\n wp_clear_scheduled_hook('do_pings');\n}\n</code></pre>\n<p>With this I get no pings and no new outgoing connections in my firewall. Thanks @kraftner for the hint to pings - I really didn't think that this is the cause of my problem (since I deactivated them in the options).</p>\n" } ]
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-pingbacks/\" rel=\"nofollow noreferrer\">Pingbacks</a>.</p>\n<p>If you don't want them you can either disable them <a href=\"https://wordpress.org/support/article/settings-discussion-screen/#default-article-setting\" rel=\"nofollow noreferrer\">globally in the settings</a> or just for a specific post in the &quot;Discussion&quot; metabox in the sidebar of that post.</p>\n" }, { "answer_id": 401309, "author": "mathse", "author_id": 216984, "author_profile": "https://wordpress.stackexchange.com/users/216984", "pm_score": 0, "selected": false, "text": "<p>I have now done the &quot;trick&quot; of <a href=\"https://wp-mix.com/wordpress-clean-up-do_pings/\" rel=\"nofollow noreferrer\">this blog post</a> and added the following code:</p>\n<pre><code>if (isset($_GET['doing_wp_cron'])) {\n remove_action('do_pings', 'do_all_pings');\n wp_clear_scheduled_hook('do_pings');\n}\n</code></pre>\n<p>With this I get no pings and no new outgoing connections in my firewall. Thanks @kraftner for the hint to pings - I really didn't think that this is the cause of my problem (since I deactivated them in the options).</p>\n" } ]
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</code> and MAY also be supported by <code>wp plugin update</code>. Daniel addresses a syntax issue with that feature here: <a href=\"https://github.com/wp-cli/wp-cli/issues/2170\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/wp-cli/issues/2170</a></p>\n<p>Documentation for <code>install</code> indicates acceptance of a plugin slug (.org) or the path/URL to the ZIP file:\n<a href=\"https://developer.wordpress.org/cli/commands/plugin/install/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/plugin/install/</a></p>\n<p>Have you tried <code>wp plugin update &quot;your_plugin_url&quot;</code>?</p>\n<p>Daniel also references the ability of non-WP.org plugins to introduce an update in his answer to a tangentially related question on Github:</p>\n<pre><code>For a non-WordPress.org plugin to introduce an update, it needs to filter the update_plugins transient to return what's called a &quot;download offer&quot; for the plugin.\n\nWP Remote has a relevant piece of support documentation: https://wpremote.com/support-center/integrating-wp-remote/adding-wp-remote-support-premium-theme-plugin/\n</code></pre>\n<p>Here's a direct link:\n<a href=\"https://github.com/wp-cli/wp-cli/issues/1662\" rel=\"nofollow noreferrer\">https://github.com/wp-cli/wp-cli/issues/1662</a></p>\n<p>Hope that helps.</p>\n" }, { "answer_id": 401530, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You would implement this:</p>\n<p><a href=\"https://make.wordpress.org/core/2021/06/29/introducing-update-uri-plugin-header-in-wordpress-5-8/\" rel=\"nofollow noreferrer\">https://make.wordpress.org/core/2021/06/29/introducing-update-uri-plugin-header-in-wordpress-5-8/</a></p>\n<p>First you would add a <code>Update URI: </code> header to your plugin with a custom domain.</p>\n<p>Second, you would add a filter to your plugin, using the filter name <code>update_plugins_{$hostname}</code> where <code>{$hostname}</code> is the value you gave your <code>Update URI: </code>. E.g. <code>Update URI: example.com</code> would have the filter <code>update_plugins_example.com</code>.</p>\n<p>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.</p>\n<p><a href=\"https://developer.wordpress.org/reference/hooks/update_plugins_hostname/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/update_plugins_hostname/</a></p>\n<p>The value you return will need to be an array containing the values in the parameter section. Or it can return <code>false</code> to indicate there are not updates.</p>\n<p>The second and third parameters can be used to figure out which plugin WP is asking for update information.</p>\n<p>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.</p>\n<p>Here's some untested pseudocode of what I think such a filter might look like:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'update_plugins_example.com', function( $update, array $plugin_data, string $plugin_file, $locales ) {\n // only check this plugin\n if ( $plugin_file !== 'myplugin.php' ) {\n return $update;\n }\n\n // already done update check elsewhere\n if ( ! empty( $update ) ) {\n return $update;\n }\n\n // CODE GOES HERE TO FIND UPDATE, maybe ask a server what\n // the latest version number is and call `version_compare`?\n $is_update_available = true;\n\n // no updates found\n if ( ! $is_update_available ) {\n return false;\n }\n\n // Update found?\n return [\n 'slug' =&gt; 'myplugin',\n 'version' =&gt; '9000',\n 'url' =&gt; 'example.com/myplugin/',\n 'package' =&gt; 'example.com/newversion.zip',\n ];\n}, 10, 4 );\n</code></pre>\n<p>As for the actual checking of the update, that depends entirely on you, there is no canonical correct way to do that.</p>\n<p>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.</p>\n" } ]
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 well? I know how to display children\ncategories</p>\n</blockquote>\n<blockquote>\n<p>I think i need to get term_id somehow</p>\n</blockquote>\n<p>On a term archive page, e.g. at <code>example.com/category/foo/</code> (for the default <code>category</code> taxonomy),</p>\n<ol>\n<li><p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_queried_object/\" rel=\"nofollow noreferrer\"><code>get_queried_object()</code></a> to retrieve the term <em>object</em> for the term being queried (<code>foo</code> in the above sample URL).</p>\n<pre class=\"lang-php prettyprint-override\"><code>$term = get_queried_object();\n$term_id = $term-&gt;term_id;\n</code></pre>\n</li>\n<li><p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_queried_object_id/\" rel=\"nofollow noreferrer\"><code>get_queried_object_id()</code></a> to retrieve just the term <em>ID</em> of the term being queried.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$term_id = get_queried_object_id();\n</code></pre>\n</li>\n</ol>\n<p>Now as for retrieving term's siblings, you can use <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a> just like you did when retrieving the term's children. So for example, for the term being queried (or simply put, the current term),</p>\n<pre class=\"lang-php prettyprint-override\"><code>$taxonomy_name = 'products';\n\n// Get the full term object/data.\n$current_term = get_queried_object();\n\n// Get the term's direct children.\n// **Use 'child_of' instead of 'parent' to retrieve direct and non-direct children.\n$children = get_terms( array(\n 'taxonomy' =&gt; $taxonomy_name,\n 'parent' =&gt; $current_term-&gt;term_id,\n 'hide_empty' =&gt; false,\n) );\n\n// Display the children.\nif ( ! empty( $children ) ) {\n echo &quot;&lt;h3&gt;Children of $current_term-&gt;name&lt;/h3&gt;&quot;;\n echo '&lt;ul&gt;';\n\n foreach ( $children as $child ) {\n echo &quot;&lt;li&gt;$child-&gt;name&lt;/li&gt;&quot;;\n }\n\n echo '&lt;/ul&gt;';\n}\n\n// Get the term's direct siblings.\n$siblings = get_terms( array(\n 'taxonomy' =&gt; $taxonomy_name,\n 'parent' =&gt; $current_term-&gt;parent,\n 'exclude' =&gt; array( $current_term-&gt;term_id ),\n 'hide_empty' =&gt; false,\n) );\n\n// Display the siblings.\nif ( ! empty( $siblings ) ) {\n echo &quot;&lt;h3&gt;Siblings of $current_term-&gt;name&lt;/h3&gt;&quot;;\n echo '&lt;ul&gt;';\n\n foreach ( $siblings as $sibling ) {\n echo &quot;&lt;li&gt;$sibling-&gt;name&lt;/li&gt;&quot;;\n }\n\n echo '&lt;/ul&gt;';\n}\n</code></pre>\n<p>And if you want to use <a href=\"https://developer.wordpress.org/reference/functions/get_term_children/\" rel=\"nofollow noreferrer\"><code>get_term_children()</code></a>, note that it retrieves all <em>direct and non-direct</em> children (just like <code>get_terms()</code> if <code>child_of</code> is used), and the function returns an <em>array of term <strong>ID</strong></em>s, hence in your <code>foreach</code>, you can use <a href=\"https://developer.wordpress.org/reference/functions/get_term/\" rel=\"nofollow noreferrer\"><code>get_term()</code></a> to get the full term object/data.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$term_id = get_queried_object_id(); // or just use a specific term ID, if you want to\n$termchildren = get_term_children( $term_id, $taxonomy_name );\n\nforeach ( $termchildren as $child_id ) {\n $child = get_term( $child_id );\n // ... your code.\n}\n</code></pre>\n<blockquote>\n<p>how i exclude existing category i am on from this list</p>\n</blockquote>\n<ul>\n<li><p>If you use <code>get_terms()</code>, you can use the <code>exclude</code> arg like you can see in my example above.</p>\n</li>\n<li><p>If you use <code>get_term_children()</code>, then you can use <code>continue</code> like so: (but that's just an example; you can use <code>array_filter()</code> to filter the <code>$termchildren</code> array <em>before</em> looping through the items, if you want to)</p>\n<pre class=\"lang-php prettyprint-override\"><code>foreach ( $termchildren as $child_id ) {\n if ( (int) $child_id === (int) $term_id ) {\n continue;\n }\n\n $child = get_term( $child_id );\n // ... your code.\n}\n</code></pre>\n</li>\n</ul>\n" }, { "answer_id": 401479, "author": "Alex Osipov", "author_id": 76850, "author_profile": "https://wordpress.stackexchange.com/users/76850", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;ul class=&quot;display-children-block slider-container-list sub-categories-block front-categories-block front-categories-scroll&quot;&gt;\n&lt;?php\n$term = get_queried_object();\n$children = get_terms( $term-&gt;taxonomy, array(\n'parent' =&gt; $term-&gt;term_id,\n'hide_empty' =&gt; false\n) );\nif ( $children ) {\nforeach( $children as $subcat ){\n 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;';\n 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;';\n echo '&lt;div class=&quot;category-title&quot;&gt;' . $subcat-&gt;name . '&lt;/div&gt;&lt;/a&gt;&lt;/li&gt;';\n}\n}\n?&gt;\n&lt;/ul&gt;\n&lt;ul class=&quot;display-siblings-block slider-container-list sub-categories-block front-categories-block front-categories-scroll&quot;&gt;\n &lt;?php\n$term = get_queried_object();\n$siblings = get_terms( $term-&gt;taxonomy, array(\n 'parent' =&gt; $term-&gt;parent,\n 'taxonomy' =&gt; $taxonomy_name,\n 'exclude' =&gt; array( $term-&gt;term_id ),\n 'hide_empty' =&gt; false,\n) );\n\nif ( $siblings ) {\n foreach( $siblings as $sibling ){\n 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;';\n 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;';\n echo '&lt;div class=&quot;category-title&quot;&gt;' . $sibling-&gt;name . '&lt;/div&gt;&lt;/a&gt;&lt;/li&gt;';\n }\n}\n?&gt;\n&lt;/ul&gt;\n</code></pre>\n<p>This is what i did for all of it and it works!</p>\n<p>Also this snippet add class to the :</p>\n<pre><code>add_filter( 'body_class', 'custom_cat_archiev_class' );\nfunction custom_cat_archiev_class( $classes ) {\n if ( is_category() ) {\n $cat = get_queried_object();\n $ancestors = get_ancestors( $cat-&gt;term_id, 'category', 'taxonomy' );\n $classes[] = 'category-level-' . ( count( $ancestors ) + 1 );\n }\n return $classes;\n}\n</code></pre>\n<p>And i am using css to remove siblings from top level Categories.</p>\n<p>Honestly i think i can make it cleaner without classes and css. But i am not sure how!</p>\n" } ]
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 well? I know how to display children\ncategories</p>\n</blockquote>\n<blockquote>\n<p>I think i need to get term_id somehow</p>\n</blockquote>\n<p>On a term archive page, e.g. at <code>example.com/category/foo/</code> (for the default <code>category</code> taxonomy),</p>\n<ol>\n<li><p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_queried_object/\" rel=\"nofollow noreferrer\"><code>get_queried_object()</code></a> to retrieve the term <em>object</em> for the term being queried (<code>foo</code> in the above sample URL).</p>\n<pre class=\"lang-php prettyprint-override\"><code>$term = get_queried_object();\n$term_id = $term-&gt;term_id;\n</code></pre>\n</li>\n<li><p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_queried_object_id/\" rel=\"nofollow noreferrer\"><code>get_queried_object_id()</code></a> to retrieve just the term <em>ID</em> of the term being queried.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$term_id = get_queried_object_id();\n</code></pre>\n</li>\n</ol>\n<p>Now as for retrieving term's siblings, you can use <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\"><code>get_terms()</code></a> just like you did when retrieving the term's children. So for example, for the term being queried (or simply put, the current term),</p>\n<pre class=\"lang-php prettyprint-override\"><code>$taxonomy_name = 'products';\n\n// Get the full term object/data.\n$current_term = get_queried_object();\n\n// Get the term's direct children.\n// **Use 'child_of' instead of 'parent' to retrieve direct and non-direct children.\n$children = get_terms( array(\n 'taxonomy' =&gt; $taxonomy_name,\n 'parent' =&gt; $current_term-&gt;term_id,\n 'hide_empty' =&gt; false,\n) );\n\n// Display the children.\nif ( ! empty( $children ) ) {\n echo &quot;&lt;h3&gt;Children of $current_term-&gt;name&lt;/h3&gt;&quot;;\n echo '&lt;ul&gt;';\n\n foreach ( $children as $child ) {\n echo &quot;&lt;li&gt;$child-&gt;name&lt;/li&gt;&quot;;\n }\n\n echo '&lt;/ul&gt;';\n}\n\n// Get the term's direct siblings.\n$siblings = get_terms( array(\n 'taxonomy' =&gt; $taxonomy_name,\n 'parent' =&gt; $current_term-&gt;parent,\n 'exclude' =&gt; array( $current_term-&gt;term_id ),\n 'hide_empty' =&gt; false,\n) );\n\n// Display the siblings.\nif ( ! empty( $siblings ) ) {\n echo &quot;&lt;h3&gt;Siblings of $current_term-&gt;name&lt;/h3&gt;&quot;;\n echo '&lt;ul&gt;';\n\n foreach ( $siblings as $sibling ) {\n echo &quot;&lt;li&gt;$sibling-&gt;name&lt;/li&gt;&quot;;\n }\n\n echo '&lt;/ul&gt;';\n}\n</code></pre>\n<p>And if you want to use <a href=\"https://developer.wordpress.org/reference/functions/get_term_children/\" rel=\"nofollow noreferrer\"><code>get_term_children()</code></a>, note that it retrieves all <em>direct and non-direct</em> children (just like <code>get_terms()</code> if <code>child_of</code> is used), and the function returns an <em>array of term <strong>ID</strong></em>s, hence in your <code>foreach</code>, you can use <a href=\"https://developer.wordpress.org/reference/functions/get_term/\" rel=\"nofollow noreferrer\"><code>get_term()</code></a> to get the full term object/data.</p>\n<pre class=\"lang-php prettyprint-override\"><code>$term_id = get_queried_object_id(); // or just use a specific term ID, if you want to\n$termchildren = get_term_children( $term_id, $taxonomy_name );\n\nforeach ( $termchildren as $child_id ) {\n $child = get_term( $child_id );\n // ... your code.\n}\n</code></pre>\n<blockquote>\n<p>how i exclude existing category i am on from this list</p>\n</blockquote>\n<ul>\n<li><p>If you use <code>get_terms()</code>, you can use the <code>exclude</code> arg like you can see in my example above.</p>\n</li>\n<li><p>If you use <code>get_term_children()</code>, then you can use <code>continue</code> like so: (but that's just an example; you can use <code>array_filter()</code> to filter the <code>$termchildren</code> array <em>before</em> looping through the items, if you want to)</p>\n<pre class=\"lang-php prettyprint-override\"><code>foreach ( $termchildren as $child_id ) {\n if ( (int) $child_id === (int) $term_id ) {\n continue;\n }\n\n $child = get_term( $child_id );\n // ... your code.\n}\n</code></pre>\n</li>\n</ul>\n" }, { "answer_id": 401479, "author": "Alex Osipov", "author_id": 76850, "author_profile": "https://wordpress.stackexchange.com/users/76850", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;ul class=&quot;display-children-block slider-container-list sub-categories-block front-categories-block front-categories-scroll&quot;&gt;\n&lt;?php\n$term = get_queried_object();\n$children = get_terms( $term-&gt;taxonomy, array(\n'parent' =&gt; $term-&gt;term_id,\n'hide_empty' =&gt; false\n) );\nif ( $children ) {\nforeach( $children as $subcat ){\n 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;';\n 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;';\n echo '&lt;div class=&quot;category-title&quot;&gt;' . $subcat-&gt;name . '&lt;/div&gt;&lt;/a&gt;&lt;/li&gt;';\n}\n}\n?&gt;\n&lt;/ul&gt;\n&lt;ul class=&quot;display-siblings-block slider-container-list sub-categories-block front-categories-block front-categories-scroll&quot;&gt;\n &lt;?php\n$term = get_queried_object();\n$siblings = get_terms( $term-&gt;taxonomy, array(\n 'parent' =&gt; $term-&gt;parent,\n 'taxonomy' =&gt; $taxonomy_name,\n 'exclude' =&gt; array( $term-&gt;term_id ),\n 'hide_empty' =&gt; false,\n) );\n\nif ( $siblings ) {\n foreach( $siblings as $sibling ){\n 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;';\n 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;';\n echo '&lt;div class=&quot;category-title&quot;&gt;' . $sibling-&gt;name . '&lt;/div&gt;&lt;/a&gt;&lt;/li&gt;';\n }\n}\n?&gt;\n&lt;/ul&gt;\n</code></pre>\n<p>This is what i did for all of it and it works!</p>\n<p>Also this snippet add class to the :</p>\n<pre><code>add_filter( 'body_class', 'custom_cat_archiev_class' );\nfunction custom_cat_archiev_class( $classes ) {\n if ( is_category() ) {\n $cat = get_queried_object();\n $ancestors = get_ancestors( $cat-&gt;term_id, 'category', 'taxonomy' );\n $classes[] = 'category-level-' . ( count( $ancestors ) + 1 );\n }\n return $classes;\n}\n</code></pre>\n<p>And i am using css to remove siblings from top level Categories.</p>\n<p>Honestly i think i can make it cleaner without classes and css. But i am not sure how!</p>\n" } ]
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/security/securing-output/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/plugins/security/securing-output/</a></p>\n" }, { "answer_id": 401501, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<ol>\n<li>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.</li>\n<li>In this case I would suggest it for similar reasons to #1. You may know where <code>$class</code> is coming from now, but this may change in future, and it prepares the function for potential use in different contexts where <code>$class</code> may not be controlled.</li>\n<li>You need to escape here because you know for certain that your code has no control over what the value of <code>$class</code> 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 <code>&quot;</code> 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.</li>\n</ol>\n" } ]
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>add_action('pre_get_posts', 'query_custom_admin_search', 21 );\nfunction query_custom_admin_search( $wp_query ) {\n global $current_user;\n if (current_user_can('administrator' &amp;&amp; is_admin()){\n if ( $wp_query-&gt;query['post_type'] != &quot;apartments&quot; ){\n return;\n }else{\n $custom_fields = array(&quot;city&quot;,&quot;state_county&quot;,);\n $search_term = $wp_query-&gt;query_vars['s'];\n if ( $search_term != '' ) {\n $meta_query = array( 'relation' =&gt; 'OR' );\n foreach( $custom_fields as $custom_field ) {\n array_push( $meta_query, array(\n 'key' =&gt; $custom_field,\n 'value' =&gt; $search_term,\n 'compare' =&gt; 'LIKE'\n ));\n }\n $wp_query-&gt;set( 'meta_query', $meta_query );\n }\n return;\n }\n }else{\n return $wp_query;\n }\n}\n</code></pre>\n" }, { "answer_id": 401642, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<blockquote>\n<p>The only problem is that the default search columns in the wp_posts\ntable such as post_title seem to no longer be searched.</p>\n</blockquote>\n<p>They're actually being searched, but the operator used is <code>AND</code> instead of <code>OR</code> as in <code>WHERE ( &lt;search query&gt; AND &lt;meta query&gt; )</code>, hence if for example one searched for <code>foo</code>, then WordPress will search for posts which..</p>\n<ul>\n<li><p>Contain <code>foo</code> in the post title/content/excerpt <em>and</em></p>\n</li>\n<li><p>Contain <code>foo</code> in the meta <code>city</code> or <code>state_county</code></p>\n</li>\n</ul>\n<p>So if you want the operator be changed to <code>OR</code>, i.e. search in the post title/content/excerpt <strong>or</strong> your custom fields, then you can try the following which simply repositions the default search query in the <code>WHERE</code> clause:</p>\n<ol>\n<li><p>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.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'pre_get_posts', 'query_custom_admin_search', 21 );\nfunction query_custom_admin_search( $query ) {\n // Check if the current user has the 'administrator' role.\n if ( ! in_array( 'administrator', (array) wp_get_current_user()-&gt;roles ) ) {\n return;\n }\n\n // Check if we're on the &quot;Posts&quot; page at wp-admin/edit.php?post_type=apartments\n // and that a search keyword is set.\n if ( ! is_admin() || ! $query-&gt;is_main_query() ||\n 'edit-apartments' !== get_current_screen()-&gt;id ||\n ! strlen( $query-&gt;get( 's' ) )\n ) {\n return;\n }\n\n // Retrieve existing meta queries, if any.\n $meta_query = (array) $query-&gt;get( 'meta_query' );\n\n // Define your custom fields (meta keys).\n $custom_fields = array( 'city', 'state_county' );\n // This is for your custom fields above.\n $meta_query2 = array( 'relation' =&gt; 'OR' );\n\n $s = $query-&gt;get( 's' );\n foreach ( $custom_fields as $meta_key ) {\n $meta_query2[] = array(\n 'key' =&gt; $meta_key,\n 'value' =&gt; $s,\n 'compare' =&gt; 'LIKE',\n );\n }\n\n // Add your meta query to the existing ones in $meta_query.\n $meta_query[] = $meta_query2;\n $query-&gt;set( 'meta_query', $meta_query );\n\n // Set a custom flag for the posts_search and posts_where.\n $query-&gt;set( '_search_OR', true );\n}\n</code></pre>\n</li>\n<li><p>This snippet uses the <a href=\"https://developer.wordpress.org/reference/hooks/posts_search/\" rel=\"nofollow noreferrer\"><code>posts_search</code> hook</a> to &quot;empty&quot; the search query, after storing it in a private arg which we'll use in the <a href=\"https://developer.wordpress.org/reference/hooks/posts_where/\" rel=\"nofollow noreferrer\"><code>posts_where</code> hook</a> where we reposition the search query.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'posts_search', 'wpse_401476_admin_posts_search', 21, 2 );\nfunction wpse_401476_admin_posts_search( $search, $query ) {\n if ( $query-&gt;get( '_search_OR' ) ) {\n $query-&gt;set( '_search_SQL', $search );\n $search = '';\n }\n\n return $search;\n}\n</code></pre>\n</li>\n<li><p>Now this snippet is the one that repositions the search query. It uses <a href=\"https://developer.wordpress.org/reference/classes/wp_meta_query/get_sql/\" rel=\"nofollow noreferrer\"><code>WP_Meta_Query::get_sql()</code></a> to retrieve the meta query's (SQL) clauses (<code>join</code> and <code>where</code>) used in the current query.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'posts_where', 'wpse_401476_admin_posts_where', 21, 2 );\nfunction wpse_401476_admin_posts_where( $where, $query ) {\n if ( $query-&gt;get( '_search_OR' ) &amp;&amp;\n $search = $query-&gt;get( '_search_SQL' )\n ) {\n global $wpdb;\n\n $clauses = $query-&gt;meta_query-&gt;get_sql( 'post', $wpdb-&gt;posts, 'ID', $query );\n\n if ( ! empty( $clauses['where'] ) ) {\n $where2 = &quot;( 1 $search ) OR ( 1 {$clauses['where']} )&quot;;\n $where = str_replace( $clauses['where'], &quot; AND ( $where2 )&quot;, $where );\n\n $query-&gt;set( '_search_SQL', false );\n $query-&gt;set( '_search_OR', false );\n }\n }\n\n return $where;\n}\n</code></pre>\n<p>So with the above, we'd get a condition that looks like <code>( ( 1 AND &lt;search query&gt; ) OR ( 1 AND &lt;meta query&gt; ) )</code> which is equivalent to the <code>( &lt;search query&gt; OR &lt;meta query&gt; )</code>.</p>\n</li>\n</ol>\n<p>Tried &amp; tested working on WordPress v5.8.3.</p>\n<h2>Notes:</h2>\n<ol>\n<li><p>Use the above snippets instead of what you have in the question.</p>\n</li>\n<li><p>The operator would only be changed if the current user has the <code>administrator</code> <em>role</em> and that the current page is the admin page for managing posts in the <code>apartments</code> post type, and that the search keyword is set, and I also checked if the current query/<code>WP_Query</code> is the <em>main</em> query.</p>\n</li>\n<li><p>I used <code>21</code> as the priority, hence you might want to use a greater number (e.g. <code>100</code>) to make the filters apply properly (i.e. not overwritten by plugins or the active theme).</p>\n</li>\n</ol>\n" } ]
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/comments page?</p>\n</blockquote>\n<p>If you meant the <strong>inline</strong> form for editing or replying to a comment at <code>wp-admin/edit-comments.php</code>, then,</p>\n<ul>\n<li><p>The form is outputted using <a href=\"https://developer.wordpress.org/reference/functions/wp_comment_reply/\" rel=\"nofollow noreferrer\"><code>wp_comment_reply()</code></a> which has a hook with the same name, i.e. <a href=\"https://developer.wordpress.org/reference/hooks/wp_comment_reply/\" rel=\"nofollow noreferrer\"><code>wp_comment_reply</code></a>, and you could use that to return your own comment reply form HTML.</p>\n</li>\n<li><p>However, the inline editing is a JavaScript feature, hence I would simply use JS to add custom fields to that form.</p>\n</li>\n</ul>\n<h2>Working Example</h2>\n<p>So here's a sample script for adding a field named <code>hidden_field</code> (labeled <code>Hidden Field</code>) to that form:</p>\n<pre class=\"lang-js prettyprint-override\"><code>jQuery( function ( $ ) {\n // Append the field at the bottom of the inline form, above the submit\n // button. Just customize the HTML, but ensure the selector is correct.\n // ( i.e. I used [name=&quot;hidden_field&quot;], so change it based on your HTML. )\n $( '#replysubmit' ).before(\n '&lt;p style=&quot;padding: 3px 0 2px 5px; clear: both&quot;&gt;' +\n '&lt;label&gt;Hidden Field:&lt;/label&gt; ' +\n '&lt;input name=&quot;hidden_field&quot; /&gt;' +\n '&lt;/p&gt;'\n );\n\n // Note: (window.)commentReply is defined by WordPress.\n $( '#the-comment-list' ).on( 'click', '.comment-inline', function() {\n var $field = $( '#replyrow input[name=&quot;hidden_field&quot;]' );\n\n // If the Quick Edit button is clicked, set the field value to the\n // current database value.\n if ( 'edit-comment' === commentReply.act ) {\n $field.val( $( '#hidden_field-' + commentReply.cid ).val() );\n } else {\n // If the Reply button is clicked, then we empty the field.\n $field.val( '' );\n }\n } );\n\n // Submit the form when the Enter key is pressed.\n $( '#replyrow input[name=&quot;hidden_field&quot;]' ).on( 'keypress', function( e ) {\n if ( e.which == 13 ) {\n commentReply.send();\n e.preventDefault();\n return false;\n }\n } );\n} );\n</code></pre>\n<ol>\n<li><p>Save it to an external JS file and load the script on the comments page, e.g. via the <a href=\"https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/\" rel=\"nofollow noreferrer\"><code>admin_enqueue_scripts</code> hook</a>, like so: ( make sure <code>admin-comments</code> which loads <code>wp-admin/js/edit-comments.js</code>, is in the dependencies list )</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_enqueue_scripts', 'my_admin_enqueue_scripts' );\nfunction my_admin_enqueue_scripts() {\n if ( 'edit-comments' === get_current_screen()-&gt;id ) {\n wp_enqueue_script( 'my-script', '/path/to/the/script.js',\n array( 'admin-comments' ) );\n }\n}\n</code></pre>\n</li>\n<li><p>To save the field, e.g. as a comment metadata, you can use the <a href=\"https://developer.wordpress.org/reference/hooks/comment_post/\" rel=\"nofollow noreferrer\"><code>comment_post</code></a> <em>and</em> (the one you already using) <a href=\"https://developer.wordpress.org/reference/hooks/edit_comment/\" rel=\"nofollow noreferrer\"><code>edit_comment</code></a> hooks. For example:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'edit_comment', 'my_save_comment_hidden_field' ); // for the Quick Edit button\nadd_action( 'comment_post', 'my_save_comment_hidden_field' ); // for the Reply button\nfunction my_save_comment_hidden_field( $comment_ID ) {\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n\n if ( ! isset( $_POST['hidden_field'] ) ||\n ! current_user_can( 'edit_comment', $comment_ID )\n ) {\n return;\n }\n\n $value = sanitize_text_field( $_POST['hidden_field'] );\n\n update_comment_meta( $comment_ID, 'hidden_field', $value );\n}\n</code></pre>\n</li>\n<li><p>Make sure to add a hidden input which stores the field value that's currently in the database. But it does not have to be an <code>&lt;input /&gt;</code>.. you could just use other element; what's important is, store the value somewhere <em>so that JS can get the value</em> and update the field value in the inline form when <em>editing a comment</em>, i.e. after clicking on &quot;Quick Edit&quot;.</p>\n<p>So for example, I added the hidden input via the <a href=\"https://developer.wordpress.org/reference/hooks/comment_text/\" rel=\"nofollow noreferrer\"><code>comment_text</code> hook</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'comment_text', 'my_comment_text', 10, 2 );\nfunction my_comment_text( $comment_text, $comment ) {\n $value = $comment ? get_comment_meta( $comment-&gt;comment_ID, 'hidden_field', true ) : '';\n\n $input = sprintf( '&lt;input type=&quot;hidden&quot; id=&quot;hidden_field-%d&quot; value=&quot;%s&quot; /&gt;',\n $comment-&gt;comment_ID, esc_attr( $value ) );\n\n return $comment_text . $input;\n}\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 401730, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": true, "text": "<p>Although @SallyCJ's answer might work, and is probably good information, I went in a different direction that worked for my application.</p>\n<p>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.</p>\n<p>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.</p>\n<p>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:</p>\n<pre><code>if (current_user_can( 'moderate_comments' ) ) {\n // forces the guid on admin/comment replies without needing\n // to add a hidden field to the dropdown form.\n $_POST['the_hidden_field'] = wp_generate_uuid4(); \n return $commentdata;\n }\n</code></pre>\n<p>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.</p>\n<p>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.</p>\n<p>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.</p>\n" } ]
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 provided by WordPress Core. They are not meant to be accessed directly. So for example, a plugin might add links to the most recent posts on your site, to the end of every post.</p>\n<p>It sounds like the best path forward for you is to learn more about how WordPress works. The <a href=\"https://developer.wordpress.org/plugins/\" rel=\"nofollow noreferrer\">Plugin Handbook</a> will help you specifically with plugins. <a href=\"https://learn.wordpress.org/course/getting-started-with-wordpress-get-familiar/\" rel=\"nofollow noreferrer\">Learn WordPress</a> is an excellent place to learn about the basics overall. Once you have a stronger foundation, <a href=\"https://developer.wordpress.org/\" rel=\"nofollow noreferrer\">Developer Resources</a> should help with additional information on WordPress functions, the Editor, themes, etc.</p>\n<p>As a quick overview, WordPress Core creates two main post types: the Post and the Page. Posts are frequently-changing or frequently-added content, like news articles. There are Categories built in so you can group related types of Posts, and Tags so you can make smaller groups of related content. Pages are more static resources - say your About Page. They don't natively include Categories but they are hierarchical, meaning one Page can be the parent of another Page, so your About Page could have a child Page of History and another child Page of Contact Us.</p>\n<p>Plugins will often add meta fields to these existing post types, or create new post types altogether - like Portfolio, or Jobs, or all sorts of other things. A plugin can also add functionality to the &quot;back end&quot; - the <code>/wp-admin/</code> area - for example, there are Google Analytics plugins that both add the tracking code to the front end and also add a dashboard widget that will display some of those statistics to logged-in users. But all this plugin data gets output somewhere native - i.e. in <code>wp-admin</code>, or within Posts. It doesn't output directly when you try to visit the plugin URL in your browser.</p>\n" }, { "answer_id": 401610, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 2, "selected": true, "text": "<p>Generally you do not want to access your PHP files directly within WordPress because you lose a lot of &quot;juice&quot;, 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 <em>index.php</em> and some mechanisms then decide what to do with the request.</p>\n<p>From what you write, it sounds like a <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">custom REST endpoint</a> might serve you well.</p>\n<p>Expanding your code to the following should already show some results:</p>\n<pre><code>add_action('rest_api_init', function () {\n register_rest_route('my-plugin/v1', '/my-page', [\n 'methods' =&gt; [\\Requests::POST],\n 'callback' =&gt; 'my_awesome_func',\n ]);\n});\n\nfunction my_awesome_func()\n{ \n if (!isset($returnVal))\n $returnVal = new stdClass();\n\n $returnVal-&gt;status = &quot;success&quot;;\n $returnVal-&gt;info = &quot;seems to work&quot;;\n\n return $returnVal;\n}\n</code></pre>\n<p>(using <a href=\"https://befused.com/php/short-array/\" rel=\"nofollow noreferrer\">short array syntax</a> and) changed</p>\n<pre><code>'methods' =&gt; 'GET',\n</code></pre>\n<p>to</p>\n<pre><code>'methods' =&gt; [\\Requests::POST],\n</code></pre>\n<p>which references the <a href=\"https://developer.wordpress.org/reference/classes/requests/\" rel=\"nofollow noreferrer\">Requests' class const</a> (my preferred style - you can also use <code>'POST'</code> directly).</p>\n<p>Most likely you want to do something with the form data, so change your <code>my_awesome_func()</code> to something like this</p>\n<pre><code>function my_awesome_func(\\WP_REST_Request $request)\n{\n if ($request-&gt;get_param('main_license_number') !== 'something') {\n return new WP_Error('Invalid license number!');\n }\n\n return [\n 'status' =&gt; 'success',\n 'info' =&gt; 'hello',\n ];\n}\n</code></pre>\n<p>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 <code>fusion-form-nonce-1808</code> 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:</p>\n<pre><code>add_action('rest_api_init', function () {\n register_rest_route('my-plugin/v1', '/my-page', [\n 'methods' =&gt; [\\Requests::POST],\n 'callback' =&gt; 'my_awesome_func',\n 'permission_callback' =&gt; function () {\n return magic_validate_my_nonce_please();\n },\n ]);\n});\n</code></pre>\n<p>or with the <a href=\"https://stitcher.io/blog/short-closures-in-php\" rel=\"nofollow noreferrer\">fancy arrow function added in PHP 7.4</a>:</p>\n<pre><code>add_action('rest_api_init', function () {\n register_rest_route('my-plugin/v1', '/my-page', [\n 'methods' =&gt; [\\Requests::POST],\n 'callback' =&gt; 'my_awesome_func',\n 'permission_callback' =&gt; fn () =&gt; magic_validate_my_nonce_please(),\n ]);\n});\n</code></pre>\n" } ]
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 provided by WordPress Core. They are not meant to be accessed directly. So for example, a plugin might add links to the most recent posts on your site, to the end of every post.</p>\n<p>It sounds like the best path forward for you is to learn more about how WordPress works. The <a href=\"https://developer.wordpress.org/plugins/\" rel=\"nofollow noreferrer\">Plugin Handbook</a> will help you specifically with plugins. <a href=\"https://learn.wordpress.org/course/getting-started-with-wordpress-get-familiar/\" rel=\"nofollow noreferrer\">Learn WordPress</a> is an excellent place to learn about the basics overall. Once you have a stronger foundation, <a href=\"https://developer.wordpress.org/\" rel=\"nofollow noreferrer\">Developer Resources</a> should help with additional information on WordPress functions, the Editor, themes, etc.</p>\n<p>As a quick overview, WordPress Core creates two main post types: the Post and the Page. Posts are frequently-changing or frequently-added content, like news articles. There are Categories built in so you can group related types of Posts, and Tags so you can make smaller groups of related content. Pages are more static resources - say your About Page. They don't natively include Categories but they are hierarchical, meaning one Page can be the parent of another Page, so your About Page could have a child Page of History and another child Page of Contact Us.</p>\n<p>Plugins will often add meta fields to these existing post types, or create new post types altogether - like Portfolio, or Jobs, or all sorts of other things. A plugin can also add functionality to the &quot;back end&quot; - the <code>/wp-admin/</code> area - for example, there are Google Analytics plugins that both add the tracking code to the front end and also add a dashboard widget that will display some of those statistics to logged-in users. But all this plugin data gets output somewhere native - i.e. in <code>wp-admin</code>, or within Posts. It doesn't output directly when you try to visit the plugin URL in your browser.</p>\n" }, { "answer_id": 401610, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 2, "selected": true, "text": "<p>Generally you do not want to access your PHP files directly within WordPress because you lose a lot of &quot;juice&quot;, 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 <em>index.php</em> and some mechanisms then decide what to do with the request.</p>\n<p>From what you write, it sounds like a <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">custom REST endpoint</a> might serve you well.</p>\n<p>Expanding your code to the following should already show some results:</p>\n<pre><code>add_action('rest_api_init', function () {\n register_rest_route('my-plugin/v1', '/my-page', [\n 'methods' =&gt; [\\Requests::POST],\n 'callback' =&gt; 'my_awesome_func',\n ]);\n});\n\nfunction my_awesome_func()\n{ \n if (!isset($returnVal))\n $returnVal = new stdClass();\n\n $returnVal-&gt;status = &quot;success&quot;;\n $returnVal-&gt;info = &quot;seems to work&quot;;\n\n return $returnVal;\n}\n</code></pre>\n<p>(using <a href=\"https://befused.com/php/short-array/\" rel=\"nofollow noreferrer\">short array syntax</a> and) changed</p>\n<pre><code>'methods' =&gt; 'GET',\n</code></pre>\n<p>to</p>\n<pre><code>'methods' =&gt; [\\Requests::POST],\n</code></pre>\n<p>which references the <a href=\"https://developer.wordpress.org/reference/classes/requests/\" rel=\"nofollow noreferrer\">Requests' class const</a> (my preferred style - you can also use <code>'POST'</code> directly).</p>\n<p>Most likely you want to do something with the form data, so change your <code>my_awesome_func()</code> to something like this</p>\n<pre><code>function my_awesome_func(\\WP_REST_Request $request)\n{\n if ($request-&gt;get_param('main_license_number') !== 'something') {\n return new WP_Error('Invalid license number!');\n }\n\n return [\n 'status' =&gt; 'success',\n 'info' =&gt; 'hello',\n ];\n}\n</code></pre>\n<p>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 <code>fusion-form-nonce-1808</code> 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:</p>\n<pre><code>add_action('rest_api_init', function () {\n register_rest_route('my-plugin/v1', '/my-page', [\n 'methods' =&gt; [\\Requests::POST],\n 'callback' =&gt; 'my_awesome_func',\n 'permission_callback' =&gt; function () {\n return magic_validate_my_nonce_please();\n },\n ]);\n});\n</code></pre>\n<p>or with the <a href=\"https://stitcher.io/blog/short-closures-in-php\" rel=\"nofollow noreferrer\">fancy arrow function added in PHP 7.4</a>:</p>\n<pre><code>add_action('rest_api_init', function () {\n register_rest_route('my-plugin/v1', '/my-page', [\n 'methods' =&gt; [\\Requests::POST],\n 'callback' =&gt; 'my_awesome_func',\n 'permission_callback' =&gt; fn () =&gt; magic_validate_my_nonce_please(),\n ]);\n});\n</code></pre>\n" } ]
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 provided by WordPress Core. They are not meant to be accessed directly. So for example, a plugin might add links to the most recent posts on your site, to the end of every post.</p>\n<p>It sounds like the best path forward for you is to learn more about how WordPress works. The <a href=\"https://developer.wordpress.org/plugins/\" rel=\"nofollow noreferrer\">Plugin Handbook</a> will help you specifically with plugins. <a href=\"https://learn.wordpress.org/course/getting-started-with-wordpress-get-familiar/\" rel=\"nofollow noreferrer\">Learn WordPress</a> is an excellent place to learn about the basics overall. Once you have a stronger foundation, <a href=\"https://developer.wordpress.org/\" rel=\"nofollow noreferrer\">Developer Resources</a> should help with additional information on WordPress functions, the Editor, themes, etc.</p>\n<p>As a quick overview, WordPress Core creates two main post types: the Post and the Page. Posts are frequently-changing or frequently-added content, like news articles. There are Categories built in so you can group related types of Posts, and Tags so you can make smaller groups of related content. Pages are more static resources - say your About Page. They don't natively include Categories but they are hierarchical, meaning one Page can be the parent of another Page, so your About Page could have a child Page of History and another child Page of Contact Us.</p>\n<p>Plugins will often add meta fields to these existing post types, or create new post types altogether - like Portfolio, or Jobs, or all sorts of other things. A plugin can also add functionality to the &quot;back end&quot; - the <code>/wp-admin/</code> area - for example, there are Google Analytics plugins that both add the tracking code to the front end and also add a dashboard widget that will display some of those statistics to logged-in users. But all this plugin data gets output somewhere native - i.e. in <code>wp-admin</code>, or within Posts. It doesn't output directly when you try to visit the plugin URL in your browser.</p>\n" }, { "answer_id": 401610, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 2, "selected": true, "text": "<p>Generally you do not want to access your PHP files directly within WordPress because you lose a lot of &quot;juice&quot;, 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 <em>index.php</em> and some mechanisms then decide what to do with the request.</p>\n<p>From what you write, it sounds like a <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">custom REST endpoint</a> might serve you well.</p>\n<p>Expanding your code to the following should already show some results:</p>\n<pre><code>add_action('rest_api_init', function () {\n register_rest_route('my-plugin/v1', '/my-page', [\n 'methods' =&gt; [\\Requests::POST],\n 'callback' =&gt; 'my_awesome_func',\n ]);\n});\n\nfunction my_awesome_func()\n{ \n if (!isset($returnVal))\n $returnVal = new stdClass();\n\n $returnVal-&gt;status = &quot;success&quot;;\n $returnVal-&gt;info = &quot;seems to work&quot;;\n\n return $returnVal;\n}\n</code></pre>\n<p>(using <a href=\"https://befused.com/php/short-array/\" rel=\"nofollow noreferrer\">short array syntax</a> and) changed</p>\n<pre><code>'methods' =&gt; 'GET',\n</code></pre>\n<p>to</p>\n<pre><code>'methods' =&gt; [\\Requests::POST],\n</code></pre>\n<p>which references the <a href=\"https://developer.wordpress.org/reference/classes/requests/\" rel=\"nofollow noreferrer\">Requests' class const</a> (my preferred style - you can also use <code>'POST'</code> directly).</p>\n<p>Most likely you want to do something with the form data, so change your <code>my_awesome_func()</code> to something like this</p>\n<pre><code>function my_awesome_func(\\WP_REST_Request $request)\n{\n if ($request-&gt;get_param('main_license_number') !== 'something') {\n return new WP_Error('Invalid license number!');\n }\n\n return [\n 'status' =&gt; 'success',\n 'info' =&gt; 'hello',\n ];\n}\n</code></pre>\n<p>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 <code>fusion-form-nonce-1808</code> 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:</p>\n<pre><code>add_action('rest_api_init', function () {\n register_rest_route('my-plugin/v1', '/my-page', [\n 'methods' =&gt; [\\Requests::POST],\n 'callback' =&gt; 'my_awesome_func',\n 'permission_callback' =&gt; function () {\n return magic_validate_my_nonce_please();\n },\n ]);\n});\n</code></pre>\n<p>or with the <a href=\"https://stitcher.io/blog/short-closures-in-php\" rel=\"nofollow noreferrer\">fancy arrow function added in PHP 7.4</a>:</p>\n<pre><code>add_action('rest_api_init', function () {\n register_rest_route('my-plugin/v1', '/my-page', [\n 'methods' =&gt; [\\Requests::POST],\n 'callback' =&gt; 'my_awesome_func',\n 'permission_callback' =&gt; fn () =&gt; magic_validate_my_nonce_please(),\n ]);\n});\n</code></pre>\n" } ]
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 the function to work</p>\n<pre class=\"lang-php prettyprint-override\"><code>function postToDraft($post_id){\n $post = array( 'ID' =&gt; $post_id, 'post_status' =&gt; 'draft' );\n wp_update_post($post);\n}\n</code></pre>\n" }, { "answer_id": 402028, "author": "Huw Rowlands", "author_id": 57571, "author_profile": "https://wordpress.stackexchange.com/users/57571", "pm_score": 0, "selected": false, "text": "<p>This line of code:</p>\n<p><code>'public' =&gt; true,</code></p>\n<p>change to</p>\n<p><code>'public' =&gt; false,</code></p>\n" } ]
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 and any passed data is the same)... that could be tricky.</p>\n<p>The only other thing I noticed is your <code>meta_query</code> arg does not contain a child array containing <code>state_clause</code> and <code>prop_type</code>.</p>\n<p>Your code is...</p>\n<pre class=\"lang-php prettyprint-override\"><code>'meta_query' =&gt; array(\n 'state_clause' =&gt; array(\n 'key' =&gt; 'state', \n 'value' =&gt; 'WI'\n ),\n 'prop_type' =&gt; array( \n 'key' =&gt; 'property_type'\n )\n),\n</code></pre>\n<p>You might need to wrap both inner <code>meta_query</code> args arrays into another array, see example below...</p>\n<p><em>...and possibly you may need to include a <code>relation</code> argument/key... see the end of the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"nofollow noreferrer\">orderby WP_Query</a> docs</em></p>\n<pre class=\"lang-php prettyprint-override\"><code>'meta_query' =&gt; array(\n array(\n 'state_clause' =&gt; array(\n 'key' =&gt; 'state', \n 'value' =&gt; 'WI'\n ),\n 'prop_type' =&gt; array( \n 'key' =&gt; 'property_type'\n )\n )\n),\n</code></pre>\n" }, { "answer_id": 401824, "author": "Ann Foley", "author_id": 80029, "author_profile": "https://wordpress.stackexchange.com/users/80029", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://dba.stackexchange.com/questions/5774/why-is-ssms-inserting-new-rows-at-the-top-of-a-table-not-the-bottom/5775#5775\">Here's a possible answer to the question</a> - the mysql versions seem to be different on the two installs. Good enough for me, for now. Thanks everyone for helping out!</p>\n" } ]
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 and any passed data is the same)... that could be tricky.</p>\n<p>The only other thing I noticed is your <code>meta_query</code> arg does not contain a child array containing <code>state_clause</code> and <code>prop_type</code>.</p>\n<p>Your code is...</p>\n<pre class=\"lang-php prettyprint-override\"><code>'meta_query' =&gt; array(\n 'state_clause' =&gt; array(\n 'key' =&gt; 'state', \n 'value' =&gt; 'WI'\n ),\n 'prop_type' =&gt; array( \n 'key' =&gt; 'property_type'\n )\n),\n</code></pre>\n<p>You might need to wrap both inner <code>meta_query</code> args arrays into another array, see example below...</p>\n<p><em>...and possibly you may need to include a <code>relation</code> argument/key... see the end of the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"nofollow noreferrer\">orderby WP_Query</a> docs</em></p>\n<pre class=\"lang-php prettyprint-override\"><code>'meta_query' =&gt; array(\n array(\n 'state_clause' =&gt; array(\n 'key' =&gt; 'state', \n 'value' =&gt; 'WI'\n ),\n 'prop_type' =&gt; array( \n 'key' =&gt; 'property_type'\n )\n )\n),\n</code></pre>\n" }, { "answer_id": 401824, "author": "Ann Foley", "author_id": 80029, "author_profile": "https://wordpress.stackexchange.com/users/80029", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://dba.stackexchange.com/questions/5774/why-is-ssms-inserting-new-rows-at-the-top-of-a-table-not-the-bottom/5775#5775\">Here's a possible answer to the question</a> - the mysql versions seem to be different on the two installs. Good enough for me, for now. Thanks everyone for helping out!</p>\n" } ]
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 in functions.php</p>\n<pre class=\"lang-php prettyprint-override\"><code>function showPosts($postsToShow){\n if( have_posts() ): ?&gt;\n &lt;div class=&quot;row all-recipes-block&quot;&gt;&lt;?php\n $countPosts = 0;\n while( have_posts() &amp;&amp; $countPosts &lt; $postsToShow): the_post(); ?&gt;\n &lt;article id=&quot;post-&lt;?php the_ID(); ?&gt;&quot; &lt;?php post_class('col-md-4'); ?&gt;&gt; &lt;?php\n if ( has_post_thumbnail() ) : ?&gt;\n &lt;a class=&quot;post-teaser&quot; href=&quot;&lt;?php the_permalink() ?&gt;&quot; title=&quot;&lt;?php the_title(); ?&gt;&quot;&gt;\n &lt;div class=&quot;thumbnail-block&quot;&gt;&lt;?php the_post_thumbnail('regular-post-thumbnail'); ?&gt;&lt;/div&gt;\n &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;\n &lt;/a&gt; &lt;?php\n endif; ?&gt;\n &lt;/article&gt; &lt;?php\n $countPosts += 1;\n endwhile; ?&gt;\n &lt;/div&gt;\n &lt;div class=&quot;pagination-block row&quot;&gt;\n &lt;?php numeric_posts_nav(); ?&gt;\n &lt;/div&gt;\n &lt;?php else: ?&gt;\n &lt;div id=&quot;post-404&quot; class=&quot;noposts&quot;&gt;\n &lt;p&gt;&lt;?php _e('None found.','example'); ?&gt;&lt;/p&gt;\n &lt;/div&gt;&lt;!-- /#post-404 --&gt;&lt;?php \n endif; wp_reset_query();\n}\n</code></pre>\n<p>Now you just need to call this function showPosts(6); in your front page, this means with your html something like this</p>\n<pre class=\"lang-php prettyprint-override\"><code>get_header('archive'); ?&gt;\n&lt;div id=&quot;primary&quot; class=&quot;content-area blog-archive col-md-9&quot;&gt;\n &lt;main id=&quot;main&quot; class=&quot;site-main&quot;&gt;\n &lt;div class=&quot;breadcrumbs-block&quot;&gt;&lt;?php\n if ( function_exists('yoast_breadcrumb') ) {\n yoast_breadcrumb( '&lt;p id=&quot;breadcrumbs&quot;&gt;','&lt;/p&gt;' );\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=24&amp;paged='. get_query_var('paged')); ?&gt;\n &lt;?php showPosts(6); ?&gt;\n &lt;/main&gt;\n&lt;/div&gt;\n&lt;?php\nget_footer();\n</code></pre>\n<p>let me know!</p>\n<p>Have notice only now that this isnt the front-page but the archive.php, so if still doesnt give the desire outcome, its because the archive.php is the one responsible for the posts loop by category or by tag or year or month. So if still doesnt work remove the above changes and strangely enough or not copy and paste your code below to the index.php</p>\n<pre class=\"lang-php prettyprint-override\"><code>$postsToShow = 6;\nget_header('archive'); ?&gt;\n&lt;div id=&quot;primary&quot; class=&quot;content-area blog-archive col-md-9&quot;&gt;\n &lt;main id=&quot;main&quot; class=&quot;site-main&quot;&gt;\n &lt;div class=&quot;breadcrumbs-block&quot;&gt;&lt;?php\n if ( function_exists('yoast_breadcrumb') ) {\n yoast_breadcrumb( '&lt;p id=&quot;breadcrumbs&quot;&gt;','&lt;/p&gt;' );\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=24&amp;paged='. get_query_var('paged')); ?&gt;\n &lt;?php if( have_posts() ): ?&gt;\n&lt;div class=&quot;row all-recipes-block&quot;&gt;&lt;?php\n $countPosts = 0;\n while( have_posts() &amp;&amp; $countPosts &lt; $postsToShow): the_post(); ?&gt;\n &lt;article id=&quot;post-&lt;?php the_ID(); ?&gt;&quot; &lt;?php post_class('col-md-4'); ?&gt;&gt; &lt;?php\n if ( has_post_thumbnail() ) : ?&gt;\n &lt;a class=&quot;post-teaser&quot; href=&quot;&lt;?php the_permalink() ?&gt;&quot; title=&quot;&lt;?php the_title(); ?&gt;&quot;&gt;\n &lt;div class=&quot;thumbnail-block&quot;&gt;&lt;?php the_post_thumbnail('regular-post-thumbnail'); ?&gt;&lt;/div&gt;\n &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;\n &lt;/a&gt; &lt;?php\n endif; ?&gt;\n &lt;/article&gt; &lt;?php\n $countPosts += 1;\n endwhile; ?&gt;\n &lt;/div&gt;\n &lt;div class=&quot;pagination-block row&quot;&gt;\n &lt;?php numeric_posts_nav(); ?&gt;\n &lt;/div&gt;\n &lt;?php else: ?&gt;\n &lt;div id=&quot;post-404&quot; class=&quot;noposts&quot;&gt;\n &lt;p&gt;&lt;?php _e('None found.','example'); ?&gt;&lt;/p&gt;\n &lt;/div&gt;&lt;!-- /#post-404 --&gt;\n &lt;?php endif; wp_reset_query(); ?&gt;\n &lt;/main&gt;\n&lt;/div&gt;\n&lt;?php\nget_footer();\n</code></pre>\n<p>Now should be like a charm!</p>\n<p>I'm creating a website with pages, shop and blog, and to achive the same has you are doing this is the tree I found out, I dont seem to find this in the internet or in the wp library. here it goes</p>\n<pre class=\"lang-php prettyprint-override\"><code>#### posts files ####\nall the articles index.php\nsingle article single.php\nall the articles with some query(year, month, tag, category...) archive.php\n</code></pre>\n<p>it seems strange to do this in the index.php and the single.php, but it is how it works for me.</p>\n" }, { "answer_id": 401916, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<blockquote>\n<p>This is my archive template — <code>page-archive.php</code>, which I am using as\na template to display all my posts/recipes</p>\n</blockquote>\n<p>So if you're using a <a href=\"https://wordpress.org/support/article/pages-screen/\" rel=\"nofollow noreferrer\">Page (post of the <code>page</code> type)</a> with a custom/specific <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">Page Template</a>, then you should <a href=\"https://developer.wordpress.org/themes/basics/the-loop/#creating-secondary-queries-and-loops\" rel=\"nofollow noreferrer\">create a <em>secondary query and loop</em></a> for retrieving and displaying your recipes/posts.</p>\n<p>But even with a default archive template such as the <code>archive.php</code> file, you should <em><strong>not</strong></em> use <code>query_posts()</code> in the template!</p>\n<p>And here's why: (bold and italic formatting was added by me)</p>\n<blockquote>\n<p>This function will <strong>completely override the main query and isn’t\nintended for use by plugins or themes</strong>. Its overly-simplistic\napproach to modifying the main query can be problematic and should be\navoided wherever possible. In most cases, there are <em>better, more\nperformant options</em> for modifying the main query such as via the\n<a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">‘pre_get_posts’</a>\naction within\n<a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">WP_Query</a>.</p>\n</blockquote>\n<blockquote>\n<p>It should be noted that using this to replace the main query on a page\ncan increase page loading times, in worst case scenarios more than\ndoubling the amount of work needed or more. While easy to use, the\nfunction is also prone to confusion and problems later on. See the\nnote further below on caveats for details.</p>\n</blockquote>\n<p>— See <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/query_posts/</a> for the caveats mentioned above and other details.</p>\n<p>And here's how can you convert your <code>query_posts()</code> code to using a secondary query/<code>WP_Query</code> and loop instead:</p>\n<ol>\n<li><p>Replace the <code>&lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=24&amp;paged='. get_query_var('paged')); ?&gt;</code> with this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n// you could also do $query = new WP_Query( 'your args here' ), but I thought\n// using array is better or more readable :)\n$query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; 24,\n 'paged' =&gt; get_query_var( 'paged' ),\n) );\n?&gt;\n</code></pre>\n</li>\n<li><p>Replace the <code>have_posts()</code> with <code>$query-&gt;have_posts()</code>, <strong>and</strong> the <code>the_post()</code> with <code>$query-&gt;the_post()</code>. I.e. Use the <code>$query</code> variable created above.</p>\n</li>\n<li><p>And finally, replace the <code>wp_reset_query()</code> with <code>wp_reset_postdata()</code>.</p>\n</li>\n</ol>\n<p><strong>Now, as for displaying only a few posts on the first page, i.e. different than your <code>posts_per_page</code> value..</strong></p>\n<p>The proper solution would be to <strong>use an <code>offset</code></strong>, like so:</p>\n<ol>\n<li><p>Replace the snippet in step 1 above with this, or use this instead of that snippet:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n// Define the number of posts per page.\n$per_page = 12; // for the 1st page\n$per_page2 = 24; // for page 2, 3, etc.\n\n// Get the current page number.\n$paged = max( 1, get_query_var( 'paged' ) );\n// This is used as the posts_per_page value.\n$per_page3 = ( $paged &gt; 1 ) ? $per_page2 : $per_page;\n\n// Calculate the offset.\n$offset = ( $paged - 1 ) * $per_page2;\n$diff = $per_page2 - $per_page;\n$minus = ( $paged &gt; 1 ) ? $diff : 0;\n\n$query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; $per_page3,\n 'offset' =&gt; $offset - $minus,\n) );\n\n// Recalculate the total number of pages.\n$query-&gt;max_num_pages = ceil(\n ( $query-&gt;found_posts + $diff ) /\n max( $per_page, $per_page2 )\n);\n?&gt;\n</code></pre>\n</li>\n<li><p>Replace the <code>&lt;?php numeric_posts_nav(); ?&gt;</code> with <code>&lt;?php numeric_posts_nav( $query ); ?&gt;</code>.</p>\n</li>\n<li><p>Edit your <em>pagination function</em> — replace this part (which is lines 775 - 787 <a href=\"https://pastebin.com/jQA3cgCx\" rel=\"nofollow noreferrer\">here</a>):</p>\n<pre class=\"lang-php prettyprint-override\"><code>function numeric_posts_nav() {\n\n if( is_singular() )\n return;\n\n global $wp_query;\n\n /** Stop execution if there's only 1 page */\n if( $wp_query-&gt;max_num_pages &lt;= 1 )\n return;\n\n $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;\n $max = intval( $wp_query-&gt;max_num_pages );\n</code></pre>\n<p>with this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function numeric_posts_nav( WP_Query $query = null ) {\n\n global $wp_query;\n\n if ( ! $query ) {\n $query =&amp; $wp_query;\n }\n\n if( $query-&gt;is_singular() || $query-&gt;max_num_pages &lt;= 1 ) {\n return;\n }\n\n $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;\n $max = intval( $query-&gt;max_num_pages );\n</code></pre>\n</li>\n</ol>\n<p>That's all and now check if it works for you! :)</p>\n" } ]
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 in functions.php</p>\n<pre class=\"lang-php prettyprint-override\"><code>function showPosts($postsToShow){\n if( have_posts() ): ?&gt;\n &lt;div class=&quot;row all-recipes-block&quot;&gt;&lt;?php\n $countPosts = 0;\n while( have_posts() &amp;&amp; $countPosts &lt; $postsToShow): the_post(); ?&gt;\n &lt;article id=&quot;post-&lt;?php the_ID(); ?&gt;&quot; &lt;?php post_class('col-md-4'); ?&gt;&gt; &lt;?php\n if ( has_post_thumbnail() ) : ?&gt;\n &lt;a class=&quot;post-teaser&quot; href=&quot;&lt;?php the_permalink() ?&gt;&quot; title=&quot;&lt;?php the_title(); ?&gt;&quot;&gt;\n &lt;div class=&quot;thumbnail-block&quot;&gt;&lt;?php the_post_thumbnail('regular-post-thumbnail'); ?&gt;&lt;/div&gt;\n &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;\n &lt;/a&gt; &lt;?php\n endif; ?&gt;\n &lt;/article&gt; &lt;?php\n $countPosts += 1;\n endwhile; ?&gt;\n &lt;/div&gt;\n &lt;div class=&quot;pagination-block row&quot;&gt;\n &lt;?php numeric_posts_nav(); ?&gt;\n &lt;/div&gt;\n &lt;?php else: ?&gt;\n &lt;div id=&quot;post-404&quot; class=&quot;noposts&quot;&gt;\n &lt;p&gt;&lt;?php _e('None found.','example'); ?&gt;&lt;/p&gt;\n &lt;/div&gt;&lt;!-- /#post-404 --&gt;&lt;?php \n endif; wp_reset_query();\n}\n</code></pre>\n<p>Now you just need to call this function showPosts(6); in your front page, this means with your html something like this</p>\n<pre class=\"lang-php prettyprint-override\"><code>get_header('archive'); ?&gt;\n&lt;div id=&quot;primary&quot; class=&quot;content-area blog-archive col-md-9&quot;&gt;\n &lt;main id=&quot;main&quot; class=&quot;site-main&quot;&gt;\n &lt;div class=&quot;breadcrumbs-block&quot;&gt;&lt;?php\n if ( function_exists('yoast_breadcrumb') ) {\n yoast_breadcrumb( '&lt;p id=&quot;breadcrumbs&quot;&gt;','&lt;/p&gt;' );\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=24&amp;paged='. get_query_var('paged')); ?&gt;\n &lt;?php showPosts(6); ?&gt;\n &lt;/main&gt;\n&lt;/div&gt;\n&lt;?php\nget_footer();\n</code></pre>\n<p>let me know!</p>\n<p>Have notice only now that this isnt the front-page but the archive.php, so if still doesnt give the desire outcome, its because the archive.php is the one responsible for the posts loop by category or by tag or year or month. So if still doesnt work remove the above changes and strangely enough or not copy and paste your code below to the index.php</p>\n<pre class=\"lang-php prettyprint-override\"><code>$postsToShow = 6;\nget_header('archive'); ?&gt;\n&lt;div id=&quot;primary&quot; class=&quot;content-area blog-archive col-md-9&quot;&gt;\n &lt;main id=&quot;main&quot; class=&quot;site-main&quot;&gt;\n &lt;div class=&quot;breadcrumbs-block&quot;&gt;&lt;?php\n if ( function_exists('yoast_breadcrumb') ) {\n yoast_breadcrumb( '&lt;p id=&quot;breadcrumbs&quot;&gt;','&lt;/p&gt;' );\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=24&amp;paged='. get_query_var('paged')); ?&gt;\n &lt;?php if( have_posts() ): ?&gt;\n&lt;div class=&quot;row all-recipes-block&quot;&gt;&lt;?php\n $countPosts = 0;\n while( have_posts() &amp;&amp; $countPosts &lt; $postsToShow): the_post(); ?&gt;\n &lt;article id=&quot;post-&lt;?php the_ID(); ?&gt;&quot; &lt;?php post_class('col-md-4'); ?&gt;&gt; &lt;?php\n if ( has_post_thumbnail() ) : ?&gt;\n &lt;a class=&quot;post-teaser&quot; href=&quot;&lt;?php the_permalink() ?&gt;&quot; title=&quot;&lt;?php the_title(); ?&gt;&quot;&gt;\n &lt;div class=&quot;thumbnail-block&quot;&gt;&lt;?php the_post_thumbnail('regular-post-thumbnail'); ?&gt;&lt;/div&gt;\n &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;\n &lt;/a&gt; &lt;?php\n endif; ?&gt;\n &lt;/article&gt; &lt;?php\n $countPosts += 1;\n endwhile; ?&gt;\n &lt;/div&gt;\n &lt;div class=&quot;pagination-block row&quot;&gt;\n &lt;?php numeric_posts_nav(); ?&gt;\n &lt;/div&gt;\n &lt;?php else: ?&gt;\n &lt;div id=&quot;post-404&quot; class=&quot;noposts&quot;&gt;\n &lt;p&gt;&lt;?php _e('None found.','example'); ?&gt;&lt;/p&gt;\n &lt;/div&gt;&lt;!-- /#post-404 --&gt;\n &lt;?php endif; wp_reset_query(); ?&gt;\n &lt;/main&gt;\n&lt;/div&gt;\n&lt;?php\nget_footer();\n</code></pre>\n<p>Now should be like a charm!</p>\n<p>I'm creating a website with pages, shop and blog, and to achive the same has you are doing this is the tree I found out, I dont seem to find this in the internet or in the wp library. here it goes</p>\n<pre class=\"lang-php prettyprint-override\"><code>#### posts files ####\nall the articles index.php\nsingle article single.php\nall the articles with some query(year, month, tag, category...) archive.php\n</code></pre>\n<p>it seems strange to do this in the index.php and the single.php, but it is how it works for me.</p>\n" }, { "answer_id": 401916, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<blockquote>\n<p>This is my archive template — <code>page-archive.php</code>, which I am using as\na template to display all my posts/recipes</p>\n</blockquote>\n<p>So if you're using a <a href=\"https://wordpress.org/support/article/pages-screen/\" rel=\"nofollow noreferrer\">Page (post of the <code>page</code> type)</a> with a custom/specific <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">Page Template</a>, then you should <a href=\"https://developer.wordpress.org/themes/basics/the-loop/#creating-secondary-queries-and-loops\" rel=\"nofollow noreferrer\">create a <em>secondary query and loop</em></a> for retrieving and displaying your recipes/posts.</p>\n<p>But even with a default archive template such as the <code>archive.php</code> file, you should <em><strong>not</strong></em> use <code>query_posts()</code> in the template!</p>\n<p>And here's why: (bold and italic formatting was added by me)</p>\n<blockquote>\n<p>This function will <strong>completely override the main query and isn’t\nintended for use by plugins or themes</strong>. Its overly-simplistic\napproach to modifying the main query can be problematic and should be\navoided wherever possible. In most cases, there are <em>better, more\nperformant options</em> for modifying the main query such as via the\n<a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">‘pre_get_posts’</a>\naction within\n<a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">WP_Query</a>.</p>\n</blockquote>\n<blockquote>\n<p>It should be noted that using this to replace the main query on a page\ncan increase page loading times, in worst case scenarios more than\ndoubling the amount of work needed or more. While easy to use, the\nfunction is also prone to confusion and problems later on. See the\nnote further below on caveats for details.</p>\n</blockquote>\n<p>— See <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/query_posts/</a> for the caveats mentioned above and other details.</p>\n<p>And here's how can you convert your <code>query_posts()</code> code to using a secondary query/<code>WP_Query</code> and loop instead:</p>\n<ol>\n<li><p>Replace the <code>&lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=24&amp;paged='. get_query_var('paged')); ?&gt;</code> with this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n// you could also do $query = new WP_Query( 'your args here' ), but I thought\n// using array is better or more readable :)\n$query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; 24,\n 'paged' =&gt; get_query_var( 'paged' ),\n) );\n?&gt;\n</code></pre>\n</li>\n<li><p>Replace the <code>have_posts()</code> with <code>$query-&gt;have_posts()</code>, <strong>and</strong> the <code>the_post()</code> with <code>$query-&gt;the_post()</code>. I.e. Use the <code>$query</code> variable created above.</p>\n</li>\n<li><p>And finally, replace the <code>wp_reset_query()</code> with <code>wp_reset_postdata()</code>.</p>\n</li>\n</ol>\n<p><strong>Now, as for displaying only a few posts on the first page, i.e. different than your <code>posts_per_page</code> value..</strong></p>\n<p>The proper solution would be to <strong>use an <code>offset</code></strong>, like so:</p>\n<ol>\n<li><p>Replace the snippet in step 1 above with this, or use this instead of that snippet:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n// Define the number of posts per page.\n$per_page = 12; // for the 1st page\n$per_page2 = 24; // for page 2, 3, etc.\n\n// Get the current page number.\n$paged = max( 1, get_query_var( 'paged' ) );\n// This is used as the posts_per_page value.\n$per_page3 = ( $paged &gt; 1 ) ? $per_page2 : $per_page;\n\n// Calculate the offset.\n$offset = ( $paged - 1 ) * $per_page2;\n$diff = $per_page2 - $per_page;\n$minus = ( $paged &gt; 1 ) ? $diff : 0;\n\n$query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; $per_page3,\n 'offset' =&gt; $offset - $minus,\n) );\n\n// Recalculate the total number of pages.\n$query-&gt;max_num_pages = ceil(\n ( $query-&gt;found_posts + $diff ) /\n max( $per_page, $per_page2 )\n);\n?&gt;\n</code></pre>\n</li>\n<li><p>Replace the <code>&lt;?php numeric_posts_nav(); ?&gt;</code> with <code>&lt;?php numeric_posts_nav( $query ); ?&gt;</code>.</p>\n</li>\n<li><p>Edit your <em>pagination function</em> — replace this part (which is lines 775 - 787 <a href=\"https://pastebin.com/jQA3cgCx\" rel=\"nofollow noreferrer\">here</a>):</p>\n<pre class=\"lang-php prettyprint-override\"><code>function numeric_posts_nav() {\n\n if( is_singular() )\n return;\n\n global $wp_query;\n\n /** Stop execution if there's only 1 page */\n if( $wp_query-&gt;max_num_pages &lt;= 1 )\n return;\n\n $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;\n $max = intval( $wp_query-&gt;max_num_pages );\n</code></pre>\n<p>with this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function numeric_posts_nav( WP_Query $query = null ) {\n\n global $wp_query;\n\n if ( ! $query ) {\n $query =&amp; $wp_query;\n }\n\n if( $query-&gt;is_singular() || $query-&gt;max_num_pages &lt;= 1 ) {\n return;\n }\n\n $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;\n $max = intval( $query-&gt;max_num_pages );\n</code></pre>\n</li>\n</ol>\n<p>That's all and now check if it works for you! :)</p>\n" } ]
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 in functions.php</p>\n<pre class=\"lang-php prettyprint-override\"><code>function showPosts($postsToShow){\n if( have_posts() ): ?&gt;\n &lt;div class=&quot;row all-recipes-block&quot;&gt;&lt;?php\n $countPosts = 0;\n while( have_posts() &amp;&amp; $countPosts &lt; $postsToShow): the_post(); ?&gt;\n &lt;article id=&quot;post-&lt;?php the_ID(); ?&gt;&quot; &lt;?php post_class('col-md-4'); ?&gt;&gt; &lt;?php\n if ( has_post_thumbnail() ) : ?&gt;\n &lt;a class=&quot;post-teaser&quot; href=&quot;&lt;?php the_permalink() ?&gt;&quot; title=&quot;&lt;?php the_title(); ?&gt;&quot;&gt;\n &lt;div class=&quot;thumbnail-block&quot;&gt;&lt;?php the_post_thumbnail('regular-post-thumbnail'); ?&gt;&lt;/div&gt;\n &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;\n &lt;/a&gt; &lt;?php\n endif; ?&gt;\n &lt;/article&gt; &lt;?php\n $countPosts += 1;\n endwhile; ?&gt;\n &lt;/div&gt;\n &lt;div class=&quot;pagination-block row&quot;&gt;\n &lt;?php numeric_posts_nav(); ?&gt;\n &lt;/div&gt;\n &lt;?php else: ?&gt;\n &lt;div id=&quot;post-404&quot; class=&quot;noposts&quot;&gt;\n &lt;p&gt;&lt;?php _e('None found.','example'); ?&gt;&lt;/p&gt;\n &lt;/div&gt;&lt;!-- /#post-404 --&gt;&lt;?php \n endif; wp_reset_query();\n}\n</code></pre>\n<p>Now you just need to call this function showPosts(6); in your front page, this means with your html something like this</p>\n<pre class=\"lang-php prettyprint-override\"><code>get_header('archive'); ?&gt;\n&lt;div id=&quot;primary&quot; class=&quot;content-area blog-archive col-md-9&quot;&gt;\n &lt;main id=&quot;main&quot; class=&quot;site-main&quot;&gt;\n &lt;div class=&quot;breadcrumbs-block&quot;&gt;&lt;?php\n if ( function_exists('yoast_breadcrumb') ) {\n yoast_breadcrumb( '&lt;p id=&quot;breadcrumbs&quot;&gt;','&lt;/p&gt;' );\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=24&amp;paged='. get_query_var('paged')); ?&gt;\n &lt;?php showPosts(6); ?&gt;\n &lt;/main&gt;\n&lt;/div&gt;\n&lt;?php\nget_footer();\n</code></pre>\n<p>let me know!</p>\n<p>Have notice only now that this isnt the front-page but the archive.php, so if still doesnt give the desire outcome, its because the archive.php is the one responsible for the posts loop by category or by tag or year or month. So if still doesnt work remove the above changes and strangely enough or not copy and paste your code below to the index.php</p>\n<pre class=\"lang-php prettyprint-override\"><code>$postsToShow = 6;\nget_header('archive'); ?&gt;\n&lt;div id=&quot;primary&quot; class=&quot;content-area blog-archive col-md-9&quot;&gt;\n &lt;main id=&quot;main&quot; class=&quot;site-main&quot;&gt;\n &lt;div class=&quot;breadcrumbs-block&quot;&gt;&lt;?php\n if ( function_exists('yoast_breadcrumb') ) {\n yoast_breadcrumb( '&lt;p id=&quot;breadcrumbs&quot;&gt;','&lt;/p&gt;' );\n }\n ?&gt;\n &lt;/div&gt;\n &lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=24&amp;paged='. get_query_var('paged')); ?&gt;\n &lt;?php if( have_posts() ): ?&gt;\n&lt;div class=&quot;row all-recipes-block&quot;&gt;&lt;?php\n $countPosts = 0;\n while( have_posts() &amp;&amp; $countPosts &lt; $postsToShow): the_post(); ?&gt;\n &lt;article id=&quot;post-&lt;?php the_ID(); ?&gt;&quot; &lt;?php post_class('col-md-4'); ?&gt;&gt; &lt;?php\n if ( has_post_thumbnail() ) : ?&gt;\n &lt;a class=&quot;post-teaser&quot; href=&quot;&lt;?php the_permalink() ?&gt;&quot; title=&quot;&lt;?php the_title(); ?&gt;&quot;&gt;\n &lt;div class=&quot;thumbnail-block&quot;&gt;&lt;?php the_post_thumbnail('regular-post-thumbnail'); ?&gt;&lt;/div&gt;\n &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;\n &lt;/a&gt; &lt;?php\n endif; ?&gt;\n &lt;/article&gt; &lt;?php\n $countPosts += 1;\n endwhile; ?&gt;\n &lt;/div&gt;\n &lt;div class=&quot;pagination-block row&quot;&gt;\n &lt;?php numeric_posts_nav(); ?&gt;\n &lt;/div&gt;\n &lt;?php else: ?&gt;\n &lt;div id=&quot;post-404&quot; class=&quot;noposts&quot;&gt;\n &lt;p&gt;&lt;?php _e('None found.','example'); ?&gt;&lt;/p&gt;\n &lt;/div&gt;&lt;!-- /#post-404 --&gt;\n &lt;?php endif; wp_reset_query(); ?&gt;\n &lt;/main&gt;\n&lt;/div&gt;\n&lt;?php\nget_footer();\n</code></pre>\n<p>Now should be like a charm!</p>\n<p>I'm creating a website with pages, shop and blog, and to achive the same has you are doing this is the tree I found out, I dont seem to find this in the internet or in the wp library. here it goes</p>\n<pre class=\"lang-php prettyprint-override\"><code>#### posts files ####\nall the articles index.php\nsingle article single.php\nall the articles with some query(year, month, tag, category...) archive.php\n</code></pre>\n<p>it seems strange to do this in the index.php and the single.php, but it is how it works for me.</p>\n" }, { "answer_id": 401916, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<blockquote>\n<p>This is my archive template — <code>page-archive.php</code>, which I am using as\na template to display all my posts/recipes</p>\n</blockquote>\n<p>So if you're using a <a href=\"https://wordpress.org/support/article/pages-screen/\" rel=\"nofollow noreferrer\">Page (post of the <code>page</code> type)</a> with a custom/specific <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">Page Template</a>, then you should <a href=\"https://developer.wordpress.org/themes/basics/the-loop/#creating-secondary-queries-and-loops\" rel=\"nofollow noreferrer\">create a <em>secondary query and loop</em></a> for retrieving and displaying your recipes/posts.</p>\n<p>But even with a default archive template such as the <code>archive.php</code> file, you should <em><strong>not</strong></em> use <code>query_posts()</code> in the template!</p>\n<p>And here's why: (bold and italic formatting was added by me)</p>\n<blockquote>\n<p>This function will <strong>completely override the main query and isn’t\nintended for use by plugins or themes</strong>. Its overly-simplistic\napproach to modifying the main query can be problematic and should be\navoided wherever possible. In most cases, there are <em>better, more\nperformant options</em> for modifying the main query such as via the\n<a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">‘pre_get_posts’</a>\naction within\n<a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">WP_Query</a>.</p>\n</blockquote>\n<blockquote>\n<p>It should be noted that using this to replace the main query on a page\ncan increase page loading times, in worst case scenarios more than\ndoubling the amount of work needed or more. While easy to use, the\nfunction is also prone to confusion and problems later on. See the\nnote further below on caveats for details.</p>\n</blockquote>\n<p>— See <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/query_posts/</a> for the caveats mentioned above and other details.</p>\n<p>And here's how can you convert your <code>query_posts()</code> code to using a secondary query/<code>WP_Query</code> and loop instead:</p>\n<ol>\n<li><p>Replace the <code>&lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=24&amp;paged='. get_query_var('paged')); ?&gt;</code> with this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n// you could also do $query = new WP_Query( 'your args here' ), but I thought\n// using array is better or more readable :)\n$query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; 24,\n 'paged' =&gt; get_query_var( 'paged' ),\n) );\n?&gt;\n</code></pre>\n</li>\n<li><p>Replace the <code>have_posts()</code> with <code>$query-&gt;have_posts()</code>, <strong>and</strong> the <code>the_post()</code> with <code>$query-&gt;the_post()</code>. I.e. Use the <code>$query</code> variable created above.</p>\n</li>\n<li><p>And finally, replace the <code>wp_reset_query()</code> with <code>wp_reset_postdata()</code>.</p>\n</li>\n</ol>\n<p><strong>Now, as for displaying only a few posts on the first page, i.e. different than your <code>posts_per_page</code> value..</strong></p>\n<p>The proper solution would be to <strong>use an <code>offset</code></strong>, like so:</p>\n<ol>\n<li><p>Replace the snippet in step 1 above with this, or use this instead of that snippet:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n// Define the number of posts per page.\n$per_page = 12; // for the 1st page\n$per_page2 = 24; // for page 2, 3, etc.\n\n// Get the current page number.\n$paged = max( 1, get_query_var( 'paged' ) );\n// This is used as the posts_per_page value.\n$per_page3 = ( $paged &gt; 1 ) ? $per_page2 : $per_page;\n\n// Calculate the offset.\n$offset = ( $paged - 1 ) * $per_page2;\n$diff = $per_page2 - $per_page;\n$minus = ( $paged &gt; 1 ) ? $diff : 0;\n\n$query = new WP_Query( array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; $per_page3,\n 'offset' =&gt; $offset - $minus,\n) );\n\n// Recalculate the total number of pages.\n$query-&gt;max_num_pages = ceil(\n ( $query-&gt;found_posts + $diff ) /\n max( $per_page, $per_page2 )\n);\n?&gt;\n</code></pre>\n</li>\n<li><p>Replace the <code>&lt;?php numeric_posts_nav(); ?&gt;</code> with <code>&lt;?php numeric_posts_nav( $query ); ?&gt;</code>.</p>\n</li>\n<li><p>Edit your <em>pagination function</em> — replace this part (which is lines 775 - 787 <a href=\"https://pastebin.com/jQA3cgCx\" rel=\"nofollow noreferrer\">here</a>):</p>\n<pre class=\"lang-php prettyprint-override\"><code>function numeric_posts_nav() {\n\n if( is_singular() )\n return;\n\n global $wp_query;\n\n /** Stop execution if there's only 1 page */\n if( $wp_query-&gt;max_num_pages &lt;= 1 )\n return;\n\n $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;\n $max = intval( $wp_query-&gt;max_num_pages );\n</code></pre>\n<p>with this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function numeric_posts_nav( WP_Query $query = null ) {\n\n global $wp_query;\n\n if ( ! $query ) {\n $query =&amp; $wp_query;\n }\n\n if( $query-&gt;is_singular() || $query-&gt;max_num_pages &lt;= 1 ) {\n return;\n }\n\n $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;\n $max = intval( $query-&gt;max_num_pages );\n</code></pre>\n</li>\n</ol>\n<p>That's all and now check if it works for you! :)</p>\n" } ]
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_Pages\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Creating_Options_Pages</a></p>\n<p>That page will give you a good starting point to make options and settings for WordPres.</p>\n" }, { "answer_id": 402811, "author": "Ben", "author_id": 148005, "author_profile": "https://wordpress.stackexchange.com/users/148005", "pm_score": 1, "selected": false, "text": "<p>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.</p>\n<p>What I usually do, is scope the constant to the corresponding classes as <code>const</code> 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:</p>\n<pre class=\"lang-php prettyprint-override\"><code>class BookPost{\n const POST_TYPE = 'book';\n \n public static function register(){\n register_post_type(self::POST_TYPE, array('labels' =&gt; self::get_labels()));\n }\n\n public static function get_labels(){\n return array(\n 'name' =&gt; __('Book', 'MyTheme'),\n //...\n );\n }\n}\n</code></pre>\n<p>Then you can call register from outside or inside of the class without worrying about the parameters, for example:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'init', 'BookPost::register' );\n</code></pre>\n<p>and if you need to access the post type (or other args) from anywhere else in the code, you can just use:</p>\n<pre class=\"lang-php prettyprint-override\"><code>BookPost::POST_TYPE;\nBookPost::get_labels();\n</code></pre>\n<p>There are a couple of things to mention here:</p>\n<ol>\n<li>Since you can't use expressions (such as calling the <code>__()</code> method) in constants, you will have to use methods for retrieving the more dynamic values like label.</li>\n<li>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.</li>\n</ol>\n<p>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:</p>\n<pre class=\"lang-php prettyprint-override\"><code>BookPost::get_latest();\nBookPost::get_all();\nBookPost::get_by_genre();\n</code></pre>\n<p>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.</p>\n" } ]
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 (e.g. better search replace) or wp cli. E.g. to change from old domain to new domain, you can use old string: <code>https://olddomain.com</code> and new string <code>https://newdomain.com</code></p>\n<p>Also, try clearing cookies and redirections cache in the browser (ctr+shift+del on Windows, cmd+shift+backspace for Mac).</p>\n" }, { "answer_id": 402311, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 3, "selected": true, "text": "<p>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 <code>options</code> table, entries <code>siteurl</code> and <code>homeurl</code>.\nIt is also possible to set this via <code>wp-config.php</code>:</p>\n<pre><code>// Home URL of your WordPress.\ndefine( 'WP_SITEURL', 'https:/example.com' );\n// URL to the WordPress root dir.\ndefine( 'WP_HOME', 'https://example.com' );\n</code></pre>\n<p>Look also inside the <code>wp-config.php</code> for the domain, because it is possible to set this via constant. The <code>.htaccess</code>, if it is an Apache server, should also validate, because the Permalink rules need the domain, especially in the 'Multisite' mode.</p>\n<p>You should also active the <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">debug mode</a>, constant <code>WP_DEBUG</code> set to true in your <code>wp-config.php</code> to get more information about your installation, your problem. It should also help to find the issue with the REST API after domain change.</p>\n<p>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 - <a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/changing-the-site-url/</a></p>\n" } ]
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 (e.g. better search replace) or wp cli. E.g. to change from old domain to new domain, you can use old string: <code>https://olddomain.com</code> and new string <code>https://newdomain.com</code></p>\n<p>Also, try clearing cookies and redirections cache in the browser (ctr+shift+del on Windows, cmd+shift+backspace for Mac).</p>\n" }, { "answer_id": 402311, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 3, "selected": true, "text": "<p>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 <code>options</code> table, entries <code>siteurl</code> and <code>homeurl</code>.\nIt is also possible to set this via <code>wp-config.php</code>:</p>\n<pre><code>// Home URL of your WordPress.\ndefine( 'WP_SITEURL', 'https:/example.com' );\n// URL to the WordPress root dir.\ndefine( 'WP_HOME', 'https://example.com' );\n</code></pre>\n<p>Look also inside the <code>wp-config.php</code> for the domain, because it is possible to set this via constant. The <code>.htaccess</code>, if it is an Apache server, should also validate, because the Permalink rules need the domain, especially in the 'Multisite' mode.</p>\n<p>You should also active the <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">debug mode</a>, constant <code>WP_DEBUG</code> set to true in your <code>wp-config.php</code> to get more information about your installation, your problem. It should also help to find the issue with the REST API after domain change.</p>\n<p>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 - <a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/changing-the-site-url/</a></p>\n" } ]
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 (e.g. better search replace) or wp cli. E.g. to change from old domain to new domain, you can use old string: <code>https://olddomain.com</code> and new string <code>https://newdomain.com</code></p>\n<p>Also, try clearing cookies and redirections cache in the browser (ctr+shift+del on Windows, cmd+shift+backspace for Mac).</p>\n" }, { "answer_id": 402311, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 3, "selected": true, "text": "<p>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 <code>options</code> table, entries <code>siteurl</code> and <code>homeurl</code>.\nIt is also possible to set this via <code>wp-config.php</code>:</p>\n<pre><code>// Home URL of your WordPress.\ndefine( 'WP_SITEURL', 'https:/example.com' );\n// URL to the WordPress root dir.\ndefine( 'WP_HOME', 'https://example.com' );\n</code></pre>\n<p>Look also inside the <code>wp-config.php</code> for the domain, because it is possible to set this via constant. The <code>.htaccess</code>, if it is an Apache server, should also validate, because the Permalink rules need the domain, especially in the 'Multisite' mode.</p>\n<p>You should also active the <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">debug mode</a>, constant <code>WP_DEBUG</code> set to true in your <code>wp-config.php</code> to get more information about your installation, your problem. It should also help to find the issue with the REST API after domain change.</p>\n<p>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 - <a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/changing-the-site-url/</a></p>\n" } ]
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 (e.g. better search replace) or wp cli. E.g. to change from old domain to new domain, you can use old string: <code>https://olddomain.com</code> and new string <code>https://newdomain.com</code></p>\n<p>Also, try clearing cookies and redirections cache in the browser (ctr+shift+del on Windows, cmd+shift+backspace for Mac).</p>\n" }, { "answer_id": 402311, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 3, "selected": true, "text": "<p>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 <code>options</code> table, entries <code>siteurl</code> and <code>homeurl</code>.\nIt is also possible to set this via <code>wp-config.php</code>:</p>\n<pre><code>// Home URL of your WordPress.\ndefine( 'WP_SITEURL', 'https:/example.com' );\n// URL to the WordPress root dir.\ndefine( 'WP_HOME', 'https://example.com' );\n</code></pre>\n<p>Look also inside the <code>wp-config.php</code> for the domain, because it is possible to set this via constant. The <code>.htaccess</code>, if it is an Apache server, should also validate, because the Permalink rules need the domain, especially in the 'Multisite' mode.</p>\n<p>You should also active the <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">debug mode</a>, constant <code>WP_DEBUG</code> set to true in your <code>wp-config.php</code> to get more information about your installation, your problem. It should also help to find the issue with the REST API after domain change.</p>\n<p>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 - <a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/changing-the-site-url/</a></p>\n" } ]
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 (e.g. better search replace) or wp cli. E.g. to change from old domain to new domain, you can use old string: <code>https://olddomain.com</code> and new string <code>https://newdomain.com</code></p>\n<p>Also, try clearing cookies and redirections cache in the browser (ctr+shift+del on Windows, cmd+shift+backspace for Mac).</p>\n" }, { "answer_id": 402311, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 3, "selected": true, "text": "<p>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 <code>options</code> table, entries <code>siteurl</code> and <code>homeurl</code>.\nIt is also possible to set this via <code>wp-config.php</code>:</p>\n<pre><code>// Home URL of your WordPress.\ndefine( 'WP_SITEURL', 'https:/example.com' );\n// URL to the WordPress root dir.\ndefine( 'WP_HOME', 'https://example.com' );\n</code></pre>\n<p>Look also inside the <code>wp-config.php</code> for the domain, because it is possible to set this via constant. The <code>.htaccess</code>, if it is an Apache server, should also validate, because the Permalink rules need the domain, especially in the 'Multisite' mode.</p>\n<p>You should also active the <a href=\"https://codex.wordpress.org/WP_DEBUG\" rel=\"nofollow noreferrer\">debug mode</a>, constant <code>WP_DEBUG</code> set to true in your <code>wp-config.php</code> to get more information about your installation, your problem. It should also help to find the issue with the REST API after domain change.</p>\n<p>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 - <a href=\"https://wordpress.org/support/article/changing-the-site-url/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/article/changing-the-site-url/</a></p>\n" } ]
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/phpunit &lt;path_to_file&gt;</code></p>\n<p>This command should be Run from root directory of wordpress.</p>\n" }, { "answer_id": 402574, "author": "Scruffy Paws", "author_id": 28787, "author_profile": "https://wordpress.stackexchange.com/users/28787", "pm_score": 0, "selected": false, "text": "<p>I had the same issue and resolved it by adding the composer autoload to the top of my tests/bootstrap.php file...</p>\n<pre><code>require 'vendor/autoload.php';\n</code></pre>\n<p>After which I can run the normal <code>phpunit</code> command.</p>\n" } ]
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_posts( $query ) \n{\n // only for feeds\n if( !$query-&gt;is_feed || !$query-&gt;is_main_query() )\n return query;\n\n $exclude = 'your-cpt';\n $post_types = $query-&gt;get('post_type');\n\n if (($key = array_search($exclude, $post_types)) !== false)\n unset($post_types[$key]);\n\n $query-&gt;set( 'post_type', $post_types );\n\n return $query;\n}\n\nadd_action( 'pre_get_posts', 'wpse_191804_pre_get_posts' );\n</code></pre>\n" }, { "answer_id": 402446, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>If you dive into how this works, you end up at <a href=\"https://developer.wordpress.org/reference/classes/wp_post_type/set_props/\" rel=\"nofollow noreferrer\"><code>set_props</code></a>. At the bottom of that function you see that setting <code>rewrite' =&gt; array('feeds' =&gt; false)</code> will be interpreted as 'no rewriting', meaning the default will be used. Also, if you have not set the <code>has_archive</code> argument WP will not know what to fill the feed with. This is what leads to your 404's.</p>\n<p>That said, what you need is a function that intercepts queries for <code>\\feed\\</code> before they lead to a 404. After all, you can't prevent people typing that url in their browser window, even if there would be a method to stop WP from generating it. So I'd do a check like this:</p>\n<pre><code>add_action ('template_redirect','wpse402292_redirect_feed');\nfunction wpse402292_redirect_feed() {\n if (is_feed (array ('post','your-custom-post-type-name')))\n wp_redirect( home_url( '' ) ); // or somewhere else\n }\n</code></pre>\n" }, { "answer_id": 402467, "author": "Steve", "author_id": 3206, "author_profile": "https://wordpress.stackexchange.com/users/3206", "pm_score": 1, "selected": true, "text": "<p>From <a href=\"https://kinsta.com/knowledgebase/wordpress-disable-rss-feed/\" rel=\"nofollow noreferrer\">this post</a>, I added</p>\n<pre><code>remove_action( 'wp_head', 'feed_links_extra', 3 );\n</code></pre>\n<p>to our child theme's <code>functions.php</code>.</p>\n<p>Our SEO manager was okay with the fact this would remove feeds for categories as well.</p>\n" } ]
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 is why your code does not work as the returned value is discarded.</p>\n<p><em>In general, if you have to write SQL to do something in WordPress then you're either working with custom tables, or something has gone horribly wrong in the development process.</em> Usually efforts to write complicated SQL queries are because the developer is unaware of functions or APIs that do this for them but faster. This is what has happened here.</p>\n<h2>What pre_get_terms actually does</h2>\n<p><code>pre_get_terms</code> allows you to modify the parameters of a <code>WP_Term_Query</code> before it builds the query and executes it. The incorrect usage of the action becomes clearer if we add proper type hinting to the function:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('pre_get_terms', function( \\WP_Term_Query $term_query ) : void {\n</code></pre>\n<p>Actions do not return values, filters return values. This action provides the term query object so that parameters can be changed/removed/set, but does not return values or results.</p>\n<h2>Sorting by multiple meta</h2>\n<p>There are already parameters for doing exactly what you want to do.\nFor example to order by 2 meta fields, <code>state</code>, then <code>city</code>, you can do something like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$term_query-&gt;set( 'orderby', [\n 'city_clause' =&gt; 'ASC',\n 'state_clause' =&gt; 'DESC',\n] );\n$term_query-&gt;set( 'meta_query', [\n 'relation' =&gt; 'AND',\n 'state_clause' =&gt; [\n 'key' =&gt; 'state',\n 'value' =&gt; 'Wisconsin',\n ],\n 'city_clause' =&gt; [\n 'key' =&gt; 'city',\n 'compare' =&gt; 'EXISTS',\n ], \n] );\n</code></pre>\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_meta_query/#comment-4187\" rel=\"nofollow noreferrer\">This was adapted from an example in the official documentation for <code>WP_Meta_Query</code> on wordpress.org.</a> Usage in <code>WP_Query</code> and <code>WP_Comment_Query</code> would be similar if not identical.</p>\n<p>Writing SQL is unnecessary, and can even be counterproductive here, WordPress already provides this functionality. As a bonus this will work with pagination, the SQL query in the question will not. It will also work with the other functionality on that page such as filters and searches.</p>\n" }, { "answer_id": 402382, "author": "jbmgil", "author_id": 218755, "author_profile": "https://wordpress.stackexchange.com/users/218755", "pm_score": 2, "selected": true, "text": "<p>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.</p>\n<p>I have a custom taxonomy called &quot;aplication&quot; and another called &quot;segment&quot;, and every application term has a custom field (ACF) for a segment term.\nWhat 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.</p>\n<p>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.</p>\n<pre>\nadd_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3);\nfunction update_aplication_segment_name( $term_id, $tt_id, $update ) {\n \n $aplication = get_term( $term_id, 'aplication' ); //Gets the object of the current aplication\n $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\n $segment = get_term( $segment_ID, 'segment' ); //Gets the segment associated with the current aplication\n \n //Remove the hook to avoid loop\n remove_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3);\n \n //Updates the value of the 'aplication_segment_name' field of the current aplication\n update_term_meta( $term_id, 'aplication_segment_name', $segment->slug); \n \n //Add the hook back\n add_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3);\n}\n</pre>\n<p>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).\n<a href=\"https://i.stack.imgur.com/bua2D.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bua2D.png\" alt=\"enter image description here\" /></a></p>\n<p>Now, to sort the application terms by their segment's name I adapted the code from this answer: <a href=\"https://wordpress.stackexchange.com/a/277755/218755\">https://wordpress.stackexchange.com/a/277755/218755</a></p>\n<pre>\nadd_filter('pre_get_terms', function( $term_query ) {\n \n global $current_screen;\n\n if ( is_admin() && $current_screen->id == 'edit-aplication' \n && ( !isset($_GET['orderby']) || $_GET['orderby'] == 'aplication_segment')) {\n\n // set orderby to the named clause in the meta_query\n $term_query -> query_vars['orderby'] = 'order_clause';\n $term_query -> query_vars['order'] = isset($_GET['order']) ? $_GET['order'] : \"DESC\";\n\n // the OR relation and the NOT EXISTS clause allow for terms without a meta_value at all\n $args = array('relation' => 'OR',\n 'order_clause' => array('key' => 'aplication_segment_name',\n 'type' => 'STRING'\n ),\n array('key' => 'aplication_segment_name',\n 'compare' => 'NOT EXISTS'\n )\n );\n\n $term_query -> meta_query = new WP_Meta_Query( $args );\n\n }\n\n return $term_query;\n \n});\n</pre>\n<p>Now the aplication terms can be sorted by their associated segment term's name!\n<a href=\"https://i.stack.imgur.com/GJcHR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GJcHR.png\" alt=\"enter image description here\" /></a></p>\n" } ]
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 is why your code does not work as the returned value is discarded.</p>\n<p><em>In general, if you have to write SQL to do something in WordPress then you're either working with custom tables, or something has gone horribly wrong in the development process.</em> Usually efforts to write complicated SQL queries are because the developer is unaware of functions or APIs that do this for them but faster. This is what has happened here.</p>\n<h2>What pre_get_terms actually does</h2>\n<p><code>pre_get_terms</code> allows you to modify the parameters of a <code>WP_Term_Query</code> before it builds the query and executes it. The incorrect usage of the action becomes clearer if we add proper type hinting to the function:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action('pre_get_terms', function( \\WP_Term_Query $term_query ) : void {\n</code></pre>\n<p>Actions do not return values, filters return values. This action provides the term query object so that parameters can be changed/removed/set, but does not return values or results.</p>\n<h2>Sorting by multiple meta</h2>\n<p>There are already parameters for doing exactly what you want to do.\nFor example to order by 2 meta fields, <code>state</code>, then <code>city</code>, you can do something like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$term_query-&gt;set( 'orderby', [\n 'city_clause' =&gt; 'ASC',\n 'state_clause' =&gt; 'DESC',\n] );\n$term_query-&gt;set( 'meta_query', [\n 'relation' =&gt; 'AND',\n 'state_clause' =&gt; [\n 'key' =&gt; 'state',\n 'value' =&gt; 'Wisconsin',\n ],\n 'city_clause' =&gt; [\n 'key' =&gt; 'city',\n 'compare' =&gt; 'EXISTS',\n ], \n] );\n</code></pre>\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_meta_query/#comment-4187\" rel=\"nofollow noreferrer\">This was adapted from an example in the official documentation for <code>WP_Meta_Query</code> on wordpress.org.</a> Usage in <code>WP_Query</code> and <code>WP_Comment_Query</code> would be similar if not identical.</p>\n<p>Writing SQL is unnecessary, and can even be counterproductive here, WordPress already provides this functionality. As a bonus this will work with pagination, the SQL query in the question will not. It will also work with the other functionality on that page such as filters and searches.</p>\n" }, { "answer_id": 402382, "author": "jbmgil", "author_id": 218755, "author_profile": "https://wordpress.stackexchange.com/users/218755", "pm_score": 2, "selected": true, "text": "<p>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.</p>\n<p>I have a custom taxonomy called &quot;aplication&quot; and another called &quot;segment&quot;, and every application term has a custom field (ACF) for a segment term.\nWhat 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.</p>\n<p>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.</p>\n<pre>\nadd_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3);\nfunction update_aplication_segment_name( $term_id, $tt_id, $update ) {\n \n $aplication = get_term( $term_id, 'aplication' ); //Gets the object of the current aplication\n $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\n $segment = get_term( $segment_ID, 'segment' ); //Gets the segment associated with the current aplication\n \n //Remove the hook to avoid loop\n remove_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3);\n \n //Updates the value of the 'aplication_segment_name' field of the current aplication\n update_term_meta( $term_id, 'aplication_segment_name', $segment->slug); \n \n //Add the hook back\n add_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3);\n}\n</pre>\n<p>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).\n<a href=\"https://i.stack.imgur.com/bua2D.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bua2D.png\" alt=\"enter image description here\" /></a></p>\n<p>Now, to sort the application terms by their segment's name I adapted the code from this answer: <a href=\"https://wordpress.stackexchange.com/a/277755/218755\">https://wordpress.stackexchange.com/a/277755/218755</a></p>\n<pre>\nadd_filter('pre_get_terms', function( $term_query ) {\n \n global $current_screen;\n\n if ( is_admin() && $current_screen->id == 'edit-aplication' \n && ( !isset($_GET['orderby']) || $_GET['orderby'] == 'aplication_segment')) {\n\n // set orderby to the named clause in the meta_query\n $term_query -> query_vars['orderby'] = 'order_clause';\n $term_query -> query_vars['order'] = isset($_GET['order']) ? $_GET['order'] : \"DESC\";\n\n // the OR relation and the NOT EXISTS clause allow for terms without a meta_value at all\n $args = array('relation' => 'OR',\n 'order_clause' => array('key' => 'aplication_segment_name',\n 'type' => 'STRING'\n ),\n array('key' => 'aplication_segment_name',\n 'compare' => 'NOT EXISTS'\n )\n );\n\n $term_query -> meta_query = new WP_Meta_Query( $args );\n\n }\n\n return $term_query;\n \n});\n</pre>\n<p>Now the aplication terms can be sorted by their associated segment term's name!\n<a href=\"https://i.stack.imgur.com/GJcHR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GJcHR.png\" alt=\"enter image description here\" /></a></p>\n" } ]
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 think I would check for a only-WP constant as <code>WPINC</code> or check if a WordPress function or Class exists</p>\n" }, { "answer_id": 402859, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": true, "text": "<p>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.</p>\n<p>I used this code block:</p>\n<pre><code>if (function_exists('get_bloginfo')) { // most likely a WordPress function\n if (get_bloginfo('admin_email')) { // set it only if there is a value (a double-check)\n $admin_email = get_bloginfo('admin_email');\n }\n}\n</code></pre>\n<p>It first checks if the <code>get_bloginfo</code> function exists, because I need to let a prior setting of $admin_email 'stand' if not running withing WP.</p>\n<p>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 <code>get_bloginfo()</code> in a non-WP site. There might be a <code>get_bloginfo()</code> 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.</p>\n<p>The next line sets that variable.</p>\n<p>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.</p>\n" } ]
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>Catches the template include conditionally <code>add_filter( 'template_include', '...' );</code>, in my case based on a regex match of the expected URI pattern</li>\n<li><code>locate_template('example-template.php')</code> to then resolve my (essentially) static template</li>\n<li>A query within my <code>example-template.php</code> that externally retrieves the resource</li>\n<li>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 <code>get_header</code> in the template to <code>202</code> where the resource is found.</li>\n<li>Example; <code>if ($resource) { @header($_SERVER['SERVER_PROTOCOL'] . ' 202 Accepted', true, 202); }</code></li>\n</ol>\n<p>Bit convoluted, but really not too much work for what I required.</p>\n" }, { "answer_id": 402905, "author": "serhumanos", "author_id": 206080, "author_profile": "https://wordpress.stackexchange.com/users/206080", "pm_score": -1, "selected": false, "text": "<p>This solve the problem for me, only need the <strong>Parent-Post-ID</strong> and the <strong>full path of the template to be used</strong> for all subpages</p>\n<p>In functions.php I have this code:</p>\n<pre><code>add_filter( 'template_include', 'template_subpage', 99 );\nfunction template_subpage( $template ) {\n\n global $post;\n if($post-&gt;post_parent == $selected_parent_id){ // the id of the parent\n\n $template = get_template_directory() . '/template-subpage.php'; // template to assign to subpages\n }\n return $template;\n}\n</code></pre>\n" } ]
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;[email protected]&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 meant to be an array, not a new <code>WP_User_Query</code>.</p>\n<p>This is what you've done:</p>\n<pre class=\"lang-php prettyprint-override\"><code>get_users( [\n ...args\n 'meta_query' =&gt; new WP_User_Query( [ ...meta args ] ) // incorrect usage!\n] );\n</code></pre>\n<p>This is what you should do instead:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$query = new WP_User_Query( [\n ... args,\n 'meta_query' =&gt; [ .... meta args ]\n] );\n</code></pre>\n<p>Remember, <code>get_users</code> is a wrapper around <code>WP_User_Query</code>, and <code>WP_User_Query</code> is for finding users, not specifying meta parameters.</p>\n" }, { "answer_id": 402802, "author": "Bazdin", "author_id": 163076, "author_profile": "https://wordpress.stackexchange.com/users/163076", "pm_score": 2, "selected": false, "text": "<p>Actually since you already have the ID you could just loop through and get the meta.</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_user_meta/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_user_meta/</a></p>\n<pre><code>get_user_meta(ID)\n</code></pre>\n" } ]
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: "[email protected]" ​​​​ 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.</p>\n<p>The <a href=\"https://developer.wordpress.org/reference/functions/get_template_part/\" rel=\"nofollow noreferrer\">get_template_part()</a> function might be a good choice in your case.</p>\n" }, { "answer_id": 402855, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 2, "selected": true, "text": "<p>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.</p>\n<p>The magic ingredient here is the third <code>$args</code> parameter you can use with <code>get_template_part()</code>. Use it to pass data to the partial file.</p>\n<pre><code>$configs = array(\n array(\n 'query' =&gt; array(\n 'post_type' =&gt; 'diagram',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'diagram-category',\n 'terms' =&gt; 'stratocaster-wiring-diagrams',\n 'field' =&gt; 'slug',\n )\n )\n ),\n 'template_name' =&gt; 'wiring-diagram',\n 'heading' =&gt; 'Some heading text',\n ),\n // more configs...\n);\n\nforeach ( $configs as $config ) {\n $config['query'] = new WP_Query( $config['query'] );\n if ( ! $config['query']-&gt;posts ) {\n continue;\n }\n \n get_template_part( 'template-parts/content-section', null, $config );\n}\n</code></pre>\n<p>Section partial,</p>\n<pre><code>&lt;h2 class=&quot;main-heading gold-line&quot;&gt;&lt;?php echo esc_html( $args['heading'] ); ?&gt;&lt;/h2&gt;\n&lt;div class=&quot;wiring-diagram-results grid-4&quot;&gt;\n &lt;?php\n while( $args['query']-&gt;have_posts() ) {\n $args['query']-&gt;the_post();\n get_template_part( 'template-parts/content', $args['template_name'] );\n }\n wp_reset_postdata();\n ?&gt;\n&lt;/div&gt;\n</code></pre>\n<p>The config array could also be placed into a separate file or function and not to have it hard-coded on the template file.</p>\n" } ]
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 updates are needed. This is because you used <code>select</code> and <code>dispatch</code> directly from the <code>@wordpress/data</code> package.</p>\n<p>You shouldn't use <code>select</code> and <code>dispatch</code> directly, you're meant to use the <code>useSelect</code> and <code>useDispatch</code> hooks.</p>\n<p>You'll also need to convert this to a function based component, you can't use hooks with class based components</p>\n" }, { "answer_id": 402884, "author": "Thomas Zwirner", "author_id": 219391, "author_profile": "https://wordpress.stackexchange.com/users/219391", "pm_score": 2, "selected": true, "text": "<p><strong>Solution found:</strong></p>\n<pre><code>const { __ } = wp.i18n;\nconst { useSelect, useDispatch } = wp.data;\nconst { PluginDocumentSettingPanel } = wp.editPost;\nconst { CheckboxControl, PanelRow } = wp.components;\n\nconst Sidebar = () =&gt; {\n const { postMeta } = useSelect( ( select ) =&gt; {\n return {\n postMeta: select( 'core/editor' ).getEditedPostAttribute( 'meta' ),\n };\n } );\n const { editPost } = useDispatch( 'core/editor', [ postMeta.code ] );\n\n return(\n &lt;PluginDocumentSettingPanel title={ __( 'Display Settings', 'myplugin') }&gt;\n &lt;PanelRow&gt;\n &lt;CheckboxControl\n label={ __( 'My Label', 'myplugin' ) }\n checked={ postMeta.code }\n onChange={ ( value ) =&gt; editPost( { meta: { code: value } } ) }\n /&gt;\n &lt;/PanelRow&gt;\n &lt;/PluginDocumentSettingPanel&gt;\n );\n}\n\nexport default Sidebar;\n</code></pre>\n" } ]
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 updates are needed. This is because you used <code>select</code> and <code>dispatch</code> directly from the <code>@wordpress/data</code> package.</p>\n<p>You shouldn't use <code>select</code> and <code>dispatch</code> directly, you're meant to use the <code>useSelect</code> and <code>useDispatch</code> hooks.</p>\n<p>You'll also need to convert this to a function based component, you can't use hooks with class based components</p>\n" }, { "answer_id": 402884, "author": "Thomas Zwirner", "author_id": 219391, "author_profile": "https://wordpress.stackexchange.com/users/219391", "pm_score": 2, "selected": true, "text": "<p><strong>Solution found:</strong></p>\n<pre><code>const { __ } = wp.i18n;\nconst { useSelect, useDispatch } = wp.data;\nconst { PluginDocumentSettingPanel } = wp.editPost;\nconst { CheckboxControl, PanelRow } = wp.components;\n\nconst Sidebar = () =&gt; {\n const { postMeta } = useSelect( ( select ) =&gt; {\n return {\n postMeta: select( 'core/editor' ).getEditedPostAttribute( 'meta' ),\n };\n } );\n const { editPost } = useDispatch( 'core/editor', [ postMeta.code ] );\n\n return(\n &lt;PluginDocumentSettingPanel title={ __( 'Display Settings', 'myplugin') }&gt;\n &lt;PanelRow&gt;\n &lt;CheckboxControl\n label={ __( 'My Label', 'myplugin' ) }\n checked={ postMeta.code }\n onChange={ ( value ) =&gt; editPost( { meta: { code: value } } ) }\n /&gt;\n &lt;/PanelRow&gt;\n &lt;/PluginDocumentSettingPanel&gt;\n );\n}\n\nexport default Sidebar;\n</code></pre>\n" } ]
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>is written in the docs</strong>, but rather obscurely. If you check out the <a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#frontend-enqueueing\" rel=\"noreferrer\">Frontend Enqueueing</a> section of the Block Editor Handbook, you'll see this statement.</p>\n<pre><code>Frontend Enqueueing #Frontend Enqueueing\nStarting 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:\n\n- script\n- viewScript (when the block defines render_callback during registration in PHP, then the block author is responsible for enqueuing the script)\n- style\n</code></pre>\n<p>As it turns out I have defined a <code>render_callback</code> so I do need to manually enqueue my <code>view.js</code> script.</p>\n<p>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. </p>\n" }, { "answer_id": 405331, "author": "Lovor", "author_id": 135704, "author_profile": "https://wordpress.stackexchange.com/users/135704", "pm_score": 2, "selected": false, "text": "<p>EVEN NEWER EDIT: I actively participated as contributor in changing this rule. Starting from WordPress 6.1, viewScript <strong>will</strong> enqueue javascript even for dynamic blocks.</p>\n<p>See <a href=\"https://core.trac.wordpress.org/ticket/56470\" rel=\"nofollow noreferrer\">trac #56470</a>.</p>\n<p>EDIT: I spoke yesterday with WP developers, viewScript does not actually <strong>enqueue</strong> script, but only <strong>registers</strong> it.</p>\n<p>The reason is that in <code>render_callback</code> you might conclude that script is not necessary and not enqueue it. So, only for <strong>dynamic blocks</strong>, viewScript registers the script, while you must enqueue it in <code>render_callback</code>. For regular React blocks, script is automatically enqueued.</p>\n<hr />\n<p>I tested this with WordPress 5.9.3 and @wordpress/scripts 22.5.0 and script does get enqueued. I think the original error was <code>&quot;viewScript&quot;: &quot;file:./build/view.js&quot;</code> in block.json. Block.json should be placed in src directory, together with view script and they are copied in the build process to build directory. Afterwards, block is initialized from build directory.</p>\n<p>i.e. for dynamic block <code>logos</code> (it has php for front end showing)</p>\n<pre class=\"lang-php prettyprint-override\"><code>...\nrequire 'logos/src/index.php';\nregister_block_type( &quot;$dir/logos/build&quot;,\n ['render_callback' =&gt; 'render_logos'] );\n...\n</code></pre>\n<p>in block.json:</p>\n<pre class=\"lang-json prettyprint-override\"><code>...\n&quot;editorScript&quot;: &quot;file:index.js&quot;,\n&quot;editorStyle&quot;: &quot;file:index.css&quot;,\n&quot;style&quot;: &quot;file:style-index.css&quot;,\n&quot;viewScript&quot;: &quot;file:logos-front.js&quot;,\n...\n</code></pre>\n" }, { "answer_id": 409960, "author": "Nabha Cosley", "author_id": 335, "author_profile": "https://wordpress.stackexchange.com/users/335", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem, but it was because my <code>wp script build</code> and <code>wp script start</code> used a custom entry point.</p>\n<p>I had to add my viewScript manually to the build/start commands as in this example. Then in <code>block.json</code> I pointed the viewScript to the build folder, and it began enqueuing automatically:</p>\n<p><code>&quot;build:custom&quot;: &quot;wp-scripts build index.js view.js --output-path=build&quot;</code></p>\n" } ]
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 file to manipulate how Apache serves files from\nits root directory, and subdirectories thereof. Most notably, WP\nmodifies this file to be able to handle pretty permalinks.</p>\n</blockquote>\n<p>And a basic .htaccess file content will looks like this:</p>\n<pre><code># BEGIN WordPress\n\nRewriteEngine On\nRewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n\n# END WordPress\n</code></pre>\n<p>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 <em>Save changes</em> button at the bottom of that page, to regenerate a new <code>.htaccess</code> file on you installation directory automatically, with your current rewrite files rules, that matches with your website configuration.</p>\n<p>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.</p>\n" }, { "answer_id": 403004, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>WordPress' standard <code>.htaccess</code> file contains:</p>\n<pre><code># BEGIN WordPress\n\nRewriteEngine On\nRewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n\n# END WordPress\n</code></pre>\n<p>It does look like your current <code>.htaccess</code> file is set up to redirect every request that comes in on any domain and any path. You can delete it and let WP generate its own, or use the standard one above.</p>\n<p>When changing domains, you'll also need to make sure to run a migration script to update all instances of the old domain within your database. The WP CLI command <code>wp search-replace</code> is one fast way to do this; there are also plugins that will do the replacement, or your host may be able to run the migration for you. Also double-check that your <code>wp-config.php</code> file has the credentials for the new server rather than the old.</p>\n" } ]
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 file to manipulate how Apache serves files from\nits root directory, and subdirectories thereof. Most notably, WP\nmodifies this file to be able to handle pretty permalinks.</p>\n</blockquote>\n<p>And a basic .htaccess file content will looks like this:</p>\n<pre><code># BEGIN WordPress\n\nRewriteEngine On\nRewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n\n# END WordPress\n</code></pre>\n<p>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 <em>Save changes</em> button at the bottom of that page, to regenerate a new <code>.htaccess</code> file on you installation directory automatically, with your current rewrite files rules, that matches with your website configuration.</p>\n<p>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.</p>\n" }, { "answer_id": 403004, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 0, "selected": false, "text": "<p>WordPress' standard <code>.htaccess</code> file contains:</p>\n<pre><code># BEGIN WordPress\n\nRewriteEngine On\nRewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n\n# END WordPress\n</code></pre>\n<p>It does look like your current <code>.htaccess</code> file is set up to redirect every request that comes in on any domain and any path. You can delete it and let WP generate its own, or use the standard one above.</p>\n<p>When changing domains, you'll also need to make sure to run a migration script to update all instances of the old domain within your database. The WP CLI command <code>wp search-replace</code> is one fast way to do this; there are also plugins that will do the replacement, or your host may be able to run the migration for you. Also double-check that your <code>wp-config.php</code> file has the credentials for the new server rather than the old.</p>\n" } ]
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 your page, and jQuery is loaded in the footer (ie, at the end), then jQuery <em>doesn't exist</em> when you're trying to run your jQuery code.</p>\n<p>Either enqueue <code>jquery</code> to load in the header (ie, set the <code>$in_footer</code> parameter to <code>false</code>), or—the better option—use <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_script()</code></a> to properly load your script. This latter option will also let you define <code>jquery</code> as a dependency for your script.</p>\n" }, { "answer_id": 403124, "author": "Rafael Atías", "author_id": 208483, "author_profile": "https://wordpress.stackexchange.com/users/208483", "pm_score": 1, "selected": false, "text": "<p>The error is self-explanatory. When you insert your code, jQuery has not been defined. You have to put that <code>script</code> after jQuery is loaded.</p>\n<p>If you can't change where jQuery is defined, as you say in your comment to <a href=\"https://wordpress.stackexchange.com/a/403117/208483\">Pat J's answer</a>, then insert your script in the <code>&lt;footer&gt;</code>.</p>\n" } ]
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 add_query_arg('nocfcache', 'true', $url);\n }\n}\n\nadd_action( 'plugins_loaded', function(){ \nif ( is_user_logged_in() ) {\n add_filter( 'home_url', 'add_admin_qs', 11, 1);\n add_filter( 'post_link', 'add_admin_qs', 10, 1);\n add_filter( 'page_link', 'add_admin_qs', 10, 1);\n add_filter( 'post_type_link', 'add_admin_qs', 10, 1);\n add_filter( 'category_link', 'add_admin_qs', 11, 1);\n add_filter( 'tag_link', 'add_admin_qs', 10, 1);\n add_filter( 'author_link', 'add_admin_qs', 11, 1);\n add_filter( 'day_link', 'add_admin_qs', 11, 1);\n add_filter( 'month_link', 'add_admin_qs', 11, 1);\n add_filter( 'year_link', 'add_admin_qs', 11, 1);\n}\n});\n</code></pre>\n<p>I think the main problem is you're loading your code at the WP load and maybe before you're really logged in for WP.</p>\n" }, { "answer_id": 403205, "author": "228", "author_id": 219741, "author_profile": "https://wordpress.stackexchange.com/users/219741", "pm_score": 1, "selected": false, "text": "<p>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.</p>\n<p><a href=\"https://i.stack.imgur.com/U0RNv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/U0RNv.png\" alt=\"enter image description here\" /></a></p>\n" } ]
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='stylesheet' id='twenty-twenty-one-style-css'... ) using javascript.</p>\n<p>in JS</p>\n<pre><code>const parentStyleCss = document.querySelector('#twenty-twenty-one-style-css');\nparentStyleCss.parentNode.removeChild(parentStyleCss);\n</code></pre>\n<p>This is not the best way to go, I know.\nSo, if anybody can give a hint to remove the line via coding in Wordpress's function.php I'd be happy to hear it.</p>\n<p>Frank</p>\n" }, { "answer_id": 403684, "author": "FDue", "author_id": 219857, "author_profile": "https://wordpress.stackexchange.com/users/219857", "pm_score": 1, "selected": false, "text": "<p>The file 'style.css' is integrated via function 'twenty_twenty_one_scripts' in the parent themes functions.php.</p>\n<pre><code>function twenty_twenty_one_scripts() {\n // Note, the is_IE global variable is defined by WordPress and is used\n // to detect if the current browser is internet explorer.\n\n global $is_IE, $wp_scripts;\n\n if ( $is_IE ) {\n // If IE 11 or below, use a flattened stylesheet with static values replacing CSS Variables.\n wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/assets/css/ie.css', array(), wp_get_theme()-&gt;get( 'Version' ) );\n } else {\n // If not IE, use the standard stylesheet.\n wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/style.css', array(), wp_get_theme()-&gt;get( 'Version' ) );\n }\n\n // RTL styles.\n wp_style_add_data( 'twenty-twenty-one-style', 'rtl', 'replace' );\n\n // Print styles.\n wp_enqueue_style( 'twenty-twenty-one-print-style', get_template_directory_uri() . '/assets/css/print.css', array(), wp_get_theme()-&gt;get( 'Version' ), 'print' );\n...\n</code></pre>\n<p>To change this, disable function 'twenty_twenty_one_scripts' in the child themes function.php</p>\n<pre><code>function remove_my_action() {\n remove_action( 'wp_enqueue_scripts', 'twenty_twenty_one_scripts' );\n}\nadd_action( 'wp_head', 'remove_my_action' );\n</code></pre>\n<p>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:</p>\n<pre><code>function my_twenty_twenty_one_scripts() {\n // Note, the is_IE global variable is defined by WordPress and is used\n // to detect if the current browser is internet explorer.\n\n global $is_IE, $wp_scripts;\n\n /*\n if ( $is_IE ) {\n // If IE 11 or below, use a flattened stylesheet with static values replacing CSS Variables.\n wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/assets/css/ie.css', array(), wp_get_theme()-&gt;get( 'Version' ) );\n } else {\n // If not IE, use the standard stylesheet.\n wp_enqueue_style( 'twenty-twenty-one-style', get_template_directory_uri() . '/style.css', array(), wp_get_theme()-&gt;get( 'Version' ) );\n }\n */\n\n // RTL styles.\n wp_style_add_data( 'twenty-twenty-one-style', 'rtl', 'replace' );\n\n // Print styles.\n wp_enqueue_style( 'twenty-twenty-one-print-style', get_template_directory_uri() . '/assets/css/print.css', array(), wp_get_theme()-&gt;get( 'Version' ), 'print' );\n...\n</code></pre>\n<p>Activate the new function 'my_twenty_twenty_one_scripts' in child themes function.php</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'my_twenty_twenty_one_scripts' );\n</code></pre>\n" } ]
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 class called <code>WP_Block_Type_Registry</code> that you can use to see what is already registered:</p>\n<pre><code>$registry = WP_Block_Type_Registry::get_instance();\nif ( ! $registry-&gt;get_registered( 'foo/column' ) ) {\n // YOUR CODE\n}\n</code></pre>\n<p>Gutenberg should fire a console error if a block has already been registered. See the <code>registerBlockType</code> src <a href=\"https://github.com/WordPress/gutenberg/blob/trunk/packages/blocks/src/api/registration.js#L247\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 410356, "author": "odil-io", "author_id": 218062, "author_profile": "https://wordpress.stackexchange.com/users/218062", "pm_score": 0, "selected": false, "text": "<p>When editing a page using Gutenberg, you can use the Developers Console to execute <a href=\"https://developer.wordpress.org/block-editor/reference-guides/packages/packages-blocks/#getblocktypes\" rel=\"nofollow noreferrer\"><code>wp.blocks.getBlockTypes()</code></a> and get all active registered blocks in Gutenberg.</p>\n<p>You can also use the <a href=\"https://developer.wordpress.org/reference/classes/wp_block_type_registry\" rel=\"nofollow noreferrer\">WP_Block_Type_Registry</a> Class in order get all server-side registered Blocks.\nYou can than either use <a href=\"https://developer.wordpress.org/reference/classes/wp_block_type_registry/get_all_registered/\" rel=\"nofollow noreferrer\">get_all_registered()</a> or <a href=\"https://developer.wordpress.org/reference/classes/wp_block_type_registry/get_instance/\" rel=\"nofollow noreferrer\">get_instance()</a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>WP_Block_Type_Registry::get_all_registered();\n</code></pre>\n<p>or</p>\n<pre class=\"lang-php prettyprint-override\"><code>WP_Block_Type_Registry::get_instance()-&gt;get_all_registered();\n</code></pre>\n<p>Both do the same. <code>get_instance()</code> returns itself.</p>\n" } ]
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>\n<pre><code>add_action(&quot;wpcf7_before_send_mail&quot;, &quot;wpcf7_pause_send&quot;); \nfunction wpcf7_pause_send($cf7) {\n \n sleep(3600);\n}\n</code></pre>\n" }, { "answer_id": 403424, "author": "Nabeen", "author_id": 204829, "author_profile": "https://wordpress.stackexchange.com/users/204829", "pm_score": -1, "selected": false, "text": "<p>In some cases, if you are not logged in on your site your form doesn't get submitted. Try submitting the form being logged in on site.</p>\n" }, { "answer_id": 403441, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>I don't know CF7 well enough to give you specifics, but I think you'll need to</p>\n<ol>\n<li>Write the form data to the database so you can read it back later, when you want to send the email. I don't believe CF does this automatically (although e.g. Gravity forms do)</li>\n<li>On submission\n<ol>\n<li>Cancel the existing email send: I'd guess there's an event you can hook and return false that'll do this</li>\n<li>Either schedule a one-off event for two hours time using wp_schedule_single_event() and the saved data's database ID, and in that event handler call back to the CF7 with the data to send the email, and then either deletes the saved form data from the database or otherwise marks it as sent</li>\n<li>Or set up a regular scheduled job with wp_schedule_event() that runs every five minutes or so and checks if it needs to send any emails, e.g. there is a new saved form data record from &gt;2 hours ago that is not already marked as sent in the database, and if so sends the email and marks that form sent</li>\n</ol>\n</li>\n<li>Depending on your traffic levels you may want to set up an alternative cron mechanism to ensure these jobs run on time: <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"nofollow noreferrer\">Hooking WP-Cron into the system scheduler</a></li>\n</ol>\n<p>Alternatively depending on how you're sending emails you may be able to generate them on the initial form submission to be sent later, e.g. if you're sending them through Outlook.com or if your wp_mail hander has built-in retry and scheduling (as I'd guess WP Offload SES might?)</p>\n" } ]
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>\n<pre><code>add_action(&quot;wpcf7_before_send_mail&quot;, &quot;wpcf7_pause_send&quot;); \nfunction wpcf7_pause_send($cf7) {\n \n sleep(3600);\n}\n</code></pre>\n" }, { "answer_id": 403424, "author": "Nabeen", "author_id": 204829, "author_profile": "https://wordpress.stackexchange.com/users/204829", "pm_score": -1, "selected": false, "text": "<p>In some cases, if you are not logged in on your site your form doesn't get submitted. Try submitting the form being logged in on site.</p>\n" }, { "answer_id": 403441, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>I don't know CF7 well enough to give you specifics, but I think you'll need to</p>\n<ol>\n<li>Write the form data to the database so you can read it back later, when you want to send the email. I don't believe CF does this automatically (although e.g. Gravity forms do)</li>\n<li>On submission\n<ol>\n<li>Cancel the existing email send: I'd guess there's an event you can hook and return false that'll do this</li>\n<li>Either schedule a one-off event for two hours time using wp_schedule_single_event() and the saved data's database ID, and in that event handler call back to the CF7 with the data to send the email, and then either deletes the saved form data from the database or otherwise marks it as sent</li>\n<li>Or set up a regular scheduled job with wp_schedule_event() that runs every five minutes or so and checks if it needs to send any emails, e.g. there is a new saved form data record from &gt;2 hours ago that is not already marked as sent in the database, and if so sends the email and marks that form sent</li>\n</ol>\n</li>\n<li>Depending on your traffic levels you may want to set up an alternative cron mechanism to ensure these jobs run on time: <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"nofollow noreferrer\">Hooking WP-Cron into the system scheduler</a></li>\n</ol>\n<p>Alternatively depending on how you're sending emails you may be able to generate them on the initial form submission to be sent later, e.g. if you're sending them through Outlook.com or if your wp_mail hander has built-in retry and scheduling (as I'd guess WP Offload SES might?)</p>\n" } ]
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>\n<pre><code>add_action(&quot;wpcf7_before_send_mail&quot;, &quot;wpcf7_pause_send&quot;); \nfunction wpcf7_pause_send($cf7) {\n \n sleep(3600);\n}\n</code></pre>\n" }, { "answer_id": 403424, "author": "Nabeen", "author_id": 204829, "author_profile": "https://wordpress.stackexchange.com/users/204829", "pm_score": -1, "selected": false, "text": "<p>In some cases, if you are not logged in on your site your form doesn't get submitted. Try submitting the form being logged in on site.</p>\n" }, { "answer_id": 403441, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>I don't know CF7 well enough to give you specifics, but I think you'll need to</p>\n<ol>\n<li>Write the form data to the database so you can read it back later, when you want to send the email. I don't believe CF does this automatically (although e.g. Gravity forms do)</li>\n<li>On submission\n<ol>\n<li>Cancel the existing email send: I'd guess there's an event you can hook and return false that'll do this</li>\n<li>Either schedule a one-off event for two hours time using wp_schedule_single_event() and the saved data's database ID, and in that event handler call back to the CF7 with the data to send the email, and then either deletes the saved form data from the database or otherwise marks it as sent</li>\n<li>Or set up a regular scheduled job with wp_schedule_event() that runs every five minutes or so and checks if it needs to send any emails, e.g. there is a new saved form data record from &gt;2 hours ago that is not already marked as sent in the database, and if so sends the email and marks that form sent</li>\n</ol>\n</li>\n<li>Depending on your traffic levels you may want to set up an alternative cron mechanism to ensure these jobs run on time: <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"nofollow noreferrer\">Hooking WP-Cron into the system scheduler</a></li>\n</ol>\n<p>Alternatively depending on how you're sending emails you may be able to generate them on the initial form submission to be sent later, e.g. if you're sending them through Outlook.com or if your wp_mail hander has built-in retry and scheduling (as I'd guess WP Offload SES might?)</p>\n" } ]
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>\n<pre><code>add_action(&quot;wpcf7_before_send_mail&quot;, &quot;wpcf7_pause_send&quot;); \nfunction wpcf7_pause_send($cf7) {\n \n sleep(3600);\n}\n</code></pre>\n" }, { "answer_id": 403424, "author": "Nabeen", "author_id": 204829, "author_profile": "https://wordpress.stackexchange.com/users/204829", "pm_score": -1, "selected": false, "text": "<p>In some cases, if you are not logged in on your site your form doesn't get submitted. Try submitting the form being logged in on site.</p>\n" }, { "answer_id": 403441, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>I don't know CF7 well enough to give you specifics, but I think you'll need to</p>\n<ol>\n<li>Write the form data to the database so you can read it back later, when you want to send the email. I don't believe CF does this automatically (although e.g. Gravity forms do)</li>\n<li>On submission\n<ol>\n<li>Cancel the existing email send: I'd guess there's an event you can hook and return false that'll do this</li>\n<li>Either schedule a one-off event for two hours time using wp_schedule_single_event() and the saved data's database ID, and in that event handler call back to the CF7 with the data to send the email, and then either deletes the saved form data from the database or otherwise marks it as sent</li>\n<li>Or set up a regular scheduled job with wp_schedule_event() that runs every five minutes or so and checks if it needs to send any emails, e.g. there is a new saved form data record from &gt;2 hours ago that is not already marked as sent in the database, and if so sends the email and marks that form sent</li>\n</ol>\n</li>\n<li>Depending on your traffic levels you may want to set up an alternative cron mechanism to ensure these jobs run on time: <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"nofollow noreferrer\">Hooking WP-Cron into the system scheduler</a></li>\n</ol>\n<p>Alternatively depending on how you're sending emails you may be able to generate them on the initial form submission to be sent later, e.g. if you're sending them through Outlook.com or if your wp_mail hander has built-in retry and scheduling (as I'd guess WP Offload SES might?)</p>\n" } ]
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>\n<pre><code>add_action(&quot;wpcf7_before_send_mail&quot;, &quot;wpcf7_pause_send&quot;); \nfunction wpcf7_pause_send($cf7) {\n \n sleep(3600);\n}\n</code></pre>\n" }, { "answer_id": 403424, "author": "Nabeen", "author_id": 204829, "author_profile": "https://wordpress.stackexchange.com/users/204829", "pm_score": -1, "selected": false, "text": "<p>In some cases, if you are not logged in on your site your form doesn't get submitted. Try submitting the form being logged in on site.</p>\n" }, { "answer_id": 403441, "author": "Rup", "author_id": 3276, "author_profile": "https://wordpress.stackexchange.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>I don't know CF7 well enough to give you specifics, but I think you'll need to</p>\n<ol>\n<li>Write the form data to the database so you can read it back later, when you want to send the email. I don't believe CF does this automatically (although e.g. Gravity forms do)</li>\n<li>On submission\n<ol>\n<li>Cancel the existing email send: I'd guess there's an event you can hook and return false that'll do this</li>\n<li>Either schedule a one-off event for two hours time using wp_schedule_single_event() and the saved data's database ID, and in that event handler call back to the CF7 with the data to send the email, and then either deletes the saved form data from the database or otherwise marks it as sent</li>\n<li>Or set up a regular scheduled job with wp_schedule_event() that runs every five minutes or so and checks if it needs to send any emails, e.g. there is a new saved form data record from &gt;2 hours ago that is not already marked as sent in the database, and if so sends the email and marks that form sent</li>\n</ol>\n</li>\n<li>Depending on your traffic levels you may want to set up an alternative cron mechanism to ensure these jobs run on time: <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/\" rel=\"nofollow noreferrer\">Hooking WP-Cron into the system scheduler</a></li>\n</ol>\n<p>Alternatively depending on how you're sending emails you may be able to generate them on the initial form submission to be sent later, e.g. if you're sending them through Outlook.com or if your wp_mail hander has built-in retry and scheduling (as I'd guess WP Offload SES might?)</p>\n" } ]
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 // The $ID of post is different from ID that i have in post_title string\n\n // In field post_title i have the json string, that i will convert to json\n $parse_post = json_encode($post-&gt;post_title); \n\n // Here is the error: Your are decoding $parse_post while parsed post has encoded $post-&gt;post_title.\n $encoded_post = wp_json_encode( $post );\n $post_decode = json_decode( $encoded_post );\n // Post Decode return this \n\n // {&quot;id&quot;:&quot;9566&quot;,&quot;date&quot;:&quot;2021-07-28T17:12:31&quot;,&quot;title&quot;:&quot;test post&quot; }\n\n // Here is the issue, i need to get the id from json in $post_decode\n $post_name = isset( $post_decode-&gt;ID ) ? $post_decode-&gt;ID : $post_decode-&gt;id;\n\n // Dir to save the file\n $dir = plugin_dir_path( __DIR__ );\n\n // Here i need to add the id inside $parse_post json string\n $file_path = &quot;$post_name'.json'&quot;;\n \n // Not show any result\n print_r($file_path);\n\n file_put_contents($dir.$file_path, $post_decode);\n}, 10, 2);\n</code></pre>\n" }, { "answer_id": 403673, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": true, "text": "<p><code>json_encode</code> takes an array/object and turns it into a JSON string.</p>\n<p><code>json_decode</code> takes a JSON string and turns it into a PHP array/object/etc</p>\n<p>With this in mind, we can see some critical mistakes are made in the code, caused by muddling up the two.</p>\n<ol>\n<li>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: <code>json_encode( json_encode( ['ID' =&gt; 2] ) )</code></li>\n<li>You're then immediatley decoding it, so <code>$post_decode</code> and <code>$post-&gt;title</code> 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</li>\n<li>Then, for some reason <code>json_encode</code> is called, but it's called on a nonexistant value. Remember, <code>$post_decode</code> is not an array/object, it's a JSON string that hasn't been decoded, what you're doing is the same as <code>$foo = 'bar'; echo $foo-&gt;ID;</code>. Expect this to generate huge amounts of PHP notices and warnings in your PHP error log.</li>\n</ol>\n<p>This is all very confusing and unnecessary.</p>\n<p>Instead take your post title and decode it from JSON into an object:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$data = json_decode( $post-&gt;post_title );\n</code></pre>\n<p>Then use it:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$ID = $data-&gt;id;\n</code></pre>\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 // The $ID of post is different from ID that i have in post_title string\n\n // In field post_title i have the json string, that i will convert to json\n $parse_post = json_encode($post-&gt;post_title); \n\n // Here is the error: Your are decoding $parse_post while parsed post has encoded $post-&gt;post_title.\n $encoded_post = wp_json_encode( $post );\n $post_decode = json_decode( $encoded_post );\n // Post Decode return this \n\n // {&quot;id&quot;:&quot;9566&quot;,&quot;date&quot;:&quot;2021-07-28T17:12:31&quot;,&quot;title&quot;:&quot;test post&quot; }\n\n // Here is the issue, i need to get the id from json in $post_decode\n $post_name = isset( $post_decode-&gt;ID ) ? $post_decode-&gt;ID : $post_decode-&gt;id;\n\n // Dir to save the file\n $dir = plugin_dir_path( __DIR__ );\n\n // Here i need to add the id inside $parse_post json string\n $file_path = &quot;$post_name'.json'&quot;;\n \n // Not show any result\n print_r($file_path);\n\n file_put_contents($dir.$file_path, $post_decode);\n}, 10, 2);\n</code></pre>\n" }, { "answer_id": 403673, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": true, "text": "<p><code>json_encode</code> takes an array/object and turns it into a JSON string.</p>\n<p><code>json_decode</code> takes a JSON string and turns it into a PHP array/object/etc</p>\n<p>With this in mind, we can see some critical mistakes are made in the code, caused by muddling up the two.</p>\n<ol>\n<li>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: <code>json_encode( json_encode( ['ID' =&gt; 2] ) )</code></li>\n<li>You're then immediatley decoding it, so <code>$post_decode</code> and <code>$post-&gt;title</code> 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</li>\n<li>Then, for some reason <code>json_encode</code> is called, but it's called on a nonexistant value. Remember, <code>$post_decode</code> is not an array/object, it's a JSON string that hasn't been decoded, what you're doing is the same as <code>$foo = 'bar'; echo $foo-&gt;ID;</code>. Expect this to generate huge amounts of PHP notices and warnings in your PHP error log.</li>\n</ol>\n<p>This is all very confusing and unnecessary.</p>\n<p>Instead take your post title and decode it from JSON into an object:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$data = json_decode( $post-&gt;post_title );\n</code></pre>\n<p>Then use it:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$ID = $data-&gt;id;\n</code></pre>\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 noreferrer\">robots.txt</a>, if you haven't. Another good reference is <a href=\"https://yoast.com/ultimate-guide-robots-txt/\" rel=\"nofollow noreferrer\">this one from Yoast</a>.</p>\n<p>The sample you posted:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php\n\nSitemap: https://knowingart.com/wp-sitemap.xml\n</code></pre>\n<p>...tells all user-agents (ie, all crawlers) that they are <em>not allowed</em> to crawl <em>anything</em> in your <code>wp-admin</code> directory <em>except</em> <code>/wp-admin/admin-ajax.php</code>, <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/#url\" rel=\"nofollow noreferrer\">which is required by WordPress for properly-functioning AJAX</a>.</p>\n<p>It's <em>not</em> telling robots to go to your <code>/wp-admin/</code> directory; it's telling them they're unwelcome there (except for the AJAX requirement).</p>\n<p>As for your question #4, I'm afraid I don't have an answer to that one.</p>\n" }, { "answer_id": 403766, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>the truth is that probably nothing should be blocked in <code>robots.txt</code> by core (this is IIRC was joost's position abot the matter) as wordpress is an open platform and front end content and styling might and is generated in all kinds of directories which might not make much sense to you and me. Wordpress is not in the buisness of preventing site owners from installing badly written plugins.</p>\n<p>Why do you have pages indexed by a search engine? Wordpress uses a kind of &quot;don't index&quot; headers for all admin pages so most likely you have some badly written code that prevents the header from bein sent. (this assumes that there is no bug in bing which is the SE which powers DDG).</p>\n<p>Maybe worth reminding that robots.txt is just an advisory file, it is up to the search engine to decide if and how to respect it. IIRC google will not respect it fully if there was a link to a page which supposed to be excluded by robots.txt</p>\n" }, { "answer_id": 414244, "author": "Zyraxx", "author_id": 230375, "author_profile": "https://wordpress.stackexchange.com/users/230375", "pm_score": 0, "selected": false, "text": "<p>There is a great reason why WordPress, despite being one of the most used frameworks, is also among the ones that has most errors and bad practices, just look at any log and count the hundreds of warnings it throws, and the reason is no other than poor development and lazy developers.</p>\n<p>Now to the point: you should always write your own robots.txt, you don't need google to index your wp-ajax, you probably aren't even using it, and in most cases it generates vulnerabilities, you should also disable access for guests or use a plugin to hide it or simply disable it completely, WP will work in 90% of cases and you will not expose your user list to the world. Also be careful with the autogenerated sitemap as it may display usernames making bruteforcing halfway easier</p>\n<p>All you need is:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\n</code></pre>\n<p>Here's an example of a sitemap showing usernames\n<a href=\"https://i.stack.imgur.com/9ANUZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9ANUZ.png\" alt=\"sitemap\" /></a></p>\n" } ]
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 noreferrer\">robots.txt</a>, if you haven't. Another good reference is <a href=\"https://yoast.com/ultimate-guide-robots-txt/\" rel=\"nofollow noreferrer\">this one from Yoast</a>.</p>\n<p>The sample you posted:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php\n\nSitemap: https://knowingart.com/wp-sitemap.xml\n</code></pre>\n<p>...tells all user-agents (ie, all crawlers) that they are <em>not allowed</em> to crawl <em>anything</em> in your <code>wp-admin</code> directory <em>except</em> <code>/wp-admin/admin-ajax.php</code>, <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/#url\" rel=\"nofollow noreferrer\">which is required by WordPress for properly-functioning AJAX</a>.</p>\n<p>It's <em>not</em> telling robots to go to your <code>/wp-admin/</code> directory; it's telling them they're unwelcome there (except for the AJAX requirement).</p>\n<p>As for your question #4, I'm afraid I don't have an answer to that one.</p>\n" }, { "answer_id": 403766, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>the truth is that probably nothing should be blocked in <code>robots.txt</code> by core (this is IIRC was joost's position abot the matter) as wordpress is an open platform and front end content and styling might and is generated in all kinds of directories which might not make much sense to you and me. Wordpress is not in the buisness of preventing site owners from installing badly written plugins.</p>\n<p>Why do you have pages indexed by a search engine? Wordpress uses a kind of &quot;don't index&quot; headers for all admin pages so most likely you have some badly written code that prevents the header from bein sent. (this assumes that there is no bug in bing which is the SE which powers DDG).</p>\n<p>Maybe worth reminding that robots.txt is just an advisory file, it is up to the search engine to decide if and how to respect it. IIRC google will not respect it fully if there was a link to a page which supposed to be excluded by robots.txt</p>\n" }, { "answer_id": 414244, "author": "Zyraxx", "author_id": 230375, "author_profile": "https://wordpress.stackexchange.com/users/230375", "pm_score": 0, "selected": false, "text": "<p>There is a great reason why WordPress, despite being one of the most used frameworks, is also among the ones that has most errors and bad practices, just look at any log and count the hundreds of warnings it throws, and the reason is no other than poor development and lazy developers.</p>\n<p>Now to the point: you should always write your own robots.txt, you don't need google to index your wp-ajax, you probably aren't even using it, and in most cases it generates vulnerabilities, you should also disable access for guests or use a plugin to hide it or simply disable it completely, WP will work in 90% of cases and you will not expose your user list to the world. Also be careful with the autogenerated sitemap as it may display usernames making bruteforcing halfway easier</p>\n<p>All you need is:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\n</code></pre>\n<p>Here's an example of a sitemap showing usernames\n<a href=\"https://i.stack.imgur.com/9ANUZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9ANUZ.png\" alt=\"sitemap\" /></a></p>\n" } ]
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 noreferrer\">robots.txt</a>, if you haven't. Another good reference is <a href=\"https://yoast.com/ultimate-guide-robots-txt/\" rel=\"nofollow noreferrer\">this one from Yoast</a>.</p>\n<p>The sample you posted:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php\n\nSitemap: https://knowingart.com/wp-sitemap.xml\n</code></pre>\n<p>...tells all user-agents (ie, all crawlers) that they are <em>not allowed</em> to crawl <em>anything</em> in your <code>wp-admin</code> directory <em>except</em> <code>/wp-admin/admin-ajax.php</code>, <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/#url\" rel=\"nofollow noreferrer\">which is required by WordPress for properly-functioning AJAX</a>.</p>\n<p>It's <em>not</em> telling robots to go to your <code>/wp-admin/</code> directory; it's telling them they're unwelcome there (except for the AJAX requirement).</p>\n<p>As for your question #4, I'm afraid I don't have an answer to that one.</p>\n" }, { "answer_id": 403766, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>the truth is that probably nothing should be blocked in <code>robots.txt</code> by core (this is IIRC was joost's position abot the matter) as wordpress is an open platform and front end content and styling might and is generated in all kinds of directories which might not make much sense to you and me. Wordpress is not in the buisness of preventing site owners from installing badly written plugins.</p>\n<p>Why do you have pages indexed by a search engine? Wordpress uses a kind of &quot;don't index&quot; headers for all admin pages so most likely you have some badly written code that prevents the header from bein sent. (this assumes that there is no bug in bing which is the SE which powers DDG).</p>\n<p>Maybe worth reminding that robots.txt is just an advisory file, it is up to the search engine to decide if and how to respect it. IIRC google will not respect it fully if there was a link to a page which supposed to be excluded by robots.txt</p>\n" }, { "answer_id": 414244, "author": "Zyraxx", "author_id": 230375, "author_profile": "https://wordpress.stackexchange.com/users/230375", "pm_score": 0, "selected": false, "text": "<p>There is a great reason why WordPress, despite being one of the most used frameworks, is also among the ones that has most errors and bad practices, just look at any log and count the hundreds of warnings it throws, and the reason is no other than poor development and lazy developers.</p>\n<p>Now to the point: you should always write your own robots.txt, you don't need google to index your wp-ajax, you probably aren't even using it, and in most cases it generates vulnerabilities, you should also disable access for guests or use a plugin to hide it or simply disable it completely, WP will work in 90% of cases and you will not expose your user list to the world. Also be careful with the autogenerated sitemap as it may display usernames making bruteforcing halfway easier</p>\n<p>All you need is:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\n</code></pre>\n<p>Here's an example of a sitemap showing usernames\n<a href=\"https://i.stack.imgur.com/9ANUZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9ANUZ.png\" alt=\"sitemap\" /></a></p>\n" } ]
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 noreferrer\">robots.txt</a>, if you haven't. Another good reference is <a href=\"https://yoast.com/ultimate-guide-robots-txt/\" rel=\"nofollow noreferrer\">this one from Yoast</a>.</p>\n<p>The sample you posted:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php\n\nSitemap: https://knowingart.com/wp-sitemap.xml\n</code></pre>\n<p>...tells all user-agents (ie, all crawlers) that they are <em>not allowed</em> to crawl <em>anything</em> in your <code>wp-admin</code> directory <em>except</em> <code>/wp-admin/admin-ajax.php</code>, <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/#url\" rel=\"nofollow noreferrer\">which is required by WordPress for properly-functioning AJAX</a>.</p>\n<p>It's <em>not</em> telling robots to go to your <code>/wp-admin/</code> directory; it's telling them they're unwelcome there (except for the AJAX requirement).</p>\n<p>As for your question #4, I'm afraid I don't have an answer to that one.</p>\n" }, { "answer_id": 403766, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>the truth is that probably nothing should be blocked in <code>robots.txt</code> by core (this is IIRC was joost's position abot the matter) as wordpress is an open platform and front end content and styling might and is generated in all kinds of directories which might not make much sense to you and me. Wordpress is not in the buisness of preventing site owners from installing badly written plugins.</p>\n<p>Why do you have pages indexed by a search engine? Wordpress uses a kind of &quot;don't index&quot; headers for all admin pages so most likely you have some badly written code that prevents the header from bein sent. (this assumes that there is no bug in bing which is the SE which powers DDG).</p>\n<p>Maybe worth reminding that robots.txt is just an advisory file, it is up to the search engine to decide if and how to respect it. IIRC google will not respect it fully if there was a link to a page which supposed to be excluded by robots.txt</p>\n" }, { "answer_id": 414244, "author": "Zyraxx", "author_id": 230375, "author_profile": "https://wordpress.stackexchange.com/users/230375", "pm_score": 0, "selected": false, "text": "<p>There is a great reason why WordPress, despite being one of the most used frameworks, is also among the ones that has most errors and bad practices, just look at any log and count the hundreds of warnings it throws, and the reason is no other than poor development and lazy developers.</p>\n<p>Now to the point: you should always write your own robots.txt, you don't need google to index your wp-ajax, you probably aren't even using it, and in most cases it generates vulnerabilities, you should also disable access for guests or use a plugin to hide it or simply disable it completely, WP will work in 90% of cases and you will not expose your user list to the world. Also be careful with the autogenerated sitemap as it may display usernames making bruteforcing halfway easier</p>\n<p>All you need is:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\n</code></pre>\n<p>Here's an example of a sitemap showing usernames\n<a href=\"https://i.stack.imgur.com/9ANUZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9ANUZ.png\" alt=\"sitemap\" /></a></p>\n" } ]
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 noreferrer\">robots.txt</a>, if you haven't. Another good reference is <a href=\"https://yoast.com/ultimate-guide-robots-txt/\" rel=\"nofollow noreferrer\">this one from Yoast</a>.</p>\n<p>The sample you posted:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php\n\nSitemap: https://knowingart.com/wp-sitemap.xml\n</code></pre>\n<p>...tells all user-agents (ie, all crawlers) that they are <em>not allowed</em> to crawl <em>anything</em> in your <code>wp-admin</code> directory <em>except</em> <code>/wp-admin/admin-ajax.php</code>, <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/#url\" rel=\"nofollow noreferrer\">which is required by WordPress for properly-functioning AJAX</a>.</p>\n<p>It's <em>not</em> telling robots to go to your <code>/wp-admin/</code> directory; it's telling them they're unwelcome there (except for the AJAX requirement).</p>\n<p>As for your question #4, I'm afraid I don't have an answer to that one.</p>\n" }, { "answer_id": 403766, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>the truth is that probably nothing should be blocked in <code>robots.txt</code> by core (this is IIRC was joost's position abot the matter) as wordpress is an open platform and front end content and styling might and is generated in all kinds of directories which might not make much sense to you and me. Wordpress is not in the buisness of preventing site owners from installing badly written plugins.</p>\n<p>Why do you have pages indexed by a search engine? Wordpress uses a kind of &quot;don't index&quot; headers for all admin pages so most likely you have some badly written code that prevents the header from bein sent. (this assumes that there is no bug in bing which is the SE which powers DDG).</p>\n<p>Maybe worth reminding that robots.txt is just an advisory file, it is up to the search engine to decide if and how to respect it. IIRC google will not respect it fully if there was a link to a page which supposed to be excluded by robots.txt</p>\n" }, { "answer_id": 414244, "author": "Zyraxx", "author_id": 230375, "author_profile": "https://wordpress.stackexchange.com/users/230375", "pm_score": 0, "selected": false, "text": "<p>There is a great reason why WordPress, despite being one of the most used frameworks, is also among the ones that has most errors and bad practices, just look at any log and count the hundreds of warnings it throws, and the reason is no other than poor development and lazy developers.</p>\n<p>Now to the point: you should always write your own robots.txt, you don't need google to index your wp-ajax, you probably aren't even using it, and in most cases it generates vulnerabilities, you should also disable access for guests or use a plugin to hide it or simply disable it completely, WP will work in 90% of cases and you will not expose your user list to the world. Also be careful with the autogenerated sitemap as it may display usernames making bruteforcing halfway easier</p>\n<p>All you need is:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\n</code></pre>\n<p>Here's an example of a sitemap showing usernames\n<a href=\"https://i.stack.imgur.com/9ANUZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9ANUZ.png\" alt=\"sitemap\" /></a></p>\n" } ]
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 noreferrer\">robots.txt</a>, if you haven't. Another good reference is <a href=\"https://yoast.com/ultimate-guide-robots-txt/\" rel=\"nofollow noreferrer\">this one from Yoast</a>.</p>\n<p>The sample you posted:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php\n\nSitemap: https://knowingart.com/wp-sitemap.xml\n</code></pre>\n<p>...tells all user-agents (ie, all crawlers) that they are <em>not allowed</em> to crawl <em>anything</em> in your <code>wp-admin</code> directory <em>except</em> <code>/wp-admin/admin-ajax.php</code>, <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/#url\" rel=\"nofollow noreferrer\">which is required by WordPress for properly-functioning AJAX</a>.</p>\n<p>It's <em>not</em> telling robots to go to your <code>/wp-admin/</code> directory; it's telling them they're unwelcome there (except for the AJAX requirement).</p>\n<p>As for your question #4, I'm afraid I don't have an answer to that one.</p>\n" }, { "answer_id": 403766, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>the truth is that probably nothing should be blocked in <code>robots.txt</code> by core (this is IIRC was joost's position abot the matter) as wordpress is an open platform and front end content and styling might and is generated in all kinds of directories which might not make much sense to you and me. Wordpress is not in the buisness of preventing site owners from installing badly written plugins.</p>\n<p>Why do you have pages indexed by a search engine? Wordpress uses a kind of &quot;don't index&quot; headers for all admin pages so most likely you have some badly written code that prevents the header from bein sent. (this assumes that there is no bug in bing which is the SE which powers DDG).</p>\n<p>Maybe worth reminding that robots.txt is just an advisory file, it is up to the search engine to decide if and how to respect it. IIRC google will not respect it fully if there was a link to a page which supposed to be excluded by robots.txt</p>\n" }, { "answer_id": 414244, "author": "Zyraxx", "author_id": 230375, "author_profile": "https://wordpress.stackexchange.com/users/230375", "pm_score": 0, "selected": false, "text": "<p>There is a great reason why WordPress, despite being one of the most used frameworks, is also among the ones that has most errors and bad practices, just look at any log and count the hundreds of warnings it throws, and the reason is no other than poor development and lazy developers.</p>\n<p>Now to the point: you should always write your own robots.txt, you don't need google to index your wp-ajax, you probably aren't even using it, and in most cases it generates vulnerabilities, you should also disable access for guests or use a plugin to hide it or simply disable it completely, WP will work in 90% of cases and you will not expose your user list to the world. Also be careful with the autogenerated sitemap as it may display usernames making bruteforcing halfway easier</p>\n<p>All you need is:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\n</code></pre>\n<p>Here's an example of a sitemap showing usernames\n<a href=\"https://i.stack.imgur.com/9ANUZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9ANUZ.png\" alt=\"sitemap\" /></a></p>\n" } ]
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 noreferrer\">robots.txt</a>, if you haven't. Another good reference is <a href=\"https://yoast.com/ultimate-guide-robots-txt/\" rel=\"nofollow noreferrer\">this one from Yoast</a>.</p>\n<p>The sample you posted:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php\n\nSitemap: https://knowingart.com/wp-sitemap.xml\n</code></pre>\n<p>...tells all user-agents (ie, all crawlers) that they are <em>not allowed</em> to crawl <em>anything</em> in your <code>wp-admin</code> directory <em>except</em> <code>/wp-admin/admin-ajax.php</code>, <a href=\"https://developer.wordpress.org/plugins/javascript/ajax/#url\" rel=\"nofollow noreferrer\">which is required by WordPress for properly-functioning AJAX</a>.</p>\n<p>It's <em>not</em> telling robots to go to your <code>/wp-admin/</code> directory; it's telling them they're unwelcome there (except for the AJAX requirement).</p>\n<p>As for your question #4, I'm afraid I don't have an answer to that one.</p>\n" }, { "answer_id": 403766, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>the truth is that probably nothing should be blocked in <code>robots.txt</code> by core (this is IIRC was joost's position abot the matter) as wordpress is an open platform and front end content and styling might and is generated in all kinds of directories which might not make much sense to you and me. Wordpress is not in the buisness of preventing site owners from installing badly written plugins.</p>\n<p>Why do you have pages indexed by a search engine? Wordpress uses a kind of &quot;don't index&quot; headers for all admin pages so most likely you have some badly written code that prevents the header from bein sent. (this assumes that there is no bug in bing which is the SE which powers DDG).</p>\n<p>Maybe worth reminding that robots.txt is just an advisory file, it is up to the search engine to decide if and how to respect it. IIRC google will not respect it fully if there was a link to a page which supposed to be excluded by robots.txt</p>\n" }, { "answer_id": 414244, "author": "Zyraxx", "author_id": 230375, "author_profile": "https://wordpress.stackexchange.com/users/230375", "pm_score": 0, "selected": false, "text": "<p>There is a great reason why WordPress, despite being one of the most used frameworks, is also among the ones that has most errors and bad practices, just look at any log and count the hundreds of warnings it throws, and the reason is no other than poor development and lazy developers.</p>\n<p>Now to the point: you should always write your own robots.txt, you don't need google to index your wp-ajax, you probably aren't even using it, and in most cases it generates vulnerabilities, you should also disable access for guests or use a plugin to hide it or simply disable it completely, WP will work in 90% of cases and you will not expose your user list to the world. Also be careful with the autogenerated sitemap as it may display usernames making bruteforcing halfway easier</p>\n<p>All you need is:</p>\n<pre><code>User-agent: *\nDisallow: /wp-admin/\n</code></pre>\n<p>Here's an example of a sitemap showing usernames\n<a href=\"https://i.stack.imgur.com/9ANUZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9ANUZ.png\" alt=\"sitemap\" /></a></p>\n" } ]
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 <a href=\"https://developer.wordpress.org/reference/hooks/login_url/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/login_url/</a></p>\n" }, { "answer_id": 404016, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 2, "selected": false, "text": "<p>I would suggest you follow @DeltaG's advice in <a href=\"https://wordpress.stackexchange.com/a/404013/8259\">their answer</a>. However, to answer your specific question...</p>\n<blockquote>\n<pre><code>Redirect 301 /wp-login.php?action=register https://example.com/register/\n</code></pre>\n</blockquote>\n<p>This will never match because the <code>Redirect</code> (mod_alias) directive matches against the URL-path only, not the query string.</p>\n<p>To perform this redirect in <code>.htaccess</code> you would need to do something like the following using mod_rewrite at the top of the <code>.htaccess</code> file, <em>before</em> the existing WordPress code block (ie. before the <code># BEGIN WordPress</code> comment marker):</p>\n<pre><code>RewriteCond %{QUERY_STRING} ^action=register$\nRewriteRule ^wp-login\\.php$ https://example.com/register/ [R=301,QSD,L]\n</code></pre>\n<p>The <code>QSD</code> flag is necessary to remove the original query string from the request.</p>\n" }, { "answer_id": 404022, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 1, "selected": false, "text": "<p>Like @DeltaG said, filtering the <code>login_url</code> is a better option than using a .htaccess redirect. If you absolutely need to use .htaccess, follow @MrWhite answer.</p>\n<p>Here is an approach using default WordPress hooks..</p>\n<pre><code>function wpse404009_redirect_to_custom_registration_page() {\n\n global $pagenow;\n \n if ( $pagenow == 'wp-login.php' &amp;&amp; ! empty( $_REQUEST['action'] ) &amp;&amp; $_REQUEST['action'] === 'register' ) {\n //We are on the registration page, redirect now.\n wp_redirect( get_permalink(999), 301 ); ; //Change 999 to the ID of your registration page\n exit;\n }\n}\nadd_action( 'login_init', 'wpse404009_redirect_to_custom_registration_page' );\n</code></pre>\n<p>If you want to filter the <code>login_url</code>.</p>\n<pre><code>function wpse404009_custom_login_page( $login_url, $redirect, $force_reauth ) {\n \n //Get the custom login page URL.\n $login_url = get_permalink(999); //Change 999 to the ID of your login page\n \n if ( !empty($redirect)) {\n $login_url = add_query_arg( 'redirect_to', urlencode( $redirect ), $login_url );\n }\n return $login_url;\n}\nadd_filter( 'login_url', 'wpse404009_custom_login_page', 10, 3 );\n</code></pre>\n" } ]
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/get_the_content/#user-contributed-notes\" rel=\"nofollow noreferrer\"><code>get_the_content()</code></a> docs page:</p>\n<blockquote>\n<p>Note that get_the_content doesn’t return the same thing as what the_content displays. For that you need to do this:</p>\n<pre><code>$content = apply_filters( 'the_content', get_the_content() );\necho $content;\n</code></pre>\n</blockquote>\n" }, { "answer_id": 404077, "author": "AlabamaScholiast", "author_id": 220620, "author_profile": "https://wordpress.stackexchange.com/users/220620", "pm_score": 2, "selected": true, "text": "<p><em>tl;dr. There's probably a good way for you to do this in the specific case you describe, although WordPress does <strong>not</strong> allow for good, general filtering of the return value from <code>get_the_content()</code>.</em></p>\n<h3>You cannot do this directly, but ...</h3>\n<p>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 <code>get_the_content()</code> just as such. <code>the_content()</code> runs its output through a final filter before outputting it, but <code>get_the_content()</code> does not run its output through a final filter before returning it; sorry.</p>\n<p>You can review the source code for <a href=\"https://developer.wordpress.org/reference/functions/get_the_content/\" rel=\"nofollow noreferrer\"><code>get_the_content()</code> at the WordPress Code Reference site</a> to confirm; you are looking for instances of the function <code>apply_filters( ... )</code> which might be applied on the return-value variable <code>$output</code>. In the current version of WordPress, there aren't any, although there are instances of <code>apply_filters( ... )</code> being used to filter components of the output (for example the &quot;Read More...&quot; link element near the end of the function.</p>\n<h3>Still, <em>in your specific case</em>, you might be able to highjack the Password-Protected Post functionality to do what you want to do ...</h3>\n<p><strong>HOWEVER</strong>, there is a potential solution for this, <em><strong>if</strong></em> 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.</p>\n<p>Here's what you need to do:</p>\n<ol>\n<li><p><strong>Set up a filter on the hook <code>post_password_required</code></strong> which will return <code>true</code> if the user is <strong>not</strong> logged in, and <code>false</code> if the user <strong>is</strong> logged in. For example, you could put this code in <code>functions.php</code> or another appropriate location:</p>\n<pre><code>add_filter( 'post_password_required', function ( $required, $post ) {\n $required = ( ! is_user_logged_in() );\n return $required;\n}, 2, 10);\n</code></pre>\n<p>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 <code>$required</code>:</p>\n<pre><code>add_filter( 'post_password_required', function ( $required, $post ) {\n $required = ( $post-&gt;post_type == 'do_pobrania' &amp;&amp; has_term( 'zabezpieczony','rodzaj_plikow', $post ) &amp;&amp; ! is_user_logged_in() );\n return $required;\n}, 2, 10);\n</code></pre>\n</li>\n<li><p><strong>Set up a hook on the filter <code>the_password_form</code></strong> 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:</p>\n<pre><code>add_filter( 'the_password_form', function ( $output, $post ) {\n $login_url = wp_login_url( home_url( $_SERVER['REQUEST_URI'] ) );\n $output = sprintf('&lt;p&gt;Please &lt;a href=&quot;%s&quot;&gt;log in&lt;/a&gt; ...&lt;/p&gt;', esc_url( $login_url ) );\n return $output;\n }, 2, 10);\n</code></pre>\n<p>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.</p>\n</li>\n</ol>\n<p>Once these two filters are added, any template or function that uses <code>get_the_content()</code> 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, <em>in general</em>, 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.</p>\n<h3>Some Technical Notes on Why This Works</h3>\n<p>The relevant part of <code>get_the_content()</code> is on lines 313-316 of <a href=\"https://developer.wordpress.org/reference/files/wp-includes/post-template.php/\" rel=\"nofollow noreferrer\"><code>wp-includes/post-template.php</code></a>:</p>\n<pre><code>function get_the_content( $more_link_text = null, $strip_teaser = false, $post = null ) {\n\n/* [...] */\n\n // If post password required and it doesn't match the cookie.\n if ( post_password_required( $_post ) ) {\n return get_the_password_form( $_post );\n }\n \n/* [...] */\n\n}\n</code></pre>\n<p>So <strong>IF</strong> <a href=\"https://developer.wordpress.org/reference/functions/post_password_required/\" rel=\"nofollow noreferrer\"><code>post_password_required()</code></a> returns <code>true</code>, <strong>THEN</strong> <code>get_the_content()</code> will just return the value returned by <a href=\"https://developer.wordpress.org/reference/functions/get_the_password_form/\" rel=\"nofollow noreferrer\"><code>get_the_password_form()</code></a> in place of the post content. <em>These</em> functions can both be filtered using simple filter hooks:</p>\n<pre><code>function post_password_required( $post = null ) {\n \n /**\n * Filters whether a post requires the user to supply a password.\n *\n * @since 4.7.0\n *\n * @param bool $required Whether the user needs to supply a password. True if password has not been\n * provided or is incorrect, false if password has been supplied or is not required.\n * @param WP_Post $post Post object.\n */\n return apply_filters( 'post_password_required', $required, $post );\n}\n</code></pre>\n<pre><code>function get_the_password_form( $post = 0 ) {\n $post = get_post( $post );\n $label = 'pwbox-' . ( empty( $post-&gt;ID ) ? rand() : $post-&gt;ID );\n $output = '&lt;form action=&quot;' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '&quot; class=&quot;post-password-form&quot; method=&quot;post&quot;&gt;\n &lt;p&gt;' . __( 'This content is password protected. To view it please enter your password below:' ) . '&lt;/p&gt;\n &lt;p&gt;&lt;label for=&quot;' . $label . '&quot;&gt;' . __( 'Password:' ) . ' &lt;input name=&quot;post_password&quot; id=&quot;' . $label . '&quot; type=&quot;password&quot; size=&quot;20&quot; /&gt;&lt;/label&gt; &lt;input type=&quot;submit&quot; name=&quot;Submit&quot; value=&quot;' . esc_attr_x( 'Enter', 'post password form' ) . '&quot; /&gt;&lt;/p&gt;&lt;/form&gt;\n ';\n \n /**\n * Filters the HTML output for the protected post password form.\n *\n * If modifying the password field, please note that the core database schema\n * limits the password field to 20 characters regardless of the value of the\n * size attribute in the form input.\n *\n * @since 2.7.0\n * @since 5.8.0 Added the `$post` parameter.\n *\n * @param string $output The password form HTML output.\n * @param WP_Post $post Post object.\n */\n return apply_filters( 'the_password_form', $output, $post );\n}\n</code></pre>\n<p>You can take advantage of these filter hooks (1) to require WordPress to block the post content in <em>any</em> context that respects Password-Protected Post security; and (2) to deliver arbitrary HTML (in this case a simple login link) in <em>place</em> of the post content in any context that displays an input field to get the post password. Hope this helps!</p>\n" } ]
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 at the time of form submission to interact with the API, you can use <code>wp_redirect()</code> to redirect the user to the expected page.</p>\n<p>Also, you can add any necessary parameters to the redirect URL passed to <code>wp_redirect()</code>.</p>\n<p>Check out the <a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/\" rel=\"nofollow noreferrer\">WP code reference</a> on <code>wp_redirect()</code>.</p>\n" }, { "answer_id": 404695, "author": "anu", "author_id": 490, "author_profile": "https://wordpress.stackexchange.com/users/490", "pm_score": 2, "selected": true, "text": "<p>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 <code>ninja_forms_run_action_settings</code> where you can filter <code>$action_settings</code> which contains the redirect url.</p>\n<p>In my Action class:</p>\n<pre><code>class CustomProcessing extends NF_Abstracts_Action {\n\nprivate string $_redirect_url;\n\n public function __construct()\n {\n\n parent::__construct();\n $this-&gt;_nicename = 'Custom Process';\n\n\n add_filter( 'ninja_forms_run_action_settings', [ $this, 'changeRedirectURL' ], 10, 4 );\n }\n\n\n public function process( $action_id, $form_id, $data ) {\n\n // code to call API endpoint\n\n // set redirect url on response from API\n if ( 201 === $response[ 'response' ][ 'code' ] ) {\n $this-&gt;_redirect_url = $body_url;\n }\n\n return $data\n\n}\n\n\n public function changeRedirectURL( $action_settings, $form_id, $action_id, $form_settings )\n {\n\n if ( '&lt;redirect action name&gt;' === $action_settings[ &quot;label&quot; ] ) {\n $action_settings[ 'redirect_url' ] = $this-&gt;_redirect_url;\n }\n\n return $action_settings;\n }\n\n\n}\n</code></pre>\n" } ]
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 at the time of form submission to interact with the API, you can use <code>wp_redirect()</code> to redirect the user to the expected page.</p>\n<p>Also, you can add any necessary parameters to the redirect URL passed to <code>wp_redirect()</code>.</p>\n<p>Check out the <a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/\" rel=\"nofollow noreferrer\">WP code reference</a> on <code>wp_redirect()</code>.</p>\n" }, { "answer_id": 404695, "author": "anu", "author_id": 490, "author_profile": "https://wordpress.stackexchange.com/users/490", "pm_score": 2, "selected": true, "text": "<p>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 <code>ninja_forms_run_action_settings</code> where you can filter <code>$action_settings</code> which contains the redirect url.</p>\n<p>In my Action class:</p>\n<pre><code>class CustomProcessing extends NF_Abstracts_Action {\n\nprivate string $_redirect_url;\n\n public function __construct()\n {\n\n parent::__construct();\n $this-&gt;_nicename = 'Custom Process';\n\n\n add_filter( 'ninja_forms_run_action_settings', [ $this, 'changeRedirectURL' ], 10, 4 );\n }\n\n\n public function process( $action_id, $form_id, $data ) {\n\n // code to call API endpoint\n\n // set redirect url on response from API\n if ( 201 === $response[ 'response' ][ 'code' ] ) {\n $this-&gt;_redirect_url = $body_url;\n }\n\n return $data\n\n}\n\n\n public function changeRedirectURL( $action_settings, $form_id, $action_id, $form_settings )\n {\n\n if ( '&lt;redirect action name&gt;' === $action_settings[ &quot;label&quot; ] ) {\n $action_settings[ 'redirect_url' ] = $this-&gt;_redirect_url;\n }\n\n return $action_settings;\n }\n\n\n}\n</code></pre>\n" } ]
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 is just in WP_Query</p>\n</blockquote>\n<p>That is normal.</p>\n<ul>\n<li><p><code>WP_Query::$query_vars</code> is an array of query vars merged with the default ones for <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a>.</p>\n<p>So if you do <code>$query = new WP_Query( array( 'post_status' =&gt; 'publish' ) )</code> (or <code>$query = new WP_Query( 'post_status=publish' )</code>) and then later do <code>$query-&gt;set( 'tax_query', array( ... ) )</code>, then <code>$query-&gt;query_vars</code> would contain both <code>post_status</code> and <code>tax_query</code>, as well as other vars like <code>posts_per_page</code>, <code>post_type</code>, etc.</p>\n</li>\n<li><p><code>WP_Query::$tax_query</code> is an instance of the <a href=\"https://developer.wordpress.org/reference/classes/wp_tax_query/\" rel=\"nofollow noreferrer\"><code>WP_Tax_Query</code> class</a> and is used by <code>WP_Query</code> for generating the SQL's <code>JOIN</code> and <code>WHERE</code> clauses for the taxonomy query (<code>tax_query</code>) in the <code>$query_vars</code> array.</p>\n</li>\n</ul>\n" }, { "answer_id": 404418, "author": "steakoverflow", "author_id": 32588, "author_profile": "https://wordpress.stackexchange.com/users/32588", "pm_score": 0, "selected": false, "text": "<p>@Sally CJ, thanks for the clearup. However in the end I removed product_cat query variable using <code>$query-&gt;set('product_cat', null);</code></p>\n<p>It seems to have done the trick, but I'll have to properly test it.</p>\n" } ]
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 this link\n<code>https://mywebsite.com/wp-admin/user-edit.php?user_id=113</code></p>\n</blockquote>\n<p>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 <strong>logged-in</strong>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_action( 'admin_init', function () {\n if ( wp_doing_ajax() || ! is_user_logged_in() ) {\n return;\n }\n\n $roles = (array) wp_get_current_user()-&gt;roles;\n if ( ! in_array( 'administrator', $roles ) ) { // allows only the Administrator role\n wp_die( 'Sorry, you are not allowed to access this page.' );\n // or you can redirect the user to somewhere, if you want to\n }\n} );\n</code></pre>\n<p>But then, you might want to change the login and registration <em>redirect URL</em> so that it doesn't send the user to an admin page upon successful login/registration — see the documentation for <a href=\"https://developer.wordpress.org/reference/hooks/login_redirect/\" rel=\"nofollow noreferrer\"><code>login_redirect</code></a> and <a href=\"https://developer.wordpress.org/reference/hooks/registration_redirect/\" rel=\"nofollow noreferrer\"><code>registration_redirect</code></a>.</p>\n<blockquote>\n<p>Problem with that is that they can then create an API key (through\napplication passwords plugin which is accessible from that page).</p>\n</blockquote>\n<p>I can't help you with that <em>plugin</em>, 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 <a href=\"https://make.wordpress.org/core/2020/11/05/application-passwords-integration-guide/\" rel=\"nofollow noreferrer\">core feature in WordPress since v5.6.0</a>. And there's actually a hook named <a href=\"https://developer.wordpress.org/reference/hooks/wp_is_application_passwords_available_for_user/\" rel=\"nofollow noreferrer\"><code>wp_is_application_passwords_available_for_user</code></a> that you could use to disable the feature for certain users.</p>\n<blockquote>\n<p>This is undesirable as I dont want the users to have API keys where\nthey can fetch/post data to server.</p>\n</blockquote>\n<p>If so, and since you said in your comment, &quot;<em>The rest api is restricted for authenticated users</em>&quot;, then how about using the <a href=\"https://developer.wordpress.org/reference/hooks/rest_authentication_errors/\" rel=\"nofollow noreferrer\"><code>rest_authentication_errors</code> hook</a> to ensure only Administrators allowed to access the REST API?</p>\n<p>Working example:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'rest_authentication_errors', function ( $errors ) {\n if ( ! is_wp_error( $errors ) ) { // do nothing if there's already an error\n if ( $can_access = is_user_logged_in() ) {\n $roles = (array) wp_get_current_user()-&gt;roles;\n $can_access = in_array( 'administrator', $roles ); // allows only the Administrator role\n }\n\n if ( ! $can_access ) {\n return new WP_Error( 'user_not_allowed',\n 'Sorry, you are not allowed to access the REST API.',\n array( 'status' =&gt; rest_authorization_required_code() )\n );\n }\n }\n\n return $errors;\n} );\n</code></pre>\n" }, { "answer_id": 411230, "author": "serhumanos", "author_id": 206080, "author_profile": "https://wordpress.stackexchange.com/users/206080", "pm_score": -1, "selected": false, "text": "<p>Add this code to your theme’s <code>functions.php</code> file or in a site-specific plugin:</p>\n<pre><code>function restrict_access_admin_panel(){\n    global $current_user;\n    get_currentuserinfo();\n \n    if ($current_user-&gt;user_level &lt; 4) {\n        wp_redirect( get_bloginfo('url') );\n        exit;\n    }\n}\nadd_action('admin_init', 'restrict_access_admin_panel', 1);\n</code></pre>\n<p>source: <a href=\"https://www.isitwp.com/restrict-wp-admin-access-to-subscribers/\" rel=\"nofollow noreferrer\">https://www.isitwp.com/restrict-wp-admin-access-to-subscribers/</a></p>\n" } ]
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 subdirectory in your htaccess lines. Check out below:</p>\n<pre><code>&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\nRewriteBase /oldsite/\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /oldsite/index.php [L]\n&lt;/IfModule&gt;\n</code></pre>\n" }, { "answer_id": 404730, "author": "Dan", "author_id": 220425, "author_profile": "https://wordpress.stackexchange.com/users/220425", "pm_score": 1, "selected": false, "text": "<p>OK fixed it!</p>\n<p>I had some errant lines in the .htaccess file:</p>\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n# WP REWRITE LOOP END\n</code></pre>\n<p>This was taking precedence over the <code>&lt;IfModule mod_rewrite.c&gt;</code> block - and explains why it was redirecting to the parent directory.</p>\n<p>(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!)</p>\n" } ]
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>\n<pre><code>$popular_topics = get_field('popular_topics');\n\nif ( $popular_topics ) : \n\n foreach ( $popular_topics as $topic ) : \n\n $id = $topic-&gt;term_id;\n $meta = get_option('wpseo_taxonomy_meta');\n\n if ( $id &amp;&amp; ( $meta &amp;&amp; !empty($meta) ) ) : \n\n $meta_desc = $meta['category'][$id]['wpseo_desc'];\n\n if ( $meta_desc ) : ?&gt;\n\n &lt;p class=&quot;my-paragraph&quot;&gt;\n &lt;?php echo esc_html( $meta_desc ); ?&gt;\n &lt;/p&gt;\n\n &lt;?php\n\n endif;\n\n endif;\n\n endforeach;\n\nendif;\n</code></pre>\n" }, { "answer_id": 404781, "author": "katiedev", "author_id": 201500, "author_profile": "https://wordpress.stackexchange.com/users/201500", "pm_score": 1, "selected": true, "text": "<p>Wrap in a <code>!empty</code> statement</p>\n<pre><code>if(!empty( $meta['category'][$id]['wpseo_desc'] )) {\n echo $meta['category'][$id]['wpseo_desc'];\n}\nelse {\n echo &quot;Meta not present&quot;;\n}\n</code></pre>\n" } ]
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>\n<pre><code>$popular_topics = get_field('popular_topics');\n\nif ( $popular_topics ) : \n\n foreach ( $popular_topics as $topic ) : \n\n $id = $topic-&gt;term_id;\n $meta = get_option('wpseo_taxonomy_meta');\n\n if ( $id &amp;&amp; ( $meta &amp;&amp; !empty($meta) ) ) : \n\n $meta_desc = $meta['category'][$id]['wpseo_desc'];\n\n if ( $meta_desc ) : ?&gt;\n\n &lt;p class=&quot;my-paragraph&quot;&gt;\n &lt;?php echo esc_html( $meta_desc ); ?&gt;\n &lt;/p&gt;\n\n &lt;?php\n\n endif;\n\n endif;\n\n endforeach;\n\nendif;\n</code></pre>\n" }, { "answer_id": 404781, "author": "katiedev", "author_id": 201500, "author_profile": "https://wordpress.stackexchange.com/users/201500", "pm_score": 1, "selected": true, "text": "<p>Wrap in a <code>!empty</code> statement</p>\n<pre><code>if(!empty( $meta['category'][$id]['wpseo_desc'] )) {\n echo $meta['category'][$id]['wpseo_desc'];\n}\nelse {\n echo &quot;Meta not present&quot;;\n}\n</code></pre>\n" } ]
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 way. So, you could simply use:</p>\n<p><code>return get_option('admins_settings')['option_name'];</code></p>\n<p>which will return boolean <code>false</code> if the option doesn't exist or it will return the option value if it does exist.</p>\n" }, { "answer_id": 404954, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<blockquote>\n<p>I'm hitting the table 2 times (if the field exists) to get its value.</p>\n</blockquote>\n<p>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.</p>\n<p>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.</p>\n<blockquote>\n<p>But this works with the simple values:</p>\n<p>But not with array values:</p>\n</blockquote>\n<p>They are all simple values, and they are <em>always</em> 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 <code>serialize</code>, then deserialize it when you fetch it. This has security consequences.</p>\n<p>There is no such thing as &quot;sub-options&quot;, &quot;nested options&quot;, or &quot;child options&quot;. There is just options. <code>admins_settings</code> 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.</p>\n<p>Instead, you have 2 options</p>\n<ol>\n<li>Store separate values as separate values, ideally with a prefix</li>\n<li>Treat you array as an array and not a weird sub-option ( because there's no such thing as sub-options )</li>\n</ol>\n<p>So you would check it the same way you would check an array has a value:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$data = [];\nif ( isset( $data['test'] ) ) {\n return $data;\n} else {\n return false;\n}\n</code></pre>\n<p>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.</p>\n" } ]
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 contain <code>wp-content</code> (they're both children of your site's root directory).</p>\n<p>Instead of <code>'wp-content/uploads/cams/'</code>, I'd recommend <code>ABSPATH . 'wp-content/uploads/cams/'</code> which should work wherever you might be in the WordPress environment.</p>\n" }, { "answer_id": 405070, "author": "Phipsen", "author_id": 150852, "author_profile": "https://wordpress.stackexchange.com/users/150852", "pm_score": 1, "selected": true, "text": "<p>ABSPATH helps to display the page in the backend in editmode. But for the frontend, the path for the <code>&lt;img../&gt;</code> tag needs to be modified. <code>cutprefix()</code> function (taken from <a href=\"https://stackoverflow.com/questions/4517067/remove-a-string-from-the-beginning-of-a-string\">here</a>) does the job.</p>\n<p>This is the working solution for the front- and backend:</p>\n<pre><code>function getlatestfile() {\n\n $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator( ABSPATH . 'wp-content/uploads/cams' ));\n foreach ($iterator as $file) {\n if ($file-&gt;isDir()) continue;\n $path = $file-&gt;getPathname();\n }\n $path = cutprefix($path, '/home/username/web/mysite.url/public_html/');\n return(&quot;&lt;img src='https://mysite.url/&quot; . $path . &quot;' /&gt;&quot;);\n}\n\n\nfunction cutprefix($str, $prefix){\n if (substr($str, 0, strlen($prefix)) == $prefix) {\n $str = substr($str, strlen($prefix));\n } \n return $str;\n}\n</code></pre>\n<p>Thanks to <a href=\"https://wordpress.stackexchange.com/users/16121/pat-j\">Pat J</a> for leading me in the right direction.</p>\n" } ]
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 the wrong user compared to what is in your table. Assuming this is running on the frontend, and you want to check the current user, it would be better to use <code>get_current_user_id()</code> and parse that to your query.</p>\n<p>I would also suggest that you sanitise all your queries before putting them through get_results. See here <a href=\"https://codex.wordpress.org/Data_Validation#Database\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Data_Validation#Database</a></p>\n" }, { "answer_id": 405426, "author": "bosco", "author_id": 25324, "author_profile": "https://wordpress.stackexchange.com/users/25324", "pm_score": 2, "selected": true, "text": "<p>The evolution of this question makes it difficult to succinctly answer, but in brief summary:</p>\n<ul>\n<li>Using <a href=\"https://developer.wordpress.org/reference/classes/wpdb/prepare/\" rel=\"nofollow noreferrer\"><code>$wpdb-&gt;prepare()</code></a> to construct arbitrary SQL queries to execute against the database helps to mitigate <a href=\"https://xkcd.com/327/\" rel=\"nofollow noreferrer\">injection vulnerabilities</a> 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.</li>\n<li>If this character data is input by end-users, you should also consider <a href=\"https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/\" rel=\"nofollow noreferrer\">sanitizing the inputs prior to inserting them into the database, and possibly escaping the values prior to displaying them on the front-end</a> to further mitigate the risk of injection vulnerability and to prevent end users from displaying arbitrary HTML/JavaScript when their character data is displayed.</li>\n<li>Queries executed via <a href=\"https://developer.wordpress.org/reference/classes/wpdb/get_results/\" rel=\"nofollow noreferrer\"><code>$wpdb-&gt;get_results()</code></a> 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.</li>\n<li>When printing a non-primative data structure such as an object, PHP won't automatically serialize the object into a string for display. <code>print_r()</code> is capable of printing most common data structures, but <code>var_dump()</code> is a invaluable development aide when you're not sure of the type of the value.</li>\n</ul>\n<p>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 <code>foreach</code> loop to place the relevant values from each item into a cell:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\nglobal $wpdb;\n$uid = get_current_user_id();\n\n$sql = $wpdb-&gt;prepare( &quot;SELECT * FROM `sr3_characters` WHERE `wp_id` = %s&quot;, array( $uid ) );\n$results = $wpdb-&gt;get_results( $sql );\n?&gt;\n&lt;html&gt;\n&lt;body&gt;\n &lt;table border=&quot;1&quot;&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th scope=&quot;col&quot;&gt;Name&lt;/th&gt;\n &lt;th scope=&quot;col&quot;&gt;Race&lt;/th&gt;\n &lt;th scope=&quot;col&quot;&gt;Gender&lt;/th&gt;\n &lt;th scope=&quot;col&quot;&gt;Age&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;?php foreach( $results as $row ) { ?&gt;\n &lt;tr&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;?php echo esc_html( $row-&gt;char_name ); ?&gt;&lt;/th&gt;\n &lt;td&gt;&lt;?php echo esc_html( $row-&gt;char_race ); ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo $row-&gt;char_gender; ?&gt;&lt;/td&gt;\n &lt;td&gt;&lt;?php echo $row-&gt;char_age; ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php } ?&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" } ]
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> global $wpdb;\n $rows = $wpdb-&gt;get_results(&quot;SELECT * FROM &quot; . $wpdb-&gt;prefix . &quot;posts&quot;);\n</code></pre>\n<p>However, have a look at this:</p>\n<p><a href=\"https://wordpress.stackexchange.com/questions/217765/do-i-need-to-prepare-query-before-get-results-get-row-and-get-var#:%7E:text=You%20can%20sanitize%20before%20passing,doing%20the%20sanitization%20for%20you\">https://wordpress.stackexchange.com/questions/217765/do-i-need-to-prepare-query-before-get-results-get-row-and-get-var#:~:text=You%20can%20sanitize%20before%20passing,doing%20the%20sanitization%20for%20you</a>.</p>\n" }, { "answer_id": 405211, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<blockquote>\n<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>\n</blockquote>\n<p>Yes, but you should be using <code>get_terms</code>/<code>WP_Term_Query</code>/<code>wp_get_object_terms</code>/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.</p>\n<p>If you're going to perform an SQL query though, don't try to escape it, use <code>prepare</code> to insert variables into the query ( never do it directly! ):</p>\n<pre class=\"lang-php prettyprint-override\"><code>$safe_sql = $wpdb-&gt;prepare(\n &quot;SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s&quot;,\n [ 'foo', 1337, '%bar' ]\n);\n</code></pre>\n<p><strong>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.</strong></p>\n" } ]
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> global $wpdb;\n $rows = $wpdb-&gt;get_results(&quot;SELECT * FROM &quot; . $wpdb-&gt;prefix . &quot;posts&quot;);\n</code></pre>\n<p>However, have a look at this:</p>\n<p><a href=\"https://wordpress.stackexchange.com/questions/217765/do-i-need-to-prepare-query-before-get-results-get-row-and-get-var#:%7E:text=You%20can%20sanitize%20before%20passing,doing%20the%20sanitization%20for%20you\">https://wordpress.stackexchange.com/questions/217765/do-i-need-to-prepare-query-before-get-results-get-row-and-get-var#:~:text=You%20can%20sanitize%20before%20passing,doing%20the%20sanitization%20for%20you</a>.</p>\n" }, { "answer_id": 405211, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<blockquote>\n<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>\n</blockquote>\n<p>Yes, but you should be using <code>get_terms</code>/<code>WP_Term_Query</code>/<code>wp_get_object_terms</code>/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.</p>\n<p>If you're going to perform an SQL query though, don't try to escape it, use <code>prepare</code> to insert variables into the query ( never do it directly! ):</p>\n<pre class=\"lang-php prettyprint-override\"><code>$safe_sql = $wpdb-&gt;prepare(\n &quot;SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s&quot;,\n [ 'foo', 1337, '%bar' ]\n);\n</code></pre>\n<p><strong>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.</strong></p>\n" } ]
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('register_block_type_args', function ($settings, $name) {\n if ($name == 'demo/content-with-sidebar') {\n $settings['render_callback'] = 'demo_blocks_content_with_sidebar';\n }\n return $settings;\n}, null, 2);\n</code></pre>\n<p>replace your block name with <code>demo/content-with-sidebar</code> here demo is the block name space.</p>\n" }, { "answer_id": 414353, "author": "NextGenThemes", "author_id": 38602, "author_profile": "https://wordpress.stackexchange.com/users/38602", "pm_score": 1, "selected": false, "text": "<p>Just for completeness, based on @Ronak's answer, actual working code with WP coding standards and types.:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\nnamespace Nextgenthemes\\Stackshitflow;\n\nadd_filter(\n 'register_block_type_args',\n __NAMESPACE__ . '\\change_render_callback_for_query_pagination_numbers',\n 10,\n 2\n);\n\nfunction change_render_callback_for_query_pagination_numbers( array $settings, string $name ): array {\n if ( 'core/query-pagination-numbers' === $name ) {\n $settings['render_callback'] = __NAMESPACE__ . '\\render_query_pagination_numbers';\n }\n return $settings;\n}\n\nfunction render_query_pagination_numbers( array $attributes, string $content, \\WP_Block $block ): string {\n\n $content = '&lt;h1&gt;HELLO WORLD&lt;/h1&gt;';\n\n return $content;\n}\n</code></pre>\n" } ]
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.addEventListener('wpcf7submit', function(event) {\n setTimeout(function() {\n jQuery('form.wpcf7-form').removeClass('sent');\n jQuery('form.wpcf7-form').removeClass('failed');\n jQuery('form.wpcf7-form').addClass('init');\n }, 1000);\n\n}, false);\n</code></pre>\n" }, { "answer_id": 409109, "author": "Trần Hữu Hiền", "author_id": 212124, "author_profile": "https://wordpress.stackexchange.com/users/212124", "pm_score": 0, "selected": false, "text": "<p>I would like to use css than:</p>\n<pre><code>.wpcf7-form.sent .wpcf7-response-output {\n animation: hideresp 5s forwards; \n animation-iteration-count: 1;\n}\n\n@keyframes hideresp {\n 90% { opacity:1; }\n 100% { opacity:0; }\n}\n</code></pre>\n" } ]
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 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.</p>\n<p>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.</p>\n<p>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.</p>\n<p>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.</p>\n<p>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.</p>\n<hr>\nAlso, a warm welcome to WPSE @jimi-del don't forget to read up on our community guidelines.\n<p><a href=\"https://wordpress.stackexchange.com/help/how-to-ask\">How do I ask a good question?</a></p>\n<p><a href=\"https://wordpress.stackexchange.com/conduct\">Code of Conduct</a></p>\n<p><a href=\"https://wordpress.stackexchange.com/help/someone-answers\">What should I do when someone answers my question?</a></p>\n" }, { "answer_id": 405586, "author": "vishwa", "author_id": 203721, "author_profile": "https://wordpress.stackexchange.com/users/203721", "pm_score": 0, "selected": false, "text": "<p>You can try this code may be useful for you.</p>\n<pre><code>&lt;?php\nadd_action('wp_head', 'artical_count_post_visits');\nfunction artical_count_post_visits() {\n if (is_single()){\n global $post;\n $views = get_post_meta($post-&gt;ID , 'article_views', true);\n if((date('D') != 'Sun')){ //weekly\n if ($views == ''){\n update_post_meta( $post-&gt;ID, 'article_views', '1');\n } else {\n $views_no = intval($views);\n update_post_meta( $post-&gt;ID, 'article_views', ++$views_no);\n }\n }else{\n update_post_meta($post-&gt;ID, 'article_views', '');\n }\n }\n //popular article set into option meta\n if((date('D') != 'Sun')){\n $blog_query = new WP_Query( array( 'post_type' =&gt; 'post','posts_per_page' =&gt; -1 ));\n if($blog_query-&gt;have_posts()){\n $previous_views = &quot;&quot;;\n $max_views = &quot;&quot;;\n $article_max_id = &quot;&quot;;\n while ($blog_query-&gt;have_posts() ) {\n $blog_query-&gt;the_post(); \n $current_views= get_post_meta(get_the_ID(), &quot;article_views&quot;, true);\n if($current_views &gt; $previous_views){\n $previous_views = $current_views;\n $max_views = $current_views;\n $article_max_id = get_the_ID();\n }\n }\n if(!empty($article_max_id) &amp;&amp; !empty($max_views)){\n update_option( 'popular_article_save', array($article_max_id =&gt; $max_views) );\n }\n wp_reset_postdata();\n wp_reset_query();\n }\n \n }else{\n update_option( 'popular_article_save', array() );\n }\n}\n?&gt;\n\n&lt;?php\nget_header(); ?&gt;\n&lt;!-- archive list --&gt;\n&lt;div class=&quot;loop&quot;&gt;\n &lt;?php\n if ( have_posts() ) {\n $popular = get_option('popular_article_save');\n while ( have_posts() ) {\n the_post(); \n $views = get_post_meta(get_the_ID(), &quot;article_views&quot;, true);\n $class = &quot;&quot;;\n if(!empty($popular)){\n foreach($popular as $key_id=&gt;$max_views){\n if($key_id == get_the_ID() &amp;&amp; $max_views == $views &amp;&amp; !empty($max_views)){\n $class = &quot;popular_week&quot;;\n }\n }\n }\n ?&gt;\n &lt;div class=&quot;article &lt;?php echo $class; ?&gt;&quot; &gt;&lt;?php echo get_the_title();?&gt;&lt;/div&gt;\n &lt;?php\n } \n } \n ?&gt;\n&lt;/div&gt;\n&lt;?php get_footer();?&gt;\n</code></pre>\n" } ]
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/hooks/render_block_data/\" rel=\"nofollow noreferrer\"><code>render_block_data</code></a> filter to modify the query block's data before it's rendered.</p>\n<p>Since 6.1. the <a href=\"https://developer.wordpress.org/reference/hooks/query_loop_block_query_vars/\" rel=\"nofollow noreferrer\"><code>query_loop_block_query_vars</code></a> filter is available if one needs to modify the underlying <code>WP_Query</code> 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 <a href=\"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\" rel=\"nofollow noreferrer\">here</a>).</p>\n<p><strong>Original answer:</strong></p>\n<p>There's an open ticket for such a query args filter <a href=\"https://core.trac.wordpress.org/ticket/54850\" rel=\"nofollow noreferrer\">#54850</a>.</p>\n<p>In the meanwhile you can try this approach, replacing the render callback of the <code>core/post-template</code> block with a wrapper callback:</p>\n<pre><code>add_filter( 'block_type_metadata_settings', function( $settings ) {\n if ( $settings['parent'][0] !== 'core/query' ) {\n return $settings;\n }\n if ( $settings['render_callback'] !== 'render_block_core_post_template' ) {\n return $settings;\n }\n $settings['render_callback']= 'wpse_render_block_core_post_template';\n return $settings;\n}); \n</code></pre>\n<p>with the wrapper callback as:</p>\n<pre><code>function wpse_render_block_core_post_template($attributes, $content, $block ){\n $output = render_block_core_post_template( $attributes, $content, $block );\n return $output;\n}\n</code></pre>\n<p>Now we have a better way to target the <code>WP_Query</code> instance within that core template.</p>\n<p>Following are two such examples.</p>\n<h2>Example with <code>pre_get_posts</code></h2>\n<p>Here's an example how to override the <em>number of posts</em> with the help of the <code>pre_get_posts</code> hook:</p>\n<pre><code>function wpse_render_block_core_post_template( $attributes, $content, $block ) {\n $cb = fn( $q ) =&gt; $q-&gt;set( 'posts_per_page', 2 );\n \n add_action( 'pre_get_posts', $cb, 999 );\n $output = render_block_core_post_template( $attributes, $content, $block );\n remove_action( 'pre_get_posts', $cb, 999 );\n\n return $output;\n}\n</code></pre>\n<h2>Example with block context</h2>\n<p>We could also change existing query arguments within <a href=\"https://github.com/WordPress/WordPress/blob/7b880889bc92552cdab7b0dd700db82a3885d02d/wp-includes/blocks.php#L1097\" rel=\"nofollow noreferrer\"><code>build_query_vars_from_query_block()</code></a>, like <code>perPage</code>, with:</p>\n<pre><code>function wpse_render_block_core_post_template( $attributes, $content, $block ) {\n $block-&gt;context['query']['perPage'] = 2;\n return render_block_core_post_template($attributes, $content, $block );\n}\n</code></pre>\n<p>Then you can add further restrictions as needed to both approaches, from e.g. other block info, like <code>queryId</code>.</p>\n" }, { "answer_id": 405881, "author": "Mark Howells-Mead", "author_id": 83412, "author_profile": "https://wordpress.stackexchange.com/users/83412", "pm_score": 1, "selected": false, "text": "<p>A modified version of the suggestion from @birgire works. Note that this applies to the <code>core/post-template</code> block, not the <code>core/query block</code>.</p>\n<pre><code>add_filter('block_type_metadata_settings', function ($settings, $metadata) {\n if ($metadata['name'] !== 'core/post-template') {\n return $settings;\n }\n if ($settings['render_callback'] !== 'render_block_core_post_template') {\n return $settings;\n }\n $settings['render_callback'] = 'wpse_render_block_core_post_template';\n return $settings;\n}, 10, 2);\n\nfunction wpse_render_block_core_post_template($attributes, $content, $block)\n{\n $callback = fn ($query) =&gt; $query-&gt;set('posts_per_page', 2);\n\n add_action('pre_get_posts', $callback, 999);\n $output = render_block_core_post_template($attributes, $content, $block);\n remove_action('pre_get_posts', $callback, 999);\n\n return $output;\n}\n</code></pre>\n" } ]
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/upgrade.php\" rel=\"nofollow noreferrer\">https://www.website.test/wp-admin/network/upgrade.php</a></p>\n<p>Or the location to where <code>/wp-admin/</code> is installed plus <code>/network/upgrade.php</code>- as commenters have mentioned - I would reach out to WP Engine though - as you may have done something unexpected by adding those tables yourself.</p>\n<p>Now might be a good time to check your backup processes have been working correctly too :-)</p>\n" }, { "answer_id": 405987, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 2, "selected": false, "text": "<p>This was an error on an older version of WordPress, version 5.1 (<a href=\"https://core.trac.wordpress.org/ticket/46167\" rel=\"nofollow noreferrer\">Core Issue #46167</a>). Do you use the last stable version of WordPress?</p>\n<p>But try the following options to solve the problem.</p>\n<h1>Install again, Core or WP CLI</h1>\n<p>Copy all files from the core again in your installation, like via sFTP, especially all files in the directories <code>wp-inlcudes</code> and <code>wp-admin</code>. Run the installation again. Alternate if you have the possibility with the usage of <a href=\"https://wp-cli.org/\" rel=\"nofollow noreferrer\">WP CLI</a> <code>wp core update-db --network</code>.</p>\n<h1>Upgrade again</h1>\n<p>Go in your installation to the URL <code>wp-admin/network/upgrade.php</code> and perform the upgrade again.</p>\n<h1>Manual</h1>\n<p>Create the table or check your manual steps for this creation</p>\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE TABLE $wpdb-&gt;blogmeta (\n meta_id bigint(20) unsigned NOT NULL auto_increment,\n blog_id bigint(20) NOT NULL default '0',\n meta_key varchar(255) default NULL,\n meta_value longtext,\n PRIMARY KEY (meta_id),\n KEY meta_key (meta_key($max_index_length)),\n KEY blog_id (blog_id)\n) $charset_collate;\n</code></pre>\n<p>Now look at the table <code>wp_sitemeta</code>, field <code>site_meta_supported</code> and set the value to 1. Background is, WP looks via <code>is_site_meta_supported()</code> for this value to use the table.</p>\n" }, { "answer_id": 409872, "author": "hax2024", "author_id": 221171, "author_profile": "https://wordpress.stackexchange.com/users/221171", "pm_score": 1, "selected": false, "text": "<p>I noticed I was only getting the error for certain subsites. I had run the Network Upgrade successfully multiple times, but when I went directly to the subsite upgrade page like at <code>mysite.com/subsites/wp-admin/upgrade.php</code>\nand then ran the database upgrade that made the errors go away for me. (I had to do that for each subsite that was creating errors)</p>\n<p>I also still do not have a <code>wp_blogmeta</code> table, but no more errors.</p>\n<p>This was running wp version 5.9.3.</p>\n" } ]
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 jetengine plugin, which is out of scope here.</p>\n<p>You should be able to identify the key by querying the DB for one of the category terms. Assuming one of the category terms has and ID of 13 and the default WP table prefix is used, you can query the termmeta like this:</p>\n<p><code>SELECT * FROM wp_termmeta where term_id = 13;</code></p>\n<p>Once you've identified the meta key that stores the image, you can use WP's <a href=\"https://developer.wordpress.org/reference/functions/get_term_meta/\" rel=\"nofollow noreferrer\">get_term_meta()</a> function to get the meta value containing the image. Then it's just a matter of outputting the value in an image tag.</p>\n" }, { "answer_id": 405689, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 3, "selected": true, "text": "<p>Since you are using ACF, you can take advantage of the <code>get_field()</code> function ACF provides.</p>\n<p>You will need to pass the term object as the second parameter.</p>\n<pre><code>$image = get_field( 'field_key', $custom_term );\n</code></pre>\n" } ]
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 jetengine plugin, which is out of scope here.</p>\n<p>You should be able to identify the key by querying the DB for one of the category terms. Assuming one of the category terms has and ID of 13 and the default WP table prefix is used, you can query the termmeta like this:</p>\n<p><code>SELECT * FROM wp_termmeta where term_id = 13;</code></p>\n<p>Once you've identified the meta key that stores the image, you can use WP's <a href=\"https://developer.wordpress.org/reference/functions/get_term_meta/\" rel=\"nofollow noreferrer\">get_term_meta()</a> function to get the meta value containing the image. Then it's just a matter of outputting the value in an image tag.</p>\n" }, { "answer_id": 405689, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 3, "selected": true, "text": "<p>Since you are using ACF, you can take advantage of the <code>get_field()</code> function ACF provides.</p>\n<p>You will need to pass the term object as the second parameter.</p>\n<pre><code>$image = get_field( 'field_key', $custom_term );\n</code></pre>\n" } ]
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 jetengine plugin, which is out of scope here.</p>\n<p>You should be able to identify the key by querying the DB for one of the category terms. Assuming one of the category terms has and ID of 13 and the default WP table prefix is used, you can query the termmeta like this:</p>\n<p><code>SELECT * FROM wp_termmeta where term_id = 13;</code></p>\n<p>Once you've identified the meta key that stores the image, you can use WP's <a href=\"https://developer.wordpress.org/reference/functions/get_term_meta/\" rel=\"nofollow noreferrer\">get_term_meta()</a> function to get the meta value containing the image. Then it's just a matter of outputting the value in an image tag.</p>\n" }, { "answer_id": 405689, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 3, "selected": true, "text": "<p>Since you are using ACF, you can take advantage of the <code>get_field()</code> function ACF provides.</p>\n<p>You will need to pass the term object as the second parameter.</p>\n<pre><code>$image = get_field( 'field_key', $custom_term );\n</code></pre>\n" } ]
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 jetengine plugin, which is out of scope here.</p>\n<p>You should be able to identify the key by querying the DB for one of the category terms. Assuming one of the category terms has and ID of 13 and the default WP table prefix is used, you can query the termmeta like this:</p>\n<p><code>SELECT * FROM wp_termmeta where term_id = 13;</code></p>\n<p>Once you've identified the meta key that stores the image, you can use WP's <a href=\"https://developer.wordpress.org/reference/functions/get_term_meta/\" rel=\"nofollow noreferrer\">get_term_meta()</a> function to get the meta value containing the image. Then it's just a matter of outputting the value in an image tag.</p>\n" }, { "answer_id": 405689, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 3, "selected": true, "text": "<p>Since you are using ACF, you can take advantage of the <code>get_field()</code> function ACF provides.</p>\n<p>You will need to pass the term object as the second parameter.</p>\n<pre><code>$image = get_field( 'field_key', $custom_term );\n</code></pre>\n" } ]
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 jetengine plugin, which is out of scope here.</p>\n<p>You should be able to identify the key by querying the DB for one of the category terms. Assuming one of the category terms has and ID of 13 and the default WP table prefix is used, you can query the termmeta like this:</p>\n<p><code>SELECT * FROM wp_termmeta where term_id = 13;</code></p>\n<p>Once you've identified the meta key that stores the image, you can use WP's <a href=\"https://developer.wordpress.org/reference/functions/get_term_meta/\" rel=\"nofollow noreferrer\">get_term_meta()</a> function to get the meta value containing the image. Then it's just a matter of outputting the value in an image tag.</p>\n" }, { "answer_id": 405689, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 3, "selected": true, "text": "<p>Since you are using ACF, you can take advantage of the <code>get_field()</code> function ACF provides.</p>\n<p>You will need to pass the term object as the second parameter.</p>\n<pre><code>$image = get_field( 'field_key', $custom_term );\n</code></pre>\n" } ]
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 jetengine plugin, which is out of scope here.</p>\n<p>You should be able to identify the key by querying the DB for one of the category terms. Assuming one of the category terms has and ID of 13 and the default WP table prefix is used, you can query the termmeta like this:</p>\n<p><code>SELECT * FROM wp_termmeta where term_id = 13;</code></p>\n<p>Once you've identified the meta key that stores the image, you can use WP's <a href=\"https://developer.wordpress.org/reference/functions/get_term_meta/\" rel=\"nofollow noreferrer\">get_term_meta()</a> function to get the meta value containing the image. Then it's just a matter of outputting the value in an image tag.</p>\n" }, { "answer_id": 405689, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 3, "selected": true, "text": "<p>Since you are using ACF, you can take advantage of the <code>get_field()</code> function ACF provides.</p>\n<p>You will need to pass the term object as the second parameter.</p>\n<pre><code>$image = get_field( 'field_key', $custom_term );\n</code></pre>\n" } ]
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_session_tokens/\" rel=\"nofollow noreferrer\">WP_Session_Tokens</a> 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.</p>\n<pre><code>&lt;?php\n/*\nPlugin Name: Logout Users\nDescription: Forces all users to be logged out twice a day.\nAuthor: Tim Ross\nVersion: 1.0.0\nAuthor URI: https://timrosswebdevelopment.com\n*/\n\n/**\n * Create hook and schedule cron job on plugin activation.\n * Schedule recurring cron event.\n */\nfunction logout_users_plugin_activate() {\n $timestamp2pm = strtotime( '14:00:00' ); // 2:00 PM.\n $timestamp10pm = strtotime( '22:00:00' ); // 10:00 PM.\n // check to make sure it's not already scheduled.\n if ( ! wp_next_scheduled( 'logout_users_plugin_cron_hook' ) ) {\n wp_schedule_event( $timestamp2pm, 'daily', 'logout_users_plugin_cron_hook' );\n wp_schedule_event( $timestamp10pm, 'daily', 'logout_users_plugin_cron_hook' );\n // use wp_schedule_single_event function for non-recurring.\n }\n}\nregister_activation_hook( __FILE__, 'logout_users_plugin_activate' );\n\n\n/**\n * Unset cron event on plugin deactivation.\n */\nfunction logout_users_plugin_deactivate() {\n wp_clear_scheduled_hook( 'logout_users_plugin_cron_hook' ); // unschedule event.\n}\nregister_deactivation_hook( __FILE__, 'logout_users_plugin_deactivate' );\n\nfunction logout_all_users() {\n // Get an instance of WP_User_Meta_Session_Tokens\n $sessions_manager = WP_Session_Tokens::get_instance();\n // Remove all the session data for all users.\n $sessions_manager-&gt;drop_sessions();\n}\n\n// hook function logout_users_plugin_cron_hook() to the action logout_users_plugin_cron_hook.\nadd_action( 'logout_users_plugin_cron_hook', 'logout_all_users' );\n</code></pre>\n" }, { "answer_id": 405928, "author": "Mand", "author_id": 222333, "author_profile": "https://wordpress.stackexchange.com/users/222333", "pm_score": 0, "selected": false, "text": "<p>Managed to solve this issue myself by deleting the usermeta from the database directly by doing as follows:</p>\n<pre><code>$stmt = $dbh-&gt;prepare('DELETE FROM wp_usermeta WHERE meta_key=\\'session_tokens\\'');\n</code></pre>\n" } ]
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_session_tokens/\" rel=\"nofollow noreferrer\">WP_Session_Tokens</a> 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.</p>\n<pre><code>&lt;?php\n/*\nPlugin Name: Logout Users\nDescription: Forces all users to be logged out twice a day.\nAuthor: Tim Ross\nVersion: 1.0.0\nAuthor URI: https://timrosswebdevelopment.com\n*/\n\n/**\n * Create hook and schedule cron job on plugin activation.\n * Schedule recurring cron event.\n */\nfunction logout_users_plugin_activate() {\n $timestamp2pm = strtotime( '14:00:00' ); // 2:00 PM.\n $timestamp10pm = strtotime( '22:00:00' ); // 10:00 PM.\n // check to make sure it's not already scheduled.\n if ( ! wp_next_scheduled( 'logout_users_plugin_cron_hook' ) ) {\n wp_schedule_event( $timestamp2pm, 'daily', 'logout_users_plugin_cron_hook' );\n wp_schedule_event( $timestamp10pm, 'daily', 'logout_users_plugin_cron_hook' );\n // use wp_schedule_single_event function for non-recurring.\n }\n}\nregister_activation_hook( __FILE__, 'logout_users_plugin_activate' );\n\n\n/**\n * Unset cron event on plugin deactivation.\n */\nfunction logout_users_plugin_deactivate() {\n wp_clear_scheduled_hook( 'logout_users_plugin_cron_hook' ); // unschedule event.\n}\nregister_deactivation_hook( __FILE__, 'logout_users_plugin_deactivate' );\n\nfunction logout_all_users() {\n // Get an instance of WP_User_Meta_Session_Tokens\n $sessions_manager = WP_Session_Tokens::get_instance();\n // Remove all the session data for all users.\n $sessions_manager-&gt;drop_sessions();\n}\n\n// hook function logout_users_plugin_cron_hook() to the action logout_users_plugin_cron_hook.\nadd_action( 'logout_users_plugin_cron_hook', 'logout_all_users' );\n</code></pre>\n" }, { "answer_id": 405928, "author": "Mand", "author_id": 222333, "author_profile": "https://wordpress.stackexchange.com/users/222333", "pm_score": 0, "selected": false, "text": "<p>Managed to solve this issue myself by deleting the usermeta from the database directly by doing as follows:</p>\n<pre><code>$stmt = $dbh-&gt;prepare('DELETE FROM wp_usermeta WHERE meta_key=\\'session_tokens\\'');\n</code></pre>\n" } ]
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_session_tokens/\" rel=\"nofollow noreferrer\">WP_Session_Tokens</a> 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.</p>\n<pre><code>&lt;?php\n/*\nPlugin Name: Logout Users\nDescription: Forces all users to be logged out twice a day.\nAuthor: Tim Ross\nVersion: 1.0.0\nAuthor URI: https://timrosswebdevelopment.com\n*/\n\n/**\n * Create hook and schedule cron job on plugin activation.\n * Schedule recurring cron event.\n */\nfunction logout_users_plugin_activate() {\n $timestamp2pm = strtotime( '14:00:00' ); // 2:00 PM.\n $timestamp10pm = strtotime( '22:00:00' ); // 10:00 PM.\n // check to make sure it's not already scheduled.\n if ( ! wp_next_scheduled( 'logout_users_plugin_cron_hook' ) ) {\n wp_schedule_event( $timestamp2pm, 'daily', 'logout_users_plugin_cron_hook' );\n wp_schedule_event( $timestamp10pm, 'daily', 'logout_users_plugin_cron_hook' );\n // use wp_schedule_single_event function for non-recurring.\n }\n}\nregister_activation_hook( __FILE__, 'logout_users_plugin_activate' );\n\n\n/**\n * Unset cron event on plugin deactivation.\n */\nfunction logout_users_plugin_deactivate() {\n wp_clear_scheduled_hook( 'logout_users_plugin_cron_hook' ); // unschedule event.\n}\nregister_deactivation_hook( __FILE__, 'logout_users_plugin_deactivate' );\n\nfunction logout_all_users() {\n // Get an instance of WP_User_Meta_Session_Tokens\n $sessions_manager = WP_Session_Tokens::get_instance();\n // Remove all the session data for all users.\n $sessions_manager-&gt;drop_sessions();\n}\n\n// hook function logout_users_plugin_cron_hook() to the action logout_users_plugin_cron_hook.\nadd_action( 'logout_users_plugin_cron_hook', 'logout_all_users' );\n</code></pre>\n" }, { "answer_id": 405928, "author": "Mand", "author_id": 222333, "author_profile": "https://wordpress.stackexchange.com/users/222333", "pm_score": 0, "selected": false, "text": "<p>Managed to solve this issue myself by deleting the usermeta from the database directly by doing as follows:</p>\n<pre><code>$stmt = $dbh-&gt;prepare('DELETE FROM wp_usermeta WHERE meta_key=\\'session_tokens\\'');\n</code></pre>\n" } ]
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_session_tokens/\" rel=\"nofollow noreferrer\">WP_Session_Tokens</a> 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.</p>\n<pre><code>&lt;?php\n/*\nPlugin Name: Logout Users\nDescription: Forces all users to be logged out twice a day.\nAuthor: Tim Ross\nVersion: 1.0.0\nAuthor URI: https://timrosswebdevelopment.com\n*/\n\n/**\n * Create hook and schedule cron job on plugin activation.\n * Schedule recurring cron event.\n */\nfunction logout_users_plugin_activate() {\n $timestamp2pm = strtotime( '14:00:00' ); // 2:00 PM.\n $timestamp10pm = strtotime( '22:00:00' ); // 10:00 PM.\n // check to make sure it's not already scheduled.\n if ( ! wp_next_scheduled( 'logout_users_plugin_cron_hook' ) ) {\n wp_schedule_event( $timestamp2pm, 'daily', 'logout_users_plugin_cron_hook' );\n wp_schedule_event( $timestamp10pm, 'daily', 'logout_users_plugin_cron_hook' );\n // use wp_schedule_single_event function for non-recurring.\n }\n}\nregister_activation_hook( __FILE__, 'logout_users_plugin_activate' );\n\n\n/**\n * Unset cron event on plugin deactivation.\n */\nfunction logout_users_plugin_deactivate() {\n wp_clear_scheduled_hook( 'logout_users_plugin_cron_hook' ); // unschedule event.\n}\nregister_deactivation_hook( __FILE__, 'logout_users_plugin_deactivate' );\n\nfunction logout_all_users() {\n // Get an instance of WP_User_Meta_Session_Tokens\n $sessions_manager = WP_Session_Tokens::get_instance();\n // Remove all the session data for all users.\n $sessions_manager-&gt;drop_sessions();\n}\n\n// hook function logout_users_plugin_cron_hook() to the action logout_users_plugin_cron_hook.\nadd_action( 'logout_users_plugin_cron_hook', 'logout_all_users' );\n</code></pre>\n" }, { "answer_id": 405928, "author": "Mand", "author_id": 222333, "author_profile": "https://wordpress.stackexchange.com/users/222333", "pm_score": 0, "selected": false, "text": "<p>Managed to solve this issue myself by deleting the usermeta from the database directly by doing as follows:</p>\n<pre><code>$stmt = $dbh-&gt;prepare('DELETE FROM wp_usermeta WHERE meta_key=\\'session_tokens\\'');\n</code></pre>\n" } ]
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 appear\non hover by default. All you have to do is iterate the recent posts and add them one by one.</p>\n<pre><code>add_action('admin_menu', function () {\n $args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'orderby' =&gt; 'post_date',\n 'sort_column' =&gt; 'post_date',\n 'sort_order' =&gt; 'asc',\n 'posts_per_page' =&gt; 10,\n );\n $arr = get_posts($args);\n foreach ($arr as $item) {\n add_submenu_page(\n 'edit.php',\n $item-&gt;post_name,\n '• ' . $item-&gt;post_title,\n 'read',\n 'post.php?post=' . $item-&gt;ID . '&amp;action=edit',\n ''\n );\n }\n});\n</code></pre>\n<p><strong>Update:</strong>\nI wrote a <a href=\"https://wordpress.org/plugins/itg-admin-hover-menus/\" rel=\"nofollow noreferrer\">plugin</a> for this. It also shows pages and custom post types. Hope that helps.</p>\n" }, { "answer_id": 406115, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p>Yes!</p>\n<p>On the admin menu hook, grab all the post types using <code>get_post_types</code>, then for each type, do a query for posts of that type, and call <code>add_submenu_page</code> with their edit URLs to put them in the menu.</p>\n<p>Here's a more comprehensive alternative to IT Goldmans answer with the following additions:</p>\n<ul>\n<li>fixes a performance and caching issue that stopped it working with caching plugins and plugin filters</li>\n<li>works for all post types</li>\n<li>adds a separator and puts them at the end</li>\n<li>edit icons!</li>\n<li>handles posts with no title</li>\n<li>respects the posts_per_page setting and default ordering</li>\n<li>doesn't break custom edit links</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/17xfA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/17xfA.png\" alt=\"enter image description here\" /></a></p>\n<p>To use, copy paste to a new PHP file in the plugins folder:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n/**\n * Plugin Name: Basic admin post submenus\n * Plugin Author: Tom J Nowell\n */\n\n// https://wordpress.stackexchange.com/questions/406113/is-there-a-way-to-add-the-list-of-recent-posts-into-the-admin-sub-menu-on-hover\n\n\nadd_action(\n 'admin_menu',\n function () : void {\n $types = get_post_types( [\n 'public' =&gt; true,\n ] );\n\n foreach( $types as $type ) {\n $parent_url = add_query_arg(\n [\n 'post_type' =&gt; $type === 'post' ? null : $type\n ],\n 'edit.php'\n );\n\n $args = [\n 'post_type' =&gt; $type,\n 'post_status' =&gt; 'publish',\n 'suppress_filters' =&gt; false,\n ];\n $posts = get_posts( $args );\n if ( empty( $posts ) ) {\n continue;\n }\n\n add_submenu_page(\n $parent_url,\n 'wp-menu-separator',\n '',\n 'read',\n '',\n '',\n 11\n );\n\n foreach ( $posts as $post ) {\n $title = ! empty( $post-&gt;post_title ) ? $post-&gt;post_title : '&lt;em&gt;' . __( 'Untitled' ) . '&lt;/em&gt;'\n add_submenu_page(\n $parent_url,\n $post-&gt;post_name,\n $title . '&lt;span class=&quot;dashicons dashicons-edit&quot;&gt;&lt;/span&gt; ',\n 'read',\n get_edit_post_link( $post-&gt;ID ),\n '',\n 11\n );\n }\n }\n }\n);\n</code></pre>\n" } ]
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/\" rel=\"nofollow noreferrer\"><code>wp_authenticate_user</code> filter</a> and return an error.</p>\n<p>Something like:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'wp_authenticate_user', 'wpse_406123_stop_login', -1 );\n\nfunction wpse_406123_stop_login() {\n $message = new WP_Error( 'login_disabled', __( '&lt;strong&gt;ERROR&lt;/strong&gt;: You cannot login at this time' ) );\n return $message;\n}\n</code></pre>\n<p>You can then change your security keys -<a href=\"https://api.wordpress.org/secret-key/1.1/salt/\" rel=\"nofollow noreferrer\">the ones that look like this</a> to something different - that will invalidate all current logins.</p>\n" }, { "answer_id": 406127, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>Here's a way to halt the login by returning an error through the <code>wp_authenticate_user</code> filter:</p>\n<pre><code>add_filter( 'wp_authenticate_user', function() {\n return new WP_Error( 'authentication_failed', esc_html__( 'Login disabled.', 'wpse' ) );\n} );\n</code></pre>\n<p>so that you will get a notice about that after trying to login:</p>\n<p><a href=\"https://i.stack.imgur.com/ioWPZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ioWPZ.png\" alt=\"enter image description here\" /></a></p>\n<p>But it will be better if users don't have to login in the first place to get the message. We can add a message like:</p>\n<pre><code>add_filter( 'login_message', function( $message ) {\n return sprintf ( \n '&lt;p class=&quot;message&quot;&gt;%s&lt;/p&gt;', \n esc_html__( ' Login is disabled! ⛔', 'wpse' ) \n ) . $message;\n} );\n</code></pre>\n<p>That will show up as:</p>\n<p><a href=\"https://i.stack.imgur.com/2oLzg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2oLzg.png\" alt=\"enter image description here\" /></a></p>\n<p>... or maybe it's better to just hide the form in the first place with e.g.:</p>\n<pre><code>add_action( 'login_enqueue_scripts', function() {\n wp_add_inline_style( \n 'login', \n ' body.login #loginform, \n body.login #nav,\n body.login .language-switcher {\n display:none;\n }' \n );\n} );\n</code></pre>\n<p>in addition to the above steps.</p>\n<p>That will give us:</p>\n<p><a href=\"https://i.stack.imgur.com/p33aq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/p33aq.png\" alt=\"enter image description here\" /></a></p>\n<p>We note that to remove the sessions for the current user there's the <code>wp_destroy_all_sessions()</code> function if needed.</p>\n" }, { "answer_id": 406301, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 0, "selected": false, "text": "<p>Wow - lots of great solutions offered....silly me, I just remove the wp-login.php file from the server, and - if as Tom Nowell asks - any currently logged-in users need to be booted out, I change the salt keys in wp-config.php.</p>\n<p>If you want to be more polite, you could swap the wp-login.php file for one that has just a nice message instead of the login form.</p>\n<p>No coding necessary, although this is definitely the lazier solution!</p>\n" } ]
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.