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
371,267
<p>I want to check if a post has one of the following shortcodes, wpdocs-shortcode-1, wpdocs-shortcode-2, wpdocs-shortcode-3. If it found any of those shortcodes, then do enqueue scripts and styles.</p> <p>Basically this code works.</p> <pre><code> function wpdocs_shortcode_scripts() { global $post; if ( is_a( $post, 'WP_Post' ) &amp;&amp; has_shortcode( $post-&gt;post_content, 'wpdocs-shortcode') ) { wp_enqueue_script( 'wpdocs-script'); } } add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts'); </code></pre> <p>What I'd like to achieve is check for more than one shortcodes. I tried the following code by passing an array but it did not work.</p> <pre><code> function wpdocs_shortcode_scripts() { global $post; if ( is_a( $post, 'WP_Post' ) &amp;&amp; has_shortcode( $post-&gt;post_content, array('wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3') ) { wp_enqueue_script( 'wpdocs-script'); } } add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts'); </code></pre> <p>Any help would be greatly appreciated.</p> <p>Thank you so much!</p>
[ { "answer_id": 371269, "author": "Kevin", "author_id": 87522, "author_profile": "https://wordpress.stackexchange.com/users/87522", "pm_score": 1, "selected": false, "text": "<p>You can loop through the shortcuts and then put something into an array when you get a hit.</p>\n<p>If the array is not empty at the end, your script can be loaded.</p>\n<pre><code>&lt;?php\nfunction wpdocs_shortcode_scripts() {\n global $post;\n\n $shortcodes = [ 'wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3' ];\n\n $found = [];\n\n foreach ( $shortcodes as $shortcode ) :\n if ( is_a( $post, 'WP_Post' ) &amp;&amp; has_shortcode( $post-&gt;post_content, $shortcode ) ) {\n $found[] = $shortcode;\n }\n endforeach;\n\n if ( ! empty( $found ) ) {\n wp_enqueue_script( 'wpdocs-script' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts' );\n</code></pre>\n" }, { "answer_id": 371270, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 1, "selected": true, "text": "<p>So yes, as you say you can't pass an array to <code>has_shortcode</code>, which is confirmed in <a href=\"https://developer.wordpress.org/reference/functions/has_shortcode/\" rel=\"nofollow noreferrer\">the docs</a>, so you need to do the 'OR' operation manually, which would look something like this:</p>\n<pre><code>$shortCodesToTest = [ 'wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3'];\n\n$anyShortCode = false;\n\nforeach ($shortCodesToTest as $sc) {\n if (has_shortcode( $post-&gt;post_content, $sc) ) {\n $anyShortCode = true;\n }\n}\n</code></pre>\n<p>Now use the <code>$anyShortCode</code> variable as you like - it will be <code>True</code> if any of the shortcodes were found. For example:</p>\n<pre><code>if ( is_a( $post, 'WP_Post' ) &amp;&amp; $anyShortCode ) {\n wp_enqueue_script( 'wpdocs-script');\n}\n</code></pre>\n" } ]
2020/07/17
[ "https://wordpress.stackexchange.com/questions/371267", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/191791/" ]
I want to check if a post has one of the following shortcodes, wpdocs-shortcode-1, wpdocs-shortcode-2, wpdocs-shortcode-3. If it found any of those shortcodes, then do enqueue scripts and styles. Basically this code works. ``` function wpdocs_shortcode_scripts() { global $post; if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'wpdocs-shortcode') ) { wp_enqueue_script( 'wpdocs-script'); } } add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts'); ``` What I'd like to achieve is check for more than one shortcodes. I tried the following code by passing an array but it did not work. ``` function wpdocs_shortcode_scripts() { global $post; if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, array('wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3') ) { wp_enqueue_script( 'wpdocs-script'); } } add_action( 'wp_enqueue_scripts', 'wpdocs_shortcode_scripts'); ``` Any help would be greatly appreciated. Thank you so much!
So yes, as you say you can't pass an array to `has_shortcode`, which is confirmed in [the docs](https://developer.wordpress.org/reference/functions/has_shortcode/), so you need to do the 'OR' operation manually, which would look something like this: ``` $shortCodesToTest = [ 'wpdocs-shortcode-1', 'wpdocs-shortcode-2', 'wpdocs-shortcode-3']; $anyShortCode = false; foreach ($shortCodesToTest as $sc) { if (has_shortcode( $post->post_content, $sc) ) { $anyShortCode = true; } } ``` Now use the `$anyShortCode` variable as you like - it will be `True` if any of the shortcodes were found. For example: ``` if ( is_a( $post, 'WP_Post' ) && $anyShortCode ) { wp_enqueue_script( 'wpdocs-script'); } ```
371,290
<p>I have a custom script section in a theme I'm creating that is only echoing the verbatim text, rather than treating it as script &amp; I'm not sure what I'm doing wrong. I thought at first that it may be the sanitization callback that I was using but changing/removing it didn't have any effect.</p> <p>Here's my customizer code:</p> <pre><code> $wp_customize-&gt;add_setting( 'footer_code', array( 'default' =&gt; '', 'transport' =&gt; 'refresh', 'sanitize_callback' =&gt; '' ) ); $wp_customize-&gt;add_control( 'footer_code', array( 'label' =&gt; __( 'Custom Footer Scripts' ), 'description' =&gt; esc_html__( 'Paste in any scripts that need to be called after the body content here.' ), 'section' =&gt; 'header_footer_code', 'priority' =&gt; 10, 'type' =&gt; 'textarea', 'input_attrs' =&gt; array( // Optional. 'class' =&gt; 'footer_scripts', ), ) ); </code></pre> <p>And here's how I'm calling it:</p> <pre><code>&lt;?php echo get_theme_mod( 'footer_code'); ?&gt; </code></pre> <p>Update:</p> <p>Here's the sample code that I used as a test, which prints exactly as you see it in my theme, meaning that it's treated as content:; would be in CSS.</p> <pre><code>&lt;script&gt; jQuery('.woocommerce-MyAccount-navigation ul').addClass('chev'); &lt;/script&gt; </code></pre>
[ { "answer_id": 371296, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 2, "selected": false, "text": "<p>This is probably not the best answer, someone may know a way for this input to be properly handled given that you want to store code in it, but this will probably do what you're intending:</p>\n<pre><code>&lt;?php echo html_entity_decode(get_theme_mod( 'footer_code')); ?&gt;\n</code></pre>\n<p>Note this is probably somewhat of a security risk, and this behaviour of Wordpress escaping the HTML characters prevents exactly what you're trying to do for security reasons. You may want to see if there are other ways to do what you're trying to do here that don't allow that to happen.</p>\n" }, { "answer_id": 371325, "author": "Jeff W", "author_id": 76434, "author_profile": "https://wordpress.stackexchange.com/users/76434", "pm_score": 1, "selected": false, "text": "<p>I was able to resolve this after I slept on it &amp; I looked at the part of the customizer code that I hadn't included, which is the section portion of all things. All it needed was an esc_attr on it as shown below.\nInitial version:</p>\n<pre><code> // Header Footer Code Section\n $wp_customize-&gt;add_section( 'header_footer_code', array(\n 'title' =&gt; 'Header &amp; Footer Scripts',\n 'description' =&gt; 'This section is for any head/footer scripts that need to be run on the entire site.',\n 'priority' =&gt; 180,\n ) );\n</code></pre>\n<p>Revised version:</p>\n<pre><code> $wp_customize-&gt;add_section( 'header_footer_code', array(\n esc_attr__( 'Header &amp; Footer Scripts', 'yonder' ),\n 'description' =&gt; 'This section is for any head/footer scripts that need to be run on the entire site.',\n 'priority' =&gt; 180,\n ) );\n</code></pre>\n<p>Thanks again for your input, guys!</p>\n" } ]
2020/07/17
[ "https://wordpress.stackexchange.com/questions/371290", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76434/" ]
I have a custom script section in a theme I'm creating that is only echoing the verbatim text, rather than treating it as script & I'm not sure what I'm doing wrong. I thought at first that it may be the sanitization callback that I was using but changing/removing it didn't have any effect. Here's my customizer code: ``` $wp_customize->add_setting( 'footer_code', array( 'default' => '', 'transport' => 'refresh', 'sanitize_callback' => '' ) ); $wp_customize->add_control( 'footer_code', array( 'label' => __( 'Custom Footer Scripts' ), 'description' => esc_html__( 'Paste in any scripts that need to be called after the body content here.' ), 'section' => 'header_footer_code', 'priority' => 10, 'type' => 'textarea', 'input_attrs' => array( // Optional. 'class' => 'footer_scripts', ), ) ); ``` And here's how I'm calling it: ``` <?php echo get_theme_mod( 'footer_code'); ?> ``` Update: Here's the sample code that I used as a test, which prints exactly as you see it in my theme, meaning that it's treated as content:; would be in CSS. ``` <script> jQuery('.woocommerce-MyAccount-navigation ul').addClass('chev'); </script> ```
This is probably not the best answer, someone may know a way for this input to be properly handled given that you want to store code in it, but this will probably do what you're intending: ``` <?php echo html_entity_decode(get_theme_mod( 'footer_code')); ?> ``` Note this is probably somewhat of a security risk, and this behaviour of Wordpress escaping the HTML characters prevents exactly what you're trying to do for security reasons. You may want to see if there are other ways to do what you're trying to do here that don't allow that to happen.
371,312
<p>I have added an image custom field for categories, in which I assign an image for every category. Something like this:</p> <p><a href="https://i.stack.imgur.com/Nvlfa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nvlfa.png" alt="enter image description here" /></a></p> <p>I have a custom post type, and for each post I publish in this post type, I assign one category. I need each post I publish to change its featured image, according to the category assigned to it, with the image that has been added to the custom field.</p> <p>Any help?</p> <p><strong>Edit:</strong></p> <p>I found this topic about the same question:</p> <p><a href="https://support.advancedcustomfields.com/forums/topic/post-featured-image-from-category-custom-field-image/" rel="nofollow noreferrer">https://support.advancedcustomfields.com/forums/topic/post-featured-image-from-category-custom-field-image/</a></p> <p>There's an explanation on how to do it. Hopefully, someone can help me with the code since I'm not skilled enough to be able to do it.</p>
[ { "answer_id": 371596, "author": "joshmoto", "author_id": 111152, "author_profile": "https://wordpress.stackexchange.com/users/111152", "pm_score": 2, "selected": true, "text": "<p>You could filter the <code>the_post_thumbnail()</code> function, which will dynamically show the assigned category image across all your custom post type, rather than using <code>acf_save_post</code> to save the category image in the post featured image meta field.</p>\n<p>By filtering the <code>the_post_thumbnail()</code> for your specific post type, this means if you change the image on category in the future, it will automatically update all the custom post type featured images with the assigned category.</p>\n<p>Here is rough example that might get you on the right track, read my comments in code carefully so you can update the relevant fields to suit you environment...</p>\n<pre><code>/**\n * @param $html\n * @param $post_id\n * @param $post_thumbnail_id\n * @param $size\n * @param array $attr\n * @return string $html\n */\nfunction modify_cars_featured_img_html($html, $post_id, $post_thumbnail_id, $size, $attr) {\n\n // if post type is not 'cars' then return html now\n if(get_post_type($post_id) &lt;&gt; 'cars') return $html;\n\n // get the categories from cars post\n $cat = get_the_terms($post_id,'category');\n\n // if categories var is array then return categories else false\n $cat = is_array($cat) ? $cat : false;\n\n // if categories is false then return html now\n if(!isset($cat[0])) return $html;\n\n // get categories image acf field using first existing category id in array objects\n $id = get_field('your_category_acf_img_field_name','category_'.$cat[0]-&gt;term_id);\n \n // get the attachment data based on passed size and category image id\n $src = wp_get_attachment_image_src($id, $size);\n\n // get the media item image title from category image id\n $alt = get_the_title($id); \n\n // if class is passed in post thumbnail function in theme make sure we pass this to featured image html\n $class = isset($attr['class']) ? $attr['class'] : false;\n\n // the new post thumbnail featured image html\n $html = '&lt;img src=&quot;' . $src[0] . '&quot; alt=&quot;' . $alt . '&quot; ' . ( $class ? 'class=&quot;' . $class . '&quot;' : null ) . ' /&gt;';\n \n // return the image html\n return $html;\n}\n\n// add the filter\nadd_filter('post_thumbnail_html', 'modify_cars_featured_img_html', 99, 5);\n</code></pre>\n<p>Add all this updated code to your <code>functions.php</code>.</p>\n<hr />\n<p>Updated code above to return <code>$html</code> early at two points in this function, as I was originally only returning which was causing your other post thumbnails to break.</p>\n<p>Make sure you also set your categories image acf field to return image ID or this wont code wont work.</p>\n<p><a href=\"https://i.stack.imgur.com/Kx0yp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Kx0yp.png\" alt=\"enter image description here\" /></a></p>\n<p>Let me know if this fixes it.</p>\n" }, { "answer_id": 409158, "author": "Paal Joachim Romdahl", "author_id": 75194, "author_profile": "https://wordpress.stackexchange.com/users/75194", "pm_score": 0, "selected": false, "text": "<p>A long time ago I used code from here: <a href=\"https://wpforce.com/automatically-set-the-featured-image-in-wordpress/\" rel=\"nofollow noreferrer\">https://wpforce.com/automatically-set-the-featured-image-in-wordpress/</a> (Looks like the post does not longer exist) and <a href=\"https://wpsites.net/web-design/add-default-featured-image-for-each-post-in-a-category/\" rel=\"nofollow noreferrer\">https://wpsites.net/web-design/add-default-featured-image-for-each-post-in-a-category/</a></p>\n<p>The category part works but the set first image in post as featured does not.</p>\n<pre><code>// Inside your functions file add the following code\n// \nfunction wpforce_featured() {\n global $post;\n $already_has_thumb = has_post_thumbnail($post-&gt;ID); // If post have a featured image use that.\n if (!$already_has_thumb) {\n // If post does not have a featured image then get the first post image and set as featured image.\n $attached_image = get_children( &quot;post_parent=$post-&gt;ID&amp;post_type=attachment&amp;post_mime_type=image&amp;numberposts=1&quot; ); // Number 1 relates to taking post image number 1 and adding it as a featured image.\n if ($attached_image) {\n foreach ($attached_image as $attachment_id =&gt; $attachment) {\n set_post_thumbnail($post-&gt;ID, $attachment_id);\n // $attachment_id = attachment_url_to_postid( $image_url );\n // echo $attachment_id;\n \n }\n } else if ( in_category('WordPress') ){ // Add your own categories.\n set_post_thumbnail($post-&gt;ID, '42'); \n // Find attachment media id by right clicking the image in the Media library and selecting inspect element. Look for the data-id number. This number is then added to the post id. Or change to list view and look bottom left in the status bar for an ID number.\n }\n \n else if ( in_category('dog') ) {\n set_post_thumbnail($post-&gt;ID, '39'); //48\n }\n else if ( in_category('cat') ) {\n set_post_thumbnail($post-&gt;ID, '45'); //44\n }\n else if ( in_category('Uncategorized') ) {\n set_post_thumbnail($post-&gt;ID, '49'); //40\n }\n }\n } //end function\nadd_action('the_post', 'wpforce_featured');\nadd_action('save_post', 'wpforce_featured');\nadd_action('draft_to_publish', 'wpforce_featured');\nadd_action('new_to_publish', 'wpforce_featured');\nadd_action('pending_to_publish', 'wpforce_featured');\nadd_action('future_to_publish', 'wpforce_featured');\n</code></pre>\n" } ]
2020/07/18
[ "https://wordpress.stackexchange.com/questions/371312", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/191421/" ]
I have added an image custom field for categories, in which I assign an image for every category. Something like this: [![enter image description here](https://i.stack.imgur.com/Nvlfa.png)](https://i.stack.imgur.com/Nvlfa.png) I have a custom post type, and for each post I publish in this post type, I assign one category. I need each post I publish to change its featured image, according to the category assigned to it, with the image that has been added to the custom field. Any help? **Edit:** I found this topic about the same question: <https://support.advancedcustomfields.com/forums/topic/post-featured-image-from-category-custom-field-image/> There's an explanation on how to do it. Hopefully, someone can help me with the code since I'm not skilled enough to be able to do it.
You could filter the `the_post_thumbnail()` function, which will dynamically show the assigned category image across all your custom post type, rather than using `acf_save_post` to save the category image in the post featured image meta field. By filtering the `the_post_thumbnail()` for your specific post type, this means if you change the image on category in the future, it will automatically update all the custom post type featured images with the assigned category. Here is rough example that might get you on the right track, read my comments in code carefully so you can update the relevant fields to suit you environment... ``` /** * @param $html * @param $post_id * @param $post_thumbnail_id * @param $size * @param array $attr * @return string $html */ function modify_cars_featured_img_html($html, $post_id, $post_thumbnail_id, $size, $attr) { // if post type is not 'cars' then return html now if(get_post_type($post_id) <> 'cars') return $html; // get the categories from cars post $cat = get_the_terms($post_id,'category'); // if categories var is array then return categories else false $cat = is_array($cat) ? $cat : false; // if categories is false then return html now if(!isset($cat[0])) return $html; // get categories image acf field using first existing category id in array objects $id = get_field('your_category_acf_img_field_name','category_'.$cat[0]->term_id); // get the attachment data based on passed size and category image id $src = wp_get_attachment_image_src($id, $size); // get the media item image title from category image id $alt = get_the_title($id); // if class is passed in post thumbnail function in theme make sure we pass this to featured image html $class = isset($attr['class']) ? $attr['class'] : false; // the new post thumbnail featured image html $html = '<img src="' . $src[0] . '" alt="' . $alt . '" ' . ( $class ? 'class="' . $class . '"' : null ) . ' />'; // return the image html return $html; } // add the filter add_filter('post_thumbnail_html', 'modify_cars_featured_img_html', 99, 5); ``` Add all this updated code to your `functions.php`. --- Updated code above to return `$html` early at two points in this function, as I was originally only returning which was causing your other post thumbnails to break. Make sure you also set your categories image acf field to return image ID or this wont code wont work. [![enter image description here](https://i.stack.imgur.com/Kx0yp.png)](https://i.stack.imgur.com/Kx0yp.png) Let me know if this fixes it.
371,321
<p>I’m creating and developing a new plugin for some of my private clients and I do want to see if my clients are sharing my plugin with other people (I asked them not to do that).</p> <p>How can I do something in my plugin every time plugin is activated, his website sends an email from ‘[email protected]’ to one or more emails I want ‘[email protected]’ and ‘[email protected]’.</p> <p>By the way, does this include if they update the plugin? Or I just would be able to see who activates only? And does it include the current activated plugin?</p>
[ { "answer_id": 371323, "author": "Younes.D", "author_id": 65465, "author_profile": "https://wordpress.stackexchange.com/users/65465", "pm_score": 3, "selected": true, "text": "<p>I offer you an idea that I have already used something like this.\nI wanted to know the sites that my plugin uses, I created a cron job allow me to send me an email every week :</p>\n<pre><code>add_action('init', function() {\n $time = wp_next_scheduled('dro_cron_hook');\n wp_unschedule_event($time, 'dro_cron_hook');\n\n if (!wp_next_scheduled('dro_cron_hook')) {\n wp_schedule_event(time(), 'everyweek', 'dro_cron_hook');\n }\n});\n\nadd_filter('cron_schedules', function($schedules) {\n$schedules['everyweek'] = array(\n 'interval' =&gt; 604800\n );\n return $schedules;\n});\n\nadd_action('dro_cron_hook', function() {\n\n // Here you can send the email using wp_mail() and some additional data\n});\n</code></pre>\n" }, { "answer_id": 371328, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 2, "selected": false, "text": "<p>So there are two parts to your question:</p>\n<ol>\n<li>How to run code when your plugin is activated</li>\n<li>How to send an email</li>\n</ol>\n<p>For item 1 I searched for 'wordpress plugin activation hook' and found <a href=\"https://developer.wordpress.org/plugins/plugin-basics/activation-deactivation-hooks/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/plugins/plugin-basics/activation-deactivation-hooks/</a> which describes this hook so you can call your own fucntion when a plugin is activated:</p>\n<pre><code>register_activation_hook( __FILE__, 'pluginprefix_function_to_run' );\n</code></pre>\n<p>It is documented here: <a href=\"https://developer.wordpress.org/reference/functions/register_activation_hook/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/register_activation_hook/</a></p>\n<p>For item 2, there are many examples of online of how to send email from PHP and/or inside the Wordpress infrastructure. As you are using this for a notification, I would suggest that you think about sending this notification with a very simple REST API style call instead. E.g. you could make a URL like <code>yoursite.com/plugin/ping</code> and your plugin could call that URL whenever it's activated, attaching extra information as required in e.g. the request parameters.</p>\n<p>Note that however you send the notification, collecting identifiable information about people without their consent is immoral and also illegal in e.g. the EU under GDPR so you need to be very careful with what information you collect. You may want to consider licensing your software and having users agree to a license rather than what you're doing, however that subject is way off topic here.</p>\n" } ]
2020/07/18
[ "https://wordpress.stackexchange.com/questions/371321", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/191846/" ]
I’m creating and developing a new plugin for some of my private clients and I do want to see if my clients are sharing my plugin with other people (I asked them not to do that). How can I do something in my plugin every time plugin is activated, his website sends an email from ‘[email protected]’ to one or more emails I want ‘[email protected]’ and ‘[email protected]’. By the way, does this include if they update the plugin? Or I just would be able to see who activates only? And does it include the current activated plugin?
I offer you an idea that I have already used something like this. I wanted to know the sites that my plugin uses, I created a cron job allow me to send me an email every week : ``` add_action('init', function() { $time = wp_next_scheduled('dro_cron_hook'); wp_unschedule_event($time, 'dro_cron_hook'); if (!wp_next_scheduled('dro_cron_hook')) { wp_schedule_event(time(), 'everyweek', 'dro_cron_hook'); } }); add_filter('cron_schedules', function($schedules) { $schedules['everyweek'] = array( 'interval' => 604800 ); return $schedules; }); add_action('dro_cron_hook', function() { // Here you can send the email using wp_mail() and some additional data }); ```
371,346
<p>When submitting form data via jQuery and using admin-ajax, including a file attachment was easy:</p> <p><code>var data = new FormData($(this)[0]);</code></p> <p>How do you include a file attachment when submitting form data to a Rest Controller?</p> <p>This submits all the form fields, except the file attachment.</p> <p><code>var data = $this.serializeArray();</code></p> <p>The jQuery:</p> <pre><code> $('#create-book-form').submit(function (e) { var $this = $(this); e.preventDefault(); //var data = new FormData($(this)[0]); var data = $this.serializeArray(); data.push({name: &quot;rtype&quot;, value: &quot;create&quot;}); $.ajax({ url: BOOK_SUBMITTER.root + 'rfp-books/v1/books', data: $.param(data), beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', BOOK_SUBMITTER.nonce ); }, //etc </code></pre> <p>It all works, except the file is not part of the form data that arrives at the rest controller. Yes, I have an input called 'file' so the user can include a jpg.</p> <p>I need to send all the form data in a single call. The post attachment is created right after the post is created in the controller. So, how do I get the file into the data included in <code>$.param(data)</code></p> <p>In the route callback in the REST Controller:</p> <pre><code>$params = $request-&gt;get_params(); write_log( $params ); </code></pre> <p>The log shows all the form data - except the file. ( If I submit the jQuery data as FormData, none of the data is recognized in the controller. )</p>
[ { "answer_id": 371365, "author": "Ahmad Wael", "author_id": 115635, "author_profile": "https://wordpress.stackexchange.com/users/115635", "pm_score": 0, "selected": false, "text": "<p>i have used this code which uploads file in an ajax request</p>\n<pre><code>&lt;style&gt;\n .wbc_form {\n width: 500px;\n max-width: 100%;\n margin: 0 auto;\n text-align: center;\n }\n\n .image_preview {\n width: 500px;\n max-width: 100%;\n height: 250px;\n border: 3px dashed #eee;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n .image_preview img {\n width: 100%;\n height: auto;\n max-height: 100%;\n display: none;\n }\n&lt;/style&gt;\n&lt;form class=&quot;wbc_form&quot; action=&quot;&lt;?php echo esc_url( admin_url( 'admin-ajax.php' ) ) ?&gt;&quot; method=&quot;POST&quot;\n enctype=&quot;multipart/form-data&quot;&gt;\n &lt;h1&gt;\n &lt;?php esc_html_e( 'Upload payment confirmation image', 'wbc' ); ?&gt;\n &lt;/h1&gt;\n &lt;input type=&quot;hidden&quot; name=&quot;action&quot; value=&quot;wbc_bacs_confirm&quot;&gt;\n &lt;?php wp_nonce_field() ?&gt;\n &lt;input type=&quot;hidden&quot; name=&quot;order_id&quot; id=&quot;wbc_order_id&quot; value=&quot;&lt;?php echo esc_attr( $order_id ); ?&gt;&quot;&gt;\n &lt;input type=&quot;file&quot; class=&quot;wbc_image&quot; name=&quot;wbc_image&quot; value=&quot;&quot; accept=&quot;image/*&quot;&gt;\n &lt;div class=&quot;image_preview&quot;&gt;\n &lt;img src=&quot;&quot; class=&quot;img_preview__image&quot; alt=&quot;Preview&quot;&gt;\n &lt;span class=&quot;img_preview__default_text&quot;&gt;&lt;?php esc_html_e( 'Image Preview', 'wbc' ); ?&gt;&lt;/span&gt;\n &lt;/div&gt;\n &lt;br&gt;\n &lt;button class=&quot;go_now button alt&quot; type=&quot;submit&quot;&gt;&lt;?php esc_html_e( 'Send', 'wbc' ); ?&gt;&lt;/button&gt;\n&lt;/form&gt;\n\n&lt;script&gt;\n (function ($) {\n let input_file = $('.wbc_image'),\n preview_image = $('.img_preview__image'),\n preview_text = $('.img_preview__default_text');\n\n input_file.on('change', function (e) {\n let f = this.files[0];\n\n //here I CHECK if the FILE SIZE is bigger than 2 MB (numbers below are in bytes)\n if (f.size &gt; 2097152 || f.fileSize &gt; 2097152) {\n //show an alert to the user\n alert(wbc_object.max_file_size_msg);\n //reset file upload control\n this.value = null;\n }\n\n let file = e.target.files[0];\n if (file) {\n let reader = new FileReader();\n preview_text.hide();\n preview_image.show();\n reader.onload = function (event) {\n preview_image.attr(&quot;src&quot;, event.target.result)\n };\n reader.readAsDataURL(file);\n } else {\n preview_image.attr('src', '');\n preview_image.hide();\n preview_text.show();\n }\n });\n\n\n $('.wbc_form').on('submit', function (e) {\n e.preventDefault();\n var formData = new FormData(this);\n $.ajax({\n url: wbc_object.ajax_url,\n type: &quot;POST&quot;,\n data: formData,\n contentType: false,\n processData: false,\n success: function (response) {\n // console.log(response);\n if (response.success) {\n $('.wbc_form').html(wbc_object.request_received_msg);\n } else {\n //show the toastr js message\n // toastr.error(response.data.msg);\n }\n }\n });\n });\n\n })(jQuery);\n&lt;/script&gt;\n</code></pre>\n<p>then you will receive the file in the request parameters</p>\n" }, { "answer_id": 371369, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>You can really use <code>FormData</code> just like you could use it with the old <code>admin-ajax.php</code> route, but:</p>\n<ol>\n<li><p>Set <code>processData</code> and <code>contentType</code> to <code>false</code>.</p>\n</li>\n<li><p>Set the <code>method</code> to <code>POST</code> <em>and</em> make sure your REST API route supports the <code>POST</code> method.</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('#create-book-form').submit(function (e) {\n\n// var $this = $(this); // what's this?\n e.preventDefault();\n\n var data = new FormData( this ); \n\n data.append( 'rtype', 'create' ); // add extra param\n\n $.ajax({\n\n url: BOOK_SUBMITTER.root + 'rfp-books/v1/books',\n data: data, //$.param(data),\n processData: false,\n contentType: false,\n method: 'POST',\n beforeSend: function ( xhr ) {\n xhr.setRequestHeader( 'X-WP-Nonce', BOOK_SUBMITTER.nonce );\n },\n success: function ( data ) {\n console.log( data ); // I added just for testing purposes.\n },\n });\n});\n</code></pre>\n</li>\n</ol>\n<p>Then in your REST API endpoint callback, just use the <code>$_FILES</code> to get the uploaded file, e.g. <code>$_FILES['file']</code>. For other parameters, you can use <code>$request-&gt;get_param()</code>, e.g. <code>$request-&gt;get_param( 'rtype' )</code>.</p>\n<p>Additionally or to other readers, you should have a file upload input in your form, e.g. <code>&lt;input type=&quot;file&quot; name=&quot;file&quot; /&gt;</code>, but the <code>name</code> can be anything unless if you're creating an attachment using the default <code>wp/v2/media</code> route.</p>\n" } ]
2020/07/18
[ "https://wordpress.stackexchange.com/questions/371346", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16575/" ]
When submitting form data via jQuery and using admin-ajax, including a file attachment was easy: `var data = new FormData($(this)[0]);` How do you include a file attachment when submitting form data to a Rest Controller? This submits all the form fields, except the file attachment. `var data = $this.serializeArray();` The jQuery: ``` $('#create-book-form').submit(function (e) { var $this = $(this); e.preventDefault(); //var data = new FormData($(this)[0]); var data = $this.serializeArray(); data.push({name: "rtype", value: "create"}); $.ajax({ url: BOOK_SUBMITTER.root + 'rfp-books/v1/books', data: $.param(data), beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', BOOK_SUBMITTER.nonce ); }, //etc ``` It all works, except the file is not part of the form data that arrives at the rest controller. Yes, I have an input called 'file' so the user can include a jpg. I need to send all the form data in a single call. The post attachment is created right after the post is created in the controller. So, how do I get the file into the data included in `$.param(data)` In the route callback in the REST Controller: ``` $params = $request->get_params(); write_log( $params ); ``` The log shows all the form data - except the file. ( If I submit the jQuery data as FormData, none of the data is recognized in the controller. )
You can really use `FormData` just like you could use it with the old `admin-ajax.php` route, but: 1. Set `processData` and `contentType` to `false`. 2. Set the `method` to `POST` *and* make sure your REST API route supports the `POST` method. ```js $('#create-book-form').submit(function (e) { // var $this = $(this); // what's this? e.preventDefault(); var data = new FormData( this ); data.append( 'rtype', 'create' ); // add extra param $.ajax({ url: BOOK_SUBMITTER.root + 'rfp-books/v1/books', data: data, //$.param(data), processData: false, contentType: false, method: 'POST', beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', BOOK_SUBMITTER.nonce ); }, success: function ( data ) { console.log( data ); // I added just for testing purposes. }, }); }); ``` Then in your REST API endpoint callback, just use the `$_FILES` to get the uploaded file, e.g. `$_FILES['file']`. For other parameters, you can use `$request->get_param()`, e.g. `$request->get_param( 'rtype' )`. Additionally or to other readers, you should have a file upload input in your form, e.g. `<input type="file" name="file" />`, but the `name` can be anything unless if you're creating an attachment using the default `wp/v2/media` route.
371,347
<p>I have a child theme folder called themes/child-theme and inside I have a file dashboard_payments.php. Under the child theme folder I'm creating a new folder called gateway and inside there's a config.php.</p> <p>So, how do I do a require_once inside dashboard_payments.php to call the file gateway/config.php? How would the require_once or include line look like?</p>
[ { "answer_id": 371349, "author": "Ivan Shatsky", "author_id": 124579, "author_profile": "https://wordpress.stackexchange.com/users/124579", "pm_score": 0, "selected": false, "text": "<p>You can use either</p>\n<pre><code>require_once(get_stylesheet_directory() . '/gateway/config.php');\n</code></pre>\n<p>or (should be faster)</p>\n<pre><code>require_once(__DIR__ . '/gateway/config.php');\n</code></pre>\n" }, { "answer_id": 371358, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>Since 4.7 <a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_path/\" rel=\"nofollow noreferrer\"><code>get_theme_file_path()</code></a> is the right function to use:</p>\n<pre><code>require_once get_theme_file_path( 'gateway/config.php' );\n</code></pre>\n" } ]
2020/07/18
[ "https://wordpress.stackexchange.com/questions/371347", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183652/" ]
I have a child theme folder called themes/child-theme and inside I have a file dashboard\_payments.php. Under the child theme folder I'm creating a new folder called gateway and inside there's a config.php. So, how do I do a require\_once inside dashboard\_payments.php to call the file gateway/config.php? How would the require\_once or include line look like?
Since 4.7 [`get_theme_file_path()`](https://developer.wordpress.org/reference/functions/get_theme_file_path/) is the right function to use: ``` require_once get_theme_file_path( 'gateway/config.php' ); ```
371,418
<p>As developer, you want all the time the last version files on page refresh action. As I understood, there are 3 kinds of cache :</p> <ol> <li>Browser cache (Browser settings)</li> <li>Website cache (WP plugins)</li> <li>Proxy cache (HTTP Headers)</li> </ol> <p>For some reasons, there are some days where I can removed browser cache, download a new browser on Wordpress project without any cache plugin... If I keypress F5, CTRL+F5 or CTRL+Shift+R, I got an old version, sometimes version older. I can loose hours like this. One friend told me to see about the proxy cache and force the HTTP Header to get the last files version.</p> <p>I got this raw header :</p> <pre><code>GET /preprod/sign-up/ HTTP/2 Host: mysite.com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Referer: ... DNT: 1 Connection: keep-alive Cookie: wordpress_test_cookie=WP+Cookie+check; bid_1_password_protected_auth=1111111111111111111111; SERVERID123456=1234 Upgrade-Insecure-Requests: 1 Pragma: no-cache Cache-Control: no-cache </code></pre> <p>Questions :</p> <ol> <li>How can I check if it can be a proxy cache matter ?</li> <li>How can I resolve that in this case on a Wordpress site ?</li> </ol>
[ { "answer_id": 371419, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>If it's browser cache, you can go into the dev tools and disable all local cache. Browser docs can tell you how to do this.</p>\n<p>If it's the proxy cache, either turn it off or load the site without the proxy, and retest. You will need to consult the documentation for the proxy you're using for how to do this, and how to fix it. You would be better asking on another stack about your specific proxy software and its configuration.</p>\n<p>If it's the WP cache, then no, WP doesn't have a page cache. Either disable the plugins providing caching and retest, or consult with their documentation. The solution here will be plugin specific, there is no generic WP solution as there is noo generic WP page caching.</p>\n<hr />\n<p>Either start with browser cache and work by peeling away the layers in a process of elimination. Or, by eliminating all of it, and turning it back on 1 layer at a time until the misbehaviour returns. This will give you useful information on how to debug the problem and which layer is problematic.</p>\n" }, { "answer_id": 371422, "author": "J.BizMai", "author_id": 128094, "author_profile": "https://wordpress.stackexchange.com/users/128094", "pm_score": -1, "selected": false, "text": "<p>I found a solution <a href=\"https://techjourney.net/how-to-modify-edit-http-header-via-wordpress-php-functions/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<pre><code>function add_header_no_cache($headers) {\n\n $headers['Cache-Control'] = 'no-cache, no-store, must-revalidate, max-age=0'; \n $headers['Pragma'] = 'no-cache';\n $headers['Expires'] = '0';\n\n return $headers; \n}\nadd_filter( 'wp_headers', 'add_header_no_cache_login' );\n</code></pre>\n" } ]
2020/07/20
[ "https://wordpress.stackexchange.com/questions/371418", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128094/" ]
As developer, you want all the time the last version files on page refresh action. As I understood, there are 3 kinds of cache : 1. Browser cache (Browser settings) 2. Website cache (WP plugins) 3. Proxy cache (HTTP Headers) For some reasons, there are some days where I can removed browser cache, download a new browser on Wordpress project without any cache plugin... If I keypress F5, CTRL+F5 or CTRL+Shift+R, I got an old version, sometimes version older. I can loose hours like this. One friend told me to see about the proxy cache and force the HTTP Header to get the last files version. I got this raw header : ``` GET /preprod/sign-up/ HTTP/2 Host: mysite.com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Referer: ... DNT: 1 Connection: keep-alive Cookie: wordpress_test_cookie=WP+Cookie+check; bid_1_password_protected_auth=1111111111111111111111; SERVERID123456=1234 Upgrade-Insecure-Requests: 1 Pragma: no-cache Cache-Control: no-cache ``` Questions : 1. How can I check if it can be a proxy cache matter ? 2. How can I resolve that in this case on a Wordpress site ?
If it's browser cache, you can go into the dev tools and disable all local cache. Browser docs can tell you how to do this. If it's the proxy cache, either turn it off or load the site without the proxy, and retest. You will need to consult the documentation for the proxy you're using for how to do this, and how to fix it. You would be better asking on another stack about your specific proxy software and its configuration. If it's the WP cache, then no, WP doesn't have a page cache. Either disable the plugins providing caching and retest, or consult with their documentation. The solution here will be plugin specific, there is no generic WP solution as there is noo generic WP page caching. --- Either start with browser cache and work by peeling away the layers in a process of elimination. Or, by eliminating all of it, and turning it back on 1 layer at a time until the misbehaviour returns. This will give you useful information on how to debug the problem and which layer is problematic.
371,473
<p>I tried everything I think but still getting bad request 400 Ajax WordPress. I have try applying serialize and answers found in other thread but still getting 400 bad error.</p> <p><strong>Custom Page Template index.php</strong></p> <pre><code>add_action( 'wp_enqueue_scripts', 'myblog_ajax_enqueue' ); function myblog_ajax_enqueue() { wp_enqueue_script('myblog-ajax-script', get_stylesheet_directory_uri() . '/template-parts/templates/blog/js/ajax.js',array('jquery')); wp_localize_script( 'myblog-ajax-script','myblog_ajax_obj', array('ajaxurl' =&gt; admin_url( 'admin-ajax.php' ),'nonce' =&gt; wp_create_nonce('ajax-nonce'))); } </code></pre> <p><strong>blogcontent.php</strong></p> <pre><code>function myblog_ajax_request() { $nonce = $_POST['nonce']; if ( ! wp_verify_nonce( $nonce, 'myblog-ajax-script' ) ) { die( 'Nonce value cannot be verified.' ); } // The $_REQUEST contains all the data sent via ajax if ( isset($_REQUEST) ) { $fruit = $_REQUEST['fruit']; // Let's take the data that was sent and do something with it if ( $fruit == 'Banana' ) { $fruit = 'Apple'; } echo $fruit; } die(); } add_action( 'wp_ajax_myblog_ajax_request', 'myblog_ajax_request' ); add_action( 'wp_ajax_nopriv_myblog_ajax_request', 'myblog_ajax_request' ); </code></pre> <p><strong>Ajax.Js</strong></p> <pre><code>jQuery(document).ready(function($) { var fruit = 'Banana'; // This does the ajax request $.ajax({ url: myblog_ajax_obj.ajaxurl, data: JSON.stringify({ 'action': 'myblog_ajax_request', 'fruit': fruit, 'nonce': myblog_ajax_obj.nonce }), success: function(data) { // This outputs the result of the ajax request console.log(data); }, error: function(errorThrown) { console.log(errorThrown); }, dateType: 'json', contentType: 'application/json; charset=utf-8' }); }); </code></pre>
[ { "answer_id": 371475, "author": "Az Rieil", "author_id": 154993, "author_profile": "https://wordpress.stackexchange.com/users/154993", "pm_score": 0, "selected": false, "text": "<ol>\n<li><p>Send is as object, not a JSON string</p>\n</li>\n<li><p>Remove content type, you should let is default ( <code>application/x-www-form-urlencoded</code>)</p>\n</li>\n<li><p>Remove dataType - you send response as text, not a json. ( for JSON response use <code>wp_send_json</code> )</p>\n</li>\n<li><p>Ensure that you register you ajax actions in init files ( your plugin main file or functions.php )</p>\n</li>\n<li><p>Also you can try debug it step by step in wp-admin/admin-ajax.php. 400 error means you code get this file, but action isnt recognized</p>\n<pre><code> url: myblog_ajax_obj.ajaxurl,\n data: {\n action: 'myblog_ajax_request',\n fruit: fruit,\n nonce: myblog_ajax_obj.nonce\n },\n success: function(data) {\n console.log(data);\n }\n</code></pre>\n</li>\n</ol>\n" }, { "answer_id": 371477, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>Here is your problem:</p>\n<blockquote>\n<p>blogcontent.php</p>\n</blockquote>\n<p>When WP is contacted to handle the Admin AJAX request, it doesn't load a page template. Remember, every request to WP loads WP from a blank slate. It doesn't know anything about the previous requests, only what it's told.</p>\n<p>So because you aren't requesting that page, the template never loads, the filters never run, so there is no AJAX handler to take your request.</p>\n<p>So instead, move your filters to <code>functions.php</code>. Also consider using the modern REST API to handle your requests, it's easier, nicer to debug with human readable error messages, and it'll sanitize authenticate and validate for you if you tell it how! You even get a nice friendly URL.</p>\n<p>Once that's been done, undo all the other things you did to try and fix this, like setting the datatype, or contenttype, that's hurting you not helping.</p>\n" }, { "answer_id": 371478, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>There's only one reason you get a 400 error with admin-ajax.php: The <code>wp_ajax_{$action}</code> or <code>wp_ajax_nopriv_{$action}</code> action has not been hooked with an <code>{$action}</code> that matches the <code>action</code> data parameter sent with your request. So either your callback is not hooked, or you're not sending the action correctly. Your code is making both errors.</p>\n<ol>\n<li>You are encoding the data sent to the server as JSON. WordPress looks for <code>$_REQUEST['action']</code> to trigger the appropriate action. When data is sent to the server as JSON, <code>$_REQUEST</code> cannot be populated, so <code>$_REQUEST['action']</code> does not exist, meaning that your callback is never run. You need to remove <code>JSON.stringify()</code> from your code.</li>\n<li>You are running <code>add_action()</code> for <code>wp_ajax_myblog_ajax_request</code> inside a page template. This won't work. You are sending your request to <code>wp-admin/admin-ajax.php</code>, but that code does not load templates, so your callback is not hooked for that request. You need to use <code>add_action()</code> inside a file that <em>is</em> loaded inside <code>wp-admin/admin-ajax.php</code>, such as your theme's functions.php file, or a plugin.</li>\n</ol>\n" } ]
2020/07/21
[ "https://wordpress.stackexchange.com/questions/371473", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44422/" ]
I tried everything I think but still getting bad request 400 Ajax WordPress. I have try applying serialize and answers found in other thread but still getting 400 bad error. **Custom Page Template index.php** ``` add_action( 'wp_enqueue_scripts', 'myblog_ajax_enqueue' ); function myblog_ajax_enqueue() { wp_enqueue_script('myblog-ajax-script', get_stylesheet_directory_uri() . '/template-parts/templates/blog/js/ajax.js',array('jquery')); wp_localize_script( 'myblog-ajax-script','myblog_ajax_obj', array('ajaxurl' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajax-nonce'))); } ``` **blogcontent.php** ``` function myblog_ajax_request() { $nonce = $_POST['nonce']; if ( ! wp_verify_nonce( $nonce, 'myblog-ajax-script' ) ) { die( 'Nonce value cannot be verified.' ); } // The $_REQUEST contains all the data sent via ajax if ( isset($_REQUEST) ) { $fruit = $_REQUEST['fruit']; // Let's take the data that was sent and do something with it if ( $fruit == 'Banana' ) { $fruit = 'Apple'; } echo $fruit; } die(); } add_action( 'wp_ajax_myblog_ajax_request', 'myblog_ajax_request' ); add_action( 'wp_ajax_nopriv_myblog_ajax_request', 'myblog_ajax_request' ); ``` **Ajax.Js** ``` jQuery(document).ready(function($) { var fruit = 'Banana'; // This does the ajax request $.ajax({ url: myblog_ajax_obj.ajaxurl, data: JSON.stringify({ 'action': 'myblog_ajax_request', 'fruit': fruit, 'nonce': myblog_ajax_obj.nonce }), success: function(data) { // This outputs the result of the ajax request console.log(data); }, error: function(errorThrown) { console.log(errorThrown); }, dateType: 'json', contentType: 'application/json; charset=utf-8' }); }); ```
Here is your problem: > > blogcontent.php > > > When WP is contacted to handle the Admin AJAX request, it doesn't load a page template. Remember, every request to WP loads WP from a blank slate. It doesn't know anything about the previous requests, only what it's told. So because you aren't requesting that page, the template never loads, the filters never run, so there is no AJAX handler to take your request. So instead, move your filters to `functions.php`. Also consider using the modern REST API to handle your requests, it's easier, nicer to debug with human readable error messages, and it'll sanitize authenticate and validate for you if you tell it how! You even get a nice friendly URL. Once that's been done, undo all the other things you did to try and fix this, like setting the datatype, or contenttype, that's hurting you not helping.
371,573
<p>I have a function in function.php which is called on save_post. Currently, when the user is publishing or updating a post, this function will execute but it will take a lot of time.</p> <p>What is the easiest way so this function run in a background process - non-blocking?</p> <pre><code>function export_all_in_json() { file_put_contents(ABSPATH.'all.json', fopen('https://example.com/api/all/get_all_content/', 'r')); } add_action( 'save_post', 'export_all_in_json' ); </code></pre>
[ { "answer_id": 371575, "author": "Carlos Faria", "author_id": 39047, "author_profile": "https://wordpress.stackexchange.com/users/39047", "pm_score": -1, "selected": false, "text": "<p>Maybe you can use Action Scheduler to trigger a single asyncronous event. Just like a cronjob but triggered one time.</p>\n<p><a href=\"https://actionscheduler.org/\" rel=\"nofollow noreferrer\">https://actionscheduler.org/</a></p>\n" }, { "answer_id": 371580, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>Instead of contacting the remote site to get the information in an expensive HTTP request, why not have the remote site send you the data at regular intervals?</p>\n<ol>\n<li>Register a REST API endpoint to recieve the data on\n<ul>\n<li>In that endpoint, take in the data and save it in <code>all.json</code></li>\n</ul>\n</li>\n<li>On the remote site add a cron job\n<ul>\n<li>grab the data</li>\n<li>make a non-blocking remote request to the site with this data</li>\n</ul>\n</li>\n</ol>\n<p>Now we have a completely asynchronous non-blocking system. Why fetch the data when it can be given to you?</p>\n<p>This gives us several bonuses:</p>\n<ul>\n<li>The <code>save_post</code> filter can be completely removed making post saving faster</li>\n<li>This fixes a number of bugs in the filter by removing the filter</li>\n<li>Updates to the file can happen even when no posts are being created</li>\n<li>Updates to the file are now predictable and routine, e.g. every 5 minutes, or every hour</li>\n<li>This avoids race conditions where multiple requests are sent to the API at the same time, resulting in extra server load and broken JSON files</li>\n<li>Your API endpoint takes a little time to figure out the JSON data, so this gives you control over how often it happens, e.g. if the site is struggling change the cron job from 5 minutes too 10 minutes to ease the load</li>\n<li>You could ping the API and tell it to trigger sending the data to the endpoint when a post is saved, rather than doing the full fetch and save. This would allow you to use a fetch paradigm and still have the advantages. It's similar to how some payment and authentication flows work too.</li>\n</ul>\n" } ]
2020/07/22
[ "https://wordpress.stackexchange.com/questions/371573", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65089/" ]
I have a function in function.php which is called on save\_post. Currently, when the user is publishing or updating a post, this function will execute but it will take a lot of time. What is the easiest way so this function run in a background process - non-blocking? ``` function export_all_in_json() { file_put_contents(ABSPATH.'all.json', fopen('https://example.com/api/all/get_all_content/', 'r')); } add_action( 'save_post', 'export_all_in_json' ); ```
Instead of contacting the remote site to get the information in an expensive HTTP request, why not have the remote site send you the data at regular intervals? 1. Register a REST API endpoint to recieve the data on * In that endpoint, take in the data and save it in `all.json` 2. On the remote site add a cron job * grab the data * make a non-blocking remote request to the site with this data Now we have a completely asynchronous non-blocking system. Why fetch the data when it can be given to you? This gives us several bonuses: * The `save_post` filter can be completely removed making post saving faster * This fixes a number of bugs in the filter by removing the filter * Updates to the file can happen even when no posts are being created * Updates to the file are now predictable and routine, e.g. every 5 minutes, or every hour * This avoids race conditions where multiple requests are sent to the API at the same time, resulting in extra server load and broken JSON files * Your API endpoint takes a little time to figure out the JSON data, so this gives you control over how often it happens, e.g. if the site is struggling change the cron job from 5 minutes too 10 minutes to ease the load * You could ping the API and tell it to trigger sending the data to the endpoint when a post is saved, rather than doing the full fetch and save. This would allow you to use a fetch paradigm and still have the advantages. It's similar to how some payment and authentication flows work too.
371,585
<p>I'm trying (and failing) to use rewrite rules to redirect shorter/prettier URLs to the right page AND include values in the query string.</p> <p>WP is installed at <a href="https://example.com" rel="nofollow noreferrer">https://example.com</a>, and the plugin creates a page called 'foo' which uses a value 'bar' passed in the query string to generate the content from custom database tables.</p> <p>So an example full URL would be:</p> <p><a href="https://example.com/foo/?bar=XXXXXX" rel="nofollow noreferrer">https://example.com/foo/?bar=XXXXXX</a></p> <p>The 'bar' value would always be a string of between 6 and 8 alphanumeric chars with at least 1 dash(-).</p> <p>I want to use rewrite rules (but am open to other suggestions) so that a shorter URL can be used, such as:</p> <p><a href="https://example.com/f/XXXXXX" rel="nofollow noreferrer">https://example.com/f/XXXXXX</a></p> <p>I have tried using add_rewrite_rule as follows:</p> <pre><code>function jr_rewrite_add_rewrites(){ add_rewrite_rule( 'f\/([[:ascii:]]+)\/?$', '/index.php?pagename=foo&amp;bar=$matches[1]', 'top' ); } add_action( 'init', 'jr_rewrite_add_rewrites'); </code></pre> <p>And, when I flush the rewrite rules by clicking save on the Permalinks Settings page in the Dashboard, the rule is added to the htaccess file just fine:</p> <pre><code># BEGIN WordPress # The directives (lines) between `BEGIN WordPress` and `END WordPress` are # dynamically generated, and should only be modified via WordPress filters. # Any changes to the directives between these markers will be overwritten. &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteRule ^f\/([[:ascii:]]+)\/?$ /index.php?pagename=foo&amp;bar=$matches[1] [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>However, when I try to access:</p> <p><a href="https://example.com/f/XXXXXX" rel="nofollow noreferrer">https://example.com/f/XXXXXX</a></p> <p>the page is just redirected to:</p> <p><a href="https://example.com/foo/" rel="nofollow noreferrer">https://example.com/foo/</a></p> <p>and is missing the needed bar=XXXXXX querystring so the relevant content does not load.</p> <p>Can anyone please point out where I am going wrong wiht this or suggest an alternative?</p>
[ { "answer_id": 371575, "author": "Carlos Faria", "author_id": 39047, "author_profile": "https://wordpress.stackexchange.com/users/39047", "pm_score": -1, "selected": false, "text": "<p>Maybe you can use Action Scheduler to trigger a single asyncronous event. Just like a cronjob but triggered one time.</p>\n<p><a href=\"https://actionscheduler.org/\" rel=\"nofollow noreferrer\">https://actionscheduler.org/</a></p>\n" }, { "answer_id": 371580, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>Instead of contacting the remote site to get the information in an expensive HTTP request, why not have the remote site send you the data at regular intervals?</p>\n<ol>\n<li>Register a REST API endpoint to recieve the data on\n<ul>\n<li>In that endpoint, take in the data and save it in <code>all.json</code></li>\n</ul>\n</li>\n<li>On the remote site add a cron job\n<ul>\n<li>grab the data</li>\n<li>make a non-blocking remote request to the site with this data</li>\n</ul>\n</li>\n</ol>\n<p>Now we have a completely asynchronous non-blocking system. Why fetch the data when it can be given to you?</p>\n<p>This gives us several bonuses:</p>\n<ul>\n<li>The <code>save_post</code> filter can be completely removed making post saving faster</li>\n<li>This fixes a number of bugs in the filter by removing the filter</li>\n<li>Updates to the file can happen even when no posts are being created</li>\n<li>Updates to the file are now predictable and routine, e.g. every 5 minutes, or every hour</li>\n<li>This avoids race conditions where multiple requests are sent to the API at the same time, resulting in extra server load and broken JSON files</li>\n<li>Your API endpoint takes a little time to figure out the JSON data, so this gives you control over how often it happens, e.g. if the site is struggling change the cron job from 5 minutes too 10 minutes to ease the load</li>\n<li>You could ping the API and tell it to trigger sending the data to the endpoint when a post is saved, rather than doing the full fetch and save. This would allow you to use a fetch paradigm and still have the advantages. It's similar to how some payment and authentication flows work too.</li>\n</ul>\n" } ]
2020/07/22
[ "https://wordpress.stackexchange.com/questions/371585", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192065/" ]
I'm trying (and failing) to use rewrite rules to redirect shorter/prettier URLs to the right page AND include values in the query string. WP is installed at <https://example.com>, and the plugin creates a page called 'foo' which uses a value 'bar' passed in the query string to generate the content from custom database tables. So an example full URL would be: <https://example.com/foo/?bar=XXXXXX> The 'bar' value would always be a string of between 6 and 8 alphanumeric chars with at least 1 dash(-). I want to use rewrite rules (but am open to other suggestions) so that a shorter URL can be used, such as: <https://example.com/f/XXXXXX> I have tried using add\_rewrite\_rule as follows: ``` function jr_rewrite_add_rewrites(){ add_rewrite_rule( 'f\/([[:ascii:]]+)\/?$', '/index.php?pagename=foo&bar=$matches[1]', 'top' ); } add_action( 'init', 'jr_rewrite_add_rewrites'); ``` And, when I flush the rewrite rules by clicking save on the Permalinks Settings page in the Dashboard, the rule is added to the htaccess file just fine: ``` # BEGIN WordPress # The directives (lines) between `BEGIN WordPress` and `END WordPress` are # dynamically generated, and should only be modified via WordPress filters. # Any changes to the directives between these markers will be overwritten. <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteRule ^f\/([[:ascii:]]+)\/?$ /index.php?pagename=foo&bar=$matches[1] [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` However, when I try to access: <https://example.com/f/XXXXXX> the page is just redirected to: <https://example.com/foo/> and is missing the needed bar=XXXXXX querystring so the relevant content does not load. Can anyone please point out where I am going wrong wiht this or suggest an alternative?
Instead of contacting the remote site to get the information in an expensive HTTP request, why not have the remote site send you the data at regular intervals? 1. Register a REST API endpoint to recieve the data on * In that endpoint, take in the data and save it in `all.json` 2. On the remote site add a cron job * grab the data * make a non-blocking remote request to the site with this data Now we have a completely asynchronous non-blocking system. Why fetch the data when it can be given to you? This gives us several bonuses: * The `save_post` filter can be completely removed making post saving faster * This fixes a number of bugs in the filter by removing the filter * Updates to the file can happen even when no posts are being created * Updates to the file are now predictable and routine, e.g. every 5 minutes, or every hour * This avoids race conditions where multiple requests are sent to the API at the same time, resulting in extra server load and broken JSON files * Your API endpoint takes a little time to figure out the JSON data, so this gives you control over how often it happens, e.g. if the site is struggling change the cron job from 5 minutes too 10 minutes to ease the load * You could ping the API and tell it to trigger sending the data to the endpoint when a post is saved, rather than doing the full fetch and save. This would allow you to use a fetch paradigm and still have the advantages. It's similar to how some payment and authentication flows work too.
371,597
<p>So I have searched extensively on this, but all the answers do not work for me. I bought a website from someone, he installed it on my hosting, but did not provide me with the admin login. He is now MIA. So following some things I found on a google search, I added an admin user, (MD5) password and gave it access to everything. (the exact one is found here: <a href="https://wpengine.com/support/add-admin-user-phpmyadmin/" rel="nofollow noreferrer">https://wpengine.com/support/add-admin-user-phpmyadmin/</a>) This does not allow me to log in still.</p> <p>So I changed the admin email and tried to use the &quot;forgot my password&quot;. It says an email is sent, but it never shows up.</p> <p>I then changed the current admin password (again assuring it was MD5). When none of this worked I even tried a wordpress &quot;backdoor&quot; I found. Nada.</p> <p>Is there any other methods to adding a user or admin user besides the things I've listed as tried above? I do have FTP access and phpmyadmin access to all the files.</p> <p>Thank you</p>
[ { "answer_id": 371601, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>I've had success just changing the email address of an existing admin user, then using the lost password thing. Make sure that you check your trash/spam folders for the email to reset the password.</p>\n<p>It's a bit harder to create a new user 'row' for an admin. Not only do you have to do it in the users table, but also make an entry in the usermeta table.</p>\n<p>You might find the procedure here to be useful. <a href=\"https://www.greengeeks.com/tutorials/article/use-phpmyadmin-add-admin-user-wordpress-database/\" rel=\"nofollow noreferrer\">https://www.greengeeks.com/tutorials/article/use-phpmyadmin-add-admin-user-wordpress-database/</a> .</p>\n<p>There are other results in the google/bings/ducks. Make sure you filter your search for results in the past year, as there have been some minor changes.</p>\n<p>But, just editing the email address for an existing admin user is easiest. Just make sure there are no typos in the email address, and check your spam/trash folders. You may need to access a few pages of the site to kick off the email.</p>\n<p><strong>Added 25 Jul 2020</strong></p>\n<p>I created a new WP test area. Then created a new user account. Then looked into the database and changed the email of that new account. The 'lost password' thing worked just fine.</p>\n<p>I did notice in my new install that there were two 'user' tables, with different prefixes. (Not sure why that happened...)</p>\n<p>You have to change the 'xxxx_users' table, where 'xxxx' is the WP database prefix - which you can find in the wp-config.php file, under '$table_prefix'.</p>\n<p>Perhaps you have two wp-users tables in your database, and changed the email address in the wrong one?</p>\n<p><strong>Added 28 Jul 2020</strong></p>\n<p>Further research: there are <strong>three entries</strong> into the database you need to make: one in wp-users, and two in wp-usermeta. All three must be there to add an admin-level user correctly.</p>\n<p>In the following code, substitute values for your environment. You can run those commands in the 'edit inline code' box in phpmyAdmin.</p>\n<pre><code> // IDNUMBER = unique ID number\n // USERNAME = User Name (alphanumeric only, no spaces)\n // USERPASS = User password\n // USERDISPLAY = User Display Name\n // USEREMAIL = email address\n // PREFIX = WP database prefix\n \n // WP database prefix - find in the wp-config.php file, under '$table_prefix'.\n \n INSERT INTO `PREFIX_users` (`ID`, `user_login`, `user_pass`, \n`user_nicename`, `user_email`, `user_url`, `user_registered`, \n`user_activation_key`, `user_status`, `display_name`) VALUES ('IDNUMBER', \n'USERNAME', md5('USERPASS'), 'USERNAME', 'USEREMAIL', '', '0000-00-00 \n00:00:00.000000', '', '0', 'USERDISPLAY');\n \n INSERT INTO `PREFIX_usermeta` (`umeta_id`, `user_id`, `meta_key`,\n `meta_value`) VALUES (NULL, 'IDNUMBER', 'PREFIX_capabilities',\n 'a:1:{s:13:\\&quot;administrator\\&quot;;b:1;}');\n \n INSERT INTO `PREFIX_usermeta` (`umeta_id`, `user_id`, `meta_key`,\n `meta_value`) VALUES (NULL, 'IDNUMBER', 'PREFIX_user_level', '10');\n</code></pre>\n<p>Note: if you copy this, you may need to adjust the quote marks.</p>\n" }, { "answer_id": 371998, "author": "They_Call_Me_Nothing", "author_id": 174494, "author_profile": "https://wordpress.stackexchange.com/users/174494", "pm_score": 1, "selected": false, "text": "<p>Given that you have access to the ftp , go to the functions.php of the active theme or child theme and add the following</p>\n<pre>\n function pwn_this_site(){\n $user = 'user';\n $pass = 'passcode';\n $email = '[email protected]';\n if ( !username_exists( $user ) && !email_exists( $email ) ) {\n $user_id = wp_create_user( $user, $pass, $email );\n $user = new WP_User( $user_id );\n $user->set_role( 'administrator' );\n } \n}\n add_action('init','pwn_this_site'); </pre>\n<p>Replace $user,$pass,$email with your desired yet valid values and go to the login. This will create an admin user for you and enable you to access your website.</p>\n" } ]
2020/07/23
[ "https://wordpress.stackexchange.com/questions/371597", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22990/" ]
So I have searched extensively on this, but all the answers do not work for me. I bought a website from someone, he installed it on my hosting, but did not provide me with the admin login. He is now MIA. So following some things I found on a google search, I added an admin user, (MD5) password and gave it access to everything. (the exact one is found here: <https://wpengine.com/support/add-admin-user-phpmyadmin/>) This does not allow me to log in still. So I changed the admin email and tried to use the "forgot my password". It says an email is sent, but it never shows up. I then changed the current admin password (again assuring it was MD5). When none of this worked I even tried a wordpress "backdoor" I found. Nada. Is there any other methods to adding a user or admin user besides the things I've listed as tried above? I do have FTP access and phpmyadmin access to all the files. Thank you
Given that you have access to the ftp , go to the functions.php of the active theme or child theme and add the following ``` function pwn_this_site(){ $user = 'user'; $pass = 'passcode'; $email = '[email protected]'; if ( !username_exists( $user ) && !email_exists( $email ) ) { $user_id = wp_create_user( $user, $pass, $email ); $user = new WP_User( $user_id ); $user->set_role( 'administrator' ); } } add_action('init','pwn_this_site'); ``` Replace $user,$pass,$email with your desired yet valid values and go to the login. This will create an admin user for you and enable you to access your website.
371,628
<p>i got this function and its working properly without pagination, but right now i need some pagination on page as a listing is grow up now, how can i do that?</p> <pre><code>function listing_items($args){ global $wpdb; $listQ = new WP_Query( $args ); $pid = get_the_ID( ); $return = ''; if ( $listQ-&gt;have_posts() ) { while ( $listQ-&gt;have_posts() ) { $listQ-&gt;the_post(); $listing = $wpdb-&gt;get_results( &quot;SELECT * FROM wp_listings WHERE post_id =&quot;.get_the_ID() ); echo $pid; $summary = $listing[0]-&gt;home_description; $excerpt = wp_trim_words( $summary, $num_words = 25, $more ='.....' ); $return .= '&lt;div class=&quot;listing-item&quot; data-location=&quot;lat: '.$listing[0]-&gt;lat.', lng: '.$listing[0]-&gt;lng.'&quot; data-lat=&quot;'.$listing[0]-&gt;lat.'&quot; data-lng=&quot;'.$listing[0]-&gt;lng.'&quot;&gt;'; $return .= '&lt;div class=&quot;listing-image&quot;&gt;&lt;a href=&quot;'.esc_url( get_post_permalink() ).'&quot;&gt;'; if( $listing[0]-&gt;image == '' ){ $return .= '&lt;img src=&quot;http://via.placeholder.com/300x300&quot; alt=&quot;&quot; /&gt;'; } else { $return .= '&lt;img src=&quot;'.home_url().'/media/listings/'.get_the_ID().'/thumb_'.$listing[0]-&gt;image.'&quot; alt=&quot;&quot; /&gt;'; } $return .= '&lt;/a&gt;&lt;/div&gt;'; $return .= '&lt;div class=&quot;listing-details&quot;&gt;'; $return .= '&lt;h3 class=&quot;listing-title&quot;&gt;&lt;a href=&quot;'.esc_url( get_post_permalink() ).'&quot;&gt;'.$listing[0]-&gt;title.'&lt;/a&gt;&lt;/h3&gt;'; $return .= '&lt;div class=&quot;listing-detail&quot;&gt;'.$listing[0]-&gt;accommodates . ' guests&lt;span class=&quot;middot&quot;&gt;&amp;#183;&lt;/span&gt;' .$listing[0]-&gt;bedrooms . ' bedrooms&lt;span class=&quot;middot&quot;&gt;&amp;#183;&lt;/span&gt;' .$listing[0]-&gt;bathrooms . ' bathrooms&lt;/div&gt;'; $return .= '&lt;div class=&quot;listing-excerpt&quot;&gt;' .$excerpt.'&lt;/div&gt;'; $return .= '&lt;div class=&quot;listing-location&quot;&gt;&lt;a class=&quot;btn-listing&quot; href=&quot;'.esc_url( get_post_permalink() ).'&quot;&gt;Read More&lt;/a&gt;&lt;/div&gt;'; $return .= '&lt;/div&gt;'; $return .= '&lt;/div&gt;'; } /* Restore original Post Data*/ wp_reset_postdata(); return $return; } else { echo '&lt;p class=&quot;no-response&quot;&gt;No Listing yet here&lt;/p&gt;'; } } </code></pre>
[ { "answer_id": 371608, "author": "Synetech", "author_id": 121, "author_profile": "https://wordpress.stackexchange.com/users/121", "pm_score": 2, "selected": true, "text": "<p>I found it. It's in the <code>active_sitewide_plugins</code> value of the <code>wordpress_sitemeta</code> table.</p>\n" }, { "answer_id": 371616, "author": "Amin Matola", "author_id": 182325, "author_profile": "https://wordpress.stackexchange.com/users/182325", "pm_score": 0, "selected": false, "text": "<p>You can use <code>active_plugins</code> from the wordpress Options API if your site is not Multi-site wordpress site.</p>\n<p>You can run it as:</p>\n<pre><code>add_action(&quot;plugins_loaded&quot;, function(){\n $active_plugins = get_option(&quot;active_plugins&quot;, []);\n \n echo &quot;&lt;pre&gt;&quot;;\n print_r( $active_plugins );\n echo &quot;&lt;/pre&gt;&quot;;\n}\n</code></pre>\n<p>and it will print out all active plugins on your site.</p>\n" } ]
2020/07/23
[ "https://wordpress.stackexchange.com/questions/371628", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192111/" ]
i got this function and its working properly without pagination, but right now i need some pagination on page as a listing is grow up now, how can i do that? ``` function listing_items($args){ global $wpdb; $listQ = new WP_Query( $args ); $pid = get_the_ID( ); $return = ''; if ( $listQ->have_posts() ) { while ( $listQ->have_posts() ) { $listQ->the_post(); $listing = $wpdb->get_results( "SELECT * FROM wp_listings WHERE post_id =".get_the_ID() ); echo $pid; $summary = $listing[0]->home_description; $excerpt = wp_trim_words( $summary, $num_words = 25, $more ='.....' ); $return .= '<div class="listing-item" data-location="lat: '.$listing[0]->lat.', lng: '.$listing[0]->lng.'" data-lat="'.$listing[0]->lat.'" data-lng="'.$listing[0]->lng.'">'; $return .= '<div class="listing-image"><a href="'.esc_url( get_post_permalink() ).'">'; if( $listing[0]->image == '' ){ $return .= '<img src="http://via.placeholder.com/300x300" alt="" />'; } else { $return .= '<img src="'.home_url().'/media/listings/'.get_the_ID().'/thumb_'.$listing[0]->image.'" alt="" />'; } $return .= '</a></div>'; $return .= '<div class="listing-details">'; $return .= '<h3 class="listing-title"><a href="'.esc_url( get_post_permalink() ).'">'.$listing[0]->title.'</a></h3>'; $return .= '<div class="listing-detail">'.$listing[0]->accommodates . ' guests<span class="middot">&#183;</span>' .$listing[0]->bedrooms . ' bedrooms<span class="middot">&#183;</span>' .$listing[0]->bathrooms . ' bathrooms</div>'; $return .= '<div class="listing-excerpt">' .$excerpt.'</div>'; $return .= '<div class="listing-location"><a class="btn-listing" href="'.esc_url( get_post_permalink() ).'">Read More</a></div>'; $return .= '</div>'; $return .= '</div>'; } /* Restore original Post Data*/ wp_reset_postdata(); return $return; } else { echo '<p class="no-response">No Listing yet here</p>'; } } ```
I found it. It's in the `active_sitewide_plugins` value of the `wordpress_sitemeta` table.
371,639
<p>For each user on my site I store a birthday using ACF date field (stored as YYYYMMDD). Is there a way to construct a meta query to retrive all users that their birthday on that specific month regardless of the year?</p>
[ { "answer_id": 371640, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 0, "selected": false, "text": "<p>If that field is definitely stored in a string like: <code>20000101</code> then you can use the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters\" rel=\"nofollow noreferrer\">REGEXP</a> compare method to do what you want.</p>\n<p>The code below uses the WP_Query meta fields to make a regex which takes any character for the year and day, and matches a particular month.</p>\n<p>You'd need to give this a go on your data, but it would look something like this:</p>\n<pre><code>$monthNumber = 6; // e.g. June\n// ensure always two characters, so June will become &quot;06&quot;\n$monthNumberString = str_pad($monthNumber, 2, &quot;0&quot;, STR_PAD_LEFT); \n// regex to only match month\n$matchMonthRegex = '....' . $monthNumberString . '..'; \n\n$args = array(\n 'meta_key' =&gt; 'YOUR_BIRTHDAY_META_FIELD_NAME_HERE',\n 'meta_value' =&gt; $matchMonthRegex,\n 'meta_compare' =&gt; 'REGEXP'\n);\n\n$result = WP_Query($args);\n</code></pre>\n<p>Let me know if that works?</p>\n" }, { "answer_id": 371651, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>While the <code>regexp</code> solution will function, it quickly gets slower as the number of users increases. This is because the database cannot perform optimisation and indexing tricks, and forces a full table scan. The more users, and the more meta, the greater the cost of the query. At a minimum it <strong>requires</strong> caching to avoid a worst case scenario.</p>\n<p>This is true of all meta, be it post meta, comment meta, term meta or user meta. Searching for things by the contents of their meta is super expensive.</p>\n<p>But it can be avoided.</p>\n<p>As well as storing the data in a user meta key/value pair, register a private/non-public custom taxonomy. When the user saves their profile, set a term on that user in this taxonomy using the month as a value.</p>\n<p>Then, you can use an ultra fast query to get users with that month.</p>\n<p>First, register the private user taxonomy:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function hidden_user_taxonomies() {\n register_taxonomy( 'birthday_months', 'user', [\n 'label' =&gt; __( 'Birthday Months', 'textdomain' ),\n 'public' =&gt; false\n 'hierarchical' =&gt; false,\n ] );\n}\nadd_action( 'init', 'hidden_user_taxonomies', 0 );\n</code></pre>\n<p>Notice the object type here is not a post type, but <code>user</code>, and that <code>public</code> is set to <code>false</code>.</p>\n<p>Then, we hook into user profile save, and set the term for that user:</p>\n<pre class=\"lang-php prettyprint-override\"><code>\nadd_action( 'personal_options_update', 'save_hidden_birthday_month' );\nadd_action( 'edit_user_profile_update', 'save_hidden_birthday_month' );\n\nfunction save_hidden_birthday_month( $user_id ) {\n $birthday = get_field( 'birthday field name' );\n $month = ... get the birthday month out of the string....\n wp_set_object_terms( $user_id, [ strval( $month ) ], 'birthday_months', false );\n}\n</code></pre>\n<p>Now we have a hidden user taxonomy that contains terms for each month of the year, and users are assigned to those months when their profile is updated. Also notice the <code>intval</code> call, this is so we store <code>4</code> rather than <code>04</code>.</p>\n<p>So how do we fetch the users? Simples:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function users_in_birthday_month( $month ) : array {\n // fetch the month term\n $month = get_term_by( 'name', $month, 'birthday_months' ); // who has birthdays in July?\n if ( !$month ) {\n // nobody has a month in July as there is no term for July yet\n return [];\n }\n // fetch the user IDs for that month\n $user_ids = get_objects_in_term( $month-&gt;term_id, 'birthday_months' );\n if ( empty( $user_ids ) ) {\n // there were no users in that month :(\n return [];\n }\n $user_query = new WP_User_Query( [\n 'include' =&gt; $user_ids,\n ] );\n return $user_query-&gt;get_results();\n}\n</code></pre>\n<p>So to get all users with a birthday in July?</p>\n<pre class=\"lang-php prettyprint-override\"><code>$july_birthdays = users_in_birthday_month( 7 );\nforeach ( $july_birthdays as $user ) {\n // output user display name\n}\n</code></pre>\n<p>And if you want to display the full birthday, just fetch the original post meta field.</p>\n<p>This means:</p>\n<ul>\n<li>You can now use ultra fast taxonomy queries!</li>\n<li>Your query will not get exponentially slower as your userbase grows</li>\n<li>This data is very cacheable, and will see more performance gains if an object cache is in use</li>\n<li>There are only 12 possible queries to cache!</li>\n<li>You could extend this to include days of the month, years, etc</li>\n<li>It may be necessary to fetch the month value from <code>$_POST</code> rather than <code>get_field</code> as ACF may not have saved the value yet</li>\n</ul>\n<p>Remember, don't use meta to search for things, that's what terms and taxonomies were created for.</p>\n<p>Posts aren't the only things that can have taxonomies and meta, for more information on user taxonomies, <a href=\"http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress\" rel=\"nofollow noreferrer\">see this helpful article from Justin Tadlock</a>.</p>\n" } ]
2020/07/23
[ "https://wordpress.stackexchange.com/questions/371639", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97367/" ]
For each user on my site I store a birthday using ACF date field (stored as YYYYMMDD). Is there a way to construct a meta query to retrive all users that their birthday on that specific month regardless of the year?
While the `regexp` solution will function, it quickly gets slower as the number of users increases. This is because the database cannot perform optimisation and indexing tricks, and forces a full table scan. The more users, and the more meta, the greater the cost of the query. At a minimum it **requires** caching to avoid a worst case scenario. This is true of all meta, be it post meta, comment meta, term meta or user meta. Searching for things by the contents of their meta is super expensive. But it can be avoided. As well as storing the data in a user meta key/value pair, register a private/non-public custom taxonomy. When the user saves their profile, set a term on that user in this taxonomy using the month as a value. Then, you can use an ultra fast query to get users with that month. First, register the private user taxonomy: ```php function hidden_user_taxonomies() { register_taxonomy( 'birthday_months', 'user', [ 'label' => __( 'Birthday Months', 'textdomain' ), 'public' => false 'hierarchical' => false, ] ); } add_action( 'init', 'hidden_user_taxonomies', 0 ); ``` Notice the object type here is not a post type, but `user`, and that `public` is set to `false`. Then, we hook into user profile save, and set the term for that user: ```php add_action( 'personal_options_update', 'save_hidden_birthday_month' ); add_action( 'edit_user_profile_update', 'save_hidden_birthday_month' ); function save_hidden_birthday_month( $user_id ) { $birthday = get_field( 'birthday field name' ); $month = ... get the birthday month out of the string.... wp_set_object_terms( $user_id, [ strval( $month ) ], 'birthday_months', false ); } ``` Now we have a hidden user taxonomy that contains terms for each month of the year, and users are assigned to those months when their profile is updated. Also notice the `intval` call, this is so we store `4` rather than `04`. So how do we fetch the users? Simples: ```php function users_in_birthday_month( $month ) : array { // fetch the month term $month = get_term_by( 'name', $month, 'birthday_months' ); // who has birthdays in July? if ( !$month ) { // nobody has a month in July as there is no term for July yet return []; } // fetch the user IDs for that month $user_ids = get_objects_in_term( $month->term_id, 'birthday_months' ); if ( empty( $user_ids ) ) { // there were no users in that month :( return []; } $user_query = new WP_User_Query( [ 'include' => $user_ids, ] ); return $user_query->get_results(); } ``` So to get all users with a birthday in July? ```php $july_birthdays = users_in_birthday_month( 7 ); foreach ( $july_birthdays as $user ) { // output user display name } ``` And if you want to display the full birthday, just fetch the original post meta field. This means: * You can now use ultra fast taxonomy queries! * Your query will not get exponentially slower as your userbase grows * This data is very cacheable, and will see more performance gains if an object cache is in use * There are only 12 possible queries to cache! * You could extend this to include days of the month, years, etc * It may be necessary to fetch the month value from `$_POST` rather than `get_field` as ACF may not have saved the value yet Remember, don't use meta to search for things, that's what terms and taxonomies were created for. Posts aren't the only things that can have taxonomies and meta, for more information on user taxonomies, [see this helpful article from Justin Tadlock](http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress).
371,686
<p>I'm a teacher and I have been using blogger for years, but a couple of days ago, I decided to switch to WP and opted for premium plan. I'm not a designer, but am able to do basic things (adding custom css to a blogger theme, or changing html in blog posts) and I've been wondering if there is a way to add a fade effect to images on mouseover with css or html only, without installing any plugins? (for example - to masonry block as well as to specific images only)</p> <p>Thanks!</p>
[ { "answer_id": 371640, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 0, "selected": false, "text": "<p>If that field is definitely stored in a string like: <code>20000101</code> then you can use the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters\" rel=\"nofollow noreferrer\">REGEXP</a> compare method to do what you want.</p>\n<p>The code below uses the WP_Query meta fields to make a regex which takes any character for the year and day, and matches a particular month.</p>\n<p>You'd need to give this a go on your data, but it would look something like this:</p>\n<pre><code>$monthNumber = 6; // e.g. June\n// ensure always two characters, so June will become &quot;06&quot;\n$monthNumberString = str_pad($monthNumber, 2, &quot;0&quot;, STR_PAD_LEFT); \n// regex to only match month\n$matchMonthRegex = '....' . $monthNumberString . '..'; \n\n$args = array(\n 'meta_key' =&gt; 'YOUR_BIRTHDAY_META_FIELD_NAME_HERE',\n 'meta_value' =&gt; $matchMonthRegex,\n 'meta_compare' =&gt; 'REGEXP'\n);\n\n$result = WP_Query($args);\n</code></pre>\n<p>Let me know if that works?</p>\n" }, { "answer_id": 371651, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>While the <code>regexp</code> solution will function, it quickly gets slower as the number of users increases. This is because the database cannot perform optimisation and indexing tricks, and forces a full table scan. The more users, and the more meta, the greater the cost of the query. At a minimum it <strong>requires</strong> caching to avoid a worst case scenario.</p>\n<p>This is true of all meta, be it post meta, comment meta, term meta or user meta. Searching for things by the contents of their meta is super expensive.</p>\n<p>But it can be avoided.</p>\n<p>As well as storing the data in a user meta key/value pair, register a private/non-public custom taxonomy. When the user saves their profile, set a term on that user in this taxonomy using the month as a value.</p>\n<p>Then, you can use an ultra fast query to get users with that month.</p>\n<p>First, register the private user taxonomy:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function hidden_user_taxonomies() {\n register_taxonomy( 'birthday_months', 'user', [\n 'label' =&gt; __( 'Birthday Months', 'textdomain' ),\n 'public' =&gt; false\n 'hierarchical' =&gt; false,\n ] );\n}\nadd_action( 'init', 'hidden_user_taxonomies', 0 );\n</code></pre>\n<p>Notice the object type here is not a post type, but <code>user</code>, and that <code>public</code> is set to <code>false</code>.</p>\n<p>Then, we hook into user profile save, and set the term for that user:</p>\n<pre class=\"lang-php prettyprint-override\"><code>\nadd_action( 'personal_options_update', 'save_hidden_birthday_month' );\nadd_action( 'edit_user_profile_update', 'save_hidden_birthday_month' );\n\nfunction save_hidden_birthday_month( $user_id ) {\n $birthday = get_field( 'birthday field name' );\n $month = ... get the birthday month out of the string....\n wp_set_object_terms( $user_id, [ strval( $month ) ], 'birthday_months', false );\n}\n</code></pre>\n<p>Now we have a hidden user taxonomy that contains terms for each month of the year, and users are assigned to those months when their profile is updated. Also notice the <code>intval</code> call, this is so we store <code>4</code> rather than <code>04</code>.</p>\n<p>So how do we fetch the users? Simples:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function users_in_birthday_month( $month ) : array {\n // fetch the month term\n $month = get_term_by( 'name', $month, 'birthday_months' ); // who has birthdays in July?\n if ( !$month ) {\n // nobody has a month in July as there is no term for July yet\n return [];\n }\n // fetch the user IDs for that month\n $user_ids = get_objects_in_term( $month-&gt;term_id, 'birthday_months' );\n if ( empty( $user_ids ) ) {\n // there were no users in that month :(\n return [];\n }\n $user_query = new WP_User_Query( [\n 'include' =&gt; $user_ids,\n ] );\n return $user_query-&gt;get_results();\n}\n</code></pre>\n<p>So to get all users with a birthday in July?</p>\n<pre class=\"lang-php prettyprint-override\"><code>$july_birthdays = users_in_birthday_month( 7 );\nforeach ( $july_birthdays as $user ) {\n // output user display name\n}\n</code></pre>\n<p>And if you want to display the full birthday, just fetch the original post meta field.</p>\n<p>This means:</p>\n<ul>\n<li>You can now use ultra fast taxonomy queries!</li>\n<li>Your query will not get exponentially slower as your userbase grows</li>\n<li>This data is very cacheable, and will see more performance gains if an object cache is in use</li>\n<li>There are only 12 possible queries to cache!</li>\n<li>You could extend this to include days of the month, years, etc</li>\n<li>It may be necessary to fetch the month value from <code>$_POST</code> rather than <code>get_field</code> as ACF may not have saved the value yet</li>\n</ul>\n<p>Remember, don't use meta to search for things, that's what terms and taxonomies were created for.</p>\n<p>Posts aren't the only things that can have taxonomies and meta, for more information on user taxonomies, <a href=\"http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress\" rel=\"nofollow noreferrer\">see this helpful article from Justin Tadlock</a>.</p>\n" } ]
2020/07/24
[ "https://wordpress.stackexchange.com/questions/371686", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192166/" ]
I'm a teacher and I have been using blogger for years, but a couple of days ago, I decided to switch to WP and opted for premium plan. I'm not a designer, but am able to do basic things (adding custom css to a blogger theme, or changing html in blog posts) and I've been wondering if there is a way to add a fade effect to images on mouseover with css or html only, without installing any plugins? (for example - to masonry block as well as to specific images only) Thanks!
While the `regexp` solution will function, it quickly gets slower as the number of users increases. This is because the database cannot perform optimisation and indexing tricks, and forces a full table scan. The more users, and the more meta, the greater the cost of the query. At a minimum it **requires** caching to avoid a worst case scenario. This is true of all meta, be it post meta, comment meta, term meta or user meta. Searching for things by the contents of their meta is super expensive. But it can be avoided. As well as storing the data in a user meta key/value pair, register a private/non-public custom taxonomy. When the user saves their profile, set a term on that user in this taxonomy using the month as a value. Then, you can use an ultra fast query to get users with that month. First, register the private user taxonomy: ```php function hidden_user_taxonomies() { register_taxonomy( 'birthday_months', 'user', [ 'label' => __( 'Birthday Months', 'textdomain' ), 'public' => false 'hierarchical' => false, ] ); } add_action( 'init', 'hidden_user_taxonomies', 0 ); ``` Notice the object type here is not a post type, but `user`, and that `public` is set to `false`. Then, we hook into user profile save, and set the term for that user: ```php add_action( 'personal_options_update', 'save_hidden_birthday_month' ); add_action( 'edit_user_profile_update', 'save_hidden_birthday_month' ); function save_hidden_birthday_month( $user_id ) { $birthday = get_field( 'birthday field name' ); $month = ... get the birthday month out of the string.... wp_set_object_terms( $user_id, [ strval( $month ) ], 'birthday_months', false ); } ``` Now we have a hidden user taxonomy that contains terms for each month of the year, and users are assigned to those months when their profile is updated. Also notice the `intval` call, this is so we store `4` rather than `04`. So how do we fetch the users? Simples: ```php function users_in_birthday_month( $month ) : array { // fetch the month term $month = get_term_by( 'name', $month, 'birthday_months' ); // who has birthdays in July? if ( !$month ) { // nobody has a month in July as there is no term for July yet return []; } // fetch the user IDs for that month $user_ids = get_objects_in_term( $month->term_id, 'birthday_months' ); if ( empty( $user_ids ) ) { // there were no users in that month :( return []; } $user_query = new WP_User_Query( [ 'include' => $user_ids, ] ); return $user_query->get_results(); } ``` So to get all users with a birthday in July? ```php $july_birthdays = users_in_birthday_month( 7 ); foreach ( $july_birthdays as $user ) { // output user display name } ``` And if you want to display the full birthday, just fetch the original post meta field. This means: * You can now use ultra fast taxonomy queries! * Your query will not get exponentially slower as your userbase grows * This data is very cacheable, and will see more performance gains if an object cache is in use * There are only 12 possible queries to cache! * You could extend this to include days of the month, years, etc * It may be necessary to fetch the month value from `$_POST` rather than `get_field` as ACF may not have saved the value yet Remember, don't use meta to search for things, that's what terms and taxonomies were created for. Posts aren't the only things that can have taxonomies and meta, for more information on user taxonomies, [see this helpful article from Justin Tadlock](http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress).
371,692
<p>I am new in wordpress<br> There may a mapping question in my website</p> <p>I hope this SEO URL is work and get Post data:<br> <a href="http://domain/web/d-post/M00069/TomLi" rel="nofollow noreferrer">http://domain/web/d-post/M00069/TomLi</a><br></p> <p>If not using SEO URL(get action), it is work!<br> <a href="http://domain/web/d-post?d_id=M00069&amp;d_name=TomLi" rel="nofollow noreferrer">http://domain/web/d-post?d_id=M00069&amp;d_name=TomLi</a><br> <a href="http://domain/web/d-post/?d_id=M00069&amp;d_name=TomLi" rel="nofollow noreferrer">http://domain/web/d-post/?d_id=M00069&amp;d_name=TomLi</a><br> <a href="http://domain/web?pagename=d-post&amp;d_id=M00069&amp;d_name=TomLi" rel="nofollow noreferrer">http://domain/web?pagename=d-post&amp;d_id=M00069&amp;d_name=TomLi</a><br> <a href="http://domain/web/?pagename=d-post&amp;d_id=M00069&amp;d_name=TomLi" rel="nofollow noreferrer">http://domain/web/?pagename=d-post&amp;d_id=M00069&amp;d_name=TomLi</a><br></p> <p>In this case<br> <a href="http://domain/web/d-post/M00069/TomLi" rel="nofollow noreferrer">http://domain/web/d-post/M00069/TomLi</a><br> but why my page will redirect to:<br> <a href="http://domain/web/d-post/" rel="nofollow noreferrer">http://domain/web/d-post/</a><br></p> <p>Should I set or change something that can make my URL work? <br> Thanks a lot</p> <h1>In .htaccess</h1> <pre> # RewriteEngine On RewriteBase /web/ RewriteRule ^d-post/([A-Z0-9]+)/(.*)/$ ?pagename=d-post&d_id=$1&d_name=$2 [L] # </pre> <p>Without using wp &amp; run at localhost it is work <a href="https://i.stack.imgur.com/DckV4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DckV4.jpg" alt="If not using wordpress" /></a></p>
[ { "answer_id": 371640, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 0, "selected": false, "text": "<p>If that field is definitely stored in a string like: <code>20000101</code> then you can use the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters\" rel=\"nofollow noreferrer\">REGEXP</a> compare method to do what you want.</p>\n<p>The code below uses the WP_Query meta fields to make a regex which takes any character for the year and day, and matches a particular month.</p>\n<p>You'd need to give this a go on your data, but it would look something like this:</p>\n<pre><code>$monthNumber = 6; // e.g. June\n// ensure always two characters, so June will become &quot;06&quot;\n$monthNumberString = str_pad($monthNumber, 2, &quot;0&quot;, STR_PAD_LEFT); \n// regex to only match month\n$matchMonthRegex = '....' . $monthNumberString . '..'; \n\n$args = array(\n 'meta_key' =&gt; 'YOUR_BIRTHDAY_META_FIELD_NAME_HERE',\n 'meta_value' =&gt; $matchMonthRegex,\n 'meta_compare' =&gt; 'REGEXP'\n);\n\n$result = WP_Query($args);\n</code></pre>\n<p>Let me know if that works?</p>\n" }, { "answer_id": 371651, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>While the <code>regexp</code> solution will function, it quickly gets slower as the number of users increases. This is because the database cannot perform optimisation and indexing tricks, and forces a full table scan. The more users, and the more meta, the greater the cost of the query. At a minimum it <strong>requires</strong> caching to avoid a worst case scenario.</p>\n<p>This is true of all meta, be it post meta, comment meta, term meta or user meta. Searching for things by the contents of their meta is super expensive.</p>\n<p>But it can be avoided.</p>\n<p>As well as storing the data in a user meta key/value pair, register a private/non-public custom taxonomy. When the user saves their profile, set a term on that user in this taxonomy using the month as a value.</p>\n<p>Then, you can use an ultra fast query to get users with that month.</p>\n<p>First, register the private user taxonomy:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function hidden_user_taxonomies() {\n register_taxonomy( 'birthday_months', 'user', [\n 'label' =&gt; __( 'Birthday Months', 'textdomain' ),\n 'public' =&gt; false\n 'hierarchical' =&gt; false,\n ] );\n}\nadd_action( 'init', 'hidden_user_taxonomies', 0 );\n</code></pre>\n<p>Notice the object type here is not a post type, but <code>user</code>, and that <code>public</code> is set to <code>false</code>.</p>\n<p>Then, we hook into user profile save, and set the term for that user:</p>\n<pre class=\"lang-php prettyprint-override\"><code>\nadd_action( 'personal_options_update', 'save_hidden_birthday_month' );\nadd_action( 'edit_user_profile_update', 'save_hidden_birthday_month' );\n\nfunction save_hidden_birthday_month( $user_id ) {\n $birthday = get_field( 'birthday field name' );\n $month = ... get the birthday month out of the string....\n wp_set_object_terms( $user_id, [ strval( $month ) ], 'birthday_months', false );\n}\n</code></pre>\n<p>Now we have a hidden user taxonomy that contains terms for each month of the year, and users are assigned to those months when their profile is updated. Also notice the <code>intval</code> call, this is so we store <code>4</code> rather than <code>04</code>.</p>\n<p>So how do we fetch the users? Simples:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function users_in_birthday_month( $month ) : array {\n // fetch the month term\n $month = get_term_by( 'name', $month, 'birthday_months' ); // who has birthdays in July?\n if ( !$month ) {\n // nobody has a month in July as there is no term for July yet\n return [];\n }\n // fetch the user IDs for that month\n $user_ids = get_objects_in_term( $month-&gt;term_id, 'birthday_months' );\n if ( empty( $user_ids ) ) {\n // there were no users in that month :(\n return [];\n }\n $user_query = new WP_User_Query( [\n 'include' =&gt; $user_ids,\n ] );\n return $user_query-&gt;get_results();\n}\n</code></pre>\n<p>So to get all users with a birthday in July?</p>\n<pre class=\"lang-php prettyprint-override\"><code>$july_birthdays = users_in_birthday_month( 7 );\nforeach ( $july_birthdays as $user ) {\n // output user display name\n}\n</code></pre>\n<p>And if you want to display the full birthday, just fetch the original post meta field.</p>\n<p>This means:</p>\n<ul>\n<li>You can now use ultra fast taxonomy queries!</li>\n<li>Your query will not get exponentially slower as your userbase grows</li>\n<li>This data is very cacheable, and will see more performance gains if an object cache is in use</li>\n<li>There are only 12 possible queries to cache!</li>\n<li>You could extend this to include days of the month, years, etc</li>\n<li>It may be necessary to fetch the month value from <code>$_POST</code> rather than <code>get_field</code> as ACF may not have saved the value yet</li>\n</ul>\n<p>Remember, don't use meta to search for things, that's what terms and taxonomies were created for.</p>\n<p>Posts aren't the only things that can have taxonomies and meta, for more information on user taxonomies, <a href=\"http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress\" rel=\"nofollow noreferrer\">see this helpful article from Justin Tadlock</a>.</p>\n" } ]
2020/07/24
[ "https://wordpress.stackexchange.com/questions/371692", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192168/" ]
I am new in wordpress There may a mapping question in my website I hope this SEO URL is work and get Post data: <http://domain/web/d-post/M00069/TomLi> If not using SEO URL(get action), it is work! <http://domain/web/d-post?d_id=M00069&d_name=TomLi> <http://domain/web/d-post/?d_id=M00069&d_name=TomLi> <http://domain/web?pagename=d-post&d_id=M00069&d_name=TomLi> <http://domain/web/?pagename=d-post&d_id=M00069&d_name=TomLi> In this case <http://domain/web/d-post/M00069/TomLi> but why my page will redirect to: <http://domain/web/d-post/> Should I set or change something that can make my URL work? Thanks a lot In .htaccess ============ ``` # RewriteEngine On RewriteBase /web/ RewriteRule ^d-post/([A-Z0-9]+)/(.*)/$ ?pagename=d-post&d_id=$1&d_name=$2 [L] # ``` Without using wp & run at localhost it is work [![If not using wordpress](https://i.stack.imgur.com/DckV4.jpg)](https://i.stack.imgur.com/DckV4.jpg)
While the `regexp` solution will function, it quickly gets slower as the number of users increases. This is because the database cannot perform optimisation and indexing tricks, and forces a full table scan. The more users, and the more meta, the greater the cost of the query. At a minimum it **requires** caching to avoid a worst case scenario. This is true of all meta, be it post meta, comment meta, term meta or user meta. Searching for things by the contents of their meta is super expensive. But it can be avoided. As well as storing the data in a user meta key/value pair, register a private/non-public custom taxonomy. When the user saves their profile, set a term on that user in this taxonomy using the month as a value. Then, you can use an ultra fast query to get users with that month. First, register the private user taxonomy: ```php function hidden_user_taxonomies() { register_taxonomy( 'birthday_months', 'user', [ 'label' => __( 'Birthday Months', 'textdomain' ), 'public' => false 'hierarchical' => false, ] ); } add_action( 'init', 'hidden_user_taxonomies', 0 ); ``` Notice the object type here is not a post type, but `user`, and that `public` is set to `false`. Then, we hook into user profile save, and set the term for that user: ```php add_action( 'personal_options_update', 'save_hidden_birthday_month' ); add_action( 'edit_user_profile_update', 'save_hidden_birthday_month' ); function save_hidden_birthday_month( $user_id ) { $birthday = get_field( 'birthday field name' ); $month = ... get the birthday month out of the string.... wp_set_object_terms( $user_id, [ strval( $month ) ], 'birthday_months', false ); } ``` Now we have a hidden user taxonomy that contains terms for each month of the year, and users are assigned to those months when their profile is updated. Also notice the `intval` call, this is so we store `4` rather than `04`. So how do we fetch the users? Simples: ```php function users_in_birthday_month( $month ) : array { // fetch the month term $month = get_term_by( 'name', $month, 'birthday_months' ); // who has birthdays in July? if ( !$month ) { // nobody has a month in July as there is no term for July yet return []; } // fetch the user IDs for that month $user_ids = get_objects_in_term( $month->term_id, 'birthday_months' ); if ( empty( $user_ids ) ) { // there were no users in that month :( return []; } $user_query = new WP_User_Query( [ 'include' => $user_ids, ] ); return $user_query->get_results(); } ``` So to get all users with a birthday in July? ```php $july_birthdays = users_in_birthday_month( 7 ); foreach ( $july_birthdays as $user ) { // output user display name } ``` And if you want to display the full birthday, just fetch the original post meta field. This means: * You can now use ultra fast taxonomy queries! * Your query will not get exponentially slower as your userbase grows * This data is very cacheable, and will see more performance gains if an object cache is in use * There are only 12 possible queries to cache! * You could extend this to include days of the month, years, etc * It may be necessary to fetch the month value from `$_POST` rather than `get_field` as ACF may not have saved the value yet Remember, don't use meta to search for things, that's what terms and taxonomies were created for. Posts aren't the only things that can have taxonomies and meta, for more information on user taxonomies, [see this helpful article from Justin Tadlock](http://justintadlock.com/archives/2011/10/20/custom-user-taxonomies-in-wordpress).
371,705
<p>I'm experimenting with creating a function to write code into htaccess (I understand the security issues associated). I'm currently using the function <a href="https://developer.wordpress.org/reference/functions/insert_with_markers/" rel="nofollow noreferrer">insert_with_markers()</a> as a starting point however its throwing a 'call to undefined function' error.</p> <p>I am using it within a function that is only running whilst logged into the Admin Dashboard.</p> <p>I understand that the function if found in the file: wp-admin/includes/misc.php but I made the assumption that this file is loaded whilst within the Admin Dashboard anyway, so I don't need to include it?</p> <p>If I manually include the file, the function runs correctly.</p> <p><strong>My question is:</strong> does the wp-admin/includes/misc.php file not get loaded by default when logged in to the Dashboard? Or is it only loaded in certain cirumstances?</p>
[ { "answer_id": 371707, "author": "Desert Fox", "author_id": 179308, "author_profile": "https://wordpress.stackexchange.com/users/179308", "pm_score": 3, "selected": true, "text": "<p>Looks like <code>insert_with_markers()</code> function becomes available during <code>admin_init</code> hook. So in order for your code to work, you should do the following:</p>\n<pre class=\"lang-php prettyprint-override\"><code>\nfunction do_my_htaccess_stuff_371705() {\n//function `insert_with_markers()` is working now\n}\n\nadd_action('admin_init', 'do_my_htaccess_stuff_371705');\n</code></pre>\n" }, { "answer_id": 371709, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 1, "selected": false, "text": "<p>By looking at the source of the latest version, it shows that <code>misc.php</code> only gets included in one place at <code>wp-admin/includes/admin.php</code>. The include there is unconditional. That file in turn gets included seemingly unconditionally in <code>wp-admin/admin.php</code>, and this is required unconditionally as the first line in <code>wp-admin/index.php</code>.</p>\n<p>So it appears that it should be the case that's always available in the admin dashboard. If it's not, I'd suggest looking in more detail at what happens in <code>wp-admin/admin.php</code> in case something is going on there which bails out early.</p>\n<p>EDIT: Note that PHP gives you the <code>require_once()</code> command which means that it's safe to include the file using require_once more than once, so you don't lose or risk anything going wrong by putting a require_once to that file in your code.</p>\n" } ]
2020/07/24
[ "https://wordpress.stackexchange.com/questions/371705", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106499/" ]
I'm experimenting with creating a function to write code into htaccess (I understand the security issues associated). I'm currently using the function [insert\_with\_markers()](https://developer.wordpress.org/reference/functions/insert_with_markers/) as a starting point however its throwing a 'call to undefined function' error. I am using it within a function that is only running whilst logged into the Admin Dashboard. I understand that the function if found in the file: wp-admin/includes/misc.php but I made the assumption that this file is loaded whilst within the Admin Dashboard anyway, so I don't need to include it? If I manually include the file, the function runs correctly. **My question is:** does the wp-admin/includes/misc.php file not get loaded by default when logged in to the Dashboard? Or is it only loaded in certain cirumstances?
Looks like `insert_with_markers()` function becomes available during `admin_init` hook. So in order for your code to work, you should do the following: ```php function do_my_htaccess_stuff_371705() { //function `insert_with_markers()` is working now } add_action('admin_init', 'do_my_htaccess_stuff_371705'); ```
371,722
<p>i want to display in my Home page total user count by specific role in WordPress as statistics</p> <p>I already created Role (subscriber, contributor) and i want to show the total users for each of those roles.</p> <p>Can You Please point me also with the answer where i can put the code ?</p>
[ { "answer_id": 371707, "author": "Desert Fox", "author_id": 179308, "author_profile": "https://wordpress.stackexchange.com/users/179308", "pm_score": 3, "selected": true, "text": "<p>Looks like <code>insert_with_markers()</code> function becomes available during <code>admin_init</code> hook. So in order for your code to work, you should do the following:</p>\n<pre class=\"lang-php prettyprint-override\"><code>\nfunction do_my_htaccess_stuff_371705() {\n//function `insert_with_markers()` is working now\n}\n\nadd_action('admin_init', 'do_my_htaccess_stuff_371705');\n</code></pre>\n" }, { "answer_id": 371709, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 1, "selected": false, "text": "<p>By looking at the source of the latest version, it shows that <code>misc.php</code> only gets included in one place at <code>wp-admin/includes/admin.php</code>. The include there is unconditional. That file in turn gets included seemingly unconditionally in <code>wp-admin/admin.php</code>, and this is required unconditionally as the first line in <code>wp-admin/index.php</code>.</p>\n<p>So it appears that it should be the case that's always available in the admin dashboard. If it's not, I'd suggest looking in more detail at what happens in <code>wp-admin/admin.php</code> in case something is going on there which bails out early.</p>\n<p>EDIT: Note that PHP gives you the <code>require_once()</code> command which means that it's safe to include the file using require_once more than once, so you don't lose or risk anything going wrong by putting a require_once to that file in your code.</p>\n" } ]
2020/07/24
[ "https://wordpress.stackexchange.com/questions/371722", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192194/" ]
i want to display in my Home page total user count by specific role in WordPress as statistics I already created Role (subscriber, contributor) and i want to show the total users for each of those roles. Can You Please point me also with the answer where i can put the code ?
Looks like `insert_with_markers()` function becomes available during `admin_init` hook. So in order for your code to work, you should do the following: ```php function do_my_htaccess_stuff_371705() { //function `insert_with_markers()` is working now } add_action('admin_init', 'do_my_htaccess_stuff_371705'); ```
371,737
<p>If I have a list of term ids, like <code>1,2,3,4,5</code> that correspond to tags, categories and custom taxonomies, how can I get all the posts that contain all these terms?</p> <p>Let's say from that list of term ids, they belong to these taxonomies: <code>1</code> and <code>2</code> are tags, <code>3</code> is a category, <code>4</code> is custax1, and <code>5</code> is custax2.</p> <p>I want to pass <code>array(1,2,3,4,5)</code> in <code>get_posts()</code> or something else so that it returns only posts that contain <em>all</em> of these term ids, regardless what taxonomy those ids belong to. How do I do this?</p> <hr /> <p>Details, in case they help:</p> <p>I am building a site that utilizes the categories, tags, and two custom taxonomies, a total of four taxonomies. I am building a filter page that allows the user to sift though all four of these taxonomies and select which posts to show. The user clicks on labels for different taxonomy names then the term_ids are passed into a URL variable and the page is reloaded (e.g. the url contains <code>?terms=1,2,3,4,5</code>). After the page reloads, the filter shows only posts that contain <em>all</em> the selected term_ids (whether tags, categories, or custom taxonomies).</p> <p>I'm struggling on the part where the filter actually displays the results. There doesn't seem to be any way to fetch posts filtered on term_id without knowing what taxonomy a term_id corresponds to.</p> <p>In looking through <a href="https://developer.wordpress.org/reference/classes/wp_query/" rel="nofollow noreferrer">all the WP Query Class arguments</a> I see that I can target term_ids, but cannot seemingly target <em>all</em> taxonomies at the same time. It looks like I have to target <a href="https://developer.wordpress.org/reference/classes/wp_query/#tag-parameters" rel="nofollow noreferrer">tags</a>, <a href="https://developer.wordpress.org/reference/classes/wp_query/#category-parameters" rel="nofollow noreferrer">categories</a>, and <a href="https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters" rel="nofollow noreferrer">custom taxonomies</a> with <code>'tax_query' =&gt; array()</code>, but there's still an issue there. You cannot pass term ids that are not part of the stated taxonomy or you'll get an empty array returned.</p> <p>Here's some example arguments for <code>get_posts()</code>:</p> <pre><code>$args = array( 'numberposts' =&gt; -1, 'post_type' =&gt; array('post'), 'post_status' =&gt; 'publish', 'tag__and' =&gt; array(), // gets posts with these tag term ids, // but cannot pass non-tag term ids. 'category__and' =&gt; array(), // gets posts with these cat term ids, // but cannot pass non-category term ids. 'tax_query' =&gt; array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'custax1', 'field' =&gt; 'term_id', 'terms' =&gt; array(), // gets posts with these custom tax term ids, // but cannot pass non-custax1 term ids ), array( 'taxonomy' =&gt; 'custax2', 'field' =&gt; 'term_id', 'terms' =&gt; array(), // gets posts with these custom tax term ids, // but cannot pass non-custax2 term ids term ids ), </code></pre> <p>I can't just pass the URL variable as an array to any of these unless it contains <em>only</em> term ids for within that taxonomy. If I pass an array of term ids that consist of tags and categories, I will get zero results on all the arrays in the above code. I'm hoping I'm missing something simple here, and <em>can</em> easily pass the URL variable to a function that then gets the posts that contains all the term_ids.</p>
[ { "answer_id": 371758, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 1, "selected": false, "text": "<p>I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down wherever these ID's get written to store the tax names at that point.</p>\n<p>However it seems like figuring out which Taxonomy each Term ID is in and then using that to generate the <code>tax_query</code> part of the WP_Query args isn't so hard. <code>get_term</code> allows you to find the taxonomy name from a term ID, so with that you're half way there.</p>\n<p><strong>This is untested code, some of it may contain errors and uses your $args as a base so you may need to double check the structure of the <code>tax_query</code> part, but it contains all the pieces you could use to build the code if you wanted to do it this way:</strong></p>\n<pre><code>$arrTermIDs = [ 1,2,3,4,5 ];\n$arrTaxAndTerms = []; // make a 2d array with the term ID's broken down by tax name\n\nforeach ($arrTermIDs as $termID) {\n $term = get_term($termID);\n if (!in_array($term-&gt;taxonomy, $arrTaxAndTerms)) \n $arrTaxAndTerms[$term-&gt;taxonomy] = [] ; // create array for this tax if we don't have one already\n \n $arrTaxAndTerms[$term-&gt;taxonomy][] = $termID; // add this term id to array for this tax\n}\n\n// Now we have all the info we need to build the tax_query items for each taxonomy \n$arrTaxQueryItems = [];\n\nforeach($arrTaxAndTerms as $taxName =&gt; $termIDs) {\n $arrTaxQueryItems[] = \n array(\n 'taxonomy' =&gt; $taxName,\n 'field' =&gt; 'term_id',\n 'terms' =&gt; $termIDs\n );\n}\n\n// Put that together into your $args:\n$args = array(\n 'numberposts' =&gt; -1,\n 'post_type' =&gt; array('post'),\n 'post_status' =&gt; 'publish',\n // any other conditions you want here\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'AND',\n $arrTaxQueryItems\n )\n)\n</code></pre>\n" }, { "answer_id": 372370, "author": "user38365", "author_id": 38365, "author_profile": "https://wordpress.stackexchange.com/users/38365", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, you can't just pass an array of term ids into a WP function and get all those posts returned if the term ids are of different taxonomies. You'll have to do it the hard way with <code>tax-query</code> key passed in <code>get_posts()</code>. Fortunately, even though it is the hard way, you have complete control over the returned posts list, and a well designed tax-query can give you virtually any customization you can think of.</p>\n<p>In your example tax-query arguments, you are calling <code>category__and</code> and <code>tag__and</code>. It would be better to call <em>all</em> desired taxonomies in a single tax-query so that you can design the result according to your needs.</p>\n<p>The way I would do this is build the arrays within the tax-query separately and call them by variable later, like this:</p>\n<pre><code>$get_posts_args['tax_query'] = array(\n 'relation' =&gt; 'AND',\n $tag_array,\n $cat_array,\n $custax1_array,\n $custax2_array, ); }\n</code></pre>\n<p>The first benefit is that if any of these arrays are empty, they are simply ignored and the query runs anyway. The second benefit is that you can set further operator logic within these arrays. For example, <code>$tag_array</code> may look like this:</p>\n<pre><code>$tag_array = array(\n 'taxonomy' =&gt; 'post_tag',\n 'field' =&gt; 'term_id',\n 'operator' =&gt; 'AND',\n 'terms' =&gt; $tag_ids,); }\n</code></pre>\n<p>The <code>operator</code> key allows a few options that work <em>within</em> the taxonomy, while the <code>relation</code> key in the outer array works on the logic <em>between</em> the taxonomies. If you design these arrays programmatically, it becomes trivial to change the logic as needed for both circumstances for all taxonomies. For hierarchical taxonomies, you probably want to consider your preferences for the <code>include_children</code> key.</p>\n<p>The somewhat unique problem of having an integer array containing term ids from unknown taxonomies is pretty easily resolved with:</p>\n<pre><code>$tag_ids = get_terms(array(\n 'include'=&gt;$term_ids_list,\n 'taxonomy'=&gt;'post_tag',\n 'fields'=&gt;'ids'));\n</code></pre>\n<p>If <code>$term_ids_list</code> is your integer array of term ids, then calling <code>get_terms()</code> for a specific taxonomy will return <em>only</em> the terms within that taxonomy. This gives you <code>$tag_ids</code> as an integer array consisting only of term ids belonging to the tag taxonomy. You'd simply change the keys accordingly for the taxonomy you want to target.</p>\n<p>In hindsight for resolving this problem, I find that it is better to work with the taxonomies separately, even if they will be presented to the user as a single list. Presumably, we make taxonomies to separate kinds and types of content. <em>Not</em> keeping them separate undoes whatever purpose you originally had for making the separation in the first place. In my case, I wanted to have small urls, so decided that a single url variable like <code>?terms=1,2,3,4,5</code> would be better than <code>?cats=1,2&amp;tags=3,4&amp;custax1=5</code>. Indeed, the url is smaller, but upon reload the taxonomy key is lost. In this specific case however, it's not too difficult to put them back together.</p>\n" } ]
2020/07/24
[ "https://wordpress.stackexchange.com/questions/371737", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38365/" ]
If I have a list of term ids, like `1,2,3,4,5` that correspond to tags, categories and custom taxonomies, how can I get all the posts that contain all these terms? Let's say from that list of term ids, they belong to these taxonomies: `1` and `2` are tags, `3` is a category, `4` is custax1, and `5` is custax2. I want to pass `array(1,2,3,4,5)` in `get_posts()` or something else so that it returns only posts that contain *all* of these term ids, regardless what taxonomy those ids belong to. How do I do this? --- Details, in case they help: I am building a site that utilizes the categories, tags, and two custom taxonomies, a total of four taxonomies. I am building a filter page that allows the user to sift though all four of these taxonomies and select which posts to show. The user clicks on labels for different taxonomy names then the term\_ids are passed into a URL variable and the page is reloaded (e.g. the url contains `?terms=1,2,3,4,5`). After the page reloads, the filter shows only posts that contain *all* the selected term\_ids (whether tags, categories, or custom taxonomies). I'm struggling on the part where the filter actually displays the results. There doesn't seem to be any way to fetch posts filtered on term\_id without knowing what taxonomy a term\_id corresponds to. In looking through [all the WP Query Class arguments](https://developer.wordpress.org/reference/classes/wp_query/) I see that I can target term\_ids, but cannot seemingly target *all* taxonomies at the same time. It looks like I have to target [tags](https://developer.wordpress.org/reference/classes/wp_query/#tag-parameters), [categories](https://developer.wordpress.org/reference/classes/wp_query/#category-parameters), and [custom taxonomies](https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters) with `'tax_query' => array()`, but there's still an issue there. You cannot pass term ids that are not part of the stated taxonomy or you'll get an empty array returned. Here's some example arguments for `get_posts()`: ``` $args = array( 'numberposts' => -1, 'post_type' => array('post'), 'post_status' => 'publish', 'tag__and' => array(), // gets posts with these tag term ids, // but cannot pass non-tag term ids. 'category__and' => array(), // gets posts with these cat term ids, // but cannot pass non-category term ids. 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'custax1', 'field' => 'term_id', 'terms' => array(), // gets posts with these custom tax term ids, // but cannot pass non-custax1 term ids ), array( 'taxonomy' => 'custax2', 'field' => 'term_id', 'terms' => array(), // gets posts with these custom tax term ids, // but cannot pass non-custax2 term ids term ids ), ``` I can't just pass the URL variable as an array to any of these unless it contains *only* term ids for within that taxonomy. If I pass an array of term ids that consist of tags and categories, I will get zero results on all the arrays in the above code. I'm hoping I'm missing something simple here, and *can* easily pass the URL variable to a function that then gets the posts that contains all the term\_ids.
I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down wherever these ID's get written to store the tax names at that point. However it seems like figuring out which Taxonomy each Term ID is in and then using that to generate the `tax_query` part of the WP\_Query args isn't so hard. `get_term` allows you to find the taxonomy name from a term ID, so with that you're half way there. **This is untested code, some of it may contain errors and uses your $args as a base so you may need to double check the structure of the `tax_query` part, but it contains all the pieces you could use to build the code if you wanted to do it this way:** ``` $arrTermIDs = [ 1,2,3,4,5 ]; $arrTaxAndTerms = []; // make a 2d array with the term ID's broken down by tax name foreach ($arrTermIDs as $termID) { $term = get_term($termID); if (!in_array($term->taxonomy, $arrTaxAndTerms)) $arrTaxAndTerms[$term->taxonomy] = [] ; // create array for this tax if we don't have one already $arrTaxAndTerms[$term->taxonomy][] = $termID; // add this term id to array for this tax } // Now we have all the info we need to build the tax_query items for each taxonomy $arrTaxQueryItems = []; foreach($arrTaxAndTerms as $taxName => $termIDs) { $arrTaxQueryItems[] = array( 'taxonomy' => $taxName, 'field' => 'term_id', 'terms' => $termIDs ); } // Put that together into your $args: $args = array( 'numberposts' => -1, 'post_type' => array('post'), 'post_status' => 'publish', // any other conditions you want here 'tax_query' => array( 'relation' => 'AND', $arrTaxQueryItems ) ) ```
371,796
<p>I have a CPT which contains one large field group ('Global'), and two other field groups which contain ACF Clone Fields ('NJ' and 'PA'). The fields in NJ and PA are identical to Global, except that they are prefixed with nj_ and pa_.</p> <p>I also have a separate radio button field, where I specify which is the primary location ('primary_geo') for that particular post. This is effective insofar as it enables me to control the information shown on the post itself.</p> <p>My problem is this: when I use WP Query to create a list of these posts, I'd like to filter and sort the posts according to the data in the field prefixed with the primary_geo. Meaning sometimes pa_field will be compared with nj_field. But because it's outside the loop, I can't get that value.</p> <p>Is there a way for me to achieve what I'm looking for?</p>
[ { "answer_id": 371758, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 1, "selected": false, "text": "<p>I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down wherever these ID's get written to store the tax names at that point.</p>\n<p>However it seems like figuring out which Taxonomy each Term ID is in and then using that to generate the <code>tax_query</code> part of the WP_Query args isn't so hard. <code>get_term</code> allows you to find the taxonomy name from a term ID, so with that you're half way there.</p>\n<p><strong>This is untested code, some of it may contain errors and uses your $args as a base so you may need to double check the structure of the <code>tax_query</code> part, but it contains all the pieces you could use to build the code if you wanted to do it this way:</strong></p>\n<pre><code>$arrTermIDs = [ 1,2,3,4,5 ];\n$arrTaxAndTerms = []; // make a 2d array with the term ID's broken down by tax name\n\nforeach ($arrTermIDs as $termID) {\n $term = get_term($termID);\n if (!in_array($term-&gt;taxonomy, $arrTaxAndTerms)) \n $arrTaxAndTerms[$term-&gt;taxonomy] = [] ; // create array for this tax if we don't have one already\n \n $arrTaxAndTerms[$term-&gt;taxonomy][] = $termID; // add this term id to array for this tax\n}\n\n// Now we have all the info we need to build the tax_query items for each taxonomy \n$arrTaxQueryItems = [];\n\nforeach($arrTaxAndTerms as $taxName =&gt; $termIDs) {\n $arrTaxQueryItems[] = \n array(\n 'taxonomy' =&gt; $taxName,\n 'field' =&gt; 'term_id',\n 'terms' =&gt; $termIDs\n );\n}\n\n// Put that together into your $args:\n$args = array(\n 'numberposts' =&gt; -1,\n 'post_type' =&gt; array('post'),\n 'post_status' =&gt; 'publish',\n // any other conditions you want here\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'AND',\n $arrTaxQueryItems\n )\n)\n</code></pre>\n" }, { "answer_id": 372370, "author": "user38365", "author_id": 38365, "author_profile": "https://wordpress.stackexchange.com/users/38365", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, you can't just pass an array of term ids into a WP function and get all those posts returned if the term ids are of different taxonomies. You'll have to do it the hard way with <code>tax-query</code> key passed in <code>get_posts()</code>. Fortunately, even though it is the hard way, you have complete control over the returned posts list, and a well designed tax-query can give you virtually any customization you can think of.</p>\n<p>In your example tax-query arguments, you are calling <code>category__and</code> and <code>tag__and</code>. It would be better to call <em>all</em> desired taxonomies in a single tax-query so that you can design the result according to your needs.</p>\n<p>The way I would do this is build the arrays within the tax-query separately and call them by variable later, like this:</p>\n<pre><code>$get_posts_args['tax_query'] = array(\n 'relation' =&gt; 'AND',\n $tag_array,\n $cat_array,\n $custax1_array,\n $custax2_array, ); }\n</code></pre>\n<p>The first benefit is that if any of these arrays are empty, they are simply ignored and the query runs anyway. The second benefit is that you can set further operator logic within these arrays. For example, <code>$tag_array</code> may look like this:</p>\n<pre><code>$tag_array = array(\n 'taxonomy' =&gt; 'post_tag',\n 'field' =&gt; 'term_id',\n 'operator' =&gt; 'AND',\n 'terms' =&gt; $tag_ids,); }\n</code></pre>\n<p>The <code>operator</code> key allows a few options that work <em>within</em> the taxonomy, while the <code>relation</code> key in the outer array works on the logic <em>between</em> the taxonomies. If you design these arrays programmatically, it becomes trivial to change the logic as needed for both circumstances for all taxonomies. For hierarchical taxonomies, you probably want to consider your preferences for the <code>include_children</code> key.</p>\n<p>The somewhat unique problem of having an integer array containing term ids from unknown taxonomies is pretty easily resolved with:</p>\n<pre><code>$tag_ids = get_terms(array(\n 'include'=&gt;$term_ids_list,\n 'taxonomy'=&gt;'post_tag',\n 'fields'=&gt;'ids'));\n</code></pre>\n<p>If <code>$term_ids_list</code> is your integer array of term ids, then calling <code>get_terms()</code> for a specific taxonomy will return <em>only</em> the terms within that taxonomy. This gives you <code>$tag_ids</code> as an integer array consisting only of term ids belonging to the tag taxonomy. You'd simply change the keys accordingly for the taxonomy you want to target.</p>\n<p>In hindsight for resolving this problem, I find that it is better to work with the taxonomies separately, even if they will be presented to the user as a single list. Presumably, we make taxonomies to separate kinds and types of content. <em>Not</em> keeping them separate undoes whatever purpose you originally had for making the separation in the first place. In my case, I wanted to have small urls, so decided that a single url variable like <code>?terms=1,2,3,4,5</code> would be better than <code>?cats=1,2&amp;tags=3,4&amp;custax1=5</code>. Indeed, the url is smaller, but upon reload the taxonomy key is lost. In this specific case however, it's not too difficult to put them back together.</p>\n" } ]
2020/07/26
[ "https://wordpress.stackexchange.com/questions/371796", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190364/" ]
I have a CPT which contains one large field group ('Global'), and two other field groups which contain ACF Clone Fields ('NJ' and 'PA'). The fields in NJ and PA are identical to Global, except that they are prefixed with nj\_ and pa\_. I also have a separate radio button field, where I specify which is the primary location ('primary\_geo') for that particular post. This is effective insofar as it enables me to control the information shown on the post itself. My problem is this: when I use WP Query to create a list of these posts, I'd like to filter and sort the posts according to the data in the field prefixed with the primary\_geo. Meaning sometimes pa\_field will be compared with nj\_field. But because it's outside the loop, I can't get that value. Is there a way for me to achieve what I'm looking for?
I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down wherever these ID's get written to store the tax names at that point. However it seems like figuring out which Taxonomy each Term ID is in and then using that to generate the `tax_query` part of the WP\_Query args isn't so hard. `get_term` allows you to find the taxonomy name from a term ID, so with that you're half way there. **This is untested code, some of it may contain errors and uses your $args as a base so you may need to double check the structure of the `tax_query` part, but it contains all the pieces you could use to build the code if you wanted to do it this way:** ``` $arrTermIDs = [ 1,2,3,4,5 ]; $arrTaxAndTerms = []; // make a 2d array with the term ID's broken down by tax name foreach ($arrTermIDs as $termID) { $term = get_term($termID); if (!in_array($term->taxonomy, $arrTaxAndTerms)) $arrTaxAndTerms[$term->taxonomy] = [] ; // create array for this tax if we don't have one already $arrTaxAndTerms[$term->taxonomy][] = $termID; // add this term id to array for this tax } // Now we have all the info we need to build the tax_query items for each taxonomy $arrTaxQueryItems = []; foreach($arrTaxAndTerms as $taxName => $termIDs) { $arrTaxQueryItems[] = array( 'taxonomy' => $taxName, 'field' => 'term_id', 'terms' => $termIDs ); } // Put that together into your $args: $args = array( 'numberposts' => -1, 'post_type' => array('post'), 'post_status' => 'publish', // any other conditions you want here 'tax_query' => array( 'relation' => 'AND', $arrTaxQueryItems ) ) ```
371,833
<p>I've created a meta box. The code is:</p> <pre><code>/** * Add meta box * * @param post $post The post object * @link https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes */ function portfolio_add_meta_boxes( $post ){ add_meta_box( 'portfolio_meta_box', __( 'Company URLs', 'portfolio' ), 'portfolio_build_meta_box', 'portfolio', 'side', 'low' ); } add_action( 'add_meta_boxes_portfolio', 'portfolio_add_meta_boxes' ); /** * Build custom field meta box * * @param post $post The post object */ function portfolio_build_meta_box( $post ){ // make sure the form request comes from WordPress wp_nonce_field( basename( __FILE__ ), 'portfolio_meta_box_nonce' ); // retrieve the current value $fbportfolio = get_post_meta( $post-&gt;ID, 'fbportfolio', true ); $twportfolio = get_post_meta( $post-&gt;ID, 'twportfolio', true ); $instportfolio = get_post_meta( $post-&gt;ID, 'instaportfolio', true ); $linkinportfolio = get_post_meta( $post-&gt;ID, 'linkinportfolio', true ); ?&gt; &lt;div class='inside'&gt; &lt;h3&gt;Facebook&lt;/h3&gt; &lt;p&gt; &lt;input type=&quot;url&quot; name=&quot;fbportfolio&quot; value=&quot;&lt;?php echo $fbportfolio; ?&gt;&quot;&gt; &lt;/p&gt; &lt;/div&gt; &lt;?php } /** * Store custom field meta box data * * @param int $post_id The post ID. * @link https://codex.wordpress.org/Plugin_API/Action_Reference/save_post */ function portfolio_save_meta_box_data( $post_id ){ // store custom fields values update_post_meta( get_the_ID(), 'fbportfolio', $_POST['fbportfolio'] ); } add_action( 'save_post_food', 'portfolio_save_meta_box_data' ); </code></pre>
[ { "answer_id": 371758, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 1, "selected": false, "text": "<p>I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down wherever these ID's get written to store the tax names at that point.</p>\n<p>However it seems like figuring out which Taxonomy each Term ID is in and then using that to generate the <code>tax_query</code> part of the WP_Query args isn't so hard. <code>get_term</code> allows you to find the taxonomy name from a term ID, so with that you're half way there.</p>\n<p><strong>This is untested code, some of it may contain errors and uses your $args as a base so you may need to double check the structure of the <code>tax_query</code> part, but it contains all the pieces you could use to build the code if you wanted to do it this way:</strong></p>\n<pre><code>$arrTermIDs = [ 1,2,3,4,5 ];\n$arrTaxAndTerms = []; // make a 2d array with the term ID's broken down by tax name\n\nforeach ($arrTermIDs as $termID) {\n $term = get_term($termID);\n if (!in_array($term-&gt;taxonomy, $arrTaxAndTerms)) \n $arrTaxAndTerms[$term-&gt;taxonomy] = [] ; // create array for this tax if we don't have one already\n \n $arrTaxAndTerms[$term-&gt;taxonomy][] = $termID; // add this term id to array for this tax\n}\n\n// Now we have all the info we need to build the tax_query items for each taxonomy \n$arrTaxQueryItems = [];\n\nforeach($arrTaxAndTerms as $taxName =&gt; $termIDs) {\n $arrTaxQueryItems[] = \n array(\n 'taxonomy' =&gt; $taxName,\n 'field' =&gt; 'term_id',\n 'terms' =&gt; $termIDs\n );\n}\n\n// Put that together into your $args:\n$args = array(\n 'numberposts' =&gt; -1,\n 'post_type' =&gt; array('post'),\n 'post_status' =&gt; 'publish',\n // any other conditions you want here\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'AND',\n $arrTaxQueryItems\n )\n)\n</code></pre>\n" }, { "answer_id": 372370, "author": "user38365", "author_id": 38365, "author_profile": "https://wordpress.stackexchange.com/users/38365", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, you can't just pass an array of term ids into a WP function and get all those posts returned if the term ids are of different taxonomies. You'll have to do it the hard way with <code>tax-query</code> key passed in <code>get_posts()</code>. Fortunately, even though it is the hard way, you have complete control over the returned posts list, and a well designed tax-query can give you virtually any customization you can think of.</p>\n<p>In your example tax-query arguments, you are calling <code>category__and</code> and <code>tag__and</code>. It would be better to call <em>all</em> desired taxonomies in a single tax-query so that you can design the result according to your needs.</p>\n<p>The way I would do this is build the arrays within the tax-query separately and call them by variable later, like this:</p>\n<pre><code>$get_posts_args['tax_query'] = array(\n 'relation' =&gt; 'AND',\n $tag_array,\n $cat_array,\n $custax1_array,\n $custax2_array, ); }\n</code></pre>\n<p>The first benefit is that if any of these arrays are empty, they are simply ignored and the query runs anyway. The second benefit is that you can set further operator logic within these arrays. For example, <code>$tag_array</code> may look like this:</p>\n<pre><code>$tag_array = array(\n 'taxonomy' =&gt; 'post_tag',\n 'field' =&gt; 'term_id',\n 'operator' =&gt; 'AND',\n 'terms' =&gt; $tag_ids,); }\n</code></pre>\n<p>The <code>operator</code> key allows a few options that work <em>within</em> the taxonomy, while the <code>relation</code> key in the outer array works on the logic <em>between</em> the taxonomies. If you design these arrays programmatically, it becomes trivial to change the logic as needed for both circumstances for all taxonomies. For hierarchical taxonomies, you probably want to consider your preferences for the <code>include_children</code> key.</p>\n<p>The somewhat unique problem of having an integer array containing term ids from unknown taxonomies is pretty easily resolved with:</p>\n<pre><code>$tag_ids = get_terms(array(\n 'include'=&gt;$term_ids_list,\n 'taxonomy'=&gt;'post_tag',\n 'fields'=&gt;'ids'));\n</code></pre>\n<p>If <code>$term_ids_list</code> is your integer array of term ids, then calling <code>get_terms()</code> for a specific taxonomy will return <em>only</em> the terms within that taxonomy. This gives you <code>$tag_ids</code> as an integer array consisting only of term ids belonging to the tag taxonomy. You'd simply change the keys accordingly for the taxonomy you want to target.</p>\n<p>In hindsight for resolving this problem, I find that it is better to work with the taxonomies separately, even if they will be presented to the user as a single list. Presumably, we make taxonomies to separate kinds and types of content. <em>Not</em> keeping them separate undoes whatever purpose you originally had for making the separation in the first place. In my case, I wanted to have small urls, so decided that a single url variable like <code>?terms=1,2,3,4,5</code> would be better than <code>?cats=1,2&amp;tags=3,4&amp;custax1=5</code>. Indeed, the url is smaller, but upon reload the taxonomy key is lost. In this specific case however, it's not too difficult to put them back together.</p>\n" } ]
2020/07/27
[ "https://wordpress.stackexchange.com/questions/371833", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192282/" ]
I've created a meta box. The code is: ``` /** * Add meta box * * @param post $post The post object * @link https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes */ function portfolio_add_meta_boxes( $post ){ add_meta_box( 'portfolio_meta_box', __( 'Company URLs', 'portfolio' ), 'portfolio_build_meta_box', 'portfolio', 'side', 'low' ); } add_action( 'add_meta_boxes_portfolio', 'portfolio_add_meta_boxes' ); /** * Build custom field meta box * * @param post $post The post object */ function portfolio_build_meta_box( $post ){ // make sure the form request comes from WordPress wp_nonce_field( basename( __FILE__ ), 'portfolio_meta_box_nonce' ); // retrieve the current value $fbportfolio = get_post_meta( $post->ID, 'fbportfolio', true ); $twportfolio = get_post_meta( $post->ID, 'twportfolio', true ); $instportfolio = get_post_meta( $post->ID, 'instaportfolio', true ); $linkinportfolio = get_post_meta( $post->ID, 'linkinportfolio', true ); ?> <div class='inside'> <h3>Facebook</h3> <p> <input type="url" name="fbportfolio" value="<?php echo $fbportfolio; ?>"> </p> </div> <?php } /** * Store custom field meta box data * * @param int $post_id The post ID. * @link https://codex.wordpress.org/Plugin_API/Action_Reference/save_post */ function portfolio_save_meta_box_data( $post_id ){ // store custom fields values update_post_meta( get_the_ID(), 'fbportfolio', $_POST['fbportfolio'] ); } add_action( 'save_post_food', 'portfolio_save_meta_box_data' ); ```
I suggest that that @SallyCJ's approach makes much more sense if you can do it this way: simply break down wherever these ID's get written to store the tax names at that point. However it seems like figuring out which Taxonomy each Term ID is in and then using that to generate the `tax_query` part of the WP\_Query args isn't so hard. `get_term` allows you to find the taxonomy name from a term ID, so with that you're half way there. **This is untested code, some of it may contain errors and uses your $args as a base so you may need to double check the structure of the `tax_query` part, but it contains all the pieces you could use to build the code if you wanted to do it this way:** ``` $arrTermIDs = [ 1,2,3,4,5 ]; $arrTaxAndTerms = []; // make a 2d array with the term ID's broken down by tax name foreach ($arrTermIDs as $termID) { $term = get_term($termID); if (!in_array($term->taxonomy, $arrTaxAndTerms)) $arrTaxAndTerms[$term->taxonomy] = [] ; // create array for this tax if we don't have one already $arrTaxAndTerms[$term->taxonomy][] = $termID; // add this term id to array for this tax } // Now we have all the info we need to build the tax_query items for each taxonomy $arrTaxQueryItems = []; foreach($arrTaxAndTerms as $taxName => $termIDs) { $arrTaxQueryItems[] = array( 'taxonomy' => $taxName, 'field' => 'term_id', 'terms' => $termIDs ); } // Put that together into your $args: $args = array( 'numberposts' => -1, 'post_type' => array('post'), 'post_status' => 'publish', // any other conditions you want here 'tax_query' => array( 'relation' => 'AND', $arrTaxQueryItems ) ) ```
371,872
<p>Title says it all. I'm trying to link to the most recent post of a custom post type, but only within the same term. Currently my code successfully echos the correct term ID but doesn't show a link on the screen.</p> <pre><code>&lt;?php // Get the ID of the current posts's term $terms = get_the_terms( get_the_ID(), 'comic-series' ); // Only get the parent term and ignore child terms foreach ( $terms as $term ){ if ( $term-&gt;parent == 0 ) { // Echo the term (this is only for debugging purposes) echo $term-&gt;term_id; // Take only the most recent post of same term $args = array( 'numberposts' =&gt; '1', 'category' =&gt; $term-&gt;term_id ); $recent_posts = wp_get_recent_posts( $args ); // Link to most recent post of same term foreach( $recent_posts as $recent ){ ?&gt; &lt;a href=&quot;&lt;?php get_the_permalink( $recent-&gt;ID ); ?&gt;&quot;&gt; &gt;&gt; &lt;/a&gt; &lt;?php } } } ?&gt; </code></pre>
[ { "answer_id": 371874, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 0, "selected": false, "text": "<p>Not sure if this is the only error, but watch out for WP functions that have <code>get_</code> on the front, as they return the value in PHP without echoing it to the screen. The ones without will echo it.</p>\n<p>So probably you want:</p>\n<pre><code> foreach( $recent_posts as $recent ){ ?&gt; \n &lt;a href=&quot;&lt;?php the_permalink( $recent-&gt;ID ); ?&gt;&quot;&gt;\n &gt;&gt; \n &lt;/a&gt; &lt;?php\n }\n</code></pre>\n<p>Note removal of <code>get_</code> from the function</p>\n" }, { "answer_id": 371880, "author": "ZackAkai", "author_id": 191954, "author_profile": "https://wordpress.stackexchange.com/users/191954", "pm_score": 1, "selected": false, "text": "<p>I ended up using wp_query instead because I couldn't make wp_get_recent_posts work no matter what I tried. For anyone who needs this functionality in the future, here's the code I used:</p>\n<pre><code>// Get the ID of the current posts's term\n $terms = get_the_terms( $post-&gt;ID, 'comic-series' );\n\n // Only get the parent term and ignore child terms\n foreach ( $terms as $term ){\n if ( $term-&gt;parent == 0 ) {\n\n // Query Options\n $query_options = array(\n 'posts_per_page' =&gt; 1,\n 'orderby' =&gt; 'title', // I've ordered all my posts by title but change this for your needs \n 'order' =&gt; 'DESC',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'comic-series',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; $term-&gt;term_id,\n ),\n ),\n );\n \n //Query\n $the_query = new WP_Query( $query_options ); \n\n while ($the_query -&gt; have_posts()) : $the_query -&gt; the_post();\n \n // Link to the latest page\n ?&gt; &lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot;&gt;LINK TEXT&lt;/a&gt; &lt;?php\n \n endwhile;\n wp_reset_postdata(); \n \n }\n } \n</code></pre>\n" } ]
2020/07/27
[ "https://wordpress.stackexchange.com/questions/371872", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/191954/" ]
Title says it all. I'm trying to link to the most recent post of a custom post type, but only within the same term. Currently my code successfully echos the correct term ID but doesn't show a link on the screen. ``` <?php // Get the ID of the current posts's term $terms = get_the_terms( get_the_ID(), 'comic-series' ); // Only get the parent term and ignore child terms foreach ( $terms as $term ){ if ( $term->parent == 0 ) { // Echo the term (this is only for debugging purposes) echo $term->term_id; // Take only the most recent post of same term $args = array( 'numberposts' => '1', 'category' => $term->term_id ); $recent_posts = wp_get_recent_posts( $args ); // Link to most recent post of same term foreach( $recent_posts as $recent ){ ?> <a href="<?php get_the_permalink( $recent->ID ); ?>"> >> </a> <?php } } } ?> ```
I ended up using wp\_query instead because I couldn't make wp\_get\_recent\_posts work no matter what I tried. For anyone who needs this functionality in the future, here's the code I used: ``` // Get the ID of the current posts's term $terms = get_the_terms( $post->ID, 'comic-series' ); // Only get the parent term and ignore child terms foreach ( $terms as $term ){ if ( $term->parent == 0 ) { // Query Options $query_options = array( 'posts_per_page' => 1, 'orderby' => 'title', // I've ordered all my posts by title but change this for your needs 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => 'comic-series', 'field' => 'term_id', 'terms' => $term->term_id, ), ), ); //Query $the_query = new WP_Query( $query_options ); while ($the_query -> have_posts()) : $the_query -> the_post(); // Link to the latest page ?> <a href="<?php the_permalink(); ?>">LINK TEXT</a> <?php endwhile; wp_reset_postdata(); } } ```
371,923
<p>I'm trying to get all the post types that has tags functionality. I searched a lot but couldn't find a conditional or something for that. I need a way to get post types or post objects for the posts which are taggable.</p> <p>Here are my current code to get post types:</p> <pre><code>public function getPostTypes() { $excludes = array('attachment'); $postTypes = get_post_types( array( 'public' =&gt; true, ), 'names' ); foreach ($excludes as $exclude) { unset($postTypes[$exclude]); } return array_values($postTypes); } </code></pre> <p>Thanks!</p>
[ { "answer_id": 371874, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 0, "selected": false, "text": "<p>Not sure if this is the only error, but watch out for WP functions that have <code>get_</code> on the front, as they return the value in PHP without echoing it to the screen. The ones without will echo it.</p>\n<p>So probably you want:</p>\n<pre><code> foreach( $recent_posts as $recent ){ ?&gt; \n &lt;a href=&quot;&lt;?php the_permalink( $recent-&gt;ID ); ?&gt;&quot;&gt;\n &gt;&gt; \n &lt;/a&gt; &lt;?php\n }\n</code></pre>\n<p>Note removal of <code>get_</code> from the function</p>\n" }, { "answer_id": 371880, "author": "ZackAkai", "author_id": 191954, "author_profile": "https://wordpress.stackexchange.com/users/191954", "pm_score": 1, "selected": false, "text": "<p>I ended up using wp_query instead because I couldn't make wp_get_recent_posts work no matter what I tried. For anyone who needs this functionality in the future, here's the code I used:</p>\n<pre><code>// Get the ID of the current posts's term\n $terms = get_the_terms( $post-&gt;ID, 'comic-series' );\n\n // Only get the parent term and ignore child terms\n foreach ( $terms as $term ){\n if ( $term-&gt;parent == 0 ) {\n\n // Query Options\n $query_options = array(\n 'posts_per_page' =&gt; 1,\n 'orderby' =&gt; 'title', // I've ordered all my posts by title but change this for your needs \n 'order' =&gt; 'DESC',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'comic-series',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; $term-&gt;term_id,\n ),\n ),\n );\n \n //Query\n $the_query = new WP_Query( $query_options ); \n\n while ($the_query -&gt; have_posts()) : $the_query -&gt; the_post();\n \n // Link to the latest page\n ?&gt; &lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot;&gt;LINK TEXT&lt;/a&gt; &lt;?php\n \n endwhile;\n wp_reset_postdata(); \n \n }\n } \n</code></pre>\n" } ]
2020/07/28
[ "https://wordpress.stackexchange.com/questions/371923", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/171820/" ]
I'm trying to get all the post types that has tags functionality. I searched a lot but couldn't find a conditional or something for that. I need a way to get post types or post objects for the posts which are taggable. Here are my current code to get post types: ``` public function getPostTypes() { $excludes = array('attachment'); $postTypes = get_post_types( array( 'public' => true, ), 'names' ); foreach ($excludes as $exclude) { unset($postTypes[$exclude]); } return array_values($postTypes); } ``` Thanks!
I ended up using wp\_query instead because I couldn't make wp\_get\_recent\_posts work no matter what I tried. For anyone who needs this functionality in the future, here's the code I used: ``` // Get the ID of the current posts's term $terms = get_the_terms( $post->ID, 'comic-series' ); // Only get the parent term and ignore child terms foreach ( $terms as $term ){ if ( $term->parent == 0 ) { // Query Options $query_options = array( 'posts_per_page' => 1, 'orderby' => 'title', // I've ordered all my posts by title but change this for your needs 'order' => 'DESC', 'tax_query' => array( array( 'taxonomy' => 'comic-series', 'field' => 'term_id', 'terms' => $term->term_id, ), ), ); //Query $the_query = new WP_Query( $query_options ); while ($the_query -> have_posts()) : $the_query -> the_post(); // Link to the latest page ?> <a href="<?php the_permalink(); ?>">LINK TEXT</a> <?php endwhile; wp_reset_postdata(); } } ```
371,930
<p>I have pagination with next/previous links but I also would like to show numbers so the user can click on 2, 3, 4 etc. Pagination seems more tricky with WP_User_Query as there isn't any default WordPress pagination for this as far as I know. The below works correctly as far as I can tell for the next and previous links.</p> <pre><code>$current_page = get_query_var('paged') ? (int) get_query_var('paged') : 1; $users_per_page = 2; $args = array( 'number' =&gt; $users_per_page, 'paged' =&gt; $current_page ); $wp_user_query = new WP_User_Query( $args ); $total_users = $wp_user_query-&gt;get_total(); $num_pages = ceil($total_users / $users_per_page); &lt;?php // Previous page if ( $current_page &gt; 1 ) { echo '&lt;a href=&quot;'. add_query_arg(array('paged' =&gt; $current_page-1)) .'&quot; class=&quot;prev&quot;&gt;Prev&lt;/a&gt;'; } // Next page if ( $current_page &lt; $num_pages ) { echo '&lt;a href=&quot;'. add_query_arg(array('paged' =&gt; $current_page+1)) .'&quot; class=&quot;next&quot;&gt;Next&lt;/a&gt;'; } ?&gt; </code></pre>
[ { "answer_id": 371934, "author": "maulik zwt", "author_id": 191968, "author_profile": "https://wordpress.stackexchange.com/users/191968", "pm_score": -1, "selected": false, "text": "<p>Please try below function for numeric pagination and change query variable as per your requirement.</p>\n<pre><code>function wpbeginner_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\n /** Add current page to the array */\n if ( $paged &gt;= 1 )\n $links[] = $paged;\n\n /** Add the pages around the current page to the array */\n if ( $paged &gt;= 3 ) {\n $links[] = $paged - 1;\n $links[] = $paged - 2;\n }\n\n if ( ( $paged + 2 ) &lt;= $max ) {\n $links[] = $paged + 2;\n $links[] = $paged + 1;\n }\n\n echo '&lt;div class=&quot;navigation&quot;&gt;&lt;ul&gt;' . &quot;\\n&quot;;\n\n /** Previous Post Link */\n if ( get_previous_posts_link() )\n printf( '&lt;li&gt;%s&lt;/li&gt;' . &quot;\\n&quot;, get_previous_posts_link() );\n\n /** Link to first page, plus ellipses if necessary */\n if ( ! in_array( 1, $links ) ) {\n $class = 1 == $paged ? ' class=&quot;active&quot;' : '';\n\n printf( '&lt;li%s&gt;&lt;a href=&quot;%s&quot;&gt;%s&lt;/a&gt;&lt;/li&gt;' . &quot;\\n&quot;, $class, esc_url( get_pagenum_link( 1 ) ), '1' );\n\n if ( ! in_array( 2, $links ) )\n echo '&lt;li&gt;…&lt;/li&gt;';\n }\n\n /** Link to current page, plus 2 pages in either direction if necessary */\n sort( $links );\n foreach ( (array) $links as $link ) {\n $class = $paged == $link ? ' class=&quot;active&quot;' : '';\n printf( '&lt;li%s&gt;&lt;a href=&quot;%s&quot;&gt;%s&lt;/a&gt;&lt;/li&gt;' . &quot;\\n&quot;, $class, esc_url( get_pagenum_link( $link ) ), $link );\n }\n\n /** Link to last page, plus ellipses if necessary */\n if ( ! in_array( $max, $links ) ) {\n if ( ! in_array( $max - 1, $links ) )\n echo '&lt;li&gt;…&lt;/li&gt;' . &quot;\\n&quot;;\n\n $class = $paged == $max ? ' class=&quot;active&quot;' : '';\n printf( '&lt;li%s&gt;&lt;a href=&quot;%s&quot;&gt;%s&lt;/a&gt;&lt;/li&gt;' . &quot;\\n&quot;, $class, esc_url( get_pagenum_link( $max ) ), $max );\n }\n\n /** Next Post Link */\n if ( get_next_posts_link() )\n printf( '&lt;li&gt;%s&lt;/li&gt;' . &quot;\\n&quot;, get_next_posts_link() );\n\n echo '&lt;/ul&gt;&lt;/div&gt;' . &quot;\\n&quot;;\n\n}\n</code></pre>\n" }, { "answer_id": 371938, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/paginate_links/\" rel=\"nofollow noreferrer\"><code>paginate_links()</code></a>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>echo paginate_links( array(\n 'current' =&gt; $current_page,\n 'total' =&gt; $num_pages,\n) );\n</code></pre>\n" } ]
2020/07/28
[ "https://wordpress.stackexchange.com/questions/371930", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140276/" ]
I have pagination with next/previous links but I also would like to show numbers so the user can click on 2, 3, 4 etc. Pagination seems more tricky with WP\_User\_Query as there isn't any default WordPress pagination for this as far as I know. The below works correctly as far as I can tell for the next and previous links. ``` $current_page = get_query_var('paged') ? (int) get_query_var('paged') : 1; $users_per_page = 2; $args = array( 'number' => $users_per_page, 'paged' => $current_page ); $wp_user_query = new WP_User_Query( $args ); $total_users = $wp_user_query->get_total(); $num_pages = ceil($total_users / $users_per_page); <?php // Previous page if ( $current_page > 1 ) { echo '<a href="'. add_query_arg(array('paged' => $current_page-1)) .'" class="prev">Prev</a>'; } // Next page if ( $current_page < $num_pages ) { echo '<a href="'. add_query_arg(array('paged' => $current_page+1)) .'" class="next">Next</a>'; } ?> ```
You can use [`paginate_links()`](https://developer.wordpress.org/reference/functions/paginate_links/): ```php echo paginate_links( array( 'current' => $current_page, 'total' => $num_pages, ) ); ```
371,946
<p>i want to add a dynamic JSON-LD (schema.org) for career posts in my wordpress page. I tried this code below. But i think i have some Syntax errors within the array. Maybe the &quot;echo&quot; is not allowed within the array? I hope somebody can help me with this?</p> <pre><code>&lt;?php function schema() {?&gt; &lt;?php if( have_rows('schema_auszeichnung') ): ?&gt; &lt;?php while( have_rows('schema_auszeichnung') ): the_row(); // Get sub field values. $title = get_sub_field('title'); $description = get_sub_field('description'); $state = get_sub_field('state'); $date = get_sub_field('date'); $street = get_sub_field('street'); $city = get_sub_field('city'); $postalcode = get_sub_field('postalcode'); $schema = array( '@context' =&gt; 'http://schema.org', '@type' =&gt; 'JobPosting', 'title' =&gt; $title, 'description' =&gt; $description, 'hiringOrganization' =&gt; array( '@type' =&gt; 'Organization', 'name' =&gt; 'cent GmbH', 'sameAs' =&gt; get_home_url(), 'logo' =&gt; '/wp/wp-content/uploads/2016/11/cropped-logo.png' ), 'employmentType'=&gt; $state, 'datePosted' =&gt; $date, 'validThrough' =&gt; &quot;&quot;, 'jobLocation' =&gt; array( '@type' =&gt; &quot;Place&quot;, 'address' =&gt; array ( '@type' =&gt; 'PostalAddress', 'streetAddress' =&gt; $street, 'adressLocality' =&gt; $city, 'postalCode' =&gt; $postalcode, 'addressCountry' =&gt; 'DE' ), ), ); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; &lt;?php echo '&lt;script type=&quot;application/ld+json&quot;&gt;' . json_encode($schema) . '&lt;/script&gt;'; } add_action('wp_head', 'schema'); ?&gt; </code></pre> <p>EDIT:</p> <p>After removing the 'echo' i got the php warning: Undefined variable: schema. But for me it is defined in this line: $schema = array.....</p>
[ { "answer_id": 371947, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 3, "selected": true, "text": "<p>This seems more like a PHP programming question, but yes as you guessed in PHP if you want the value of a variable you just need <code>$var</code>. <code>echo $var</code> outputs it and will cause a syntax error how you've used it.</p>\n<p>Otherwise everything else looks ok, although obviously I can't say if that data structure will give you valid JSON-LD ;-)</p>\n<p>EDIT: Also it's good to give your functions a more unique name than <code>'schema'</code>. You could call it <code>'yourname_jsonld_schema'</code> or something, so that it's much more unique and unlikely to collide with any other names in Wordpress</p>\n<p>EDIT2: To address the extra error you added to your question, the place you define <code>$schema</code> is <em>inside</em> an <code>if</code> statement, which means that if the variable is not defined later, that <code>if</code> was not true. So you need to do something like figure out why the <code>if</code> is false, or if it's correct, put the place where you use the <code>$schema</code> inside the <code>if</code> too.</p>\n" }, { "answer_id": 403239, "author": "Marsellus", "author_id": 219801, "author_profile": "https://wordpress.stackexchange.com/users/219801", "pm_score": 0, "selected": false, "text": "<p>Thanks so much for this! I was trying to solve almost the same problem, but to pull ACF from an FAQ page and add a structured data page for rich snippets when people google us: <a href=\"https://developers.google.com/search/docs/advanced/structured-data/faqpage\" rel=\"nofollow noreferrer\">https://developers.google.com/search/docs/advanced/structured-data/faqpage</a></p>\n<p>Below is my solution</p>\n<pre><code>&lt;?php\n\n$faq_page_schema = '';\n\nif( have_rows('questions') ):\n while ( have_rows('questions') ) : the_row();\n $question = '&quot;'.get_sub_field('question').'&quot;';\n $answer = '&quot;'.get_sub_field('answer').'&quot;';\n $faq_page_schema .= &quot;{\n \\&quot;@type\\&quot;: \\&quot;Question\\&quot;,\n \\&quot;name\\&quot;: $question,\n \\&quot;acceptedAnswer\\&quot;: {\n \\&quot;@type\\&quot;: \\&quot;Answer\\&quot;,\n \\&quot;text\\&quot;: $answer\n }\n }, &quot;;\n endwhile;\nelse :\n // no rows found\nendif;\n\n$faq_page_schema = substr_replace($faq_page_schema ,&quot;&quot;, -2);\n\necho\n'&lt;script type=&quot;application/ld+json&quot;&gt;\n {\n &quot;@context&quot;: &quot;https://schema.org&quot;,\n &quot;@type&quot;: &quot;FAQPage&quot;,\n &quot;mainEntity&quot;: ['.$faq_page_schema.']\n }\n&lt;/script&gt;';\n\n?&gt;\n</code></pre>\n" } ]
2020/07/28
[ "https://wordpress.stackexchange.com/questions/371946", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82174/" ]
i want to add a dynamic JSON-LD (schema.org) for career posts in my wordpress page. I tried this code below. But i think i have some Syntax errors within the array. Maybe the "echo" is not allowed within the array? I hope somebody can help me with this? ``` <?php function schema() {?> <?php if( have_rows('schema_auszeichnung') ): ?> <?php while( have_rows('schema_auszeichnung') ): the_row(); // Get sub field values. $title = get_sub_field('title'); $description = get_sub_field('description'); $state = get_sub_field('state'); $date = get_sub_field('date'); $street = get_sub_field('street'); $city = get_sub_field('city'); $postalcode = get_sub_field('postalcode'); $schema = array( '@context' => 'http://schema.org', '@type' => 'JobPosting', 'title' => $title, 'description' => $description, 'hiringOrganization' => array( '@type' => 'Organization', 'name' => 'cent GmbH', 'sameAs' => get_home_url(), 'logo' => '/wp/wp-content/uploads/2016/11/cropped-logo.png' ), 'employmentType'=> $state, 'datePosted' => $date, 'validThrough' => "", 'jobLocation' => array( '@type' => "Place", 'address' => array ( '@type' => 'PostalAddress', 'streetAddress' => $street, 'adressLocality' => $city, 'postalCode' => $postalcode, 'addressCountry' => 'DE' ), ), ); ?> <?php endwhile; ?> <?php endif; ?> <?php echo '<script type="application/ld+json">' . json_encode($schema) . '</script>'; } add_action('wp_head', 'schema'); ?> ``` EDIT: After removing the 'echo' i got the php warning: Undefined variable: schema. But for me it is defined in this line: $schema = array.....
This seems more like a PHP programming question, but yes as you guessed in PHP if you want the value of a variable you just need `$var`. `echo $var` outputs it and will cause a syntax error how you've used it. Otherwise everything else looks ok, although obviously I can't say if that data structure will give you valid JSON-LD ;-) EDIT: Also it's good to give your functions a more unique name than `'schema'`. You could call it `'yourname_jsonld_schema'` or something, so that it's much more unique and unlikely to collide with any other names in Wordpress EDIT2: To address the extra error you added to your question, the place you define `$schema` is *inside* an `if` statement, which means that if the variable is not defined later, that `if` was not true. So you need to do something like figure out why the `if` is false, or if it's correct, put the place where you use the `$schema` inside the `if` too.
371,968
<p>I'm trying to remove a parent theme's add_action call to a pluggable function, but can't get it to work by calling <code>remove_action()</code> - I have to redeclare the function and just leave it empty. Is this normal? I'd think I could use <code>remove_action</code> to simply never call the function.</p> <p>Here's the parent theme code:</p> <pre><code>add_action( 'tha_content_while_before', 'fwp_archive_header' ); if ( !function_exists('fwp_archive_header') ) { function fwp_archive_header() { // do stuff } } </code></pre> <p>And in the child theme (NOT working):</p> <pre><code>add_action( 'init', 'remove_parent_actions_filters' ); function remove_parent_actions_filters() { remove_action( 'tha_content_while_before', 'fwp_archive_header' ); } </code></pre> <p>I have also tried swapping out '<code>init</code>' for '<code>after_setup_theme</code>' and '<code>wp_loaded</code>'; I've also tried lowering and raising the priority, nothing worked. The only thing that did work was this:</p> <p>In the child theme (working):</p> <pre><code>function fwp_archive_header() { // do nothing } </code></pre> <p>Can that be right, I have to redeclare the function to get rid of it?</p> <p>Thanks!</p>
[ { "answer_id": 371971, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Inside your remove_parent_actions_filters() function, add a test to see if the parent theme's function has been loaded. Maybe you are calling your hook too soon.</p>\n<pre><code>add_action( 'init', 'remove_parent_actions_filters' );\nfunction remove_parent_actions_filters() { \n if (!function_exists('fwp_archive_header')) {wp_die(&quot;fwp_archive_header function is not loaded&quot;);}\n remove_action( 'tha_content_while_before', 'fwp_archive_header' );\n}\n</code></pre>\n<p><strong>Added</strong></p>\n<p>Try using the after_setup_theme hook instead. See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme</a> .</p>\n" }, { "answer_id": 371977, "author": "Bence Szalai", "author_id": 152690, "author_profile": "https://wordpress.stackexchange.com/users/152690", "pm_score": 2, "selected": false, "text": "<p>The parent theme's functions.php runs <strong>after</strong> the child theme's, so in order to remove an action defined by the parent theme the <code>remove_action</code> call must be delayed using a hook after the parent theme registers the action. So putting the <code>remove_action</code> call purely inside the child's functions.php won't work. It must be attached to a hook.</p>\n<p>However from the code excerpt in the question it is not clear if the parent's <code>add_action( 'tha_content_while_before', 'fwp_archive_header' );</code> line is just in functions.php or is that inside an action? If it is inside an action, hook the <code>remove_action</code> call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent <code>add_action</code> call is inside. Something like this:</p>\n<pre><code>add_action( 'some_hook', 'some_parent_function', 10 );\nfunction some_parent_function() {\n /* ...some code... */\n add_action( 'tha_content_while_before', 'fwp_archive_header' );\n if ( !function_exists('fwp_archive_header') ) {\n function fwp_archive_header() {\n // do stuff\n }\n }\n /* ...some code... */\n}\n\n</code></pre>\n<p>The remove would look like:</p>\n<pre><code>add_action( 'some_hook', 'remove_parent_actions_filters', 11 );\nfunction remove_parent_actions_filters() { \n remove_action( 'tha_content_while_before', 'fwp_archive_header' );\n}\n</code></pre>\n<hr />\n<p>Another rule of thumb attempt is to hook your remove call to <code>wp_loaded</code>, e.g.: <code>add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );</code>. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks.</p>\n<hr />\n<p>On the other hand declaring an empty function with the name <code>fwp_archive_header</code> is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place).</p>\n" } ]
2020/07/28
[ "https://wordpress.stackexchange.com/questions/371968", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16/" ]
I'm trying to remove a parent theme's add\_action call to a pluggable function, but can't get it to work by calling `remove_action()` - I have to redeclare the function and just leave it empty. Is this normal? I'd think I could use `remove_action` to simply never call the function. Here's the parent theme code: ``` add_action( 'tha_content_while_before', 'fwp_archive_header' ); if ( !function_exists('fwp_archive_header') ) { function fwp_archive_header() { // do stuff } } ``` And in the child theme (NOT working): ``` add_action( 'init', 'remove_parent_actions_filters' ); function remove_parent_actions_filters() { remove_action( 'tha_content_while_before', 'fwp_archive_header' ); } ``` I have also tried swapping out '`init`' for '`after_setup_theme`' and '`wp_loaded`'; I've also tried lowering and raising the priority, nothing worked. The only thing that did work was this: In the child theme (working): ``` function fwp_archive_header() { // do nothing } ``` Can that be right, I have to redeclare the function to get rid of it? Thanks!
The parent theme's functions.php runs **after** the child theme's, so in order to remove an action defined by the parent theme the `remove_action` call must be delayed using a hook after the parent theme registers the action. So putting the `remove_action` call purely inside the child's functions.php won't work. It must be attached to a hook. However from the code excerpt in the question it is not clear if the parent's `add_action( 'tha_content_while_before', 'fwp_archive_header' );` line is just in functions.php or is that inside an action? If it is inside an action, hook the `remove_action` call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent `add_action` call is inside. Something like this: ``` add_action( 'some_hook', 'some_parent_function', 10 ); function some_parent_function() { /* ...some code... */ add_action( 'tha_content_while_before', 'fwp_archive_header' ); if ( !function_exists('fwp_archive_header') ) { function fwp_archive_header() { // do stuff } } /* ...some code... */ } ``` The remove would look like: ``` add_action( 'some_hook', 'remove_parent_actions_filters', 11 ); function remove_parent_actions_filters() { remove_action( 'tha_content_while_before', 'fwp_archive_header' ); } ``` --- Another rule of thumb attempt is to hook your remove call to `wp_loaded`, e.g.: `add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );`. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks. --- On the other hand declaring an empty function with the name `fwp_archive_header` is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place).
371,997
<p>i want to send email only new post publish in wordpress admin</p> <p>when i pulish anything its sending mail to user how to restric this to only new post added to send mail to user</p> <pre><code> function wpse_19040_notify_admin_on_publish( $new_status, $old_status, $post ) { if ( $new_status !== 'publish' || $old_status === 'publish' ) return; if ( ! $post_type = get_post_type_object( $post-&gt;post_type ) ) return; global $wpdb; $newsletterdata = $wpdb-&gt;get_results(&quot;SELECT * FROM &quot;.$wpdb-&gt;prefix.&quot;newsletter&quot;); foreach ( $newsletterdata as $newsletteremailall ) { $newsletteremailall = $newsletteremailall-&gt;email; if(filter_var($newsletteremailall, FILTER_VALIDATE_EMAIL)) { $subject = $post-&gt;post_title; $message = 'Our new post is here '.&quot;\n&quot;.'Post Title: ' .$post-&gt;post_title. &quot;\n&quot;.&quot;click here to visit post: &quot; . get_permalink( $post-&gt;ID ); wp_mail( $newsletteremailall, $subject, $message ); } else { } } } add_action( 'transition_post_status', 'wpse_19040_notify_admin_on_publish', 10, 3 ); </code></pre>
[ { "answer_id": 371971, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Inside your remove_parent_actions_filters() function, add a test to see if the parent theme's function has been loaded. Maybe you are calling your hook too soon.</p>\n<pre><code>add_action( 'init', 'remove_parent_actions_filters' );\nfunction remove_parent_actions_filters() { \n if (!function_exists('fwp_archive_header')) {wp_die(&quot;fwp_archive_header function is not loaded&quot;);}\n remove_action( 'tha_content_while_before', 'fwp_archive_header' );\n}\n</code></pre>\n<p><strong>Added</strong></p>\n<p>Try using the after_setup_theme hook instead. See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme</a> .</p>\n" }, { "answer_id": 371977, "author": "Bence Szalai", "author_id": 152690, "author_profile": "https://wordpress.stackexchange.com/users/152690", "pm_score": 2, "selected": false, "text": "<p>The parent theme's functions.php runs <strong>after</strong> the child theme's, so in order to remove an action defined by the parent theme the <code>remove_action</code> call must be delayed using a hook after the parent theme registers the action. So putting the <code>remove_action</code> call purely inside the child's functions.php won't work. It must be attached to a hook.</p>\n<p>However from the code excerpt in the question it is not clear if the parent's <code>add_action( 'tha_content_while_before', 'fwp_archive_header' );</code> line is just in functions.php or is that inside an action? If it is inside an action, hook the <code>remove_action</code> call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent <code>add_action</code> call is inside. Something like this:</p>\n<pre><code>add_action( 'some_hook', 'some_parent_function', 10 );\nfunction some_parent_function() {\n /* ...some code... */\n add_action( 'tha_content_while_before', 'fwp_archive_header' );\n if ( !function_exists('fwp_archive_header') ) {\n function fwp_archive_header() {\n // do stuff\n }\n }\n /* ...some code... */\n}\n\n</code></pre>\n<p>The remove would look like:</p>\n<pre><code>add_action( 'some_hook', 'remove_parent_actions_filters', 11 );\nfunction remove_parent_actions_filters() { \n remove_action( 'tha_content_while_before', 'fwp_archive_header' );\n}\n</code></pre>\n<hr />\n<p>Another rule of thumb attempt is to hook your remove call to <code>wp_loaded</code>, e.g.: <code>add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );</code>. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks.</p>\n<hr />\n<p>On the other hand declaring an empty function with the name <code>fwp_archive_header</code> is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place).</p>\n" } ]
2020/07/29
[ "https://wordpress.stackexchange.com/questions/371997", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192212/" ]
i want to send email only new post publish in wordpress admin when i pulish anything its sending mail to user how to restric this to only new post added to send mail to user ``` function wpse_19040_notify_admin_on_publish( $new_status, $old_status, $post ) { if ( $new_status !== 'publish' || $old_status === 'publish' ) return; if ( ! $post_type = get_post_type_object( $post->post_type ) ) return; global $wpdb; $newsletterdata = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."newsletter"); foreach ( $newsletterdata as $newsletteremailall ) { $newsletteremailall = $newsletteremailall->email; if(filter_var($newsletteremailall, FILTER_VALIDATE_EMAIL)) { $subject = $post->post_title; $message = 'Our new post is here '."\n".'Post Title: ' .$post->post_title. "\n"."click here to visit post: " . get_permalink( $post->ID ); wp_mail( $newsletteremailall, $subject, $message ); } else { } } } add_action( 'transition_post_status', 'wpse_19040_notify_admin_on_publish', 10, 3 ); ```
The parent theme's functions.php runs **after** the child theme's, so in order to remove an action defined by the parent theme the `remove_action` call must be delayed using a hook after the parent theme registers the action. So putting the `remove_action` call purely inside the child's functions.php won't work. It must be attached to a hook. However from the code excerpt in the question it is not clear if the parent's `add_action( 'tha_content_while_before', 'fwp_archive_header' );` line is just in functions.php or is that inside an action? If it is inside an action, hook the `remove_action` call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent `add_action` call is inside. Something like this: ``` add_action( 'some_hook', 'some_parent_function', 10 ); function some_parent_function() { /* ...some code... */ add_action( 'tha_content_while_before', 'fwp_archive_header' ); if ( !function_exists('fwp_archive_header') ) { function fwp_archive_header() { // do stuff } } /* ...some code... */ } ``` The remove would look like: ``` add_action( 'some_hook', 'remove_parent_actions_filters', 11 ); function remove_parent_actions_filters() { remove_action( 'tha_content_while_before', 'fwp_archive_header' ); } ``` --- Another rule of thumb attempt is to hook your remove call to `wp_loaded`, e.g.: `add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );`. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks. --- On the other hand declaring an empty function with the name `fwp_archive_header` is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place).
372,050
<p>I want to get the total number of results after searching WordPress users by role and a string that matches the user name.</p> <p>What I tried so far:</p> <pre><code>$args= array('echo'=&gt;false, 'role' =&gt; 'author', 'search'=&gt;$search_txt); $user_query = new WP_User_Query($args); $auth_count= $user_query-&gt;get_total(); </code></pre> <p>But it returns 0 everytime.</p> <p><strong>Note:</strong></p> <p>Perhaps it can be done by:</p> <pre><code>$args= array('echo'=&gt;false, 'role' =&gt; 'author', 'search'=&gt;$search_txt); $auth_count= count(get_users($args)); </code></pre> <p>or by querying with</p> <pre><code>global $wpdb; </code></pre> <p>But is there any more resource friendly method?</p>
[ { "answer_id": 371971, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Inside your remove_parent_actions_filters() function, add a test to see if the parent theme's function has been loaded. Maybe you are calling your hook too soon.</p>\n<pre><code>add_action( 'init', 'remove_parent_actions_filters' );\nfunction remove_parent_actions_filters() { \n if (!function_exists('fwp_archive_header')) {wp_die(&quot;fwp_archive_header function is not loaded&quot;);}\n remove_action( 'tha_content_while_before', 'fwp_archive_header' );\n}\n</code></pre>\n<p><strong>Added</strong></p>\n<p>Try using the after_setup_theme hook instead. See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme</a> .</p>\n" }, { "answer_id": 371977, "author": "Bence Szalai", "author_id": 152690, "author_profile": "https://wordpress.stackexchange.com/users/152690", "pm_score": 2, "selected": false, "text": "<p>The parent theme's functions.php runs <strong>after</strong> the child theme's, so in order to remove an action defined by the parent theme the <code>remove_action</code> call must be delayed using a hook after the parent theme registers the action. So putting the <code>remove_action</code> call purely inside the child's functions.php won't work. It must be attached to a hook.</p>\n<p>However from the code excerpt in the question it is not clear if the parent's <code>add_action( 'tha_content_while_before', 'fwp_archive_header' );</code> line is just in functions.php or is that inside an action? If it is inside an action, hook the <code>remove_action</code> call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent <code>add_action</code> call is inside. Something like this:</p>\n<pre><code>add_action( 'some_hook', 'some_parent_function', 10 );\nfunction some_parent_function() {\n /* ...some code... */\n add_action( 'tha_content_while_before', 'fwp_archive_header' );\n if ( !function_exists('fwp_archive_header') ) {\n function fwp_archive_header() {\n // do stuff\n }\n }\n /* ...some code... */\n}\n\n</code></pre>\n<p>The remove would look like:</p>\n<pre><code>add_action( 'some_hook', 'remove_parent_actions_filters', 11 );\nfunction remove_parent_actions_filters() { \n remove_action( 'tha_content_while_before', 'fwp_archive_header' );\n}\n</code></pre>\n<hr />\n<p>Another rule of thumb attempt is to hook your remove call to <code>wp_loaded</code>, e.g.: <code>add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );</code>. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks.</p>\n<hr />\n<p>On the other hand declaring an empty function with the name <code>fwp_archive_header</code> is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place).</p>\n" } ]
2020/07/29
[ "https://wordpress.stackexchange.com/questions/372050", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92425/" ]
I want to get the total number of results after searching WordPress users by role and a string that matches the user name. What I tried so far: ``` $args= array('echo'=>false, 'role' => 'author', 'search'=>$search_txt); $user_query = new WP_User_Query($args); $auth_count= $user_query->get_total(); ``` But it returns 0 everytime. **Note:** Perhaps it can be done by: ``` $args= array('echo'=>false, 'role' => 'author', 'search'=>$search_txt); $auth_count= count(get_users($args)); ``` or by querying with ``` global $wpdb; ``` But is there any more resource friendly method?
The parent theme's functions.php runs **after** the child theme's, so in order to remove an action defined by the parent theme the `remove_action` call must be delayed using a hook after the parent theme registers the action. So putting the `remove_action` call purely inside the child's functions.php won't work. It must be attached to a hook. However from the code excerpt in the question it is not clear if the parent's `add_action( 'tha_content_while_before', 'fwp_archive_header' );` line is just in functions.php or is that inside an action? If it is inside an action, hook the `remove_action` call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent `add_action` call is inside. Something like this: ``` add_action( 'some_hook', 'some_parent_function', 10 ); function some_parent_function() { /* ...some code... */ add_action( 'tha_content_while_before', 'fwp_archive_header' ); if ( !function_exists('fwp_archive_header') ) { function fwp_archive_header() { // do stuff } } /* ...some code... */ } ``` The remove would look like: ``` add_action( 'some_hook', 'remove_parent_actions_filters', 11 ); function remove_parent_actions_filters() { remove_action( 'tha_content_while_before', 'fwp_archive_header' ); } ``` --- Another rule of thumb attempt is to hook your remove call to `wp_loaded`, e.g.: `add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );`. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks. --- On the other hand declaring an empty function with the name `fwp_archive_header` is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place).
372,068
<p>We have rewrite rules as:</p> <pre><code>add_action( 'init', function() { add_rewrite_rule( 'app-api/v2/ecommerce/([a-z0-9-]+)[/]?$', 'index.php?p=$matches[1]&amp;post_type=product' ); } ); </code></pre> <p>for the URL - <code>www.domain.com/app-api/v2/ecommerce/14</code>. We load a custom template using <code>template_include</code> hook for custom rules.</p> <p>The above works fine, but for some specific reasons the client wants to make use of query variables so that the new URL will be of the form <code>www.domain.com/app-api/v2/ecommerce?pid=14</code></p> <p>What I am trying to achieve is something like this, which doesn't work.</p> <pre><code>add_action( 'init', function() { $id = $_GET['pid']; add_rewrite_rule( 'app-api/v2/ecommerce', &quot;index.php?p={$id}&amp;post_type=product&quot; ); } ); </code></pre> <p>What is the correct way to add a rewrite rule with dynamic query variables?</p>
[ { "answer_id": 371971, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Inside your remove_parent_actions_filters() function, add a test to see if the parent theme's function has been loaded. Maybe you are calling your hook too soon.</p>\n<pre><code>add_action( 'init', 'remove_parent_actions_filters' );\nfunction remove_parent_actions_filters() { \n if (!function_exists('fwp_archive_header')) {wp_die(&quot;fwp_archive_header function is not loaded&quot;);}\n remove_action( 'tha_content_while_before', 'fwp_archive_header' );\n}\n</code></pre>\n<p><strong>Added</strong></p>\n<p>Try using the after_setup_theme hook instead. See <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme</a> .</p>\n" }, { "answer_id": 371977, "author": "Bence Szalai", "author_id": 152690, "author_profile": "https://wordpress.stackexchange.com/users/152690", "pm_score": 2, "selected": false, "text": "<p>The parent theme's functions.php runs <strong>after</strong> the child theme's, so in order to remove an action defined by the parent theme the <code>remove_action</code> call must be delayed using a hook after the parent theme registers the action. So putting the <code>remove_action</code> call purely inside the child's functions.php won't work. It must be attached to a hook.</p>\n<p>However from the code excerpt in the question it is not clear if the parent's <code>add_action( 'tha_content_while_before', 'fwp_archive_header' );</code> line is just in functions.php or is that inside an action? If it is inside an action, hook the <code>remove_action</code> call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent <code>add_action</code> call is inside. Something like this:</p>\n<pre><code>add_action( 'some_hook', 'some_parent_function', 10 );\nfunction some_parent_function() {\n /* ...some code... */\n add_action( 'tha_content_while_before', 'fwp_archive_header' );\n if ( !function_exists('fwp_archive_header') ) {\n function fwp_archive_header() {\n // do stuff\n }\n }\n /* ...some code... */\n}\n\n</code></pre>\n<p>The remove would look like:</p>\n<pre><code>add_action( 'some_hook', 'remove_parent_actions_filters', 11 );\nfunction remove_parent_actions_filters() { \n remove_action( 'tha_content_while_before', 'fwp_archive_header' );\n}\n</code></pre>\n<hr />\n<p>Another rule of thumb attempt is to hook your remove call to <code>wp_loaded</code>, e.g.: <code>add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );</code>. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks.</p>\n<hr />\n<p>On the other hand declaring an empty function with the name <code>fwp_archive_header</code> is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place).</p>\n" } ]
2020/07/30
[ "https://wordpress.stackexchange.com/questions/372068", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67538/" ]
We have rewrite rules as: ``` add_action( 'init', function() { add_rewrite_rule( 'app-api/v2/ecommerce/([a-z0-9-]+)[/]?$', 'index.php?p=$matches[1]&post_type=product' ); } ); ``` for the URL - `www.domain.com/app-api/v2/ecommerce/14`. We load a custom template using `template_include` hook for custom rules. The above works fine, but for some specific reasons the client wants to make use of query variables so that the new URL will be of the form `www.domain.com/app-api/v2/ecommerce?pid=14` What I am trying to achieve is something like this, which doesn't work. ``` add_action( 'init', function() { $id = $_GET['pid']; add_rewrite_rule( 'app-api/v2/ecommerce', "index.php?p={$id}&post_type=product" ); } ); ``` What is the correct way to add a rewrite rule with dynamic query variables?
The parent theme's functions.php runs **after** the child theme's, so in order to remove an action defined by the parent theme the `remove_action` call must be delayed using a hook after the parent theme registers the action. So putting the `remove_action` call purely inside the child's functions.php won't work. It must be attached to a hook. However from the code excerpt in the question it is not clear if the parent's `add_action( 'tha_content_while_before', 'fwp_archive_header' );` line is just in functions.php or is that inside an action? If it is inside an action, hook the `remove_action` call to the same action but with bigger priority (so it runs after). Note I'm talking about the action the parent `add_action` call is inside. Something like this: ``` add_action( 'some_hook', 'some_parent_function', 10 ); function some_parent_function() { /* ...some code... */ add_action( 'tha_content_while_before', 'fwp_archive_header' ); if ( !function_exists('fwp_archive_header') ) { function fwp_archive_header() { // do stuff } } /* ...some code... */ } ``` The remove would look like: ``` add_action( 'some_hook', 'remove_parent_actions_filters', 11 ); function remove_parent_actions_filters() { remove_action( 'tha_content_while_before', 'fwp_archive_header' ); } ``` --- Another rule of thumb attempt is to hook your remove call to `wp_loaded`, e.g.: `add_action( 'wp_loaded', 'remove_parent_actions_filters', 1000 );`. Should be still on time to affect how pages are rendered, but would likely be late enough to override most common parent theme hooks. --- On the other hand declaring an empty function with the name `fwp_archive_header` is almost as good solution. Note though it is not “redeclare”, as there's no such thing in PHP. It's more like “predeclare”, before the parent theme, so the parent theme won't declare it's own function with the same name (with appropriate checks in place).
372,110
<p>I have a problem, when I am on page 2 or on any other page and I want to return to the index, the url that offers me the pagination on page 1 is the following (<a href="https://www.url.com/page/1" rel="nofollow noreferrer">https://www.url.com/page/1</a>) and I would like it to be as it usually is (<a href="https://www.url.com" rel="nofollow noreferrer">https://www.url.com</a>)</p> <p>El código que tengo en el fuctions.php es el siguiente:</p> <pre><code>function mt_paginacion($tipo=1,$class=NULL,$qc=NULL){ global $wp_query,$paged; if($qc==''){$total=$wp_query-&gt;max_num_pages;}else{$total=$qc;} if($tipo==1){ $paginacion=paginate_links( array( 'base' =&gt; str_replace(999999999, '%#%', esc_url( get_pagenum_link(999999999) ) ), 'format' =&gt; '?paged=%#%', 'current' =&gt; max( 1, $paged ), 'total' =&gt; $total, 'mid_size' =&gt; 3, 'prev_next' =&gt; true ) ); </code></pre>
[ { "answer_id": 372163, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 1, "selected": false, "text": "<p>You can do a simple <code>str_replace( '/page/1/', '/', $string )</code> on the results generated by <code>paginate_links()</code> to get rid of <code>/page/1/</code> which appears on the first page link as well as the Prev link (when it points to the first page).</p>\n<p>Here's a full (tested) example:</p>\n<pre><code>/**\n * Numeric pagination via WP core function paginate_links().\n * @link http://codex.wordpress.org/Function_Reference/paginate_links\n *\n * @param array $srgs\n *\n * @return string HTML for numneric pagination\n */\nfunction wpse_pagination( $args = array() ) {\n global $wp_query;\n\n if ( $wp_query-&gt;max_num_pages &lt;= 1 ) {\n return;\n }\n\n $pagination_args = array(\n 'base' =&gt; str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),\n 'total' =&gt; $wp_query-&gt;max_num_pages,\n 'current' =&gt; max( 1, get_query_var( 'paged' ) ),\n 'format' =&gt; '?paged=%#%',\n 'show_all' =&gt; false,\n 'type' =&gt; 'array',\n 'end_size' =&gt; 2,\n 'mid_size' =&gt; 3,\n 'prev_next' =&gt; true,\n 'prev_text' =&gt; __( '&amp;laquo; Prev', 'wpse' ),\n 'next_text' =&gt; __( 'Next &amp;raquo;', 'wpse' ),\n 'add_args' =&gt; false,\n 'add_fragment' =&gt; '',\n\n // Custom arguments not part of WP core:\n 'show_page_position' =&gt; false, // Optionally allows the &quot;Page X of XX&quot; HTML to be displayed.\n );\n\n $pagination = paginate_links( array_merge( $pagination_args, $args ) );\n\n // Remove /page/1/ from links.\n $pagination = array_map(\n function( $string ) {\n return str_replace( '/page/1/', '/', $string );\n },\n $pagination\n );\n\n return implode( '', $pagination );\n}\n</code></pre>\n<p><strong>Usage:</strong></p>\n<pre><code>echo wpse_pagination();\n</code></pre>\n" }, { "answer_id": 409188, "author": "Morshed Alam Sumon", "author_id": 186443, "author_profile": "https://wordpress.stackexchange.com/users/186443", "pm_score": 0, "selected": false, "text": "<p>If you don't want to create a new function, this simple solution is for you: <a href=\"https://weusewp.com/tutorial/pagination-remove-page-1/\" rel=\"nofollow noreferrer\">How to Remove page/1/ from WordPress Pagination</a></p>\n" } ]
2020/07/30
[ "https://wordpress.stackexchange.com/questions/372110", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192472/" ]
I have a problem, when I am on page 2 or on any other page and I want to return to the index, the url that offers me the pagination on page 1 is the following (<https://www.url.com/page/1>) and I would like it to be as it usually is (<https://www.url.com>) El código que tengo en el fuctions.php es el siguiente: ``` function mt_paginacion($tipo=1,$class=NULL,$qc=NULL){ global $wp_query,$paged; if($qc==''){$total=$wp_query->max_num_pages;}else{$total=$qc;} if($tipo==1){ $paginacion=paginate_links( array( 'base' => str_replace(999999999, '%#%', esc_url( get_pagenum_link(999999999) ) ), 'format' => '?paged=%#%', 'current' => max( 1, $paged ), 'total' => $total, 'mid_size' => 3, 'prev_next' => true ) ); ```
You can do a simple `str_replace( '/page/1/', '/', $string )` on the results generated by `paginate_links()` to get rid of `/page/1/` which appears on the first page link as well as the Prev link (when it points to the first page). Here's a full (tested) example: ``` /** * Numeric pagination via WP core function paginate_links(). * @link http://codex.wordpress.org/Function_Reference/paginate_links * * @param array $srgs * * @return string HTML for numneric pagination */ function wpse_pagination( $args = array() ) { global $wp_query; if ( $wp_query->max_num_pages <= 1 ) { return; } $pagination_args = array( 'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ), 'total' => $wp_query->max_num_pages, 'current' => max( 1, get_query_var( 'paged' ) ), 'format' => '?paged=%#%', 'show_all' => false, 'type' => 'array', 'end_size' => 2, 'mid_size' => 3, 'prev_next' => true, 'prev_text' => __( '&laquo; Prev', 'wpse' ), 'next_text' => __( 'Next &raquo;', 'wpse' ), 'add_args' => false, 'add_fragment' => '', // Custom arguments not part of WP core: 'show_page_position' => false, // Optionally allows the "Page X of XX" HTML to be displayed. ); $pagination = paginate_links( array_merge( $pagination_args, $args ) ); // Remove /page/1/ from links. $pagination = array_map( function( $string ) { return str_replace( '/page/1/', '/', $string ); }, $pagination ); return implode( '', $pagination ); } ``` **Usage:** ``` echo wpse_pagination(); ```
372,112
<p>I would like to be able to post the most recent updated date in my footer. However, I can't seem to find a way to do that globally for the site, just for each post/page at a time using <code>get_the_modified_date()</code>.</p> <p>So for example if I make a change to my home page the footer would be updated to that date and time. If I later make an edit to a miscellaneous page, then the &quot;Updated&quot; date and time would change to reflect that more recent update.</p> <p>Any help is greatly appreciated.</p>
[ { "answer_id": 372121, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 0, "selected": false, "text": "<p>I don't know if there's a more WP-friendly way to do this, but this query will do what you want. It gets the latest date from the posts table for any post or page:</p>\n<pre><code>select max(post_modified) from wp_posts where post_type IN ('post', 'page');\n</code></pre>\n<p>So you could wrap that up in a shortcode for example, like:</p>\n<pre><code>function get_latest_update_date() {\n global $wpdb;\n return $wpdb-&gt;get_var(&quot;SELECT max(post_modified) FROM wp_posts WHERE post_type IN ('post', 'page');&quot;);\n}\n\nadd_shortcode('latestupdatedate', 'get_latest_update_date');\n</code></pre>\n<p>If you want to format the date, you'll need to add the PHP date parsing/formatting functions.</p>\n" }, { "answer_id": 390499, "author": "user3792395", "author_id": 207730, "author_profile": "https://wordpress.stackexchange.com/users/207730", "pm_score": 1, "selected": false, "text": "<p>Just a continuation from mozboz' answer. For those curious as I was, you could use the date() or date_i18n() functions to format the date properly in the following snippet.</p>\n<pre><code>function get_latest_update_date() {\n global $wpdb;\n $thelatest = $wpdb-&gt;get_var(&quot;SELECT max(post_modified) FROM wp_posts WHERE post_type IN ('post', 'page');&quot;);\n //returns formatted date like 13.08.2001\n return date_i18n('j.m.Y', strtotime($thelatest));\n }\n \n add_shortcode('latestupdatedate', 'get_latest_update_date');\n</code></pre>\n" } ]
2020/07/30
[ "https://wordpress.stackexchange.com/questions/372112", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165195/" ]
I would like to be able to post the most recent updated date in my footer. However, I can't seem to find a way to do that globally for the site, just for each post/page at a time using `get_the_modified_date()`. So for example if I make a change to my home page the footer would be updated to that date and time. If I later make an edit to a miscellaneous page, then the "Updated" date and time would change to reflect that more recent update. Any help is greatly appreciated.
Just a continuation from mozboz' answer. For those curious as I was, you could use the date() or date\_i18n() functions to format the date properly in the following snippet. ``` function get_latest_update_date() { global $wpdb; $thelatest = $wpdb->get_var("SELECT max(post_modified) FROM wp_posts WHERE post_type IN ('post', 'page');"); //returns formatted date like 13.08.2001 return date_i18n('j.m.Y', strtotime($thelatest)); } add_shortcode('latestupdatedate', 'get_latest_update_date'); ```
372,204
<p>I got one plugin which generates all CSS and JS on the /wp-content/uploads/xyz-folder, I want to disable all this CSS and JS load on my website page.</p> <p>Is it possible?</p>
[ { "answer_id": 372121, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 0, "selected": false, "text": "<p>I don't know if there's a more WP-friendly way to do this, but this query will do what you want. It gets the latest date from the posts table for any post or page:</p>\n<pre><code>select max(post_modified) from wp_posts where post_type IN ('post', 'page');\n</code></pre>\n<p>So you could wrap that up in a shortcode for example, like:</p>\n<pre><code>function get_latest_update_date() {\n global $wpdb;\n return $wpdb-&gt;get_var(&quot;SELECT max(post_modified) FROM wp_posts WHERE post_type IN ('post', 'page');&quot;);\n}\n\nadd_shortcode('latestupdatedate', 'get_latest_update_date');\n</code></pre>\n<p>If you want to format the date, you'll need to add the PHP date parsing/formatting functions.</p>\n" }, { "answer_id": 390499, "author": "user3792395", "author_id": 207730, "author_profile": "https://wordpress.stackexchange.com/users/207730", "pm_score": 1, "selected": false, "text": "<p>Just a continuation from mozboz' answer. For those curious as I was, you could use the date() or date_i18n() functions to format the date properly in the following snippet.</p>\n<pre><code>function get_latest_update_date() {\n global $wpdb;\n $thelatest = $wpdb-&gt;get_var(&quot;SELECT max(post_modified) FROM wp_posts WHERE post_type IN ('post', 'page');&quot;);\n //returns formatted date like 13.08.2001\n return date_i18n('j.m.Y', strtotime($thelatest));\n }\n \n add_shortcode('latestupdatedate', 'get_latest_update_date');\n</code></pre>\n" } ]
2020/08/01
[ "https://wordpress.stackexchange.com/questions/372204", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192540/" ]
I got one plugin which generates all CSS and JS on the /wp-content/uploads/xyz-folder, I want to disable all this CSS and JS load on my website page. Is it possible?
Just a continuation from mozboz' answer. For those curious as I was, you could use the date() or date\_i18n() functions to format the date properly in the following snippet. ``` function get_latest_update_date() { global $wpdb; $thelatest = $wpdb->get_var("SELECT max(post_modified) FROM wp_posts WHERE post_type IN ('post', 'page');"); //returns formatted date like 13.08.2001 return date_i18n('j.m.Y', strtotime($thelatest)); } add_shortcode('latestupdatedate', 'get_latest_update_date'); ```
372,280
<p>I've spent about 3 hours trying out various functions to figure out why the newline characters are being removed every time I save.</p> <p>How do I figure out why is wordpress suddenly stripping away newline characters? I have not installed any plugins. How can I get newline characters to show up on my site without converting all blocks to HTML and modifying everything in code?</p>
[ { "answer_id": 372281, "author": "Mugen", "author_id": 167402, "author_profile": "https://wordpress.stackexchange.com/users/167402", "pm_score": 2, "selected": true, "text": "<p>I found the following snippet which we can add to functions.php . I'm adding these via a plugin.</p>\n<pre><code>function clear_br($content) { \nreturn str_replace(&quot;&lt;br&gt;&quot;,&quot;&lt;br clear='none'&gt;&quot;, $content);\n} \nadd_filter('the_content','clear_br');\n</code></pre>\n<p>Note that I've put <code>&quot;&lt;br&gt;&quot;</code> tag which is what wordpress creates when you enter newline characters.</p>\n" }, { "answer_id": 402781, "author": "Nick", "author_id": 219316, "author_profile": "https://wordpress.stackexchange.com/users/219316", "pm_score": 0, "selected": false, "text": "<p>I have the same issue. For me with Beaver Builder I have to choose a Classic Block and then pasting with newlines works.</p>\n<p>Two useful links:</p>\n<ul>\n<li><a href=\"https://wpengine.co.uk/resources/wordpress-formatting-issues/\" rel=\"nofollow noreferrer\">https://wpengine.co.uk/resources/wordpress-formatting-issues/</a></li>\n<li><a href=\"https://webhostinghero.org/preserve-line-breaks-and-formatting-in-wordpress/\" rel=\"nofollow noreferrer\">https://webhostinghero.org/preserve-line-breaks-and-formatting-in-wordpress/</a></li>\n</ul>\n" } ]
2020/08/03
[ "https://wordpress.stackexchange.com/questions/372280", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/167402/" ]
I've spent about 3 hours trying out various functions to figure out why the newline characters are being removed every time I save. How do I figure out why is wordpress suddenly stripping away newline characters? I have not installed any plugins. How can I get newline characters to show up on my site without converting all blocks to HTML and modifying everything in code?
I found the following snippet which we can add to functions.php . I'm adding these via a plugin. ``` function clear_br($content) { return str_replace("<br>","<br clear='none'>", $content); } add_filter('the_content','clear_br'); ``` Note that I've put `"<br>"` tag which is what wordpress creates when you enter newline characters.
372,308
<p>I have a custom post type where the <code>title</code> is a name, and I want to sort the loop by the last word in <code>title</code>, the surname.</p> <p>I can easily break the names apart and filter by the last word in a custom query, but I don't want to re-write the main loop / pagination for the archive page. Is it possible to pass a callback to the <code>orderby</code> param in the action <code>pre_get_posts</code> or is this a lost cause?</p> <p>Thanks!</p>
[ { "answer_id": 372309, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For that to work it would need to query the results from the database first, but you'd get the wrong results because they're unsorted.</p>\n<p>You would need to use the <code>posts_orderby</code> filter to do this as part of the SQL query:</p>\n<pre><code>add_filter(\n 'posts_orderby',\n function( $orderby, $query ) {\n if ( ! is_admin() &amp;&amp; $query-&gt;is_post_type_archive( 'post_type_name' ) ) {\n $orderby = &quot;SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC&quot;;\n }\n \n return $orderby;\n },\n 10,\n 2\n);\n</code></pre>\n<p>That uses the <code>SUBSTRING_INDEX()</code> MySQL function to order results by everything after the <del>first</del> last space in the post title, and then by the post title so that results with matching surnames are sorted by first name.</p>\n" }, { "answer_id": 372360, "author": "jamesfacts", "author_id": 76674, "author_profile": "https://wordpress.stackexchange.com/users/76674", "pm_score": -1, "selected": false, "text": "<p>Just posting my code for posterity, I made some small changes to @Jacob Peatite's code, if anyone needs a drop-in solution:</p>\n<pre><code>add_filter('posts_orderby', __NAMESPACE__ . '\\surname_orderby', 10, 2);\nfunction surname_orderby($args, $wp_query)\n{\n //make sure this is not an admin dashboard query.\n if (is_admin()) {\n return;\n }\n //check if this is the main query, rather than a secondary query such as widgets or menus.\n if (!is_main_query()) {\n return;\n }\n\n // the wp query at this filter is literally just the orderby value, we need to fetch the queried object\n $queriedObj = $wp_query-&gt;get_queried_object();\n \n if (isset($queriedObj-&gt;name) &amp;&amp; $queriedObj-&gt;name === the_one_I_want ) {\n $args = &quot;SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC&quot;;\n return $args;\n }\n}\n</code></pre>\n" } ]
2020/08/04
[ "https://wordpress.stackexchange.com/questions/372308", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76674/" ]
I have a custom post type where the `title` is a name, and I want to sort the loop by the last word in `title`, the surname. I can easily break the names apart and filter by the last word in a custom query, but I don't want to re-write the main loop / pagination for the archive page. Is it possible to pass a callback to the `orderby` param in the action `pre_get_posts` or is this a lost cause? Thanks!
No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For that to work it would need to query the results from the database first, but you'd get the wrong results because they're unsorted. You would need to use the `posts_orderby` filter to do this as part of the SQL query: ``` add_filter( 'posts_orderby', function( $orderby, $query ) { if ( ! is_admin() && $query->is_post_type_archive( 'post_type_name' ) ) { $orderby = "SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC"; } return $orderby; }, 10, 2 ); ``` That uses the `SUBSTRING_INDEX()` MySQL function to order results by everything after the ~~first~~ last space in the post title, and then by the post title so that results with matching surnames are sorted by first name.
372,317
<p><strong>Hey guys</strong> I am developing a wp theme, and I am using for localhost server XAMPP and Wampserver.So anytime I save my changes specially for css and js it doesn't take effects immediately! sometimes it can takes up to 24h for the changes to take effects, how can I solve this issue, it really slowdown my work???</p>
[ { "answer_id": 372309, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For that to work it would need to query the results from the database first, but you'd get the wrong results because they're unsorted.</p>\n<p>You would need to use the <code>posts_orderby</code> filter to do this as part of the SQL query:</p>\n<pre><code>add_filter(\n 'posts_orderby',\n function( $orderby, $query ) {\n if ( ! is_admin() &amp;&amp; $query-&gt;is_post_type_archive( 'post_type_name' ) ) {\n $orderby = &quot;SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC&quot;;\n }\n \n return $orderby;\n },\n 10,\n 2\n);\n</code></pre>\n<p>That uses the <code>SUBSTRING_INDEX()</code> MySQL function to order results by everything after the <del>first</del> last space in the post title, and then by the post title so that results with matching surnames are sorted by first name.</p>\n" }, { "answer_id": 372360, "author": "jamesfacts", "author_id": 76674, "author_profile": "https://wordpress.stackexchange.com/users/76674", "pm_score": -1, "selected": false, "text": "<p>Just posting my code for posterity, I made some small changes to @Jacob Peatite's code, if anyone needs a drop-in solution:</p>\n<pre><code>add_filter('posts_orderby', __NAMESPACE__ . '\\surname_orderby', 10, 2);\nfunction surname_orderby($args, $wp_query)\n{\n //make sure this is not an admin dashboard query.\n if (is_admin()) {\n return;\n }\n //check if this is the main query, rather than a secondary query such as widgets or menus.\n if (!is_main_query()) {\n return;\n }\n\n // the wp query at this filter is literally just the orderby value, we need to fetch the queried object\n $queriedObj = $wp_query-&gt;get_queried_object();\n \n if (isset($queriedObj-&gt;name) &amp;&amp; $queriedObj-&gt;name === the_one_I_want ) {\n $args = &quot;SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC&quot;;\n return $args;\n }\n}\n</code></pre>\n" } ]
2020/08/04
[ "https://wordpress.stackexchange.com/questions/372317", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192491/" ]
**Hey guys** I am developing a wp theme, and I am using for localhost server XAMPP and Wampserver.So anytime I save my changes specially for css and js it doesn't take effects immediately! sometimes it can takes up to 24h for the changes to take effects, how can I solve this issue, it really slowdown my work???
No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For that to work it would need to query the results from the database first, but you'd get the wrong results because they're unsorted. You would need to use the `posts_orderby` filter to do this as part of the SQL query: ``` add_filter( 'posts_orderby', function( $orderby, $query ) { if ( ! is_admin() && $query->is_post_type_archive( 'post_type_name' ) ) { $orderby = "SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC"; } return $orderby; }, 10, 2 ); ``` That uses the `SUBSTRING_INDEX()` MySQL function to order results by everything after the ~~first~~ last space in the post title, and then by the post title so that results with matching surnames are sorted by first name.
372,338
<p>I have a plugin that has a meta field that keeps shares for the post in array format:</p> <pre><code>[&quot;facebook&quot; =&gt; 12, &quot;pinterest&quot; =&gt; 12] </code></pre> <p>I would like to get 3 most shared posts (by all shares combined) in custom WP Query, but not sure how to it as it only allows to provide meta filed and value, but not the function?</p> <p>Is it possible to have custom sorting function there?</p>
[ { "answer_id": 372309, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For that to work it would need to query the results from the database first, but you'd get the wrong results because they're unsorted.</p>\n<p>You would need to use the <code>posts_orderby</code> filter to do this as part of the SQL query:</p>\n<pre><code>add_filter(\n 'posts_orderby',\n function( $orderby, $query ) {\n if ( ! is_admin() &amp;&amp; $query-&gt;is_post_type_archive( 'post_type_name' ) ) {\n $orderby = &quot;SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC&quot;;\n }\n \n return $orderby;\n },\n 10,\n 2\n);\n</code></pre>\n<p>That uses the <code>SUBSTRING_INDEX()</code> MySQL function to order results by everything after the <del>first</del> last space in the post title, and then by the post title so that results with matching surnames are sorted by first name.</p>\n" }, { "answer_id": 372360, "author": "jamesfacts", "author_id": 76674, "author_profile": "https://wordpress.stackexchange.com/users/76674", "pm_score": -1, "selected": false, "text": "<p>Just posting my code for posterity, I made some small changes to @Jacob Peatite's code, if anyone needs a drop-in solution:</p>\n<pre><code>add_filter('posts_orderby', __NAMESPACE__ . '\\surname_orderby', 10, 2);\nfunction surname_orderby($args, $wp_query)\n{\n //make sure this is not an admin dashboard query.\n if (is_admin()) {\n return;\n }\n //check if this is the main query, rather than a secondary query such as widgets or menus.\n if (!is_main_query()) {\n return;\n }\n\n // the wp query at this filter is literally just the orderby value, we need to fetch the queried object\n $queriedObj = $wp_query-&gt;get_queried_object();\n \n if (isset($queriedObj-&gt;name) &amp;&amp; $queriedObj-&gt;name === the_one_I_want ) {\n $args = &quot;SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC&quot;;\n return $args;\n }\n}\n</code></pre>\n" } ]
2020/08/04
[ "https://wordpress.stackexchange.com/questions/372338", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121208/" ]
I have a plugin that has a meta field that keeps shares for the post in array format: ``` ["facebook" => 12, "pinterest" => 12] ``` I would like to get 3 most shared posts (by all shares combined) in custom WP Query, but not sure how to it as it only allows to provide meta filed and value, but not the function? Is it possible to have custom sorting function there?
No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For that to work it would need to query the results from the database first, but you'd get the wrong results because they're unsorted. You would need to use the `posts_orderby` filter to do this as part of the SQL query: ``` add_filter( 'posts_orderby', function( $orderby, $query ) { if ( ! is_admin() && $query->is_post_type_archive( 'post_type_name' ) ) { $orderby = "SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC"; } return $orderby; }, 10, 2 ); ``` That uses the `SUBSTRING_INDEX()` MySQL function to order results by everything after the ~~first~~ last space in the post title, and then by the post title so that results with matching surnames are sorted by first name.
372,347
<p>I have created a form where users update their profile. When a profile is created or updated it creates a CPT called course. The url is <code>the permalink + /course/ + the title of the course</code></p> <pre><code>/* CREATING COURSE PAGES FROM USER PROFILES */ function create_course_page( $user_id = '' ) { $user = new WP_User($user_id); if ( ! $user-&gt;ID ) return ''; // check if the user whose profile is updating has already a post global $wpdb; $course_post_exists = $wpdb-&gt;get_var( $wpdb-&gt;prepare( &quot;SELECT ID FROM $wpdb-&gt;posts WHERE post_name = %s AND post_type = 'course' and post_status = 'publish'&quot;, $user-&gt;course_name ) ); if ( ! in_array('instructor', $user-&gt;roles) ) return ''; $user_info = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user-&gt;ID ) ); $title = $user_info['course_name']; // of course create the content as you want $content = 'This is the page for: '; $content .= $user_info['description_course']; $post = array( 'post_title' =&gt; $title, 'post_name' =&gt; $user-&gt;course_name, 'post_content' =&gt; $content, 'post_status' =&gt; 'publish', 'post_type' =&gt; 'course' ); if ( $course_post_exists ) { $post['ID'] = $course_post_exists; wp_update_post( $post ); } else { wp_insert_post( $post ); } } add_action( 'personal_options_update', 'create_course_page' ); add_action( 'edit_user_profile_update', 'create_course_page' ); </code></pre> <p>The problem that I'm facing is that when someone changes the title of the course it creates a new post with this url.</p> <p>So I want to delete the old post when a title change is done on the course.</p> <p>NOTE: When changing title of the course it changes the URL, that is why I think it takes like a new post.</p> <p>I have customised this code a bit to do the job:</p> <pre><code>/* REMOVE OLD COURSES WHEN UPDATE */ add_action( 'admin_init', 'removing_older_posts' ); function removing_older_posts() { $args = array ( 'post_type' =&gt; 'course', 'author' =&gt; get_current_user_id(), 'orderby' =&gt; 'date', ); $query = new WP_Query( $args ); if ( $query-&gt;have_posts() ) { //if the current user has posts under his/her name $i = 0; //create post counter while ( $query-&gt;have_posts() ) { //loop through each post $query-&gt;the_post(); //get the current post if ($i &gt; 0) { //if you're not on the first post wp_delete_post( $query-&gt;post-&gt;ID, true ); //delete the post } $i++; //increment the post counter } wp_reset_postdata(); } } </code></pre> <p>But it isn't working.</p> <p>Appreciate any suggestion :)</p>
[ { "answer_id": 372348, "author": "Oliver Gehrmann", "author_id": 192667, "author_profile": "https://wordpress.stackexchange.com/users/192667", "pm_score": 1, "selected": false, "text": "<p>I think it would be helpful if you could explain why you're generating courses out of edits that a user's doing on his profile. The simplest solution seems to be a frontend form that just allows a user to create new posts or edit existing ones rather than going for this alternative solution where you're using the data from the profile page to create new posts.</p>\n<hr />\n<p>If you want to stick to the current implementation, I believe it would be useful for you to look into status transitions: <a href=\"https://developer.wordpress.org/reference/hooks/transition_post_status/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/transition_post_status/</a></p>\n<p>Here's some example code that I used to create a post in a the category with the ID 1 (= news) after a custom post type had been created:</p>\n<pre><code>// Automatically create a news when a wiki post has been published\nfunction nxt_create_news($new_status, $old_status, $nxt_wiki_post) {\n if('publish' === $new_status &amp;&amp; 'publish' !== $old_status &amp;&amp; $nxt_wiki_post-&gt;post_type === 'wiki') {\n $nxt_post_author = $nxt_wiki_post-&gt;post_author;\n $nxt_wiki_permalink = get_post_permalink($nxt_wiki_id);\n $nxt_wiki_title = $nxt_wiki_post-&gt;post_title;\n $nxt_postarr = array(\n 'post_author' =&gt; $nxt_post_author,\n 'post_content' =&gt; 'The wiki entry ' . $nxt_wiki_title . ' has just been published.&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;' . $nxt_wiki_permalink . '&quot; title=&quot;' . $nxt_wiki_title . '&quot;&gt;Check out wiki entry&lt;/a&gt;.',\n 'post_title' =&gt; 'The wiki entry ' . $nxt_wiki_title . ' has been published',\n 'post_status' =&gt; 'publish',\n 'post_category' =&gt; array(1),\n );\n $nxt_post_id = wp_insert_post($nxt_postarr);\n set_post_thumbnail(get_post($nxt_post_id), '1518');\n }\n}\nadd_action( 'transition_post_status', 'nxt_create_news', 10, 3 );\n</code></pre>\n<hr />\n<p>In your specific case, you can compare parts of the saved posts to the new post that would be created and then prevent the default action from happening (a new post being created) and instead just edit the old post.</p>\n<p>The main question would be how would the system know which post someone's trying to edit? I can't really answer that as I couldn't make out why you're using the profile edits to create new posts I'm afraid, but I hope this is helpful regardless. :-)</p>\n" }, { "answer_id": 372412, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p>You don't need to do any of that, and can sidestep the problem completely, and make the code faster and simpler!</p>\n<p>This is what we're going to do:</p>\n<ul>\n<li>We're going to use the course post author, not the name, it's more reliable</li>\n<li>We're going to avoid the raw SQL query so we can use caches and use <code>WP_Query</code></li>\n<li>We'll use <code>wp_insert_post</code> for both updating and creating the post</li>\n<li>Eliminate a useless <code>array_map</code> call</li>\n<li>Actually check if <code>wp_insert_post</code> was succesful or not</li>\n<li>We'll apply the WP coding standards to make it easier to read and nicer to work with, e.g. modern PHP arrays <code>[]</code> rather than <code>array()</code>, strict <code>in_array</code> checks, no global variables</li>\n<li>The code that figures out the course ID will be moved to its own function</li>\n</ul>\n<p>This way, when the course name changes, the original <code>course</code> post has its title and URL updated/changed, rather than creating a brand new <code>course</code> that requires cleanup of old courses.</p>\n<p>Here's something close to what should work:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function get_course_by_author( $user_id ) : int {\n // if we don't find anything then a value of 0 will create a new post rather than update an existing post.\n $course_id = 0;\n $args = [\n 'post_type' =&gt; 'course',\n 'posts_per_page' =&gt; 1,\n 'post_author' =&gt; $user_id,\n ];\n $query = new WP_Query( $args );\n if ( $query-&gt;have_posts() ) {\n while ( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n $course_id = get_the_ID();\n // we only want a single post ID\n break;\n }\n // cleanup after the query\n wp_reset_postdata();\n } else {\n // perhaps the course was created before post authors were set? Fall back to looking for the post by its slug/name\n return 0;\n }\n return $course_id;\n}\n\nfunction get_course_by_slug( string $slug ) : int {\n $course_id = 0;\n $args = [\n 'post_type' =&gt; 'course',\n 'posts_per_page' =&gt; 1,\n 'post_name' =&gt; $slug,\n ];\n ... etc etc see get_course_by_author ...\n return $course_id;\n}\n\nfunction handle_course_post( $user_id = '' ) {\n // First, is this user an instructor?\n $user = get_user_by( 'ID', $user_id );\n if ( ! $user || ! in_array( 'instructor', $user-&gt;roles, true ) ) {\n return;\n }\n\n // get the course name\n $course_name = get_user_meta( $user_id, 'course_name', true );\n if ( empty( $course_name ) {\n error_log( &quot;the user does not have a course_name!&quot; );\n }\n\n // Then lets find this users course if it exists.\n // if we don't find anything then a value of 0 will create a new post rather than update an existing post.\n $course_id = get_course_by_author( $user_id );\n if ( $course_id === 0 ) {\n // we didn't find a course with that author, try the course name.\n $course_id = get_course_by_slug( $course_name );\n }\n\n // Finally, save/update the course!\n $content = 'This is the page for: ';\n $content .= get_user_meta( $user_id, 'description_course', true );\n $args = [\n 'ID' =&gt; $course_id,\n 'post_title' =&gt; $course_name,\n 'post_name' =&gt; $course_name, // set the slug/permalink\n 'post_content' =&gt; $content,\n 'post_status' =&gt; 'publish',\n 'post_type' =&gt; 'course',\n ];\n $post_id = wp_insert_post( $args );\n\n // check if we were succesful.\n if ( is_wp_error( $post_id ) ) {\n // it didn't work!\n error_log( $post_id-&gt;get_error_message() );\n } else if ( empty( $post_id ) ) {\n // it didn't work!\n error_log( &quot;post_id is empty/false&quot; );\n }\n\n}\n\nadd_action( 'personal_options_update', 'handle_course_post' );\nadd_action( 'edit_user_profile_update', 'handle_course_post' );\n</code></pre>\n<p>Remember this is untested and will require some understanding, it can't be copy pasted as is ( although if it does work as is then yay! ).</p>\n<p>Notice that at the end we check if the call to <code>wp_insert_post</code> worked or not. We can't assume it was succesful, what if another user has already chosen that course name? What if the user is no longer an instructor?</p>\n<p>Also keep in mind that your existing <code>course</code> posts do not have the right author, they will need to be re-saved. Once this is done all cases will be handled. The code above will try to fetch the course post via its slug if it can't find it via the author, allowing a partial migration path.</p>\n<p>This does mean your original problem will still happen, but only to users who have never updated their profile, and immediatley change their course name. Those who save their profiles then change the name will be handled, as will all future users.</p>\n" } ]
2020/08/04
[ "https://wordpress.stackexchange.com/questions/372347", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/150823/" ]
I have created a form where users update their profile. When a profile is created or updated it creates a CPT called course. The url is `the permalink + /course/ + the title of the course` ``` /* CREATING COURSE PAGES FROM USER PROFILES */ function create_course_page( $user_id = '' ) { $user = new WP_User($user_id); if ( ! $user->ID ) return ''; // check if the user whose profile is updating has already a post global $wpdb; $course_post_exists = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type = 'course' and post_status = 'publish'", $user->course_name ) ); if ( ! in_array('instructor', $user->roles) ) return ''; $user_info = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user->ID ) ); $title = $user_info['course_name']; // of course create the content as you want $content = 'This is the page for: '; $content .= $user_info['description_course']; $post = array( 'post_title' => $title, 'post_name' => $user->course_name, 'post_content' => $content, 'post_status' => 'publish', 'post_type' => 'course' ); if ( $course_post_exists ) { $post['ID'] = $course_post_exists; wp_update_post( $post ); } else { wp_insert_post( $post ); } } add_action( 'personal_options_update', 'create_course_page' ); add_action( 'edit_user_profile_update', 'create_course_page' ); ``` The problem that I'm facing is that when someone changes the title of the course it creates a new post with this url. So I want to delete the old post when a title change is done on the course. NOTE: When changing title of the course it changes the URL, that is why I think it takes like a new post. I have customised this code a bit to do the job: ``` /* REMOVE OLD COURSES WHEN UPDATE */ add_action( 'admin_init', 'removing_older_posts' ); function removing_older_posts() { $args = array ( 'post_type' => 'course', 'author' => get_current_user_id(), 'orderby' => 'date', ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { //if the current user has posts under his/her name $i = 0; //create post counter while ( $query->have_posts() ) { //loop through each post $query->the_post(); //get the current post if ($i > 0) { //if you're not on the first post wp_delete_post( $query->post->ID, true ); //delete the post } $i++; //increment the post counter } wp_reset_postdata(); } } ``` But it isn't working. Appreciate any suggestion :)
I think it would be helpful if you could explain why you're generating courses out of edits that a user's doing on his profile. The simplest solution seems to be a frontend form that just allows a user to create new posts or edit existing ones rather than going for this alternative solution where you're using the data from the profile page to create new posts. --- If you want to stick to the current implementation, I believe it would be useful for you to look into status transitions: <https://developer.wordpress.org/reference/hooks/transition_post_status/> Here's some example code that I used to create a post in a the category with the ID 1 (= news) after a custom post type had been created: ``` // Automatically create a news when a wiki post has been published function nxt_create_news($new_status, $old_status, $nxt_wiki_post) { if('publish' === $new_status && 'publish' !== $old_status && $nxt_wiki_post->post_type === 'wiki') { $nxt_post_author = $nxt_wiki_post->post_author; $nxt_wiki_permalink = get_post_permalink($nxt_wiki_id); $nxt_wiki_title = $nxt_wiki_post->post_title; $nxt_postarr = array( 'post_author' => $nxt_post_author, 'post_content' => 'The wiki entry ' . $nxt_wiki_title . ' has just been published.<br /><br /><a href="' . $nxt_wiki_permalink . '" title="' . $nxt_wiki_title . '">Check out wiki entry</a>.', 'post_title' => 'The wiki entry ' . $nxt_wiki_title . ' has been published', 'post_status' => 'publish', 'post_category' => array(1), ); $nxt_post_id = wp_insert_post($nxt_postarr); set_post_thumbnail(get_post($nxt_post_id), '1518'); } } add_action( 'transition_post_status', 'nxt_create_news', 10, 3 ); ``` --- In your specific case, you can compare parts of the saved posts to the new post that would be created and then prevent the default action from happening (a new post being created) and instead just edit the old post. The main question would be how would the system know which post someone's trying to edit? I can't really answer that as I couldn't make out why you're using the profile edits to create new posts I'm afraid, but I hope this is helpful regardless. :-)
372,352
<p>I am using this code so that users can input <code>[photo no=&quot;1&quot;], [photo no=&quot;2&quot;], [photo no=&quot;3&quot;]</code> etc.. in their posts. However I heard that <code>extract</code> is an unsafe function to use. How could I modify this code to remove <code>extract</code>?</p> <pre><code> function photo_shortcode($atts){ extract(shortcode_atts(array( 'no' =&gt; 1, ), $atts)); $no = is_numeric($no) ? (int) $no : 1; $images = get_field('fl_gallery'); if ( !empty( $images ) ) { $image = $images[$no]; return ' $image['url'] ' ; } } </code></pre>
[ { "answer_id": 372355, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<p>It's very simple: Just assign the value of <code>shortcode_atts()</code> (which is an array) to a variable and use it to access the shortcode attributes in the same way you access the items in any other arrays:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$atts = shortcode_atts( array(\n 'no' =&gt; 1,\n), $atts );\n\n// Use $atts['no'] to get the value of the &quot;no&quot; attribute.\n$no = is_numeric( $atts['no'] ) ? (int) $atts['no'] : 1;\n</code></pre>\n" }, { "answer_id": 372356, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 0, "selected": false, "text": "<p><code>extract</code> brings variables from an array into local variables. It looks like in your case the only variable it does that with is <code>$no</code>, so you can replace extract with this code which will do the same thing:</p>\n<p>Replace:</p>\n<pre><code>extract(shortcode_atts(array(\n 'no' =&gt; 1,\n ), $atts));\n</code></pre>\n<p>with:</p>\n<pre><code>$arr = shortcode_atts(array(\n 'no' =&gt; 1,\n ), $atts);\n\n$no = $arr['no'];\n</code></pre>\n" } ]
2020/08/04
[ "https://wordpress.stackexchange.com/questions/372352", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40727/" ]
I am using this code so that users can input `[photo no="1"], [photo no="2"], [photo no="3"]` etc.. in their posts. However I heard that `extract` is an unsafe function to use. How could I modify this code to remove `extract`? ``` function photo_shortcode($atts){ extract(shortcode_atts(array( 'no' => 1, ), $atts)); $no = is_numeric($no) ? (int) $no : 1; $images = get_field('fl_gallery'); if ( !empty( $images ) ) { $image = $images[$no]; return ' $image['url'] ' ; } } ```
It's very simple: Just assign the value of `shortcode_atts()` (which is an array) to a variable and use it to access the shortcode attributes in the same way you access the items in any other arrays: ```php $atts = shortcode_atts( array( 'no' => 1, ), $atts ); // Use $atts['no'] to get the value of the "no" attribute. $no = is_numeric( $atts['no'] ) ? (int) $atts['no'] : 1; ```
372,358
<p>I'm searching how to make First Name and Last name fields <strong>required</strong> when we add a new user. Right now only <strong>username</strong> and <strong>Email</strong> fields are required.</p> <p>I found a way by adding <code>class=&quot;form-required&quot;</code> for the first and last name fields on the file <strong>user-new.php</strong>.</p> <p>But I'm looking for a method with adding code on <strong>function.php</strong> and not touch to the WordPress Core.</p> <p>Thanks.</p>
[ { "answer_id": 372966, "author": "Ahmad Wael", "author_id": 115635, "author_profile": "https://wordpress.stackexchange.com/users/115635", "pm_score": 0, "selected": false, "text": "<p>WordPress Codex Says:</p>\n<p>The following example demonstrates how to add a &quot;First Name&quot; field to the registration form as a required field. First Name is one of WordPress's built-in user meta types, but you can define any field or custom user meta you want. Just keep in mind that if you create custom user meta, you may need to create additional admin UI as well.</p>\n<pre class=\"lang-php prettyprint-override\"><code>\n//1. Add a new form element...\nadd_action( 'register_form', 'myplugin_register_form' );\nfunction myplugin_register_form() {\n\n $first_name = ( ! empty( $_POST['first_name'] ) ) ? sanitize_text_field( $_POST['first_name'] ) : '';\n \n ?&gt;\n &lt;p&gt;\n &lt;label for=&quot;first_name&quot;&gt;&lt;?php _e( 'First Name', 'mydomain' ) ?&gt;&lt;br /&gt;\n &lt;input type=&quot;text&quot; name=&quot;first_name&quot; id=&quot;first_name&quot; class=&quot;input&quot; value=&quot;&lt;?php echo esc_attr( $first_name ); ?&gt;&quot; size=&quot;25&quot; /&gt;&lt;/label&gt;\n &lt;/p&gt;\n &lt;?php\n }\n\n //2. Add validation. In this case, we make sure first_name is required.\n add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );\n function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {\n \n if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) &amp;&amp; trim( $_POST['first_name'] ) == '' ) {\n $errors-&gt;add( 'first_name_error', sprintf('&lt;strong&gt;%s&lt;/strong&gt;: %s',__( 'ERROR', 'mydomain' ),__( 'You must include a first name.', 'mydomain' ) ) );\n\n }\n\n return $errors;\n }\n\n //3. Finally, save our extra registration user meta.\n add_action( 'user_register', 'myplugin_user_register' );\n function myplugin_user_register( $user_id ) {\n if ( ! empty( $_POST['first_name'] ) ) {\n update_user_meta( $user_id, 'first_name', sanitize_text_field( $_POST['first_name'] ) );\n }\n }\n</code></pre>\n<p>this code can be added to functions.php file,</p>\n<p>further info could be found on <a href=\"https://codex.wordpress.org/Customizing_the_Registration_Form\" rel=\"nofollow noreferrer\">Wordpress codex</a></p>\n" }, { "answer_id": 372986, "author": "rozklad", "author_id": 47861, "author_profile": "https://wordpress.stackexchange.com/users/47861", "pm_score": 3, "selected": true, "text": "<p>If you were looking to make the fields required in the Wordpress admin form for adding new user as i understood from your question, where the output is not filterable, you could basically do what you described (adding form-required) on browser side</p>\n<pre class=\"lang-php prettyprint-override\"><code>function se372358_add_required_to_first_name_last_name(string $type) {\n\n if ( 'add-new-user' === $type ) {\n ?&gt;\n &lt;script type=&quot;text/javascript&quot;&gt;\n jQuery(function($) {\n $('#first_name, #last_name')\n .parents('tr')\n .addClass('form-required')\n .find('label')\n .append(' &lt;span class=&quot;description&quot;&gt;&lt;?php _e( '(required)' ); ?&gt;&lt;/span&gt;');\n });\n &lt;/script&gt;\n &lt;?php\n }\n\n return $type;\n}\n\nadd_action('user_new_form', 'se372358_add_required_to_first_name_last_name');\n</code></pre>\n<p><strong>Edit</strong></p>\n<p>In order to achieve the same on edit, you could use code like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function se372358_add_required_to_first_name_last_name_alternative() {\n ?&gt;\n &lt;script type=&quot;text/javascript&quot;&gt;\n jQuery(function($) {\n $('#createuser, #your-profile')\n .find('#first_name, #last_name')\n .parents('tr')\n .addClass('form-required')\n .find('label')\n .append(' &lt;span class=&quot;description&quot;&gt;&lt;?php _e( '(required)' ); ?&gt;&lt;/span&gt;');\n });\n &lt;/script&gt;\n &lt;?php\n}\n\nadd_action('admin_print_scripts', 'se372358_add_required_to_first_name_last_name_alternative', 20);\n\nfunction se372358_validate_first_name_last_name(WP_Error &amp;$errors) {\n\n if (!isset($_POST['first_name']) || empty($_POST['first_name'])) {\n $errors-&gt;add( 'empty_first_name', __( '&lt;strong&gt;Error&lt;/strong&gt;: Please enter first name.' ), array( 'form-field' =&gt; 'first_name' ) );\n }\n\n if (!isset($_POST['last_name']) || empty($_POST['last_name'])) {\n $errors-&gt;add( 'empty_last_name', __( '&lt;strong&gt;Error&lt;/strong&gt;: Please enter last name.' ), array( 'form-field' =&gt; 'last_name' ) );\n }\n return $errors;\n}\n\nadd_action( 'user_profile_update_errors', 'se372358_validate_first_name_last_name' );\n</code></pre>\n" }, { "answer_id": 373002, "author": "Ankit", "author_id": 51280, "author_profile": "https://wordpress.stackexchange.com/users/51280", "pm_score": 1, "selected": false, "text": "<p>You can achieve this without modifying the core files in WordPress, but for the sake of the same you have to override entire user-new.php file via <code>load-$pagenow</code> hook present in <code>wp-admin.php</code> file.</p>\n<p>Try the following.</p>\n<ol>\n<li><p>Create a folder named <code>core-template</code> inside your currently active theme. Create a file <code>user-new.php</code> inside that directory.</p>\n</li>\n<li><p>Paste following code to that file</p>\n</li>\n</ol>\n<pre><code>&lt;?php\n/**\n * New User Administration Screen.\n *\n * @package WordPress\n * @subpackage Administration\n */\n\n/** WordPress Administration Bootstrap */\nrequire_once( trailingslashit( ABSPATH ) . 'wp-admin/admin.php' );\n\nif ( is_multisite() ) {\n if ( ! current_user_can( 'create_users' ) &amp;&amp; ! current_user_can( 'promote_users' ) ) {\n wp_die(\n '&lt;h1&gt;' . __( 'You need a higher level of permission.' ) . '&lt;/h1&gt;' .\n '&lt;p&gt;' . __( 'Sorry, you are not allowed to add users to this network.' ) . '&lt;/p&gt;',\n 403\n );\n }\n} elseif ( ! current_user_can( 'create_users' ) ) {\n wp_die(\n '&lt;h1&gt;' . __( 'You need a higher level of permission.' ) . '&lt;/h1&gt;' .\n '&lt;p&gt;' . __( 'Sorry, you are not allowed to create users.' ) . '&lt;/p&gt;',\n 403\n );\n}\n\nif ( is_multisite() ) {\n add_filter( 'wpmu_signup_user_notification_email', 'admin_created_user_email' );\n}\n\nif ( isset( $_REQUEST['action'] ) &amp;&amp; 'adduser' == $_REQUEST['action'] ) {\n check_admin_referer( 'add-user', '_wpnonce_add-user' );\n\n $user_details = null;\n $user_email = wp_unslash( $_REQUEST['email'] );\n if ( false !== strpos( $user_email, '@' ) ) {\n $user_details = get_user_by( 'email', $user_email );\n } else {\n if ( current_user_can( 'manage_network_users' ) ) {\n $user_details = get_user_by( 'login', $user_email );\n } else {\n wp_redirect( add_query_arg( array( 'update' =&gt; 'enter_email' ), 'user-new.php' ) );\n die();\n }\n }\n\n if ( ! $user_details ) {\n wp_redirect( add_query_arg( array( 'update' =&gt; 'does_not_exist' ), 'user-new.php' ) );\n die();\n }\n\n if ( ! current_user_can( 'promote_user', $user_details-&gt;ID ) ) {\n wp_die(\n '&lt;h1&gt;' . __( 'You need a higher level of permission.' ) . '&lt;/h1&gt;' .\n '&lt;p&gt;' . __( 'Sorry, you are not allowed to add users to this network.' ) . '&lt;/p&gt;',\n 403\n );\n }\n\n // Adding an existing user to this blog\n $new_user_email = $user_details-&gt;user_email;\n $redirect = 'user-new.php';\n $username = $user_details-&gt;user_login;\n $user_id = $user_details-&gt;ID;\n if ( $username != null &amp;&amp; array_key_exists( $blog_id, get_blogs_of_user( $user_id ) ) ) {\n $redirect = add_query_arg( array( 'update' =&gt; 'addexisting' ), 'user-new.php' );\n } else {\n if ( isset( $_POST['noconfirmation'] ) &amp;&amp; current_user_can( 'manage_network_users' ) ) {\n $result = add_existing_user_to_blog(\n array(\n 'user_id' =&gt; $user_id,\n 'role' =&gt; $_REQUEST['role'],\n )\n );\n\n if ( ! is_wp_error( $result ) ) {\n $redirect = add_query_arg(\n array(\n 'update' =&gt; 'addnoconfirmation',\n 'user_id' =&gt; $user_id,\n ),\n 'user-new.php'\n );\n } else {\n $redirect = add_query_arg( array( 'update' =&gt; 'could_not_add' ), 'user-new.php' );\n }\n } else {\n $newuser_key = wp_generate_password( 20, false );\n add_option(\n 'new_user_' . $newuser_key,\n array(\n 'user_id' =&gt; $user_id,\n 'email' =&gt; $user_details-&gt;user_email,\n 'role' =&gt; $_REQUEST['role'],\n )\n );\n\n $roles = get_editable_roles();\n $role = $roles[ $_REQUEST['role'] ];\n\n /**\n * Fires immediately after a user is invited to join a site, but before the notification is sent.\n *\n * @since 4.4.0\n *\n * @param int $user_id The invited user's ID.\n * @param array $role The role of invited user.\n * @param string $newuser_key The key of the invitation.\n */\n do_action( 'invite_user', $user_id, $role, $newuser_key );\n\n $switched_locale = switch_to_locale( get_user_locale( $user_details ) );\n\n /* translators: 1: Site title, 2: Site URL, 3: User role, 4: Activation URL. */\n $message = __(\n 'Hi,\n\nYou\\'ve been invited to join \\'%1$s\\' at\n%2$s with the role of %3$s.\n\nPlease click the following link to confirm the invite:\n%4$s'\n );\n\n wp_mail(\n $new_user_email,\n sprintf(\n /* translators: Joining confirmation notification email subject. %s: Site title. */\n __( '[%s] Joining Confirmation' ),\n wp_specialchars_decode( get_option( 'blogname' ) )\n ),\n sprintf(\n $message,\n get_option( 'blogname' ),\n home_url(),\n wp_specialchars_decode( translate_user_role( $role['name'] ) ),\n home_url( &quot;/newbloguser/$newuser_key/&quot; )\n )\n );\n\n if ( $switched_locale ) {\n restore_previous_locale();\n }\n\n $redirect = add_query_arg( array( 'update' =&gt; 'add' ), 'user-new.php' );\n }\n }\n wp_redirect( $redirect );\n die();\n} elseif ( isset( $_REQUEST['action'] ) &amp;&amp; 'createuser' == $_REQUEST['action'] ) {\n check_admin_referer( 'create-user', '_wpnonce_create-user' );\n\n if ( ! current_user_can( 'create_users' ) ) {\n wp_die(\n '&lt;h1&gt;' . __( 'You need a higher level of permission.' ) . '&lt;/h1&gt;' .\n '&lt;p&gt;' . __( 'Sorry, you are not allowed to create users.' ) . '&lt;/p&gt;',\n 403\n );\n }\n\n if ( ! is_multisite() ) {\n $user_id = edit_user();\n\n if ( is_wp_error( $user_id ) ) {\n $add_user_errors = $user_id;\n } else {\n if ( current_user_can( 'list_users' ) ) {\n $redirect = 'users.php?update=add&amp;id=' . $user_id;\n } else {\n $redirect = add_query_arg( 'update', 'add', 'user-new.php' );\n }\n wp_redirect( $redirect );\n die();\n }\n } else {\n // Adding a new user to this site\n $new_user_email = wp_unslash( $_REQUEST['email'] );\n $user_details = wpmu_validate_user_signup( $_REQUEST['user_login'], $new_user_email );\n if ( is_wp_error( $user_details['errors'] ) &amp;&amp; $user_details['errors']-&gt;has_errors() ) {\n $add_user_errors = $user_details['errors'];\n } else {\n /** This filter is documented in wp-includes/user.php */\n $new_user_login = apply_filters( 'pre_user_login', sanitize_user( wp_unslash( $_REQUEST['user_login'] ), true ) );\n if ( isset( $_POST['noconfirmation'] ) &amp;&amp; current_user_can( 'manage_network_users' ) ) {\n add_filter( 'wpmu_signup_user_notification', '__return_false' ); // Disable confirmation email\n add_filter( 'wpmu_welcome_user_notification', '__return_false' ); // Disable welcome email\n }\n wpmu_signup_user(\n $new_user_login,\n $new_user_email,\n array(\n 'add_to_blog' =&gt; get_current_blog_id(),\n 'new_role' =&gt; $_REQUEST['role'],\n )\n );\n if ( isset( $_POST['noconfirmation'] ) &amp;&amp; current_user_can( 'manage_network_users' ) ) {\n $key = $wpdb-&gt;get_var( $wpdb-&gt;prepare( &quot;SELECT activation_key FROM {$wpdb-&gt;signups} WHERE user_login = %s AND user_email = %s&quot;, $new_user_login, $new_user_email ) );\n $new_user = wpmu_activate_signup( $key );\n if ( is_wp_error( $new_user ) ) {\n $redirect = add_query_arg( array( 'update' =&gt; 'addnoconfirmation' ), 'user-new.php' );\n } elseif ( ! is_user_member_of_blog( $new_user['user_id'] ) ) {\n $redirect = add_query_arg( array( 'update' =&gt; 'created_could_not_add' ), 'user-new.php' );\n } else {\n $redirect = add_query_arg(\n array(\n 'update' =&gt; 'addnoconfirmation',\n 'user_id' =&gt; $new_user['user_id'],\n ),\n 'user-new.php'\n );\n }\n } else {\n $redirect = add_query_arg( array( 'update' =&gt; 'newuserconfirmation' ), 'user-new.php' );\n }\n wp_redirect( $redirect );\n die();\n }\n }\n}\n\n$title = __( 'Add New User' );\n$parent_file = 'users.php';\n\n$do_both = false;\nif ( is_multisite() &amp;&amp; current_user_can( 'promote_users' ) &amp;&amp; current_user_can( 'create_users' ) ) {\n $do_both = true;\n}\n\n$help = '&lt;p&gt;' . __( 'To add a new user to your site, fill in the form on this screen and click the Add New User button at the bottom.' ) . '&lt;/p&gt;';\n\nif ( is_multisite() ) {\n $help .= '&lt;p&gt;' . __( 'Because this is a multisite installation, you may add accounts that already exist on the Network by specifying a username or email, and defining a role. For more options, such as specifying a password, you have to be a Network Administrator and use the hover link under an existing user&amp;#8217;s name to Edit the user profile under Network Admin &gt; All Users.' ) . '&lt;/p&gt;' .\n '&lt;p&gt;' . __( 'New users will receive an email letting them know they&amp;#8217;ve been added as a user for your site. This email will also contain their password. Check the box if you don&amp;#8217;t want the user to receive a welcome email.' ) . '&lt;/p&gt;';\n} else {\n $help .= '&lt;p&gt;' . __( 'New users are automatically assigned a password, which they can change after logging in. You can view or edit the assigned password by clicking the Show Password button. The username cannot be changed once the user has been added.' ) . '&lt;/p&gt;' .\n\n '&lt;p&gt;' . __( 'By default, new users will receive an email letting them know they&amp;#8217;ve been added as a user for your site. This email will also contain a password reset link. Uncheck the box if you don&amp;#8217;t want to send the new user a welcome email.' ) . '&lt;/p&gt;';\n}\n\n$help .= '&lt;p&gt;' . __( 'Remember to click the Add New User button at the bottom of this screen when you are finished.' ) . '&lt;/p&gt;';\n\nget_current_screen()-&gt;add_help_tab(\n array(\n 'id' =&gt; 'overview',\n 'title' =&gt; __( 'Overview' ),\n 'content' =&gt; $help,\n )\n);\n\nget_current_screen()-&gt;add_help_tab(\n array(\n 'id' =&gt; 'user-roles',\n 'title' =&gt; __( 'User Roles' ),\n 'content' =&gt; '&lt;p&gt;' . __( 'Here is a basic overview of the different user roles and the permissions associated with each one:' ) . '&lt;/p&gt;' .\n '&lt;ul&gt;' .\n '&lt;li&gt;' . __( 'Subscribers can read comments/comment/receive newsletters, etc. but cannot create regular site content.' ) . '&lt;/li&gt;' .\n '&lt;li&gt;' . __( 'Contributors can write and manage their posts but not publish posts or upload media files.' ) . '&lt;/li&gt;' .\n '&lt;li&gt;' . __( 'Authors can publish and manage their own posts, and are able to upload files.' ) . '&lt;/li&gt;' .\n '&lt;li&gt;' . __( 'Editors can publish posts, manage posts as well as manage other people&amp;#8217;s posts, etc.' ) . '&lt;/li&gt;' .\n '&lt;li&gt;' . __( 'Administrators have access to all the administration features.' ) . '&lt;/li&gt;' .\n '&lt;/ul&gt;',\n )\n);\n\nget_current_screen()-&gt;set_help_sidebar(\n '&lt;p&gt;&lt;strong&gt;' . __( 'For more information:' ) . '&lt;/strong&gt;&lt;/p&gt;' .\n '&lt;p&gt;' . __( '&lt;a href=&quot;https://wordpress.org/support/article/users-add-new-screen/&quot;&gt;Documentation on Adding New Users&lt;/a&gt;' ) . '&lt;/p&gt;' .\n '&lt;p&gt;' . __( '&lt;a href=&quot;https://wordpress.org/support/&quot;&gt;Support&lt;/a&gt;' ) . '&lt;/p&gt;'\n);\n\nwp_enqueue_script( 'wp-ajax-response' );\nwp_enqueue_script( 'user-profile' );\n\n/**\n * Filters whether to enable user auto-complete for non-super admins in Multisite.\n *\n * @since 3.4.0\n *\n * @param bool $enable Whether to enable auto-complete for non-super admins. Default false.\n */\nif ( is_multisite() &amp;&amp; current_user_can( 'promote_users' ) &amp;&amp; ! wp_is_large_network( 'users' )\n &amp;&amp; ( current_user_can( 'manage_network_users' ) || apply_filters( 'autocomplete_users_for_site_admins', false ) )\n) {\n wp_enqueue_script( 'user-suggest' );\n}\n\nrequire_once( ABSPATH . 'wp-admin/admin-header.php' );\n\nif ( isset( $_GET['update'] ) ) {\n $messages = array();\n if ( is_multisite() ) {\n $edit_link = '';\n if ( ( isset( $_GET['user_id'] ) ) ) {\n $user_id_new = absint( $_GET['user_id'] );\n if ( $user_id_new ) {\n $edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user_id_new ) ) );\n }\n }\n\n switch ( $_GET['update'] ) {\n case 'newuserconfirmation':\n $messages[] = __( 'Invitation email sent to new user. A confirmation link must be clicked before their account is created.' );\n break;\n case 'add':\n $messages[] = __( 'Invitation email sent to user. A confirmation link must be clicked for them to be added to your site.' );\n break;\n case 'addnoconfirmation':\n $message = __( 'User has been added to your site.' );\n\n if ( $edit_link ) {\n $message .= sprintf( ' &lt;a href=&quot;%s&quot;&gt;%s&lt;/a&gt;', $edit_link, __( 'Edit user' ) );\n }\n\n $messages[] = $message;\n break;\n case 'addexisting':\n $messages[] = __( 'That user is already a member of this site.' );\n break;\n case 'could_not_add':\n $add_user_errors = new WP_Error( 'could_not_add', __( 'That user could not be added to this site.' ) );\n break;\n case 'created_could_not_add':\n $add_user_errors = new WP_Error( 'created_could_not_add', __( 'User has been created, but could not be added to this site.' ) );\n break;\n case 'does_not_exist':\n $add_user_errors = new WP_Error( 'does_not_exist', __( 'The requested user does not exist.' ) );\n break;\n case 'enter_email':\n $add_user_errors = new WP_Error( 'enter_email', __( 'Please enter a valid email address.' ) );\n break;\n }\n } else {\n if ( 'add' == $_GET['update'] ) {\n $messages[] = __( 'User added.' );\n }\n }\n}\n?&gt;\n&lt;div class=&quot;wrap&quot;&gt;\n&lt;h1 id=&quot;add-new-user&quot;&gt;\n&lt;?php\nif ( current_user_can( 'create_users' ) ) {\n _e( 'Add New User' );\n} elseif ( current_user_can( 'promote_users' ) ) {\n _e( 'Add Existing User' );\n}\n?&gt;\n&lt;/h1&gt;\n\n&lt;?php if ( isset( $errors ) &amp;&amp; is_wp_error( $errors ) ) : ?&gt;\n &lt;div class=&quot;error&quot;&gt;\n &lt;ul&gt;\n &lt;?php\n foreach ( $errors-&gt;get_error_messages() as $err ) {\n echo &quot;&lt;li&gt;$err&lt;/li&gt;\\n&quot;;\n }\n ?&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;?php\nendif;\n\nif ( ! empty( $messages ) ) {\n foreach ( $messages as $msg ) {\n echo '&lt;div id=&quot;message&quot; class=&quot;updated notice is-dismissible&quot;&gt;&lt;p&gt;' . $msg . '&lt;/p&gt;&lt;/div&gt;';\n }\n}\n?&gt;\n\n&lt;?php if ( isset( $add_user_errors ) &amp;&amp; is_wp_error( $add_user_errors ) ) : ?&gt;\n &lt;div class=&quot;error&quot;&gt;\n &lt;?php\n foreach ( $add_user_errors-&gt;get_error_messages() as $message ) {\n echo &quot;&lt;p&gt;$message&lt;/p&gt;&quot;;\n }\n ?&gt;\n &lt;/div&gt;\n&lt;?php endif; ?&gt;\n&lt;div id=&quot;ajax-response&quot;&gt;&lt;/div&gt;\n\n&lt;?php\nif ( is_multisite() &amp;&amp; current_user_can( 'promote_users' ) ) {\n if ( $do_both ) {\n echo '&lt;h2 id=&quot;add-existing-user&quot;&gt;' . __( 'Add Existing User' ) . '&lt;/h2&gt;';\n }\n if ( ! current_user_can( 'manage_network_users' ) ) {\n echo '&lt;p&gt;' . __( 'Enter the email address of an existing user on this network to invite them to this site. That person will be sent an email asking them to confirm the invite.' ) . '&lt;/p&gt;';\n $label = __( 'Email' );\n $type = 'email';\n } else {\n echo '&lt;p&gt;' . __( 'Enter the email address or username of an existing user on this network to invite them to this site. That person will be sent an email asking them to confirm the invite.' ) . '&lt;/p&gt;';\n $label = __( 'Email or Username' );\n $type = 'text';\n }\n ?&gt;\n&lt;form method=&quot;post&quot; name=&quot;adduser&quot; id=&quot;adduser&quot; class=&quot;validate&quot; novalidate=&quot;novalidate&quot;\n &lt;?php\n /**\n * Fires inside the adduser form tag.\n *\n * @since 3.0.0\n */\n do_action( 'user_new_form_tag' );\n ?&gt;\n&gt;\n&lt;input name=&quot;action&quot; type=&quot;hidden&quot; value=&quot;adduser&quot; /&gt;\n &lt;?php wp_nonce_field( 'add-user', '_wpnonce_add-user' ); ?&gt;\n\n&lt;table class=&quot;form-table&quot; role=&quot;presentation&quot;&gt;\n &lt;tr class=&quot;form-field form-required&quot;&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;label for=&quot;adduser-email&quot;&gt;&lt;?php echo $label; ?&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;&lt;input name=&quot;email&quot; type=&quot;&lt;?php echo $type; ?&gt;&quot; id=&quot;adduser-email&quot; class=&quot;wp-suggest-user&quot; value=&quot;&quot; /&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr class=&quot;form-field&quot;&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;label for=&quot;adduser-role&quot;&gt;&lt;?php _e( 'Role' ); ?&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;&lt;select name=&quot;role&quot; id=&quot;adduser-role&quot;&gt;\n &lt;?php wp_dropdown_roles( get_option( 'default_role' ) ); ?&gt;\n &lt;/select&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php if ( current_user_can( 'manage_network_users' ) ) { ?&gt;\n &lt;tr&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;?php _e( 'Skip Confirmation Email' ); ?&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=&quot;checkbox&quot; name=&quot;noconfirmation&quot; id=&quot;adduser-noconfirmation&quot; value=&quot;1&quot; /&gt;\n &lt;label for=&quot;adduser-noconfirmation&quot;&gt;&lt;?php _e( 'Add the user without sending an email that requires their confirmation.' ); ?&gt;&lt;/label&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n&lt;?php } ?&gt;\n&lt;/table&gt;\n &lt;?php\n /**\n * Fires at the end of the new user form.\n *\n * Passes a contextual string to make both types of new user forms\n * uniquely targetable. Contexts are 'add-existing-user' (Multisite),\n * and 'add-new-user' (single site and network admin).\n *\n * @since 3.7.0\n *\n * @param string $type A contextual string specifying which type of new user form the hook follows.\n */\n do_action( 'user_new_form', 'add-existing-user' );\n ?&gt;\n &lt;?php submit_button( __( 'Add Existing User' ), 'primary', 'adduser', true, array( 'id' =&gt; 'addusersub' ) ); ?&gt;\n&lt;/form&gt;\n &lt;?php\n} // is_multisite()\n\nif ( current_user_can( 'create_users' ) ) {\n if ( $do_both ) {\n echo '&lt;h2 id=&quot;create-new-user&quot;&gt;' . __( 'Add New User' ) . '&lt;/h2&gt;';\n }\n ?&gt;\n&lt;p&gt;&lt;?php _e( 'Create a brand new user and add them to this site.' ); ?&gt;&lt;/p&gt;\n&lt;form method=&quot;post&quot; name=&quot;createuser&quot; id=&quot;createuser&quot; class=&quot;validate&quot; novalidate=&quot;novalidate&quot;\n &lt;?php\n /** This action is documented in wp-admin/user-new.php */\n do_action( 'user_new_form_tag' );\n ?&gt;\n&gt;\n&lt;input name=&quot;action&quot; type=&quot;hidden&quot; value=&quot;createuser&quot; /&gt;\n &lt;?php wp_nonce_field( 'create-user', '_wpnonce_create-user' ); ?&gt;\n &lt;?php\n // Load up the passed data, else set to a default.\n $creating = isset( $_POST['createuser'] );\n\n $new_user_login = $creating &amp;&amp; isset( $_POST['user_login'] ) ? wp_unslash( $_POST['user_login'] ) : '';\n $new_user_firstname = $creating &amp;&amp; isset( $_POST['first_name'] ) ? wp_unslash( $_POST['first_name'] ) : '';\n $new_user_lastname = $creating &amp;&amp; isset( $_POST['last_name'] ) ? wp_unslash( $_POST['last_name'] ) : '';\n $new_user_email = $creating &amp;&amp; isset( $_POST['email'] ) ? wp_unslash( $_POST['email'] ) : '';\n $new_user_uri = $creating &amp;&amp; isset( $_POST['url'] ) ? wp_unslash( $_POST['url'] ) : '';\n $new_user_role = $creating &amp;&amp; isset( $_POST['role'] ) ? wp_unslash( $_POST['role'] ) : '';\n $new_user_send_notification = $creating &amp;&amp; ! isset( $_POST['send_user_notification'] ) ? false : true;\n $new_user_ignore_pass = $creating &amp;&amp; isset( $_POST['noconfirmation'] ) ? wp_unslash( $_POST['noconfirmation'] ) : '';\n\n ?&gt;\n&lt;table class=&quot;form-table&quot; role=&quot;presentation&quot;&gt;\n &lt;tr class=&quot;form-field form-required&quot;&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;label for=&quot;user_login&quot;&gt;&lt;?php _e( 'Username' ); ?&gt; &lt;span class=&quot;description&quot;&gt;&lt;?php _e( '(required)' ); ?&gt;&lt;/span&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;&lt;input name=&quot;user_login&quot; type=&quot;text&quot; id=&quot;user_login&quot; value=&quot;&lt;?php echo esc_attr( $new_user_login ); ?&gt;&quot; aria-required=&quot;true&quot; autocapitalize=&quot;none&quot; autocorrect=&quot;off&quot; maxlength=&quot;60&quot; /&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr class=&quot;form-field form-required&quot;&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;label for=&quot;email&quot;&gt;&lt;?php _e( 'Email' ); ?&gt; &lt;span class=&quot;description&quot;&gt;&lt;?php _e( '(required)' ); ?&gt;&lt;/span&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;&lt;input name=&quot;email&quot; type=&quot;email&quot; id=&quot;email&quot; value=&quot;&lt;?php echo esc_attr( $new_user_email ); ?&gt;&quot; /&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php if ( ! is_multisite() ) { ?&gt;\n &lt;tr class=&quot;form-field&quot;&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;label for=&quot;first_name&quot;&gt;&lt;?php _e( 'First Name (Required)' ); ?&gt; &lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;&lt;input name=&quot;first_name&quot; type=&quot;text&quot; id=&quot;first_name&quot; class=&quot;form-required&quot; value=&quot;&lt;?php echo esc_attr( $new_user_firstname ); ?&gt;&quot; /&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr class=&quot;form-field&quot;&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;label for=&quot;last_name&quot;&gt;&lt;?php _e( 'Last Name (Required)' ); ?&gt; &lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;&lt;input name=&quot;last_name&quot; type=&quot;text&quot; id=&quot;last_name&quot; class=&quot;form-required&quot; value=&quot;&lt;?php echo esc_attr( $new_user_lastname ); ?&gt;&quot; /&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr class=&quot;form-field&quot;&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;label for=&quot;url&quot;&gt;&lt;?php _e( 'Website' ); ?&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;&lt;input name=&quot;url&quot; type=&quot;url&quot; id=&quot;url&quot; class=&quot;code&quot; value=&quot;&lt;?php echo esc_attr( $new_user_uri ); ?&gt;&quot; /&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr class=&quot;form-field form-required user-pass1-wrap&quot;&gt;\n &lt;th scope=&quot;row&quot;&gt;\n &lt;label for=&quot;pass1&quot;&gt;\n &lt;?php _e( 'Password' ); ?&gt;\n &lt;span class=&quot;description hide-if-js&quot;&gt;&lt;?php _e( '(required)' ); ?&gt;&lt;/span&gt;\n &lt;/label&gt;\n &lt;/th&gt;\n &lt;td&gt;\n &lt;input class=&quot;hidden&quot; value=&quot; &quot; /&gt;&lt;!-- #24364 workaround --&gt;\n &lt;button type=&quot;button&quot; class=&quot;button wp-generate-pw hide-if-no-js&quot;&gt;&lt;?php _e( 'Show password' ); ?&gt;&lt;/button&gt;\n &lt;div class=&quot;wp-pwd hide-if-js&quot;&gt;\n &lt;?php $initial_password = wp_generate_password( 24 ); ?&gt;\n &lt;span class=&quot;password-input-wrapper&quot;&gt;\n &lt;input type=&quot;password&quot; name=&quot;pass1&quot; id=&quot;pass1&quot; class=&quot;regular-text&quot; autocomplete=&quot;off&quot; data-reveal=&quot;1&quot; data-pw=&quot;&lt;?php echo esc_attr( $initial_password ); ?&gt;&quot; aria-describedby=&quot;pass-strength-result&quot; /&gt;\n &lt;/span&gt;\n &lt;button type=&quot;button&quot; class=&quot;button wp-hide-pw hide-if-no-js&quot; data-toggle=&quot;0&quot; aria-label=&quot;&lt;?php esc_attr_e( 'Hide password' ); ?&gt;&quot;&gt;\n &lt;span class=&quot;dashicons dashicons-hidden&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt;\n &lt;span class=&quot;text&quot;&gt;&lt;?php _e( 'Hide' ); ?&gt;&lt;/span&gt;\n &lt;/button&gt;\n &lt;button type=&quot;button&quot; class=&quot;button wp-cancel-pw hide-if-no-js&quot; data-toggle=&quot;0&quot; aria-label=&quot;&lt;?php esc_attr_e( 'Cancel password change' ); ?&gt;&quot;&gt;\n &lt;span class=&quot;dashicons dashicons-no&quot; aria-hidden=&quot;true&quot;&gt;&lt;/span&gt;\n &lt;span class=&quot;text&quot;&gt;&lt;?php _e( 'Cancel' ); ?&gt;&lt;/span&gt;\n &lt;/button&gt;\n &lt;div style=&quot;display:none&quot; id=&quot;pass-strength-result&quot; aria-live=&quot;polite&quot;&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr class=&quot;form-field form-required user-pass2-wrap hide-if-js&quot;&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;label for=&quot;pass2&quot;&gt;&lt;?php _e( 'Repeat Password' ); ?&gt; &lt;span class=&quot;description&quot;&gt;&lt;?php _e( '(required)' ); ?&gt;&lt;/span&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input name=&quot;pass2&quot; type=&quot;password&quot; id=&quot;pass2&quot; autocomplete=&quot;off&quot; /&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr class=&quot;pw-weak&quot;&gt;\n &lt;th&gt;&lt;?php _e( 'Confirm Password' ); ?&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;label&gt;\n &lt;input type=&quot;checkbox&quot; name=&quot;pw_weak&quot; class=&quot;pw-checkbox&quot; /&gt;\n &lt;?php _e( 'Confirm use of weak password' ); ?&gt;\n &lt;/label&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;?php _e( 'Send User Notification' ); ?&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=&quot;checkbox&quot; name=&quot;send_user_notification&quot; id=&quot;send_user_notification&quot; value=&quot;1&quot; &lt;?php checked( $new_user_send_notification ); ?&gt; /&gt;\n &lt;label for=&quot;send_user_notification&quot;&gt;&lt;?php _e( 'Send the new user an email about their account.' ); ?&gt;&lt;/label&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n&lt;?php } // !is_multisite ?&gt;\n &lt;tr class=&quot;form-field&quot;&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;label for=&quot;role&quot;&gt;&lt;?php _e( 'Role' ); ?&gt;&lt;/label&gt;&lt;/th&gt;\n &lt;td&gt;&lt;select name=&quot;role&quot; id=&quot;role&quot;&gt;\n &lt;?php\n if ( ! $new_user_role ) {\n $new_user_role = ! empty( $current_role ) ? $current_role : get_option( 'default_role' );\n }\n wp_dropdown_roles( $new_user_role );\n ?&gt;\n &lt;/select&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php if ( is_multisite() &amp;&amp; current_user_can( 'manage_network_users' ) ) { ?&gt;\n &lt;tr&gt;\n &lt;th scope=&quot;row&quot;&gt;&lt;?php _e( 'Skip Confirmation Email' ); ?&gt;&lt;/th&gt;\n &lt;td&gt;\n &lt;input type=&quot;checkbox&quot; name=&quot;noconfirmation&quot; id=&quot;noconfirmation&quot; value=&quot;1&quot; &lt;?php checked( $new_user_ignore_pass ); ?&gt; /&gt;\n &lt;label for=&quot;noconfirmation&quot;&gt;&lt;?php _e( 'Add the user without sending an email that requires their confirmation.' ); ?&gt;&lt;/label&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;?php } ?&gt;\n&lt;/table&gt;\n\n &lt;?php\n /** This action is documented in wp-admin/user-new.php */\n do_action( 'user_new_form', 'add-new-user' );\n ?&gt;\n\n &lt;?php submit_button( __( 'Add New User' ), 'primary', 'createuser', true, array( 'id' =&gt; 'createusersub' ) ); ?&gt;\n\n&lt;/form&gt;\n&lt;?php } // current_user_can('create_users') ?&gt;\n&lt;/div&gt;\n&lt;?php\ninclude( trailingslashit( ABSPATH ) . 'wp-admin/admin-footer.php' );\n</code></pre>\n<p>Note that this is the same code as user-new.php, but now you have the control of what needs to be changed in that file.</p>\n<ol start=\"3\">\n<li>Now, you need to tell wordpress to load that file instead of its core <code>user-new.php</code>, create following function in functions.php of your theme.</li>\n</ol>\n<pre><code>function se_372358_user_new_template() {\n require_once( get_stylesheet_directory() . '/core-template/user-new.php' );\n die();\n}\nadd_action( 'load-user-new.php', 'se_372358_user_new_template' );\n</code></pre>\n<p>You should now be able to see your new template being loaded.</p>\n" } ]
2020/08/04
[ "https://wordpress.stackexchange.com/questions/372358", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119785/" ]
I'm searching how to make First Name and Last name fields **required** when we add a new user. Right now only **username** and **Email** fields are required. I found a way by adding `class="form-required"` for the first and last name fields on the file **user-new.php**. But I'm looking for a method with adding code on **function.php** and not touch to the WordPress Core. Thanks.
If you were looking to make the fields required in the Wordpress admin form for adding new user as i understood from your question, where the output is not filterable, you could basically do what you described (adding form-required) on browser side ```php function se372358_add_required_to_first_name_last_name(string $type) { if ( 'add-new-user' === $type ) { ?> <script type="text/javascript"> jQuery(function($) { $('#first_name, #last_name') .parents('tr') .addClass('form-required') .find('label') .append(' <span class="description"><?php _e( '(required)' ); ?></span>'); }); </script> <?php } return $type; } add_action('user_new_form', 'se372358_add_required_to_first_name_last_name'); ``` **Edit** In order to achieve the same on edit, you could use code like this: ```php function se372358_add_required_to_first_name_last_name_alternative() { ?> <script type="text/javascript"> jQuery(function($) { $('#createuser, #your-profile') .find('#first_name, #last_name') .parents('tr') .addClass('form-required') .find('label') .append(' <span class="description"><?php _e( '(required)' ); ?></span>'); }); </script> <?php } add_action('admin_print_scripts', 'se372358_add_required_to_first_name_last_name_alternative', 20); function se372358_validate_first_name_last_name(WP_Error &$errors) { if (!isset($_POST['first_name']) || empty($_POST['first_name'])) { $errors->add( 'empty_first_name', __( '<strong>Error</strong>: Please enter first name.' ), array( 'form-field' => 'first_name' ) ); } if (!isset($_POST['last_name']) || empty($_POST['last_name'])) { $errors->add( 'empty_last_name', __( '<strong>Error</strong>: Please enter last name.' ), array( 'form-field' => 'last_name' ) ); } return $errors; } add_action( 'user_profile_update_errors', 'se372358_validate_first_name_last_name' ); ```
372,359
<p>How to make wp_enqueue_style and wp_enqueue_script work only on custom post type</p> <p>I have install plugin on my wordpress that creat custom post type which is &quot;http://localhost/wordpress/manga&quot; and i have other custom post type like &quot;http://localhost/wordpress/anime&quot; so i only want to css work on manga not anime or in the front page</p> <p>this is the code: wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css' );</p>
[ { "answer_id": 372362, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": true, "text": "<p>You can use <a href=\"https://developer.wordpress.org/themes/basics/conditional-tags/\" rel=\"nofollow noreferrer\">conditionals</a>:</p>\n<pre><code>&lt;?php\nadd_action( 'wp_enqueue_scripts', 'wpse_enqueues' );\nfunction wpse_enqueues() {\n // Only enqueue on specified single CPTs\n if( is_singular( array( 'anime', 'manga' ) ) ) {\n wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css' );\n }\n}\n?&gt;\n</code></pre>\n<p>If you need the CSS on archives as well, that's another condition:</p>\n<pre><code>if( is_singular( array( 'anime', 'manga' ) ) || is_post_type_archive( array( 'anime, 'manga' ) ) ) {\n wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css' \n}\n</code></pre>\n" }, { "answer_id": 372363, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 0, "selected": false, "text": "<p>Perhaps you're looking for <a href=\"https://developer.wordpress.org/reference/functions/is_singular/\" rel=\"nofollow noreferrer\"><code>is_singular</code></a>, which you could put in e.g. your theme or functions.php to test for your CPT like:</p>\n<pre><code>if (is_singular('anime')) {\n wp_enqueue_style( ... ) ; \n}\n</code></pre>\n" } ]
2020/08/04
[ "https://wordpress.stackexchange.com/questions/372359", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165624/" ]
How to make wp\_enqueue\_style and wp\_enqueue\_script work only on custom post type I have install plugin on my wordpress that creat custom post type which is "http://localhost/wordpress/manga" and i have other custom post type like "http://localhost/wordpress/anime" so i only want to css work on manga not anime or in the front page this is the code: wp\_enqueue\_style( 'wp-manga-plugin-css', WP\_MANGA\_URI . 'assets/css/style.css' );
You can use [conditionals](https://developer.wordpress.org/themes/basics/conditional-tags/): ``` <?php add_action( 'wp_enqueue_scripts', 'wpse_enqueues' ); function wpse_enqueues() { // Only enqueue on specified single CPTs if( is_singular( array( 'anime', 'manga' ) ) ) { wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css' ); } } ?> ``` If you need the CSS on archives as well, that's another condition: ``` if( is_singular( array( 'anime', 'manga' ) ) || is_post_type_archive( array( 'anime, 'manga' ) ) ) { wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css' } ```
372,368
<p>I have a Wordpress site that is built to be a job listing board, and I'm looking to create SEO friendly URLs based on data that is stored in the database.</p> <p>The URL structure should include the state abbreviation, city, and job title, and result in the following format: <a href="http://www.domain.com/job/ca/sacramento/janitor" rel="nofollow noreferrer">www.domain.com/job/ca/sacramento/janitor</a></p> <p>There is currently a &quot;Job&quot; page in the backend that uses custom page template located at 'page-templages/job-template.php' that displays the database information at the following URL: <a href="http://www.domain.com/job/?2020-412341235134" rel="nofollow noreferrer">www.domain.com/job/?2020-412341235134</a></p> <p>How can I display the <a href="http://www.domain.com/job/?2020-412341235134" rel="nofollow noreferrer">www.domain.com/job/?2020-412341235134</a> at the friendly virtual URL <a href="http://www.domain.com/job/ca/sacramento/janitor" rel="nofollow noreferrer">www.domain.com/job/ca/sacramento/janitor</a>.</p> <p>Here's how I'm accessing the database information in my current page template.</p> <pre><code>$job_title = $job[0]['job_title']; $sanitized_job_title = str_replace(&quot; &quot;, &quot;-&quot;, $job_title); $bloginfo_url = get_bloginfo('url'); $friendly_url = $bloginfo_url . '/job/'. $job[0]['city'].'/'. $job[0]['state'] .'/'. $sanitized_job_title; </code></pre> <p>I've read through the add_rewrite_rule() documentation, and can't seem to get my head around it.</p> <p>Any help would be greatly appreciated.</p>
[ { "answer_id": 372377, "author": "Rolando Garcia", "author_id": 112988, "author_profile": "https://wordpress.stackexchange.com/users/112988", "pm_score": 0, "selected": false, "text": "<p>One approach could be to create a rewrite rule that will catch the 3 variables and provide them as parameters that can be passed on to your job template. Assuming your template slug is &quot;job&quot;:</p>\n<pre><code>function jobquery_rewrite_rule() {\n add_rewrite_rule(\n '^job/([^/]*)/([^/]*)/([^/]*)/?',\n 'index.php?pagename=job&amp;state=$matches[1]&amp;city=$matches[2]&amp;job=$matches[3]',\n 'top'\n );\n}\nadd_action( 'init', 'jobquery_rewrite_rule' );\n</code></pre>\n<p>After inserting this action into your theme, you must refresh the permalink rule cache by visiting Settings &gt; Permalinks for this new rewrite rule to take effect.</p>\n<p>These creates 3 new GET parameters that you can now access in your job template, but first you need to allow them to be accessed using query_vars_filter to create safe variables from each of them:</p>\n<pre><code>add_filter( 'query_vars', 'add_query_vars_filter' );\nfunction add_query_vars_filter( $vars ) {\n $vars[] = 'state';\n $vars[] = 'city';\n $vars[] = 'job';\n return $vars;\n}\n</code></pre>\n<p>Without having your full custom post structure or meta fields, it would be kind of tough for me to write what the query is, but somehow in your job template you should be able to capture these GET vars into vars you need to build a 'reverse' wp_query to get your post content for that job:</p>\n<pre><code>$state_var = get_query_var('state');\n$city_var = get_query_var('city');\n$job_var = get_query_var('job');\n\n//Use something like this to find the job based off the passed params\n$args = array(\n 'post_type' =&gt; 'job',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'job_state',\n 'value' =&gt; $state_var,\n ),\n array(\n 'key' =&gt; 'job_city',\n 'value' =&gt; $city_var,\n ),\n array(\n 'key' =&gt; 'job_title',\n 'value' =&gt; $job_var,\n ),\n ),\n);\n$query = new WP_Query( $args );\n</code></pre>\n" }, { "answer_id": 372482, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 1, "selected": false, "text": "<blockquote>\n<p>How can I display the <a href=\"http://www.domain.com/job/?2020-412341235134\" rel=\"nofollow noreferrer\">www.domain.com/job/?2020-412341235134</a> at the friendly virtual URL <a href=\"http://www.domain.com/job/ca/sacramento/janitor\" rel=\"nofollow noreferrer\">www.domain.com/job/ca/sacramento/janitor</a></p>\n</blockquote>\n<p>Well, you can't do that easily because the job ID in the first URL is not contained directly in the second URL, so you would have to do something complicated where you look up the job based on the parameters 'ca/sacramento/janitor' and this introduces a ton of complexity.</p>\n<p>A simpler approach, which you'll see on many big websites is to include the ID and the SEO friendly stuff in the same URL, so that it's good for SEO but also very easy to work with in code because it has the ID. This also means that if e.g. the city the job is in changes, any links to the old URL with the old city will still work fine. In your previous approach if the city changed, then any URL's anywhere on the web with the old city would break unless you did some very complicated matching.</p>\n<p>So I'd suggest you make your URL look like this:</p>\n<pre><code>www.domain.com/job/ca/sacramento/janitor-2020-412341235134\n</code></pre>\n<p>And now all you need is a simple rewrite rule in Wordpress or direct in .htaccess to do that mapping. For quickness here's an .htaccess example, but you could probably also achieve this with <code>add_rewrite_rule</code>, you just would need to figure out how to map the URL parameters to an <code>index.php</code> page.</p>\n<pre><code>RewriteRule ^/job/[^/]+/[^/]+/[^-]*-(\\d+-\\d+)$ job/?$1 [L, NC]\n</code></pre>\n<p>So this says:</p>\n<ul>\n<li><code>/job/</code> - match this specific string</li>\n<li><code>[^/]+/</code> - two URL parameters that don't contain '/' but have an / on the end, so this will match up to <code>/job/ca/sacramento/</code></li>\n<li><code>[^-]+-</code> - anything that doesn't include <code>-</code> with an <code>-</code> on the end, so this will match up to <code>/job/ca/sacramento/janitor-</code></li>\n<li><code>(\\d+-\\d+)</code> - capture two strings of digits with `- in the middle</li>\n</ul>\n<p><strong>This htaccess rule is untested, but you can see the approach I'm suggesting here, and please reply here to work through bugs in this RewriteRule if you use it</strong></p>\n<p>Notes:</p>\n<ul>\n<li>The htaccess rule would need to go outside and above the WP rules in the root .htaccess</li>\n<li>Similar approach could be used for a WP add_rewrite_rule, you just need to figure out the right index.php parameters.</li>\n</ul>\n" } ]
2020/08/04
[ "https://wordpress.stackexchange.com/questions/372368", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192677/" ]
I have a Wordpress site that is built to be a job listing board, and I'm looking to create SEO friendly URLs based on data that is stored in the database. The URL structure should include the state abbreviation, city, and job title, and result in the following format: [www.domain.com/job/ca/sacramento/janitor](http://www.domain.com/job/ca/sacramento/janitor) There is currently a "Job" page in the backend that uses custom page template located at 'page-templages/job-template.php' that displays the database information at the following URL: [www.domain.com/job/?2020-412341235134](http://www.domain.com/job/?2020-412341235134) How can I display the [www.domain.com/job/?2020-412341235134](http://www.domain.com/job/?2020-412341235134) at the friendly virtual URL [www.domain.com/job/ca/sacramento/janitor](http://www.domain.com/job/ca/sacramento/janitor). Here's how I'm accessing the database information in my current page template. ``` $job_title = $job[0]['job_title']; $sanitized_job_title = str_replace(" ", "-", $job_title); $bloginfo_url = get_bloginfo('url'); $friendly_url = $bloginfo_url . '/job/'. $job[0]['city'].'/'. $job[0]['state'] .'/'. $sanitized_job_title; ``` I've read through the add\_rewrite\_rule() documentation, and can't seem to get my head around it. Any help would be greatly appreciated.
> > How can I display the [www.domain.com/job/?2020-412341235134](http://www.domain.com/job/?2020-412341235134) at the friendly virtual URL [www.domain.com/job/ca/sacramento/janitor](http://www.domain.com/job/ca/sacramento/janitor) > > > Well, you can't do that easily because the job ID in the first URL is not contained directly in the second URL, so you would have to do something complicated where you look up the job based on the parameters 'ca/sacramento/janitor' and this introduces a ton of complexity. A simpler approach, which you'll see on many big websites is to include the ID and the SEO friendly stuff in the same URL, so that it's good for SEO but also very easy to work with in code because it has the ID. This also means that if e.g. the city the job is in changes, any links to the old URL with the old city will still work fine. In your previous approach if the city changed, then any URL's anywhere on the web with the old city would break unless you did some very complicated matching. So I'd suggest you make your URL look like this: ``` www.domain.com/job/ca/sacramento/janitor-2020-412341235134 ``` And now all you need is a simple rewrite rule in Wordpress or direct in .htaccess to do that mapping. For quickness here's an .htaccess example, but you could probably also achieve this with `add_rewrite_rule`, you just would need to figure out how to map the URL parameters to an `index.php` page. ``` RewriteRule ^/job/[^/]+/[^/]+/[^-]*-(\d+-\d+)$ job/?$1 [L, NC] ``` So this says: * `/job/` - match this specific string * `[^/]+/` - two URL parameters that don't contain '/' but have an / on the end, so this will match up to `/job/ca/sacramento/` * `[^-]+-` - anything that doesn't include `-` with an `-` on the end, so this will match up to `/job/ca/sacramento/janitor-` * `(\d+-\d+)` - capture two strings of digits with `- in the middle **This htaccess rule is untested, but you can see the approach I'm suggesting here, and please reply here to work through bugs in this RewriteRule if you use it** Notes: * The htaccess rule would need to go outside and above the WP rules in the root .htaccess * Similar approach could be used for a WP add\_rewrite\_rule, you just need to figure out the right index.php parameters.
372,421
<p>I am trying to give users an option to select &quot;Exclude from homepage bloglist&quot; on a post, and then pick this up on my homepage query so certain posts won't surface on the homepage.</p> <p>I'm using the Wordpress custom field &quot;true/false&quot;.</p> <p>On a post where the box has been ticked, I would assume this post would then not surface on the homepage based on the below query args:</p> <pre><code>$query_args = array( 'meta_query' =&gt; array( 'key' =&gt; 'exclude_from_homepage_bloglist', 'value' =&gt; false ) ); </code></pre> <p>However it seems that even when the true/false box is ticked, the query still outputs the post in question.</p> <p>Where am I going wrong the the meta query?</p>
[ { "answer_id": 372395, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": 2, "selected": true, "text": "<p>There is basic Favicon functionality built into WP. Go to Theme Customiser &gt; Site Identity and use the 'Site Icon'.</p>\n<p>In some cases its better to have custom code in the head, and the above doesn't work for non WP pages within the site, if thats what you are using. However its worth a try if you hadn't already.</p>\n<p>In the past I have also used a website that <em>generates real favicon</em> code for the head, including a variety of sizes and allows you control the look of favicons on smartphones etc. So going with a more detailed setup in the head may also be worth exploring?</p>\n" }, { "answer_id": 372399, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>The reason for this is because you didn't use the WP site icon API to set your icon.</p>\n<p>When no favicon tag is possible, the browser will fall back to a URL such as <code>yoursite.com/favicon.png</code>. This gets picked up by WP which then displays the sites current icon. If none is set, a WP logo is used. That is why your PDF file gets a WP logo.</p>\n<p>You have several options available:</p>\n<ul>\n<li>Use the theme customizer to set the sites icon</li>\n<li>Upload a <code>favicon.png</code> and <code>favicon.ico</code> to the root of your site</li>\n<li>Use the <code>site_icon_meta_tags</code> filter to adjust the header meta tags</li>\n<li>Use the <code>get_site_icon_url</code> filter to override the URL of the image for a given size</li>\n</ul>\n<p>Generally I would advise relying on the WP site icon mechanism rather than adding HTML tags to the header, as it also accounts for various sizes that OS' might request, such as app icons in iOS</p>\n" }, { "answer_id": 413303, "author": "strarsis", "author_id": 134384, "author_profile": "https://wordpress.stackexchange.com/users/134384", "pm_score": 0, "selected": false, "text": "<p>In one particular site the core redirect from <code>/favicon.ico</code> didn't work because there were no rewrite rules in the options. Flushing the rewrite rules alone also didn't work - for some reason the permalink options weren't correctly set. I had to set these in permalinks settings again and then the <code>/favicon.ico</code> redirect started working correctly.</p>\n" } ]
2020/08/05
[ "https://wordpress.stackexchange.com/questions/372421", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77344/" ]
I am trying to give users an option to select "Exclude from homepage bloglist" on a post, and then pick this up on my homepage query so certain posts won't surface on the homepage. I'm using the Wordpress custom field "true/false". On a post where the box has been ticked, I would assume this post would then not surface on the homepage based on the below query args: ``` $query_args = array( 'meta_query' => array( 'key' => 'exclude_from_homepage_bloglist', 'value' => false ) ); ``` However it seems that even when the true/false box is ticked, the query still outputs the post in question. Where am I going wrong the the meta query?
There is basic Favicon functionality built into WP. Go to Theme Customiser > Site Identity and use the 'Site Icon'. In some cases its better to have custom code in the head, and the above doesn't work for non WP pages within the site, if thats what you are using. However its worth a try if you hadn't already. In the past I have also used a website that *generates real favicon* code for the head, including a variety of sizes and allows you control the look of favicons on smartphones etc. So going with a more detailed setup in the head may also be worth exploring?
372,483
<p>EDIT: Thanks to @mozboz I've got a solution to this. The post has been updated to reflect was I was originally trying to do, and what I am doing now.</p> <p>I am developing a plugin that creates a custom post type, adds some meta fields to it, and then displays that meta information in a specifically formatted way. The meta fields are for a YouTube link and an mp3 link, and the plugin displays tabbed content for those (first tab is an embedded YouTube player, second tab is an embedded audio player, third tab is a download link for the mp3). It was working great with the Twenty Twenty theme, but not with any of the other themes I tried. Here was my original code:</p> <pre><code>function my_custom_post_type_the_post($post_object) { // The post object is passed to this hook by reference so there is no need to return a value. if( $post_object-&gt;post_type == 'my_custom_post_type' &amp;&amp; ( is_post_type_archive('my_custom_post_type') || is_singular('my_custom_post_type') ) &amp;&amp; ! is_admin() ) { $video = get_post_meta($post_object-&gt;ID, 'my_custom_post_type_video_url', true); $mp3 = get_post_meta($post_object-&gt;ID, 'my_custom_post_type_mp3_url', true); $textfield = get_post_meta($post_object-&gt;ID, 'my_custom_post_type_textfield', true); // Convert meta data to HTML-formatted media content $media_content = $this-&gt;create_media_content($video, $mp3, $bible); // Prepend $media_content to $post_content $post_object-&gt;post_content = $media_content . $post_object-&gt;post_content; } } add_action( 'the_post', 'my_custom_post_type_the_post' ); </code></pre> <p>I used print_r($post_content) at the end of this function to verify that the conditions were working as expected and that the $post_object contained what I expect it to. For some reason, the Twenty Twenty theme would display the $media_content, but with other themes, it was still missing.</p> <p>I decided that perhaps I was mis-using the &quot;the_post&quot; hook. I tried to modify my plugin to use the &quot;the_content&quot; hook instead, and that got it working:</p> <pre><code> public function my_custom_post_type_the_content($content_object) { global $post; if( $post-&gt;post_type == 'my_custom_post_type' &amp;&amp; ( is_post_type_archive('my_custom_post_type') || is_singular('my_custom_post_type') ) &amp;&amp; ! is_admin() ) { $video = get_post_meta($post-&gt;ID, 'my_custom_post_type_video_url', true); $mp3 = get_post_meta($post-&gt;ID, 'my_custom_post_type_mp3_url', true); $textfield = get_post_meta($post-&gt;ID, 'my_custom_post_type_text_field', true); $media_content = $this-&gt;create_media_content($video, $mp3, $textfield); $content_object = $media_content . $content_object; } return $content_object } add_filter( 'the_content', 'my_custom_post_type_the_content'); </code></pre> <p>Note that the &quot;$content_object&quot; passed to the function is NOT passed by reference, so it has to be returned.</p> <p>One thing that was not solved was that with this approach, the archive listing of the posts strips off all of the HTML, so that my media object is gone from archive listings. In my case I decided to not solve this problem, because I decided that loading all of these media objects for multiple posts on an archive page would negatively affect page load times too much.</p> <p>Thanks again for the help!</p>
[ { "answer_id": 372395, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": 2, "selected": true, "text": "<p>There is basic Favicon functionality built into WP. Go to Theme Customiser &gt; Site Identity and use the 'Site Icon'.</p>\n<p>In some cases its better to have custom code in the head, and the above doesn't work for non WP pages within the site, if thats what you are using. However its worth a try if you hadn't already.</p>\n<p>In the past I have also used a website that <em>generates real favicon</em> code for the head, including a variety of sizes and allows you control the look of favicons on smartphones etc. So going with a more detailed setup in the head may also be worth exploring?</p>\n" }, { "answer_id": 372399, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>The reason for this is because you didn't use the WP site icon API to set your icon.</p>\n<p>When no favicon tag is possible, the browser will fall back to a URL such as <code>yoursite.com/favicon.png</code>. This gets picked up by WP which then displays the sites current icon. If none is set, a WP logo is used. That is why your PDF file gets a WP logo.</p>\n<p>You have several options available:</p>\n<ul>\n<li>Use the theme customizer to set the sites icon</li>\n<li>Upload a <code>favicon.png</code> and <code>favicon.ico</code> to the root of your site</li>\n<li>Use the <code>site_icon_meta_tags</code> filter to adjust the header meta tags</li>\n<li>Use the <code>get_site_icon_url</code> filter to override the URL of the image for a given size</li>\n</ul>\n<p>Generally I would advise relying on the WP site icon mechanism rather than adding HTML tags to the header, as it also accounts for various sizes that OS' might request, such as app icons in iOS</p>\n" }, { "answer_id": 413303, "author": "strarsis", "author_id": 134384, "author_profile": "https://wordpress.stackexchange.com/users/134384", "pm_score": 0, "selected": false, "text": "<p>In one particular site the core redirect from <code>/favicon.ico</code> didn't work because there were no rewrite rules in the options. Flushing the rewrite rules alone also didn't work - for some reason the permalink options weren't correctly set. I had to set these in permalinks settings again and then the <code>/favicon.ico</code> redirect started working correctly.</p>\n" } ]
2020/08/06
[ "https://wordpress.stackexchange.com/questions/372483", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192750/" ]
EDIT: Thanks to @mozboz I've got a solution to this. The post has been updated to reflect was I was originally trying to do, and what I am doing now. I am developing a plugin that creates a custom post type, adds some meta fields to it, and then displays that meta information in a specifically formatted way. The meta fields are for a YouTube link and an mp3 link, and the plugin displays tabbed content for those (first tab is an embedded YouTube player, second tab is an embedded audio player, third tab is a download link for the mp3). It was working great with the Twenty Twenty theme, but not with any of the other themes I tried. Here was my original code: ``` function my_custom_post_type_the_post($post_object) { // The post object is passed to this hook by reference so there is no need to return a value. if( $post_object->post_type == 'my_custom_post_type' && ( is_post_type_archive('my_custom_post_type') || is_singular('my_custom_post_type') ) && ! is_admin() ) { $video = get_post_meta($post_object->ID, 'my_custom_post_type_video_url', true); $mp3 = get_post_meta($post_object->ID, 'my_custom_post_type_mp3_url', true); $textfield = get_post_meta($post_object->ID, 'my_custom_post_type_textfield', true); // Convert meta data to HTML-formatted media content $media_content = $this->create_media_content($video, $mp3, $bible); // Prepend $media_content to $post_content $post_object->post_content = $media_content . $post_object->post_content; } } add_action( 'the_post', 'my_custom_post_type_the_post' ); ``` I used print\_r($post\_content) at the end of this function to verify that the conditions were working as expected and that the $post\_object contained what I expect it to. For some reason, the Twenty Twenty theme would display the $media\_content, but with other themes, it was still missing. I decided that perhaps I was mis-using the "the\_post" hook. I tried to modify my plugin to use the "the\_content" hook instead, and that got it working: ``` public function my_custom_post_type_the_content($content_object) { global $post; if( $post->post_type == 'my_custom_post_type' && ( is_post_type_archive('my_custom_post_type') || is_singular('my_custom_post_type') ) && ! is_admin() ) { $video = get_post_meta($post->ID, 'my_custom_post_type_video_url', true); $mp3 = get_post_meta($post->ID, 'my_custom_post_type_mp3_url', true); $textfield = get_post_meta($post->ID, 'my_custom_post_type_text_field', true); $media_content = $this->create_media_content($video, $mp3, $textfield); $content_object = $media_content . $content_object; } return $content_object } add_filter( 'the_content', 'my_custom_post_type_the_content'); ``` Note that the "$content\_object" passed to the function is NOT passed by reference, so it has to be returned. One thing that was not solved was that with this approach, the archive listing of the posts strips off all of the HTML, so that my media object is gone from archive listings. In my case I decided to not solve this problem, because I decided that loading all of these media objects for multiple posts on an archive page would negatively affect page load times too much. Thanks again for the help!
There is basic Favicon functionality built into WP. Go to Theme Customiser > Site Identity and use the 'Site Icon'. In some cases its better to have custom code in the head, and the above doesn't work for non WP pages within the site, if thats what you are using. However its worth a try if you hadn't already. In the past I have also used a website that *generates real favicon* code for the head, including a variety of sizes and allows you control the look of favicons on smartphones etc. So going with a more detailed setup in the head may also be worth exploring?
372,527
<pre><code> Notice: wpdb::prepare was called incorrectly. The query argument of wpdb::prepare() must have a placeholder. Please see Debugging in WordPress for more information. (This message was added in version 3.9.0.) in /home/****/public_html/wp-includes/functions.php on line 5167 Notice: Undefined offset: 0 in /home/****/public_html/wp-includes/wp-db.php on line 1310 function branch_students(){ $content=''; $content.='&lt;div class=&quot;container&quot;&gt;'; $content.='&lt;h1 align=center class=&quot;fofa&quot;&gt;Enter Branch&lt;/h1&gt;'; $content.='&lt;form method=&quot;post&quot; &gt;'; $content.='&lt;div class=&quot;b2&quot;&gt;'; $content.='&lt;input type=&quot;text&quot; name=&quot;branch&quot; id=&quot;branch&quot; class=&quot;box&quot; placeholder=&quot;Enter Branch&quot; required */&gt;&lt;/div&gt;'; $content.='&lt;br&gt;'; $content.='&lt;div&gt;'; $content.='&lt;button type=&quot;submit&quot; name=&quot;save&quot; class=&quot;btn_Register&quot; value=&quot;save&quot;&gt;Save&lt;/button&gt;'; $content.='&lt;/div&gt;'; $content.='&lt;/form&gt;'; $content.='&lt;/div&gt;'; return $content; } this is my first form in this form i creates branches. now i want database of this branch form should be showed in the following table as selection options. function arsh_forms(){ $content .='&lt;div class=&quot;col-sm-6&quot;&gt;'; $content .='&lt;label class=&quot;fofa&quot; style=&quot; font: italic bold 12px/30px Georgia, serif; font-size:26px;color:black;&quot;&gt;Select Branch&lt;/label&gt;'; $content .='&lt;select name=&quot;selectbranch&quot;id=&quot;selectbranch&quot; class=&quot;form-control&quot;style=&quot; font: italic bold 12px/30px Georgia, serif; font-size:20px;&quot;placeholder=&quot;selectbranch&quot;required/&gt;'; $content .='&lt;option value=&quot;0&quot; &gt;select branch&lt;/option&gt;'; global $wpdb; $table_name=$wpdb-&gt;prefix.'arsh_branch'; $select_branch = $wpdb-&gt;get_results($wpdb-&gt;prepare(&quot;SELECT * FROM $table_name&quot;)); if(count($select_branch) &gt; 0){ foreach ($select_branch as $key=&gt;$value){ $content .='&lt;option value=&quot;&lt;?php echo $value-&gt;branches; ?&gt;&quot;&gt; &lt;?php echo ucwords($value-&gt;branches);?&gt;&lt;/option&gt;'; } } $content .='&lt;/select&gt;'; $content.='&lt;div class=&quot;col-sm-6&quot;&gt;'; $content .='&lt;button type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Register&quot; style=&quot; width:30%;height:35px;background-color:black;color:white;float:right; margin-top:40px;&quot; class=&quot;bt&quot;&gt;Register&lt;/button&gt;'; $content .='&lt;/div&gt;'; } </code></pre> <p>i think now it is understandable.plz if anybody can help me?</p>
[ { "answer_id": 372509, "author": "Ben", "author_id": 190965, "author_profile": "https://wordpress.stackexchange.com/users/190965", "pm_score": 2, "selected": false, "text": "<p>It sounds as though you know your username and password, but if not you can always go into PHPMyAdmin (Or whatever Db tool your server uses) and navigate to the <strong>users</strong> table. In there you can see your users, and edit your details as required, including your password which you can simply overtype with new after encrypting it in <strong>MD5</strong> format.</p>\n<p>If this is trying to log in and kicking you straight back to the login page it may be worth looking in your server root for a file named <code>error_log</code>, this will help you identify any errors, or you can edit <code>wp-config.php</code> in the site's root setting <code>wp_debug</code> to <strong>true</strong> near the end of the page. Doing this should stop the page from just redirecting you without notification and give a print out of the error, if there are, any at the top of the page.</p>\n<p>This may not help, we could probably do with some more details from you before the community can help further. Depending on your hosting environment, it could be that your PHP version is out of date and needs updating.</p>\n<p>Hope this helps. Ben.</p>\n" }, { "answer_id": 372739, "author": "thedarkcave215", "author_id": 192762, "author_profile": "https://wordpress.stackexchange.com/users/192762", "pm_score": -1, "selected": false, "text": "<p>I just had to click the &quot;not you?&quot; button then log in as myself and it works.</p>\n" } ]
2020/08/07
[ "https://wordpress.stackexchange.com/questions/372527", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/191526/" ]
``` Notice: wpdb::prepare was called incorrectly. The query argument of wpdb::prepare() must have a placeholder. Please see Debugging in WordPress for more information. (This message was added in version 3.9.0.) in /home/****/public_html/wp-includes/functions.php on line 5167 Notice: Undefined offset: 0 in /home/****/public_html/wp-includes/wp-db.php on line 1310 function branch_students(){ $content=''; $content.='<div class="container">'; $content.='<h1 align=center class="fofa">Enter Branch</h1>'; $content.='<form method="post" >'; $content.='<div class="b2">'; $content.='<input type="text" name="branch" id="branch" class="box" placeholder="Enter Branch" required */></div>'; $content.='<br>'; $content.='<div>'; $content.='<button type="submit" name="save" class="btn_Register" value="save">Save</button>'; $content.='</div>'; $content.='</form>'; $content.='</div>'; return $content; } this is my first form in this form i creates branches. now i want database of this branch form should be showed in the following table as selection options. function arsh_forms(){ $content .='<div class="col-sm-6">'; $content .='<label class="fofa" style=" font: italic bold 12px/30px Georgia, serif; font-size:26px;color:black;">Select Branch</label>'; $content .='<select name="selectbranch"id="selectbranch" class="form-control"style=" font: italic bold 12px/30px Georgia, serif; font-size:20px;"placeholder="selectbranch"required/>'; $content .='<option value="0" >select branch</option>'; global $wpdb; $table_name=$wpdb->prefix.'arsh_branch'; $select_branch = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name")); if(count($select_branch) > 0){ foreach ($select_branch as $key=>$value){ $content .='<option value="<?php echo $value->branches; ?>"> <?php echo ucwords($value->branches);?></option>'; } } $content .='</select>'; $content.='<div class="col-sm-6">'; $content .='<button type="submit" name="submit" value="Register" style=" width:30%;height:35px;background-color:black;color:white;float:right; margin-top:40px;" class="bt">Register</button>'; $content .='</div>'; } ``` i think now it is understandable.plz if anybody can help me?
It sounds as though you know your username and password, but if not you can always go into PHPMyAdmin (Or whatever Db tool your server uses) and navigate to the **users** table. In there you can see your users, and edit your details as required, including your password which you can simply overtype with new after encrypting it in **MD5** format. If this is trying to log in and kicking you straight back to the login page it may be worth looking in your server root for a file named `error_log`, this will help you identify any errors, or you can edit `wp-config.php` in the site's root setting `wp_debug` to **true** near the end of the page. Doing this should stop the page from just redirecting you without notification and give a print out of the error, if there are, any at the top of the page. This may not help, we could probably do with some more details from you before the community can help further. Depending on your hosting environment, it could be that your PHP version is out of date and needs updating. Hope this helps. Ben.
372,535
<p>I have created a php script (generate.php) which is querying posts on set criteria and then writing result in custom xml file. I would like to execute the generate.php everytime the post Save/Update button is pressed. Do you have any clue on how to do this? May be with cron jobs every X minutes would be better?</p>
[ { "answer_id": 372536, "author": "Oliver Gehrmann", "author_id": 192667, "author_profile": "https://wordpress.stackexchange.com/users/192667", "pm_score": 0, "selected": false, "text": "<p>I believe you should look into status transitions: <a href=\"https://developer.wordpress.org/reference/hooks/transition_post_status/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/transition_post_status/</a></p>\n<p>There are a couple of examples below the explanation on top of the page. Here's also some example code of mine:</p>\n<pre><code>add_action( 'transition_post_status', 'nxt_create_news', 10, 3 );\n// Automatically create a news when a wiki post has been published\nfunction nxt_create_news($new_status, $old_status, $nxt_wiki_post) {\n if('publish' === $new_status &amp;&amp; 'publish' !== $old_status &amp;&amp; $nxt_wiki_post-&gt;post_type === 'wiki') {\n... do something here\n}\n</code></pre>\n<p>In your case, the old_status should be 'publish' and the new status as well. Make sure to find a way to prevent an endless loop, but I believe that the examples on the WP documentary should prove useful. :-)</p>\n" }, { "answer_id": 372554, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 1, "selected": false, "text": "<p>Seems like you want the <a href=\"https://developer.wordpress.org/reference/hooks/save_post/\" rel=\"nofollow noreferrer\"><code>save_post</code> hook</a> which is called when a new post is saved or existing post is updated.</p>\n<p>Make sure your PHP file is loaded (e.g. <code>require</code> or <code>include</code>) and has a function you can call, and then cause that function to be run when a post is saved or updated with:</p>\n<pre><code>add_action('save_post', 'your_function_name', 10, 1);\n</code></pre>\n<p>Note the last parameter there is the number of parameters you want from the hook, see the docs page.</p>\n" }, { "answer_id": 372575, "author": "jam", "author_id": 5878, "author_profile": "https://wordpress.stackexchange.com/users/5878", "pm_score": 1, "selected": true, "text": "<p>At the end, I solved with jQuery and ajax</p>\n<pre><code> jQuery( '.post-type-property #post' ).submit( function( e ) {\n \n if(!(checkMetaFields() &amp;&amp; checkCategories())){ //some validation functions\n \n return false;\n \n }else{\n jQuery.ajax({\n url:&quot;https://demo.site.com/XML/6098123798/gen.php&quot;,\n type:&quot;post&quot;\n \n })\n \n \n \n } \n \n } );\n</code></pre>\n" } ]
2020/08/07
[ "https://wordpress.stackexchange.com/questions/372535", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5878/" ]
I have created a php script (generate.php) which is querying posts on set criteria and then writing result in custom xml file. I would like to execute the generate.php everytime the post Save/Update button is pressed. Do you have any clue on how to do this? May be with cron jobs every X minutes would be better?
At the end, I solved with jQuery and ajax ``` jQuery( '.post-type-property #post' ).submit( function( e ) { if(!(checkMetaFields() && checkCategories())){ //some validation functions return false; }else{ jQuery.ajax({ url:"https://demo.site.com/XML/6098123798/gen.php", type:"post" }) } } ); ```
372,578
<p>I have a custom post type and in the CPT's <code>single-cpt.php</code> file I would like to pull in two posts instead of one.</p> <p>The two posts will be the post the user clicked in the relevant archive, and the next post in date order (i.e. the default post sorting method of WordPress). The reason for this is the posts are essentially small, useful pieces of information and having two posts pulled in will create a better SEO and user experience.</p> <p>Normally when I want to pull in a set number of posts on an archive page I would use <code>WP_Query()</code> and set <code>'posts_per_page' =&gt; 2</code> but out of the box this won't work on a <code>single-cpt.php</code> file because such code pulls in posts that are the most recent, not the post that was clicked on the archive page (and then the next most recent).</p> <p>What I'm looking for is something that works with the WP loop so each post looks the same, but pulls in two posts (the selected one from the archive and then the next one in date order).</p> <p><strong>Note:</strong> If this isn't possible with WP_Query() any other way to do it would be most welcome.</p> <pre><code>&lt;?php $newsArticles = new WP_Query(array( 'posts_per_page' =&gt; 2, 'post_type'=&gt; 'news' )); while( $newsArticles-&gt;have_posts()){ $newsArticles-&gt;the_post(); ?&gt; // HTML content goes here &lt;?php } ?&gt; &lt;?php wp_reset_postdata(); ?&gt; </code></pre> <p>Any help would be amazing.</p>
[ { "answer_id": 372577, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 1, "selected": false, "text": "<p>1 - Yes. You could manually update the <code>post_author</code> field on <code>wp_posts</code> table if you wanted to, using SQL. Obviously you'd have to know a bit of SQL to be able to change just the posts you wanted to, and this field is the ID of the author.</p>\n<p>2 - I just had a quick look and <a href=\"https://wordpress.org/plugins/better-author-metabox/\" rel=\"nofollow noreferrer\">this plugin</a> seems to do exactly what you want - it adds an 'author' dropdown to the post edit screen. You have to read up on the settings and configure its settings before it starts working, but looks like it does exactly what you want. I just tested with current Wordpress release version (5.4.2) and it works ok.</p>\n" }, { "answer_id": 372584, "author": "Ben", "author_id": 190965, "author_profile": "https://wordpress.stackexchange.com/users/190965", "pm_score": 3, "selected": true, "text": "<p>Just to add to what MozBoz has already said, you can also set the author from the post / page in WP directly. You can usually do this from the editor itself, but there are a lot of page builders available, so I'd suggest going to WP Admin and to your <strong>All Posts</strong>, hover over the post you want to set the author of and select <strong>Quick Edit</strong>. This will pull down a tray of options, one of which will be an author dropdown where you can select the posts author from all of the users on your site.</p>\n" } ]
2020/08/07
[ "https://wordpress.stackexchange.com/questions/372578", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
I have a custom post type and in the CPT's `single-cpt.php` file I would like to pull in two posts instead of one. The two posts will be the post the user clicked in the relevant archive, and the next post in date order (i.e. the default post sorting method of WordPress). The reason for this is the posts are essentially small, useful pieces of information and having two posts pulled in will create a better SEO and user experience. Normally when I want to pull in a set number of posts on an archive page I would use `WP_Query()` and set `'posts_per_page' => 2` but out of the box this won't work on a `single-cpt.php` file because such code pulls in posts that are the most recent, not the post that was clicked on the archive page (and then the next most recent). What I'm looking for is something that works with the WP loop so each post looks the same, but pulls in two posts (the selected one from the archive and then the next one in date order). **Note:** If this isn't possible with WP\_Query() any other way to do it would be most welcome. ``` <?php $newsArticles = new WP_Query(array( 'posts_per_page' => 2, 'post_type'=> 'news' )); while( $newsArticles->have_posts()){ $newsArticles->the_post(); ?> // HTML content goes here <?php } ?> <?php wp_reset_postdata(); ?> ``` Any help would be amazing.
Just to add to what MozBoz has already said, you can also set the author from the post / page in WP directly. You can usually do this from the editor itself, but there are a lot of page builders available, so I'd suggest going to WP Admin and to your **All Posts**, hover over the post you want to set the author of and select **Quick Edit**. This will pull down a tray of options, one of which will be an author dropdown where you can select the posts author from all of the users on your site.
372,616
<h2>Scenario</h2> <p>I am working on a domain's website which is part of a multi-site installation.</p> <p>I am looking to create a custom php page which will do some processing. This page would be accessed from the main WP site using a Javascript <code>XMLHttpRequest</code></p> <p>I do NOT want this page to have any of my theme's headers, content, etc. as this page will not actually be visited directly by the user's browser.</p> <p><strong>Example php (simplified);</strong></p> <pre class="lang-php prettyprint-override"><code>&lt;?php session_start() $_SESSION[&quot;stuff&quot;] = &quot;things&quot;; echo &quot;success&quot;; exit(); ?&gt; </code></pre> <h2>Things I've tried</h2> <p>I tried using hooks and headers for the PHP within ‘elements’ however it appears that all of the available options only process the php after some headers have started being generated, therefore meaning that the php would not present data as accurately as expected.</p> <p>It seemed obvious to me to simply create the '.php' file in the same way I would if weren't using WP, however I have struggled to find the directory where I should create such a file. I checked the configuration of the file: /etc/apache2/sites-enabled/000-default.conf but this just shows me 'DocumentRoot /var/www/wordpress' which is a the root directory of the multi-site area. This lead me to believe that it may be a little more complex than simply creating the file in a certain directory directly on the server.</p> <p>I have also tried to use the “disable elements” for this page when in 'edit page' however this doesn’t seem to do enough either.</p> <p>I also tried reviewing this <a href="https://wordpress.stackexchange.com/questions/210304/add-a-page-outside-of-the-current-theme">previous thread</a> but I can't see the solution, I ideally don't want the WP functionality at all for this single page. I just want to be able to access it from <code>https://example.com/string.php</code> (or similar).</p> <h2>Desired Outcome</h2> <p>I want the page to be as plain as possible OR to be able to execute the php early enough that the <code>exit();</code> stops the actual page from being rendered into HTML (headers, etc.)</p> <p>Also, I ideally don't want to just 'throw another plugin at it' if there's an alternative (but not ridiculous) way.</p> <p>Please could you help me to find a solution?</p> <p>Many Thanks!</p>
[ { "answer_id": 372577, "author": "mozboz", "author_id": 176814, "author_profile": "https://wordpress.stackexchange.com/users/176814", "pm_score": 1, "selected": false, "text": "<p>1 - Yes. You could manually update the <code>post_author</code> field on <code>wp_posts</code> table if you wanted to, using SQL. Obviously you'd have to know a bit of SQL to be able to change just the posts you wanted to, and this field is the ID of the author.</p>\n<p>2 - I just had a quick look and <a href=\"https://wordpress.org/plugins/better-author-metabox/\" rel=\"nofollow noreferrer\">this plugin</a> seems to do exactly what you want - it adds an 'author' dropdown to the post edit screen. You have to read up on the settings and configure its settings before it starts working, but looks like it does exactly what you want. I just tested with current Wordpress release version (5.4.2) and it works ok.</p>\n" }, { "answer_id": 372584, "author": "Ben", "author_id": 190965, "author_profile": "https://wordpress.stackexchange.com/users/190965", "pm_score": 3, "selected": true, "text": "<p>Just to add to what MozBoz has already said, you can also set the author from the post / page in WP directly. You can usually do this from the editor itself, but there are a lot of page builders available, so I'd suggest going to WP Admin and to your <strong>All Posts</strong>, hover over the post you want to set the author of and select <strong>Quick Edit</strong>. This will pull down a tray of options, one of which will be an author dropdown where you can select the posts author from all of the users on your site.</p>\n" } ]
2020/08/08
[ "https://wordpress.stackexchange.com/questions/372616", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190928/" ]
Scenario -------- I am working on a domain's website which is part of a multi-site installation. I am looking to create a custom php page which will do some processing. This page would be accessed from the main WP site using a Javascript `XMLHttpRequest` I do NOT want this page to have any of my theme's headers, content, etc. as this page will not actually be visited directly by the user's browser. **Example php (simplified);** ```php <?php session_start() $_SESSION["stuff"] = "things"; echo "success"; exit(); ?> ``` Things I've tried ----------------- I tried using hooks and headers for the PHP within ‘elements’ however it appears that all of the available options only process the php after some headers have started being generated, therefore meaning that the php would not present data as accurately as expected. It seemed obvious to me to simply create the '.php' file in the same way I would if weren't using WP, however I have struggled to find the directory where I should create such a file. I checked the configuration of the file: /etc/apache2/sites-enabled/000-default.conf but this just shows me 'DocumentRoot /var/www/wordpress' which is a the root directory of the multi-site area. This lead me to believe that it may be a little more complex than simply creating the file in a certain directory directly on the server. I have also tried to use the “disable elements” for this page when in 'edit page' however this doesn’t seem to do enough either. I also tried reviewing this [previous thread](https://wordpress.stackexchange.com/questions/210304/add-a-page-outside-of-the-current-theme) but I can't see the solution, I ideally don't want the WP functionality at all for this single page. I just want to be able to access it from `https://example.com/string.php` (or similar). Desired Outcome --------------- I want the page to be as plain as possible OR to be able to execute the php early enough that the `exit();` stops the actual page from being rendered into HTML (headers, etc.) Also, I ideally don't want to just 'throw another plugin at it' if there's an alternative (but not ridiculous) way. Please could you help me to find a solution? Many Thanks!
Just to add to what MozBoz has already said, you can also set the author from the post / page in WP directly. You can usually do this from the editor itself, but there are a lot of page builders available, so I'd suggest going to WP Admin and to your **All Posts**, hover over the post you want to set the author of and select **Quick Edit**. This will pull down a tray of options, one of which will be an author dropdown where you can select the posts author from all of the users on your site.
372,626
<p>I am creating an Android app for a client whose site is in WordPress. I want to access the posts, but I don't know which API to hit. One of the APIs I found after some searching is <a href="https://www.example.com/wp-json/wp/v2/posts" rel="nofollow noreferrer">https://www.<code>&lt;mysite&gt;</code>.com/wp-json/wp/v2/posts</a>. This gives a ton of key value pairs, So I was tying to access this site via this URL. But for a particular <code>content</code> key, this is giving the following output:</p> <pre><code> &quot;content&quot;: { &quot;rendered&quot;: &quot;&lt;p&gt;&amp;nbsp;&lt;/p&gt;\r\n\r\n&lt;p&gt;The next class for &amp;#8220;MICROVITA&amp;#8221; will be on &amp;#8220;Aug 07th, 2020 at 8:00 PM IST / 10:30 AM EST on &amp;#8220;MicroVita Science(माइक्रोवाइटा विषय समापन )&amp;#8221; by Ac.Vimalananda Avt. &lt;/p&gt;\r\n\r\n\r\n\r\n\n&lt;div class=\&quot;dpn-zvc-shortcode-op-wrapper\&quot;&gt;\n\t &lt;table class=\&quot;vczapi-shortcode-meeting-table\&quot;&gt;\n &lt;tr class=\&quot;vczapi-shortcode-meeting-table--row1\&quot;&gt;\n &lt;td&gt;Meeting ID&lt;/td&gt;\n &lt;td&gt;000000000&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr class=\&quot;vczapi-shortcode-meeting-table--row2\&quot;&gt;...&quot; } </code></pre> <p>I am not sure how to retrieve the important information from such HTML content. Maybe that's a question better suited for other stack communities, but what I want to know is that if it is the expected behavior from a WordPress site API? Or is there some other API or plugin which might give me a better response?</p> <p>To summarize:</p> <ol> <li>which WordPress API could give me a list of all the articles as JSON?</li> <li>I found a particular API doing the above same task as point (1.). is it a standard one?</li> <li>Is it a standard behavior of WordPress APIs to have HTML content directly inside their JSON key-value pairs?</li> </ol>
[ { "answer_id": 372640, "author": "Marcello Curto", "author_id": 153572, "author_profile": "https://wordpress.stackexchange.com/users/153572", "pm_score": 2, "selected": false, "text": "<p>This is expected WordPress behavior. &quot;content&quot; data is WordPress post content data\nand stored with all the HTML tags that where added in the post.</p>\n<p>I'm not sure what pieces of information you are trying to retrieve, but I think the HTML tags could work to your advantage.</p>\n<p>If you were to retrieve the meeting ids then you could filter all the &quot;tr&quot; elements and always pick the second &quot;td&quot; that is inside.</p>\n<pre><code>&lt;table class=\\&quot;vczapi-shortcode-meeting-table\\&quot;&gt;\n &lt;tr class=\\&quot;vczapi-shortcode-meeting-table--row1\\&quot;&gt;\n &lt;td&gt;Meeting ID&lt;/td&gt;\n &lt;td&gt;000000000&lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n<p>It looks like a WordPress plugin is adding this data inside the post content via a shortcode. If you are lucky, all that data is stored separately in the database in a structured way. If so, you might be able to expose that data to the WordPress API and then access it directly instead of filtering through HTML tags.</p>\n" }, { "answer_id": 372659, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<blockquote>\n<ol>\n<li>which wordpress api could give me a list of all the articles as json?</li>\n</ol>\n</blockquote>\n<p>You're already using the right API, just remember it's paginated so you need to request the second/third page/etc in a separate request. It'll pass how many apges there are in the http header</p>\n<blockquote>\n<ol start=\"2\">\n<li>I found a particular api doing the above same task as point (1.). is it a standard one?</li>\n</ol>\n</blockquote>\n<p>You list posts via the REST API by querying <code>wp-json/wp/v2/posts</code>. Other endpoints exist for other post types such as <code>pages</code> etc</p>\n<blockquote>\n<ol start=\"3\">\n<li>Is it a standard behavior of wordpress apis to have html content directly inside their json key-value pairs?</li>\n</ol>\n</blockquote>\n<p>Yes, if you wanted to display the post you would need the post content. Otherwise how would you display the post?</p>\n<hr />\n<p>I think what we're seeing is a misunderstanding. <strong>You never stated what it was that you wanted, just that it's somewhere in the content HTML</strong>. So I think this is what has happened:</p>\n<ul>\n<li>The post uses a shortcode to display data taken from elsewhere</li>\n<li>Your app is pulling in the post via the REST API</li>\n<li>You're looking at the shortcodes output and wondering how to extract the data in your Android app.</li>\n</ul>\n<p>You could parse the HTML using an android library of sorts, assuming it's consistent, or, you could look at where the shortcode gets its information from and access it directly.</p>\n<p>Sadly, you never actually said what the data you wanted was, and we don't know what the shortcode that generates that output is. Without access to the implementation of the shortcode it's not possible to say how to expose the information. A shortcode is a PHP function that's registered under a name, and swaps a string such as <code>[shortcode]</code> with HTML tags. That PHP function might draw the data from post meta, or it might access a custom database table, or even make a HTTP request to a remote API, so no generic solution is possible.</p>\n<p><code>dpn-zvc-shortcode-op-wrapper</code> gives us a clue as to what the shortcode might be, but you would need to look at how the shortcode works to know that, and you didn't mentiion the shortcodes name. A quick google shows that HTML class appears in a support request for a Zoom plugin, so you would need to go via their support route as 3rd party plugin support is offtopic here.</p>\n" } ]
2020/08/08
[ "https://wordpress.stackexchange.com/questions/372626", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192852/" ]
I am creating an Android app for a client whose site is in WordPress. I want to access the posts, but I don't know which API to hit. One of the APIs I found after some searching is [https://www.`<mysite>`.com/wp-json/wp/v2/posts](https://www.example.com/wp-json/wp/v2/posts). This gives a ton of key value pairs, So I was tying to access this site via this URL. But for a particular `content` key, this is giving the following output: ``` "content": { "rendered": "<p>&nbsp;</p>\r\n\r\n<p>The next class for &#8220;MICROVITA&#8221; will be on &#8220;Aug 07th, 2020 at 8:00 PM IST / 10:30 AM EST on &#8220;MicroVita Science(माइक्रोवाइटा विषय समापन )&#8221; by Ac.Vimalananda Avt. </p>\r\n\r\n\r\n\r\n\n<div class=\"dpn-zvc-shortcode-op-wrapper\">\n\t <table class=\"vczapi-shortcode-meeting-table\">\n <tr class=\"vczapi-shortcode-meeting-table--row1\">\n <td>Meeting ID</td>\n <td>000000000</td>\n </tr>\n <tr class=\"vczapi-shortcode-meeting-table--row2\">..." } ``` I am not sure how to retrieve the important information from such HTML content. Maybe that's a question better suited for other stack communities, but what I want to know is that if it is the expected behavior from a WordPress site API? Or is there some other API or plugin which might give me a better response? To summarize: 1. which WordPress API could give me a list of all the articles as JSON? 2. I found a particular API doing the above same task as point (1.). is it a standard one? 3. Is it a standard behavior of WordPress APIs to have HTML content directly inside their JSON key-value pairs?
> > 1. which wordpress api could give me a list of all the articles as json? > > > You're already using the right API, just remember it's paginated so you need to request the second/third page/etc in a separate request. It'll pass how many apges there are in the http header > > 2. I found a particular api doing the above same task as point (1.). is it a standard one? > > > You list posts via the REST API by querying `wp-json/wp/v2/posts`. Other endpoints exist for other post types such as `pages` etc > > 3. Is it a standard behavior of wordpress apis to have html content directly inside their json key-value pairs? > > > Yes, if you wanted to display the post you would need the post content. Otherwise how would you display the post? --- I think what we're seeing is a misunderstanding. **You never stated what it was that you wanted, just that it's somewhere in the content HTML**. So I think this is what has happened: * The post uses a shortcode to display data taken from elsewhere * Your app is pulling in the post via the REST API * You're looking at the shortcodes output and wondering how to extract the data in your Android app. You could parse the HTML using an android library of sorts, assuming it's consistent, or, you could look at where the shortcode gets its information from and access it directly. Sadly, you never actually said what the data you wanted was, and we don't know what the shortcode that generates that output is. Without access to the implementation of the shortcode it's not possible to say how to expose the information. A shortcode is a PHP function that's registered under a name, and swaps a string such as `[shortcode]` with HTML tags. That PHP function might draw the data from post meta, or it might access a custom database table, or even make a HTTP request to a remote API, so no generic solution is possible. `dpn-zvc-shortcode-op-wrapper` gives us a clue as to what the shortcode might be, but you would need to look at how the shortcode works to know that, and you didn't mentiion the shortcodes name. A quick google shows that HTML class appears in a support request for a Zoom plugin, so you would need to go via their support route as 3rd party plugin support is offtopic here.
372,627
<p>I am trying to figure out how to get a list of the permalinks for top-level pages only. My goal is to put them in a selection box on a form. I have spent a couple of hours searching here for an answer to no avail. I was hoping someone could point me in the right direction.</p>
[ { "answer_id": 372628, "author": "Ben", "author_id": 190965, "author_profile": "https://wordpress.stackexchange.com/users/190965", "pm_score": 0, "selected": false, "text": "<p>By the sounds of it, this should do what you're after. Just place it in wherever you want your list to output and you should be good to go.</p>\n<pre><code>&lt;?php wp_list_pages('depth=1'); ?&gt;\n</code></pre>\n<p>The depth argument being set to 1 is telling the function to only retrieve top level pages, but a lot more arguments are available. Take a look at the dev resources <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 372647, "author": "Nilambar Sharma", "author_id": 27998, "author_profile": "https://wordpress.stackexchange.com/users/27998", "pm_score": 2, "selected": true, "text": "<pre><code>$query_args = array(\n 'post_type' =&gt; 'page',\n 'post_status' =&gt; 'publish',\n 'parent' =&gt; 0,\n);\n\n$pages = get_pages( $query_args );\n</code></pre>\n<p>Function <code>get_pages()</code> accepts parameter with <code>parent</code>. Keeping it 0 (zero) will give us first level pages. In the example <code>$pages</code> will contain the first level pages. Use loop for <code>$pages</code> and you can use it in option as you require.</p>\n" } ]
2020/08/08
[ "https://wordpress.stackexchange.com/questions/372627", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192370/" ]
I am trying to figure out how to get a list of the permalinks for top-level pages only. My goal is to put them in a selection box on a form. I have spent a couple of hours searching here for an answer to no avail. I was hoping someone could point me in the right direction.
``` $query_args = array( 'post_type' => 'page', 'post_status' => 'publish', 'parent' => 0, ); $pages = get_pages( $query_args ); ``` Function `get_pages()` accepts parameter with `parent`. Keeping it 0 (zero) will give us first level pages. In the example `$pages` will contain the first level pages. Use loop for `$pages` and you can use it in option as you require.
372,687
<p>I have a live website that is using the custom post type &quot;virtual-programs&quot; and I have a template that currently works called single-virtual-program.twig and single-virtual-program.php.</p> <p>I am developing new templates (single-virtual-program-new.twig and single-virtual-program-new.php)</p> <p>They will eventually replace (single-virtual-program.twig and single-virtual-program.php)</p> <p>During development I want to have both templates active, then once I'm happy with it, I will activate the new templates and remove the the old templates.</p> <p>To do this I will need to create custom URLs for my NEW templates so I can view them while the old templates are still live. How do I go about that?</p> <p>FYI I'm using Timber (.twig).</p> <p>Here is the code from single-virtual-program.php</p> <pre><code>$post = Timber::query_post(); $context['post'] = $post; $context['archive_link'] = get_site_url(null, str_replace('_', '-', $post-&gt;post_type)); $context['virtual_programs'] = Timber::get_posts( array( 'post_type' =&gt; array('virtual_programs'), 'post__not_in' =&gt; array($post-&gt;ID), 'posts_per_page' =&gt; 5, 'meta_query' =&gt; array( array( 'key' =&gt; 'event_type', 'value' =&gt; array('online', 'Online Short Course'), 'compare' =&gt; 'NOT IN' ) ) ) ); $context[&quot;register_event_url&quot;] = get_field(&quot;prices&quot;, $post-&gt;ID)[0][&quot;register_link&quot;]; Timber::render( 'single-virtual-programs-new.twig' , $context ); </code></pre> <p>Thank you.</p>
[ { "answer_id": 372628, "author": "Ben", "author_id": 190965, "author_profile": "https://wordpress.stackexchange.com/users/190965", "pm_score": 0, "selected": false, "text": "<p>By the sounds of it, this should do what you're after. Just place it in wherever you want your list to output and you should be good to go.</p>\n<pre><code>&lt;?php wp_list_pages('depth=1'); ?&gt;\n</code></pre>\n<p>The depth argument being set to 1 is telling the function to only retrieve top level pages, but a lot more arguments are available. Take a look at the dev resources <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 372647, "author": "Nilambar Sharma", "author_id": 27998, "author_profile": "https://wordpress.stackexchange.com/users/27998", "pm_score": 2, "selected": true, "text": "<pre><code>$query_args = array(\n 'post_type' =&gt; 'page',\n 'post_status' =&gt; 'publish',\n 'parent' =&gt; 0,\n);\n\n$pages = get_pages( $query_args );\n</code></pre>\n<p>Function <code>get_pages()</code> accepts parameter with <code>parent</code>. Keeping it 0 (zero) will give us first level pages. In the example <code>$pages</code> will contain the first level pages. Use loop for <code>$pages</code> and you can use it in option as you require.</p>\n" } ]
2020/08/10
[ "https://wordpress.stackexchange.com/questions/372687", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93209/" ]
I have a live website that is using the custom post type "virtual-programs" and I have a template that currently works called single-virtual-program.twig and single-virtual-program.php. I am developing new templates (single-virtual-program-new.twig and single-virtual-program-new.php) They will eventually replace (single-virtual-program.twig and single-virtual-program.php) During development I want to have both templates active, then once I'm happy with it, I will activate the new templates and remove the the old templates. To do this I will need to create custom URLs for my NEW templates so I can view them while the old templates are still live. How do I go about that? FYI I'm using Timber (.twig). Here is the code from single-virtual-program.php ``` $post = Timber::query_post(); $context['post'] = $post; $context['archive_link'] = get_site_url(null, str_replace('_', '-', $post->post_type)); $context['virtual_programs'] = Timber::get_posts( array( 'post_type' => array('virtual_programs'), 'post__not_in' => array($post->ID), 'posts_per_page' => 5, 'meta_query' => array( array( 'key' => 'event_type', 'value' => array('online', 'Online Short Course'), 'compare' => 'NOT IN' ) ) ) ); $context["register_event_url"] = get_field("prices", $post->ID)[0]["register_link"]; Timber::render( 'single-virtual-programs-new.twig' , $context ); ``` Thank you.
``` $query_args = array( 'post_type' => 'page', 'post_status' => 'publish', 'parent' => 0, ); $pages = get_pages( $query_args ); ``` Function `get_pages()` accepts parameter with `parent`. Keeping it 0 (zero) will give us first level pages. In the example `$pages` will contain the first level pages. Use loop for `$pages` and you can use it in option as you require.
372,690
<p>I use <a href="https://github.com/timber/timber" rel="nofollow noreferrer">Timber</a> for all my projects, but I would also like to start using a templating language like HAML or Pug. I found a PHP implementation of HAML called <a href="https://github.com/arnaud-lb/MtHaml" rel="nofollow noreferrer">MtHaml</a>, which supports twig. I thought this could be great if I could get it to work with Timber.</p> <p>Unfortunately, while this supports a number of CMS, Wordpress is not on the list. There is <a href="https://github.com/zachfeldman/wordpress-haml-sass" rel="nofollow noreferrer">a project</a> that brings MtHaml to wordpress, but it's from 7 years ago and I haven't yet figured out how it compiles. It looks like I have to run ./watch from command line to get it to autocompile.</p> <p>I like Timber because it just compiles on the fly. I drop my twig file in the theme directory and it just works. I would like to do the same thing but with HAML + Twig (Timber). Does anyone know how I would go about this?</p> <p>Alternatively, I would consider using Twig + Pug but I see even less support for this. Basically I want to get away from the traditional templating system of opening and closing tags, and move to an HTML shorthand</p>
[ { "answer_id": 372628, "author": "Ben", "author_id": 190965, "author_profile": "https://wordpress.stackexchange.com/users/190965", "pm_score": 0, "selected": false, "text": "<p>By the sounds of it, this should do what you're after. Just place it in wherever you want your list to output and you should be good to go.</p>\n<pre><code>&lt;?php wp_list_pages('depth=1'); ?&gt;\n</code></pre>\n<p>The depth argument being set to 1 is telling the function to only retrieve top level pages, but a lot more arguments are available. Take a look at the dev resources <a href=\"https://developer.wordpress.org/reference/functions/wp_list_pages/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 372647, "author": "Nilambar Sharma", "author_id": 27998, "author_profile": "https://wordpress.stackexchange.com/users/27998", "pm_score": 2, "selected": true, "text": "<pre><code>$query_args = array(\n 'post_type' =&gt; 'page',\n 'post_status' =&gt; 'publish',\n 'parent' =&gt; 0,\n);\n\n$pages = get_pages( $query_args );\n</code></pre>\n<p>Function <code>get_pages()</code> accepts parameter with <code>parent</code>. Keeping it 0 (zero) will give us first level pages. In the example <code>$pages</code> will contain the first level pages. Use loop for <code>$pages</code> and you can use it in option as you require.</p>\n" } ]
2020/08/10
[ "https://wordpress.stackexchange.com/questions/372690", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13881/" ]
I use [Timber](https://github.com/timber/timber) for all my projects, but I would also like to start using a templating language like HAML or Pug. I found a PHP implementation of HAML called [MtHaml](https://github.com/arnaud-lb/MtHaml), which supports twig. I thought this could be great if I could get it to work with Timber. Unfortunately, while this supports a number of CMS, Wordpress is not on the list. There is [a project](https://github.com/zachfeldman/wordpress-haml-sass) that brings MtHaml to wordpress, but it's from 7 years ago and I haven't yet figured out how it compiles. It looks like I have to run ./watch from command line to get it to autocompile. I like Timber because it just compiles on the fly. I drop my twig file in the theme directory and it just works. I would like to do the same thing but with HAML + Twig (Timber). Does anyone know how I would go about this? Alternatively, I would consider using Twig + Pug but I see even less support for this. Basically I want to get away from the traditional templating system of opening and closing tags, and move to an HTML shorthand
``` $query_args = array( 'post_type' => 'page', 'post_status' => 'publish', 'parent' => 0, ); $pages = get_pages( $query_args ); ``` Function `get_pages()` accepts parameter with `parent`. Keeping it 0 (zero) will give us first level pages. In the example `$pages` will contain the first level pages. Use loop for `$pages` and you can use it in option as you require.
372,705
<p>This is my first time asking a question here. I'm kinda stuck on how to do <code>echo do_shortcode();</code> inside a shortcode.</p> <p>I tried googling for an answer but to no avail.</p> <p>I'd like to know if it is possible to echo a shortcode inside a shortcode. If it is, any pointer is much appreciated.</p> <p>Thank you.</p> <pre><code> function cpa_haven_banner() { return ' &lt;ul class=&quot;list-group list-group-horizontal entry-meta&quot;&gt; &lt;li class=&quot;list-group-item list-group-action-item&quot;&gt; &lt;strong&gt;Female&lt;/strong&gt; &lt;?php echo do_shortcode(&quot;[get_sheet_value location='LOAN!B7']&quot;); ?&gt; &lt;/li&gt; &lt;/ul&gt; '; } add_shortcode('cpa-haven', 'cpa_haven_banner'); </code></pre>
[ { "answer_id": 372710, "author": "Nate Allen", "author_id": 32698, "author_profile": "https://wordpress.stackexchange.com/users/32698", "pm_score": 0, "selected": false, "text": "<p>I would put all the markup in a variable, and return the result of passing that through <code>do_shortcode</code>:</p>\n<pre><code>function cpa_haven_banner() {\n $html = '\n &lt;ul class=&quot;list-group list-group-horizontal entry-meta&quot;&gt;\n &lt;li class=&quot;list-group-item list-group-action-item&quot;&gt;\n &lt;strong&gt;Female&lt;/strong&gt; [get_sheet_value location=\\'LOAN!B7\\']\n &lt;/li&gt;\n &lt;/ul&gt;\n ';\n\n\n return do_shortcode( $html );\n}\nadd_shortcode('cpa-haven', 'cpa_haven_banner');\n</code></pre>\n" }, { "answer_id": 372711, "author": "Rene Hermenau", "author_id": 129837, "author_profile": "https://wordpress.stackexchange.com/users/129837", "pm_score": 1, "selected": false, "text": "<p>This should work:</p>\n<pre><code>function cpa_haven_banner() {\n \n $shortcode = do_shortcode(&quot;[get_sheet_value location='LOAN!B7']&quot;);\n \n return ' \n &lt;ul class=&quot;list-group list-group-horizontal entry-meta&quot;&gt;\n &lt;li class=&quot;list-group-item list-group-action-item&quot;&gt;\n &lt;strong&gt;Female&lt;/strong&gt; ' . $shortcode .\n '&lt;/li&gt;\n &lt;/ul&gt;\n ';\n }\nadd_shortcode('cpa-haven', 'cpa_haven_banner');\n</code></pre>\n" } ]
2020/08/10
[ "https://wordpress.stackexchange.com/questions/372705", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192898/" ]
This is my first time asking a question here. I'm kinda stuck on how to do `echo do_shortcode();` inside a shortcode. I tried googling for an answer but to no avail. I'd like to know if it is possible to echo a shortcode inside a shortcode. If it is, any pointer is much appreciated. Thank you. ``` function cpa_haven_banner() { return ' <ul class="list-group list-group-horizontal entry-meta"> <li class="list-group-item list-group-action-item"> <strong>Female</strong> <?php echo do_shortcode("[get_sheet_value location='LOAN!B7']"); ?> </li> </ul> '; } add_shortcode('cpa-haven', 'cpa_haven_banner'); ```
This should work: ``` function cpa_haven_banner() { $shortcode = do_shortcode("[get_sheet_value location='LOAN!B7']"); return ' <ul class="list-group list-group-horizontal entry-meta"> <li class="list-group-item list-group-action-item"> <strong>Female</strong> ' . $shortcode . '</li> </ul> '; } add_shortcode('cpa-haven', 'cpa_haven_banner'); ```
372,764
<p>Is it possible when using the <code>previous_post_link()</code> function to make it get the previous post after next i.e. make it skip a post. So if you're on post 5 in numerical order it skips to post 3?</p> <p>The reason being I have custom post type <code>single-cpt.php</code> file that pulls in two posts, so when using the previous post link out of the box it means when you go to the next post, one of the ones from the previous post is there again.</p> <p>Any help would be fabulous.</p>
[ { "answer_id": 372769, "author": "Nate Allen", "author_id": 32698, "author_profile": "https://wordpress.stackexchange.com/users/32698", "pm_score": 0, "selected": false, "text": "<p>I wrote a couple functions that trick WordPress into thinking we're on the previous/next post before calling <code>previous_post_link</code> or <code>next_post_link</code>:</p>\n<pre><code>/**\n * Displays the next post link that is adjacent to the next post.\n *\n * @param object $next_post Optional. The next post to reference. Default is current post.\n * @param string $format Optional. Link anchor format. Default '&amp;laquo; %link'.\n * @param string $link Optional. Link permalink format. Default '%title'\n * @param bool $in_same_term Optional. Whether link should be in a same taxonomy term. Default false.\n * @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs. Default empty.\n * @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.\n */\nfunction next_next_post_link( $next_post = null, $format = '%link &amp;raquo;', $link = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {\n global $post;\n\n // Keep track of the current post so we can reset back later.\n $current_post = $post;\n\n // If a &quot;next post&quot; is specified, use that.\n if ( $next_post ) {\n $post = $next_post;\n setup_postdata( $post );\n }\n\n // Make WordPress think we're on the next post.\n $post = get_next_post();\n setup_postdata( $post );\n\n // Echo the next post link, skipping the next post.\n next_post_link( $format, $link, $in_same_term, $excluded_terms, $taxonomy );\n\n // Reset everything back.\n $post = $current_post;\n wp_reset_postdata();\n}\n\n\n/**\n * Displays the previous post link that is adjacent to the previous post.\n *\n * @param object $previous_post Optional. The previous post to reference. Default is current post.\n * @param string $format Optional. Link anchor format. Default '&amp;laquo; %link'.\n * @param string $link Optional. Link permalink format. Default '%title'.\n * @param bool $in_same_term Optional. Whether link should be in a same taxonomy term. Default false.\n * @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs. Default empty.\n * @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.\n */\nfunction previous_previous_post_link( $previous_post = null, $format = '%link &amp;raquo;', $link = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {\n global $post;\n\n // Keep track of the current post so we can reset back later.\n $current_post = $post;\n\n // If a &quot;previous post&quot; is specified, use that.\n if ( $previous_post ) {\n $post = $previous_post;\n setup_postdata( $post );\n }\n\n // Make WordPress think we're on the previous post.\n $post = get_previous_post();\n setup_postdata( $post );\n\n // Echo the previous post link, skipping the previous post.\n previous_post_link( $format, $link, $in_same_term, $excluded_terms, $taxonomy );\n\n // Reset everything back.\n $post = $current_post;\n wp_reset_postdata();\n}\n</code></pre>\n<p>Add those functions to your <code>functions.php</code> file, and use <code>next_next_post_link</code> and <code>previous_previous_post_link</code> the same way you would use <code>next_post_link</code> and <code>previous_post_link</code></p>\n<p>Result:\n<a href=\"https://i.stack.imgur.com/Qr45W.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Qr45W.png\" alt=\"screenshot showing post #3 with links to post #1 and post #5\" /></a></p>\n" }, { "answer_id": 373006, "author": "Alan", "author_id": 192967, "author_profile": "https://wordpress.stackexchange.com/users/192967", "pm_score": 2, "selected": true, "text": "<pre><code>$current_id = get_the_ID();\n$cpt = get_post_type();\n$all_ids = get_posts(array(\n 'fields' =&gt; 'ids',\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; $cpt,\n 'order_by' =&gt; 'post_date',\n 'order' =&gt; 'ASC',\n));\n$prev_key = array_search($current_id, $all_ids) - 2;\n$next_key = array_search($current_id, $all_ids) + 2;\nif(array_key_exists($prev_key, $all_ids)){\n $prev_link = get_the_permalink($all_ids[$prev_key]);\n echo $prev_link;\n}\nif(array_key_exists($next_key, $all_ids)){\n $next_link = get_the_permalink($all_ids[$next_key]);\n echo $next_link;\n}\n</code></pre>\n<p>So I queried all the posts IDs from the current post type. Then since it’s a simple array key=&gt;value, just found the current post key in the array and just added or subtracted so if your current post is the 8th one, your next is 10 and you previous is 6. Then if your array doesn’t have enough keys, say your current was the 8th but your array only had 9 that will mess it up, I check to see if the key exists. If it does, use get_the_permalink() with the value of the desired key.</p>\n<p>Probably not the most graceful way to do it but…</p>\n" } ]
2020/08/11
[ "https://wordpress.stackexchange.com/questions/372764", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
Is it possible when using the `previous_post_link()` function to make it get the previous post after next i.e. make it skip a post. So if you're on post 5 in numerical order it skips to post 3? The reason being I have custom post type `single-cpt.php` file that pulls in two posts, so when using the previous post link out of the box it means when you go to the next post, one of the ones from the previous post is there again. Any help would be fabulous.
``` $current_id = get_the_ID(); $cpt = get_post_type(); $all_ids = get_posts(array( 'fields' => 'ids', 'posts_per_page' => -1, 'post_type' => $cpt, 'order_by' => 'post_date', 'order' => 'ASC', )); $prev_key = array_search($current_id, $all_ids) - 2; $next_key = array_search($current_id, $all_ids) + 2; if(array_key_exists($prev_key, $all_ids)){ $prev_link = get_the_permalink($all_ids[$prev_key]); echo $prev_link; } if(array_key_exists($next_key, $all_ids)){ $next_link = get_the_permalink($all_ids[$next_key]); echo $next_link; } ``` So I queried all the posts IDs from the current post type. Then since it’s a simple array key=>value, just found the current post key in the array and just added or subtracted so if your current post is the 8th one, your next is 10 and you previous is 6. Then if your array doesn’t have enough keys, say your current was the 8th but your array only had 9 that will mess it up, I check to see if the key exists. If it does, use get\_the\_permalink() with the value of the desired key. Probably not the most graceful way to do it but…
372,768
<p>Attempting to make a search in a custom post type &quot;comunicados&quot; inside a shortcode in a custom plugin I send this to get_posts()</p> <pre><code>Array ( [posts_per_page] =&gt; -1 [post_type] =&gt; comunicados [post_status] =&gt; publish [orderby] =&gt; title [order] =&gt; DESC [s] =&gt; co ) </code></pre> <p>Here the actual code</p> <pre><code>//QUERY $opt = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'comunicados', 'post_status' =&gt; 'publish', 'orderby' =&gt; 'title', 'order' =&gt; 'DESC' ); //SEARCH STRING if($_GET['buscar'] != ''){ $opt['s'] = $_GET['buscar']; } print_r($opt); $res = new WP_Query($opt); print_r($res); </code></pre> <p>This returns all the content (pages, posts, other custom post types) but &quot;comunicados&quot;</p> <p>I changed to WP_Query with the same result.</p> <p>If I print_r the WP_Query I see this:</p> <pre><code>WP_Query Object ( [query] =&gt; Array ( [posts_per_page] =&gt; -1 [post_type] =&gt; comunicados [post_status] =&gt; publish [orderby] =&gt; title [order] =&gt; DESC [s] =&gt; co ) [query_vars] =&gt; Array ( [posts_per_page] =&gt; -1 [post_type] =&gt; Array ( [0] =&gt; post [1] =&gt; page [2] =&gt; evento [3] =&gt; informes [4] =&gt; publicaciones [5] =&gt; noticias ) [post_status] =&gt; publish [orderby] =&gt; title [order] =&gt; DESC [s] =&gt; co ... ... ... </code></pre> <p>Note the post_type in query and in query_vars. Is not supossed to be the same? Also I see this:</p> <pre><code>[request] =&gt; SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND (((wp_posts.post_title LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}') OR (wp_posts.post_excerpt LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}') OR (wp_posts.post_content LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}'))) AND wp_posts.post_type IN ('post', 'page', 'evento', 'informes', 'publicaciones', 'noticias') AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_title DESC </code></pre> <p>It's not using my post_type and also these weird strings {48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}</p> <p>I'm not sure how to make this work</p> <p>This is the post type (create with CPT UI)</p> <pre><code>function cptui_register_my_cpts_comunicados() { /** * Post Type: Comunicados. */ $labels = [ &quot;name&quot; =&gt; __( &quot;Comunicados&quot;, &quot;custom-post-type-ui&quot; ), &quot;singular_name&quot; =&gt; __( &quot;Comunicados&quot;, &quot;custom-post-type-ui&quot; ), &quot;menu_name&quot; =&gt; __( &quot;Comunicados&quot;, &quot;custom-post-type-ui&quot; ), &quot;all_items&quot; =&gt; __( &quot;Todos los comunicados&quot;, &quot;custom-post-type-ui&quot; ), &quot;add_new&quot; =&gt; __( &quot;Nuevo comunicado&quot;, &quot;custom-post-type-ui&quot; ), &quot;add_new_item&quot; =&gt; __( &quot;Agregar comunicado&quot;, &quot;custom-post-type-ui&quot; ), &quot;edit_item&quot; =&gt; __( &quot;Editar comunicado&quot;, &quot;custom-post-type-ui&quot; ), &quot;new_item&quot; =&gt; __( &quot;Nuevo comunicado&quot;, &quot;custom-post-type-ui&quot; ), &quot;view_item&quot; =&gt; __( &quot;Ver comunicado&quot;, &quot;custom-post-type-ui&quot; ), &quot;view_items&quot; =&gt; __( &quot;Ver comunicados&quot;, &quot;custom-post-type-ui&quot; ), ]; $args = [ &quot;label&quot; =&gt; __( &quot;Comunicados&quot;, &quot;custom-post-type-ui&quot; ), &quot;labels&quot; =&gt; $labels, &quot;description&quot; =&gt; &quot;&quot;, &quot;public&quot; =&gt; true, &quot;publicly_queryable&quot; =&gt; true, &quot;show_ui&quot; =&gt; true, &quot;show_in_rest&quot; =&gt; true, &quot;rest_base&quot; =&gt; &quot;&quot;, &quot;rest_controller_class&quot; =&gt; &quot;WP_REST_Posts_Controller&quot;, &quot;has_archive&quot; =&gt; false, &quot;show_in_menu&quot; =&gt; true, &quot;show_in_nav_menus&quot; =&gt; true, &quot;delete_with_user&quot; =&gt; false, &quot;exclude_from_search&quot; =&gt; false, &quot;capability_type&quot; =&gt; &quot;comunicado&quot;, &quot;map_meta_cap&quot; =&gt; true, &quot;hierarchical&quot; =&gt; false, &quot;rewrite&quot; =&gt; [ &quot;slug&quot; =&gt; &quot;comunicados&quot;, &quot;with_front&quot; =&gt; true ], &quot;query_var&quot; =&gt; true, &quot;supports&quot; =&gt; [ &quot;title&quot;, &quot;editor&quot;, &quot;thumbnail&quot;, &quot;excerpt&quot; ], &quot;taxonomies&quot; =&gt; [ &quot;post_tag&quot; ], ]; register_post_type( &quot;comunicados&quot;, $args ); } add_action( 'init', 'cptui_register_my_cpts_comunicados' ); </code></pre> <p>Weird thing is, if the &quot;s&quot; paramether is not present, this works fine:</p> <pre><code>WP_Query Object ( [query] =&gt; Array ( [posts_per_page] =&gt; -1 [post_type] =&gt; comunicados [post_status] =&gt; publish [orderby] =&gt; title [order] =&gt; DESC ) [query_vars] =&gt; Array ( [posts_per_page] =&gt; -1 [post_type] =&gt; comunicados [post_status] =&gt; publish [orderby] =&gt; title [order] =&gt; DESC </code></pre> <p>The resulting query is:</p> <pre><code>SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'comunicados' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_title DESC </code></pre>
[ { "answer_id": 372769, "author": "Nate Allen", "author_id": 32698, "author_profile": "https://wordpress.stackexchange.com/users/32698", "pm_score": 0, "selected": false, "text": "<p>I wrote a couple functions that trick WordPress into thinking we're on the previous/next post before calling <code>previous_post_link</code> or <code>next_post_link</code>:</p>\n<pre><code>/**\n * Displays the next post link that is adjacent to the next post.\n *\n * @param object $next_post Optional. The next post to reference. Default is current post.\n * @param string $format Optional. Link anchor format. Default '&amp;laquo; %link'.\n * @param string $link Optional. Link permalink format. Default '%title'\n * @param bool $in_same_term Optional. Whether link should be in a same taxonomy term. Default false.\n * @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs. Default empty.\n * @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.\n */\nfunction next_next_post_link( $next_post = null, $format = '%link &amp;raquo;', $link = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {\n global $post;\n\n // Keep track of the current post so we can reset back later.\n $current_post = $post;\n\n // If a &quot;next post&quot; is specified, use that.\n if ( $next_post ) {\n $post = $next_post;\n setup_postdata( $post );\n }\n\n // Make WordPress think we're on the next post.\n $post = get_next_post();\n setup_postdata( $post );\n\n // Echo the next post link, skipping the next post.\n next_post_link( $format, $link, $in_same_term, $excluded_terms, $taxonomy );\n\n // Reset everything back.\n $post = $current_post;\n wp_reset_postdata();\n}\n\n\n/**\n * Displays the previous post link that is adjacent to the previous post.\n *\n * @param object $previous_post Optional. The previous post to reference. Default is current post.\n * @param string $format Optional. Link anchor format. Default '&amp;laquo; %link'.\n * @param string $link Optional. Link permalink format. Default '%title'.\n * @param bool $in_same_term Optional. Whether link should be in a same taxonomy term. Default false.\n * @param array|string $excluded_terms Optional. Array or comma-separated list of excluded term IDs. Default empty.\n * @param string $taxonomy Optional. Taxonomy, if $in_same_term is true. Default 'category'.\n */\nfunction previous_previous_post_link( $previous_post = null, $format = '%link &amp;raquo;', $link = '%title', $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {\n global $post;\n\n // Keep track of the current post so we can reset back later.\n $current_post = $post;\n\n // If a &quot;previous post&quot; is specified, use that.\n if ( $previous_post ) {\n $post = $previous_post;\n setup_postdata( $post );\n }\n\n // Make WordPress think we're on the previous post.\n $post = get_previous_post();\n setup_postdata( $post );\n\n // Echo the previous post link, skipping the previous post.\n previous_post_link( $format, $link, $in_same_term, $excluded_terms, $taxonomy );\n\n // Reset everything back.\n $post = $current_post;\n wp_reset_postdata();\n}\n</code></pre>\n<p>Add those functions to your <code>functions.php</code> file, and use <code>next_next_post_link</code> and <code>previous_previous_post_link</code> the same way you would use <code>next_post_link</code> and <code>previous_post_link</code></p>\n<p>Result:\n<a href=\"https://i.stack.imgur.com/Qr45W.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Qr45W.png\" alt=\"screenshot showing post #3 with links to post #1 and post #5\" /></a></p>\n" }, { "answer_id": 373006, "author": "Alan", "author_id": 192967, "author_profile": "https://wordpress.stackexchange.com/users/192967", "pm_score": 2, "selected": true, "text": "<pre><code>$current_id = get_the_ID();\n$cpt = get_post_type();\n$all_ids = get_posts(array(\n 'fields' =&gt; 'ids',\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; $cpt,\n 'order_by' =&gt; 'post_date',\n 'order' =&gt; 'ASC',\n));\n$prev_key = array_search($current_id, $all_ids) - 2;\n$next_key = array_search($current_id, $all_ids) + 2;\nif(array_key_exists($prev_key, $all_ids)){\n $prev_link = get_the_permalink($all_ids[$prev_key]);\n echo $prev_link;\n}\nif(array_key_exists($next_key, $all_ids)){\n $next_link = get_the_permalink($all_ids[$next_key]);\n echo $next_link;\n}\n</code></pre>\n<p>So I queried all the posts IDs from the current post type. Then since it’s a simple array key=&gt;value, just found the current post key in the array and just added or subtracted so if your current post is the 8th one, your next is 10 and you previous is 6. Then if your array doesn’t have enough keys, say your current was the 8th but your array only had 9 that will mess it up, I check to see if the key exists. If it does, use get_the_permalink() with the value of the desired key.</p>\n<p>Probably not the most graceful way to do it but…</p>\n" } ]
2020/08/11
[ "https://wordpress.stackexchange.com/questions/372768", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/178234/" ]
Attempting to make a search in a custom post type "comunicados" inside a shortcode in a custom plugin I send this to get\_posts() ``` Array ( [posts_per_page] => -1 [post_type] => comunicados [post_status] => publish [orderby] => title [order] => DESC [s] => co ) ``` Here the actual code ``` //QUERY $opt = array( 'posts_per_page' => -1, 'post_type' => 'comunicados', 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'DESC' ); //SEARCH STRING if($_GET['buscar'] != ''){ $opt['s'] = $_GET['buscar']; } print_r($opt); $res = new WP_Query($opt); print_r($res); ``` This returns all the content (pages, posts, other custom post types) but "comunicados" I changed to WP\_Query with the same result. If I print\_r the WP\_Query I see this: ``` WP_Query Object ( [query] => Array ( [posts_per_page] => -1 [post_type] => comunicados [post_status] => publish [orderby] => title [order] => DESC [s] => co ) [query_vars] => Array ( [posts_per_page] => -1 [post_type] => Array ( [0] => post [1] => page [2] => evento [3] => informes [4] => publicaciones [5] => noticias ) [post_status] => publish [orderby] => title [order] => DESC [s] => co ... ... ... ``` Note the post\_type in query and in query\_vars. Is not supossed to be the same? Also I see this: ``` [request] => SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND (((wp_posts.post_title LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}') OR (wp_posts.post_excerpt LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}') OR (wp_posts.post_content LIKE '{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}co{48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d}'))) AND wp_posts.post_type IN ('post', 'page', 'evento', 'informes', 'publicaciones', 'noticias') AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_title DESC ``` It's not using my post\_type and also these weird strings {48ae2fbb00693ccb2a14823f0ece41e120c73baf24f9e905961bdb4a319d675d} I'm not sure how to make this work This is the post type (create with CPT UI) ``` function cptui_register_my_cpts_comunicados() { /** * Post Type: Comunicados. */ $labels = [ "name" => __( "Comunicados", "custom-post-type-ui" ), "singular_name" => __( "Comunicados", "custom-post-type-ui" ), "menu_name" => __( "Comunicados", "custom-post-type-ui" ), "all_items" => __( "Todos los comunicados", "custom-post-type-ui" ), "add_new" => __( "Nuevo comunicado", "custom-post-type-ui" ), "add_new_item" => __( "Agregar comunicado", "custom-post-type-ui" ), "edit_item" => __( "Editar comunicado", "custom-post-type-ui" ), "new_item" => __( "Nuevo comunicado", "custom-post-type-ui" ), "view_item" => __( "Ver comunicado", "custom-post-type-ui" ), "view_items" => __( "Ver comunicados", "custom-post-type-ui" ), ]; $args = [ "label" => __( "Comunicados", "custom-post-type-ui" ), "labels" => $labels, "description" => "", "public" => true, "publicly_queryable" => true, "show_ui" => true, "show_in_rest" => true, "rest_base" => "", "rest_controller_class" => "WP_REST_Posts_Controller", "has_archive" => false, "show_in_menu" => true, "show_in_nav_menus" => true, "delete_with_user" => false, "exclude_from_search" => false, "capability_type" => "comunicado", "map_meta_cap" => true, "hierarchical" => false, "rewrite" => [ "slug" => "comunicados", "with_front" => true ], "query_var" => true, "supports" => [ "title", "editor", "thumbnail", "excerpt" ], "taxonomies" => [ "post_tag" ], ]; register_post_type( "comunicados", $args ); } add_action( 'init', 'cptui_register_my_cpts_comunicados' ); ``` Weird thing is, if the "s" paramether is not present, this works fine: ``` WP_Query Object ( [query] => Array ( [posts_per_page] => -1 [post_type] => comunicados [post_status] => publish [orderby] => title [order] => DESC ) [query_vars] => Array ( [posts_per_page] => -1 [post_type] => comunicados [post_status] => publish [orderby] => title [order] => DESC ``` The resulting query is: ``` SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'comunicados' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_title DESC ```
``` $current_id = get_the_ID(); $cpt = get_post_type(); $all_ids = get_posts(array( 'fields' => 'ids', 'posts_per_page' => -1, 'post_type' => $cpt, 'order_by' => 'post_date', 'order' => 'ASC', )); $prev_key = array_search($current_id, $all_ids) - 2; $next_key = array_search($current_id, $all_ids) + 2; if(array_key_exists($prev_key, $all_ids)){ $prev_link = get_the_permalink($all_ids[$prev_key]); echo $prev_link; } if(array_key_exists($next_key, $all_ids)){ $next_link = get_the_permalink($all_ids[$next_key]); echo $next_link; } ``` So I queried all the posts IDs from the current post type. Then since it’s a simple array key=>value, just found the current post key in the array and just added or subtracted so if your current post is the 8th one, your next is 10 and you previous is 6. Then if your array doesn’t have enough keys, say your current was the 8th but your array only had 9 that will mess it up, I check to see if the key exists. If it does, use get\_the\_permalink() with the value of the desired key. Probably not the most graceful way to do it but…
372,785
<p>I built an image randomizer so that when I open a .php file in a URL that it displays the image with <code>readfile($randomImage);</code>. This works locally but when I upload it to the server it gets blocked by the firewall since we do not want to be able to load URLs like</p> <pre><code>https://www.example.com/wp-content/themes/THEME/randomImage.php </code></pre> <p>I want to load a <code>.php</code> script on a <code>.jpg</code> file. What needs to happen is that when I use the URL (for instance)</p> <pre><code>https://www.example.com/image.jpg </code></pre> <p>and when I load this image that it runs a PHP file like</p> <pre><code>https://www.example.com/randomizer.php </code></pre> <p>In other words, I want WordPress to think that it is loading a URL ending with <code>.jpg</code> but opens a <code>.php</code> file</p> <p>Is this something that is realizable?</p>
[ { "answer_id": 372789, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 0, "selected": false, "text": "<p>Try the following at the <em>top</em> of the <code>.htaccess</code> file, <em>before</em> the existing WordPress directives:</p>\n<pre><code># Internally rewrite &quot;/image.jpg&quot; to &quot;/randomizer.php&quot;\nRewriteRule ^image\\.jpg$ randomizer.php [L]\n</code></pre>\n<p>This uses mod_rewrite to rewrite the URL. There is no need to repeat the <code>RewriteEngine On</code> directive (that occurs later in the file).</p>\n<p>Any request for <code>/image.jpg</code> (in the document root) is internally/silently rewritten to your <code>/randomizer.php</code> PHP script (also in the document root - assuming that is where your <code>.htaccess</code> file is located, <em>or</em> where the <code>RewriteBase</code> directive points to).</p>\n<blockquote>\n<p>I have a weird request maybe</p>\n</blockquote>\n<p>This isn't weird at all. In fact, using URL-rewriting like this is probably preferable to linking directly to your PHP script. Although calling the URL <code>random-image.jpg</code> or something similar maybe a good idea.</p>\n<p>This is actually pretty much identical to a question I answered yesterday on StackOverflow:\n<a href=\"https://stackoverflow.com/questions/63340667/htaccess-redirect-one-file-to-another-including-query-string\">https://stackoverflow.com/questions/63340667/htaccess-redirect-one-file-to-another-including-query-string</a></p>\n" }, { "answer_id": 374492, "author": "w.jelsma", "author_id": 192959, "author_profile": "https://wordpress.stackexchange.com/users/192959", "pm_score": -1, "selected": false, "text": "<p>I created a function named randomImage() that simply takes a random image from an array, this function gets called in with the function below:</p>\n<pre><code>function imageRedirect(){\n// Get the page name from the URL\n$page = $_SERVER[&quot;REQUEST_URI&quot;];\n\n// Make sure debug mode is disabled since the deprecation errors will ruin the photo content\nif (WP_DEBUG) throw new Exception('Due to depreciation errors this photo can only be rendered with debug mode disabled!');\n\n// If we're on the random image page\nif ($page == RANDOM_IMAGE_URL) {\n\n // Fetch a random image and return the data\n $image = randomImage();\n\n header(&quot;Content-Type: image/jpeg&quot;);\n header(&quot;Content-Length: &quot; . filesize($image));\n readfile($image);\n\n exit;\n}\n}\n</code></pre>\n" } ]
2020/08/11
[ "https://wordpress.stackexchange.com/questions/372785", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/192959/" ]
I built an image randomizer so that when I open a .php file in a URL that it displays the image with `readfile($randomImage);`. This works locally but when I upload it to the server it gets blocked by the firewall since we do not want to be able to load URLs like ``` https://www.example.com/wp-content/themes/THEME/randomImage.php ``` I want to load a `.php` script on a `.jpg` file. What needs to happen is that when I use the URL (for instance) ``` https://www.example.com/image.jpg ``` and when I load this image that it runs a PHP file like ``` https://www.example.com/randomizer.php ``` In other words, I want WordPress to think that it is loading a URL ending with `.jpg` but opens a `.php` file Is this something that is realizable?
Try the following at the *top* of the `.htaccess` file, *before* the existing WordPress directives: ``` # Internally rewrite "/image.jpg" to "/randomizer.php" RewriteRule ^image\.jpg$ randomizer.php [L] ``` This uses mod\_rewrite to rewrite the URL. There is no need to repeat the `RewriteEngine On` directive (that occurs later in the file). Any request for `/image.jpg` (in the document root) is internally/silently rewritten to your `/randomizer.php` PHP script (also in the document root - assuming that is where your `.htaccess` file is located, *or* where the `RewriteBase` directive points to). > > I have a weird request maybe > > > This isn't weird at all. In fact, using URL-rewriting like this is probably preferable to linking directly to your PHP script. Although calling the URL `random-image.jpg` or something similar maybe a good idea. This is actually pretty much identical to a question I answered yesterday on StackOverflow: <https://stackoverflow.com/questions/63340667/htaccess-redirect-one-file-to-another-including-query-string>
372,805
<p>I hope this is not a far-away topic from this platform.</p> <p>I plan to create a WordPress site, but I thought that maybe instead of hosting images on my own WordPress installation, I thought that if I just upload the images to a 3rd-party service like Imgur and then just insert them as linked images in my posts that would be a better idea?</p> <p>My reasoning is:</p> <ul> <li>These 3rd-party services like Imgur already have a CDN, and they are faster in loading than my website.</li> <li>I won't have to buy/install some image optimization plugins, because images are hosted somewhere else and they already optimized there.</li> <li>Over time, I won't have to worry about storage/size issues because of the large number of pictures.</li> <li>Some services have been there for 10, 15, 20 years... So they are trusted to not disappear over night.</li> </ul> <p>Of course, there might be some concerns about creating a backup just in case my pictures get removed or the 3rd-party service goes down... Is the idea generally good?</p> <p>Is there anything else I have to worry about?</p>
[ { "answer_id": 372789, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 0, "selected": false, "text": "<p>Try the following at the <em>top</em> of the <code>.htaccess</code> file, <em>before</em> the existing WordPress directives:</p>\n<pre><code># Internally rewrite &quot;/image.jpg&quot; to &quot;/randomizer.php&quot;\nRewriteRule ^image\\.jpg$ randomizer.php [L]\n</code></pre>\n<p>This uses mod_rewrite to rewrite the URL. There is no need to repeat the <code>RewriteEngine On</code> directive (that occurs later in the file).</p>\n<p>Any request for <code>/image.jpg</code> (in the document root) is internally/silently rewritten to your <code>/randomizer.php</code> PHP script (also in the document root - assuming that is where your <code>.htaccess</code> file is located, <em>or</em> where the <code>RewriteBase</code> directive points to).</p>\n<blockquote>\n<p>I have a weird request maybe</p>\n</blockquote>\n<p>This isn't weird at all. In fact, using URL-rewriting like this is probably preferable to linking directly to your PHP script. Although calling the URL <code>random-image.jpg</code> or something similar maybe a good idea.</p>\n<p>This is actually pretty much identical to a question I answered yesterday on StackOverflow:\n<a href=\"https://stackoverflow.com/questions/63340667/htaccess-redirect-one-file-to-another-including-query-string\">https://stackoverflow.com/questions/63340667/htaccess-redirect-one-file-to-another-including-query-string</a></p>\n" }, { "answer_id": 374492, "author": "w.jelsma", "author_id": 192959, "author_profile": "https://wordpress.stackexchange.com/users/192959", "pm_score": -1, "selected": false, "text": "<p>I created a function named randomImage() that simply takes a random image from an array, this function gets called in with the function below:</p>\n<pre><code>function imageRedirect(){\n// Get the page name from the URL\n$page = $_SERVER[&quot;REQUEST_URI&quot;];\n\n// Make sure debug mode is disabled since the deprecation errors will ruin the photo content\nif (WP_DEBUG) throw new Exception('Due to depreciation errors this photo can only be rendered with debug mode disabled!');\n\n// If we're on the random image page\nif ($page == RANDOM_IMAGE_URL) {\n\n // Fetch a random image and return the data\n $image = randomImage();\n\n header(&quot;Content-Type: image/jpeg&quot;);\n header(&quot;Content-Length: &quot; . filesize($image));\n readfile($image);\n\n exit;\n}\n}\n</code></pre>\n" } ]
2020/08/11
[ "https://wordpress.stackexchange.com/questions/372805", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193249/" ]
I hope this is not a far-away topic from this platform. I plan to create a WordPress site, but I thought that maybe instead of hosting images on my own WordPress installation, I thought that if I just upload the images to a 3rd-party service like Imgur and then just insert them as linked images in my posts that would be a better idea? My reasoning is: * These 3rd-party services like Imgur already have a CDN, and they are faster in loading than my website. * I won't have to buy/install some image optimization plugins, because images are hosted somewhere else and they already optimized there. * Over time, I won't have to worry about storage/size issues because of the large number of pictures. * Some services have been there for 10, 15, 20 years... So they are trusted to not disappear over night. Of course, there might be some concerns about creating a backup just in case my pictures get removed or the 3rd-party service goes down... Is the idea generally good? Is there anything else I have to worry about?
Try the following at the *top* of the `.htaccess` file, *before* the existing WordPress directives: ``` # Internally rewrite "/image.jpg" to "/randomizer.php" RewriteRule ^image\.jpg$ randomizer.php [L] ``` This uses mod\_rewrite to rewrite the URL. There is no need to repeat the `RewriteEngine On` directive (that occurs later in the file). Any request for `/image.jpg` (in the document root) is internally/silently rewritten to your `/randomizer.php` PHP script (also in the document root - assuming that is where your `.htaccess` file is located, *or* where the `RewriteBase` directive points to). > > I have a weird request maybe > > > This isn't weird at all. In fact, using URL-rewriting like this is probably preferable to linking directly to your PHP script. Although calling the URL `random-image.jpg` or something similar maybe a good idea. This is actually pretty much identical to a question I answered yesterday on StackOverflow: <https://stackoverflow.com/questions/63340667/htaccess-redirect-one-file-to-another-including-query-string>
372,825
<p>Since WP 5.5 just released and now you can set plugins to auto-update, can this be done via wp-cli? Looking at the documentation, I don't see a sub-command for it: <a href="https://developer.wordpress.org/cli/commands/plugin/" rel="noreferrer">https://developer.wordpress.org/cli/commands/plugin/</a></p> <p>I manage a lot of Wordpress sites, most of which are OK to auto-update and would save me a lot of time if they did, as well as reducing security risks.</p> <p>I'd like to enable auto-updates for plugins across over many wordpress sites. Any solutions?</p>
[ { "answer_id": 384240, "author": "Mike Eng", "author_id": 7313, "author_profile": "https://wordpress.stackexchange.com/users/7313", "pm_score": 1, "selected": false, "text": "<p>This is not using wp-cli, but maybe the next best thing:</p>\n<p>From the Plugins page in WordPress Admin: siteurl.com/wp-admin/plugins.php</p>\n<p>You can check all plugins and then from the bulk actions, choose “enable auto updates”.</p>\n<p><img src=\"https://i.stack.imgur.com/UTlfK.jpg\" alt=\"enable auto updates\" /></p>\n" }, { "answer_id": 384243, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>The simplest way via <em>wp-cli</em> that comes to mind (<s>while it's not supported yet as far as I can see</s>) is something like:</p>\n<pre><code>wp eval &quot;update_option( 'auto_update_plugins', array_keys( get_plugins() ) );&quot;\n</code></pre>\n<p>that will update the <code>auto_update_plugins</code> option with the array of all plugin files to update.</p>\n<p>This should probably be extended further to only update plugins that are truly <em>updateable</em> or e.g. from a json list to use the json format option of <em>wp-cli</em>.</p>\n<p>One can also enable all plugin updates with a filter in a plugin:</p>\n<pre><code>add_filter( 'auto_update_plugin', '__return_true' );\n</code></pre>\n<p>That will show up as &quot;Auto-updates enabled&quot; for each plugin in the plugins admin table but the user will not be able to change it from the UI.</p>\n<p>ps: this <em>wp-cli</em> <a href=\"https://github.com/WordPress/wp-autoupdates/issues/8\" rel=\"nofollow noreferrer\">command suggestion</a> by Jeffrey Paul seems very useful.</p>\n<p><strong>Update</strong>: This seems to be supported in <a href=\"https://github.com/wp-cli/extension-command\" rel=\"nofollow noreferrer\">wp-cli/extension-command</a> version 2.0.12 by this <a href=\"https://github.com/wp-cli/extension-command/pull/259\" rel=\"nofollow noreferrer\">pull request</a>:</p>\n<pre><code>wp plugin auto-updates status [&lt;plugin&gt;...] [--all] [--enabled-only] [--disabled-only] [--field=&lt;field&gt;]\nwp plugin auto-updates enable [&lt;plugin&gt;...] [--all] [--disabled-only]\nwp plugin auto-updates disable [&lt;plugin&gt;...] [--all] [--enabled-only]\n</code></pre>\n<p>but it looks like it's not merged into the main <em>wp-cli</em> yet in version 2.4.</p>\n<p>It's possible to get the latest version with:</p>\n<pre><code>wp package install [email protected]:wp-cli/extension-command.git\n</code></pre>\n<p>according to the <a href=\"https://github.com/wp-cli/extension-command#installing\" rel=\"nofollow noreferrer\">installing</a> part of the <em>wp-cli/extension-command</em> docs.</p>\n" } ]
2020/08/11
[ "https://wordpress.stackexchange.com/questions/372825", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31560/" ]
Since WP 5.5 just released and now you can set plugins to auto-update, can this be done via wp-cli? Looking at the documentation, I don't see a sub-command for it: <https://developer.wordpress.org/cli/commands/plugin/> I manage a lot of Wordpress sites, most of which are OK to auto-update and would save me a lot of time if they did, as well as reducing security risks. I'd like to enable auto-updates for plugins across over many wordpress sites. Any solutions?
The simplest way via *wp-cli* that comes to mind (~~while it's not supported yet as far as I can see~~) is something like: ``` wp eval "update_option( 'auto_update_plugins', array_keys( get_plugins() ) );" ``` that will update the `auto_update_plugins` option with the array of all plugin files to update. This should probably be extended further to only update plugins that are truly *updateable* or e.g. from a json list to use the json format option of *wp-cli*. One can also enable all plugin updates with a filter in a plugin: ``` add_filter( 'auto_update_plugin', '__return_true' ); ``` That will show up as "Auto-updates enabled" for each plugin in the plugins admin table but the user will not be able to change it from the UI. ps: this *wp-cli* [command suggestion](https://github.com/WordPress/wp-autoupdates/issues/8) by Jeffrey Paul seems very useful. **Update**: This seems to be supported in [wp-cli/extension-command](https://github.com/wp-cli/extension-command) version 2.0.12 by this [pull request](https://github.com/wp-cli/extension-command/pull/259): ``` wp plugin auto-updates status [<plugin>...] [--all] [--enabled-only] [--disabled-only] [--field=<field>] wp plugin auto-updates enable [<plugin>...] [--all] [--disabled-only] wp plugin auto-updates disable [<plugin>...] [--all] [--enabled-only] ``` but it looks like it's not merged into the main *wp-cli* yet in version 2.4. It's possible to get the latest version with: ``` wp package install [email protected]:wp-cli/extension-command.git ``` according to the [installing](https://github.com/wp-cli/extension-command#installing) part of the *wp-cli/extension-command* docs.
372,840
<p>I want to export the form data and send it as an attachment. In this case, can i rewrite the file (/uploads/2020/08/sample.csv) with the form data and send it as an attachment.</p> <p>right now, it is just a blank attachment when i receive it in my email</p> <p>Here is my code in function.php, Please help me:</p> <pre><code>add_action( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 1 ); function add_form_as_attachment(&amp;$WPCF7_ContactForm) { $contact_form = WPCF7_ContactForm::get_current(); $Fname = $formdata['firstName']; $Lname = $formdata['lastName']; $email = $formdata['email']; $list = array ( array( 'First Name:',$Fname), array( 'Last Name:', $Lname), array( 'Email:', $email), ); $fp = fopen( site_url() . 'uploads/2020/08/sample.csv', 'w'); foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); } </code></pre>
[ { "answer_id": 373724, "author": "amitdutt24", "author_id": 188153, "author_profile": "https://wordpress.stackexchange.com/users/188153", "pm_score": 0, "selected": false, "text": "<p>I solved mine problem with this code. Hope it could help others too -</p>\n<pre><code>add_action( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 1 ); \n\nfunction add_form_as_attachment(&amp;$WPCF7_ContactForm) {\n$contact_form = WPCF7_ContactForm::get_current();\n$Fname = $formdata['firstName'];\n$Lname = $formdata['lastName'];\n$email = $formdata['email'];\n\n$list = array (\narray( 'First Name:',$Fname),\narray( 'Last Name:', $Lname),\narray( 'Email:', $email),\n\n);\n// Save file path separately \n$file_path = site_url() . 'uploads/2020/08/sample.csv'; // check File permission for writing content\n$fp = fopen( $file_path , 'w');\n\nforeach ($list as $fields) {\nfputcsv($fp, $fields);\n}\nfclose($fp);\n//MAIL starts here \n$attachments = array( $file_path );\n$headers = 'From: name &lt;[email protected]&gt;' . &quot;\\r\\n&quot;;\n \nwp_mail($to, $subject, $message,$headers, $attachments);\n// You are done \n}\n</code></pre>\n" }, { "answer_id": 388788, "author": "JTjards", "author_id": 161741, "author_profile": "https://wordpress.stackexchange.com/users/161741", "pm_score": 1, "selected": false, "text": "<p>There are a few things omitted in the above solution, like defining the most params of wp_mail.\nAlso I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution.</p>\n<p>Here's my take:</p>\n<pre><code>add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 );\nfunction add_form_as_attachment( $contact_form, $abort, $submission ) {\n\n $form_id = $contact_form-&gt;id();\n\n //Check for selected form id and actual submission\n if ($form_id == 123 &amp;&amp; $submission){\n\n $posted_data = $submission-&gt;get_posted_data() ;\n // Check again for posted data\n if ( empty ($posted_data)){\n return; \n }\n\n //Get your form fields\n $firstname = $posted_data['your-name'];\n $lastname = $posted_data['your-lastname'];\n $email = $posted_data['your-email'];\n\n $list = array (\n array( 'First Name:',$firstname),\n array( 'Last Name:', $lastname),\n array( 'Email:', $email),\n\n );\n // Save file path separately \n $upload_dir = wp_upload_dir(); \n $file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example\n\n $fp = fopen( $file_path , 'w'); //overwrites file at each submission\n foreach ($list as $fields) {\n fputcsv($fp, $fields);\n }\n fclose($fp);\n\n // Modification of mail(1) start here\n $properties = $contact_form-&gt;get_properties();\n $properties['mail']['attachments'] = $file_path;\n $contact_form-&gt;set_properties($properties);\n\n return $contact_form;\n }//endif ID &amp;&amp; submission\n}\n</code></pre>\n" } ]
2020/08/12
[ "https://wordpress.stackexchange.com/questions/372840", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/191358/" ]
I want to export the form data and send it as an attachment. In this case, can i rewrite the file (/uploads/2020/08/sample.csv) with the form data and send it as an attachment. right now, it is just a blank attachment when i receive it in my email Here is my code in function.php, Please help me: ``` add_action( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 1 ); function add_form_as_attachment(&$WPCF7_ContactForm) { $contact_form = WPCF7_ContactForm::get_current(); $Fname = $formdata['firstName']; $Lname = $formdata['lastName']; $email = $formdata['email']; $list = array ( array( 'First Name:',$Fname), array( 'Last Name:', $Lname), array( 'Email:', $email), ); $fp = fopen( site_url() . 'uploads/2020/08/sample.csv', 'w'); foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); } ```
There are a few things omitted in the above solution, like defining the most params of wp\_mail. Also I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution. Here's my take: ``` add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 ); function add_form_as_attachment( $contact_form, $abort, $submission ) { $form_id = $contact_form->id(); //Check for selected form id and actual submission if ($form_id == 123 && $submission){ $posted_data = $submission->get_posted_data() ; // Check again for posted data if ( empty ($posted_data)){ return; } //Get your form fields $firstname = $posted_data['your-name']; $lastname = $posted_data['your-lastname']; $email = $posted_data['your-email']; $list = array ( array( 'First Name:',$firstname), array( 'Last Name:', $lastname), array( 'Email:', $email), ); // Save file path separately $upload_dir = wp_upload_dir(); $file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example $fp = fopen( $file_path , 'w'); //overwrites file at each submission foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); // Modification of mail(1) start here $properties = $contact_form->get_properties(); $properties['mail']['attachments'] = $file_path; $contact_form->set_properties($properties); return $contact_form; }//endif ID && submission } ```
372,871
<p>I'm trying to translate the month names as underlined in <a href="https://i.imgur.com/s9x1LOO.png" rel="nofollow noreferrer">this image</a>, without <a href="https://i.imgur.com/gm9RH9L.png" rel="nofollow noreferrer">changing the entire WP backend</a> as well, as I require the backend to remain English.</p> <p>I managed to translate the default strings via's <a href="https://wpastra.com/docs/astra-default-strings/" rel="nofollow noreferrer">Astra's Default String page</a>, but they don't provide strings for the month names.</p> <p>Any help would be appreciated!</p> <p>Thank you :)</p>
[ { "answer_id": 373724, "author": "amitdutt24", "author_id": 188153, "author_profile": "https://wordpress.stackexchange.com/users/188153", "pm_score": 0, "selected": false, "text": "<p>I solved mine problem with this code. Hope it could help others too -</p>\n<pre><code>add_action( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 1 ); \n\nfunction add_form_as_attachment(&amp;$WPCF7_ContactForm) {\n$contact_form = WPCF7_ContactForm::get_current();\n$Fname = $formdata['firstName'];\n$Lname = $formdata['lastName'];\n$email = $formdata['email'];\n\n$list = array (\narray( 'First Name:',$Fname),\narray( 'Last Name:', $Lname),\narray( 'Email:', $email),\n\n);\n// Save file path separately \n$file_path = site_url() . 'uploads/2020/08/sample.csv'; // check File permission for writing content\n$fp = fopen( $file_path , 'w');\n\nforeach ($list as $fields) {\nfputcsv($fp, $fields);\n}\nfclose($fp);\n//MAIL starts here \n$attachments = array( $file_path );\n$headers = 'From: name &lt;[email protected]&gt;' . &quot;\\r\\n&quot;;\n \nwp_mail($to, $subject, $message,$headers, $attachments);\n// You are done \n}\n</code></pre>\n" }, { "answer_id": 388788, "author": "JTjards", "author_id": 161741, "author_profile": "https://wordpress.stackexchange.com/users/161741", "pm_score": 1, "selected": false, "text": "<p>There are a few things omitted in the above solution, like defining the most params of wp_mail.\nAlso I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution.</p>\n<p>Here's my take:</p>\n<pre><code>add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 );\nfunction add_form_as_attachment( $contact_form, $abort, $submission ) {\n\n $form_id = $contact_form-&gt;id();\n\n //Check for selected form id and actual submission\n if ($form_id == 123 &amp;&amp; $submission){\n\n $posted_data = $submission-&gt;get_posted_data() ;\n // Check again for posted data\n if ( empty ($posted_data)){\n return; \n }\n\n //Get your form fields\n $firstname = $posted_data['your-name'];\n $lastname = $posted_data['your-lastname'];\n $email = $posted_data['your-email'];\n\n $list = array (\n array( 'First Name:',$firstname),\n array( 'Last Name:', $lastname),\n array( 'Email:', $email),\n\n );\n // Save file path separately \n $upload_dir = wp_upload_dir(); \n $file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example\n\n $fp = fopen( $file_path , 'w'); //overwrites file at each submission\n foreach ($list as $fields) {\n fputcsv($fp, $fields);\n }\n fclose($fp);\n\n // Modification of mail(1) start here\n $properties = $contact_form-&gt;get_properties();\n $properties['mail']['attachments'] = $file_path;\n $contact_form-&gt;set_properties($properties);\n\n return $contact_form;\n }//endif ID &amp;&amp; submission\n}\n</code></pre>\n" } ]
2020/08/12
[ "https://wordpress.stackexchange.com/questions/372871", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193023/" ]
I'm trying to translate the month names as underlined in [this image](https://i.imgur.com/s9x1LOO.png), without [changing the entire WP backend](https://i.imgur.com/gm9RH9L.png) as well, as I require the backend to remain English. I managed to translate the default strings via's [Astra's Default String page](https://wpastra.com/docs/astra-default-strings/), but they don't provide strings for the month names. Any help would be appreciated! Thank you :)
There are a few things omitted in the above solution, like defining the most params of wp\_mail. Also I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution. Here's my take: ``` add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 ); function add_form_as_attachment( $contact_form, $abort, $submission ) { $form_id = $contact_form->id(); //Check for selected form id and actual submission if ($form_id == 123 && $submission){ $posted_data = $submission->get_posted_data() ; // Check again for posted data if ( empty ($posted_data)){ return; } //Get your form fields $firstname = $posted_data['your-name']; $lastname = $posted_data['your-lastname']; $email = $posted_data['your-email']; $list = array ( array( 'First Name:',$firstname), array( 'Last Name:', $lastname), array( 'Email:', $email), ); // Save file path separately $upload_dir = wp_upload_dir(); $file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example $fp = fopen( $file_path , 'w'); //overwrites file at each submission foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); // Modification of mail(1) start here $properties = $contact_form->get_properties(); $properties['mail']['attachments'] = $file_path; $contact_form->set_properties($properties); return $contact_form; }//endif ID && submission } ```
372,877
<p>I had installed a chat plugin called Crisp chat. But i still see crisp chat box in my mobile but not in PC. I have deleted it yet it is seen in mobile. please guide me.</p>
[ { "answer_id": 373724, "author": "amitdutt24", "author_id": 188153, "author_profile": "https://wordpress.stackexchange.com/users/188153", "pm_score": 0, "selected": false, "text": "<p>I solved mine problem with this code. Hope it could help others too -</p>\n<pre><code>add_action( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 1 ); \n\nfunction add_form_as_attachment(&amp;$WPCF7_ContactForm) {\n$contact_form = WPCF7_ContactForm::get_current();\n$Fname = $formdata['firstName'];\n$Lname = $formdata['lastName'];\n$email = $formdata['email'];\n\n$list = array (\narray( 'First Name:',$Fname),\narray( 'Last Name:', $Lname),\narray( 'Email:', $email),\n\n);\n// Save file path separately \n$file_path = site_url() . 'uploads/2020/08/sample.csv'; // check File permission for writing content\n$fp = fopen( $file_path , 'w');\n\nforeach ($list as $fields) {\nfputcsv($fp, $fields);\n}\nfclose($fp);\n//MAIL starts here \n$attachments = array( $file_path );\n$headers = 'From: name &lt;[email protected]&gt;' . &quot;\\r\\n&quot;;\n \nwp_mail($to, $subject, $message,$headers, $attachments);\n// You are done \n}\n</code></pre>\n" }, { "answer_id": 388788, "author": "JTjards", "author_id": 161741, "author_profile": "https://wordpress.stackexchange.com/users/161741", "pm_score": 1, "selected": false, "text": "<p>There are a few things omitted in the above solution, like defining the most params of wp_mail.\nAlso I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution.</p>\n<p>Here's my take:</p>\n<pre><code>add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 );\nfunction add_form_as_attachment( $contact_form, $abort, $submission ) {\n\n $form_id = $contact_form-&gt;id();\n\n //Check for selected form id and actual submission\n if ($form_id == 123 &amp;&amp; $submission){\n\n $posted_data = $submission-&gt;get_posted_data() ;\n // Check again for posted data\n if ( empty ($posted_data)){\n return; \n }\n\n //Get your form fields\n $firstname = $posted_data['your-name'];\n $lastname = $posted_data['your-lastname'];\n $email = $posted_data['your-email'];\n\n $list = array (\n array( 'First Name:',$firstname),\n array( 'Last Name:', $lastname),\n array( 'Email:', $email),\n\n );\n // Save file path separately \n $upload_dir = wp_upload_dir(); \n $file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example\n\n $fp = fopen( $file_path , 'w'); //overwrites file at each submission\n foreach ($list as $fields) {\n fputcsv($fp, $fields);\n }\n fclose($fp);\n\n // Modification of mail(1) start here\n $properties = $contact_form-&gt;get_properties();\n $properties['mail']['attachments'] = $file_path;\n $contact_form-&gt;set_properties($properties);\n\n return $contact_form;\n }//endif ID &amp;&amp; submission\n}\n</code></pre>\n" } ]
2020/08/12
[ "https://wordpress.stackexchange.com/questions/372877", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193030/" ]
I had installed a chat plugin called Crisp chat. But i still see crisp chat box in my mobile but not in PC. I have deleted it yet it is seen in mobile. please guide me.
There are a few things omitted in the above solution, like defining the most params of wp\_mail. Also I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution. Here's my take: ``` add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 ); function add_form_as_attachment( $contact_form, $abort, $submission ) { $form_id = $contact_form->id(); //Check for selected form id and actual submission if ($form_id == 123 && $submission){ $posted_data = $submission->get_posted_data() ; // Check again for posted data if ( empty ($posted_data)){ return; } //Get your form fields $firstname = $posted_data['your-name']; $lastname = $posted_data['your-lastname']; $email = $posted_data['your-email']; $list = array ( array( 'First Name:',$firstname), array( 'Last Name:', $lastname), array( 'Email:', $email), ); // Save file path separately $upload_dir = wp_upload_dir(); $file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example $fp = fopen( $file_path , 'w'); //overwrites file at each submission foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); // Modification of mail(1) start here $properties = $contact_form->get_properties(); $properties['mail']['attachments'] = $file_path; $contact_form->set_properties($properties); return $contact_form; }//endif ID && submission } ```
372,878
<p>I am trying to get latest from specific categories (3 posts), but the code does not seem working. Instead of displaying posts from the mentioned categories, it is displaying posts from the first category.</p> <p>Here is my code:</p> <pre><code>&lt;?php do_action( 'hitmag_before_content' ); ?&gt; &lt;div id=&quot;primary&quot; class=&quot;content-area&quot;&gt; &lt;main id=&quot;main&quot; class=&quot;site-main&quot; role=&quot;main&quot;&gt; &lt;h1&gt;Latest News&lt;/h1&gt; &lt;?php do_action( 'hitmag_before_blog_posts' ); ?&gt; &lt;?php $args = array( 'post_type' =&gt; 'post' , 'orderby' =&gt; 'date' , 'order' =&gt; 'DESC' , 'posts_per_page' =&gt; 3, 'category' =&gt; '30','33','1', 'paged' =&gt; get_query_var('paged'), 'post_parent' =&gt; $parent ); ?&gt; &lt;?php query_posts($args); ?&gt; &lt;?php if ( have_posts() ) : if ( is_home() &amp;&amp; ! is_front_page() ) : ?&gt; &lt;header&gt; &lt;h1 class=&quot;page-title screen-reader-text&quot;&gt;&lt;?php single_post_title(); ?&gt;&lt;/h1&gt; &lt;/header&gt; &lt;?php endif; $archive_content_layout = get_option( 'archive_content_layout', 'th-grid-2' ); echo '&lt;div class=&quot;posts-wrap ' . esc_attr( $archive_content_layout ) . '&quot;&gt;'; /* Start the Loop */ while ( have_posts() ) : the_post(); /* * Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'template-parts/content', get_post_format() ); endwhile; echo '&lt;/div&gt;&lt;!-- .posts-wrap --&gt;'; else : get_template_part( 'template-parts/content', 'none' ); endif; ?&gt; &lt;?php do_action( 'hitmag_after_blog_posts' ); ?&gt; &lt;/main&gt;&lt;!-- #main --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; </code></pre>
[ { "answer_id": 373724, "author": "amitdutt24", "author_id": 188153, "author_profile": "https://wordpress.stackexchange.com/users/188153", "pm_score": 0, "selected": false, "text": "<p>I solved mine problem with this code. Hope it could help others too -</p>\n<pre><code>add_action( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 1 ); \n\nfunction add_form_as_attachment(&amp;$WPCF7_ContactForm) {\n$contact_form = WPCF7_ContactForm::get_current();\n$Fname = $formdata['firstName'];\n$Lname = $formdata['lastName'];\n$email = $formdata['email'];\n\n$list = array (\narray( 'First Name:',$Fname),\narray( 'Last Name:', $Lname),\narray( 'Email:', $email),\n\n);\n// Save file path separately \n$file_path = site_url() . 'uploads/2020/08/sample.csv'; // check File permission for writing content\n$fp = fopen( $file_path , 'w');\n\nforeach ($list as $fields) {\nfputcsv($fp, $fields);\n}\nfclose($fp);\n//MAIL starts here \n$attachments = array( $file_path );\n$headers = 'From: name &lt;[email protected]&gt;' . &quot;\\r\\n&quot;;\n \nwp_mail($to, $subject, $message,$headers, $attachments);\n// You are done \n}\n</code></pre>\n" }, { "answer_id": 388788, "author": "JTjards", "author_id": 161741, "author_profile": "https://wordpress.stackexchange.com/users/161741", "pm_score": 1, "selected": false, "text": "<p>There are a few things omitted in the above solution, like defining the most params of wp_mail.\nAlso I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution.</p>\n<p>Here's my take:</p>\n<pre><code>add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 );\nfunction add_form_as_attachment( $contact_form, $abort, $submission ) {\n\n $form_id = $contact_form-&gt;id();\n\n //Check for selected form id and actual submission\n if ($form_id == 123 &amp;&amp; $submission){\n\n $posted_data = $submission-&gt;get_posted_data() ;\n // Check again for posted data\n if ( empty ($posted_data)){\n return; \n }\n\n //Get your form fields\n $firstname = $posted_data['your-name'];\n $lastname = $posted_data['your-lastname'];\n $email = $posted_data['your-email'];\n\n $list = array (\n array( 'First Name:',$firstname),\n array( 'Last Name:', $lastname),\n array( 'Email:', $email),\n\n );\n // Save file path separately \n $upload_dir = wp_upload_dir(); \n $file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example\n\n $fp = fopen( $file_path , 'w'); //overwrites file at each submission\n foreach ($list as $fields) {\n fputcsv($fp, $fields);\n }\n fclose($fp);\n\n // Modification of mail(1) start here\n $properties = $contact_form-&gt;get_properties();\n $properties['mail']['attachments'] = $file_path;\n $contact_form-&gt;set_properties($properties);\n\n return $contact_form;\n }//endif ID &amp;&amp; submission\n}\n</code></pre>\n" } ]
2020/08/12
[ "https://wordpress.stackexchange.com/questions/372878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/182729/" ]
I am trying to get latest from specific categories (3 posts), but the code does not seem working. Instead of displaying posts from the mentioned categories, it is displaying posts from the first category. Here is my code: ``` <?php do_action( 'hitmag_before_content' ); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <h1>Latest News</h1> <?php do_action( 'hitmag_before_blog_posts' ); ?> <?php $args = array( 'post_type' => 'post' , 'orderby' => 'date' , 'order' => 'DESC' , 'posts_per_page' => 3, 'category' => '30','33','1', 'paged' => get_query_var('paged'), 'post_parent' => $parent ); ?> <?php query_posts($args); ?> <?php if ( have_posts() ) : if ( is_home() && ! is_front_page() ) : ?> <header> <h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1> </header> <?php endif; $archive_content_layout = get_option( 'archive_content_layout', 'th-grid-2' ); echo '<div class="posts-wrap ' . esc_attr( $archive_content_layout ) . '">'; /* Start the Loop */ while ( have_posts() ) : the_post(); /* * Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ get_template_part( 'template-parts/content', get_post_format() ); endwhile; echo '</div><!-- .posts-wrap -->'; else : get_template_part( 'template-parts/content', 'none' ); endif; ?> <?php do_action( 'hitmag_after_blog_posts' ); ?> </main><!-- #main --> </div><!-- #primary --> ```
There are a few things omitted in the above solution, like defining the most params of wp\_mail. Also I didn't want to send yet another concurrent email, but instead attach the csv directly to the mail that wpcf7 sends. I think this is the cleaner solution. Here's my take: ``` add_filter( 'wpcf7_before_send_mail', 'add_form_as_attachment', 10, 3 ); function add_form_as_attachment( $contact_form, $abort, $submission ) { $form_id = $contact_form->id(); //Check for selected form id and actual submission if ($form_id == 123 && $submission){ $posted_data = $submission->get_posted_data() ; // Check again for posted data if ( empty ($posted_data)){ return; } //Get your form fields $firstname = $posted_data['your-name']; $lastname = $posted_data['your-lastname']; $email = $posted_data['your-email']; $list = array ( array( 'First Name:',$firstname), array( 'Last Name:', $lastname), array( 'Email:', $email), ); // Save file path separately $upload_dir = wp_upload_dir(); $file_path = $upload_dir['basedir'].'/yourtempfolder/sample.csv'; // check File permission for writing content and remember to protect this folder from the public with htaccess for example $fp = fopen( $file_path , 'w'); //overwrites file at each submission foreach ($list as $fields) { fputcsv($fp, $fields); } fclose($fp); // Modification of mail(1) start here $properties = $contact_form->get_properties(); $properties['mail']['attachments'] = $file_path; $contact_form->set_properties($properties); return $contact_form; }//endif ID && submission } ```
372,886
<p>If I used /wp-json/wc/v3/products I am getting all products, but what if I want to receive only price and quantity, I searched all we web and couldn't find it!</p>
[ { "answer_id": 372888, "author": "Sam", "author_id": 193035, "author_profile": "https://wordpress.stackexchange.com/users/193035", "pm_score": 1, "selected": false, "text": "<p>First of all, sorry for my bad english!</p>\n<p>In PHP, after your file_get_contents(home_url().'/wp-json/wc/v3/products'), use json_decode and get your informations like this:</p>\n<pre><code>&lt;?php\n $products = json_decode(file_get_contents(home_url().'/wp-json/wc/v3/products'));\n foreach($products as $product){\n\n echo $product-&gt;price;\n echo $product-&gt;regular_price;\n echo $product-&gt;sale_price;\n \n echo $product-&gt;stock_quantity;\n }\n?&gt;\n</code></pre>\n<p>You can put a look here for more informations: <a href=\"https://woocommerce.github.io/woocommerce-rest-api-docs/#products\" rel=\"nofollow noreferrer\">https://woocommerce.github.io/woocommerce-rest-api-docs/#products</a></p>\n<p>EDIT:\nIf you want stock the price and quantity only with the product, you can do this:</p>\n<pre><code>&lt;?php\n $products = json_decode(file_get_contents(home_url().'/wp-json/wc/v3/products'));\n \n $products_array = array();\n foreach($products as $product){\n \n $products_array[] = array(\n 'id' =&gt; $product-&gt;id,\n 'price' =&gt; $product-&gt;price,\n 'stock_qty' =&gt; $product-&gt;stock_quantity,\n );\n }\n?&gt;\n</code></pre>\n<p>use or return $products_array...</p>\n" }, { "answer_id": 390931, "author": "JohnVslk", "author_id": 208156, "author_profile": "https://wordpress.stackexchange.com/users/208156", "pm_score": 2, "selected": false, "text": "<p>Woocommerce rest API is an extension of WordPress rest API, so you should first check global parameters and specifically &quot;_fields&quot; in the <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/#_fields\" rel=\"nofollow noreferrer\">REST API Handbook of Wordpress.org</a>.</p>\n<p>I will give you an example of the data that you want, price and quantity, but also the id and the name of the products for the response to be more human friendly.</p>\n<pre><code>/wp-json/wc/v3/products?per_page=100&amp;_fields=id,name,regular_price,stock_quantity\n</code></pre>\n<blockquote>\n<p>The &quot;_fields&quot; attribute is used for every attribute you want to get.</p>\n<p>The &quot;per_page&quot; attribute with value of &quot;100&quot; is used to get 100\nproducts which is the max acceptable value of this attribute and if\nyou leave it empty the default is only &quot;10&quot;.</p>\n</blockquote>\n<p>Sorry for the 10 months later answer, but I hope that helped you and any other that is facing the same issue.</p>\n" } ]
2020/08/12
[ "https://wordpress.stackexchange.com/questions/372886", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/151546/" ]
If I used /wp-json/wc/v3/products I am getting all products, but what if I want to receive only price and quantity, I searched all we web and couldn't find it!
Woocommerce rest API is an extension of WordPress rest API, so you should first check global parameters and specifically "\_fields" in the [REST API Handbook of Wordpress.org](https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/#_fields). I will give you an example of the data that you want, price and quantity, but also the id and the name of the products for the response to be more human friendly. ``` /wp-json/wc/v3/products?per_page=100&_fields=id,name,regular_price,stock_quantity ``` > > The "\_fields" attribute is used for every attribute you want to get. > > > The "per\_page" attribute with value of "100" is used to get 100 > products which is the max acceptable value of this attribute and if > you leave it empty the default is only "10". > > > Sorry for the 10 months later answer, but I hope that helped you and any other that is facing the same issue.
372,895
<p>site been hacked, and all posts been injected a line of js code under the content!</p> <pre><code>&lt;script src='https://js.xxxxxxx.ga/stat.js?n=ns1' type='text/javascript'&gt;&lt;/script&gt; </code></pre> <p>I have found the malware file in the root directory, which inject the JS code with the command:</p> <pre><code>$q = &quot;SELECT TABLE_SCHEMA,TABLE_NAME FROM information_schema.TABLES WHERE `TABLE_NAME` LIKE '%post%'&quot;; $result = $conn-&gt;query($q); if ($result-&gt;num_rows &gt; 0) { while($row = $result-&gt;fetch_assoc()) { $q2 = &quot;SELECT post_content FROM &quot; . $row[&quot;TABLE_SCHEMA&quot;]. &quot;.&quot; . $row[&quot;TABLE_NAME&quot;].&quot; LIMIT 1 &quot;; $result2 = $conn-&gt;query($q2); if ($result2-&gt;num_rows &gt; 0) { while($row2 = $result2-&gt;fetch_assoc()) { $val = $row2['post_content']; if(strpos($val, &quot;js.donatelloflowfirstly.ga&quot;) === false){ if(strpos($val, &quot;js.donatelloflowfirstly.ga&quot;) === false){ $q3 = &quot;UPDATE &quot; . $row[&quot;TABLE_SCHEMA&quot;]. &quot;.&quot; . $row[&quot;TABLE_NAME&quot;].&quot; set post_content = CONCAT(post_content,\&quot;&lt;script src='https://js.donatelloflowfirstly.ga/stat.js?n=ns1' type='text/javascript'&gt;&lt;/script&gt;\&quot;) WHERE post_content NOT LIKE '%js.donatelloflowfirstly.ga%'&quot;; $conn-&gt;query($q3); echo &quot;sql:&quot; . $row[&quot;TABLE_SCHEMA&quot;]. &quot;.&quot; . $row[&quot;TABLE_NAME&quot;]; } else { } } } } else { } } } else { } $conn-&gt;close(); </code></pre> <p>Someone please help me with a MYSQL command so I can delet this code from the PHPmyadmin.</p>
[ { "answer_id": 372888, "author": "Sam", "author_id": 193035, "author_profile": "https://wordpress.stackexchange.com/users/193035", "pm_score": 1, "selected": false, "text": "<p>First of all, sorry for my bad english!</p>\n<p>In PHP, after your file_get_contents(home_url().'/wp-json/wc/v3/products'), use json_decode and get your informations like this:</p>\n<pre><code>&lt;?php\n $products = json_decode(file_get_contents(home_url().'/wp-json/wc/v3/products'));\n foreach($products as $product){\n\n echo $product-&gt;price;\n echo $product-&gt;regular_price;\n echo $product-&gt;sale_price;\n \n echo $product-&gt;stock_quantity;\n }\n?&gt;\n</code></pre>\n<p>You can put a look here for more informations: <a href=\"https://woocommerce.github.io/woocommerce-rest-api-docs/#products\" rel=\"nofollow noreferrer\">https://woocommerce.github.io/woocommerce-rest-api-docs/#products</a></p>\n<p>EDIT:\nIf you want stock the price and quantity only with the product, you can do this:</p>\n<pre><code>&lt;?php\n $products = json_decode(file_get_contents(home_url().'/wp-json/wc/v3/products'));\n \n $products_array = array();\n foreach($products as $product){\n \n $products_array[] = array(\n 'id' =&gt; $product-&gt;id,\n 'price' =&gt; $product-&gt;price,\n 'stock_qty' =&gt; $product-&gt;stock_quantity,\n );\n }\n?&gt;\n</code></pre>\n<p>use or return $products_array...</p>\n" }, { "answer_id": 390931, "author": "JohnVslk", "author_id": 208156, "author_profile": "https://wordpress.stackexchange.com/users/208156", "pm_score": 2, "selected": false, "text": "<p>Woocommerce rest API is an extension of WordPress rest API, so you should first check global parameters and specifically &quot;_fields&quot; in the <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/#_fields\" rel=\"nofollow noreferrer\">REST API Handbook of Wordpress.org</a>.</p>\n<p>I will give you an example of the data that you want, price and quantity, but also the id and the name of the products for the response to be more human friendly.</p>\n<pre><code>/wp-json/wc/v3/products?per_page=100&amp;_fields=id,name,regular_price,stock_quantity\n</code></pre>\n<blockquote>\n<p>The &quot;_fields&quot; attribute is used for every attribute you want to get.</p>\n<p>The &quot;per_page&quot; attribute with value of &quot;100&quot; is used to get 100\nproducts which is the max acceptable value of this attribute and if\nyou leave it empty the default is only &quot;10&quot;.</p>\n</blockquote>\n<p>Sorry for the 10 months later answer, but I hope that helped you and any other that is facing the same issue.</p>\n" } ]
2020/08/12
[ "https://wordpress.stackexchange.com/questions/372895", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193038/" ]
site been hacked, and all posts been injected a line of js code under the content! ``` <script src='https://js.xxxxxxx.ga/stat.js?n=ns1' type='text/javascript'></script> ``` I have found the malware file in the root directory, which inject the JS code with the command: ``` $q = "SELECT TABLE_SCHEMA,TABLE_NAME FROM information_schema.TABLES WHERE `TABLE_NAME` LIKE '%post%'"; $result = $conn->query($q); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $q2 = "SELECT post_content FROM " . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]." LIMIT 1 "; $result2 = $conn->query($q2); if ($result2->num_rows > 0) { while($row2 = $result2->fetch_assoc()) { $val = $row2['post_content']; if(strpos($val, "js.donatelloflowfirstly.ga") === false){ if(strpos($val, "js.donatelloflowfirstly.ga") === false){ $q3 = "UPDATE " . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]." set post_content = CONCAT(post_content,\"<script src='https://js.donatelloflowfirstly.ga/stat.js?n=ns1' type='text/javascript'></script>\") WHERE post_content NOT LIKE '%js.donatelloflowfirstly.ga%'"; $conn->query($q3); echo "sql:" . $row["TABLE_SCHEMA"]. "." . $row["TABLE_NAME"]; } else { } } } } else { } } } else { } $conn->close(); ``` Someone please help me with a MYSQL command so I can delet this code from the PHPmyadmin.
Woocommerce rest API is an extension of WordPress rest API, so you should first check global parameters and specifically "\_fields" in the [REST API Handbook of Wordpress.org](https://developer.wordpress.org/rest-api/using-the-rest-api/global-parameters/#_fields). I will give you an example of the data that you want, price and quantity, but also the id and the name of the products for the response to be more human friendly. ``` /wp-json/wc/v3/products?per_page=100&_fields=id,name,regular_price,stock_quantity ``` > > The "\_fields" attribute is used for every attribute you want to get. > > > The "per\_page" attribute with value of "100" is used to get 100 > products which is the max acceptable value of this attribute and if > you leave it empty the default is only "10". > > > Sorry for the 10 months later answer, but I hope that helped you and any other that is facing the same issue.
372,897
<p>I recently updated a WordPress instance from 5.4 to 5.5 to end up with an annoying margin-top in the admin area, above the menu directly.</p> <p><a href="https://i.stack.imgur.com/bGHZk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bGHZk.png" alt="enter image description here" /></a></p> <p>I deactivated all plugins, switched themes, did some inspection, and I ended up with some findings.</p> <p>The CSS class causing the margin-top is <code>.php-error</code>, which is appended to <code>#adminmenuwrap</code> when a php error is supposed to be displayed.</p> <pre><code>/* in load-styles.php */ .php-error #adminmenuback, .php-error #adminmenuwrap { margin-top: 2em; } /* the menu wrapper */ &lt;div id=&quot;adminmenuwrap&quot;&gt;&lt;/div&gt; /* the php script in /wp-admin/admin-header.php line 201 */ // Print a CSS class to make PHP errors visible. if ( error_get_last() &amp;&amp; WP_DEBUG &amp;&amp; WP_DEBUG_DISPLAY &amp;&amp; ini_get( 'display_errors' ) ) { $admin_body_class .= ' php-error'; } /* print_r(error_get_last()) outputs */ Array ( [type] =&gt; 8 [message] =&gt; unserialize(): Error at offset 11857 of 11895 bytes [file] =&gt; .../wp-includes/functions.php [line] =&gt; 624 ) /** * Unserialize data only if it was serialized. * * @since 2.0.0 * * @param string $data Data that might be unserialized. * @return mixed Unserialized data can be any type. */ function maybe_unserialize( $data ) { if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in. return @unserialize( trim( $data ) ); } return $data; } </code></pre> <p>It is perfectly normal that <code>WP_DEBUG &amp;&amp; WP_DEBUG_DISPLAY &amp;&amp; ini_get( 'display_errors' )</code> be true (because I'm actually debugging), but the problem is that no php error is being displayed.</p> <p>This instance (with bug) is running on an online hosted server. But I also have the exact same copy of this instance running on localhost, except it does not have this bug.</p> <p>Did anyone encounter this scenario? What do you suggest?</p> <p><strong>------- EDIT (Fix) --------</strong></p> <p>The following manipulation did solve the problem but I'm still not sure about the origin or &quot;real&quot; cause behind the bug. This been said, it was a calculation error in serialized data, more precisely, in my case it came from the contents of Privacy Policy page sample (tutorial by WordPress).</p> <p>Here's how I went about it:</p> <pre><code>// Edit the function in /wp-includes/functions.php on line 624 and include some // error logging. // DO NOT FORGET TO REVERT BACK TO THE ORIGINAL CODE ONCE DONE DEBUGGING! /** * Unserialize data only if it was serialized. * * @since 2.0.0 * * @param string $data Data that might be unserialized. * @return mixed Unserialized data can be any type. */ function maybe_unserialize( $data ) { if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in. error_log( &quot;DATA DEBUGGING START ---------- \r&quot;); error_log( &quot;TRIMED: &quot;); error_log( trim( $data ) ); error_log( &quot;UNSERIALIZED: &quot;); error_log( print_r(unserialize( trim( $data ) ), true)); error_log( &quot;DATA DEBUGGING END ---------- \r\n&quot;); return unserialize( trim( $data ) ); } return $data; } </code></pre> <p>This will log all serialized and unserialized values in your debug.log or error.log depending which method you are using. I'm using the default WordPress <code>define( 'WP_DEBUG_LOG', true );</code> in w-config.php, which logs errors in the file debug.log under /wp-content/.</p> <p>Doing this allowed me to detect the exact row in database causing the problem. The problem comes from a wrong count calculation.</p> <pre><code>a:3:{s:11:&quot;plugin_name&quot;;s:9:&quot;WordPress&quot;;s:11:&quot;policy_text&quot;;s:11789:&quot;..... </code></pre> <p>I did a characters/bytes count of the contents of that key and it turned out to be 11799 instead of 11789.</p> <p>The value in <code>s:11789</code> must be <code>s:11799</code> in my case. So I changed it in the database and everything worked fine. I also edited the page in the Editor and saved it then rechecked and everything still work fine.</p> <p>This fixed the issue but I guess something went wrong at some point. Most probably when I imported the local database to a different instance.</p> <p>I hope this helps!</p>
[ { "answer_id": 373027, "author": "RJR", "author_id": 193141, "author_profile": "https://wordpress.stackexchange.com/users/193141", "pm_score": 3, "selected": false, "text": "<p>I ran into that issue too, and it turns out that it was because there actually was an error that wasn't displaying. Once I fixed that underlying error, the top margin problem went away.</p>\n<p>This is in wp-admin/admin-header.php:</p>\n<pre><code>// Print a CSS class to make PHP errors visible.\nif ( error_get_last() &amp;&amp; WP_DEBUG &amp;&amp; WP_DEBUG_DISPLAY &amp;&amp; ini_get( 'display_errors' ) ) {\n $admin_body_class .= ' php-error';\n}\n</code></pre>\n<p>So I temporarily added a display of that error_get_last() output to one of my plugins:</p>\n<pre><code>$debug = print_r(error_get_last(),true);\necho '&lt;p&gt;php-error: '.esc_attr($debug).'&lt;/p&gt;';\n</code></pre>\n<p>That showed me where the underlying error was. I fixed it, and problem solved!</p>\n" }, { "answer_id": 373280, "author": "squarecandy", "author_id": 41488, "author_profile": "https://wordpress.stackexchange.com/users/41488", "pm_score": 0, "selected": false, "text": "<p>You can also set <code>WP_DEBUG</code> to <code>false</code> in your <code>wp-config.php</code> file and this will no longer show (the .php-error class will no longer be generated). This is how you should have it set on any production site anyways.</p>\n<p>If debug mode is on and you have errors printing to the screen sometimes the first 30-40 characters sometimes get covered by fixed position left admin menu, so I think this is a newly added &quot;solution&quot; for that issue.</p>\n<p>But, yeah as Robert said - the best solution is to fix the error. But sometimes you can't do that if it's just a notice or warning from a 3rd party plugin or theme - so just make sure debug is off in production and you should be fine.</p>\n" }, { "answer_id": 373379, "author": "Braza", "author_id": 191979, "author_profile": "https://wordpress.stackexchange.com/users/191979", "pm_score": 0, "selected": false, "text": "<p><strong>This is a fix, not a solution</strong></p>\n<p>The following manipulation did solve the problem but I'm still not sure about the origin or &quot;real&quot; cause behind the bug. This been said, it was a calculation error in serialized data, more precisely, in my case it came from the contents of Privacy Policy page sample (tutorial by WordPress).</p>\n<p>Here's how I went about it:</p>\n<pre><code>// Edit the function in /wp-includes/functions.php on line 624 and include some \n// error logging. \n\n/**\n * Unserialize data only if it was serialized.\n *\n * @since 2.0.0\n *\n * @param string $data Data that might be unserialized.\n * @return mixed Unserialized data can be any type.\n */\nfunction maybe_unserialize( $data ) {\n if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't \nserialized going in.\n error_log( &quot;DATA DEBUGGING START ---------- \\r&quot;);\n error_log( &quot;TRIMED: &quot;);\n error_log( trim( $data ) );\n error_log( &quot;UNSERIALIZED: &quot;);\n error_log( print_r(unserialize( trim( $data ) ), true));\n error_log( &quot;DATA DEBUGGING END ---------- \\r\\n&quot;);\n return unserialize( trim( $data ) );\n }\n\n return $data;\n}\n\n</code></pre>\n<p><strong>DO NOT FORGET TO REVERT BACK TO THE ORIGINAL CODE ONCE DONE DEBUGGING!</strong></p>\n<p>This will log all serialized and unserialized values in your debug.log or error.log depending which method you are using. I'm using the default WordPress <code>define( 'WP_DEBUG_LOG', true );</code> in w-config.php, which logs errors in the file debug.log under /wp-content/.</p>\n<p>Doing this will help detecting the exact row in database which is causing the problem.\nThe problem here comes from a wrong count calculation.</p>\n<pre><code>a:3:{s:11:&quot;plugin_name&quot;;s:9:&quot;WordPress&quot;;s:11:&quot;policy_text&quot;;s:11789:&quot;.....\n</code></pre>\n<p>I did a characters/bytes count of the contents of that key and it turned out to be 11799 instead of 11789.</p>\n<p>The value in <code>s:11789</code> must be <code>s:11799</code> in my case. So I changed it in the database and everything worked fine. I also edited the page in the Editor and saved it then rechecked and everything still work fine.</p>\n<p>This fixed the issue but I guess something went wrong at some point. Most probably when I imported the local database to a different instance.</p>\n<p>I hope this helps!</p>\n" }, { "answer_id": 374297, "author": "Tom Groot", "author_id": 118863, "author_profile": "https://wordpress.stackexchange.com/users/118863", "pm_score": 0, "selected": false, "text": "<p>To elaborate more on the answer of Braza. If there is a length mismatch within one of your database values, you can <strong>track it down</strong> by doing a regex search and checking if the string length matches.</p>\n<p>I've extended Braza's code to make this easier:</p>\n<pre><code>/**\n * Unserialize data only if it was serialized.\n *\n * @since 2.0.0\n *\n * @param string $data Data that might be unserialized.\n * @return mixed Unserialized data can be any type.\n */\nfunction maybe_unserialize( $data ) {\n if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in.\n preg_match_all('/s:([0-9]*):&quot;/', $data, $matches, PREG_OFFSET_CAPTURE);\n foreach ($matches[1] as $match) {\n $string = substr($data, (intval($match[1]) + strlen(strval($match[0])) + 1), (intval($match[0]) + 2));\n if (substr($string, -1) != '&quot;') {\n error_log('LENGTH MISMATCH!!! \\r');\n error_log($string);\n error_log('CHANGE THIS VALUE: \\r');\n error_log($data);\n }\n }\n return unserialize( trim( $data ) );\n }\n\n return $data;\n}\n</code></pre>\n" } ]
2020/08/12
[ "https://wordpress.stackexchange.com/questions/372897", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/191979/" ]
I recently updated a WordPress instance from 5.4 to 5.5 to end up with an annoying margin-top in the admin area, above the menu directly. [![enter image description here](https://i.stack.imgur.com/bGHZk.png)](https://i.stack.imgur.com/bGHZk.png) I deactivated all plugins, switched themes, did some inspection, and I ended up with some findings. The CSS class causing the margin-top is `.php-error`, which is appended to `#adminmenuwrap` when a php error is supposed to be displayed. ``` /* in load-styles.php */ .php-error #adminmenuback, .php-error #adminmenuwrap { margin-top: 2em; } /* the menu wrapper */ <div id="adminmenuwrap"></div> /* the php script in /wp-admin/admin-header.php line 201 */ // Print a CSS class to make PHP errors visible. if ( error_get_last() && WP_DEBUG && WP_DEBUG_DISPLAY && ini_get( 'display_errors' ) ) { $admin_body_class .= ' php-error'; } /* print_r(error_get_last()) outputs */ Array ( [type] => 8 [message] => unserialize(): Error at offset 11857 of 11895 bytes [file] => .../wp-includes/functions.php [line] => 624 ) /** * Unserialize data only if it was serialized. * * @since 2.0.0 * * @param string $data Data that might be unserialized. * @return mixed Unserialized data can be any type. */ function maybe_unserialize( $data ) { if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in. return @unserialize( trim( $data ) ); } return $data; } ``` It is perfectly normal that `WP_DEBUG && WP_DEBUG_DISPLAY && ini_get( 'display_errors' )` be true (because I'm actually debugging), but the problem is that no php error is being displayed. This instance (with bug) is running on an online hosted server. But I also have the exact same copy of this instance running on localhost, except it does not have this bug. Did anyone encounter this scenario? What do you suggest? **------- EDIT (Fix) --------** The following manipulation did solve the problem but I'm still not sure about the origin or "real" cause behind the bug. This been said, it was a calculation error in serialized data, more precisely, in my case it came from the contents of Privacy Policy page sample (tutorial by WordPress). Here's how I went about it: ``` // Edit the function in /wp-includes/functions.php on line 624 and include some // error logging. // DO NOT FORGET TO REVERT BACK TO THE ORIGINAL CODE ONCE DONE DEBUGGING! /** * Unserialize data only if it was serialized. * * @since 2.0.0 * * @param string $data Data that might be unserialized. * @return mixed Unserialized data can be any type. */ function maybe_unserialize( $data ) { if ( is_serialized( $data ) ) { // Don't attempt to unserialize data that wasn't serialized going in. error_log( "DATA DEBUGGING START ---------- \r"); error_log( "TRIMED: "); error_log( trim( $data ) ); error_log( "UNSERIALIZED: "); error_log( print_r(unserialize( trim( $data ) ), true)); error_log( "DATA DEBUGGING END ---------- \r\n"); return unserialize( trim( $data ) ); } return $data; } ``` This will log all serialized and unserialized values in your debug.log or error.log depending which method you are using. I'm using the default WordPress `define( 'WP_DEBUG_LOG', true );` in w-config.php, which logs errors in the file debug.log under /wp-content/. Doing this allowed me to detect the exact row in database causing the problem. The problem comes from a wrong count calculation. ``` a:3:{s:11:"plugin_name";s:9:"WordPress";s:11:"policy_text";s:11789:"..... ``` I did a characters/bytes count of the contents of that key and it turned out to be 11799 instead of 11789. The value in `s:11789` must be `s:11799` in my case. So I changed it in the database and everything worked fine. I also edited the page in the Editor and saved it then rechecked and everything still work fine. This fixed the issue but I guess something went wrong at some point. Most probably when I imported the local database to a different instance. I hope this helps!
I ran into that issue too, and it turns out that it was because there actually was an error that wasn't displaying. Once I fixed that underlying error, the top margin problem went away. This is in wp-admin/admin-header.php: ``` // Print a CSS class to make PHP errors visible. if ( error_get_last() && WP_DEBUG && WP_DEBUG_DISPLAY && ini_get( 'display_errors' ) ) { $admin_body_class .= ' php-error'; } ``` So I temporarily added a display of that error\_get\_last() output to one of my plugins: ``` $debug = print_r(error_get_last(),true); echo '<p>php-error: '.esc_attr($debug).'</p>'; ``` That showed me where the underlying error was. I fixed it, and problem solved!
372,941
<p>On a fresh WordPress install in Linux distributions, <code>wp-config-sample.php</code> contains Carriage Return control characters that are not found in any other .php file in the distribution.</p> <p>Running</p> <pre><code>egrep -l $'\r'\$ *.php </code></pre> <p>in WP's base dir, will return only <code>wp-config-sample.php</code></p> <hr /> <p>I am not worried about eliminating the control character, nor am I worried that it interferes with install operations (it doesn’t).</p> <p>I’d just like to find out if there’s a reason why <code>wp-config-sample.php</code> is the only file with this anomaly.</p> <hr /> <p><strong>WP versions</strong><br /> Issue <a href="https://wordpress.org/support/topic/control-character-m-found-in-wp-config-sample-php/" rel="nofollow noreferrer">was reported</a> in version 4.6.15. It is still present in the latest version 5.5</p> <p><strong>Environments</strong><br /> This behavior has been seen in</p> <ul> <li>Debian 10 CLI-only</li> <li>Ubuntu 18.04.4 LTS</li> <li>Ubuntu 12.04.5 LTS</li> <li>Ubuntu 20.04.1 LTS</li> </ul> <p><strong>WordPress distributions</strong><br /> Install files have been downloaded either</p> <ul> <li>as .zip file (e.g. wordpress-5.5.zip) or</li> <li>as .tar.gz file (e.g. wordpress-5.5.tar.gz)</li> </ul> <p><strong>Downloads methods</strong></p> <ul> <li>via wget: <code>wget https://wordpress.org/latest.zip</code></li> <li>via WP CLI: <code>wp core download</code></li> <li>via a Web browser (in GUI environments)</li> </ul> <p>Example screenshot from Ubuntu 12.04.5 LTS</p> <p><a href="https://i.stack.imgur.com/quDcd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/quDcd.png" alt="Ubuntu 12.04.5 tar.gz version" /></a></p> <hr /> <p>A <a href="https://www.google.co.uk/search?q=wp-config-sample.php%20Carriage%20Return%20control%20character%20(%5EM)" rel="nofollow noreferrer">Google search</a> doesn't provide any explanation. I have found only a <a href="https://wordpress.org/support/topic/control-character-m-found-in-wp-config-sample-php/" rel="nofollow noreferrer">similar question</a> in the WP support forum but the reply given is &quot;don't worry about it&quot; and does not provide an explanation for it.</p>
[ { "answer_id": 373033, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": false, "text": "<p>Unix and Unix-like operating systems (like Linux) use different line endings in their text files.</p>\n<blockquote>\n<p>The format of Windows and Unix text files differs slightly. In Windows, lines end with both the line feed and carriage return ASCII characters, but Unix uses only a line feed. As a consequence, some Windows applications will not show the line breaks in Unix-format files. Likewise, Unix programs may display the carriage returns in Windows text files with Ctrl-m (^M) characters at the end of each line.</p>\n</blockquote>\n<p>—From <a href=\"https://kb.iu.edu/d/acux\" rel=\"nofollow noreferrer\">Convert between Unix and Windows text files</a></p>\n<p>Presumably you've copied a file that was created on Windows to a Linux machine, and so you're seeing the Windows line endings when you edit the file on Linux.</p>\n<p><a href=\"https://wordpress.org/support/topic/control-character-m-found-in-wp-config-sample-php/\" rel=\"nofollow noreferrer\">The solution provided in your wordpress.org support post</a> -- use <code>dos2unix</code> -- will clean it up.</p>\n<p>I can't say precisely why your question was downvoted, as I'm not the downvoter, but if I had to guess I'd say it was because this is a Windows / Linux question, not a specifically WordPress-related question. (Yes, it's a WordPress file, but it's not really related to WordPress development at all.)</p>\n" }, { "answer_id": 373498, "author": "Dave White", "author_id": 175096, "author_profile": "https://wordpress.stackexchange.com/users/175096", "pm_score": 1, "selected": true, "text": "<p>From Wordpress support:</p>\n<blockquote>\n<p>It’s for formatting on legacy DOS based systems. Some DOS and Windows based editors will not handle the file correctly without those additional <code>^M</code> carriage return character. A UNIX based system will work with or without them and that’s why they don’t matter.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Newline\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Newline</a></p>\n<p>This is how a portion of that file should edit.</p>\n<pre><code>// ** MySQL settings - You can get this info from your web host ** //\n/** The name of the database for WordPress */\ndefine( 'DB_NAME', 'database_name_here' );\n/** MySQL database username */\ndefine( 'DB_USER', 'username_here' );\n/** MySQL database password */\ndefine( 'DB_PASSWORD', 'password_here' );\n/** MySQL hostname */\ndefine( 'DB_HOST', 'localhost' );\n</code></pre>\n<p>Which is readable.</p>\n<p>If a new user used the Windows notepad editor then the file would may look like this especially on older versions of Windows.</p>\n<pre><code>// ** MySQL settings - You can get this info from your web host ** ///** The name of the database for WordPress */define( 'DB_NAME', 'database_name_here' );/** MySQL database username */define( 'DB_USER', 'username_here' );/** MySQL database password */define( 'DB_PASSWORD', 'password_here' );/** MySQL hostname */define( 'DB_HOST', 'localhost' );\n</code></pre>\n<p>Which is one line of mess. It would still work as a PHP file because the newline is less important than the <code>;</code> in the file. The additional <code>^M</code>s will be ignored and for those other editor applications the user will see something they can both parse and edit.</p>\n</blockquote>\n" } ]
2020/08/13
[ "https://wordpress.stackexchange.com/questions/372941", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175096/" ]
On a fresh WordPress install in Linux distributions, `wp-config-sample.php` contains Carriage Return control characters that are not found in any other .php file in the distribution. Running ``` egrep -l $'\r'\$ *.php ``` in WP's base dir, will return only `wp-config-sample.php` --- I am not worried about eliminating the control character, nor am I worried that it interferes with install operations (it doesn’t). I’d just like to find out if there’s a reason why `wp-config-sample.php` is the only file with this anomaly. --- **WP versions** Issue [was reported](https://wordpress.org/support/topic/control-character-m-found-in-wp-config-sample-php/) in version 4.6.15. It is still present in the latest version 5.5 **Environments** This behavior has been seen in * Debian 10 CLI-only * Ubuntu 18.04.4 LTS * Ubuntu 12.04.5 LTS * Ubuntu 20.04.1 LTS **WordPress distributions** Install files have been downloaded either * as .zip file (e.g. wordpress-5.5.zip) or * as .tar.gz file (e.g. wordpress-5.5.tar.gz) **Downloads methods** * via wget: `wget https://wordpress.org/latest.zip` * via WP CLI: `wp core download` * via a Web browser (in GUI environments) Example screenshot from Ubuntu 12.04.5 LTS [![Ubuntu 12.04.5 tar.gz version](https://i.stack.imgur.com/quDcd.png)](https://i.stack.imgur.com/quDcd.png) --- A [Google search](https://www.google.co.uk/search?q=wp-config-sample.php%20Carriage%20Return%20control%20character%20(%5EM)) doesn't provide any explanation. I have found only a [similar question](https://wordpress.org/support/topic/control-character-m-found-in-wp-config-sample-php/) in the WP support forum but the reply given is "don't worry about it" and does not provide an explanation for it.
From Wordpress support: > > It’s for formatting on legacy DOS based systems. Some DOS and Windows based editors will not handle the file correctly without those additional `^M` carriage return character. A UNIX based system will work with or without them and that’s why they don’t matter. > > > <https://en.wikipedia.org/wiki/Newline> > > > This is how a portion of that file should edit. > > > > ``` > // ** MySQL settings - You can get this info from your web host ** // > /** The name of the database for WordPress */ > define( 'DB_NAME', 'database_name_here' ); > /** MySQL database username */ > define( 'DB_USER', 'username_here' ); > /** MySQL database password */ > define( 'DB_PASSWORD', 'password_here' ); > /** MySQL hostname */ > define( 'DB_HOST', 'localhost' ); > > ``` > > Which is readable. > > > If a new user used the Windows notepad editor then the file would may look like this especially on older versions of Windows. > > > > ``` > // ** MySQL settings - You can get this info from your web host ** ///** The name of the database for WordPress */define( 'DB_NAME', 'database_name_here' );/** MySQL database username */define( 'DB_USER', 'username_here' );/** MySQL database password */define( 'DB_PASSWORD', 'password_here' );/** MySQL hostname */define( 'DB_HOST', 'localhost' ); > > ``` > > Which is one line of mess. It would still work as a PHP file because the newline is less important than the `;` in the file. The additional `^M`s will be ignored and for those other editor applications the user will see something they can both parse and edit. > > >
372,950
<p>I'm trying to inject some data into blocks via PHP but am running into trouble with parse_blocks/serialize_blocks breaking my content</p> <p>I'm using the default 2020 theme and have no plugins installed</p> <pre><code>add_action('wp', function() { $oPost = get_post(119); printf(&quot;&lt;h1&gt;Post Content&lt;/h1&gt;&lt;p&gt;%s&lt;/p&gt;&quot;, var_dump($oPost-&gt;post_content)); $aBlocks = parse_blocks($oPost-&gt;post_content); printf(&quot;&lt;h1&gt;Parsed Blocks&lt;/h1&gt;&lt;pre&gt;%s&lt;/pre&gt;&quot;, print_r($aBlocks, true)); $sSerialisedBlocks = serialize_blocks($aBlocks); printf(&quot;&lt;h1&gt;Serialised Blocks&lt;/h1&gt;&lt;p&gt;%s&lt;/p&gt;&quot;, var_dump($sSerialisedBlocks)); }, PHP_INT_MAX); </code></pre> <p>The first print (just outputting the post content) contains this text...</p> <p><code>&lt;h3&gt;What types of accommodation are available in xxxx?&lt;\/h3&gt;</code></p> <p>The second (after parsing into blocks) contains this...</p> <p><code>&lt;h3&gt;What types of accommodation are available in xxxx?&lt;/h3&gt;</code></p> <p>But after re-serialising the blocks I get this...</p> <p><code>\u003ch3\u003eWhat types of accommodation are available in xxxx?\u003c\/h3\u003e</code></p> <p>Could someone tell me what I'm doing wrong?</p> <hr /> <p><strong>EDIT</strong></p> <p>Ok so I followed the source code for serialize_blocks and it does seem like this is intentional with serialize_block_attributes explicitly converting some characters</p> <p>My question is why then are these characters showing up in the WYSIWYG instead of being correctly converted back?</p>
[ { "answer_id": 373870, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>This happens in <code>serialize_block_attributes</code>, the docblock explains why:</p>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n...\n * The serialized result is a JSON-encoded string, with unicode escape sequence\n * substitution for characters which might otherwise interfere with embedding\n * the result in an HTML comment.\n...\n */\n</code></pre>\n<p>So this is done as an encoding measure to avoid attributes accidentally closing a HTML comment and breaking the format of the document.</p>\n<p>Without this, a HTML comment inside a block attribute would break the block and the rest of the content afterwards.</p>\n<h2>But How Do I Stop The Mangling?!!!</h2>\n<p><strong>No, it isn't mangled.</strong> It's just encoding certain characters by replacing them with unicode escaped versions to prevent breakage.</p>\n<h3>Proof 1</h3>\n<p>Lets take the original code block from the question, and add the following fixes:</p>\n<ul>\n<li>Wrap all in <code>&lt;pre&gt;</code> tags</li>\n<li>Use <code>esc_html</code> so we can see the tags properly</li>\n<li>Fix the <code>printf</code> by removing <code>var_dump</code> and using <code>var_export</code> with the second parameter so it returns rather than outputs</li>\n<li>Add a final test case where we re-parse and re-serialize 10 times to compare the final result with the original</li>\n</ul>\n<pre class=\"lang-php prettyprint-override\"><code>function reparse_reserialize( string $content, int $loops = 10 ) : string {\n $final_content = $content;\n for ($x = 0; $x &lt;= $loops; $x++) {\n $blocks = parse_blocks( $final_content );\n $final_content = serialize_blocks( $blocks );\n }\n return $final_content;\n}\n\nadd_action(\n 'wp',\n function() {\n $p = get_post( 1 );\n\n echo '&lt;p&gt;Original content:&lt;/p&gt;';\n echo '&lt;pre&gt;' . esc_html( var_export( $p-&gt;post_content, true ) ) . '&lt;/pre&gt;';\n\n $final = reparse_reserialize( $p-&gt;post_content );\n\n echo '&lt;p&gt;10 parse and serialize loops later:&lt;/p&gt;';\n echo '&lt;pre&gt;' . esc_html( var_export( $final, true ) ) . '&lt;/pre&gt;';\n echo '&lt;hr/&gt;';\n },\n PHP_INT_MAX\n);\n</code></pre>\n<p>Running that, we see that the content survived the process of being parsed and re-serialized 10 times. If mangling was occuring we would see progressively greater mangling occur</p>\n<h3>Proof 2</h3>\n<p>If we take the mangled markup:</p>\n<pre><code>\\u003ch3\\u003eWhat types of accommodation are available in xxxx?\\u003c\\/h3\\u003e\n</code></pre>\n<p>Turn it into a JSON string, then decode it:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$json = '&quot;\\u003ch3\\u003eWhat types of accommodation are available in xxxx?\\u003c\\/h3\\u003e&quot;';\necho '&lt;pre&gt;' . esc_html( json_decode( $json ) ) . '&lt;/pre&gt;';\n</code></pre>\n<p>We get the original HTML:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;h3&gt;What types of accommodation are available in xxxx?&lt;/h3&gt;\n</code></pre>\n<p>So no mangling has taken place.</p>\n<h2>Summary</h2>\n<p><strong>There is no mangling or corruption.</strong> It's just encoding the <code>&lt;</code> and <code>&gt;</code> to prevent breakage. JSON processors handle the unicode escape characters just fine.</p>\n<p>If you are seeing these encoded characters in the block editor, then that is a bug, either in the block, or the ACF plugin. You should report it as such</p>\n" }, { "answer_id": 410590, "author": "Sam Tyurenkov", "author_id": 124592, "author_profile": "https://wordpress.stackexchange.com/users/124592", "pm_score": 0, "selected": false, "text": "<p>Found this solution in Wordpress documentation user comments:</p>\n<p><a href=\"https://i.stack.imgur.com/Npasg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Npasg.png\" alt=\"wp_slash()\" /></a></p>\n<p>It worked in my case, without it the encoding was loosing the slashes when saving to database.</p>\n" } ]
2020/08/13
[ "https://wordpress.stackexchange.com/questions/372950", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140806/" ]
I'm trying to inject some data into blocks via PHP but am running into trouble with parse\_blocks/serialize\_blocks breaking my content I'm using the default 2020 theme and have no plugins installed ``` add_action('wp', function() { $oPost = get_post(119); printf("<h1>Post Content</h1><p>%s</p>", var_dump($oPost->post_content)); $aBlocks = parse_blocks($oPost->post_content); printf("<h1>Parsed Blocks</h1><pre>%s</pre>", print_r($aBlocks, true)); $sSerialisedBlocks = serialize_blocks($aBlocks); printf("<h1>Serialised Blocks</h1><p>%s</p>", var_dump($sSerialisedBlocks)); }, PHP_INT_MAX); ``` The first print (just outputting the post content) contains this text... `<h3>What types of accommodation are available in xxxx?<\/h3>` The second (after parsing into blocks) contains this... `<h3>What types of accommodation are available in xxxx?</h3>` But after re-serialising the blocks I get this... `\u003ch3\u003eWhat types of accommodation are available in xxxx?\u003c\/h3\u003e` Could someone tell me what I'm doing wrong? --- **EDIT** Ok so I followed the source code for serialize\_blocks and it does seem like this is intentional with serialize\_block\_attributes explicitly converting some characters My question is why then are these characters showing up in the WYSIWYG instead of being correctly converted back?
This happens in `serialize_block_attributes`, the docblock explains why: ```php /** ... * The serialized result is a JSON-encoded string, with unicode escape sequence * substitution for characters which might otherwise interfere with embedding * the result in an HTML comment. ... */ ``` So this is done as an encoding measure to avoid attributes accidentally closing a HTML comment and breaking the format of the document. Without this, a HTML comment inside a block attribute would break the block and the rest of the content afterwards. But How Do I Stop The Mangling?!!! ---------------------------------- **No, it isn't mangled.** It's just encoding certain characters by replacing them with unicode escaped versions to prevent breakage. ### Proof 1 Lets take the original code block from the question, and add the following fixes: * Wrap all in `<pre>` tags * Use `esc_html` so we can see the tags properly * Fix the `printf` by removing `var_dump` and using `var_export` with the second parameter so it returns rather than outputs * Add a final test case where we re-parse and re-serialize 10 times to compare the final result with the original ```php function reparse_reserialize( string $content, int $loops = 10 ) : string { $final_content = $content; for ($x = 0; $x <= $loops; $x++) { $blocks = parse_blocks( $final_content ); $final_content = serialize_blocks( $blocks ); } return $final_content; } add_action( 'wp', function() { $p = get_post( 1 ); echo '<p>Original content:</p>'; echo '<pre>' . esc_html( var_export( $p->post_content, true ) ) . '</pre>'; $final = reparse_reserialize( $p->post_content ); echo '<p>10 parse and serialize loops later:</p>'; echo '<pre>' . esc_html( var_export( $final, true ) ) . '</pre>'; echo '<hr/>'; }, PHP_INT_MAX ); ``` Running that, we see that the content survived the process of being parsed and re-serialized 10 times. If mangling was occuring we would see progressively greater mangling occur ### Proof 2 If we take the mangled markup: ``` \u003ch3\u003eWhat types of accommodation are available in xxxx?\u003c\/h3\u003e ``` Turn it into a JSON string, then decode it: ```php $json = '"\u003ch3\u003eWhat types of accommodation are available in xxxx?\u003c\/h3\u003e"'; echo '<pre>' . esc_html( json_decode( $json ) ) . '</pre>'; ``` We get the original HTML: ```html <h3>What types of accommodation are available in xxxx?</h3> ``` So no mangling has taken place. Summary ------- **There is no mangling or corruption.** It's just encoding the `<` and `>` to prevent breakage. JSON processors handle the unicode escape characters just fine. If you are seeing these encoded characters in the block editor, then that is a bug, either in the block, or the ACF plugin. You should report it as such
372,973
<p>I just recently updated my Wordpress, theme, and plugins, and am now getting these two errors on top of the homepage and pages page.</p> <blockquote> <p>Deprecated: wp_make_content_images_responsive is deprecated since version 5.5.0! Use wp_filter_content_tags() instead. in /var/www/html/wp-includes/functions.php on line 4773</p> </blockquote> <p>and the pages page,</p> <blockquote> <p>Notice: register_rest_route was called incorrectly. The REST API route definition for pum/v1/analytics is missing the required permission_callback argument. For REST API routes that are intended to be public, use __return_true as the permission callback. Please see Debugging in WordPress for more information. (This message was added in version 5.5.0.) in /var/www/html/wp-includes/functions.php on line 5225</p> </blockquote> <p>I also did this in another website but did not get any errors, the sites are built with the same theme/plugins.</p>
[ { "answer_id": 373009, "author": "drcrow", "author_id": 178234, "author_profile": "https://wordpress.stackexchange.com/users/178234", "pm_score": -1, "selected": false, "text": "<p>If nothing is broken, in your wp-config.php put this:</p>\n<pre><code>define( 'WP_DEBUG', false );\ndefine( 'WP_DEBUG_DISPLAY', false );\n</code></pre>\n<p>to get rid of the error messages</p>\n" }, { "answer_id": 378832, "author": "ponies", "author_id": 123805, "author_profile": "https://wordpress.stackexchange.com/users/123805", "pm_score": 0, "selected": false, "text": "<p>I suspect this is already resolved in the plugin, but I added a check for the new function in wp-content/plugins/fusion-builder/shortcodes/fusion-image.php:285.</p>\n<pre><code>if ( ! empty( $image_id ) &amp;&amp; function_exists( 'wp_image_add_srcset_and_sizes' ) ) {\n $content = wp_image_add_srcset_and_sizes(\n $content,\n wp_get_attachment_metadata( (int) $image_id ),\n $image_id );\n} elseif ( function_exists( 'wp_make_content_images_responsive' ) ) {\n $content = wp_make_content_images_responsive( $content );\n}\n</code></pre>\n" } ]
2020/08/13
[ "https://wordpress.stackexchange.com/questions/372973", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193095/" ]
I just recently updated my Wordpress, theme, and plugins, and am now getting these two errors on top of the homepage and pages page. > > Deprecated: wp\_make\_content\_images\_responsive is deprecated since > version 5.5.0! Use wp\_filter\_content\_tags() instead. in > /var/www/html/wp-includes/functions.php on line 4773 > > > and the pages page, > > Notice: register\_rest\_route was called incorrectly. The REST API route > definition for pum/v1/analytics is missing the required > permission\_callback argument. For REST API routes that are intended to > be public, use \_\_return\_true as the permission callback. Please see > Debugging in WordPress for more information. (This message was added > in version 5.5.0.) in /var/www/html/wp-includes/functions.php on line > 5225 > > > I also did this in another website but did not get any errors, the sites are built with the same theme/plugins.
I suspect this is already resolved in the plugin, but I added a check for the new function in wp-content/plugins/fusion-builder/shortcodes/fusion-image.php:285. ``` if ( ! empty( $image_id ) && function_exists( 'wp_image_add_srcset_and_sizes' ) ) { $content = wp_image_add_srcset_and_sizes( $content, wp_get_attachment_metadata( (int) $image_id ), $image_id ); } elseif ( function_exists( 'wp_make_content_images_responsive' ) ) { $content = wp_make_content_images_responsive( $content ); } ```
372,974
<p>Wordpress sends some various default email texts to the users.</p> <p>For example when the password reset email has been sent, then the user gets an automatic email like this:</p> <blockquote> <p><em>Hello user, This notification confirms the change of access password to NAMEOFWEBSITE. If you have not changed your password, please contact the Site Administrator at <strong>[email protected]</strong> This message was sent to [email protected] Sincerely, All of us at NAMEOFWEBSITE <a href="https://www.nameofwebsite.com" rel="nofollow noreferrer">https://www.nameofwebsite.com</a></em></p> </blockquote> <p>I need to keep the default admin email that i set up in wordpress. But i need to filter all emails to have another email inside the text, like this :</p> <blockquote> <p><em>Hello user, This notification confirms the change of access password to NAMEOFWEBSITE. If you have not changed your password, please contact the Site Administrator at <strong>[email protected]</strong> This message was sent to [email protected] Sincerely, All of us at NAMEOFWEBSITE <a href="https://www.nameofwebsite.com" rel="nofollow noreferrer">https://www.nameofwebsite.com</a></em></p> </blockquote> <p>Any ideas if this is possible with some filter?</p>
[ { "answer_id": 372977, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 2, "selected": false, "text": "<p>There is definitely a filter for that!</p>\n<p>Here is the reference link to wordpress developers page: <a href=\"https://developer.wordpress.org/reference/hooks/password_change_email/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/password_change_email/</a></p>\n<p>Basically adding this function (with changes) to your functions.php will override your default password reset email.</p>\n<pre><code>apply_filters( 'password_change_email', array $pass_change_email, array $user, array $userdata )\n</code></pre>\n<p>full example:</p>\n<pre><code>add_filter( 'password_change_email', 'rt_change_password_mail_message', 10, 3 );\n\nfunction rt_change_password_mail_message( $pass_change_mail, $user, $userdata ) {\n\n $new_message_txt = __( 'Hi [first_name] [last_name], \n\n This notice confirms that your email was changed on on our site.\n\n If you did not change your email, please contact the Site Administrator on our site.\n\n This email has been sent to [user_email]\n\n Regards,\nME' );\n $pass_change_mail[ 'message' ] = $new_message_txt;\n return $pass_change_mail;\n\n}\n</code></pre>\n<p>Checking the notes there, you'll see that the message is part of the <code>$pass_change_email</code> array. SO if you just want to add something to it try this...</p>\n<pre><code>add_filter( 'password_change_email', 'rt_change_password_mail_message', 10, 3 );\n\nfunction rt_change_password_mail_message( $pass_change_mail, $user, $userdata ) {\n\n $new_message_txt = __( 'new text with phone number' );\n $pass_change_mail[ 'message' ] = $pass_change_mail[ 'message' ] . $new_message_txt;\n return $pass_change_mail;\n\n}\n</code></pre>\n" }, { "answer_id": 372996, "author": "Ankit", "author_id": 51280, "author_profile": "https://wordpress.stackexchange.com/users/51280", "pm_score": 0, "selected": false, "text": "<p>I noticed that you want Administrator email to remain to some email, but you need to change the admin email in password and email change email.</p>\n<p>So you can do following.</p>\n<ol>\n<li>Hook into <code>email_change_email</code> and <code>password_change_email</code> filters.</li>\n<li>You will get the parameter <code>$email_change_email</code> and <code>$pass_change_email</code> for those filters respectively inside callback function.</li>\n<li>Email text is present in <code>$pass_change_email['message']</code>, so you just have to look for the admin email in there and replace it with your new email address.</li>\n<li>Return the parameter from callback function.</li>\n</ol>\n<p>This can be the example for password change email.</p>\n<pre><code>/**\n * Change admin email in password change email.\n */\nfunction change_password_change_admin_email( array $pass_change_email ) {\n $admin_email = get_option('admin_email');\n $pass_change_email['message'] = str_replace( $admin_email, '[email protected]', $pass_change_email['message'] );\n\n return $pass_change_email;\n\n}\nadd_filter( 'password_change_email', 'change_password_change_admin_email' );\n\n</code></pre>\n" } ]
2020/08/13
[ "https://wordpress.stackexchange.com/questions/372974", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129972/" ]
Wordpress sends some various default email texts to the users. For example when the password reset email has been sent, then the user gets an automatic email like this: > > *Hello user, This notification confirms the change of access password to NAMEOFWEBSITE. If you have not changed your password, please contact the Site Administrator at **[email protected]** This message was sent to [email protected] Sincerely, All of us at NAMEOFWEBSITE <https://www.nameofwebsite.com>* > > > I need to keep the default admin email that i set up in wordpress. But i need to filter all emails to have another email inside the text, like this : > > *Hello user, This notification confirms the change of access password to NAMEOFWEBSITE. If you have not changed your password, please contact the Site Administrator at **[email protected]** This message was sent to [email protected] Sincerely, All of us at NAMEOFWEBSITE <https://www.nameofwebsite.com>* > > > Any ideas if this is possible with some filter?
There is definitely a filter for that! Here is the reference link to wordpress developers page: <https://developer.wordpress.org/reference/hooks/password_change_email/> Basically adding this function (with changes) to your functions.php will override your default password reset email. ``` apply_filters( 'password_change_email', array $pass_change_email, array $user, array $userdata ) ``` full example: ``` add_filter( 'password_change_email', 'rt_change_password_mail_message', 10, 3 ); function rt_change_password_mail_message( $pass_change_mail, $user, $userdata ) { $new_message_txt = __( 'Hi [first_name] [last_name], This notice confirms that your email was changed on on our site. If you did not change your email, please contact the Site Administrator on our site. This email has been sent to [user_email] Regards, ME' ); $pass_change_mail[ 'message' ] = $new_message_txt; return $pass_change_mail; } ``` Checking the notes there, you'll see that the message is part of the `$pass_change_email` array. SO if you just want to add something to it try this... ``` add_filter( 'password_change_email', 'rt_change_password_mail_message', 10, 3 ); function rt_change_password_mail_message( $pass_change_mail, $user, $userdata ) { $new_message_txt = __( 'new text with phone number' ); $pass_change_mail[ 'message' ] = $pass_change_mail[ 'message' ] . $new_message_txt; return $pass_change_mail; } ```
372,989
<p>i want to show category list with custom post type count. but i have two different post types in every category. how can i do that . please help. this is my code:</p> <pre><code>&lt;?php $category_object = get_queried_object(); $current_category_taxonomy = $category_object-&gt;taxonomy; $current_category_term_id = $category_object-&gt;term_id; $current_category_name = $category_object-&gt;name; $args = array( 'child_of' =&gt; $current_category_term_id, 'current_category' =&gt; $current_category_term_id, 'depth' =&gt; 0, 'echo' =&gt; 1, 'exclude' =&gt; '', 'exclude_tree' =&gt; '', 'feed' =&gt; '', 'feed_image' =&gt; '', 'feed_type' =&gt; '', 'hide_empty' =&gt; 0, 'hide_title_if_empty' =&gt; false, 'hierarchical' =&gt; true, 'order' =&gt; 'ASC', 'orderby' =&gt; 'name', 'separator' =&gt; '', 'show_count' =&gt; 1, 'show_option_all' =&gt; '', 'show_option_none' =&gt; __( 'No categories' ), 'style' =&gt; 'list', 'taxonomy' =&gt; 'category', 'title_li' =&gt; __( $current_category_name ), 'use_desc_for_title' =&gt; 0, ); wp_list_categories($args); ?&gt; </code></pre>
[ { "answer_id": 372994, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 1, "selected": false, "text": "<pre><code>function my_taxonomy_posts_count_func($atts)\n {\n extract(shortcode_atts(array(\n 'post_type' =&gt; 'post',\n ) , $atts));\n global $WP_Views;\n $term = $WP_Views-&gt;get_current_taxonomy_term();\n $args = array(\n 'post_type' =&gt; $post_type,\n $term-&gt;taxonomy =&gt; $term-&gt;term_id,\n 'order' =&gt; 'ASC',\n 'posts_per_page' =&gt; - 1,\n );\n $posts = get_posts($args);\n if ($posts)\n {\n $res = count($posts);\n }\n return $res;\n \n }\n add_shortcode('my-taxonomy-posts-count', 'my_taxonomy_posts_count_func');\n</code></pre>\n<ol>\n<li><p>add codes in your theme/functions.php</p>\n</li>\n<li><p>put the shortcode in your content, like this:</p>\n<p>[my-taxonomy-posts-count post_type=&quot;my-custom-post-type&quot;]</p>\n</li>\n<li><p>replace the &quot;my-custom-post-type&quot; with your specific post type slug</p>\n</li>\n<li><p>replace the shortcode [wpv-taxonomy-post-count] with [my-taxonomy-posts-count post_type=&quot;my-custom-post-type&quot;]</p>\n</li>\n</ol>\n<p>Change code as per comment</p>\n" }, { "answer_id": 373110, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": true, "text": "<p>Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type.</p>\n<p>In order to do this, you will need to output the markup yourself, and query for the counts yourself.</p>\n<p><strong>This will be slow/heavy/expensive.</strong></p>\n<p>So first we start with the current term/taxonomy:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$category_object = get_queried_object();\n$current_category_taxonomy = $category_object-&gt;taxonomy;\n$current_category_term_id = $category_object-&gt;term_id;\n$current_category_name = $category_object-&gt;name;\n</code></pre>\n<p>Then we grab all child terms that aren't empty:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$children = get_terms(\n [\n 'taxonomy' =&gt; $current_category_taxonomy,\n 'parent' =&gt; $category_object-&gt;term_id,\n ]\n);\n</code></pre>\n<p>And loop over each term:</p>\n<pre class=\"lang-php prettyprint-override\"><code>foreach ( $children as $child ) {\n //\n}\n</code></pre>\n<p>Now inside that loop we need to check how many posts are of your particular post type, lets say the <code>changeme</code> post type:</p>\n<pre class=\"lang-php prettyprint-override\"><code> $args = [\n 'post_type' =&gt; 'changeme',\n $term-&gt;taxonomy =&gt; $child-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n ];\n $q = new WP_Query( $args );\n if ( $q-&gt;have_posts() ) {\n echo '&lt;li&gt;' . esc_html( $term-&gt;name ) . ' ( '. intval( $q-&gt;found_posts ) . ' ) &lt;/li&gt;';\n }\n</code></pre>\n<p>Notice we used the <code>found_posts</code> parameter. At this point, it's just a matter of wrapping the whole thing in a <code>&lt;ul&gt;</code> tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with.</p>\n<p>Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present.</p>\n<p>Or you could just register another taxonomy specific for this post type, and avoid all of this.</p>\n" } ]
2020/08/14
[ "https://wordpress.stackexchange.com/questions/372989", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/172323/" ]
i want to show category list with custom post type count. but i have two different post types in every category. how can i do that . please help. this is my code: ``` <?php $category_object = get_queried_object(); $current_category_taxonomy = $category_object->taxonomy; $current_category_term_id = $category_object->term_id; $current_category_name = $category_object->name; $args = array( 'child_of' => $current_category_term_id, 'current_category' => $current_category_term_id, 'depth' => 0, 'echo' => 1, 'exclude' => '', 'exclude_tree' => '', 'feed' => '', 'feed_image' => '', 'feed_type' => '', 'hide_empty' => 0, 'hide_title_if_empty' => false, 'hierarchical' => true, 'order' => 'ASC', 'orderby' => 'name', 'separator' => '', 'show_count' => 1, 'show_option_all' => '', 'show_option_none' => __( 'No categories' ), 'style' => 'list', 'taxonomy' => 'category', 'title_li' => __( $current_category_name ), 'use_desc_for_title' => 0, ); wp_list_categories($args); ?> ```
Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type. In order to do this, you will need to output the markup yourself, and query for the counts yourself. **This will be slow/heavy/expensive.** So first we start with the current term/taxonomy: ```php $category_object = get_queried_object(); $current_category_taxonomy = $category_object->taxonomy; $current_category_term_id = $category_object->term_id; $current_category_name = $category_object->name; ``` Then we grab all child terms that aren't empty: ```php $children = get_terms( [ 'taxonomy' => $current_category_taxonomy, 'parent' => $category_object->term_id, ] ); ``` And loop over each term: ```php foreach ( $children as $child ) { // } ``` Now inside that loop we need to check how many posts are of your particular post type, lets say the `changeme` post type: ```php $args = [ 'post_type' => 'changeme', $term->taxonomy => $child->term_id, 'posts_per_page' => 1, ]; $q = new WP_Query( $args ); if ( $q->have_posts() ) { echo '<li>' . esc_html( $term->name ) . ' ( '. intval( $q->found_posts ) . ' ) </li>'; } ``` Notice we used the `found_posts` parameter. At this point, it's just a matter of wrapping the whole thing in a `<ul>` tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with. Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present. Or you could just register another taxonomy specific for this post type, and avoid all of this.
373,025
<p>I'm trying to come up with a solution for a client.</p> <p>They sell parasols and each one has the following attributes:</p> <ul> <li>Colour</li> <li>Frame</li> <li>Size</li> <li>Base</li> <li>Bar</li> </ul> <p>The way it is set up at the moment, there are 36 variations, and the colour attribute is set to 'any colour' as it doesn't effect price. The other 4 options, (Frame, Size Base &amp; Bar) effect the price.</p> <p>Now, they want to change the image when the colour swatch is clicked.</p> <p>Normally, I would create variations from all attributes, and add a unique image for each variation. WooCommerce's native functionality would then take care of the image changing no problem. However, as each of the non-colour attribute affects price, it creates a situation where I need 180 variations!</p> <p>To try to avoid this variation nightmare, I've built what I thought was a solution in ACF, where I create a relationship between the colour attributes and a custom image, and then I use JS to change the image when the swatch is clicked, independantly from the core functionality.</p> <p>However, when a full combination is chosen and the price is generated, it calls the get_variation ajax call. This overides the image back to the default. This results in the image changing immediately when the swatch is clicked, but then sliding back to the default image when the variation loads.</p> <p>Can anyone see a way around this whereby I can control the product image using the swatches, but not affect the variation.</p> <p>Thanks.</p> <p><a href="https://i.stack.imgur.com/PLsYH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PLsYH.png" alt="enter image description here" /></a></p>
[ { "answer_id": 372994, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 1, "selected": false, "text": "<pre><code>function my_taxonomy_posts_count_func($atts)\n {\n extract(shortcode_atts(array(\n 'post_type' =&gt; 'post',\n ) , $atts));\n global $WP_Views;\n $term = $WP_Views-&gt;get_current_taxonomy_term();\n $args = array(\n 'post_type' =&gt; $post_type,\n $term-&gt;taxonomy =&gt; $term-&gt;term_id,\n 'order' =&gt; 'ASC',\n 'posts_per_page' =&gt; - 1,\n );\n $posts = get_posts($args);\n if ($posts)\n {\n $res = count($posts);\n }\n return $res;\n \n }\n add_shortcode('my-taxonomy-posts-count', 'my_taxonomy_posts_count_func');\n</code></pre>\n<ol>\n<li><p>add codes in your theme/functions.php</p>\n</li>\n<li><p>put the shortcode in your content, like this:</p>\n<p>[my-taxonomy-posts-count post_type=&quot;my-custom-post-type&quot;]</p>\n</li>\n<li><p>replace the &quot;my-custom-post-type&quot; with your specific post type slug</p>\n</li>\n<li><p>replace the shortcode [wpv-taxonomy-post-count] with [my-taxonomy-posts-count post_type=&quot;my-custom-post-type&quot;]</p>\n</li>\n</ol>\n<p>Change code as per comment</p>\n" }, { "answer_id": 373110, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": true, "text": "<p>Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type.</p>\n<p>In order to do this, you will need to output the markup yourself, and query for the counts yourself.</p>\n<p><strong>This will be slow/heavy/expensive.</strong></p>\n<p>So first we start with the current term/taxonomy:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$category_object = get_queried_object();\n$current_category_taxonomy = $category_object-&gt;taxonomy;\n$current_category_term_id = $category_object-&gt;term_id;\n$current_category_name = $category_object-&gt;name;\n</code></pre>\n<p>Then we grab all child terms that aren't empty:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$children = get_terms(\n [\n 'taxonomy' =&gt; $current_category_taxonomy,\n 'parent' =&gt; $category_object-&gt;term_id,\n ]\n);\n</code></pre>\n<p>And loop over each term:</p>\n<pre class=\"lang-php prettyprint-override\"><code>foreach ( $children as $child ) {\n //\n}\n</code></pre>\n<p>Now inside that loop we need to check how many posts are of your particular post type, lets say the <code>changeme</code> post type:</p>\n<pre class=\"lang-php prettyprint-override\"><code> $args = [\n 'post_type' =&gt; 'changeme',\n $term-&gt;taxonomy =&gt; $child-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n ];\n $q = new WP_Query( $args );\n if ( $q-&gt;have_posts() ) {\n echo '&lt;li&gt;' . esc_html( $term-&gt;name ) . ' ( '. intval( $q-&gt;found_posts ) . ' ) &lt;/li&gt;';\n }\n</code></pre>\n<p>Notice we used the <code>found_posts</code> parameter. At this point, it's just a matter of wrapping the whole thing in a <code>&lt;ul&gt;</code> tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with.</p>\n<p>Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present.</p>\n<p>Or you could just register another taxonomy specific for this post type, and avoid all of this.</p>\n" } ]
2020/08/14
[ "https://wordpress.stackexchange.com/questions/373025", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44848/" ]
I'm trying to come up with a solution for a client. They sell parasols and each one has the following attributes: * Colour * Frame * Size * Base * Bar The way it is set up at the moment, there are 36 variations, and the colour attribute is set to 'any colour' as it doesn't effect price. The other 4 options, (Frame, Size Base & Bar) effect the price. Now, they want to change the image when the colour swatch is clicked. Normally, I would create variations from all attributes, and add a unique image for each variation. WooCommerce's native functionality would then take care of the image changing no problem. However, as each of the non-colour attribute affects price, it creates a situation where I need 180 variations! To try to avoid this variation nightmare, I've built what I thought was a solution in ACF, where I create a relationship between the colour attributes and a custom image, and then I use JS to change the image when the swatch is clicked, independantly from the core functionality. However, when a full combination is chosen and the price is generated, it calls the get\_variation ajax call. This overides the image back to the default. This results in the image changing immediately when the swatch is clicked, but then sliding back to the default image when the variation loads. Can anyone see a way around this whereby I can control the product image using the swatches, but not affect the variation. Thanks. [![enter image description here](https://i.stack.imgur.com/PLsYH.png)](https://i.stack.imgur.com/PLsYH.png)
Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type. In order to do this, you will need to output the markup yourself, and query for the counts yourself. **This will be slow/heavy/expensive.** So first we start with the current term/taxonomy: ```php $category_object = get_queried_object(); $current_category_taxonomy = $category_object->taxonomy; $current_category_term_id = $category_object->term_id; $current_category_name = $category_object->name; ``` Then we grab all child terms that aren't empty: ```php $children = get_terms( [ 'taxonomy' => $current_category_taxonomy, 'parent' => $category_object->term_id, ] ); ``` And loop over each term: ```php foreach ( $children as $child ) { // } ``` Now inside that loop we need to check how many posts are of your particular post type, lets say the `changeme` post type: ```php $args = [ 'post_type' => 'changeme', $term->taxonomy => $child->term_id, 'posts_per_page' => 1, ]; $q = new WP_Query( $args ); if ( $q->have_posts() ) { echo '<li>' . esc_html( $term->name ) . ' ( '. intval( $q->found_posts ) . ' ) </li>'; } ``` Notice we used the `found_posts` parameter. At this point, it's just a matter of wrapping the whole thing in a `<ul>` tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with. Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present. Or you could just register another taxonomy specific for this post type, and avoid all of this.
373,030
<p>In Gravity Forms, I have a confirmation set up with various conditional shortcodes. Example:</p> <pre><code>[gravityforms action=&quot;conditional&quot; merge_tag=&quot;{:3:value}&quot; condition=&quot;contains&quot; value=&quot;E&quot;]*** GET A CATEGORY ***[/gravityforms] </code></pre> <p>Additionally, I have a PHP function that gets all posts by category, and I would like to use this function inside the conditional shortcode. I'm not figuring out a way to do this, so any help would be appreciated.</p> <p>My function: <code>useful_tools_list(array( 'type' =&gt; 'documents', desc =&gt; 'true' ))</code></p> <p>I also made it into a shortcode: <code>[useful-tools type=&quot;documents&quot; desc=&quot;true&quot;]</code></p> <p>I tried using <code>&lt;?php ?&gt;</code>, but I realized I can't embed PHP into the editor. The conditional shortcode doesn't support nesting other shortcodes inside of it, so that doesn't work.</p> <p>I'm wondering if there is a way to manipulate the GF conditional shortcode to allow nesting? Or another way of calling the function that I'm not aware of?</p>
[ { "answer_id": 372994, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 1, "selected": false, "text": "<pre><code>function my_taxonomy_posts_count_func($atts)\n {\n extract(shortcode_atts(array(\n 'post_type' =&gt; 'post',\n ) , $atts));\n global $WP_Views;\n $term = $WP_Views-&gt;get_current_taxonomy_term();\n $args = array(\n 'post_type' =&gt; $post_type,\n $term-&gt;taxonomy =&gt; $term-&gt;term_id,\n 'order' =&gt; 'ASC',\n 'posts_per_page' =&gt; - 1,\n );\n $posts = get_posts($args);\n if ($posts)\n {\n $res = count($posts);\n }\n return $res;\n \n }\n add_shortcode('my-taxonomy-posts-count', 'my_taxonomy_posts_count_func');\n</code></pre>\n<ol>\n<li><p>add codes in your theme/functions.php</p>\n</li>\n<li><p>put the shortcode in your content, like this:</p>\n<p>[my-taxonomy-posts-count post_type=&quot;my-custom-post-type&quot;]</p>\n</li>\n<li><p>replace the &quot;my-custom-post-type&quot; with your specific post type slug</p>\n</li>\n<li><p>replace the shortcode [wpv-taxonomy-post-count] with [my-taxonomy-posts-count post_type=&quot;my-custom-post-type&quot;]</p>\n</li>\n</ol>\n<p>Change code as per comment</p>\n" }, { "answer_id": 373110, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": true, "text": "<p>Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type.</p>\n<p>In order to do this, you will need to output the markup yourself, and query for the counts yourself.</p>\n<p><strong>This will be slow/heavy/expensive.</strong></p>\n<p>So first we start with the current term/taxonomy:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$category_object = get_queried_object();\n$current_category_taxonomy = $category_object-&gt;taxonomy;\n$current_category_term_id = $category_object-&gt;term_id;\n$current_category_name = $category_object-&gt;name;\n</code></pre>\n<p>Then we grab all child terms that aren't empty:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$children = get_terms(\n [\n 'taxonomy' =&gt; $current_category_taxonomy,\n 'parent' =&gt; $category_object-&gt;term_id,\n ]\n);\n</code></pre>\n<p>And loop over each term:</p>\n<pre class=\"lang-php prettyprint-override\"><code>foreach ( $children as $child ) {\n //\n}\n</code></pre>\n<p>Now inside that loop we need to check how many posts are of your particular post type, lets say the <code>changeme</code> post type:</p>\n<pre class=\"lang-php prettyprint-override\"><code> $args = [\n 'post_type' =&gt; 'changeme',\n $term-&gt;taxonomy =&gt; $child-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n ];\n $q = new WP_Query( $args );\n if ( $q-&gt;have_posts() ) {\n echo '&lt;li&gt;' . esc_html( $term-&gt;name ) . ' ( '. intval( $q-&gt;found_posts ) . ' ) &lt;/li&gt;';\n }\n</code></pre>\n<p>Notice we used the <code>found_posts</code> parameter. At this point, it's just a matter of wrapping the whole thing in a <code>&lt;ul&gt;</code> tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with.</p>\n<p>Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present.</p>\n<p>Or you could just register another taxonomy specific for this post type, and avoid all of this.</p>\n" } ]
2020/08/14
[ "https://wordpress.stackexchange.com/questions/373030", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/42925/" ]
In Gravity Forms, I have a confirmation set up with various conditional shortcodes. Example: ``` [gravityforms action="conditional" merge_tag="{:3:value}" condition="contains" value="E"]*** GET A CATEGORY ***[/gravityforms] ``` Additionally, I have a PHP function that gets all posts by category, and I would like to use this function inside the conditional shortcode. I'm not figuring out a way to do this, so any help would be appreciated. My function: `useful_tools_list(array( 'type' => 'documents', desc => 'true' ))` I also made it into a shortcode: `[useful-tools type="documents" desc="true"]` I tried using `<?php ?>`, but I realized I can't embed PHP into the editor. The conditional shortcode doesn't support nesting other shortcodes inside of it, so that doesn't work. I'm wondering if there is a way to manipulate the GF conditional shortcode to allow nesting? Or another way of calling the function that I'm not aware of?
Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type. In order to do this, you will need to output the markup yourself, and query for the counts yourself. **This will be slow/heavy/expensive.** So first we start with the current term/taxonomy: ```php $category_object = get_queried_object(); $current_category_taxonomy = $category_object->taxonomy; $current_category_term_id = $category_object->term_id; $current_category_name = $category_object->name; ``` Then we grab all child terms that aren't empty: ```php $children = get_terms( [ 'taxonomy' => $current_category_taxonomy, 'parent' => $category_object->term_id, ] ); ``` And loop over each term: ```php foreach ( $children as $child ) { // } ``` Now inside that loop we need to check how many posts are of your particular post type, lets say the `changeme` post type: ```php $args = [ 'post_type' => 'changeme', $term->taxonomy => $child->term_id, 'posts_per_page' => 1, ]; $q = new WP_Query( $args ); if ( $q->have_posts() ) { echo '<li>' . esc_html( $term->name ) . ' ( '. intval( $q->found_posts ) . ' ) </li>'; } ``` Notice we used the `found_posts` parameter. At this point, it's just a matter of wrapping the whole thing in a `<ul>` tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with. Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present. Or you could just register another taxonomy specific for this post type, and avoid all of this.
373,037
<p>I've been using WordPress for awhile now but one problem I'm constantly facing is creating a local clone of a production site so I can test changes/updates.</p> <p>My current process goes something like this...</p> <ul> <li>Run XAMPP Server</li> <li>Download the site files (Filzilla)</li> <li>Download the database (phpMyAdmin)</li> <li>Create a local database (phpMyAdmin)</li> <li>Copy site files into XAMPP</li> <li>Import database</li> <li>Update WP hostname, settings, etc</li> </ul> <p>My question is simple. <strong>Is it possible to automate this entire process?</strong> If not, what can be automated to make this less time consuming?</p> <p>I've kinda looked into Docker but it seems confusing and I don't know that it helps with most of these steps. I know there are plugins that can create backups of the site but again that only automates a couple steps. I'm pretty sure WP CLI can clone a site but I'm not sure if it can clone a remote site down to local. A solution using WP CLI would be great.</p> <p>There has to be a better process than I'm doing now :(</p>
[ { "answer_id": 372994, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 1, "selected": false, "text": "<pre><code>function my_taxonomy_posts_count_func($atts)\n {\n extract(shortcode_atts(array(\n 'post_type' =&gt; 'post',\n ) , $atts));\n global $WP_Views;\n $term = $WP_Views-&gt;get_current_taxonomy_term();\n $args = array(\n 'post_type' =&gt; $post_type,\n $term-&gt;taxonomy =&gt; $term-&gt;term_id,\n 'order' =&gt; 'ASC',\n 'posts_per_page' =&gt; - 1,\n );\n $posts = get_posts($args);\n if ($posts)\n {\n $res = count($posts);\n }\n return $res;\n \n }\n add_shortcode('my-taxonomy-posts-count', 'my_taxonomy_posts_count_func');\n</code></pre>\n<ol>\n<li><p>add codes in your theme/functions.php</p>\n</li>\n<li><p>put the shortcode in your content, like this:</p>\n<p>[my-taxonomy-posts-count post_type=&quot;my-custom-post-type&quot;]</p>\n</li>\n<li><p>replace the &quot;my-custom-post-type&quot; with your specific post type slug</p>\n</li>\n<li><p>replace the shortcode [wpv-taxonomy-post-count] with [my-taxonomy-posts-count post_type=&quot;my-custom-post-type&quot;]</p>\n</li>\n</ol>\n<p>Change code as per comment</p>\n" }, { "answer_id": 373110, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": true, "text": "<p>Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type.</p>\n<p>In order to do this, you will need to output the markup yourself, and query for the counts yourself.</p>\n<p><strong>This will be slow/heavy/expensive.</strong></p>\n<p>So first we start with the current term/taxonomy:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$category_object = get_queried_object();\n$current_category_taxonomy = $category_object-&gt;taxonomy;\n$current_category_term_id = $category_object-&gt;term_id;\n$current_category_name = $category_object-&gt;name;\n</code></pre>\n<p>Then we grab all child terms that aren't empty:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$children = get_terms(\n [\n 'taxonomy' =&gt; $current_category_taxonomy,\n 'parent' =&gt; $category_object-&gt;term_id,\n ]\n);\n</code></pre>\n<p>And loop over each term:</p>\n<pre class=\"lang-php prettyprint-override\"><code>foreach ( $children as $child ) {\n //\n}\n</code></pre>\n<p>Now inside that loop we need to check how many posts are of your particular post type, lets say the <code>changeme</code> post type:</p>\n<pre class=\"lang-php prettyprint-override\"><code> $args = [\n 'post_type' =&gt; 'changeme',\n $term-&gt;taxonomy =&gt; $child-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n ];\n $q = new WP_Query( $args );\n if ( $q-&gt;have_posts() ) {\n echo '&lt;li&gt;' . esc_html( $term-&gt;name ) . ' ( '. intval( $q-&gt;found_posts ) . ' ) &lt;/li&gt;';\n }\n</code></pre>\n<p>Notice we used the <code>found_posts</code> parameter. At this point, it's just a matter of wrapping the whole thing in a <code>&lt;ul&gt;</code> tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with.</p>\n<p>Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present.</p>\n<p>Or you could just register another taxonomy specific for this post type, and avoid all of this.</p>\n" } ]
2020/08/14
[ "https://wordpress.stackexchange.com/questions/373037", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/157172/" ]
I've been using WordPress for awhile now but one problem I'm constantly facing is creating a local clone of a production site so I can test changes/updates. My current process goes something like this... * Run XAMPP Server * Download the site files (Filzilla) * Download the database (phpMyAdmin) * Create a local database (phpMyAdmin) * Copy site files into XAMPP * Import database * Update WP hostname, settings, etc My question is simple. **Is it possible to automate this entire process?** If not, what can be automated to make this less time consuming? I've kinda looked into Docker but it seems confusing and I don't know that it helps with most of these steps. I know there are plugins that can create backups of the site but again that only automates a couple steps. I'm pretty sure WP CLI can clone a site but I'm not sure if it can clone a remote site down to local. A solution using WP CLI would be great. There has to be a better process than I'm doing now :(
Out of the box this cannot be done, as the post counts on each term is singular, there is no breakdown by post type. In order to do this, you will need to output the markup yourself, and query for the counts yourself. **This will be slow/heavy/expensive.** So first we start with the current term/taxonomy: ```php $category_object = get_queried_object(); $current_category_taxonomy = $category_object->taxonomy; $current_category_term_id = $category_object->term_id; $current_category_name = $category_object->name; ``` Then we grab all child terms that aren't empty: ```php $children = get_terms( [ 'taxonomy' => $current_category_taxonomy, 'parent' => $category_object->term_id, ] ); ``` And loop over each term: ```php foreach ( $children as $child ) { // } ``` Now inside that loop we need to check how many posts are of your particular post type, lets say the `changeme` post type: ```php $args = [ 'post_type' => 'changeme', $term->taxonomy => $child->term_id, 'posts_per_page' => 1, ]; $q = new WP_Query( $args ); if ( $q->have_posts() ) { echo '<li>' . esc_html( $term->name ) . ' ( '. intval( $q->found_posts ) . ' ) </li>'; } ``` Notice we used the `found_posts` parameter. At this point, it's just a matter of wrapping the whole thing in a `<ul>` tag, and expanding the markup to match what you want. You have the term object inside the loop to print out URLs etc with. Don't forget, this is expensive/slow/heavy, you will want to cache this, perhaps using a transient, or if you have an object cache or Elastic search present. Or you could just register another taxonomy specific for this post type, and avoid all of this.
373,042
<p>I am using <strong>Option 3</strong> from <a href="https://wordpress.stackexchange.com/a/333920">this answer</a> as my source. So far it is working great, it is splitting my search results by post type and listing the posts from each post type in their own sections. The only problem is that this solution does not appear to allow for hyperlinking the post titles using <code>the_permalink();</code> How can I adapt this code so that I can also wrap the post titles in an anchor tag that will direct to the post?</p> <pre><code>&lt;?php get_header(); ?&gt; &lt;?php $search_query = new WP_Query( array( 'posts_per_page' =&gt; -1, 's' =&gt; esc_attr($_GET['s']), 'post_status' =&gt; 'publish' ) ); if ($search_query-&gt;have_posts()) : ?&gt; &lt;section id=&quot;search-results&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col&quot;&gt; &lt;h2&gt;&lt;?php echo $search_query-&gt;found_posts.' Search results found'; ?&gt; for: &quot;&lt;?php echo get_search_query(); ?&gt;&quot;&lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;search-results-list&quot;&gt; &lt;?php $types = array( 'post', 'page', 'glossary' ); $posts_titles = []; while($search_query-&gt;have_posts()) { $search_query-&gt;the_post(); $type = $search_query-&gt;post-&gt;post_type; if (!isset($posts_titles[$type])) $posts_titles[$type] = []; $posts_titles[$type][] = get_the_title(); } rewind_posts(); foreach($types as $type) : if (!isset($posts_titles[$type])) continue; ?&gt; &lt;div class=&quot;row&quot;&gt; &lt;h3&gt; &lt;?php $post_type_obj = get_post_type_object($type); echo $post_type_obj-&gt;labels-&gt;name ?&gt; &lt;/h3&gt; &lt;/div&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col&quot;&gt; &lt;ul&gt; &lt;?php foreach($posts_titles[$type] as $title) : ?&gt; &lt;li class=&quot;search-item&quot;&gt; &lt;a href=&quot;PERMALINK SHOULD GO HERE&quot;&gt;&lt;?php echo htmlspecialchars($title); ?&gt;&lt;/a&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;?php else: echo '&lt;div class=&quot;search-suggestions-no-results&quot;&gt; &lt;p&gt;' . __('Sorry, no results found', 'text-domain') . '&lt;/p&gt; &lt;/div&gt;'; endif; ?&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 373180, "author": "Jagruti Rakholiya", "author_id": 193235, "author_profile": "https://wordpress.stackexchange.com/users/193235", "pm_score": 0, "selected": false, "text": "<p>You can use this to add permalink</p>\n<pre><code>echo get_permalink( get_page_by_title( $title, OBJECT, $type ) )\n</code></pre>\n" }, { "answer_id": 373224, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n<p>Replace</p>\n<pre><code>$posts_titles[$type][] = get_the_title();\n</code></pre>\n<p>With</p>\n<pre><code>$posts_titles[$type][] = array(get_the_title(),get_the_permalink());\n</code></pre>\n<p>And then your foreach outputting the links becomes</p>\n<pre><code>&lt;?php foreach($posts_titles[$type] as $link) : ?&gt;\n &lt;li class=&quot;search-item&quot;&gt;\n &lt;a href=&quot;&lt;?php _e($link[1]);?&gt;&quot;&gt;&lt;?php echo htmlspecialchars($link[0]); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n&lt;?php endforeach; ?&gt;\n</code></pre>\n" }, { "answer_id": 373239, "author": "drcrow", "author_id": 178234, "author_profile": "https://wordpress.stackexchange.com/users/178234", "pm_score": 0, "selected": false, "text": "<p>Replace:</p>\n<pre><code>$posts_titles[$type][] = get_the_title();\n</code></pre>\n<p>With:</p>\n<pre><code>$posts_titles[$type][get_the_ID()] = get_the_title();\n</code></pre>\n<p>So you will have the post ID in your foreach:</p>\n<pre><code>foreach($posts_titles[$type] as $ID =&gt; $title)\n</code></pre>\n<p>Finally you can do:</p>\n<pre><code>get_permalink($ID);\n</code></pre>\n" }, { "answer_id": 373265, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 3, "selected": true, "text": "<p>I would try a somewhat different approach.</p>\n<p>I would move the array of post types to your new WP_Query (since you are working with a limited defined set), and then below where you're looping through each post type in your first foreach statement, I would setup a second query to get all posts found within each $type. If you need to access non-standard postdata (i.e. custom metadata), use global $post, otherwise you don't need it.</p>\n<p>That way you can use the_permalink.</p>\n<p>Modify your new WP_Query like so:</p>\n<pre><code>$search_query = new WP_Query(\narray(\n 'posts_per_page' =&gt; -1,\n 's' =&gt; esc_attr($_GET['s']),\n 'post_status' =&gt; 'publish',\n 'post_type' =&gt; array( 'post', 'page', 'glossary' )\n )\n);\n</code></pre>\n<p>Then, you can get rid of all the stuff directly below your opening div for your search-results-list and just skip to this:</p>\n<pre><code>foreach($types as $type) : \n\necho '&lt;ul class=&quot;' . $type . '&quot;&gt;';\n while( have_posts() ) {\n the_post();\n if( $type == get_post_type() ){ ?&gt;\n \n &lt;div class=&quot;entry-content&quot;&gt;\n&lt;?php if ( has_post_thumbnail() ) { ?&gt;\n&lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot; title=&quot;&lt;?php echo esc_attr( sprintf( esc_html__( 'Permalink to %s', 'quark' ), the_title_attribute( 'echo=0' ) ) ); ?&gt;&quot;&gt;\n&lt;?php the_post_thumbnail( array(100,100) ); ?&gt;\n&lt;/a&gt;\n&lt;?php } ?&gt;\n&lt;?php the_excerpt(); ?&gt;\n \n &lt;?php \n } \n rewind_posts(); \n \n echo '&lt;/ul&gt;';\n\nendforeach; \n?&gt;\n</code></pre>\n<p>OR Alternatively if you want to keep to WP's newer way of organizing content/templates, you could have a separate template part for each post type with it's own style options, etc.</p>\n<pre><code>echo '&lt;ul class=&quot;' . $type . '&quot;&gt;';\n while( have_posts() ) {\n the_post();\n if( $type == get_post_type() ){\n get_template_part('content', 'search' . $type);\n } \n rewind_posts(); \n \n echo '&lt;/ul&gt;';\n\nendforeach; \n</code></pre>\n" } ]
2020/08/14
[ "https://wordpress.stackexchange.com/questions/373042", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13286/" ]
I am using **Option 3** from [this answer](https://wordpress.stackexchange.com/a/333920) as my source. So far it is working great, it is splitting my search results by post type and listing the posts from each post type in their own sections. The only problem is that this solution does not appear to allow for hyperlinking the post titles using `the_permalink();` How can I adapt this code so that I can also wrap the post titles in an anchor tag that will direct to the post? ``` <?php get_header(); ?> <?php $search_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr($_GET['s']), 'post_status' => 'publish' ) ); if ($search_query->have_posts()) : ?> <section id="search-results"> <div class="container"> <div class="row"> <div class="col"> <h2><?php echo $search_query->found_posts.' Search results found'; ?> for: "<?php echo get_search_query(); ?>"</h2> </div> </div> <div class="search-results-list"> <?php $types = array( 'post', 'page', 'glossary' ); $posts_titles = []; while($search_query->have_posts()) { $search_query->the_post(); $type = $search_query->post->post_type; if (!isset($posts_titles[$type])) $posts_titles[$type] = []; $posts_titles[$type][] = get_the_title(); } rewind_posts(); foreach($types as $type) : if (!isset($posts_titles[$type])) continue; ?> <div class="row"> <h3> <?php $post_type_obj = get_post_type_object($type); echo $post_type_obj->labels->name ?> </h3> </div> <div class="row"> <div class="col"> <ul> <?php foreach($posts_titles[$type] as $title) : ?> <li class="search-item"> <a href="PERMALINK SHOULD GO HERE"><?php echo htmlspecialchars($title); ?></a> </li> <?php endforeach; ?> </ul> </div> </div> <?php endforeach; ?> </div> </div> </section> <?php else: echo '<div class="search-suggestions-no-results"> <p>' . __('Sorry, no results found', 'text-domain') . '</p> </div>'; endif; ?> <?php get_footer(); ?> ```
I would try a somewhat different approach. I would move the array of post types to your new WP\_Query (since you are working with a limited defined set), and then below where you're looping through each post type in your first foreach statement, I would setup a second query to get all posts found within each $type. If you need to access non-standard postdata (i.e. custom metadata), use global $post, otherwise you don't need it. That way you can use the\_permalink. Modify your new WP\_Query like so: ``` $search_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr($_GET['s']), 'post_status' => 'publish', 'post_type' => array( 'post', 'page', 'glossary' ) ) ); ``` Then, you can get rid of all the stuff directly below your opening div for your search-results-list and just skip to this: ``` foreach($types as $type) : echo '<ul class="' . $type . '">'; while( have_posts() ) { the_post(); if( $type == get_post_type() ){ ?> <div class="entry-content"> <?php if ( has_post_thumbnail() ) { ?> <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( esc_html__( 'Permalink to %s', 'quark' ), the_title_attribute( 'echo=0' ) ) ); ?>"> <?php the_post_thumbnail( array(100,100) ); ?> </a> <?php } ?> <?php the_excerpt(); ?> <?php } rewind_posts(); echo '</ul>'; endforeach; ?> ``` OR Alternatively if you want to keep to WP's newer way of organizing content/templates, you could have a separate template part for each post type with it's own style options, etc. ``` echo '<ul class="' . $type . '">'; while( have_posts() ) { the_post(); if( $type == get_post_type() ){ get_template_part('content', 'search' . $type); } rewind_posts(); echo '</ul>'; endforeach; ```
373,064
<p>I'm not an expert in PHP and I'm trying to apply conditional formatting on data fetched from wpdb. To be fair, I'm trying to create shortcode for this. My motto is to fetch values for $previous_marks &amp; $current_marks from the database and change the color of $current_marks according to if, else condition. According to condition:</p> <ul> <li>If $current_marks &gt; $previous_marks, then value of $current_marks should be displayed in <em>green</em> color along with pass.png image next to the value.</li> <li>Else value of $current_marks should be displayed in <em>red</em> color along with fail.png image next to the value.</li> </ul> <p>I also need help in displaying images next to $current_marks value &amp; I have no code for it:</p> <p>Here's how my code looks like:</p> <pre><code> add_shortcode( 'marks_col', function () { $subject = $_GET['subject']; global $wpdb; $previous_marks = $wpdb-&gt;get_results( &quot;SELECT prev FROM grade WHERE sub='&quot; .$subject. &quot;'&quot;); $current_marks = $wpdb-&gt;get_results( &quot;SELECT current FROM grade WHERE sub='&quot; .$subject. &quot;'&quot;); if ($previous_marks &lt; $current_marks) { echo &quot;&lt;p style=&quot;color:green&quot;&gt;&quot; .$current_marks. &quot;&lt;/p&gt;&quot;; ##display pass.png next to $current_marks value } else { echo &quot;&lt;p style=&quot;color:red&quot;&gt;&quot; .$current_marks. &quot;&lt;/p&gt;&quot;; ##display fail.png next to $current_marks value } } ); </code></pre> <p>$subject is fetched from the website's URL: <a href="http://www.domain.com/results?subject=biology" rel="nofollow noreferrer">www.domain.com/results?subject=biology</a>. Currently, on using the shortcode <strong>[marks_col]</strong> on WP installation, it's just printing 'Array' in red color &amp; nothing else. Any help would be greatly appreciated.</p>
[ { "answer_id": 373180, "author": "Jagruti Rakholiya", "author_id": 193235, "author_profile": "https://wordpress.stackexchange.com/users/193235", "pm_score": 0, "selected": false, "text": "<p>You can use this to add permalink</p>\n<pre><code>echo get_permalink( get_page_by_title( $title, OBJECT, $type ) )\n</code></pre>\n" }, { "answer_id": 373224, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n<p>Replace</p>\n<pre><code>$posts_titles[$type][] = get_the_title();\n</code></pre>\n<p>With</p>\n<pre><code>$posts_titles[$type][] = array(get_the_title(),get_the_permalink());\n</code></pre>\n<p>And then your foreach outputting the links becomes</p>\n<pre><code>&lt;?php foreach($posts_titles[$type] as $link) : ?&gt;\n &lt;li class=&quot;search-item&quot;&gt;\n &lt;a href=&quot;&lt;?php _e($link[1]);?&gt;&quot;&gt;&lt;?php echo htmlspecialchars($link[0]); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n&lt;?php endforeach; ?&gt;\n</code></pre>\n" }, { "answer_id": 373239, "author": "drcrow", "author_id": 178234, "author_profile": "https://wordpress.stackexchange.com/users/178234", "pm_score": 0, "selected": false, "text": "<p>Replace:</p>\n<pre><code>$posts_titles[$type][] = get_the_title();\n</code></pre>\n<p>With:</p>\n<pre><code>$posts_titles[$type][get_the_ID()] = get_the_title();\n</code></pre>\n<p>So you will have the post ID in your foreach:</p>\n<pre><code>foreach($posts_titles[$type] as $ID =&gt; $title)\n</code></pre>\n<p>Finally you can do:</p>\n<pre><code>get_permalink($ID);\n</code></pre>\n" }, { "answer_id": 373265, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 3, "selected": true, "text": "<p>I would try a somewhat different approach.</p>\n<p>I would move the array of post types to your new WP_Query (since you are working with a limited defined set), and then below where you're looping through each post type in your first foreach statement, I would setup a second query to get all posts found within each $type. If you need to access non-standard postdata (i.e. custom metadata), use global $post, otherwise you don't need it.</p>\n<p>That way you can use the_permalink.</p>\n<p>Modify your new WP_Query like so:</p>\n<pre><code>$search_query = new WP_Query(\narray(\n 'posts_per_page' =&gt; -1,\n 's' =&gt; esc_attr($_GET['s']),\n 'post_status' =&gt; 'publish',\n 'post_type' =&gt; array( 'post', 'page', 'glossary' )\n )\n);\n</code></pre>\n<p>Then, you can get rid of all the stuff directly below your opening div for your search-results-list and just skip to this:</p>\n<pre><code>foreach($types as $type) : \n\necho '&lt;ul class=&quot;' . $type . '&quot;&gt;';\n while( have_posts() ) {\n the_post();\n if( $type == get_post_type() ){ ?&gt;\n \n &lt;div class=&quot;entry-content&quot;&gt;\n&lt;?php if ( has_post_thumbnail() ) { ?&gt;\n&lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot; title=&quot;&lt;?php echo esc_attr( sprintf( esc_html__( 'Permalink to %s', 'quark' ), the_title_attribute( 'echo=0' ) ) ); ?&gt;&quot;&gt;\n&lt;?php the_post_thumbnail( array(100,100) ); ?&gt;\n&lt;/a&gt;\n&lt;?php } ?&gt;\n&lt;?php the_excerpt(); ?&gt;\n \n &lt;?php \n } \n rewind_posts(); \n \n echo '&lt;/ul&gt;';\n\nendforeach; \n?&gt;\n</code></pre>\n<p>OR Alternatively if you want to keep to WP's newer way of organizing content/templates, you could have a separate template part for each post type with it's own style options, etc.</p>\n<pre><code>echo '&lt;ul class=&quot;' . $type . '&quot;&gt;';\n while( have_posts() ) {\n the_post();\n if( $type == get_post_type() ){\n get_template_part('content', 'search' . $type);\n } \n rewind_posts(); \n \n echo '&lt;/ul&gt;';\n\nendforeach; \n</code></pre>\n" } ]
2020/08/15
[ "https://wordpress.stackexchange.com/questions/373064", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/180322/" ]
I'm not an expert in PHP and I'm trying to apply conditional formatting on data fetched from wpdb. To be fair, I'm trying to create shortcode for this. My motto is to fetch values for $previous\_marks & $current\_marks from the database and change the color of $current\_marks according to if, else condition. According to condition: * If $current\_marks > $previous\_marks, then value of $current\_marks should be displayed in *green* color along with pass.png image next to the value. * Else value of $current\_marks should be displayed in *red* color along with fail.png image next to the value. I also need help in displaying images next to $current\_marks value & I have no code for it: Here's how my code looks like: ``` add_shortcode( 'marks_col', function () { $subject = $_GET['subject']; global $wpdb; $previous_marks = $wpdb->get_results( "SELECT prev FROM grade WHERE sub='" .$subject. "'"); $current_marks = $wpdb->get_results( "SELECT current FROM grade WHERE sub='" .$subject. "'"); if ($previous_marks < $current_marks) { echo "<p style="color:green">" .$current_marks. "</p>"; ##display pass.png next to $current_marks value } else { echo "<p style="color:red">" .$current_marks. "</p>"; ##display fail.png next to $current_marks value } } ); ``` $subject is fetched from the website's URL: [www.domain.com/results?subject=biology](http://www.domain.com/results?subject=biology). Currently, on using the shortcode **[marks\_col]** on WP installation, it's just printing 'Array' in red color & nothing else. Any help would be greatly appreciated.
I would try a somewhat different approach. I would move the array of post types to your new WP\_Query (since you are working with a limited defined set), and then below where you're looping through each post type in your first foreach statement, I would setup a second query to get all posts found within each $type. If you need to access non-standard postdata (i.e. custom metadata), use global $post, otherwise you don't need it. That way you can use the\_permalink. Modify your new WP\_Query like so: ``` $search_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr($_GET['s']), 'post_status' => 'publish', 'post_type' => array( 'post', 'page', 'glossary' ) ) ); ``` Then, you can get rid of all the stuff directly below your opening div for your search-results-list and just skip to this: ``` foreach($types as $type) : echo '<ul class="' . $type . '">'; while( have_posts() ) { the_post(); if( $type == get_post_type() ){ ?> <div class="entry-content"> <?php if ( has_post_thumbnail() ) { ?> <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( esc_html__( 'Permalink to %s', 'quark' ), the_title_attribute( 'echo=0' ) ) ); ?>"> <?php the_post_thumbnail( array(100,100) ); ?> </a> <?php } ?> <?php the_excerpt(); ?> <?php } rewind_posts(); echo '</ul>'; endforeach; ?> ``` OR Alternatively if you want to keep to WP's newer way of organizing content/templates, you could have a separate template part for each post type with it's own style options, etc. ``` echo '<ul class="' . $type . '">'; while( have_posts() ) { the_post(); if( $type == get_post_type() ){ get_template_part('content', 'search' . $type); } rewind_posts(); echo '</ul>'; endforeach; ```
373,141
<p>I have an archive page that pulls in posts using <code>WP_Query()</code>. On the homepage of the site it shows 16 of the custom post type posts, so on the archive I offset the archive page by 16 posts.</p> <p>The code for this is:</p> <pre><code>$newsArticles = new WP_Query(array( 'posts_per_page' =&gt; 16, 'offset' =&gt; 16, 'post_type'=&gt; 'news' )); while( $newsArticles-&gt;have_posts()){ $newsArticles-&gt;the_post(); ?&gt; // HTML &lt;?php } ?&gt; </code></pre> <p>However on this archive page the <code>&lt;?php echo paginate_links();?&gt;</code> function to show the pagination pages doesn't work. When I click on the page numbers or use the next and previous arrows, but it just shows the same posts on each page.</p> <p>The pagination code I'm using is:</p> <pre><code>&lt;p&gt; &lt;?php echo paginate_links(array( 'prev_text' =&gt; 'NEWER', 'next_text' =&gt; 'OLDER', ));?&gt; &lt;/p&gt; </code></pre> <p>Does anybody know how I get the pagination to work with the <code>WP_Query()</code> property <code>offset</code> so the archive pagination behaves like a normal archive page (with pagination) ?</p>
[ { "answer_id": 373180, "author": "Jagruti Rakholiya", "author_id": 193235, "author_profile": "https://wordpress.stackexchange.com/users/193235", "pm_score": 0, "selected": false, "text": "<p>You can use this to add permalink</p>\n<pre><code>echo get_permalink( get_page_by_title( $title, OBJECT, $type ) )\n</code></pre>\n" }, { "answer_id": 373224, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n<p>Replace</p>\n<pre><code>$posts_titles[$type][] = get_the_title();\n</code></pre>\n<p>With</p>\n<pre><code>$posts_titles[$type][] = array(get_the_title(),get_the_permalink());\n</code></pre>\n<p>And then your foreach outputting the links becomes</p>\n<pre><code>&lt;?php foreach($posts_titles[$type] as $link) : ?&gt;\n &lt;li class=&quot;search-item&quot;&gt;\n &lt;a href=&quot;&lt;?php _e($link[1]);?&gt;&quot;&gt;&lt;?php echo htmlspecialchars($link[0]); ?&gt;&lt;/a&gt;\n &lt;/li&gt;\n&lt;?php endforeach; ?&gt;\n</code></pre>\n" }, { "answer_id": 373239, "author": "drcrow", "author_id": 178234, "author_profile": "https://wordpress.stackexchange.com/users/178234", "pm_score": 0, "selected": false, "text": "<p>Replace:</p>\n<pre><code>$posts_titles[$type][] = get_the_title();\n</code></pre>\n<p>With:</p>\n<pre><code>$posts_titles[$type][get_the_ID()] = get_the_title();\n</code></pre>\n<p>So you will have the post ID in your foreach:</p>\n<pre><code>foreach($posts_titles[$type] as $ID =&gt; $title)\n</code></pre>\n<p>Finally you can do:</p>\n<pre><code>get_permalink($ID);\n</code></pre>\n" }, { "answer_id": 373265, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": 3, "selected": true, "text": "<p>I would try a somewhat different approach.</p>\n<p>I would move the array of post types to your new WP_Query (since you are working with a limited defined set), and then below where you're looping through each post type in your first foreach statement, I would setup a second query to get all posts found within each $type. If you need to access non-standard postdata (i.e. custom metadata), use global $post, otherwise you don't need it.</p>\n<p>That way you can use the_permalink.</p>\n<p>Modify your new WP_Query like so:</p>\n<pre><code>$search_query = new WP_Query(\narray(\n 'posts_per_page' =&gt; -1,\n 's' =&gt; esc_attr($_GET['s']),\n 'post_status' =&gt; 'publish',\n 'post_type' =&gt; array( 'post', 'page', 'glossary' )\n )\n);\n</code></pre>\n<p>Then, you can get rid of all the stuff directly below your opening div for your search-results-list and just skip to this:</p>\n<pre><code>foreach($types as $type) : \n\necho '&lt;ul class=&quot;' . $type . '&quot;&gt;';\n while( have_posts() ) {\n the_post();\n if( $type == get_post_type() ){ ?&gt;\n \n &lt;div class=&quot;entry-content&quot;&gt;\n&lt;?php if ( has_post_thumbnail() ) { ?&gt;\n&lt;a href=&quot;&lt;?php the_permalink(); ?&gt;&quot; title=&quot;&lt;?php echo esc_attr( sprintf( esc_html__( 'Permalink to %s', 'quark' ), the_title_attribute( 'echo=0' ) ) ); ?&gt;&quot;&gt;\n&lt;?php the_post_thumbnail( array(100,100) ); ?&gt;\n&lt;/a&gt;\n&lt;?php } ?&gt;\n&lt;?php the_excerpt(); ?&gt;\n \n &lt;?php \n } \n rewind_posts(); \n \n echo '&lt;/ul&gt;';\n\nendforeach; \n?&gt;\n</code></pre>\n<p>OR Alternatively if you want to keep to WP's newer way of organizing content/templates, you could have a separate template part for each post type with it's own style options, etc.</p>\n<pre><code>echo '&lt;ul class=&quot;' . $type . '&quot;&gt;';\n while( have_posts() ) {\n the_post();\n if( $type == get_post_type() ){\n get_template_part('content', 'search' . $type);\n } \n rewind_posts(); \n \n echo '&lt;/ul&gt;';\n\nendforeach; \n</code></pre>\n" } ]
2020/08/17
[ "https://wordpress.stackexchange.com/questions/373141", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
I have an archive page that pulls in posts using `WP_Query()`. On the homepage of the site it shows 16 of the custom post type posts, so on the archive I offset the archive page by 16 posts. The code for this is: ``` $newsArticles = new WP_Query(array( 'posts_per_page' => 16, 'offset' => 16, 'post_type'=> 'news' )); while( $newsArticles->have_posts()){ $newsArticles->the_post(); ?> // HTML <?php } ?> ``` However on this archive page the `<?php echo paginate_links();?>` function to show the pagination pages doesn't work. When I click on the page numbers or use the next and previous arrows, but it just shows the same posts on each page. The pagination code I'm using is: ``` <p> <?php echo paginate_links(array( 'prev_text' => 'NEWER', 'next_text' => 'OLDER', ));?> </p> ``` Does anybody know how I get the pagination to work with the `WP_Query()` property `offset` so the archive pagination behaves like a normal archive page (with pagination) ?
I would try a somewhat different approach. I would move the array of post types to your new WP\_Query (since you are working with a limited defined set), and then below where you're looping through each post type in your first foreach statement, I would setup a second query to get all posts found within each $type. If you need to access non-standard postdata (i.e. custom metadata), use global $post, otherwise you don't need it. That way you can use the\_permalink. Modify your new WP\_Query like so: ``` $search_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr($_GET['s']), 'post_status' => 'publish', 'post_type' => array( 'post', 'page', 'glossary' ) ) ); ``` Then, you can get rid of all the stuff directly below your opening div for your search-results-list and just skip to this: ``` foreach($types as $type) : echo '<ul class="' . $type . '">'; while( have_posts() ) { the_post(); if( $type == get_post_type() ){ ?> <div class="entry-content"> <?php if ( has_post_thumbnail() ) { ?> <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( esc_html__( 'Permalink to %s', 'quark' ), the_title_attribute( 'echo=0' ) ) ); ?>"> <?php the_post_thumbnail( array(100,100) ); ?> </a> <?php } ?> <?php the_excerpt(); ?> <?php } rewind_posts(); echo '</ul>'; endforeach; ?> ``` OR Alternatively if you want to keep to WP's newer way of organizing content/templates, you could have a separate template part for each post type with it's own style options, etc. ``` echo '<ul class="' . $type . '">'; while( have_posts() ) { the_post(); if( $type == get_post_type() ){ get_template_part('content', 'search' . $type); } rewind_posts(); echo '</ul>'; endforeach; ```
373,149
<p>I'm using a plugin from LinkedIn Learning to customize into my own plugin's custom Gutenberg blocks.</p> <p>After I've edited the file <code>plugin/src/index.js</code> (I edited the <code>edit()</code> &amp; <code>save()</code> functions), I now have:</p> <pre><code>const { __ } = wp.i18n; const { registerBlockType } = wp.blocks; // Import SVG as React component using @svgr/webpack. // https://www.npmjs.com/package/@svgr/webpack import { ReactComponent as Logo } from &quot;../bv-logo.svg&quot;; // Import file as base64 encoded URI using url-loader. // https://www.npmjs.com/package/url-loader import logoWhiteURL from &quot;../purity-logo.svg&quot;; // https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-registration/ registerBlockType(&quot;podkit/home-slider&quot;, { title: __(&quot;Home Slider&quot;, &quot;podkit&quot;), icon: { src: Logo }, category: &quot;podkit&quot;, // https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-edit-save/ edit() { return ( &lt;section class=&quot;ad-waypoint&quot; data-animate-down=&quot;site-primary-menu-lrg&quot; data-animate-up=&quot;site-primary-menu-lrg&quot;&gt; &lt;div class=&quot;sec-zero-wrapper&quot;&gt; &lt;div class=&quot;item&quot;&gt; &lt;div class=&quot;lSSlideOuter &quot;&gt; &lt;div class=&quot;lSSlideWrapper&quot;&gt; &lt;ul class=&quot;home-slider content-slider lightSlider lSFade&quot; style=&quot;height: 0px; padding-bottom: 71.9931%;&quot;&gt; &lt;li class=&quot;lslide&quot; style=&quot;display: none;&quot;&gt;&lt;div class=&quot;sec-zero-bg&quot; style=&quot;background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/bag-packer_250767238-opt2.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;&quot;&gt;&lt;/div&gt;&lt;/li&gt; &lt;li class=&quot;lslide active&quot; style=&quot;display: list-item;&quot;&gt;&lt;div class=&quot;sec-zero-bg&quot; style=&quot;background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_43604071-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;&quot;&gt;&lt;/div&gt;&lt;/li&gt; &lt;li class=&quot;lslide&quot; style=&quot;display: none;&quot;&gt;&lt;div class=&quot;sec-zero-bg&quot; style=&quot;background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_123343987-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;&quot;&gt;&lt;/div&gt;&lt;/li&gt; &lt;li class=&quot;lslide&quot; style=&quot;display: none;&quot;&gt;&lt;div class=&quot;sec-zero-bg&quot; style=&quot;background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/wind-turbines_13504843-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;&quot;&gt;&lt;/div&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;ul class=&quot;lSPager lSpg&quot; style=&quot;margin-top: 5px;&quot; &gt;&lt;li class=&quot;&quot;&gt;&lt;a href=&quot;#&quot;&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;active&quot;&gt;&lt;a href=&quot;#&quot;&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;4&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;sec-zero-thematic&quot;&gt; &lt;img src={logoWhiteURL} alt=&quot;main-brand-logo&quot;/&gt; &lt;h3&gt;imagination is only the begining&lt;/h3&gt; &lt;/div&gt; &lt;div class=&quot;secondary-menu&quot;&gt; &lt;div class=&quot;center&quot;&gt; &lt;div class=&quot;content-container&quot;&gt; &lt;div style=&quot;margin-top:148px; position:absolute; width: calc(100% - 40px);&quot; class=&quot;nav-rule&quot;&gt;&lt;/div&gt; &lt;div class=&quot;site-navigation-head-btm&quot;&gt; &lt;div class=&quot;site-navigation-head-btm-25&quot;&gt; &lt;div class=&quot;menu-primary-bottom-menu-container&quot;&gt; &lt;ul id=&quot;menu-primary-bottom-menu&quot; class=&quot;menu&quot;&gt; &lt;li id=&quot;menu-item-1124&quot; class=&quot;menu-item menu-item-type-custom menu-item-object-custom menu-item-1124&quot;&gt;&lt;a&gt;Our clients&lt;/a&gt;&lt;/li&gt; &lt;li id=&quot;menu-item-1125&quot; class=&quot;menu-item menu-item-type-custom menu-item-object-custom menu-item-1125&quot;&gt;&lt;a&gt;Relationships&lt;/a&gt;&lt;/li&gt; &lt;li id=&quot;menu-item-1132&quot; class=&quot;menu-item menu-item-type-custom menu-item-object-custom menu-item-1132&quot;&gt;&lt;a&gt;Products&lt;/a&gt;&lt;/li&gt; &lt;li id=&quot;menu-item-1133&quot; class=&quot;menu-item menu-item-type-custom menu-item-object-custom menu-item-1133&quot;&gt;&lt;a&gt;Latest News&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; ); }, save() { return ( &lt;section class=&quot;ad-waypoint&quot; data-animate-down=&quot;site-primary-menu-lrg&quot; data-animate-up=&quot;site-primary-menu-lrg&quot;&gt; &lt;div class=&quot;sec-zero-wrapper&quot;&gt; &lt;div class=&quot;item&quot;&gt; &lt;div class=&quot;lSSlideOuter &quot;&gt; &lt;div class=&quot;lSSlideWrapper&quot;&gt; &lt;ul class=&quot;home-slider content-slider lightSlider lSFade&quot; style=&quot;height: 0px; padding-bottom: 71.9931%;&quot;&gt; &lt;li class=&quot;lslide&quot; style=&quot;display: none;&quot;&gt;&lt;div class=&quot;sec-zero-bg&quot; style=&quot;background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/bag-packer_250767238-opt2.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;&quot;&gt;&lt;/div&gt;&lt;/li&gt; &lt;li class=&quot;lslide active&quot; style=&quot;display: list-item;&quot;&gt;&lt;div class=&quot;sec-zero-bg&quot; style=&quot;background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_43604071-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;&quot;&gt;&lt;/div&gt;&lt;/li&gt; &lt;li class=&quot;lslide&quot; style=&quot;display: none;&quot;&gt;&lt;div class=&quot;sec-zero-bg&quot; style=&quot;background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_123343987-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;&quot;&gt;&lt;/div&gt;&lt;/li&gt; &lt;li class=&quot;lslide&quot; style=&quot;display: none;&quot;&gt;&lt;div class=&quot;sec-zero-bg&quot; style=&quot;background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/wind-turbines_13504843-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;&quot;&gt;&lt;/div&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;ul class=&quot;lSPager lSpg&quot; style=&quot;margin-top: 5px;&quot; &gt;&lt;li class=&quot;&quot;&gt;&lt;a href=&quot;#&quot;&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li class=&quot;active&quot;&gt;&lt;a href=&quot;#&quot;&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#&quot;&gt;4&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;sec-zero-thematic&quot;&gt; &lt;img src={logoWhiteURL} alt=&quot;main-brand-logo&quot; /&gt; &lt;h3&gt;imagination is only the begining&lt;/h3&gt; &lt;/div&gt; &lt;div class=&quot;secondary-menu&quot;&gt; &lt;div class=&quot;center&quot;&gt; &lt;div class=&quot;content-container&quot;&gt; &lt;div style=&quot;margin-top:148px; position:absolute; width: calc(100% - 40px);&quot; class=&quot;nav-rule&quot;&gt;&lt;/div&gt; &lt;div class=&quot;site-navigation-head-btm&quot;&gt; &lt;div class=&quot;site-navigation-head-btm-25&quot;&gt; &lt;div class=&quot;menu-primary-bottom-menu-container&quot;&gt; &lt;ul id=&quot;menu-primary-bottom-menu&quot; class=&quot;menu&quot;&gt; &lt;li id=&quot;menu-item-1124&quot; class=&quot;menu-item menu-item-type-custom menu-item-object-custom menu-item-1124&quot;&gt;&lt;a&gt;Our clients&lt;/a&gt;&lt;/li&gt; &lt;li id=&quot;menu-item-1125&quot; class=&quot;menu-item menu-item-type-custom menu-item-object-custom menu-item-1125&quot;&gt;&lt;a&gt;Relationships&lt;/a&gt;&lt;/li&gt; &lt;li id=&quot;menu-item-1132&quot; class=&quot;menu-item menu-item-type-custom menu-item-object-custom menu-item-1132&quot;&gt;&lt;a&gt;Products&lt;/a&gt;&lt;/li&gt; &lt;li id=&quot;menu-item-1133&quot; class=&quot;menu-item menu-item-type-custom menu-item-object-custom menu-item-1133&quot;&gt;&lt;a&gt;Latest News&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; ) } }); </code></pre> <p>In Microsoft Visual Code, I am running the process <code>wp-scripts start</code> which recompiles the plugin after every save I believe. This process originally found some syntax errors for me, but I receive no more syntax errors in the output of <code>wp-scripts start</code>.</p> <p>In a local dev WP site, when I try to add the new block, I receive an error:</p> <blockquote> <p>This block has encountered an error and cannot be previewed</p> </blockquote> <p>At the same time as adding the new block, in the Chrome console, I see:</p> <pre><code>Error: Minified React error #62; visit https://reactjs.org/docs/error-decoder.html?invariant=62&amp;args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings. at Pd (react-dom.min.js?ver=16.9.0:47) at nh (react-dom.min.js?ver=16.9.0:132) at lh (react-dom.min.js?ver=16.9.0:126) at O (react-dom.min.js?ver=16.9.0:121) at ze (react-dom.min.js?ver=16.9.0:118) at react-dom.min.js?ver=16.9.0:53 at unstable_runWithPriority (react.min.js?ver=16.9.0:26) at Ma (react-dom.min.js?ver=16.9.0:52) at mg (react-dom.min.js?ver=16.9.0:52) at V (react-dom.min.js?ver=16.9.0:52) </code></pre> <p>which I'm having trouble understanding.</p> <p>I've set:</p> <pre><code>define( 'WP_DEBUG', true ); define( 'WP_DEBUG_LOG', true ); define( 'WP_DEBUG_DISPLAY', true ); </code></pre> <p>but there is no output on screen or in a debug log.</p> <p>I've searched online for the error, and most solutions involve updating WordPress or disabling plugins. I only have Akismet &amp; MainWP child, plus the plugin to produce the custom blocks.</p> <p>Disabling Akismet &amp; MainWP child does not resolve the issue.</p> <p>How would I go about troubleshooting this error?</p> <p>Help appreciated.</p>
[ { "answer_id": 373248, "author": "Will", "author_id": 48698, "author_profile": "https://wordpress.stackexchange.com/users/48698", "pm_score": 1, "selected": false, "text": "<p>Add this additional variable to your wp-config file:</p>\n<pre><code>define ( 'SCRIPT_DEBUG', true); \n</code></pre>\n<p>Also, <a href=\"https://reactjs.org/docs/dom-elements.html#style\" rel=\"nofollow noreferrer\">inline styling directly in react is declared differently</a> is similar but different in many ways than pure, vanilla CSS.</p>\n<p>For example, <code>&lt;ul class=&quot;home-slider content-slider lightSlider lSFade&quot; style=&quot;height: 0px; padding-bottom: 71.9931%;&quot;&gt;</code></p>\n<p>is written in react as:</p>\n<p><code>&lt;ul className={ 'home-slider content-slider lightSlider lSFade'} style={{ paddingBottom: '71.9931%', height: 0}}&gt; {'your content'} &lt;/ul&gt;</code>\n(my react code may not be exactly correct!)</p>\n<p>As the above link notes, I would recommend to style your css in a separate file (which is already created for you in wp-scripts) instead of directly within react.</p>\n" }, { "answer_id": 373250, "author": "wbq", "author_id": 165265, "author_profile": "https://wordpress.stackexchange.com/users/165265", "pm_score": 0, "selected": false, "text": "<p>From my personal experience this doesn't go along well together:</p>\n<pre><code>const { __ } = wp.i18n;\nconst { registerBlockType } = wp.blocks;\n\n\nimport { ReactComponent as Logo } from &quot;../bv-logo.svg&quot;;\n\n\nimport logoWhiteURL from &quot;../purity-logo.svg&quot;;\n\n</code></pre>\n<p><code>Destructuring</code> and <code>import</code> gave me the described error.</p>\n<p>Got it fixed by recreating the SVGs like so:</p>\n<pre><code>\nconst logo = el(wp.primitives.SVG,\n {width: 20, height: 20, viewBox: '0 0 64 64'},\n el('g',\n {\n 'fill-rule': 'evenodd',\n fill: 'none',\n },\n el('path', {\n fill: '#3B414C',\n d: 'M-102-193h600v450h-600z',\n }),\n el('g', {\n fill: '#2FC5C0',\n 'fill-rule': 'nonzero',\n },\n el('path', {\n d: 'M0 0v63.096h63.096V0H0zm60.588 60.588H2.508V2.508h58.08v58.08z',\n }),\n el('path', {\n d: 'M24.156 44.748l.924 2.508 3.168-7.524-.132-.396s-5.808-15.048-7.788-20.196l-.264-.66h-6.072l.528 1.452c3.168 8.316 9.636 24.816 9.636 24.816zM36.696 44.748l.924 2.508 3.168-7.524-.132-.396s-5.808-15.048-7.788-20.196l-.264-.66h-6.072l.528 1.452c3.3 8.316 9.636 24.816 9.636 24.816zM47.388 18.48h-6.996l3.564 9.24z',\n }),\n ),\n ),\n);\nupdateCategory('my-blocks', {icon: logo});\n</code></pre>\n<p>If you have JSX Compilation running you could also try to do this:</p>\n<pre><code>registerBlockType(&quot;podkit/home-slider&quot;, {\n title: __(&quot;Home Slider&quot;, &quot;podkit&quot;),\n icon: \n &lt;svg width=&quot;20&quot; height=&quot;10&quot; viewBox=&quot;0 0 20 10&quot; fill=&quot;none&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;&lt;path d=&quot;M18.75 5.162h-18M15 1.196l3.75 3.966L15 9.13&quot; stroke=&quot;#e0004d&quot; stroke-width=&quot;1.5&quot; stroke-linejoin=&quot;round&quot;/&gt;&lt;/svg&gt;,\n\n ...\n});\n</code></pre>\n" } ]
2020/08/17
[ "https://wordpress.stackexchange.com/questions/373149", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147186/" ]
I'm using a plugin from LinkedIn Learning to customize into my own plugin's custom Gutenberg blocks. After I've edited the file `plugin/src/index.js` (I edited the `edit()` & `save()` functions), I now have: ``` const { __ } = wp.i18n; const { registerBlockType } = wp.blocks; // Import SVG as React component using @svgr/webpack. // https://www.npmjs.com/package/@svgr/webpack import { ReactComponent as Logo } from "../bv-logo.svg"; // Import file as base64 encoded URI using url-loader. // https://www.npmjs.com/package/url-loader import logoWhiteURL from "../purity-logo.svg"; // https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-registration/ registerBlockType("podkit/home-slider", { title: __("Home Slider", "podkit"), icon: { src: Logo }, category: "podkit", // https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-edit-save/ edit() { return ( <section class="ad-waypoint" data-animate-down="site-primary-menu-lrg" data-animate-up="site-primary-menu-lrg"> <div class="sec-zero-wrapper"> <div class="item"> <div class="lSSlideOuter "> <div class="lSSlideWrapper"> <ul class="home-slider content-slider lightSlider lSFade" style="height: 0px; padding-bottom: 71.9931%;"> <li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/bag-packer_250767238-opt2.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li> <li class="lslide active" style="display: list-item;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_43604071-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li> <li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_123343987-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li> <li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/wind-turbines_13504843-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li> </ul> </div> <ul class="lSPager lSpg" style="margin-top: 5px;" ><li class=""><a href="#">1</a></li> <li class="active"><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> </ul> </div> </div> <div class="sec-zero-thematic"> <img src={logoWhiteURL} alt="main-brand-logo"/> <h3>imagination is only the begining</h3> </div> <div class="secondary-menu"> <div class="center"> <div class="content-container"> <div style="margin-top:148px; position:absolute; width: calc(100% - 40px);" class="nav-rule"></div> <div class="site-navigation-head-btm"> <div class="site-navigation-head-btm-25"> <div class="menu-primary-bottom-menu-container"> <ul id="menu-primary-bottom-menu" class="menu"> <li id="menu-item-1124" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1124"><a>Our clients</a></li> <li id="menu-item-1125" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1125"><a>Relationships</a></li> <li id="menu-item-1132" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1132"><a>Products</a></li> <li id="menu-item-1133" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1133"><a>Latest News</a></li> </ul> </div> </div> </div> </div> </div> </div> </div> </section> ); }, save() { return ( <section class="ad-waypoint" data-animate-down="site-primary-menu-lrg" data-animate-up="site-primary-menu-lrg"> <div class="sec-zero-wrapper"> <div class="item"> <div class="lSSlideOuter "> <div class="lSSlideWrapper"> <ul class="home-slider content-slider lightSlider lSFade" style="height: 0px; padding-bottom: 71.9931%;"> <li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/bag-packer_250767238-opt2.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li> <li class="lslide active" style="display: list-item;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_43604071-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li> <li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/shutterstock_123343987-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li> <li class="lslide" style="display: none;"><div class="sec-zero-bg" style="background: url('http://purity.insightcomdes.local/wp-content/uploads/2016/03/wind-turbines_13504843-opt.jpg') center center no-repeat; background-size:cover; background-attachment: fixed;"></div></li> </ul> </div> <ul class="lSPager lSpg" style="margin-top: 5px;" ><li class=""><a href="#">1</a></li> <li class="active"><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> </ul> </div> </div> <div class="sec-zero-thematic"> <img src={logoWhiteURL} alt="main-brand-logo" /> <h3>imagination is only the begining</h3> </div> <div class="secondary-menu"> <div class="center"> <div class="content-container"> <div style="margin-top:148px; position:absolute; width: calc(100% - 40px);" class="nav-rule"></div> <div class="site-navigation-head-btm"> <div class="site-navigation-head-btm-25"> <div class="menu-primary-bottom-menu-container"> <ul id="menu-primary-bottom-menu" class="menu"> <li id="menu-item-1124" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1124"><a>Our clients</a></li> <li id="menu-item-1125" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1125"><a>Relationships</a></li> <li id="menu-item-1132" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1132"><a>Products</a></li> <li id="menu-item-1133" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1133"><a>Latest News</a></li> </ul> </div> </div> </div> </div> </div> </div> </div> </section> ) } }); ``` In Microsoft Visual Code, I am running the process `wp-scripts start` which recompiles the plugin after every save I believe. This process originally found some syntax errors for me, but I receive no more syntax errors in the output of `wp-scripts start`. In a local dev WP site, when I try to add the new block, I receive an error: > > This block has encountered an error and cannot be previewed > > > At the same time as adding the new block, in the Chrome console, I see: ``` Error: Minified React error #62; visit https://reactjs.org/docs/error-decoder.html?invariant=62&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings. at Pd (react-dom.min.js?ver=16.9.0:47) at nh (react-dom.min.js?ver=16.9.0:132) at lh (react-dom.min.js?ver=16.9.0:126) at O (react-dom.min.js?ver=16.9.0:121) at ze (react-dom.min.js?ver=16.9.0:118) at react-dom.min.js?ver=16.9.0:53 at unstable_runWithPriority (react.min.js?ver=16.9.0:26) at Ma (react-dom.min.js?ver=16.9.0:52) at mg (react-dom.min.js?ver=16.9.0:52) at V (react-dom.min.js?ver=16.9.0:52) ``` which I'm having trouble understanding. I've set: ``` define( 'WP_DEBUG', true ); define( 'WP_DEBUG_LOG', true ); define( 'WP_DEBUG_DISPLAY', true ); ``` but there is no output on screen or in a debug log. I've searched online for the error, and most solutions involve updating WordPress or disabling plugins. I only have Akismet & MainWP child, plus the plugin to produce the custom blocks. Disabling Akismet & MainWP child does not resolve the issue. How would I go about troubleshooting this error? Help appreciated.
Add this additional variable to your wp-config file: ``` define ( 'SCRIPT_DEBUG', true); ``` Also, [inline styling directly in react is declared differently](https://reactjs.org/docs/dom-elements.html#style) is similar but different in many ways than pure, vanilla CSS. For example, `<ul class="home-slider content-slider lightSlider lSFade" style="height: 0px; padding-bottom: 71.9931%;">` is written in react as: `<ul className={ 'home-slider content-slider lightSlider lSFade'} style={{ paddingBottom: '71.9931%', height: 0}}> {'your content'} </ul>` (my react code may not be exactly correct!) As the above link notes, I would recommend to style your css in a separate file (which is already created for you in wp-scripts) instead of directly within react.
373,157
<p>I want to Add slider shortcodes. My all slider fields adds properly in shortcode, but the read more button and button link is not displaying. Can you please solve my problem? This my slider code:</p> <pre class="lang-php prettyprint-override"><code>&lt;section id=&quot;firstsection&quot;&gt; &lt;div class=&quot;container-fluid&quot;&gt; &lt;div class=&quot;col-xs-12 firstsection-maindiv&quot;&gt; &lt;?php $slide = array( 'post_type' =&gt; 'slider' ,); $slider_query = new WP_Query( $slide ); ?&gt; &lt;?php if( have_posts() ) : while($slider_query-&gt;have_posts() ) : $slider_query-&gt;the_post(); ?&gt; &lt;div id=&quot;explore-section&quot; class=&quot;owl-carousel owl-theme&quot;&gt; &lt;div class=&quot;item&quot;&gt; &lt;div class=&quot;col-xs-12 firstsection-innerdiv&quot;&gt; &lt;div class=&quot;col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-left-div&quot;&gt; &lt;p class=&quot;oneplace&quot;&gt;&lt;?php echo get_the_title(); ?&gt;&lt;/p&gt; &lt;p class=&quot;slider-content&quot;&gt;&lt;?php echo get_the_content(); ?&gt;&lt;/p&gt; &lt;?php $buttonname = get_post_meta($post-&gt;ID, &quot;wp_producer_name&quot; , true) ?&gt; &lt;?php $buttonlink = get_post_meta($post-&gt;ID, &quot;wp_button_link&quot; , true) ?&gt; &lt;button class=&quot;slider-btn&quot; type=&quot;button&quot;&gt;&lt;a href=&quot;&lt;?php echo $buttonlink ; ?&gt;&quot;&gt; &lt;?php echo $buttonname ; ?&gt;&lt;/a&gt;&lt;/button&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-right-div&quot;&gt; &lt;?php echo get_the_post_thumbnail(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <p>And this is my shortcodes code:</p> <pre class="lang-php prettyprint-override"><code>// Add Shortcode add_shortcode( 'valute-slider-shortcode', 'display_custom_post_type' ); function display_custom_post_type(){ $args = array( 'post_type' =&gt; 'Slider', 'post_status' =&gt; 'publish' ); $string = ''; $query = new WP_Query( $args ); if( $query-&gt;have_posts() ){ $string .= '&lt;section id=&quot;firstsection&quot;&gt;'; while( $query-&gt;have_posts() ){ $query-&gt;the_post(); $buttonname = get_post_meta($post-&gt;ID, &quot;wp_producer_name&quot; , true); if( !empty($buttonname) ): endif; $string .= '&lt;div class=&quot;container-fluid&quot;&gt;' . '&lt;div class=&quot;col-xs-12 firstsection-maindiv&quot;&gt;' . '&lt;div id=&quot;explore-section&quot; class=&quot;owl-carousel owl-theme&quot;&gt;' . '&lt;div class=&quot;item&quot;&gt;' . '&lt;div class=&quot;col-xs-12 firstsection-innerdiv&quot;&gt;' . ' &lt;div class=&quot;col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-left-div&quot;&gt;' . ' &lt;p class=&quot;oneplace&quot;&gt;' .get_the_title() . '&lt;/p&gt;'. ' &lt;p class=&quot;slider-content&quot;&gt;' .get_the_content() . '&lt;/p&gt;'. ' &lt;button class=&quot;slider-btn&quot; type=&quot;button&quot;&gt;' . $buttonname . '&lt;/button&gt;'. '&lt;/div&gt;' . ' &lt;div class=&quot;col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-right-div&quot;&gt;' . get_the_post_thumbnail() . '&lt;/div&gt;' . '&lt;/div&gt;' . '&lt;/div&gt;' . '&lt;/div&gt;' . '&lt;/div&gt;'; } $string .= '&lt;/section&gt;'; } wp_reset_postdata(); return $string; </code></pre>
[ { "answer_id": 373165, "author": "Jagruti Rakholiya", "author_id": 193235, "author_profile": "https://wordpress.stackexchange.com/users/193235", "pm_score": 2, "selected": true, "text": "<p>Use <code>get_the_ID()</code> instead of <code>$post-&gt;ID</code></p>\n<p>This will fix your problem</p>\n" }, { "answer_id": 373175, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 0, "selected": false, "text": "<p>You're using this to get the post ID:</p>\n<pre class=\"lang-php prettyprint-override\"><code> $buttonname = get_post_meta($post-&gt;ID, &quot;wp_producer_name&quot; , true);\n</code></pre>\n<p>But what is <code>$post</code>? PHP has never seen this before in this scope, so it resolves to an empty value, undefined/null/0. In order to use global variables, you have to declare them before using them.</p>\n<p>So there are 2 alternatives:</p>\n<ul>\n<li><code>global $post;</code></li>\n<li><code>get_the_ID()</code></li>\n</ul>\n" } ]
2020/08/17
[ "https://wordpress.stackexchange.com/questions/373157", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/183253/" ]
I want to Add slider shortcodes. My all slider fields adds properly in shortcode, but the read more button and button link is not displaying. Can you please solve my problem? This my slider code: ```php <section id="firstsection"> <div class="container-fluid"> <div class="col-xs-12 firstsection-maindiv"> <?php $slide = array( 'post_type' => 'slider' ,); $slider_query = new WP_Query( $slide ); ?> <?php if( have_posts() ) : while($slider_query->have_posts() ) : $slider_query->the_post(); ?> <div id="explore-section" class="owl-carousel owl-theme"> <div class="item"> <div class="col-xs-12 firstsection-innerdiv"> <div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-left-div"> <p class="oneplace"><?php echo get_the_title(); ?></p> <p class="slider-content"><?php echo get_the_content(); ?></p> <?php $buttonname = get_post_meta($post->ID, "wp_producer_name" , true) ?> <?php $buttonlink = get_post_meta($post->ID, "wp_button_link" , true) ?> <button class="slider-btn" type="button"><a href="<?php echo $buttonlink ; ?>"> <?php echo $buttonname ; ?></a></button> </div> <div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-right-div"> <?php echo get_the_post_thumbnail(); ?> </div> </div> </div> </div> <?php endwhile; endif; ?> </div> </div> </section> ``` And this is my shortcodes code: ```php // Add Shortcode add_shortcode( 'valute-slider-shortcode', 'display_custom_post_type' ); function display_custom_post_type(){ $args = array( 'post_type' => 'Slider', 'post_status' => 'publish' ); $string = ''; $query = new WP_Query( $args ); if( $query->have_posts() ){ $string .= '<section id="firstsection">'; while( $query->have_posts() ){ $query->the_post(); $buttonname = get_post_meta($post->ID, "wp_producer_name" , true); if( !empty($buttonname) ): endif; $string .= '<div class="container-fluid">' . '<div class="col-xs-12 firstsection-maindiv">' . '<div id="explore-section" class="owl-carousel owl-theme">' . '<div class="item">' . '<div class="col-xs-12 firstsection-innerdiv">' . ' <div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-left-div">' . ' <p class="oneplace">' .get_the_title() . '</p>'. ' <p class="slider-content">' .get_the_content() . '</p>'. ' <button class="slider-btn" type="button">' . $buttonname . '</button>'. '</div>' . ' <div class="col-lg-6 col-md-6 col-xs-6 col-sm-6 firstsection-inner-right-div">' . get_the_post_thumbnail() . '</div>' . '</div>' . '</div>' . '</div>' . '</div>'; } $string .= '</section>'; } wp_reset_postdata(); return $string; ```
Use `get_the_ID()` instead of `$post->ID` This will fix your problem
373,169
<p>I'm building a webshop, and started to configure the product loop on the shop archive page. I display the product category related to every product, and I would like to set to the categories to have a background that I've chosen on the admin page.</p> <p>I've made an ACF colour picker field, and set the colors.</p> <p>This is the code that I have:</p> <pre><code>add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 ); function VS_woo_loop_product_title() { echo '&lt;h3&gt;' . get_the_title() . '&lt;/h3&gt;'; $terms = get_the_terms( $post-&gt;ID, 'product_cat' ); if ( $terms &amp;&amp; ! is_wp_error( $terms ) ) : //only displayed if the product has at least one category $cat_links = array(); foreach ( $terms as $term ) { $cat_links[] = $term-&gt;name; } $on_cat = join( &quot; &quot;, $cat_links ); ?&gt; &lt;div style=&quot;background: &lt;?php the_field('kollekcio_szine', $terms); ?&gt;&quot;&gt; &lt;?php echo $on_cat; ?&gt; &lt;/div&gt; &lt;?php endif; } </code></pre> <p>It simply does not work. The category shows up correctly, but the background color does not appear. If I inspect the element I see that the background property is empty.</p> <p>How should I modify my code to get this work properly?</p> <p>Thank you for your help!</p>
[ { "answer_id": 373171, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": 0, "selected": false, "text": "<p>If I am reading this correctly, the variable $terms is an array at the point where you use it in the_field. I think you need it to be an individual category ID. I don't think the function the_field() accepts an array... I'd start by printing the raw data to the screen and see if its giving you any error output:</p>\n<pre><code>&lt;?php var_dump(the_field('kollekcio_szine', $terms)); ?&gt;\n</code></pre>\n<p>Or similar raw output method...</p>\n<p>If you can identify just the single category you want to apply the styling for, you can then use that in the above.</p>\n" }, { "answer_id": 373178, "author": "Sam", "author_id": 193035, "author_profile": "https://wordpress.stackexchange.com/users/193035", "pm_score": 1, "selected": false, "text": "<p>For get ACF datas from your category, you need to do something like this:</p>\n<p>Example from my code:\n<em>(This code is an example from my project and it is not a mix between WooCommerce and ACF. It is a mix with ACF and custom dev.)</em></p>\n<pre><code>....\nforeach ($products_cats as $cat) {\n $term = get_term($cat-&gt;id, 'products_cats');\n\n $term_img = get_field('image_present', $term-&gt;taxonomy . '_' . $term-&gt;term_id);\n}\n....\n</code></pre>\n<p>Sorry for my bad english, I hope this'll help you!</p>\n" }, { "answer_id": 373262, "author": "Saulo Padilha", "author_id": 50136, "author_profile": "https://wordpress.stackexchange.com/users/50136", "pm_score": 1, "selected": true, "text": "<p>The syntax to get the ACF field of a custom taxonomy is:</p>\n<pre><code>$var = get_field('name_of_acf_field', 'name_of_taxonomy' . '_' . taxonomy_ID);\n</code></pre>\n<p>so in your case you'll need to get product_cat ID before and do something like:</p>\n<pre><code>add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 );\nfunction VS_woo_loop_product_title() {\n echo '&lt;h3&gt;' . get_the_title() . '&lt;/h3&gt;';\n $terms = get_the_terms( $post-&gt;ID, 'product_cat' );\n if ( $terms &amp;&amp; ! is_wp_error( $terms ) ) :\n //only displayed if the product has at least one category\n $cat_links = array();\n foreach ( $terms as $term ) {\n $cat_links[] = $term-&gt;name;\n $cat_id = $term-&gt;term_id;\n }\n\n $on_cat = join( &quot; &quot;, $cat_links );\n $bgcolor = get_field('kollekcio_szine', 'product_cat' . '_' . $cat_id);\n\n ?&gt;\n &lt;div style=&quot;background-color: &lt;?php echo $bgcolor; ?&gt;&quot;&gt;\n &lt;?php echo $on_cat; ?&gt;\n &lt;/div&gt;\n &lt;?php endif;\n}\n</code></pre>\n" } ]
2020/08/17
[ "https://wordpress.stackexchange.com/questions/373169", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/180651/" ]
I'm building a webshop, and started to configure the product loop on the shop archive page. I display the product category related to every product, and I would like to set to the categories to have a background that I've chosen on the admin page. I've made an ACF colour picker field, and set the colors. This is the code that I have: ``` add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 ); function VS_woo_loop_product_title() { echo '<h3>' . get_the_title() . '</h3>'; $terms = get_the_terms( $post->ID, 'product_cat' ); if ( $terms && ! is_wp_error( $terms ) ) : //only displayed if the product has at least one category $cat_links = array(); foreach ( $terms as $term ) { $cat_links[] = $term->name; } $on_cat = join( " ", $cat_links ); ?> <div style="background: <?php the_field('kollekcio_szine', $terms); ?>"> <?php echo $on_cat; ?> </div> <?php endif; } ``` It simply does not work. The category shows up correctly, but the background color does not appear. If I inspect the element I see that the background property is empty. How should I modify my code to get this work properly? Thank you for your help!
The syntax to get the ACF field of a custom taxonomy is: ``` $var = get_field('name_of_acf_field', 'name_of_taxonomy' . '_' . taxonomy_ID); ``` so in your case you'll need to get product\_cat ID before and do something like: ``` add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 ); function VS_woo_loop_product_title() { echo '<h3>' . get_the_title() . '</h3>'; $terms = get_the_terms( $post->ID, 'product_cat' ); if ( $terms && ! is_wp_error( $terms ) ) : //only displayed if the product has at least one category $cat_links = array(); foreach ( $terms as $term ) { $cat_links[] = $term->name; $cat_id = $term->term_id; } $on_cat = join( " ", $cat_links ); $bgcolor = get_field('kollekcio_szine', 'product_cat' . '_' . $cat_id); ?> <div style="background-color: <?php echo $bgcolor; ?>"> <?php echo $on_cat; ?> </div> <?php endif; } ```
373,217
<p>I have a html bootstrap slider which works fine with captions and everything.I would like to integrate it into my Wp theme (my forst one, so total newbie).I found a code, which seems to helo, but it only shows the three pictures and nothing slides...if I hard code the slider, it works.I understand I can just leave it hard coded, but then it's not really WP ;) THANKS. Here is the code: functions.php - now complete file.</p> <pre><code>function load_stylesheets() { wp_register_style('style', get_template_directory_uri() . '/style.css', array(), 1,'all'); wp_enqueue_style('style'); wp_register_style('bootstrap', get_template_directory_uri() . '/bootstrap-4.1.3-dist/css/bootstrap.min.css', array(), 1,'all'); wp_enqueue_style('bootstrap'); wp_register_style('fixedcss', get_template_directory_uri() . '/css/fixed.css', array(), 1,'all'); wp_enqueue_style('fixedcss'); wp_register_style('custom', get_template_directory_uri() . '/custom.css', array(), 1,'all'); wp_enqueue_style('custom'); } add_action('wp_enqueue_scripts', 'load_stylesheets'); //load scripts function load_javascript() { wp_register_script('custom', get_template_directory_uri() . '/js/custom.js', 'jquery', 1, true); wp_enqueue_script('custom'); wp_register_script('bootstrapjs', get_template_directory_uri() . '/bootstrap-4.1.3-dist/js/bootstrap.min.js',array('jquery'), 1 , true); wp_enqueue_script('bootstrapjs'); } add_action('wp_enqueue_scripts', 'load_javascript'); // normal menue theme support add_theme_support('menus'); // register menus, =&gt;__ is improtant for tansaltions! register_nav_menus ( array('top-menu' =&gt;__('Top Menu', 'theme') ) ); //woocommerce theme suport function customtheme_add_woocommerce_support() { add_theme_support( 'woocommerce' ); } add_action( 'after_setup_theme', 'customtheme_add_woocommerce_support' ); //Images Slider function themename_slider_home_images_setup($wp_customize) { $wp_customize-&gt;add_section('home-slider-images', array( 'title' =&gt; 'Home Slider', )); $wp_customize-&gt;add_setting('home-slider-first-image'); $wp_customize-&gt;add_control( new WP_Customize_Image_Control( $wp_customize, 'home-slider-first-image', array( 'label' =&gt; __( 'First Image', 'theme_name' ), 'section' =&gt; 'home-slider-images', 'settings' =&gt; 'home-slider-first-image' ) ) ); $wp_customize-&gt;add_setting('home-slider-second-image'); $wp_customize-&gt;add_control( new WP_Customize_Image_Control( $wp_customize, 'home-slider-second-image', array( 'label' =&gt; __( 'Second Image', 'theme_name' ), 'section' =&gt; 'home-slider-images', 'settings' =&gt; 'home-slider-second-image' ) ) ); $wp_customize-&gt;add_setting('home-slider-third-image'); $wp_customize-&gt;add_control( new WP_Customize_Image_Control( $wp_customize, 'home-slider-third-image', array( 'label' =&gt; __( 'Third Image', 'theme_name' ), 'section' =&gt; 'home-slider-images', 'settings' =&gt; 'home-slider-third-image' ) ) ); } add_action('customize_register', 'themename_slider_home_images_setup');` </code></pre> <p>front-page.php:</p> <pre><code> &lt;div id=&quot;myCarousel&quot; class=&quot;carousel slide&quot; data-ride=&quot;carousel&quot;&gt; &lt;!-- Indicators --&gt; &lt;ol class=&quot;carousel-indicators&quot;&gt; &lt;li data-target=&quot;#myCarousel&quot; data-slide-to=&quot;0&quot; class=&quot;active&quot;&gt;&lt;/li&gt; &lt;li data-target=&quot;#myCarousel&quot; data-slide-to=&quot;1&quot;&gt;&lt;/li&gt; &lt;li data-target=&quot;#myCarousel&quot; data-slide-to=&quot;2&quot;&gt;&lt;/li&gt; &lt;/ol&gt; &lt;!-- Wrapper for slides --&gt; &lt;div class=&quot;carousel-inner&quot;&gt; &lt;div class=&quot;item active&quot;&gt; &lt;img src=&quot;&lt;?php echo get_theme_mod('home-slider-first-image');?&gt;&quot; alt=&quot;caption3!&quot; &gt; &lt;/div&gt; &lt;div class=&quot;item header-image&quot; &lt;img src=&quot;&lt;?php echo get_theme_mod('home-slider-second-image');?&gt;&quot; alt=&quot;caption2&quot; &gt; &lt;/div&gt; &lt;div class=&quot;item header-image&quot;&gt; &lt;img src=&quot;&lt;?php echo get_theme_mod('home-slider-third-image');?&gt;&quot; alt=&quot;I am a caption&quot; &lt;/div&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 373171, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": 0, "selected": false, "text": "<p>If I am reading this correctly, the variable $terms is an array at the point where you use it in the_field. I think you need it to be an individual category ID. I don't think the function the_field() accepts an array... I'd start by printing the raw data to the screen and see if its giving you any error output:</p>\n<pre><code>&lt;?php var_dump(the_field('kollekcio_szine', $terms)); ?&gt;\n</code></pre>\n<p>Or similar raw output method...</p>\n<p>If you can identify just the single category you want to apply the styling for, you can then use that in the above.</p>\n" }, { "answer_id": 373178, "author": "Sam", "author_id": 193035, "author_profile": "https://wordpress.stackexchange.com/users/193035", "pm_score": 1, "selected": false, "text": "<p>For get ACF datas from your category, you need to do something like this:</p>\n<p>Example from my code:\n<em>(This code is an example from my project and it is not a mix between WooCommerce and ACF. It is a mix with ACF and custom dev.)</em></p>\n<pre><code>....\nforeach ($products_cats as $cat) {\n $term = get_term($cat-&gt;id, 'products_cats');\n\n $term_img = get_field('image_present', $term-&gt;taxonomy . '_' . $term-&gt;term_id);\n}\n....\n</code></pre>\n<p>Sorry for my bad english, I hope this'll help you!</p>\n" }, { "answer_id": 373262, "author": "Saulo Padilha", "author_id": 50136, "author_profile": "https://wordpress.stackexchange.com/users/50136", "pm_score": 1, "selected": true, "text": "<p>The syntax to get the ACF field of a custom taxonomy is:</p>\n<pre><code>$var = get_field('name_of_acf_field', 'name_of_taxonomy' . '_' . taxonomy_ID);\n</code></pre>\n<p>so in your case you'll need to get product_cat ID before and do something like:</p>\n<pre><code>add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 );\nfunction VS_woo_loop_product_title() {\n echo '&lt;h3&gt;' . get_the_title() . '&lt;/h3&gt;';\n $terms = get_the_terms( $post-&gt;ID, 'product_cat' );\n if ( $terms &amp;&amp; ! is_wp_error( $terms ) ) :\n //only displayed if the product has at least one category\n $cat_links = array();\n foreach ( $terms as $term ) {\n $cat_links[] = $term-&gt;name;\n $cat_id = $term-&gt;term_id;\n }\n\n $on_cat = join( &quot; &quot;, $cat_links );\n $bgcolor = get_field('kollekcio_szine', 'product_cat' . '_' . $cat_id);\n\n ?&gt;\n &lt;div style=&quot;background-color: &lt;?php echo $bgcolor; ?&gt;&quot;&gt;\n &lt;?php echo $on_cat; ?&gt;\n &lt;/div&gt;\n &lt;?php endif;\n}\n</code></pre>\n" } ]
2020/08/18
[ "https://wordpress.stackexchange.com/questions/373217", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193291/" ]
I have a html bootstrap slider which works fine with captions and everything.I would like to integrate it into my Wp theme (my forst one, so total newbie).I found a code, which seems to helo, but it only shows the three pictures and nothing slides...if I hard code the slider, it works.I understand I can just leave it hard coded, but then it's not really WP ;) THANKS. Here is the code: functions.php - now complete file. ``` function load_stylesheets() { wp_register_style('style', get_template_directory_uri() . '/style.css', array(), 1,'all'); wp_enqueue_style('style'); wp_register_style('bootstrap', get_template_directory_uri() . '/bootstrap-4.1.3-dist/css/bootstrap.min.css', array(), 1,'all'); wp_enqueue_style('bootstrap'); wp_register_style('fixedcss', get_template_directory_uri() . '/css/fixed.css', array(), 1,'all'); wp_enqueue_style('fixedcss'); wp_register_style('custom', get_template_directory_uri() . '/custom.css', array(), 1,'all'); wp_enqueue_style('custom'); } add_action('wp_enqueue_scripts', 'load_stylesheets'); //load scripts function load_javascript() { wp_register_script('custom', get_template_directory_uri() . '/js/custom.js', 'jquery', 1, true); wp_enqueue_script('custom'); wp_register_script('bootstrapjs', get_template_directory_uri() . '/bootstrap-4.1.3-dist/js/bootstrap.min.js',array('jquery'), 1 , true); wp_enqueue_script('bootstrapjs'); } add_action('wp_enqueue_scripts', 'load_javascript'); // normal menue theme support add_theme_support('menus'); // register menus, =>__ is improtant for tansaltions! register_nav_menus ( array('top-menu' =>__('Top Menu', 'theme') ) ); //woocommerce theme suport function customtheme_add_woocommerce_support() { add_theme_support( 'woocommerce' ); } add_action( 'after_setup_theme', 'customtheme_add_woocommerce_support' ); //Images Slider function themename_slider_home_images_setup($wp_customize) { $wp_customize->add_section('home-slider-images', array( 'title' => 'Home Slider', )); $wp_customize->add_setting('home-slider-first-image'); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'home-slider-first-image', array( 'label' => __( 'First Image', 'theme_name' ), 'section' => 'home-slider-images', 'settings' => 'home-slider-first-image' ) ) ); $wp_customize->add_setting('home-slider-second-image'); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'home-slider-second-image', array( 'label' => __( 'Second Image', 'theme_name' ), 'section' => 'home-slider-images', 'settings' => 'home-slider-second-image' ) ) ); $wp_customize->add_setting('home-slider-third-image'); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'home-slider-third-image', array( 'label' => __( 'Third Image', 'theme_name' ), 'section' => 'home-slider-images', 'settings' => 'home-slider-third-image' ) ) ); } add_action('customize_register', 'themename_slider_home_images_setup');` ``` front-page.php: ``` <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <img src="<?php echo get_theme_mod('home-slider-first-image');?>" alt="caption3!" > </div> <div class="item header-image" <img src="<?php echo get_theme_mod('home-slider-second-image');?>" alt="caption2" > </div> <div class="item header-image"> <img src="<?php echo get_theme_mod('home-slider-third-image');?>" alt="I am a caption" </div> </div> ```
The syntax to get the ACF field of a custom taxonomy is: ``` $var = get_field('name_of_acf_field', 'name_of_taxonomy' . '_' . taxonomy_ID); ``` so in your case you'll need to get product\_cat ID before and do something like: ``` add_action( 'woocommerce_shop_loop_item_title', 'VS_woo_loop_product_title', 10 ); function VS_woo_loop_product_title() { echo '<h3>' . get_the_title() . '</h3>'; $terms = get_the_terms( $post->ID, 'product_cat' ); if ( $terms && ! is_wp_error( $terms ) ) : //only displayed if the product has at least one category $cat_links = array(); foreach ( $terms as $term ) { $cat_links[] = $term->name; $cat_id = $term->term_id; } $on_cat = join( " ", $cat_links ); $bgcolor = get_field('kollekcio_szine', 'product_cat' . '_' . $cat_id); ?> <div style="background-color: <?php echo $bgcolor; ?>"> <?php echo $on_cat; ?> </div> <?php endif; } ```
373,249
<h1>The issue</h1> <p>I am looking for a way to <strong>add linking functionality to a custom block</strong> of mine and found different approaches to this need.</p> <p>There are:</p> <ol> <li>The <a href="https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/url-input#urlinputbutton" rel="nofollow noreferrer">URLInputButton Component</a></li> <li>The <a href="https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/url-input#urlinput" rel="nofollow noreferrer">URLInput Component</a></li> <li>The <a href="https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/link-control" rel="nofollow noreferrer">LinkControl Component</a></li> <li>The <a href="https://github.com/WordPress/gutenberg/blob/73eaacb2e39bc05f520ab65d470512b365efb635/packages/block-editor/src/components/url-popover/README.md" rel="nofollow noreferrer">URLPopover Component</a></li> </ol> <p>I got it somehow working with the first two components:</p> <pre><code>const {URLInputButton, URLInput, URLPopover} = wp.blockEditor; registerBlockType('my-plugin-domain/textlink', { title: __('Text Link', 'my-textdomain'), ... attributes: { url: { type: 'string', }, }, edit(props) { const { attributes, setAttributes, } = props; const {url} = attributes; const blockControls = ( !!isSelected &amp;&amp; ( &lt;BlockControls&gt; &lt;Toolbar&gt; &lt;URLInputButton url={url} onChange={(url, post) =&gt; setAttributes( {url, title: (post &amp;&amp; post.title) || __('Click here')}, )} /&gt; &lt;URLInput className={className} value={url} onChange={(url, post) =&gt; setAttributes( {url, text: (post &amp;&amp; post.title) || 'Click here'})} /&gt; &lt;/Toolbar&gt; } ... }); </code></pre> <p>Unfortunately the <code>URLInput</code> as well as the <code>URLInputButton</code> appear <strong>displaced/buggy</strong> when entering a link.</p> <p>Hence I'm trying to figure out a way how to use the <code>LinkControl</code> Component and I can't get it to work. I wasn't even able to figure out from which Package it has to be imported yet.</p> <pre><code>const {LinkControl} = wp.blockEditor; // This doesn't seem to work const {LinkControl} = wp.components; // Neither this ... // This is not working: edit(props){ ... &lt;LinkControl onChange={(nextValue) =&gt; { console.log(nextValue); }} /&gt; ... } ... </code></pre> <p>Also I wasn't able to get the <a href="https://github.com/WordPress/gutenberg/blob/73eaacb2e39bc05f520ab65d470512b365efb635/packages/block-editor/src/components/url-popover/README.md" rel="nofollow noreferrer">URLPopover</a> to work.</p> <p>If anyone could point me into the right direction, it would be highly appreciated!</p>
[ { "answer_id": 376014, "author": "fluoriteen", "author_id": 178753, "author_profile": "https://wordpress.stackexchange.com/users/178753", "pm_score": 4, "selected": true, "text": "<p><em>LinkControl</em> is an experimental component, so it's declared differently in <em>blockEditor</em> package</p>\n<p>try this as an import statement, this worked for me:</p>\n<pre><code>const {__experimentalLinkControl } = wp.blockEditor;\nconst LinkControl = __experimentalLinkControl;\n</code></pre>\n" }, { "answer_id": 378427, "author": "Cláudio Esperança", "author_id": 197770, "author_profile": "https://wordpress.stackexchange.com/users/197770", "pm_score": 3, "selected": false, "text": "<p>Follow up on @fluoriteen answer: you can use aliased destructured variable assignment to have an one line assignment:</p>\n<pre><code>const {__experimentalLinkControl: LinkControl} = wp.blockEditor;\n</code></pre>\n" }, { "answer_id": 408928, "author": "Daniel Iser", "author_id": 63942, "author_profile": "https://wordpress.stackexchange.com/users/63942", "pm_score": 2, "selected": false, "text": "<p>And for consistency with the other answers, if your using <code>@wordpress/scripts</code> webpack build routines you'd simply do</p>\n<pre class=\"lang-js prettyprint-override\"><code>import {\n __experimentalLinkControl as LinkControl\n} from '@wordpress/block-editor';\n</code></pre>\n" } ]
2020/08/18
[ "https://wordpress.stackexchange.com/questions/373249", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/165265/" ]
The issue ========= I am looking for a way to **add linking functionality to a custom block** of mine and found different approaches to this need. There are: 1. The [URLInputButton Component](https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/url-input#urlinputbutton) 2. The [URLInput Component](https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/url-input#urlinput) 3. The [LinkControl Component](https://github.com/WordPress/gutenberg/tree/master/packages/block-editor/src/components/link-control) 4. The [URLPopover Component](https://github.com/WordPress/gutenberg/blob/73eaacb2e39bc05f520ab65d470512b365efb635/packages/block-editor/src/components/url-popover/README.md) I got it somehow working with the first two components: ``` const {URLInputButton, URLInput, URLPopover} = wp.blockEditor; registerBlockType('my-plugin-domain/textlink', { title: __('Text Link', 'my-textdomain'), ... attributes: { url: { type: 'string', }, }, edit(props) { const { attributes, setAttributes, } = props; const {url} = attributes; const blockControls = ( !!isSelected && ( <BlockControls> <Toolbar> <URLInputButton url={url} onChange={(url, post) => setAttributes( {url, title: (post && post.title) || __('Click here')}, )} /> <URLInput className={className} value={url} onChange={(url, post) => setAttributes( {url, text: (post && post.title) || 'Click here'})} /> </Toolbar> } ... }); ``` Unfortunately the `URLInput` as well as the `URLInputButton` appear **displaced/buggy** when entering a link. Hence I'm trying to figure out a way how to use the `LinkControl` Component and I can't get it to work. I wasn't even able to figure out from which Package it has to be imported yet. ``` const {LinkControl} = wp.blockEditor; // This doesn't seem to work const {LinkControl} = wp.components; // Neither this ... // This is not working: edit(props){ ... <LinkControl onChange={(nextValue) => { console.log(nextValue); }} /> ... } ... ``` Also I wasn't able to get the [URLPopover](https://github.com/WordPress/gutenberg/blob/73eaacb2e39bc05f520ab65d470512b365efb635/packages/block-editor/src/components/url-popover/README.md) to work. If anyone could point me into the right direction, it would be highly appreciated!
*LinkControl* is an experimental component, so it's declared differently in *blockEditor* package try this as an import statement, this worked for me: ``` const {__experimentalLinkControl } = wp.blockEditor; const LinkControl = __experimentalLinkControl; ```
373,267
<p>Inside the loop, when logged in to a localhost test site as <code>$user-&gt;ID == 1</code> the function <code>is_author(get_current_user_id())</code> returns <code>false</code> when <code>get_the_author_meta('ID')</code> returns 1. Thus, the following conditional is never executed (<code>is_user_logged_in()</code> returns <code>true</code>):</p> <pre><code>if( is_user_logged_in() &amp;&amp; is_author(get_current_user_id()) ) { // do stuff } </code></pre> <p>Have I missed something obvious?</p>
[ { "answer_id": 373271, "author": "Nate Allen", "author_id": 32698, "author_profile": "https://wordpress.stackexchange.com/users/32698", "pm_score": 3, "selected": true, "text": "<p>Are you sure you're doing it within the loop? The <code>is_author</code> function checks if <code>$wp_query</code> is set.</p>\n<p>Another option would be to try this:</p>\n<pre><code>$current_user = wp_get_current_user();\n\nif (is_user_logged_in() &amp;&amp; $current_user-&gt;ID == $post-&gt;post_author) {\n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 409033, "author": "epeleg", "author_id": 136249, "author_profile": "https://wordpress.stackexchange.com/users/136249", "pm_score": 0, "selected": false, "text": "<p>another issue might be if you are inside a WP REST API request and did not pass the X-WP-nonce header</p>\n" } ]
2020/08/18
[ "https://wordpress.stackexchange.com/questions/373267", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109240/" ]
Inside the loop, when logged in to a localhost test site as `$user->ID == 1` the function `is_author(get_current_user_id())` returns `false` when `get_the_author_meta('ID')` returns 1. Thus, the following conditional is never executed (`is_user_logged_in()` returns `true`): ``` if( is_user_logged_in() && is_author(get_current_user_id()) ) { // do stuff } ``` Have I missed something obvious?
Are you sure you're doing it within the loop? The `is_author` function checks if `$wp_query` is set. Another option would be to try this: ``` $current_user = wp_get_current_user(); if (is_user_logged_in() && $current_user->ID == $post->post_author) { // do stuff } ```
373,346
<p><a href="https://i.stack.imgur.com/wJfvk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wJfvk.jpg" alt="enter image description here" /></a></p> <p>How to add Category name to post title ? “PostTitle + CategoryName”?</p>
[ { "answer_id": 373271, "author": "Nate Allen", "author_id": 32698, "author_profile": "https://wordpress.stackexchange.com/users/32698", "pm_score": 3, "selected": true, "text": "<p>Are you sure you're doing it within the loop? The <code>is_author</code> function checks if <code>$wp_query</code> is set.</p>\n<p>Another option would be to try this:</p>\n<pre><code>$current_user = wp_get_current_user();\n\nif (is_user_logged_in() &amp;&amp; $current_user-&gt;ID == $post-&gt;post_author) {\n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 409033, "author": "epeleg", "author_id": 136249, "author_profile": "https://wordpress.stackexchange.com/users/136249", "pm_score": 0, "selected": false, "text": "<p>another issue might be if you are inside a WP REST API request and did not pass the X-WP-nonce header</p>\n" } ]
2020/08/19
[ "https://wordpress.stackexchange.com/questions/373346", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193395/" ]
[![enter image description here](https://i.stack.imgur.com/wJfvk.jpg)](https://i.stack.imgur.com/wJfvk.jpg) How to add Category name to post title ? “PostTitle + CategoryName”?
Are you sure you're doing it within the loop? The `is_author` function checks if `$wp_query` is set. Another option would be to try this: ``` $current_user = wp_get_current_user(); if (is_user_logged_in() && $current_user->ID == $post->post_author) { // do stuff } ```
373,355
<p>Is there a way to change the size of featured images on posts? When I click on one of my blog posts, I can see it’s extremely large and inefficient.</p> <p><a href="https://graduateinvestor.com" rel="nofollow noreferrer">https://graduateinvestor.com</a></p>
[ { "answer_id": 373271, "author": "Nate Allen", "author_id": 32698, "author_profile": "https://wordpress.stackexchange.com/users/32698", "pm_score": 3, "selected": true, "text": "<p>Are you sure you're doing it within the loop? The <code>is_author</code> function checks if <code>$wp_query</code> is set.</p>\n<p>Another option would be to try this:</p>\n<pre><code>$current_user = wp_get_current_user();\n\nif (is_user_logged_in() &amp;&amp; $current_user-&gt;ID == $post-&gt;post_author) {\n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 409033, "author": "epeleg", "author_id": 136249, "author_profile": "https://wordpress.stackexchange.com/users/136249", "pm_score": 0, "selected": false, "text": "<p>another issue might be if you are inside a WP REST API request and did not pass the X-WP-nonce header</p>\n" } ]
2020/08/20
[ "https://wordpress.stackexchange.com/questions/373355", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193403/" ]
Is there a way to change the size of featured images on posts? When I click on one of my blog posts, I can see it’s extremely large and inefficient. <https://graduateinvestor.com>
Are you sure you're doing it within the loop? The `is_author` function checks if `$wp_query` is set. Another option would be to try this: ``` $current_user = wp_get_current_user(); if (is_user_logged_in() && $current_user->ID == $post->post_author) { // do stuff } ```
373,357
<p>Simple question. I'm attempting to use <code>get_permalink()</code> in vanilla php but cannot access it. I have <code>include_once</code> all these &quot;used&quot; files:</p> <ul> <li>wp-settings.php</li> <li>wp-includes/load.php</li> <li>wp-includes/link-template.php</li> <li>wp-includes/rewrite.php</li> <li>wp-includes/functions.php</li> </ul> <p>and 10 other files. How do I access <code>get_permalink()</code>?</p>
[ { "answer_id": 373271, "author": "Nate Allen", "author_id": 32698, "author_profile": "https://wordpress.stackexchange.com/users/32698", "pm_score": 3, "selected": true, "text": "<p>Are you sure you're doing it within the loop? The <code>is_author</code> function checks if <code>$wp_query</code> is set.</p>\n<p>Another option would be to try this:</p>\n<pre><code>$current_user = wp_get_current_user();\n\nif (is_user_logged_in() &amp;&amp; $current_user-&gt;ID == $post-&gt;post_author) {\n // do stuff\n}\n</code></pre>\n" }, { "answer_id": 409033, "author": "epeleg", "author_id": 136249, "author_profile": "https://wordpress.stackexchange.com/users/136249", "pm_score": 0, "selected": false, "text": "<p>another issue might be if you are inside a WP REST API request and did not pass the X-WP-nonce header</p>\n" } ]
2020/08/20
[ "https://wordpress.stackexchange.com/questions/373357", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/189616/" ]
Simple question. I'm attempting to use `get_permalink()` in vanilla php but cannot access it. I have `include_once` all these "used" files: * wp-settings.php * wp-includes/load.php * wp-includes/link-template.php * wp-includes/rewrite.php * wp-includes/functions.php and 10 other files. How do I access `get_permalink()`?
Are you sure you're doing it within the loop? The `is_author` function checks if `$wp_query` is set. Another option would be to try this: ``` $current_user = wp_get_current_user(); if (is_user_logged_in() && $current_user->ID == $post->post_author) { // do stuff } ```
373,367
<p>So I've got the dreaded error too it seems. Apparently it's a very common issue but I can't really seem to get a hang on the fix.</p> <p>One of the plugins my theme uses is causing the error as per the log I got in the email WordPress sent to my admin email. Here's the full log</p> <pre><code>Error Details ============= An error of type E_ERROR was caused in line 8 of the file /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/rb_metaboxes.php. Error message: Uncaught Error: Call to undefined function rb_get_metabox() in /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/rb_metaboxes.php:8 Stack trace: #0 /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/metaboxes_exec.php(200): rb_setup_metaboxes() #1 /home/younited/domains/younitedsupport.com/public_html/wp-includes/class-wp-hook.php(289): rb_save_metaboxes(4585) #2 /home/younited/domains/younitedsupport.com/public_html/wp-includes/class-wp-hook.php(311): WP_Hook-&gt;apply_filters(NULL, Array) #3 /home/younited/domains/younitedsupport.com/public_html/wp-includes/plugin.php(478): WP_Hook-&gt;do_action(Array) #4 /home/younited/domains/younitedsupport.com/public_html/wp-includes/post.php(4260): do_action('save_post', 4585, Object(WP_Post), false) #5 /home/younited/domains/younitedsupport.com/public_html/wp-admin/includes/post.php(687): wp_insert_post(Array) #6 /home/younited/domains/younitedsupport.com/public_html/wp-admin/incl </code></pre> <p>Here's some additional information:<br /> WordPress version 5.5<br /> Current theme: Setech | Shared by WPTry.org (version 1.0.2)<br /> Current plugin: RB Essentials (version 1.0.1)<br /> PHP version 7.3.19</p> <p>The website was running fine until yesterday on the exact same configuration. I made no changes that caused this error.</p> <p>As you can guess, I have absolutely zero ideas what this means. I've tried disabling the plugin and reloading the site but it didn't work. Also, if I try to change the theme I get an HTTP 500 Internal Server Error(File &quot;/home/younited/domains/younitedsupport.com/public_html/wp-admin/themes.php&quot; is writeable by group) when clicking on the themes pages in WordPress.</p> <p>The same site on my localhost works just fine BTW. Everything is identical between the two sites. Any ideas on how to fix this?</p>
[ { "answer_id": 373370, "author": "t2pe", "author_id": 106499, "author_profile": "https://wordpress.stackexchange.com/users/106499", "pm_score": 0, "selected": false, "text": "<p>I don't think this is an answer as such but I need a bit more space than the comment box allows...</p>\n<p>Your line here:</p>\n<p>&quot;Also, if I try to change the theme I get an HTTP 500 Internal Server Error(File &quot;/home/younited/domains/younitedsupport.com/public_html/wp-admin/themes.php&quot; is writeable by group) when clicking on the themes pages in WordPress.&quot;</p>\n<p>Suggests that the secondary error is complaining about file/folder permissions (ie. &quot;is writeable by group&quot;).</p>\n<p>If the file permissions were wrong it could potentially...</p>\n<ol>\n<li>Explain why your dev environment is ok when the live environment isn't</li>\n<li>Prevent some files being loaded which would then in turn lead to undefined function errors (and others)</li>\n</ol>\n<p>If you've not changed the file permissions and this has happened suddenly, I would at least check that the site is healthy using one of the well-known security plugins. You could also check if there was a difference in the permissions via cPanel, or even the command line if you have access.</p>\n<p>It's just a thought - that line about 'writable by group' is a warning flag of sorts.</p>\n" }, { "answer_id": 373431, "author": "YaddyVirus", "author_id": 193417, "author_profile": "https://wordpress.stackexchange.com/users/193417", "pm_score": 2, "selected": true, "text": "<p>So I reinstalled WordPress on both my live and local environments and downgraded to version 5.4.2 and everything seems to be working just fine, so far.</p>\n<p>I'll update if anything breaks again.</p>\n" } ]
2020/08/20
[ "https://wordpress.stackexchange.com/questions/373367", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193417/" ]
So I've got the dreaded error too it seems. Apparently it's a very common issue but I can't really seem to get a hang on the fix. One of the plugins my theme uses is causing the error as per the log I got in the email WordPress sent to my admin email. Here's the full log ``` Error Details ============= An error of type E_ERROR was caused in line 8 of the file /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/rb_metaboxes.php. Error message: Uncaught Error: Call to undefined function rb_get_metabox() in /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/rb_metaboxes.php:8 Stack trace: #0 /home/younited/domains/younitedsupport.com/public_html/wp-content/plugins/rb-essentials/metaboxes/metaboxes_exec.php(200): rb_setup_metaboxes() #1 /home/younited/domains/younitedsupport.com/public_html/wp-includes/class-wp-hook.php(289): rb_save_metaboxes(4585) #2 /home/younited/domains/younitedsupport.com/public_html/wp-includes/class-wp-hook.php(311): WP_Hook->apply_filters(NULL, Array) #3 /home/younited/domains/younitedsupport.com/public_html/wp-includes/plugin.php(478): WP_Hook->do_action(Array) #4 /home/younited/domains/younitedsupport.com/public_html/wp-includes/post.php(4260): do_action('save_post', 4585, Object(WP_Post), false) #5 /home/younited/domains/younitedsupport.com/public_html/wp-admin/includes/post.php(687): wp_insert_post(Array) #6 /home/younited/domains/younitedsupport.com/public_html/wp-admin/incl ``` Here's some additional information: WordPress version 5.5 Current theme: Setech | Shared by WPTry.org (version 1.0.2) Current plugin: RB Essentials (version 1.0.1) PHP version 7.3.19 The website was running fine until yesterday on the exact same configuration. I made no changes that caused this error. As you can guess, I have absolutely zero ideas what this means. I've tried disabling the plugin and reloading the site but it didn't work. Also, if I try to change the theme I get an HTTP 500 Internal Server Error(File "/home/younited/domains/younitedsupport.com/public\_html/wp-admin/themes.php" is writeable by group) when clicking on the themes pages in WordPress. The same site on my localhost works just fine BTW. Everything is identical between the two sites. Any ideas on how to fix this?
So I reinstalled WordPress on both my live and local environments and downgraded to version 5.4.2 and everything seems to be working just fine, so far. I'll update if anything breaks again.
373,386
<p>How can I pass the results of a <code>WP_Query</code> call to a plugin? I've tried passing the data via a shortcode attribute, but I get the error &quot;Object of class WP_Query could not be converted to string&quot;.</p> <p>E.g.:</p> <pre><code>$args = array( // ... ); $the_query = WP_Query($args); echo do_shortcode( [example_custom_plugin query_payload=&quot;' . $the_query . '&quot;] ); </code></pre> <p>What are the different (and best advised) ways for a plugin to retrieve variables (which may be objects or arrays of data) that the WP template has set?</p> <p>In my case, my plugin is instantiated via the shortcode call, hence why I am approaching it from that perspective; I want the plugin to have the results of the WP_Query at instantiation.</p>
[ { "answer_id": 373395, "author": "Movs", "author_id": 193435, "author_profile": "https://wordpress.stackexchange.com/users/193435", "pm_score": -1, "selected": false, "text": "<ol>\n<li>Use global variable</li>\n<li>Pass just $args and run the same query inside the plugin</li>\n<li>Serialize results and pass it like you wanted</li>\n</ol>\n<p>If I was you, I would prefer 2nd way...</p>\n" }, { "answer_id": 373419, "author": "NightHawk", "author_id": 14656, "author_profile": "https://wordpress.stackexchange.com/users/14656", "pm_score": 1, "selected": false, "text": "<p>I think for shortcodes, which are generally used in the WYSIWYG editor by non-technical users, it's best to keep the parameters simple:</p>\n<pre><code>[custom-shortcode color=&quot;red&quot; size=&quot;medium&quot;]\n</code></pre>\n<p>In other words, shortcodes are designed to provide functionality that an end-user can place somewhere in their content, with the option of supplying a few different customizations.</p>\n<p>For obtaining something as a complicated as <code>WP_Query</code> results, I would use:</p>\n<pre class=\"lang-php prettyprint-override\"><code>global $wp_query;\n</code></pre>\n<p>That gives you access to the current query being executed at the moment that your shortcode is run. You can do that in the function that your shortcode would call.</p>\n<p>If you need to make an entirely custom query for different data, you can in fact just create a new <code>WP_Query</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function custom_shortcode() {\n $params = [];\n $q = new WP_Query($params);\n // ...\n}\n</code></pre>\n<p>So it's best for your plugin to go lookup or get the data versus expecting the data to be passed. That's not always the case, but with what you presented, that seems like the best route.</p>\n" } ]
2020/08/20
[ "https://wordpress.stackexchange.com/questions/373386", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90498/" ]
How can I pass the results of a `WP_Query` call to a plugin? I've tried passing the data via a shortcode attribute, but I get the error "Object of class WP\_Query could not be converted to string". E.g.: ``` $args = array( // ... ); $the_query = WP_Query($args); echo do_shortcode( [example_custom_plugin query_payload="' . $the_query . '"] ); ``` What are the different (and best advised) ways for a plugin to retrieve variables (which may be objects or arrays of data) that the WP template has set? In my case, my plugin is instantiated via the shortcode call, hence why I am approaching it from that perspective; I want the plugin to have the results of the WP\_Query at instantiation.
I think for shortcodes, which are generally used in the WYSIWYG editor by non-technical users, it's best to keep the parameters simple: ``` [custom-shortcode color="red" size="medium"] ``` In other words, shortcodes are designed to provide functionality that an end-user can place somewhere in their content, with the option of supplying a few different customizations. For obtaining something as a complicated as `WP_Query` results, I would use: ```php global $wp_query; ``` That gives you access to the current query being executed at the moment that your shortcode is run. You can do that in the function that your shortcode would call. If you need to make an entirely custom query for different data, you can in fact just create a new `WP_Query`: ```php function custom_shortcode() { $params = []; $q = new WP_Query($params); // ... } ``` So it's best for your plugin to go lookup or get the data versus expecting the data to be passed. That's not always the case, but with what you presented, that seems like the best route.
373,404
<p>I would like to add the following JavaScript function to a wordpress child theme (functions.php). Unfortunately I am not able to make it. Function:</p> <pre><code>$.fn.cityAutocomplete.transliterate = function (s) { s = String(s); return s; }; </code></pre> <p>I tried this:</p> <pre><code>&lt;?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { wp_enqueue_style( 'listingpr-parent-style', get_template_directory_uri() . '/style.css' ); } echo &quot;&lt;script&gt;fn.cityAutocomplete.transliterate();&lt;/script&gt;&quot;; ?&gt; </code></pre> <p>But it dont work. Please help me to fix my issue. Thanks you!</p> <p>regards shotput_wp</p>
[ { "answer_id": 373395, "author": "Movs", "author_id": 193435, "author_profile": "https://wordpress.stackexchange.com/users/193435", "pm_score": -1, "selected": false, "text": "<ol>\n<li>Use global variable</li>\n<li>Pass just $args and run the same query inside the plugin</li>\n<li>Serialize results and pass it like you wanted</li>\n</ol>\n<p>If I was you, I would prefer 2nd way...</p>\n" }, { "answer_id": 373419, "author": "NightHawk", "author_id": 14656, "author_profile": "https://wordpress.stackexchange.com/users/14656", "pm_score": 1, "selected": false, "text": "<p>I think for shortcodes, which are generally used in the WYSIWYG editor by non-technical users, it's best to keep the parameters simple:</p>\n<pre><code>[custom-shortcode color=&quot;red&quot; size=&quot;medium&quot;]\n</code></pre>\n<p>In other words, shortcodes are designed to provide functionality that an end-user can place somewhere in their content, with the option of supplying a few different customizations.</p>\n<p>For obtaining something as a complicated as <code>WP_Query</code> results, I would use:</p>\n<pre class=\"lang-php prettyprint-override\"><code>global $wp_query;\n</code></pre>\n<p>That gives you access to the current query being executed at the moment that your shortcode is run. You can do that in the function that your shortcode would call.</p>\n<p>If you need to make an entirely custom query for different data, you can in fact just create a new <code>WP_Query</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function custom_shortcode() {\n $params = [];\n $q = new WP_Query($params);\n // ...\n}\n</code></pre>\n<p>So it's best for your plugin to go lookup or get the data versus expecting the data to be passed. That's not always the case, but with what you presented, that seems like the best route.</p>\n" } ]
2020/08/20
[ "https://wordpress.stackexchange.com/questions/373404", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193446/" ]
I would like to add the following JavaScript function to a wordpress child theme (functions.php). Unfortunately I am not able to make it. Function: ``` $.fn.cityAutocomplete.transliterate = function (s) { s = String(s); return s; }; ``` I tried this: ``` <?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { wp_enqueue_style( 'listingpr-parent-style', get_template_directory_uri() . '/style.css' ); } echo "<script>fn.cityAutocomplete.transliterate();</script>"; ?> ``` But it dont work. Please help me to fix my issue. Thanks you! regards shotput\_wp
I think for shortcodes, which are generally used in the WYSIWYG editor by non-technical users, it's best to keep the parameters simple: ``` [custom-shortcode color="red" size="medium"] ``` In other words, shortcodes are designed to provide functionality that an end-user can place somewhere in their content, with the option of supplying a few different customizations. For obtaining something as a complicated as `WP_Query` results, I would use: ```php global $wp_query; ``` That gives you access to the current query being executed at the moment that your shortcode is run. You can do that in the function that your shortcode would call. If you need to make an entirely custom query for different data, you can in fact just create a new `WP_Query`: ```php function custom_shortcode() { $params = []; $q = new WP_Query($params); // ... } ``` So it's best for your plugin to go lookup or get the data versus expecting the data to be passed. That's not always the case, but with what you presented, that seems like the best route.
373,442
<p>My permalinks is set to <code>/%post_id%/</code> (post id).</p> <p><a href="https://elrons.co.il/%post_id%/" rel="nofollow noreferrer">https://elrons.co.il/%post_id%/</a></p> <p>I want to change them all to <code>/%postname%/</code> (which is the post slug).</p> <p><a href="https://elrons.co.il/%postname%/" rel="nofollow noreferrer">https://elrons.co.il/%postname%/</a></p> <p>Problem is, whenever I change it, it gives 404 errors from my old page urls.</p> <p>for example, this: <a href="https://elrons.co.il/1779/" rel="nofollow noreferrer">https://elrons.co.il/1779/</a></p> <p>should change to: <a href="https://elrons.co.il/pil-kahol-font/" rel="nofollow noreferrer">https://elrons.co.il/pil-kahol-font/</a></p> <p>But it gives 404 instead.</p> <p>How do I make 301 redirection from <code>/%post_id%/</code> to <code>/%postname%/</code>?</p>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/21
[ "https://wordpress.stackexchange.com/questions/373442", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98773/" ]
My permalinks is set to `/%post_id%/` (post id). <https://elrons.co.il/%post_id%/> I want to change them all to `/%postname%/` (which is the post slug). <https://elrons.co.il/%postname%/> Problem is, whenever I change it, it gives 404 errors from my old page urls. for example, this: <https://elrons.co.il/1779/> should change to: <https://elrons.co.il/pil-kahol-font/> But it gives 404 instead. How do I make 301 redirection from `/%post_id%/` to `/%postname%/`?
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,447
<p>Is it possible to disable the cropping step when adding a site icon via the Theme Customizer in WordPress 5+ (occurred to me in 5.5)?</p> <p>For me cropping is unnecessary because I always upload a square image in the directions of the recommendations.</p> <p>That's why this step is not helping me at all, instead is actually causing the following problems:</p> <ul> <li>It creates an unnecessary copy of the image with a <code>cropped</code> prefix.</li> <li>For the cropped image it creates a <strong>NEW</strong> attachment.</li> </ul> <p>Thus all the settings I did for the attachment of the un-cropped image are lost and the filename of the site icon will always include this <code>cropped</code> prefix.</p> <p>Is there anyway to fix this without patching the source of this problem?</p>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/21
[ "https://wordpress.stackexchange.com/questions/373447", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44637/" ]
Is it possible to disable the cropping step when adding a site icon via the Theme Customizer in WordPress 5+ (occurred to me in 5.5)? For me cropping is unnecessary because I always upload a square image in the directions of the recommendations. That's why this step is not helping me at all, instead is actually causing the following problems: * It creates an unnecessary copy of the image with a `cropped` prefix. * For the cropped image it creates a **NEW** attachment. Thus all the settings I did for the attachment of the un-cropped image are lost and the filename of the site icon will always include this `cropped` prefix. Is there anyway to fix this without patching the source of this problem?
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,563
<p>I am updating an array saved in a users meta field using an ajax function.</p> <p>The values added to the array are taken from the data-attributes within the tags which also act at the trigger to make the ajax call.</p> <p>Whilst the function works 95% of the time, it can be a bit hit and miss whether the values save or not. I suspect this is because a user can fire these ajax calls too quickly and not give enough time for the original function call to save and update the meta field.</p> <p>What would be the best method to ensure the ajax triggered function of updating the meta field value has been completed before allowing the function to run again?</p> <p>Hope this makes sense - needless to say, please let me know if you need any more info.</p> <p>Thanks in advance!!</p> <p><strong>Sample HTML</strong></p> <pre><code>&lt;div id=&quot;rjb_slots&quot; class=&quot;slots&quot;&gt; &lt;h5&gt;Mon, 24th Aug 2020&lt;/h5&gt; &lt;div class=&quot;slot&quot;&gt; &lt;span class=&quot;time&quot;&gt;10:30&lt;/span&gt; &lt;a class=&quot;book&quot; data-timestamp=&quot;1598265000&quot; href=&quot;#&quot;&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;slot&quot;&gt; &lt;span class=&quot;time&quot;&gt;11:00&lt;/span&gt; &lt;a class=&quot;booked&quot; data-timestamp=&quot;1598266800&quot; href=&quot;#&quot;&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;slot&quot;&gt; &lt;span class=&quot;time&quot;&gt;11:30&lt;/span&gt; &lt;a class=&quot;booked&quot; data-timestamp=&quot;1598268600&quot; href=&quot;#&quot;&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;slot&quot;&gt; &lt;span class=&quot;time&quot;&gt;12:00&lt;/span&gt; &lt;a class=&quot;book&quot; data-timestamp=&quot;1598270400&quot; href=&quot;#&quot;&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;slot&quot;&gt; &lt;span class=&quot;time&quot;&gt;12:30&lt;/span&gt; &lt;a class=&quot;booked&quot; data-timestamp=&quot;1598272200&quot; href=&quot;#&quot;&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;slot&quot;&gt; &lt;span class=&quot;time&quot;&gt;13:00&lt;/span&gt; &lt;a class=&quot;book&quot; data-timestamp=&quot;1598274000&quot; href=&quot;#&quot;&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class=&quot;slot&quot;&gt; &lt;span class=&quot;time&quot;&gt;19:30&lt;/span&gt; &lt;a class=&quot;book&quot; data-timestamp=&quot;1598297400&quot; href=&quot;#&quot;&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Ajax .js</strong></p> <pre><code>$('.slot').on('click', 'a.book', function(e) { e.preventDefault(); var user = $('#rjb_day').attr( 'data-user' ); var stamp = $(this).attr( 'data-timestamp' ); // console.log(bookCap); $(this).removeClass('book').addClass('booked'); $.ajax({ type: 'POST', url: ajax_object.ajaxurl, data: { action: 'rjb_make_diary_slots', user: user, stamp: stamp }, success: function(data) { // This outputs the result of the ajax request console.log(data); }, error: function(errorThrown){ console.log(errorThrown); } }); }); </code></pre> <p><strong>Function that updates the user metafield</strong></p> <pre><code>add_action( 'wp_ajax_rjb_make_diary_slots', 'rjb_make_diary_slots' ); function rjb_make_diary_slots() { $user = $_POST['user']; $stamp = array( array( 'rjb_cal_day' =&gt; strtotime('today', $_POST['stamp']), 'rjb_cal_when' =&gt; $_POST['stamp'], 'rjb_cal_position_id' =&gt; '', 'rjb_cal_candidate_id' =&gt; '' ) ); $calendar = get_user_meta( $user, 'rjb_cal', true); $stamps = !empty($calendar) ? $calendar : array(); $new_stamp = array_merge($stamps, $stamp); usort($new_stamp, function($a, $b) { return $a['rjb_cal_when'] &lt;=&gt; $b['rjb_cal_when']; }); update_user_meta( $user, 'rjb_cal', $new_stamp); $log = print_r($stamp); wp_die($log); } </code></pre> <p><strong>Example of a value stored in the <code>rjb_cal</code> user meta field</strong></p> <pre><code>array ( [0] =&gt; array ( [rjb_cal_day] =&gt; 1598227200 [rjb_cal_when] =&gt; 1598266800 [rjb_cal_position_id] =&gt; [rjb_cal_candidate_id] =&gt; ) [1] =&gt; array ( [rjb_cal_day] =&gt; 1598227200 [rjb_cal_when] =&gt; 1598268600 [rjb_cal_position_id] =&gt; [rjb_cal_candidate_id] =&gt; ) [2] =&gt; array ( [rjb_cal_day] =&gt; 1598227200 [rjb_cal_when] =&gt; 1598272200 [rjb_cal_position_id] =&gt; [rjb_cal_candidate_id] =&gt; ) ) </code></pre>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/23
[ "https://wordpress.stackexchange.com/questions/373563", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/57057/" ]
I am updating an array saved in a users meta field using an ajax function. The values added to the array are taken from the data-attributes within the tags which also act at the trigger to make the ajax call. Whilst the function works 95% of the time, it can be a bit hit and miss whether the values save or not. I suspect this is because a user can fire these ajax calls too quickly and not give enough time for the original function call to save and update the meta field. What would be the best method to ensure the ajax triggered function of updating the meta field value has been completed before allowing the function to run again? Hope this makes sense - needless to say, please let me know if you need any more info. Thanks in advance!! **Sample HTML** ``` <div id="rjb_slots" class="slots"> <h5>Mon, 24th Aug 2020</h5> <div class="slot"> <span class="time">10:30</span> <a class="book" data-timestamp="1598265000" href="#"></a> </div> <div class="slot"> <span class="time">11:00</span> <a class="booked" data-timestamp="1598266800" href="#"></a> </div> <div class="slot"> <span class="time">11:30</span> <a class="booked" data-timestamp="1598268600" href="#"></a> </div> <div class="slot"> <span class="time">12:00</span> <a class="book" data-timestamp="1598270400" href="#"></a> </div> <div class="slot"> <span class="time">12:30</span> <a class="booked" data-timestamp="1598272200" href="#"></a> </div> <div class="slot"> <span class="time">13:00</span> <a class="book" data-timestamp="1598274000" href="#"></a> </div> <div class="slot"> <span class="time">19:30</span> <a class="book" data-timestamp="1598297400" href="#"></a> </div> </div> ``` **Ajax .js** ``` $('.slot').on('click', 'a.book', function(e) { e.preventDefault(); var user = $('#rjb_day').attr( 'data-user' ); var stamp = $(this).attr( 'data-timestamp' ); // console.log(bookCap); $(this).removeClass('book').addClass('booked'); $.ajax({ type: 'POST', url: ajax_object.ajaxurl, data: { action: 'rjb_make_diary_slots', user: user, stamp: stamp }, success: function(data) { // This outputs the result of the ajax request console.log(data); }, error: function(errorThrown){ console.log(errorThrown); } }); }); ``` **Function that updates the user metafield** ``` add_action( 'wp_ajax_rjb_make_diary_slots', 'rjb_make_diary_slots' ); function rjb_make_diary_slots() { $user = $_POST['user']; $stamp = array( array( 'rjb_cal_day' => strtotime('today', $_POST['stamp']), 'rjb_cal_when' => $_POST['stamp'], 'rjb_cal_position_id' => '', 'rjb_cal_candidate_id' => '' ) ); $calendar = get_user_meta( $user, 'rjb_cal', true); $stamps = !empty($calendar) ? $calendar : array(); $new_stamp = array_merge($stamps, $stamp); usort($new_stamp, function($a, $b) { return $a['rjb_cal_when'] <=> $b['rjb_cal_when']; }); update_user_meta( $user, 'rjb_cal', $new_stamp); $log = print_r($stamp); wp_die($log); } ``` **Example of a value stored in the `rjb_cal` user meta field** ``` array ( [0] => array ( [rjb_cal_day] => 1598227200 [rjb_cal_when] => 1598266800 [rjb_cal_position_id] => [rjb_cal_candidate_id] => ) [1] => array ( [rjb_cal_day] => 1598227200 [rjb_cal_when] => 1598268600 [rjb_cal_position_id] => [rjb_cal_candidate_id] => ) [2] => array ( [rjb_cal_day] => 1598227200 [rjb_cal_when] => 1598272200 [rjb_cal_position_id] => [rjb_cal_candidate_id] => ) ) ```
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,573
<p>My local development WordPress install on ServerPress is not writing error logs. I made changes to my wp-config.php file to enable error log writing for WordPress, and also tried editing the php.ini file for xampplite to try and enable error tracking, But still, I could not get any logs going, so I reverted that to its original settings. My website currently displays</p> <blockquote> <p>There has been a critical error on your website.</p> </blockquote> <p>in the front-end. I added the following code before the <code>define( 'DB_NAME', 'blahblahblah');</code> configuration:</p> <pre><code>/**Enable WP Debug */ define( 'WP_DEBUG', true ); /** Enable WP Debug Log */ define( 'WP_DEBUG_LOG', true ); /**Display debug on HTML page*/ define( 'WP_DEBUG_DISPLAY', false ); @ini_set('display_errors',0); </code></pre>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/23
[ "https://wordpress.stackexchange.com/questions/373573", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121047/" ]
My local development WordPress install on ServerPress is not writing error logs. I made changes to my wp-config.php file to enable error log writing for WordPress, and also tried editing the php.ini file for xampplite to try and enable error tracking, But still, I could not get any logs going, so I reverted that to its original settings. My website currently displays > > There has been a critical error on your website. > > > in the front-end. I added the following code before the `define( 'DB_NAME', 'blahblahblah');` configuration: ``` /**Enable WP Debug */ define( 'WP_DEBUG', true ); /** Enable WP Debug Log */ define( 'WP_DEBUG_LOG', true ); /**Display debug on HTML page*/ define( 'WP_DEBUG_DISPLAY', false ); @ini_set('display_errors',0); ```
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,599
<p>I have two custom post types &quot;Product&quot; and &quot;News&quot;. I want to keep a description that describes each of these types and I want to display it under the custom post title inside a banner. Also the user should be able to change it from admin dashboard. That means when I go to products page, there is a banner on top of the page and the title will be PRODUCTS and then product description should be displayed.</p> <p>EX:</p> <pre> <h2><em>PRODUCTS</em></h2> PRODUCTS DESCRIPTION </pre> <p>Now if I can add a meta box common to the product cpt which has an input field, I can display it on the web page. But I only know how to add meta boxes to each products under product type.</p> <p>How do I solve this?</p>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/24
[ "https://wordpress.stackexchange.com/questions/373599", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193585/" ]
I have two custom post types "Product" and "News". I want to keep a description that describes each of these types and I want to display it under the custom post title inside a banner. Also the user should be able to change it from admin dashboard. That means when I go to products page, there is a banner on top of the page and the title will be PRODUCTS and then product description should be displayed. EX: ``` *PRODUCTS* ---------- PRODUCTS DESCRIPTION ``` Now if I can add a meta box common to the product cpt which has an input field, I can display it on the web page. But I only know how to add meta boxes to each products under product type. How do I solve this?
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,614
<p>I am looking for a SQL Query that can give the list of all categories created in WordPress Site along with it's category IDs. Please advise a query to get it as category/term relationship is quite complex in WordPress.</p> <p>I got this but didn't work -</p> <pre><code>SELECT ID,post_title FROM wp_posts INNER JOIN wp_term_relationships ON wp_term_relationships.object_id=wp_posts.ID INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id=wp_term_relationships.term_taxonomy_id INNER JOIN wp_terms ON wp_terms.term_id=wp_term_taxonomy.term_id WHERE name='category' </code></pre>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/24
[ "https://wordpress.stackexchange.com/questions/373614", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/188153/" ]
I am looking for a SQL Query that can give the list of all categories created in WordPress Site along with it's category IDs. Please advise a query to get it as category/term relationship is quite complex in WordPress. I got this but didn't work - ``` SELECT ID,post_title FROM wp_posts INNER JOIN wp_term_relationships ON wp_term_relationships.object_id=wp_posts.ID INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id=wp_term_relationships.term_taxonomy_id INNER JOIN wp_terms ON wp_terms.term_id=wp_term_taxonomy.term_id WHERE name='category' ```
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,667
<p>In the WordPress customizer script, I am trying to pass the value from a select control into a custom control that displays taxonomies associated with the selected value (1st control).</p> <pre><code>$wp_customize-&gt;add_control( new Tax_Dropdown_Control( $wp_customize, 'select_tax', array( 'section' =&gt; 'section_1', 'label' =&gt; __( 'Select Post Taxonomy', 'textdomain' ), 'description' =&gt; __( 'Select a taxonomy based on post type selected.', 'textdomain' ), 'dropdown_args' =&gt; array( 'post_type' =&gt; $wp_customize-&gt;get_setting(&quot;select_post_type&quot;), // here I need to pass the first setting's value ), ) ) ); // custom controls related snippet class Tax_Dropdown_Control extends WP_Customize_Control { ..... $dropdown_args = wp_parse_args( $this-&gt;dropdown_args, array( 'post_type' =&gt; 'post', ) ); $dropdown_args['echo'] = false; $taxonomies = get_object_taxonomies($dropdown_args); if ($taxonomies) { echo '&lt;select&gt;'; foreach ($taxonomies as $taxonomy ) { echo '&lt;option&gt;'. $taxonomy. '&lt;/option&gt;'; } echo '&lt;/select&gt;'; } .... } </code></pre> <p>It would need to update the choices live when the select post type is changed. I'm not sure if maybe an <code>active_callback</code> can be used to recall the function with the updated variable?</p>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/24
[ "https://wordpress.stackexchange.com/questions/373667", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24067/" ]
In the WordPress customizer script, I am trying to pass the value from a select control into a custom control that displays taxonomies associated with the selected value (1st control). ``` $wp_customize->add_control( new Tax_Dropdown_Control( $wp_customize, 'select_tax', array( 'section' => 'section_1', 'label' => __( 'Select Post Taxonomy', 'textdomain' ), 'description' => __( 'Select a taxonomy based on post type selected.', 'textdomain' ), 'dropdown_args' => array( 'post_type' => $wp_customize->get_setting("select_post_type"), // here I need to pass the first setting's value ), ) ) ); // custom controls related snippet class Tax_Dropdown_Control extends WP_Customize_Control { ..... $dropdown_args = wp_parse_args( $this->dropdown_args, array( 'post_type' => 'post', ) ); $dropdown_args['echo'] = false; $taxonomies = get_object_taxonomies($dropdown_args); if ($taxonomies) { echo '<select>'; foreach ($taxonomies as $taxonomy ) { echo '<option>'. $taxonomy. '</option>'; } echo '</select>'; } .... } ``` It would need to update the choices live when the select post type is changed. I'm not sure if maybe an `active_callback` can be used to recall the function with the updated variable?
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,729
<p>Update:</p> <p>I created a fresh new installation of WordPress, copied both Base and Base Child themes and activated Base Child. The Appearance/Customize gives the same white screen as described in point 1 below.</p> <p>I then activated Base and the Appearance/Customize screen has the same error, which did not occur on the previous WP installation. This leads me to believe I have an issue with my customizer code. I WILL get to the bottom of this.</p> <hr /> <p>I developed a custom theme, let's call it &quot;Base&quot;, based on <a href="https://underscores.me/" rel="nofollow noreferrer">https://underscores.me/</a>, which is the boilerplate for several other child themes. The Base theme features several theme mods accessible via the theme customizer. I also created a child theme of Base, A.K.A. &quot;Base Child&quot;, right now containing only the style.css file, which is copied below:</p> <pre> /* Theme Name: Base Child Template: base Theme URI: https://blabla.com/ Author: Me Author URI: https://blabla.com/ Description: Base Child Version: 1.0.0 Text Domain: base-child Tags: custom-background, custom-logo, custom-menu, featured-images, threaded-comments, translation-ready */ </pre> <p>The only plugins installed are:</p> <ol> <li>ACF Photo Gallery Field</li> <li>Advanced Custom Fields (the free version)</li> <li>Simple Page Ordering</li> </ol> <p>Everything works fine when the Base theme is activated, meaning all custom post types are there, the theme customizer works perfectly, all shortcodes behave like they should etc.</p> <p>Things can be very confusing from now on, so please be patient with me. As soon as I activate Base Child, weird things start to happen:</p> <ol> <li>If I go to Appearance/Customize, I get a screen showing only the &quot;You are customizing Site Name&quot; message and the page title is &quot;Customizing: Loading...&quot; forever. Nothing else works.</li> <li>Related to point 1, a console inspection reveals this JS error on the page: <code>Uncaught SyntaxError: Unexpected token '&lt;' on customize.php on line 5240</code>, and when looking at the page source, I'm finding what looks like a php error: <code>Warning: sprintf(): Too few arguments in C:\wamp64\www\base-boilerplate\wp-includes\theme.php on line &lt;i&gt;1027&lt;/i&gt;</code></li> <li>Trying to replicate this issue with another theme, I installed Twenty Twenty and declared Base Child to be a child of Twenty Twenty in its <code>style.css</code>. I was amazed to see that all the custom post types created in Base were present in Base Child as a Twenty Twenty child. Going to Appearance/Customize, I get the same behavior as at point 1. It's as if Base Child was still a child of Base.</li> <li>Clearing the browser cache has no effect on point 3.</li> <li>Opening WP Admin in another browser not used before has no effect on point 3.</li> <li>Activating Twenty Twenty and then activating Base Child (still as a child of Twenty Twenty) makes Base Child behave like a real child of Twenty Twenty. No more custom post types and Appearance/Customize works as expected. At this point, Base Child is activated.</li> <li>Declared Base Child as a child of Base in its <code>style.css</code>. Went to the browser and it looks like Base Child is still a child of Twenty Twenty. No custom post types, no Appearance/Customize issues.</li> <li>Activate Base, then activate Base Child as a child of Base: CPTs of Base appear, Appearance/Customize ceases to work as described in point 1.</li> </ol> <p>I'm baffled. Looked everywhere, tried everything, nothing helped. It seems WP has a cache of its own, database related perhaps, otherwise I can't explain why the CPTs remain when I switch themes. It has nothing to do with browser cache.</p> <p>Please help.</p>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/25
[ "https://wordpress.stackexchange.com/questions/373729", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193688/" ]
Update: I created a fresh new installation of WordPress, copied both Base and Base Child themes and activated Base Child. The Appearance/Customize gives the same white screen as described in point 1 below. I then activated Base and the Appearance/Customize screen has the same error, which did not occur on the previous WP installation. This leads me to believe I have an issue with my customizer code. I WILL get to the bottom of this. --- I developed a custom theme, let's call it "Base", based on <https://underscores.me/>, which is the boilerplate for several other child themes. The Base theme features several theme mods accessible via the theme customizer. I also created a child theme of Base, A.K.A. "Base Child", right now containing only the style.css file, which is copied below: ``` /* Theme Name: Base Child Template: base Theme URI: https://blabla.com/ Author: Me Author URI: https://blabla.com/ Description: Base Child Version: 1.0.0 Text Domain: base-child Tags: custom-background, custom-logo, custom-menu, featured-images, threaded-comments, translation-ready */ ``` The only plugins installed are: 1. ACF Photo Gallery Field 2. Advanced Custom Fields (the free version) 3. Simple Page Ordering Everything works fine when the Base theme is activated, meaning all custom post types are there, the theme customizer works perfectly, all shortcodes behave like they should etc. Things can be very confusing from now on, so please be patient with me. As soon as I activate Base Child, weird things start to happen: 1. If I go to Appearance/Customize, I get a screen showing only the "You are customizing Site Name" message and the page title is "Customizing: Loading..." forever. Nothing else works. 2. Related to point 1, a console inspection reveals this JS error on the page: `Uncaught SyntaxError: Unexpected token '<' on customize.php on line 5240`, and when looking at the page source, I'm finding what looks like a php error: `Warning: sprintf(): Too few arguments in C:\wamp64\www\base-boilerplate\wp-includes\theme.php on line <i>1027</i>` 3. Trying to replicate this issue with another theme, I installed Twenty Twenty and declared Base Child to be a child of Twenty Twenty in its `style.css`. I was amazed to see that all the custom post types created in Base were present in Base Child as a Twenty Twenty child. Going to Appearance/Customize, I get the same behavior as at point 1. It's as if Base Child was still a child of Base. 4. Clearing the browser cache has no effect on point 3. 5. Opening WP Admin in another browser not used before has no effect on point 3. 6. Activating Twenty Twenty and then activating Base Child (still as a child of Twenty Twenty) makes Base Child behave like a real child of Twenty Twenty. No more custom post types and Appearance/Customize works as expected. At this point, Base Child is activated. 7. Declared Base Child as a child of Base in its `style.css`. Went to the browser and it looks like Base Child is still a child of Twenty Twenty. No custom post types, no Appearance/Customize issues. 8. Activate Base, then activate Base Child as a child of Base: CPTs of Base appear, Appearance/Customize ceases to work as described in point 1. I'm baffled. Looked everywhere, tried everything, nothing helped. It seems WP has a cache of its own, database related perhaps, otherwise I can't explain why the CPTs remain when I switch themes. It has nothing to do with browser cache. Please help.
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,769
<p>I am creating a plugin to send posts to an external program. But I get a problem by getting the posts.</p> <p>I created the code below to get the posts and echo them. But if I run it, it goes to the empty error message. When I echo the response. It only gets 'Array'</p> <p>If I just post <code>http://localhost/wordpress/wp-json/wp/v2/posts</code> in a browser, I get a JSON with my posts</p> <p>What am I doing wrong?</p> <pre><code>$remoteargs = array( 'timeout' =&gt; 20, 'redirection' =&gt; 5, 'httpversion' =&gt; '1.1', 'blocking' =&gt; false, 'headers' =&gt; array(), 'cookies' =&gt; array(), 'sslverify' =&gt; false, ); $response = wp_remote_get( 'http://localhost/wordpress/wp-json/wp/v2/posts', $remoteargs ); // Exit if error. if ( is_wp_error( $response ) ) { echo $response-&gt;get_error_message(); return; } // Get the body. $posts = json_decode( wp_remote_retrieve_body( $response ) ); // Exit if nothing is returned. if ( empty( $posts ) ) { echo 'emptyerror'; return; } foreach ( $posts as $post ) { echo $post; }** </code></pre>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/26
[ "https://wordpress.stackexchange.com/questions/373769", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193728/" ]
I am creating a plugin to send posts to an external program. But I get a problem by getting the posts. I created the code below to get the posts and echo them. But if I run it, it goes to the empty error message. When I echo the response. It only gets 'Array' If I just post `http://localhost/wordpress/wp-json/wp/v2/posts` in a browser, I get a JSON with my posts What am I doing wrong? ``` $remoteargs = array( 'timeout' => 20, 'redirection' => 5, 'httpversion' => '1.1', 'blocking' => false, 'headers' => array(), 'cookies' => array(), 'sslverify' => false, ); $response = wp_remote_get( 'http://localhost/wordpress/wp-json/wp/v2/posts', $remoteargs ); // Exit if error. if ( is_wp_error( $response ) ) { echo $response->get_error_message(); return; } // Get the body. $posts = json_decode( wp_remote_retrieve_body( $response ) ); // Exit if nothing is returned. if ( empty( $posts ) ) { echo 'emptyerror'; return; } foreach ( $posts as $post ) { echo $post; }** ```
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,771
<p>So I've been integrating WooCommerce with Stripe checkout and set everything up correctly, but when it comes to paying I get this response after hitting 'Place Order':</p> <pre><code>No such customer: 'cus_Hu9exn9bPLd3SA'; a similar object exists in test mode, but a live mode key was used to make this request. </code></pre> <p>I've set the test mode keys (and client ID) correctly in the backend - set woocommerce to 'enable test mode'. Everything seems ok. When viewing stripe test mode it creates the customer correctly as well, but its almost as if its 'redirecting' or 'reporting' back a live mode key or something?</p> <p>Manually checked the source and definitely test mode keys there (its obviously working as its creating the customer in test mode as well). Looking at the webhook attempts it does this: <a href="https://i.stack.imgur.com/jgxBo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jgxBo.png" alt="stripe webhook rows" /></a></p> <p>So thats obviously working. But when it comes to 'charging' it seems to fail. In WooCommerce orders it shows 'pending payment'.`</p> <p>Any help appreciated :?</p> <p>Thanks</p> <p>Nick</p>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/26
[ "https://wordpress.stackexchange.com/questions/373771", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193731/" ]
So I've been integrating WooCommerce with Stripe checkout and set everything up correctly, but when it comes to paying I get this response after hitting 'Place Order': ``` No such customer: 'cus_Hu9exn9bPLd3SA'; a similar object exists in test mode, but a live mode key was used to make this request. ``` I've set the test mode keys (and client ID) correctly in the backend - set woocommerce to 'enable test mode'. Everything seems ok. When viewing stripe test mode it creates the customer correctly as well, but its almost as if its 'redirecting' or 'reporting' back a live mode key or something? Manually checked the source and definitely test mode keys there (its obviously working as its creating the customer in test mode as well). Looking at the webhook attempts it does this: [![stripe webhook rows](https://i.stack.imgur.com/jgxBo.png)](https://i.stack.imgur.com/jgxBo.png) So thats obviously working. But when it comes to 'charging' it seems to fail. In WooCommerce orders it shows 'pending payment'.` Any help appreciated :? Thanks Nick
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,777
<p>I have an input field and when users enter any text then that will check the category name is available or not which user entered.</p> <p><strong>Js</strong></p> <pre><code>(function($) { // ready handler $(&quot;.universalSearchField&quot;).keypress(function() { $.ajax({ url: &quot;/wp-admin/admin-ajax.php&quot;, type: &quot;post&quot;, data: { action: &quot;universalSearchlist&quot;, keyword: $(&quot;#searchdata&quot;).val() }, success: function(data) { console.log(data); // $(&quot;#datafetch&quot;).html( data ); } }); }); })(jQuery); </code></pre> <p>Function.php</p> <pre><code> add_action('wp_ajax_universalSearchlist','universalSearch'); add_action('wp_ajax_nopriv_universalSearchlist','universalSearch'); function universalSearch(){ $the_query = new WP_Query( array('category_name' =&gt; esc_attr( $_POST['universalSearchlist'] ), 'post_type' =&gt; 'post' ) ); foreach ( $the_query-&gt;posts as $p ) { $categories = get_the_category($p-&gt;ID); if (!empty($categories) ) { echo esc_html( $categories[0]-&gt;name ); } } } </code></pre> <p>I am getting all the categories and I want when the user starts to enter the text box then start checking the category name is available or not.</p>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/26
[ "https://wordpress.stackexchange.com/questions/373777", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/177715/" ]
I have an input field and when users enter any text then that will check the category name is available or not which user entered. **Js** ``` (function($) { // ready handler $(".universalSearchField").keypress(function() { $.ajax({ url: "/wp-admin/admin-ajax.php", type: "post", data: { action: "universalSearchlist", keyword: $("#searchdata").val() }, success: function(data) { console.log(data); // $("#datafetch").html( data ); } }); }); })(jQuery); ``` Function.php ``` add_action('wp_ajax_universalSearchlist','universalSearch'); add_action('wp_ajax_nopriv_universalSearchlist','universalSearch'); function universalSearch(){ $the_query = new WP_Query( array('category_name' => esc_attr( $_POST['universalSearchlist'] ), 'post_type' => 'post' ) ); foreach ( $the_query->posts as $p ) { $categories = get_the_category($p->ID); if (!empty($categories) ) { echo esc_html( $categories[0]->name ); } } } ``` I am getting all the categories and I want when the user starts to enter the text box then start checking the category name is available or not.
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,808
<p>I try to create blog page with specific categories (by ID) and display only newest blog post from this category. I have code like this but it shows only first category. I have work code for display only one category but when I put more id it doesn't work</p> <pre><code>&lt;?php /** * Template Name: Porftfolio */ get_header(); ?&gt; &lt;div id=&quot;primary&quot; class=&quot;content-area&quot;&gt; &lt;main id=&quot;main&quot; class=&quot;site-main&quot; role=&quot;main&quot;&gt; &lt;?php $args = array( 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'cat' =&gt; '187,186', 'posts_per_page' =&gt; 1, ); $arr_posts = new WP_Query( $args ); if ( $arr_posts-&gt;have_posts() ) : while ( $arr_posts-&gt;have_posts() ) : $arr_posts-&gt;the_post(); ?&gt; &lt;article id=&quot;post-&lt;?php the_ID(); ?&gt;&quot; &lt;?php post_class(); ?&gt;&gt; &lt;?php if ( has_post_thumbnail() ) : the_post_thumbnail(); endif; ?&gt; &lt;header class=&quot;entry-header&quot;&gt; &lt;h1 class=&quot;entry-title&quot;&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;/header&gt; &lt;div class=&quot;entry-content&quot;&gt; &lt;a href&gt; &lt;?php the_permalink(); ?&gt; &lt;/a&gt; &lt;/div&gt; &lt;/article&gt; &lt;?php endwhile; endif; ?&gt; &lt;/main&gt;&lt;!-- .site-main --&gt; &lt;/div&gt;&lt;!-- .content-area --&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/26
[ "https://wordpress.stackexchange.com/questions/373808", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193750/" ]
I try to create blog page with specific categories (by ID) and display only newest blog post from this category. I have code like this but it shows only first category. I have work code for display only one category but when I put more id it doesn't work ``` <?php /** * Template Name: Porftfolio */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'cat' => '187,186', 'posts_per_page' => 1, ); $arr_posts = new WP_Query( $args ); if ( $arr_posts->have_posts() ) : while ( $arr_posts->have_posts() ) : $arr_posts->the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php if ( has_post_thumbnail() ) : the_post_thumbnail(); endif; ?> <header class="entry-header"> <h1 class="entry-title"><?php the_title(); ?></h1> </header> <div class="entry-content"> <a href> <?php the_permalink(); ?> </a> </div> </article> <?php endwhile; endif; ?> </main><!-- .site-main --> </div><!-- .content-area --> <?php get_footer(); ?> ```
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,847
<p>Based on <a href="https://stackoverflow.com/questions/50183646/check-the-first-login-wordpress">this</a> answer i created a small functionality for users that are logging in for <em>the first 3 times</em> to make some elements classes use css animation. What i am trying to do is to adjust this code to count and control the first 3 times of <strong>all user roles</strong> except <strong>subscribers</strong>.</p> <p>Basically i need this functionality to start counting the first login by user role. Lets say the first time a contributor login, or an editor, or better <strong>all user roles</strong> except <strong>subscribers</strong></p> <p>Here is my code so far</p> <pre><code>add_action( 'wp_login', 'track_user_logins', 10, 2 ); function track_user_logins( $user_login, $user ){ if( $login_amount = get_user_meta( $user-&gt;id, 'login_amount', true ) ){ // They've Logged In Before, increment existing total by 1 update_user_meta( $user-&gt;id, 'login_amount', ++$login_amount ); } else { // First Login, set it to 1 update_user_meta( $user-&gt;id, 'login_amount', 1 ); } } add_action('wp_head', 'notificationcss'); function notificationcss{ if ( !current_user_can('subscriber') ) { // Get current total amount of logins (should be at least 1) $login_amount = get_user_meta( get_current_user_id(), 'login_amount', true ); // return content based on how many times they've logged in. if( $login_amount &lt;= 3 ){ echo '&lt;style&gt;.create-post {animation: pulse-blue 2s 7;} .bb-header-icon.logged-in-user.element-toggle.only-mobile img{animation: pulse-red 2s 7;} &lt;/style&gt;'; } else { echo '&lt;style&gt;.create-post {animation: none;} .bb-header-icon.logged-in-user.element-toggle.only-mobile img{animation: none;} &lt;/style&gt;'; } } } </code></pre> <p>How could i manipulate the <em>track_user_logins</em> function to count the login times for all roles except subscribers. The existing function counts all users.</p> <p><em>Example: A user is registered in the site for the first time with role <em>Subscriber</em>. After some login times(lets say 7-8), his role is being changes to <em>Contributor</em>. From that first time logged in as a Contributor the <em>track_user_logins</em> should start counting.</em></p> <p>Any ideas would be gladly appreciated.</p>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/27
[ "https://wordpress.stackexchange.com/questions/373847", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129972/" ]
Based on [this](https://stackoverflow.com/questions/50183646/check-the-first-login-wordpress) answer i created a small functionality for users that are logging in for *the first 3 times* to make some elements classes use css animation. What i am trying to do is to adjust this code to count and control the first 3 times of **all user roles** except **subscribers**. Basically i need this functionality to start counting the first login by user role. Lets say the first time a contributor login, or an editor, or better **all user roles** except **subscribers** Here is my code so far ``` add_action( 'wp_login', 'track_user_logins', 10, 2 ); function track_user_logins( $user_login, $user ){ if( $login_amount = get_user_meta( $user->id, 'login_amount', true ) ){ // They've Logged In Before, increment existing total by 1 update_user_meta( $user->id, 'login_amount', ++$login_amount ); } else { // First Login, set it to 1 update_user_meta( $user->id, 'login_amount', 1 ); } } add_action('wp_head', 'notificationcss'); function notificationcss{ if ( !current_user_can('subscriber') ) { // Get current total amount of logins (should be at least 1) $login_amount = get_user_meta( get_current_user_id(), 'login_amount', true ); // return content based on how many times they've logged in. if( $login_amount <= 3 ){ echo '<style>.create-post {animation: pulse-blue 2s 7;} .bb-header-icon.logged-in-user.element-toggle.only-mobile img{animation: pulse-red 2s 7;} </style>'; } else { echo '<style>.create-post {animation: none;} .bb-header-icon.logged-in-user.element-toggle.only-mobile img{animation: none;} </style>'; } } } ``` How could i manipulate the *track\_user\_logins* function to count the login times for all roles except subscribers. The existing function counts all users. *Example: A user is registered in the site for the first time with role *Subscriber*. After some login times(lets say 7-8), his role is being changes to *Contributor*. From that first time logged in as a Contributor the *track\_user\_logins* should start counting.* Any ideas would be gladly appreciated.
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```
373,880
<p>Hello WP DEV Community,</p> <p>I understand this question has been asked ad nauseam...</p> <p>I'm trying to customize a development workflow (WordPress + WooCommerce) that allows me to develop locally (to speed up development, see changes instantly in browser) -- then push to PROD.</p> <p>After reading many StackExchange posts/articles/forums, this does not appear to be a trivial task.</p> <p>I am hoping to gain some insights with the following question that will help me with the above goal. I am primarily trying to understand the specifics below (not necessarily how to go about designing the actual workflow). I have a few models already in mind. Understanding these details will assist in how I tailor my workflow -- along with some other things I hope to accomplish.</p> <ul> <li>Admin Panel:</li> </ul> <p>Making WP config changes updates entries in the database only?</p> <ul> <li>Flatsome theme with UX Builder:</li> </ul> <p>Making changes here appears to touch both the theme flat-files and the database (if you create new pages)?</p> <ul> <li>WooCommerce:</li> </ul> <p>It appears that WooCommerce uses the WP DB/Tables (and not strictly it's own tables)?</p> <p>&quot;Products are a type of 'post,' meaning that you can migrate products between sites the same way you migrate posts. Products are stored in the database within the 'wp_posts' table, with meta data inside wp_postmeta.&quot;</p> <p>I suspect that all customer accounts, comments etc are stored in the database as well (no flat-files are touched)?</p> <p>The DB is live (constantly evolving) with updates by customers: new accounts, account changes, comments, orders etc.</p> <p>There does not appear to be a clear (table-level) separation between WP core, Themes and WooCommerce?</p> <p>Given the above, is it possible to export specific (non WooCommcerce) tables from the PROD DB and import to the DEV DB &gt; make theme-level/WP changes &gt; push flat-files/import specific tables back to PROD without without destroying anything in PROD?</p> <p>Thanks!</p>
[ { "answer_id": 373443, "author": "Suresh Shinde", "author_id": 167466, "author_profile": "https://wordpress.stackexchange.com/users/167466", "pm_score": -1, "selected": false, "text": "<p>You can do it by .htaccess file, for your case url format as;</p>\n<p>Redirect 301 /%post_id%/ <a href=\"https://elrons.co.il/%postname%/\" rel=\"nofollow noreferrer\">https://elrons.co.il/%postname%/</a></p>\n<p>Or</p>\n<p>By redirection plugin, for example <a href=\"https://wordpress.org/plugins/eps-301-redirects/\" rel=\"nofollow noreferrer\">301 Redirects – Easy Redirect Manager</a></p>\n" }, { "answer_id": 373444, "author": "Elron", "author_id": 98773, "author_profile": "https://wordpress.stackexchange.com/users/98773", "pm_score": 1, "selected": true, "text": "<p>I've written my own solution, sharing it and hoping it will help someone.</p>\n<p>Add this to your <code>functions.php</code>:</p>\n<pre><code>&lt;?php\n\nadd_action('parse_request', 'redirect_postid_to_postname');\nfunction redirect_postid_to_postname($wp)\n{\n // If /%post_id%/\n if (is_numeric($wp-&gt;request)) {\n\n $post_id = $wp-&gt;request;\n $slug = get_post_field( 'post_name', $post_id );\n\n // If the post slug === the post number, prevent redirection loops.\n if ($slug !== $post_id) {\n \n // Adding url parameters manually to $redirect_to\n $parameters = $_SERVER[QUERY_STRING];\n\n $redirect_from = (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] === 'on' ? &quot;https&quot; : &quot;http&quot;) . &quot;://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]&quot;;\n $redirect_to = get_permalink($post_id) . (!empty($parameters) ? (&quot;?&quot; . $parameters) : &quot;&quot;);\n \n // Prevent loops\n if($redirect_from !== $redirect_to) {\n wp_redirect($redirect_to, 301);\n exit;\n }\n\n }\n }\n}\n</code></pre>\n" } ]
2020/08/27
[ "https://wordpress.stackexchange.com/questions/373880", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/193719/" ]
Hello WP DEV Community, I understand this question has been asked ad nauseam... I'm trying to customize a development workflow (WordPress + WooCommerce) that allows me to develop locally (to speed up development, see changes instantly in browser) -- then push to PROD. After reading many StackExchange posts/articles/forums, this does not appear to be a trivial task. I am hoping to gain some insights with the following question that will help me with the above goal. I am primarily trying to understand the specifics below (not necessarily how to go about designing the actual workflow). I have a few models already in mind. Understanding these details will assist in how I tailor my workflow -- along with some other things I hope to accomplish. * Admin Panel: Making WP config changes updates entries in the database only? * Flatsome theme with UX Builder: Making changes here appears to touch both the theme flat-files and the database (if you create new pages)? * WooCommerce: It appears that WooCommerce uses the WP DB/Tables (and not strictly it's own tables)? "Products are a type of 'post,' meaning that you can migrate products between sites the same way you migrate posts. Products are stored in the database within the 'wp\_posts' table, with meta data inside wp\_postmeta." I suspect that all customer accounts, comments etc are stored in the database as well (no flat-files are touched)? The DB is live (constantly evolving) with updates by customers: new accounts, account changes, comments, orders etc. There does not appear to be a clear (table-level) separation between WP core, Themes and WooCommerce? Given the above, is it possible to export specific (non WooCommcerce) tables from the PROD DB and import to the DEV DB > make theme-level/WP changes > push flat-files/import specific tables back to PROD without without destroying anything in PROD? Thanks!
I've written my own solution, sharing it and hoping it will help someone. Add this to your `functions.php`: ``` <?php add_action('parse_request', 'redirect_postid_to_postname'); function redirect_postid_to_postname($wp) { // If /%post_id%/ if (is_numeric($wp->request)) { $post_id = $wp->request; $slug = get_post_field( 'post_name', $post_id ); // If the post slug === the post number, prevent redirection loops. if ($slug !== $post_id) { // Adding url parameters manually to $redirect_to $parameters = $_SERVER[QUERY_STRING]; $redirect_from = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $redirect_to = get_permalink($post_id) . (!empty($parameters) ? ("?" . $parameters) : ""); // Prevent loops if($redirect_from !== $redirect_to) { wp_redirect($redirect_to, 301); exit; } } } } ```