qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
306,726
<p>I apologize in advance if this is wrong place to ask my question (mods: please move it to appropriate place)</p> <hr> <p>I'm seeing following message in my wordpress logs:</p> <blockquote> <p>PHP Warning: include(): Unable to allocate memory for pool.</p> </blockquote> <p>and/or</p> <blockquote> <p>PHP Warning: Unknown: Unable to allocate memory for pool. in Unknown on line 0</p> </blockquote> <p><code>php -v</code>:</p> <pre><code># php -v PHP 5.3.3 (cli) (built: Nov 7 2016 11:21:30) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies # </code></pre> <p><code>memory_limit</code> and/or <code>apc.shm_size</code> set to <code>128M</code>:</p> <pre><code># grep ^memory_limit ./php.ini memory_limit = 128M # grep ^apc.shm_size ./php.d/apc.ini apc.shm_size=128M # </code></pre> <hr> <p>I've tried setting <code>memory_limit</code> to <code>-1</code> and/or <code>512M</code> for test, yet same results (message above).</p> <p>Please advise.</p>
[ { "answer_id": 306735, "author": "Edward Caissie", "author_id": 1952, "author_profile": "https://wordpress.stackexchange.com/users/1952", "pm_score": 1, "selected": false, "text": "<p>Does this topic help (it appears to be referencing the items you are looking at currently) <a href=\"https://stackoverflow.com/questions/3723316/what-is-causing-unable-to-allocate-memory-for-pool-in-php\">https://stackoverflow.com/questions/3723316/what-is-causing-unable-to-allocate-memory-for-pool-in-php</a> ?</p>\n" }, { "answer_id": 306808, "author": "Lisa Baird", "author_id": 145764, "author_profile": "https://wordpress.stackexchange.com/users/145764", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem. I caused it when tried increasing my memory limits by editing the. htaccess, wpconfig and wpsetup files. Undoing my changes didn't help so I just started over since it was a new setup. I would look at these files as a starting point. </p>\n" } ]
2018/06/22
[ "https://wordpress.stackexchange.com/questions/306726", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3255/" ]
I apologize in advance if this is wrong place to ask my question (mods: please move it to appropriate place) --- I'm seeing following message in my wordpress logs: > > PHP Warning: include(): Unable to allocate memory for pool. > > > and/or > > PHP Warning: Unknown: Unable to allocate memory for pool. in Unknown > on line 0 > > > `php -v`: ``` # php -v PHP 5.3.3 (cli) (built: Nov 7 2016 11:21:30) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies # ``` `memory_limit` and/or `apc.shm_size` set to `128M`: ``` # grep ^memory_limit ./php.ini memory_limit = 128M # grep ^apc.shm_size ./php.d/apc.ini apc.shm_size=128M # ``` --- I've tried setting `memory_limit` to `-1` and/or `512M` for test, yet same results (message above). Please advise.
Does this topic help (it appears to be referencing the items you are looking at currently) <https://stackoverflow.com/questions/3723316/what-is-causing-unable-to-allocate-memory-for-pool-in-php> ?
306,752
<p>I'm hoping someone who knows more than me about PHP and WordPress can help me out with this issue. I have a custom post type with posts I am displaying using the following code:</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'upcoming_event', 'posts_per_page' =&gt; 3 ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); echo '&lt;div class="upcomingevents"&gt;'; echo '&lt;h4&gt;'; the_title(); echo '&lt;/h4&gt;'; echo '&lt;div class="upcomingeventimage"&gt;'; the_post_thumbnail('medium'); echo '&lt;/div&gt;'; echo '&lt;div class="upcoming-event-entry-content"&gt;'; the_content(); echo '&lt;/div&gt;'; echo '&lt;/div&gt;'; endwhile; wp_reset_postdata(); ?&gt; </code></pre> <p>While this works fine in a php file, I'm trying to also make it easily accessible via shortcode. I made the shortcode, and the shortcode works, but every time I place it on a page/post and click "update" or "publish" it sends me to a page with this content printed on it (and only this content printed on it)... But it still saves it, and it still displays fine on the page I saved it on. I know I'm missing something, but I'm so novice at PHP that I don't know what it is.</p> <p>Here's my shortcode:</p> <pre><code>// Shortcode for Upcoming Events function upcoming_events_shortcode() { $args = array( 'post_type' =&gt; 'upcoming_event', 'posts_per_page' =&gt; 3 ); $query = new WP_Query( $args ); while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); echo '&lt;div class="upcomingevents"&gt;'; echo '&lt;h4&gt;'; the_title(); echo '&lt;/h4&gt;'; echo '&lt;div class="upcomingeventimage"&gt;'; the_post_thumbnail('medium'); echo '&lt;/div&gt;'; echo '&lt;div class="upcoming-event-entry-content"&gt;'; the_content(); echo '&lt;/div&gt;'; echo '&lt;/div&gt;'; endwhile; wp_reset_postdata(); } add_shortcode('upcoming-events', 'upcoming_events_shortcode'); </code></pre> <p>Thanks for any help! I'm learning as I go with this and usually I can Google my way out of most things, not this one though. Scratching my head on it.</p>
[ { "answer_id": 306735, "author": "Edward Caissie", "author_id": 1952, "author_profile": "https://wordpress.stackexchange.com/users/1952", "pm_score": 1, "selected": false, "text": "<p>Does this topic help (it appears to be referencing the items you are looking at currently) <a href=\"https://stackoverflow.com/questions/3723316/what-is-causing-unable-to-allocate-memory-for-pool-in-php\">https://stackoverflow.com/questions/3723316/what-is-causing-unable-to-allocate-memory-for-pool-in-php</a> ?</p>\n" }, { "answer_id": 306808, "author": "Lisa Baird", "author_id": 145764, "author_profile": "https://wordpress.stackexchange.com/users/145764", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem. I caused it when tried increasing my memory limits by editing the. htaccess, wpconfig and wpsetup files. Undoing my changes didn't help so I just started over since it was a new setup. I would look at these files as a starting point. </p>\n" } ]
2018/06/22
[ "https://wordpress.stackexchange.com/questions/306752", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145742/" ]
I'm hoping someone who knows more than me about PHP and WordPress can help me out with this issue. I have a custom post type with posts I am displaying using the following code: ``` <?php $args = array( 'post_type' => 'upcoming_event', 'posts_per_page' => 3 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); echo '<div class="upcomingevents">'; echo '<h4>'; the_title(); echo '</h4>'; echo '<div class="upcomingeventimage">'; the_post_thumbnail('medium'); echo '</div>'; echo '<div class="upcoming-event-entry-content">'; the_content(); echo '</div>'; echo '</div>'; endwhile; wp_reset_postdata(); ?> ``` While this works fine in a php file, I'm trying to also make it easily accessible via shortcode. I made the shortcode, and the shortcode works, but every time I place it on a page/post and click "update" or "publish" it sends me to a page with this content printed on it (and only this content printed on it)... But it still saves it, and it still displays fine on the page I saved it on. I know I'm missing something, but I'm so novice at PHP that I don't know what it is. Here's my shortcode: ``` // Shortcode for Upcoming Events function upcoming_events_shortcode() { $args = array( 'post_type' => 'upcoming_event', 'posts_per_page' => 3 ); $query = new WP_Query( $args ); while ( $query->have_posts() ) : $query->the_post(); echo '<div class="upcomingevents">'; echo '<h4>'; the_title(); echo '</h4>'; echo '<div class="upcomingeventimage">'; the_post_thumbnail('medium'); echo '</div>'; echo '<div class="upcoming-event-entry-content">'; the_content(); echo '</div>'; echo '</div>'; endwhile; wp_reset_postdata(); } add_shortcode('upcoming-events', 'upcoming_events_shortcode'); ``` Thanks for any help! I'm learning as I go with this and usually I can Google my way out of most things, not this one though. Scratching my head on it.
Does this topic help (it appears to be referencing the items you are looking at currently) <https://stackoverflow.com/questions/3723316/what-is-causing-unable-to-allocate-memory-for-pool-in-php> ?
306,756
<p>I noticed recently that when uploading files larger than 7mb to a Wordpress site that I developed, I get an HTTP Error. I've checked some of my PHP variables, and have verified that <code>memory_limit</code> is set to 256M and both <code>post_max_size</code> and <code>upload_max_filesize</code> are set to 128M. After reading <a href="https://wordpress.stackexchange.com/questions/51592/http-error-when-uploading-images">this thread</a>, I tried installing the Default to GD plugin that uses GD as the default WP_Image_Editor class.</p> <p>After installing the plugin, I'm not having the issue anymore. That said, I'm curious if there's a way to fix this issue with the newer WP_Image_Editor class?</p> <p>I've also noticed that when I get the HTTP error, I can look at the files attached to the post I added the file to and see that the file is actually there and was successfully uploaded. However, Wordpress seems to have issues displaying it in the Media browser.</p> <p>I also noticed that if I upload multiple large images over 7mb, I will see the most recent image as the first item in the media library. If I delete that image, I'll see the next most recently uploaded image. For some reason Wordpress is only able to show the most recent image and the thumbnail seems to be broken. However if you navigate to the uploaded file's URI, you can see that the file uploaded successfully.</p> <p>Does anyone have an idea what's going on with this and is this a known error in Wordpress that's being addressed? Thanks!</p>
[ { "answer_id": 306761, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": false, "text": "<p>I sometimes get this exact same issue and set of symptoms.</p>\n\n<p>It's caused by the image being too large for the memory available. Not the file size as that has compressed data, but the actual width x height x colourdepth.</p>\n\n<p>You can see the full size image because it uploaded fine. You have trouble in the media browser because WP ran out of memory while scaling and cropping the image and so there is no version available for the media browser thumbnail. </p>\n\n<p>I've always found that allocating much more memory to the process fixes it. Or use smaller images (dimensions, not file size).</p>\n\n<p>WordPress will use the higher of WP_MAX_MEMORY_LIMIT and your PHP memory limit, so as long as your hosting allows the easiest thing to do is to set WP_MAX_MEMORY_LIMIT in your wp-config.php:</p>\n\n<pre><code>define( 'WP_MAX_MEMORY_LIMIT', '257M' ); // you choose how much\n</code></pre>\n\n<p>The default is 256M for image handling anyway, so if you have problems resizing images it'll need to be something higher than 256M.</p>\n\n<p>As long as your host allows PHP to increase the memory using <code>@ini_set</code> then this will work.</p>\n" }, { "answer_id": 306764, "author": "Evaluation Unit", "author_id": 145742, "author_profile": "https://wordpress.stackexchange.com/users/145742", "pm_score": 0, "selected": false, "text": "<p>You will need to change your memory limit within your php.ini file. You will want to add or update the following information:</p>\n\n<pre><code>define('WP_MEMORY_LIMIT', '256M');\n</code></pre>\n\n<p>In my personal experience, I wouldn't make it 256 MB, but I'd maybe make it 60 as opposed to 40 like you said above.</p>\n" }, { "answer_id": 306781, "author": "Ariful Islam", "author_id": 20831, "author_profile": "https://wordpress.stackexchange.com/users/20831", "pm_score": 0, "selected": false, "text": "<p>if you are running apache base webserver then you could use this code into your htaccess file </p>\n\n<p><code>SetEnv MAGICK_THREAD_LIMIT 1</code></p>\n\n<p>I have fixed my problem by using this code. You can try. </p>\n" } ]
2018/06/22
[ "https://wordpress.stackexchange.com/questions/306756", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47939/" ]
I noticed recently that when uploading files larger than 7mb to a Wordpress site that I developed, I get an HTTP Error. I've checked some of my PHP variables, and have verified that `memory_limit` is set to 256M and both `post_max_size` and `upload_max_filesize` are set to 128M. After reading [this thread](https://wordpress.stackexchange.com/questions/51592/http-error-when-uploading-images), I tried installing the Default to GD plugin that uses GD as the default WP\_Image\_Editor class. After installing the plugin, I'm not having the issue anymore. That said, I'm curious if there's a way to fix this issue with the newer WP\_Image\_Editor class? I've also noticed that when I get the HTTP error, I can look at the files attached to the post I added the file to and see that the file is actually there and was successfully uploaded. However, Wordpress seems to have issues displaying it in the Media browser. I also noticed that if I upload multiple large images over 7mb, I will see the most recent image as the first item in the media library. If I delete that image, I'll see the next most recently uploaded image. For some reason Wordpress is only able to show the most recent image and the thumbnail seems to be broken. However if you navigate to the uploaded file's URI, you can see that the file uploaded successfully. Does anyone have an idea what's going on with this and is this a known error in Wordpress that's being addressed? Thanks!
I sometimes get this exact same issue and set of symptoms. It's caused by the image being too large for the memory available. Not the file size as that has compressed data, but the actual width x height x colourdepth. You can see the full size image because it uploaded fine. You have trouble in the media browser because WP ran out of memory while scaling and cropping the image and so there is no version available for the media browser thumbnail. I've always found that allocating much more memory to the process fixes it. Or use smaller images (dimensions, not file size). WordPress will use the higher of WP\_MAX\_MEMORY\_LIMIT and your PHP memory limit, so as long as your hosting allows the easiest thing to do is to set WP\_MAX\_MEMORY\_LIMIT in your wp-config.php: ``` define( 'WP_MAX_MEMORY_LIMIT', '257M' ); // you choose how much ``` The default is 256M for image handling anyway, so if you have problems resizing images it'll need to be something higher than 256M. As long as your host allows PHP to increase the memory using `@ini_set` then this will work.
306,784
<p><a href="https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet" rel="nofollow noreferrer">WordPress documentation</a> says to enqueue parent stylesheet in child theme:</p> <pre><code>add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { $parent_style = 'parent-style'; // Why enqueue parent style again? The child theme works perfectly without this line wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()-&gt;get('Version') ); } </code></pre> <p>But parent theme stylesheet is already enqueued in parent theme, what's the point to enqueue it again in child theme?</p>
[ { "answer_id": 306761, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": false, "text": "<p>I sometimes get this exact same issue and set of symptoms.</p>\n\n<p>It's caused by the image being too large for the memory available. Not the file size as that has compressed data, but the actual width x height x colourdepth.</p>\n\n<p>You can see the full size image because it uploaded fine. You have trouble in the media browser because WP ran out of memory while scaling and cropping the image and so there is no version available for the media browser thumbnail. </p>\n\n<p>I've always found that allocating much more memory to the process fixes it. Or use smaller images (dimensions, not file size).</p>\n\n<p>WordPress will use the higher of WP_MAX_MEMORY_LIMIT and your PHP memory limit, so as long as your hosting allows the easiest thing to do is to set WP_MAX_MEMORY_LIMIT in your wp-config.php:</p>\n\n<pre><code>define( 'WP_MAX_MEMORY_LIMIT', '257M' ); // you choose how much\n</code></pre>\n\n<p>The default is 256M for image handling anyway, so if you have problems resizing images it'll need to be something higher than 256M.</p>\n\n<p>As long as your host allows PHP to increase the memory using <code>@ini_set</code> then this will work.</p>\n" }, { "answer_id": 306764, "author": "Evaluation Unit", "author_id": 145742, "author_profile": "https://wordpress.stackexchange.com/users/145742", "pm_score": 0, "selected": false, "text": "<p>You will need to change your memory limit within your php.ini file. You will want to add or update the following information:</p>\n\n<pre><code>define('WP_MEMORY_LIMIT', '256M');\n</code></pre>\n\n<p>In my personal experience, I wouldn't make it 256 MB, but I'd maybe make it 60 as opposed to 40 like you said above.</p>\n" }, { "answer_id": 306781, "author": "Ariful Islam", "author_id": 20831, "author_profile": "https://wordpress.stackexchange.com/users/20831", "pm_score": 0, "selected": false, "text": "<p>if you are running apache base webserver then you could use this code into your htaccess file </p>\n\n<p><code>SetEnv MAGICK_THREAD_LIMIT 1</code></p>\n\n<p>I have fixed my problem by using this code. You can try. </p>\n" } ]
2018/06/23
[ "https://wordpress.stackexchange.com/questions/306784", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2426/" ]
[WordPress documentation](https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet) says to enqueue parent stylesheet in child theme: ``` add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { $parent_style = 'parent-style'; // Why enqueue parent style again? The child theme works perfectly without this line wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version') ); } ``` But parent theme stylesheet is already enqueued in parent theme, what's the point to enqueue it again in child theme?
I sometimes get this exact same issue and set of symptoms. It's caused by the image being too large for the memory available. Not the file size as that has compressed data, but the actual width x height x colourdepth. You can see the full size image because it uploaded fine. You have trouble in the media browser because WP ran out of memory while scaling and cropping the image and so there is no version available for the media browser thumbnail. I've always found that allocating much more memory to the process fixes it. Or use smaller images (dimensions, not file size). WordPress will use the higher of WP\_MAX\_MEMORY\_LIMIT and your PHP memory limit, so as long as your hosting allows the easiest thing to do is to set WP\_MAX\_MEMORY\_LIMIT in your wp-config.php: ``` define( 'WP_MAX_MEMORY_LIMIT', '257M' ); // you choose how much ``` The default is 256M for image handling anyway, so if you have problems resizing images it'll need to be something higher than 256M. As long as your host allows PHP to increase the memory using `@ini_set` then this will work.
306,816
<p>I'm using Contact Form 7 and Flamingo to create a consultant registration form on my Wordpress site. By my client request, every submission need to have a registration code (reg_code) which is a combination of submission date and a random number to make it unique.</p> <p>So I added an hidden input field to my CF7 code with the id "reg_code". On my first try, I used JS to generate a "reg_code" variable right after users visit my site and set the hidden field value to the generated "reg_code" variable. The "reg_code" was saved to CF7 submission successfully but in some cases, when a user didn't submit the form at the first visit time but after a few days, the date part in his "reg_code" would not be correct because that code was generated at his first visit time and cached in the browser.</p> <p>To avoid this issue, I decided to move the "reg_code" generation function from JS to PHP and the procedure would be like this:</p> <ol> <li>Submit button clicked</li> <li>Use AJAX to call a PHP function which returns a reg_code</li> <li>Set the hidden field "reg_code" in CF7 value to the returned result</li> <li>Really perform CF7 submission which saves all CF7 fields to Flamingo</li> </ol> <p>This is my JS to trigger the AJAX call before CF7 submit event:</p> <pre><code>$('.wpcf7-form').on('submit', function (e) { $.ajax({ type: "post", dataType: "json", url: js_object.ajax_url, data: { action: "custom_reg_code", }, success: function (response) { if (response.success) { $('#reg_code').val(response.data) } else { console.log('Something wrong') } }, error: function (jqXHR, textStatus, errorThrown) { console.log('fail: ' + textStatus, errorThrown); }, complete: function() { } }) }) </code></pre> <p>My result: It works only some times. Only some submissions have "reg_code" value, some others have empty "reg_code".</p> <p>As my guess, the CF7 submit event won't wait for AJAX call to be complete. I tried to add <strong>e.preventDefault()</strong> to the code above to stop the default CF7 submit but no success then. I also tried the CF7 eventListener "wpcf7submit" but still no luck.</p> <p>Finally, the question is: Is there any way to pause the default CF7 submit event to modify an input field value, then continue the submission process ?</p> <p>Thank you very much</p>
[ { "answer_id": 306819, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 3, "selected": true, "text": "<p>You could save your AJAX pain and go about this in a different way by placing a hidden field within your form in PHP.</p>\n\n<h1>Method 1, with the aid of a plugin</h1>\n\n<p>I generally use the Contact Form 7 Dynamic Text Extension plugin as an easy route to creating custom CF7 tags, which still needs a little coding. You could also go the extra distance and just code your own CF7 tags, but I haven't tried that yet, but I might as an edit to this answer.</p>\n\n<p>With this plugin in place you can put tags into your CF7 form like this:</p>\n\n<pre><code>[dynamichidden custom-reg-code “CF7_custom_reg_code”]\n</code></pre>\n\n<p>And in the email pane of CF7's admin page you'd insert [custom-reg-code].</p>\n\n<p>To get it working, just make yourself a matching shortcode to generate your string:</p>\n\n<pre><code>function generateRandomString($length = 10) {\n return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);\n}\n\nfunction wpse306816_CF7_custom_reg_code() {\n\n return date(\"Ymd\") . generateRandomString();\n}\n\nadd_shortcode('CF7_custom_reg_code', 'wpse306816_CF7_custom_reg_code');\n</code></pre>\n\n<p>Hat-tip to <a href=\"https://stackoverflow.com/a/13212994/6347850\">https://stackoverflow.com/a/13212994/6347850</a> for the random number generation.</p>\n\n<p>Now you will have a hidden field in your form made up of the current date and a random number that you can use in your form's sent email or save in Flamingo just like any other CF7 field.</p>\n\n<h1>Method 2, without the aid of a plugin</h1>\n\n<p>And a little research has shown that it's even easier to just write your own CF7 tag and not bother with the plugin.</p>\n\n<p>To create a CF7 tag <code>[serial]</code>, you register it using <code>wpcf7_add_form_tag()</code> on the <code>wpcf7_init</code> action hook, passing the name of the tag and the name of a callback function to handle it:</p>\n\n<pre><code>add_action( 'wpcf7_init', 'wpse306816_CF7_add_custom_tag' );\n\nfunction wpse306816_CF7_add_custom_tag() {\n wpcf7_add_form_tag(\n 'serial',\n 'wpse306816_CF7_handle_custom_tag' );\n}\n</code></pre>\n\n<p>And for your case, the callback simply needs to return the serial string value:</p>\n\n<pre><code>function generateRandomString($length = 10) {\n return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);\n}\n\nfunction wpse306816_CF7_handle_custom_tag( $tag ) {\n return date(\"Ymd\") . generateRandomString();\n}\n</code></pre>\n" }, { "answer_id": 364708, "author": "Dan S", "author_id": 117833, "author_profile": "https://wordpress.stackexchange.com/users/117833", "pm_score": 2, "selected": false, "text": "<p>I'd like to chime in here because I was just struggling with this same problem - modifying inputs before CF7 was submitted via ajax. I believe the original poster was trying to figure out how to do this via Javascript, which Andy did not address in his answer. So here is an example of how to do that:</p>\n\n<pre><code>var form = document.getElementsByClassName('wpcf7-form')[0];\nform.addEventListener('submit', function(evt) {\n form.elements['reg_code'].value = 'parsed_code';\n}, { capture: true });\n</code></pre>\n\n<p>Pay close attention to last argument in the event listener - <code>useCapture = true</code>. This argument is false by default. My original code, which didn’t work, ignored this argument. The CF7 Ajax submission would always fire first, thus ignoring my event. By simply changing useCapture to true, your event fires first before dispatching the CF7 Ajax event. </p>\n\n<p><strike>I haven’t tried it yet, but I assume by also using <code>evt.preventDefault()</code>, you could effectively stop the CF7 Ajax form from submitting if needed.</strike> <i>Tested 4/22/2019 - doesn’t work.</i></p>\n" } ]
2018/06/23
[ "https://wordpress.stackexchange.com/questions/306816", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70137/" ]
I'm using Contact Form 7 and Flamingo to create a consultant registration form on my Wordpress site. By my client request, every submission need to have a registration code (reg\_code) which is a combination of submission date and a random number to make it unique. So I added an hidden input field to my CF7 code with the id "reg\_code". On my first try, I used JS to generate a "reg\_code" variable right after users visit my site and set the hidden field value to the generated "reg\_code" variable. The "reg\_code" was saved to CF7 submission successfully but in some cases, when a user didn't submit the form at the first visit time but after a few days, the date part in his "reg\_code" would not be correct because that code was generated at his first visit time and cached in the browser. To avoid this issue, I decided to move the "reg\_code" generation function from JS to PHP and the procedure would be like this: 1. Submit button clicked 2. Use AJAX to call a PHP function which returns a reg\_code 3. Set the hidden field "reg\_code" in CF7 value to the returned result 4. Really perform CF7 submission which saves all CF7 fields to Flamingo This is my JS to trigger the AJAX call before CF7 submit event: ``` $('.wpcf7-form').on('submit', function (e) { $.ajax({ type: "post", dataType: "json", url: js_object.ajax_url, data: { action: "custom_reg_code", }, success: function (response) { if (response.success) { $('#reg_code').val(response.data) } else { console.log('Something wrong') } }, error: function (jqXHR, textStatus, errorThrown) { console.log('fail: ' + textStatus, errorThrown); }, complete: function() { } }) }) ``` My result: It works only some times. Only some submissions have "reg\_code" value, some others have empty "reg\_code". As my guess, the CF7 submit event won't wait for AJAX call to be complete. I tried to add **e.preventDefault()** to the code above to stop the default CF7 submit but no success then. I also tried the CF7 eventListener "wpcf7submit" but still no luck. Finally, the question is: Is there any way to pause the default CF7 submit event to modify an input field value, then continue the submission process ? Thank you very much
You could save your AJAX pain and go about this in a different way by placing a hidden field within your form in PHP. Method 1, with the aid of a plugin ================================== I generally use the Contact Form 7 Dynamic Text Extension plugin as an easy route to creating custom CF7 tags, which still needs a little coding. You could also go the extra distance and just code your own CF7 tags, but I haven't tried that yet, but I might as an edit to this answer. With this plugin in place you can put tags into your CF7 form like this: ``` [dynamichidden custom-reg-code “CF7_custom_reg_code”] ``` And in the email pane of CF7's admin page you'd insert [custom-reg-code]. To get it working, just make yourself a matching shortcode to generate your string: ``` function generateRandomString($length = 10) { return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length); } function wpse306816_CF7_custom_reg_code() { return date("Ymd") . generateRandomString(); } add_shortcode('CF7_custom_reg_code', 'wpse306816_CF7_custom_reg_code'); ``` Hat-tip to <https://stackoverflow.com/a/13212994/6347850> for the random number generation. Now you will have a hidden field in your form made up of the current date and a random number that you can use in your form's sent email or save in Flamingo just like any other CF7 field. Method 2, without the aid of a plugin ===================================== And a little research has shown that it's even easier to just write your own CF7 tag and not bother with the plugin. To create a CF7 tag `[serial]`, you register it using `wpcf7_add_form_tag()` on the `wpcf7_init` action hook, passing the name of the tag and the name of a callback function to handle it: ``` add_action( 'wpcf7_init', 'wpse306816_CF7_add_custom_tag' ); function wpse306816_CF7_add_custom_tag() { wpcf7_add_form_tag( 'serial', 'wpse306816_CF7_handle_custom_tag' ); } ``` And for your case, the callback simply needs to return the serial string value: ``` function generateRandomString($length = 10) { return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length); } function wpse306816_CF7_handle_custom_tag( $tag ) { return date("Ymd") . generateRandomString(); } ```
306,859
<p>I want my WordPress homepage to display post by popularity. Like it automatically bring the post to top which have been visited by most visitors and same in ascending order. Any help will be appreciated.</p>
[ { "answer_id": 306819, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 3, "selected": true, "text": "<p>You could save your AJAX pain and go about this in a different way by placing a hidden field within your form in PHP.</p>\n\n<h1>Method 1, with the aid of a plugin</h1>\n\n<p>I generally use the Contact Form 7 Dynamic Text Extension plugin as an easy route to creating custom CF7 tags, which still needs a little coding. You could also go the extra distance and just code your own CF7 tags, but I haven't tried that yet, but I might as an edit to this answer.</p>\n\n<p>With this plugin in place you can put tags into your CF7 form like this:</p>\n\n<pre><code>[dynamichidden custom-reg-code “CF7_custom_reg_code”]\n</code></pre>\n\n<p>And in the email pane of CF7's admin page you'd insert [custom-reg-code].</p>\n\n<p>To get it working, just make yourself a matching shortcode to generate your string:</p>\n\n<pre><code>function generateRandomString($length = 10) {\n return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);\n}\n\nfunction wpse306816_CF7_custom_reg_code() {\n\n return date(\"Ymd\") . generateRandomString();\n}\n\nadd_shortcode('CF7_custom_reg_code', 'wpse306816_CF7_custom_reg_code');\n</code></pre>\n\n<p>Hat-tip to <a href=\"https://stackoverflow.com/a/13212994/6347850\">https://stackoverflow.com/a/13212994/6347850</a> for the random number generation.</p>\n\n<p>Now you will have a hidden field in your form made up of the current date and a random number that you can use in your form's sent email or save in Flamingo just like any other CF7 field.</p>\n\n<h1>Method 2, without the aid of a plugin</h1>\n\n<p>And a little research has shown that it's even easier to just write your own CF7 tag and not bother with the plugin.</p>\n\n<p>To create a CF7 tag <code>[serial]</code>, you register it using <code>wpcf7_add_form_tag()</code> on the <code>wpcf7_init</code> action hook, passing the name of the tag and the name of a callback function to handle it:</p>\n\n<pre><code>add_action( 'wpcf7_init', 'wpse306816_CF7_add_custom_tag' );\n\nfunction wpse306816_CF7_add_custom_tag() {\n wpcf7_add_form_tag(\n 'serial',\n 'wpse306816_CF7_handle_custom_tag' );\n}\n</code></pre>\n\n<p>And for your case, the callback simply needs to return the serial string value:</p>\n\n<pre><code>function generateRandomString($length = 10) {\n return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);\n}\n\nfunction wpse306816_CF7_handle_custom_tag( $tag ) {\n return date(\"Ymd\") . generateRandomString();\n}\n</code></pre>\n" }, { "answer_id": 364708, "author": "Dan S", "author_id": 117833, "author_profile": "https://wordpress.stackexchange.com/users/117833", "pm_score": 2, "selected": false, "text": "<p>I'd like to chime in here because I was just struggling with this same problem - modifying inputs before CF7 was submitted via ajax. I believe the original poster was trying to figure out how to do this via Javascript, which Andy did not address in his answer. So here is an example of how to do that:</p>\n\n<pre><code>var form = document.getElementsByClassName('wpcf7-form')[0];\nform.addEventListener('submit', function(evt) {\n form.elements['reg_code'].value = 'parsed_code';\n}, { capture: true });\n</code></pre>\n\n<p>Pay close attention to last argument in the event listener - <code>useCapture = true</code>. This argument is false by default. My original code, which didn’t work, ignored this argument. The CF7 Ajax submission would always fire first, thus ignoring my event. By simply changing useCapture to true, your event fires first before dispatching the CF7 Ajax event. </p>\n\n<p><strike>I haven’t tried it yet, but I assume by also using <code>evt.preventDefault()</code>, you could effectively stop the CF7 Ajax form from submitting if needed.</strike> <i>Tested 4/22/2019 - doesn’t work.</i></p>\n" } ]
2018/06/24
[ "https://wordpress.stackexchange.com/questions/306859", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145800/" ]
I want my WordPress homepage to display post by popularity. Like it automatically bring the post to top which have been visited by most visitors and same in ascending order. Any help will be appreciated.
You could save your AJAX pain and go about this in a different way by placing a hidden field within your form in PHP. Method 1, with the aid of a plugin ================================== I generally use the Contact Form 7 Dynamic Text Extension plugin as an easy route to creating custom CF7 tags, which still needs a little coding. You could also go the extra distance and just code your own CF7 tags, but I haven't tried that yet, but I might as an edit to this answer. With this plugin in place you can put tags into your CF7 form like this: ``` [dynamichidden custom-reg-code “CF7_custom_reg_code”] ``` And in the email pane of CF7's admin page you'd insert [custom-reg-code]. To get it working, just make yourself a matching shortcode to generate your string: ``` function generateRandomString($length = 10) { return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length); } function wpse306816_CF7_custom_reg_code() { return date("Ymd") . generateRandomString(); } add_shortcode('CF7_custom_reg_code', 'wpse306816_CF7_custom_reg_code'); ``` Hat-tip to <https://stackoverflow.com/a/13212994/6347850> for the random number generation. Now you will have a hidden field in your form made up of the current date and a random number that you can use in your form's sent email or save in Flamingo just like any other CF7 field. Method 2, without the aid of a plugin ===================================== And a little research has shown that it's even easier to just write your own CF7 tag and not bother with the plugin. To create a CF7 tag `[serial]`, you register it using `wpcf7_add_form_tag()` on the `wpcf7_init` action hook, passing the name of the tag and the name of a callback function to handle it: ``` add_action( 'wpcf7_init', 'wpse306816_CF7_add_custom_tag' ); function wpse306816_CF7_add_custom_tag() { wpcf7_add_form_tag( 'serial', 'wpse306816_CF7_handle_custom_tag' ); } ``` And for your case, the callback simply needs to return the serial string value: ``` function generateRandomString($length = 10) { return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length); } function wpse306816_CF7_handle_custom_tag( $tag ) { return date("Ymd") . generateRandomString(); } ```
306,868
<p>I'm new to wordpress and am trying to develop my first own theme. The thing is: the front page must be static, with no display of posts. But I need a blog section and am trying to do it by creating a custom page template that calls the last 10 posts.</p> <p>How would I do that using the loop? Please, help me! Thank you all in advance!</p>
[ { "answer_id": 306879, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 0, "selected": false, "text": "<p>If you create a page template with your own query, you are throwing away all the work WordPress does for you. </p>\n\n<p>In your settings set a static front page. Make a second page and in the settings choose it as your “page for posts”</p>\n\n<p>Then if your theme has a valid loop in the templates everything should just work. </p>\n" }, { "answer_id": 306984, "author": "Amritosh pandey", "author_id": 145702, "author_profile": "https://wordpress.stackexchange.com/users/145702", "pm_score": 1, "selected": false, "text": "<p>By default WordPress displays your content in a blog format on the homepage. </p>\n\n<p>Using Default Static and Blog Page Settings in WordPress.\nWordPress comes with built-in support for creating a custom home page (static front page), and a separate page for blog posts. To use this method, you need to create two new WordPress pages. </p>\n\n<p>The first page is going to be your custom home page.</p>\n\n<p>Next you need to create another page for your blog posts. You can title this page as Blog. A lot of WordPress themes come with different templates, and it is possible that your theme may have a template to be used for blog page. However, if there is no template available in your theme, then you can simply choose default. Don’t forget to disable the comments and trackbacks option on this page as well.</p>\n\n<p>Now we need to get WordPress to use these pages accordingly. To do that go to Setttings » Reading and under the Front page displays option choose A static page. Below that choose the page to be used as the front page and the page for your blog posts. Save your changes, and load your site to review changes. </p>\n\n<hr>\n\n<p>And If you want to create a custom Template that calls the latest 10 posts, You can use the following step (Note - You can use your own HTML for the required layout) -</p>\n\n<p><strong>Step 1: Page template</strong></p>\n\n<p><em>Create a blank page template named “page-blog.php” and include the following code:</em></p>\n\n<pre><code> &lt;?php\n /*\n Template Name: Blog\n */\n ?&gt;\n &lt;?php get_header(); ?&gt;\n\n &lt;div id=\"content\"&gt;\n\n &lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=10&amp;paged='. get_query_var('paged')); ?&gt;\n\n &lt;?php if( have_posts() ): ?&gt;\n\n &lt;?php while( have_posts() ): the_post(); ?&gt;\n\n &lt;div id=\"post-&lt;?php get_the_ID(); ?&gt;\" &lt;?php post_class(); ?&gt;&gt;\n\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_post_thumbnail( array(200,220) ); ?&gt;&lt;/a&gt;\n\n &lt;h2&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt;\n\n &lt;span class=\"meta\"&gt;&lt;?php author_profile_avatar_link(48); ?&gt; &lt;strong&gt;&lt;?php the_time('F jS, Y'); ?&gt;&lt;/strong&gt; / &lt;strong&gt;&lt;?php the_author_link(); ?&gt;&lt;/strong&gt; / &lt;span class=\"comments\"&gt;&lt;?php comments_popup_link(__('0 comments','example'),__('1 comment','example'),__('% comments','example')); ?&gt;&lt;/span&gt;&lt;/span&gt;\n\n &lt;?php the_excerpt(__('Continue reading »','example')); ?&gt;\n\n &lt;/div&gt;&lt;!-- /#post-&lt;?php get_the_ID(); ?&gt; --&gt;\n\n &lt;?php endwhile; ?&gt;\n\n &lt;div class=\"navigation\"&gt;\n &lt;span class=\"newer\"&gt;&lt;?php previous_posts_link(__('« Newer','example')) ?&gt;&lt;/span&gt; &lt;span class=\"older\"&gt;&lt;?php next_posts_link(__('Older »','example')) ?&gt;&lt;/span&gt;\n &lt;/div&gt;&lt;!-- /.navigation --&gt;\n\n &lt;?php else: ?&gt;\n\n &lt;div id=\"post-404\" class=\"noposts\"&gt;\n\n &lt;p&gt;&lt;?php _e('None found.','example'); ?&gt;&lt;/p&gt;\n\n &lt;/div&gt;&lt;!-- /#post-404 --&gt;\n\n &lt;?php endif; wp_reset_query(); ?&gt;\n\n &lt;/div&gt;&lt;!-- /#content --&gt;\n\n &lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p><em>Instead of showing 5 posts, you can set posts_per_page=10 or whatever works best.</em></p>\n\n<p>Note also that the HTML used in this example is rudimentary to keep things simple. You'll probably need to make a few changes to the markup to synchronize with your theme design.</p>\n\n<p><strong>Step 2: Add New Page</strong></p>\n\n<p>Once page-blog.php is complete and uploaded to the server, log in to the WP Admin and visit the Add New Page screen. There, create a new page named \"Blog\" (or whatever you want), and set its Template as \"Blog\" from the \"Page Attributes\" panel.</p>\n\n<p>Done! \nNow visit the Blog page after publishing and you should see the custom WP_Query loop working: your latest blog posts will be displayed on the page.</p>\n" } ]
2018/06/25
[ "https://wordpress.stackexchange.com/questions/306868", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145809/" ]
I'm new to wordpress and am trying to develop my first own theme. The thing is: the front page must be static, with no display of posts. But I need a blog section and am trying to do it by creating a custom page template that calls the last 10 posts. How would I do that using the loop? Please, help me! Thank you all in advance!
By default WordPress displays your content in a blog format on the homepage. Using Default Static and Blog Page Settings in WordPress. WordPress comes with built-in support for creating a custom home page (static front page), and a separate page for blog posts. To use this method, you need to create two new WordPress pages. The first page is going to be your custom home page. Next you need to create another page for your blog posts. You can title this page as Blog. A lot of WordPress themes come with different templates, and it is possible that your theme may have a template to be used for blog page. However, if there is no template available in your theme, then you can simply choose default. Don’t forget to disable the comments and trackbacks option on this page as well. Now we need to get WordPress to use these pages accordingly. To do that go to Setttings » Reading and under the Front page displays option choose A static page. Below that choose the page to be used as the front page and the page for your blog posts. Save your changes, and load your site to review changes. --- And If you want to create a custom Template that calls the latest 10 posts, You can use the following step (Note - You can use your own HTML for the required layout) - **Step 1: Page template** *Create a blank page template named “page-blog.php” and include the following code:* ``` <?php /* Template Name: Blog */ ?> <?php get_header(); ?> <div id="content"> <?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?> <?php if( have_posts() ): ?> <?php while( have_posts() ): the_post(); ?> <div id="post-<?php get_the_ID(); ?>" <?php post_class(); ?>> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( array(200,220) ); ?></a> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <span class="meta"><?php author_profile_avatar_link(48); ?> <strong><?php the_time('F jS, Y'); ?></strong> / <strong><?php the_author_link(); ?></strong> / <span class="comments"><?php comments_popup_link(__('0 comments','example'),__('1 comment','example'),__('% comments','example')); ?></span></span> <?php the_excerpt(__('Continue reading »','example')); ?> </div><!-- /#post-<?php get_the_ID(); ?> --> <?php endwhile; ?> <div class="navigation"> <span class="newer"><?php previous_posts_link(__('« Newer','example')) ?></span> <span class="older"><?php next_posts_link(__('Older »','example')) ?></span> </div><!-- /.navigation --> <?php else: ?> <div id="post-404" class="noposts"> <p><?php _e('None found.','example'); ?></p> </div><!-- /#post-404 --> <?php endif; wp_reset_query(); ?> </div><!-- /#content --> <?php get_footer(); ?> ``` *Instead of showing 5 posts, you can set posts\_per\_page=10 or whatever works best.* Note also that the HTML used in this example is rudimentary to keep things simple. You'll probably need to make a few changes to the markup to synchronize with your theme design. **Step 2: Add New Page** Once page-blog.php is complete and uploaded to the server, log in to the WP Admin and visit the Add New Page screen. There, create a new page named "Blog" (or whatever you want), and set its Template as "Blog" from the "Page Attributes" panel. Done! Now visit the Blog page after publishing and you should see the custom WP\_Query loop working: your latest blog posts will be displayed on the page.
306,873
<p>I'm trying to upload files with dwg extension to media but when I do that I get an error telling me that uploading files with this extension is not allowed. I tried to upload them via ftp but I cannot see them in my panel afterwards. I've looked for a solution online and tried adding this to my <code>functions.php</code>:</p> <pre><code>function custom_upload_mimes ( $existing_mimes=array() ) { $existing_mimes[‘dwg’] = ‘application/dwg’; return $existing_mimes; } add_filter(‘upload_mimes’,’custom_upload_mimes’); </code></pre> <p>But it didn't change anything. Is there any other way to bypass this file restriction? </p>
[ { "answer_id": 306874, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>Your code should work just fine. The only problem in there is that you’ve set incorrect mime type, I guess...</p>\n\n<p>It should be <code>image/vnd.dwg</code>.</p>\n\n<p>So this one should work:</p>\n\n<pre><code>function custom_upload_mimes ( $existing_mimes=array() ) {\n $existing_mimes['dwg'] = 'image/vnd.dwg';\n return $existing_mimes;\n}\nadd_filter('upload_mimes', 'custom_upload_mimes');\n</code></pre>\n" }, { "answer_id": 385764, "author": "creaweb80", "author_id": 203995, "author_profile": "https://wordpress.stackexchange.com/users/203995", "pm_score": 0, "selected": false, "text": "<p>If it can help:\nto fix the <code>Due to safety reasons this file type is not allowed</code> error</p>\n<p>you need to add this in the <code>wp-config.php</code> :</p>\n<pre><code>define('ALLOW_UNFILTERED_UPLOADS', true);\n</code></pre>\n<p>The dwg mimes are multiple, you should add all these:</p>\n<pre><code>function custom_upload_mimes ( $existing_mimes=array() ) {\n $existing_mimes['dwg'] = 'image/vnd.dwg';\n $existing_mimes['dwg'] = 'application/acad';\n $existing_mimes['dwg'] = 'application/autocad';\n $existing_mimes['dwg'] = 'application/autocaddwg';\n $existing_mimes['dwg'] = 'application/dwg';\n $existing_mimes['dwg'] = 'drawing/dwg';\n $existing_mimes['dwg'] = 'image/dwg';\n\n return $existing_mimes;\n}\nadd_filter('upload_mimes', 'custom_upload_mimes');\n</code></pre>\n" } ]
2018/06/25
[ "https://wordpress.stackexchange.com/questions/306873", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145150/" ]
I'm trying to upload files with dwg extension to media but when I do that I get an error telling me that uploading files with this extension is not allowed. I tried to upload them via ftp but I cannot see them in my panel afterwards. I've looked for a solution online and tried adding this to my `functions.php`: ``` function custom_upload_mimes ( $existing_mimes=array() ) { $existing_mimes[‘dwg’] = ‘application/dwg’; return $existing_mimes; } add_filter(‘upload_mimes’,’custom_upload_mimes’); ``` But it didn't change anything. Is there any other way to bypass this file restriction?
Your code should work just fine. The only problem in there is that you’ve set incorrect mime type, I guess... It should be `image/vnd.dwg`. So this one should work: ``` function custom_upload_mimes ( $existing_mimes=array() ) { $existing_mimes['dwg'] = 'image/vnd.dwg'; return $existing_mimes; } add_filter('upload_mimes', 'custom_upload_mimes'); ```
306,887
<p>I am trying to create custom post &amp; post tags with following code</p> <pre><code>function cptportfolioPost_init() { register_post_type( 'portfolio', array( 'labels' =&gt; array( 'name' =&gt; __( 'Portfolio' ), 'singular_name' =&gt; __( 'Portfolio' ) ), 'public' =&gt; true, 'has_archive' =&gt; true, 'menu_icon' =&gt; 'dashicons-calendar-alt', 'taxonomies' =&gt; array('post_tag'), 'supports' =&gt; array( 'title', 'editor', 'excerpt', 'revisions', 'thumbnail', 'author', 'page-attributes', ) ) ); } add_action( 'init', 'cptportfolioPost_init' ); </code></pre> <p>get tags on the post page with this code </p> <pre><code>&lt;?php $tags = get_tags(); $html = '&lt;div class="post-tags-wrap"&gt;'; foreach ( $tags as $tag ) { $tag_link = get_tag_link( $tag-&gt;term_id ); $html .= "&lt;a href='{$tag_link}' title='{$tag-&gt;name} Tag' class='{$tag-&gt;slug}'&gt;"; $html .= "{$tag-&gt;name}&lt;/a&gt;"; } $html .= '&lt;/div&gt;'; echo $html;?&gt; </code></pre> <p>in dashboard my custom post has a tags option, in frontend on post page selected tags also displayed but when I click tags link, tags page doesn't display custom post related to that tag only display WordPress default post related to that tag So how can I get my custom post on the tags page </p>
[ { "answer_id": 306874, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>Your code should work just fine. The only problem in there is that you’ve set incorrect mime type, I guess...</p>\n\n<p>It should be <code>image/vnd.dwg</code>.</p>\n\n<p>So this one should work:</p>\n\n<pre><code>function custom_upload_mimes ( $existing_mimes=array() ) {\n $existing_mimes['dwg'] = 'image/vnd.dwg';\n return $existing_mimes;\n}\nadd_filter('upload_mimes', 'custom_upload_mimes');\n</code></pre>\n" }, { "answer_id": 385764, "author": "creaweb80", "author_id": 203995, "author_profile": "https://wordpress.stackexchange.com/users/203995", "pm_score": 0, "selected": false, "text": "<p>If it can help:\nto fix the <code>Due to safety reasons this file type is not allowed</code> error</p>\n<p>you need to add this in the <code>wp-config.php</code> :</p>\n<pre><code>define('ALLOW_UNFILTERED_UPLOADS', true);\n</code></pre>\n<p>The dwg mimes are multiple, you should add all these:</p>\n<pre><code>function custom_upload_mimes ( $existing_mimes=array() ) {\n $existing_mimes['dwg'] = 'image/vnd.dwg';\n $existing_mimes['dwg'] = 'application/acad';\n $existing_mimes['dwg'] = 'application/autocad';\n $existing_mimes['dwg'] = 'application/autocaddwg';\n $existing_mimes['dwg'] = 'application/dwg';\n $existing_mimes['dwg'] = 'drawing/dwg';\n $existing_mimes['dwg'] = 'image/dwg';\n\n return $existing_mimes;\n}\nadd_filter('upload_mimes', 'custom_upload_mimes');\n</code></pre>\n" } ]
2018/06/25
[ "https://wordpress.stackexchange.com/questions/306887", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102143/" ]
I am trying to create custom post & post tags with following code ``` function cptportfolioPost_init() { register_post_type( 'portfolio', array( 'labels' => array( 'name' => __( 'Portfolio' ), 'singular_name' => __( 'Portfolio' ) ), 'public' => true, 'has_archive' => true, 'menu_icon' => 'dashicons-calendar-alt', 'taxonomies' => array('post_tag'), 'supports' => array( 'title', 'editor', 'excerpt', 'revisions', 'thumbnail', 'author', 'page-attributes', ) ) ); } add_action( 'init', 'cptportfolioPost_init' ); ``` get tags on the post page with this code ``` <?php $tags = get_tags(); $html = '<div class="post-tags-wrap">'; foreach ( $tags as $tag ) { $tag_link = get_tag_link( $tag->term_id ); $html .= "<a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}'>"; $html .= "{$tag->name}</a>"; } $html .= '</div>'; echo $html;?> ``` in dashboard my custom post has a tags option, in frontend on post page selected tags also displayed but when I click tags link, tags page doesn't display custom post related to that tag only display WordPress default post related to that tag So how can I get my custom post on the tags page
Your code should work just fine. The only problem in there is that you’ve set incorrect mime type, I guess... It should be `image/vnd.dwg`. So this one should work: ``` function custom_upload_mimes ( $existing_mimes=array() ) { $existing_mimes['dwg'] = 'image/vnd.dwg'; return $existing_mimes; } add_filter('upload_mimes', 'custom_upload_mimes'); ```
306,904
<p>I occasionally want to reset my WordPress installation back to default--both the database and files. What is the most efficient way to do so? </p> <p>I know there are viable plugins to reset the database. But are there automated methods to reset the files to default as well? Or do I need to simply delete everything and re-upload all the WordPress files?</p>
[ { "answer_id": 306922, "author": "Benjamin Atkin", "author_id": 8567, "author_profile": "https://wordpress.stackexchange.com/users/8567", "pm_score": 0, "selected": false, "text": "<p>You can use git and a script:</p>\n\n<pre><code>#!/bin/bash\n# check out a revision\ngit checkout master\n\n# Force-add the wordpress config to the index so it\n# isn't removed in the next step (add any other\n# .gitignore'd files you want to keep to the end of\n# this)\ngit add -f config/wp-config.php \n\n# remove any files/directories not in the index\ngit clean -fdx\n\n# removes files added to index in step 2 from the\n# index (but doesn't remove them from the disk)\ngit reset\n</code></pre>\n" }, { "answer_id": 306927, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<p>If you only want to <em>empty</em> the site of its <em>content</em> (<em>posts</em>, <em>comments</em>, <em>terms</em>, and <em>meta</em>) then there's a <a href=\"https://developer.wordpress.org/cli/commands/site/empty/\" rel=\"nofollow noreferrer\">wp-cli</a> command for that:</p>\n\n<pre><code>$ wp site empty\n</code></pre>\n\n<p>Use the the <code>--uploads</code> parameter to delete all files in the uploads folder and <code>--yes</code> to skip the conformation.</p>\n\n<p><strong>Warning: Remember to backup before testing!</strong></p>\n\n<p>See <a href=\"https://developer.wordpress.org/cli/commands/site/empty/\" rel=\"nofollow noreferrer\">the wp-cli docs</a> for more information:</p>\n" } ]
2018/06/25
[ "https://wordpress.stackexchange.com/questions/306904", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51204/" ]
I occasionally want to reset my WordPress installation back to default--both the database and files. What is the most efficient way to do so? I know there are viable plugins to reset the database. But are there automated methods to reset the files to default as well? Or do I need to simply delete everything and re-upload all the WordPress files?
If you only want to *empty* the site of its *content* (*posts*, *comments*, *terms*, and *meta*) then there's a [wp-cli](https://developer.wordpress.org/cli/commands/site/empty/) command for that: ``` $ wp site empty ``` Use the the `--uploads` parameter to delete all files in the uploads folder and `--yes` to skip the conformation. **Warning: Remember to backup before testing!** See [the wp-cli docs](https://developer.wordpress.org/cli/commands/site/empty/) for more information:
306,990
<p>I just want to setup SMTP for a specific instance of <code>wp_mail()</code>. </p> <p>I have tested plugins like "Easy WP SMTP" and also checked how to set up SMTP manually but all <strong>these apply to the entire site</strong> and then every email from the site is sent through the SMTP account.</p> <p>I don't want to send any other emails like newsletters or comment approval emails through the same SMTP account.</p>
[ { "answer_id": 318826, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": false, "text": "<p>The following is a way to handle your question. It is in two parts. First, you would create your connection as constants to be used later. The best way to do this is in wp-config.php. (You mentioned that you're doing this in a custom plugin. If that's something that is to be portable, then you may want to change this to saving setting in the db instead.) Second, you'll apply a function hooked to the phpmailer that WP uses. In that function you can define your criteria in which you'd use the SMTP connection instead of the default.</p>\n\n<p>You can set up your SMTP credentials and server connection info in wp-config.php as constants as follows:</p>\n\n<pre><code>/*\n * Set the following constants in wp-config.php\n * These should be added somewhere BEFORE the\n * constant ABSPATH is defined.\n */\ndefine( 'SMTP_USER', '[email protected]' ); // Username to use for SMTP authentication\ndefine( 'SMTP_PASS', 'smtp password' ); // Password to use for SMTP authentication\ndefine( 'SMTP_HOST', 'smtp.example.com' ); // The hostname of the mail server\ndefine( 'SMTP_FROM', '[email protected]' ); // SMTP From email address\ndefine( 'SMTP_NAME', 'e.g Website Name' ); // SMTP From name\ndefine( 'SMTP_PORT', '25' ); // SMTP port number - likely to be 25, 465 or 587\ndefine( 'SMTP_SECURE', 'tls' ); // Encryption system to use - ssl or tls\ndefine( 'SMTP_AUTH', true ); // Use SMTP authentication (true|false)\ndefine( 'SMTP_DEBUG', 0 ); // for debugging purposes only set to 1 or 2\n</code></pre>\n\n<p>Once you've added that to your wp-config.php file, you have constants that you can use to connect and send any email via SMTP. You can do this by hooking to the phpmailer_init action and using that to set up connection criteria using the constants you defined above.</p>\n\n<p>In your specific case, you would want to add some conditional logic in the function to identify the condition in which you want to send via SMTP. Set up your conditional so that only your criteria uses the SMTP connection for the phpmailer, and all others would use whatever is already being used.</p>\n\n<p>Since we don't know what that is from your OP, I've represented it here with a generic <code>true === $some_criteria</code>:</p>\n\n<pre><code>add_action( 'phpmailer_init', 'send_smtp_email' );\nfunction send_smtp_email( $phpmailer ) {\n\n if ( true === $some_criteria ) {\n if ( ! is_object( $phpmailer ) ) {\n $phpmailer = (object) $phpmailer;\n }\n\n $phpmailer-&gt;Mailer = 'smtp';\n $phpmailer-&gt;Host = SMTP_HOST;\n $phpmailer-&gt;SMTPAuth = SMTP_AUTH;\n $phpmailer-&gt;Port = SMTP_PORT;\n $phpmailer-&gt;Username = SMTP_USER;\n $phpmailer-&gt;Password = SMTP_PASS;\n $phpmailer-&gt;SMTPSecure = SMTP_SECURE;\n $phpmailer-&gt;From = SMTP_FROM;\n $phpmailer-&gt;FromName = SMTP_NAME;\n }\n\n // any other case would not change the sending server\n}\n</code></pre>\n\n<p>This concept is from the following gist on github:\n<a href=\"https://gist.github.com/butlerblog/c5c5eae5ace5bdaefb5d\" rel=\"nofollow noreferrer\">https://gist.github.com/butlerblog/c5c5eae5ace5bdaefb5d</a></p>\n\n<p>General instructions on it here:\n<a href=\"http://b.utler.co/Y3\" rel=\"nofollow noreferrer\">http://b.utler.co/Y3</a></p>\n" }, { "answer_id": 406973, "author": "Dev Ze", "author_id": 223337, "author_profile": "https://wordpress.stackexchange.com/users/223337", "pm_score": 0, "selected": false, "text": "<p>As I cant yet comment but would like to thank @butlerblog for pointing me in the right direction and because I am really frustrated that that this is not implemented in none of the bigger SMTP plugins, like WP Mail SMTP or Post SMTP Mailer or whatever, I created an account here to post my version of the solution.</p>\n<p>My use case seems so standard that I am really baffled that this is not build in into wordpress or that there is no plugin for it out there.</p>\n<p>My problem is that I have the normal admin email for system notifications, like new comments, or new user registration or things like that but I wanted a different email to contact the users, in my case after ordering something (via woocommerce). (Order confirmation, invoice, shipping confirmed, ...)</p>\n<p>The problem is, that my email server does not allow sending emails in the name of other users. So I needed a way to store two different user names and passwords for the smtp configuration.\nBut all the aforementioned plugins permit only ONE single email to be configured via SMTP (at least when using a custom SMTP server, I did not test anything like sendrid or mailgun). I am using Namecheap Privateemail...</p>\n<p>So I am now using the WP Mail SMTP plugin and I configured it for the admin email, lets say [email protected]. After testing that the config works, via the plugins testing functionality I added the following code to functions.php and configured woocommerce to send emails via [email protected]</p>\n<pre><code>// Use 20 as priority so that this action is called after the wp mail smtp plugin action\nadd_action( 'phpmailer_init', 'send_smtp_email', 20 );\nfunction send_smtp_email( $phpmailer ) {\n if ( $phpmailer-&gt;From === '[email protected]' ) {\n $phpmailer-&gt;Username = '[email protected]';\n $phpmailer-&gt;Password = 'your_password_here';\n }\n // Debugging (send complete $phpmailer object to your email):\n // $phpmailer-&gt;Body = 'phpmailer: '.print_r($phpmailer, true);\n}\n</code></pre>\n<p>The password could also be saved in wp-config.php as mentioned in the other response and that way no other admin would have access. (I assume)</p>\n<p>Note: I am no wordpress dev, so there might be problems with this approach with I am not aware of (yet).</p>\n" } ]
2018/06/26
[ "https://wordpress.stackexchange.com/questions/306990", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101689/" ]
I just want to setup SMTP for a specific instance of `wp_mail()`. I have tested plugins like "Easy WP SMTP" and also checked how to set up SMTP manually but all **these apply to the entire site** and then every email from the site is sent through the SMTP account. I don't want to send any other emails like newsletters or comment approval emails through the same SMTP account.
The following is a way to handle your question. It is in two parts. First, you would create your connection as constants to be used later. The best way to do this is in wp-config.php. (You mentioned that you're doing this in a custom plugin. If that's something that is to be portable, then you may want to change this to saving setting in the db instead.) Second, you'll apply a function hooked to the phpmailer that WP uses. In that function you can define your criteria in which you'd use the SMTP connection instead of the default. You can set up your SMTP credentials and server connection info in wp-config.php as constants as follows: ``` /* * Set the following constants in wp-config.php * These should be added somewhere BEFORE the * constant ABSPATH is defined. */ define( 'SMTP_USER', '[email protected]' ); // Username to use for SMTP authentication define( 'SMTP_PASS', 'smtp password' ); // Password to use for SMTP authentication define( 'SMTP_HOST', 'smtp.example.com' ); // The hostname of the mail server define( 'SMTP_FROM', '[email protected]' ); // SMTP From email address define( 'SMTP_NAME', 'e.g Website Name' ); // SMTP From name define( 'SMTP_PORT', '25' ); // SMTP port number - likely to be 25, 465 or 587 define( 'SMTP_SECURE', 'tls' ); // Encryption system to use - ssl or tls define( 'SMTP_AUTH', true ); // Use SMTP authentication (true|false) define( 'SMTP_DEBUG', 0 ); // for debugging purposes only set to 1 or 2 ``` Once you've added that to your wp-config.php file, you have constants that you can use to connect and send any email via SMTP. You can do this by hooking to the phpmailer\_init action and using that to set up connection criteria using the constants you defined above. In your specific case, you would want to add some conditional logic in the function to identify the condition in which you want to send via SMTP. Set up your conditional so that only your criteria uses the SMTP connection for the phpmailer, and all others would use whatever is already being used. Since we don't know what that is from your OP, I've represented it here with a generic `true === $some_criteria`: ``` add_action( 'phpmailer_init', 'send_smtp_email' ); function send_smtp_email( $phpmailer ) { if ( true === $some_criteria ) { if ( ! is_object( $phpmailer ) ) { $phpmailer = (object) $phpmailer; } $phpmailer->Mailer = 'smtp'; $phpmailer->Host = SMTP_HOST; $phpmailer->SMTPAuth = SMTP_AUTH; $phpmailer->Port = SMTP_PORT; $phpmailer->Username = SMTP_USER; $phpmailer->Password = SMTP_PASS; $phpmailer->SMTPSecure = SMTP_SECURE; $phpmailer->From = SMTP_FROM; $phpmailer->FromName = SMTP_NAME; } // any other case would not change the sending server } ``` This concept is from the following gist on github: <https://gist.github.com/butlerblog/c5c5eae5ace5bdaefb5d> General instructions on it here: <http://b.utler.co/Y3>
307,003
<p>I need to put link with image at the end of post page. What I am looking for is that at the end of each new post, I need to have small image with link that opens in a new window. How to do that? Thanks.</p>
[ { "answer_id": 318826, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 2, "selected": false, "text": "<p>The following is a way to handle your question. It is in two parts. First, you would create your connection as constants to be used later. The best way to do this is in wp-config.php. (You mentioned that you're doing this in a custom plugin. If that's something that is to be portable, then you may want to change this to saving setting in the db instead.) Second, you'll apply a function hooked to the phpmailer that WP uses. In that function you can define your criteria in which you'd use the SMTP connection instead of the default.</p>\n\n<p>You can set up your SMTP credentials and server connection info in wp-config.php as constants as follows:</p>\n\n<pre><code>/*\n * Set the following constants in wp-config.php\n * These should be added somewhere BEFORE the\n * constant ABSPATH is defined.\n */\ndefine( 'SMTP_USER', '[email protected]' ); // Username to use for SMTP authentication\ndefine( 'SMTP_PASS', 'smtp password' ); // Password to use for SMTP authentication\ndefine( 'SMTP_HOST', 'smtp.example.com' ); // The hostname of the mail server\ndefine( 'SMTP_FROM', '[email protected]' ); // SMTP From email address\ndefine( 'SMTP_NAME', 'e.g Website Name' ); // SMTP From name\ndefine( 'SMTP_PORT', '25' ); // SMTP port number - likely to be 25, 465 or 587\ndefine( 'SMTP_SECURE', 'tls' ); // Encryption system to use - ssl or tls\ndefine( 'SMTP_AUTH', true ); // Use SMTP authentication (true|false)\ndefine( 'SMTP_DEBUG', 0 ); // for debugging purposes only set to 1 or 2\n</code></pre>\n\n<p>Once you've added that to your wp-config.php file, you have constants that you can use to connect and send any email via SMTP. You can do this by hooking to the phpmailer_init action and using that to set up connection criteria using the constants you defined above.</p>\n\n<p>In your specific case, you would want to add some conditional logic in the function to identify the condition in which you want to send via SMTP. Set up your conditional so that only your criteria uses the SMTP connection for the phpmailer, and all others would use whatever is already being used.</p>\n\n<p>Since we don't know what that is from your OP, I've represented it here with a generic <code>true === $some_criteria</code>:</p>\n\n<pre><code>add_action( 'phpmailer_init', 'send_smtp_email' );\nfunction send_smtp_email( $phpmailer ) {\n\n if ( true === $some_criteria ) {\n if ( ! is_object( $phpmailer ) ) {\n $phpmailer = (object) $phpmailer;\n }\n\n $phpmailer-&gt;Mailer = 'smtp';\n $phpmailer-&gt;Host = SMTP_HOST;\n $phpmailer-&gt;SMTPAuth = SMTP_AUTH;\n $phpmailer-&gt;Port = SMTP_PORT;\n $phpmailer-&gt;Username = SMTP_USER;\n $phpmailer-&gt;Password = SMTP_PASS;\n $phpmailer-&gt;SMTPSecure = SMTP_SECURE;\n $phpmailer-&gt;From = SMTP_FROM;\n $phpmailer-&gt;FromName = SMTP_NAME;\n }\n\n // any other case would not change the sending server\n}\n</code></pre>\n\n<p>This concept is from the following gist on github:\n<a href=\"https://gist.github.com/butlerblog/c5c5eae5ace5bdaefb5d\" rel=\"nofollow noreferrer\">https://gist.github.com/butlerblog/c5c5eae5ace5bdaefb5d</a></p>\n\n<p>General instructions on it here:\n<a href=\"http://b.utler.co/Y3\" rel=\"nofollow noreferrer\">http://b.utler.co/Y3</a></p>\n" }, { "answer_id": 406973, "author": "Dev Ze", "author_id": 223337, "author_profile": "https://wordpress.stackexchange.com/users/223337", "pm_score": 0, "selected": false, "text": "<p>As I cant yet comment but would like to thank @butlerblog for pointing me in the right direction and because I am really frustrated that that this is not implemented in none of the bigger SMTP plugins, like WP Mail SMTP or Post SMTP Mailer or whatever, I created an account here to post my version of the solution.</p>\n<p>My use case seems so standard that I am really baffled that this is not build in into wordpress or that there is no plugin for it out there.</p>\n<p>My problem is that I have the normal admin email for system notifications, like new comments, or new user registration or things like that but I wanted a different email to contact the users, in my case after ordering something (via woocommerce). (Order confirmation, invoice, shipping confirmed, ...)</p>\n<p>The problem is, that my email server does not allow sending emails in the name of other users. So I needed a way to store two different user names and passwords for the smtp configuration.\nBut all the aforementioned plugins permit only ONE single email to be configured via SMTP (at least when using a custom SMTP server, I did not test anything like sendrid or mailgun). I am using Namecheap Privateemail...</p>\n<p>So I am now using the WP Mail SMTP plugin and I configured it for the admin email, lets say [email protected]. After testing that the config works, via the plugins testing functionality I added the following code to functions.php and configured woocommerce to send emails via [email protected]</p>\n<pre><code>// Use 20 as priority so that this action is called after the wp mail smtp plugin action\nadd_action( 'phpmailer_init', 'send_smtp_email', 20 );\nfunction send_smtp_email( $phpmailer ) {\n if ( $phpmailer-&gt;From === '[email protected]' ) {\n $phpmailer-&gt;Username = '[email protected]';\n $phpmailer-&gt;Password = 'your_password_here';\n }\n // Debugging (send complete $phpmailer object to your email):\n // $phpmailer-&gt;Body = 'phpmailer: '.print_r($phpmailer, true);\n}\n</code></pre>\n<p>The password could also be saved in wp-config.php as mentioned in the other response and that way no other admin would have access. (I assume)</p>\n<p>Note: I am no wordpress dev, so there might be problems with this approach with I am not aware of (yet).</p>\n" } ]
2018/06/26
[ "https://wordpress.stackexchange.com/questions/307003", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145893/" ]
I need to put link with image at the end of post page. What I am looking for is that at the end of each new post, I need to have small image with link that opens in a new window. How to do that? Thanks.
The following is a way to handle your question. It is in two parts. First, you would create your connection as constants to be used later. The best way to do this is in wp-config.php. (You mentioned that you're doing this in a custom plugin. If that's something that is to be portable, then you may want to change this to saving setting in the db instead.) Second, you'll apply a function hooked to the phpmailer that WP uses. In that function you can define your criteria in which you'd use the SMTP connection instead of the default. You can set up your SMTP credentials and server connection info in wp-config.php as constants as follows: ``` /* * Set the following constants in wp-config.php * These should be added somewhere BEFORE the * constant ABSPATH is defined. */ define( 'SMTP_USER', '[email protected]' ); // Username to use for SMTP authentication define( 'SMTP_PASS', 'smtp password' ); // Password to use for SMTP authentication define( 'SMTP_HOST', 'smtp.example.com' ); // The hostname of the mail server define( 'SMTP_FROM', '[email protected]' ); // SMTP From email address define( 'SMTP_NAME', 'e.g Website Name' ); // SMTP From name define( 'SMTP_PORT', '25' ); // SMTP port number - likely to be 25, 465 or 587 define( 'SMTP_SECURE', 'tls' ); // Encryption system to use - ssl or tls define( 'SMTP_AUTH', true ); // Use SMTP authentication (true|false) define( 'SMTP_DEBUG', 0 ); // for debugging purposes only set to 1 or 2 ``` Once you've added that to your wp-config.php file, you have constants that you can use to connect and send any email via SMTP. You can do this by hooking to the phpmailer\_init action and using that to set up connection criteria using the constants you defined above. In your specific case, you would want to add some conditional logic in the function to identify the condition in which you want to send via SMTP. Set up your conditional so that only your criteria uses the SMTP connection for the phpmailer, and all others would use whatever is already being used. Since we don't know what that is from your OP, I've represented it here with a generic `true === $some_criteria`: ``` add_action( 'phpmailer_init', 'send_smtp_email' ); function send_smtp_email( $phpmailer ) { if ( true === $some_criteria ) { if ( ! is_object( $phpmailer ) ) { $phpmailer = (object) $phpmailer; } $phpmailer->Mailer = 'smtp'; $phpmailer->Host = SMTP_HOST; $phpmailer->SMTPAuth = SMTP_AUTH; $phpmailer->Port = SMTP_PORT; $phpmailer->Username = SMTP_USER; $phpmailer->Password = SMTP_PASS; $phpmailer->SMTPSecure = SMTP_SECURE; $phpmailer->From = SMTP_FROM; $phpmailer->FromName = SMTP_NAME; } // any other case would not change the sending server } ``` This concept is from the following gist on github: <https://gist.github.com/butlerblog/c5c5eae5ace5bdaefb5d> General instructions on it here: <http://b.utler.co/Y3>
307,018
<p>I am a newbe in wordpress theme development. Can anyone tell me where I should implement the code for any ajax functionalities(say a voting system for posts)? should I write it on a separate plugin or as a custom code in functions.php please do explain your reason, thanks.</p>
[ { "answer_id": 307022, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Use REST API endpoint instead!</p>\n\n<p>Lets register an endpoint at <code>/wp-json/tomjn/v1/test</code>, that calls <code>tomjn_rest_test()</code> when you hit it:</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'tomjn/v1', '/test/', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'tomjn_rest_test'\n ) );\n} );\n</code></pre>\n\n<p>Now lets add the <code>tomjn_rest_test</code> function:</p>\n\n<pre><code>function tomjn_rest_test( $request ) {\n return \"moomins\";\n}\n</code></pre>\n\n<p>Now when we visit tomjn.com/wp-json/tomjn/v1/test we get:</p>\n\n<p><a href=\"https://i.stack.imgur.com/fpAf1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fpAf1.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now we can grab it on the frontend:</p>\n\n<pre><code>&lt;script&gt;\njQuery.ajax({\n url: &lt;?php echo wp_json_encode( esc_url_raw( rest_url( 'tomjn/v1/test' ) ) ); ?&gt;\n}).done(function( data ) {\n // do something\n jQuery( '#tomsword' ).text( data );\n});\n&lt;/script&gt;\n</code></pre>\n\n<p>That code looks for a <code>&lt;div id=\"tomsword\"&gt;</code> and sets the contents to whatever the endpoint returned.</p>\n\n<h3>But Where Do I Put The Code? Theme or Plugin?</h3>\n\n<p>You can register you endpoints in a plugin or theme, just remember:</p>\n\n<ul>\n<li>themes determine how your site looks</li>\n<li>plugins determine what you site can do</li>\n</ul>\n\n<p><strong>Voting sounds like functionality, not decoration, and should go in a plugin.</strong></p>\n\n<p>If you put it in a theme, then that functionality is forever trapped in that theme unless a developer manually extracts it. Any voting data is unavailable as soon as the user changes the theme</p>\n" }, { "answer_id": 307385, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Too low to comment — please see this helpful guide on <a href=\"https://wpza.net/wordpress-setup/how-to-update-wordpress-posts-with-ajax-on-the-front-end/\" rel=\"nofollow noreferrer\">updating posts with ajax</a>. You can use this to <code>update_post_meta()</code> to +1 per click and then update the frontend number by +1 for visual effect. Upon refresh, it'll be the new +1'd value.</p>\n" } ]
2018/06/26
[ "https://wordpress.stackexchange.com/questions/307018", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145902/" ]
I am a newbe in wordpress theme development. Can anyone tell me where I should implement the code for any ajax functionalities(say a voting system for posts)? should I write it on a separate plugin or as a custom code in functions.php please do explain your reason, thanks.
Use REST API endpoint instead! Lets register an endpoint at `/wp-json/tomjn/v1/test`, that calls `tomjn_rest_test()` when you hit it: ``` add_action( 'rest_api_init', function () { register_rest_route( 'tomjn/v1', '/test/', array( 'methods' => 'GET', 'callback' => 'tomjn_rest_test' ) ); } ); ``` Now lets add the `tomjn_rest_test` function: ``` function tomjn_rest_test( $request ) { return "moomins"; } ``` Now when we visit tomjn.com/wp-json/tomjn/v1/test we get: [![enter image description here](https://i.stack.imgur.com/fpAf1.png)](https://i.stack.imgur.com/fpAf1.png) Now we can grab it on the frontend: ``` <script> jQuery.ajax({ url: <?php echo wp_json_encode( esc_url_raw( rest_url( 'tomjn/v1/test' ) ) ); ?> }).done(function( data ) { // do something jQuery( '#tomsword' ).text( data ); }); </script> ``` That code looks for a `<div id="tomsword">` and sets the contents to whatever the endpoint returned. ### But Where Do I Put The Code? Theme or Plugin? You can register you endpoints in a plugin or theme, just remember: * themes determine how your site looks * plugins determine what you site can do **Voting sounds like functionality, not decoration, and should go in a plugin.** If you put it in a theme, then that functionality is forever trapped in that theme unless a developer manually extracts it. Any voting data is unavailable as soon as the user changes the theme
307,040
<p>Is it possible / how can I get all posts from all sites on a multisite installation using the REST API? On the front page of the primary site, I want to display recent posts from <em>all</em> the sites; e.g., mysite.com shows recent posts from mysite.com/site1, myite.com/site2, etc., merged together (possibly with some filtering). I know how to do this with PHP; I want to see if I can do it using the REST API.</p> <p>Josh Pollock @ torquemag has proposed this solution: <a href="https://torquemag.io/2016/07/combine-wordpress-sites-rest-api/" rel="nofollow noreferrer">https://torquemag.io/2016/07/combine-wordpress-sites-rest-api/</a></p> <p>Josh's example envisions combining posts from 2 completely different sites, and so I'm wondering if there is another way to do this within a single multisite install. I haven't done much with custom endpoints til now and wondering if a custom endpoint could accomplish this as well.</p> <p>Also curious about any potential performance issues involved.</p>
[ { "answer_id": 307045, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>Yes, there is a way to do that. It's a bit complex for here; you have to loop through all sites (after you get a list of sites), do a wp_query for each one, then output results for each wp_query. </p>\n\n<p>Take a look at my \"Multisite Post Display\" plugin <a href=\"https://wordpress.org/plugins/multisite-post-reader/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/multisite-post-reader/</a> . Open source, of course, so you can dig into the code to get hints of how I did it, and adjust for your needs.</p>\n\n<p>Haven't tested performance on a site. Hope it helps.</p>\n" }, { "answer_id": 307051, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Here's a REST API recipe for <strong>latest post per site on a multi-site</strong>, for relatively few sites:</p>\n\n<ul>\n<li>Use <code>get_sites()</code>,</li>\n<li>loop over sites and switch to each site,</li>\n<li>query latest post on each site,</li>\n<li>collect data, </li>\n<li>order data by <em>utime</em>,</li>\n<li>serve data</li>\n</ul>\n\n<p><strong>Example REST Routes</strong></p>\n\n<pre><code>https://example.com/wp-json/wpse/v1/latest-post-per-site\nhttps://example.com/wp-json/wpse/v1/latest-post-per-site?number=10\nhttps://example.com/wp-json/wpse/v1/latest-post-per-site?debug\n</code></pre>\n\n<p><strong>Example Plugin</strong></p>\n\n<p>Here's a demo plugin implementing the above recipe (needs testing):</p>\n\n<pre><code>&lt;?php\n/**\n * Plugin Name: WPSE-307040: Rest API - Latest Post Per Site\n * Description: Rest API - latest post per site (multisite).\n * Plugin URI: https://wordpress.stackexchange.com/a/307051/26350\n * Author: birgire\n * Version: 1.0.0\n */\n\nnamespace WPSE\\RestAPI\\LatestPostPerSite;\n\n/**\n * Register Rest Route\n */\n\nadd_action( 'rest_api_init', function() {\n register_rest_route(\n 'wpse/v1',\n '/latest-post-per-site/',\n [\n 'methods' =&gt; 'GET',\n 'callback' =&gt; __NAMESPACE__.'\\rest_results'\n ]\n );\n} );\n\n\n/**\n * Rest Results\n */\nfunction rest_results( $request ) {\n $parameters = $request-&gt;get_query_params();\n\n // Default 10 items\n $number = isset( $parameters['number'] ) ? (int) $parameters['number'] : 10;\n\n // Max 30 items\n if( $number &gt; 30 ) {\n $number = 30;\n }\n\n $items = [];\n $i = 0;\n\n $blogs = get_sites( [\n 'orderby' =&gt; 'last_updated',\n 'order' =&gt; 'DESC',\n 'number' =&gt; (int) $number \n ] );\n\n foreach ( $blogs as $blog ) {\n switch_to_blog( $blog-&gt;blog_id );\n\n // Site info\n $details = get_blog_details( $blog-&gt;blog_id );\n\n $items[$i]['sitename'] = esc_html( $details-&gt;blogname );\n $items[$i]['siteid'] = (int) $blog-&gt;blog_id;\n $items[$i]['homeurl'] = esc_url( $details-&gt;home );\n\n // Latest post\n $args = [\n 'orderby' =&gt; 'post_date',\n 'order' =&gt; 'DESC',\n 'posts_per_page' =&gt; 1,\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'ignore_sticky_posts' =&gt; true,\n 'no_found_rows' =&gt; true,\n 'update_post_term_cache' =&gt; false,\n 'update_post_meta_cache' =&gt; false,\n ];\n\n $query = new \\WP_Query( $args );\n\n if( $query-&gt;have_posts() ) {\n while( $query-&gt;have_posts() ) {\n $query-&gt;the_post();\n // Title\n $items[$i]['title'] = esc_html( get_the_title( get_the_ID() ) );\n // Date\n $items[$i]['date'] = esc_html( get_the_date( 'Y-m-d H:i:s', get_the_ID() ) );\n // Unix time\n $items[$i]['utime'] = esc_html( get_the_date( 'U', get_the_ID() ) );\n // Excerpt\n $items[$i]['excerpt'] = esc_html( wp_trim_words( strip_shortcodes( get_the_content() ), 50 ) );\n // Permalink\n $items[$i]['url'] = esc_url( get_permalink( get_the_ID() ) );\n }\n wp_reset_postdata();\n }\n\n $i++;\n restore_current_blog();\n\n // Sort by utime.\n $items = wp_list_sort( $items, 'utime', 'DESC' );\n\n $data = [\n 'success' =&gt; true,\n 'count' =&gt; count( $items ),\n 'items' =&gt; $items,\n ];\n\n // Debug for super admins.\n if( isset( $parameters['debug'] ) &amp;&amp; current_user_can( 'manage_networks' ) ) {\n $data['qrs'] = get_num_queries();\n $data['sec'] = timer_stop(0);\n }\n\n return $data;\n }\n</code></pre>\n\n<p>For larger number of sites, I would instead consider hooking into the <em>create/update/delete</em> for <em>post/meta/taxonomy/term</em> on each site, to sync and collect site wide data to a dedicated data site in the multi-site network.</p>\n\n<p>Hope it helps!</p>\n" } ]
2018/06/26
[ "https://wordpress.stackexchange.com/questions/307040", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124357/" ]
Is it possible / how can I get all posts from all sites on a multisite installation using the REST API? On the front page of the primary site, I want to display recent posts from *all* the sites; e.g., mysite.com shows recent posts from mysite.com/site1, myite.com/site2, etc., merged together (possibly with some filtering). I know how to do this with PHP; I want to see if I can do it using the REST API. Josh Pollock @ torquemag has proposed this solution: <https://torquemag.io/2016/07/combine-wordpress-sites-rest-api/> Josh's example envisions combining posts from 2 completely different sites, and so I'm wondering if there is another way to do this within a single multisite install. I haven't done much with custom endpoints til now and wondering if a custom endpoint could accomplish this as well. Also curious about any potential performance issues involved.
Here's a REST API recipe for **latest post per site on a multi-site**, for relatively few sites: * Use `get_sites()`, * loop over sites and switch to each site, * query latest post on each site, * collect data, * order data by *utime*, * serve data **Example REST Routes** ``` https://example.com/wp-json/wpse/v1/latest-post-per-site https://example.com/wp-json/wpse/v1/latest-post-per-site?number=10 https://example.com/wp-json/wpse/v1/latest-post-per-site?debug ``` **Example Plugin** Here's a demo plugin implementing the above recipe (needs testing): ``` <?php /** * Plugin Name: WPSE-307040: Rest API - Latest Post Per Site * Description: Rest API - latest post per site (multisite). * Plugin URI: https://wordpress.stackexchange.com/a/307051/26350 * Author: birgire * Version: 1.0.0 */ namespace WPSE\RestAPI\LatestPostPerSite; /** * Register Rest Route */ add_action( 'rest_api_init', function() { register_rest_route( 'wpse/v1', '/latest-post-per-site/', [ 'methods' => 'GET', 'callback' => __NAMESPACE__.'\rest_results' ] ); } ); /** * Rest Results */ function rest_results( $request ) { $parameters = $request->get_query_params(); // Default 10 items $number = isset( $parameters['number'] ) ? (int) $parameters['number'] : 10; // Max 30 items if( $number > 30 ) { $number = 30; } $items = []; $i = 0; $blogs = get_sites( [ 'orderby' => 'last_updated', 'order' => 'DESC', 'number' => (int) $number ] ); foreach ( $blogs as $blog ) { switch_to_blog( $blog->blog_id ); // Site info $details = get_blog_details( $blog->blog_id ); $items[$i]['sitename'] = esc_html( $details->blogname ); $items[$i]['siteid'] = (int) $blog->blog_id; $items[$i]['homeurl'] = esc_url( $details->home ); // Latest post $args = [ 'orderby' => 'post_date', 'order' => 'DESC', 'posts_per_page' => 1, 'post_type' => 'post', 'post_status' => 'publish', 'ignore_sticky_posts' => true, 'no_found_rows' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, ]; $query = new \WP_Query( $args ); if( $query->have_posts() ) { while( $query->have_posts() ) { $query->the_post(); // Title $items[$i]['title'] = esc_html( get_the_title( get_the_ID() ) ); // Date $items[$i]['date'] = esc_html( get_the_date( 'Y-m-d H:i:s', get_the_ID() ) ); // Unix time $items[$i]['utime'] = esc_html( get_the_date( 'U', get_the_ID() ) ); // Excerpt $items[$i]['excerpt'] = esc_html( wp_trim_words( strip_shortcodes( get_the_content() ), 50 ) ); // Permalink $items[$i]['url'] = esc_url( get_permalink( get_the_ID() ) ); } wp_reset_postdata(); } $i++; restore_current_blog(); // Sort by utime. $items = wp_list_sort( $items, 'utime', 'DESC' ); $data = [ 'success' => true, 'count' => count( $items ), 'items' => $items, ]; // Debug for super admins. if( isset( $parameters['debug'] ) && current_user_can( 'manage_networks' ) ) { $data['qrs'] = get_num_queries(); $data['sec'] = timer_stop(0); } return $data; } ``` For larger number of sites, I would instead consider hooking into the *create/update/delete* for *post/meta/taxonomy/term* on each site, to sync and collect site wide data to a dedicated data site in the multi-site network. Hope it helps!
307,088
<p>Im trying to get this simple condition tag to work . Im having no luck</p> <pre><code>// If we are logged in, and NOT an admin and NOT on specific page... if ( is_user_logged_in() &amp; !is_admin() ) &amp; !is_page('account') ) { </code></pre>
[ { "answer_id": 307089, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Count the brackets, you've got an extra one:</p>\n\n<pre><code>// ↓ here\nif ( is_user_logged_in() &amp; !is_admin() ) &amp; !is_page('account') ) {\n</code></pre>\n\n<p>Also, you should use double ampersands in conditions like this. So:</p>\n\n<pre><code>if ( is_user_logged_in() &amp;&amp; !is_admin() &amp;&amp; !is_page('account') ) {\n</code></pre>\n" }, { "answer_id": 309209, "author": "StudioHeads", "author_id": 108508, "author_profile": "https://wordpress.stackexchange.com/users/108508", "pm_score": -1, "selected": true, "text": "<pre><code>if(strpos($_SERVER['REQUEST_URI'], '/account/') === FALSE AND strpos($_SERVER['REQUEST_URI'], '/wp-admin/') === FALSE AND ! is_user_logged_in() === FALSE) {\n</code></pre>\n" } ]
2018/06/27
[ "https://wordpress.stackexchange.com/questions/307088", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108508/" ]
Im trying to get this simple condition tag to work . Im having no luck ``` // If we are logged in, and NOT an admin and NOT on specific page... if ( is_user_logged_in() & !is_admin() ) & !is_page('account') ) { ```
``` if(strpos($_SERVER['REQUEST_URI'], '/account/') === FALSE AND strpos($_SERVER['REQUEST_URI'], '/wp-admin/') === FALSE AND ! is_user_logged_in() === FALSE) { ```
307,105
<p>I have the following website: <a href="https://www.bibaboegifts.be" rel="nofollow noreferrer">www.bibaboegifts.be</a>.</p> <ul> <li>When giving in the URL <a href="https://www.bibaboegifts.be" rel="nofollow noreferrer">https://www.bibaboegifts.be</a>, the CSS is loaded. </li> <li>However, when giving in the URL <a href="https://bibaboegifts.be" rel="nofollow noreferrer">https://bibaboegifts.be</a> (<strong>without the www. part</strong>), the CSS is not loaded. Only the content is displayed, but my lay-out is not applied.</li> </ul> <p>Any idea why this is the case &amp; how this can be resolved? </p>
[ { "answer_id": 307089, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Count the brackets, you've got an extra one:</p>\n\n<pre><code>// ↓ here\nif ( is_user_logged_in() &amp; !is_admin() ) &amp; !is_page('account') ) {\n</code></pre>\n\n<p>Also, you should use double ampersands in conditions like this. So:</p>\n\n<pre><code>if ( is_user_logged_in() &amp;&amp; !is_admin() &amp;&amp; !is_page('account') ) {\n</code></pre>\n" }, { "answer_id": 309209, "author": "StudioHeads", "author_id": 108508, "author_profile": "https://wordpress.stackexchange.com/users/108508", "pm_score": -1, "selected": true, "text": "<pre><code>if(strpos($_SERVER['REQUEST_URI'], '/account/') === FALSE AND strpos($_SERVER['REQUEST_URI'], '/wp-admin/') === FALSE AND ! is_user_logged_in() === FALSE) {\n</code></pre>\n" } ]
2018/06/27
[ "https://wordpress.stackexchange.com/questions/307105", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129008/" ]
I have the following website: [www.bibaboegifts.be](https://www.bibaboegifts.be). * When giving in the URL <https://www.bibaboegifts.be>, the CSS is loaded. * However, when giving in the URL <https://bibaboegifts.be> (**without the www. part**), the CSS is not loaded. Only the content is displayed, but my lay-out is not applied. Any idea why this is the case & how this can be resolved?
``` if(strpos($_SERVER['REQUEST_URI'], '/account/') === FALSE AND strpos($_SERVER['REQUEST_URI'], '/wp-admin/') === FALSE AND ! is_user_logged_in() === FALSE) { ```
307,109
<p>I have a custom page template defined and working properly. On this specific page, I want to list a lot of links, and paginate them, to display 100 links per page.</p> <p>Here is the code in my template file, working exactly like I want</p> <pre><code>&lt;div class="container"&gt; &lt;ul class="row listing-items"&gt; &lt;?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $custom_args = array( 'post_type' =&gt; 'page', 'posts_per_page' =&gt; 90, 'paged' =&gt; $paged, 'order' =&gt; 'ASC', 'orderby' =&gt; 'title', 'post__not_in' =&gt; array('6','6371','9522','5038','6380','9521','6385','9276','4159','4087','4085','4082'), 'post_parent__in' =&gt; array('13', '154', '127', '162', '123', '167', '159', '121','18675','18676','18677','18678','18679','18680','18681','18682','18683','18684','18685','18687','18688','18689','18690','18691','18692','18693','18695','18696','18697','18699','18700','18701','18702','18703','18704','18694','18709','18705','18710','18706','18707','18718','18719','18720','18721','18722','18723','18724','18725','18726','18711','18727','18728','18729','18730','18731','18732','18716','18733','18734','18712','18735','18736','18737','18738','18739','18740','18741','18742','18743','18744','18745','18746','18717','18747','18686','18708','18748','18713','18749','18750','18751','18714','18752','18698','18753','18754','18755','18757','18758','18759','18760','18715','18761','18762','18756'), ); $wp_query = new WP_Query( $custom_args ); if ( $wp_query-&gt;have_posts() ) { while ( $wp_query-&gt;have_posts() ) : $wp_query-&gt;the_post(); echo '&lt;li class="listing-item col-12 col-sm-12 col-md-12 col-lg-6 col-xl-6"&gt;'; echo '&lt;a href="'.get_the_permalink().'"&gt;Voiture '.get_the_title().'&lt;/a&gt;&lt;/li&gt;'; endwhile; wp_reset_postdata(); } ?&gt; &lt;/ul&gt; </code></pre> <p></p> <p>Now, for SEO purposes, I want to add in my header rel Next and Prev, so Google understand the pagination and can understand which page is the current one, and which page is next and prev. </p> <p>Here is my code in functions.php</p> <pre><code>function rel_next_prev() { global $paged; if ( get_previous_posts_link() ) { echo '&lt;link rel="prev" href="'.get_pagenum_link( $paged - 1 ).'" /&gt;'; } if ( get_next_posts_link() ) { echo '&lt;link rel="next" href="'.get_pagenum_link( $paged + 1 ).'" /&gt;'; } } add_action( 'wp_head', 'rel_next_prev' ); </code></pre> <p>Unfortunately, this is partially working. I always get the Rel Prev link in the header, but is not currently based on the query I did. Let me explain:</p> <p>When my query is set, I have 19 pages, under this format:</p> <pre><code>http://localhost:3000/villes/page/2/ </code></pre> <p>So If I change the URL to be (404)</p> <pre><code> http://localhost:3000/villes/page/222/ </code></pre> <p>I still get rel Prev with 221 in the header.</p> <p><em>So to resume:</em></p> <p><strong>How do I properly set rel next/prev in the header based on the current query I'm doing?</strong></p> <p>Thanks!</p>
[ { "answer_id": 307182, "author": "yofisim", "author_id": 98907, "author_profile": "https://wordpress.stackexchange.com/users/98907", "pm_score": 3, "selected": true, "text": "<p>After a huge night overthinking this, and thanks to Joost de Valk (Yoast SEO plugin author), I found the solution.</p>\n\n<p>As per this thread: <a href=\"https://github.com/Yoast/wordpress-seo/issues/437\" rel=\"nofollow noreferrer\">https://github.com/Yoast/wordpress-seo/issues/437</a> , what I want to achieve the way I do, <strong>is undoable, or at least, a very bad practice.</strong> </p>\n\n<p>If you want your custom query to have the default pagination and rel next prev in the header, you need to call it before <code>get_header();</code></p>\n\n<h1>THEORIC SOLUTION</h1>\n\n<p>To make your custom query work with default WP and Yoast functions, you need to:</p>\n\n<ol>\n<li>Put your query <strong>BEFORE</strong> <code>get_header();</code></li>\n<li>Be sure your query has the default name provided by WP, which is <code>$wp_query</code></li>\n<li>That being said, you will need to create a specific page template for your query, so you can set your query before getting the header.</li>\n</ol>\n\n<h1>PRACTIC SOLUTION</h1>\n\n<p>For the previous code I had, which was working with <code>get_template_part();</code>.</p>\n\n<ol>\n<li><p>Create a custom page-template, refering to the page ID or the page slug. More on this here: <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/template-files-section/page-template-files/</a></p></li>\n<li><p>Set your custom query before the <code>get_header();</code> function.</p></li>\n<li>Be sure to re-adapt your code, so it displays the way you want.</li>\n</ol>\n\n<p>Here is my code, which is working as expected. <strong>Be sure to keep the</strong> <code>rel_next_prev();</code> <strong>function I placed in my functions.php</strong></p>\n\n<p>Final Result:</p>\n\n<pre><code>&lt;?php\n$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;\n$custom_args = array(\n 'post_type' =&gt; 'page',\n 'posts_per_page' =&gt; 90,\n 'paged' =&gt; $paged,\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'title',\n 'post__not_in' =&gt; array('6','6371','9522','5038','6380','9521','6385','9276','4159','4087','4085','4082'),\n 'post_parent__in' =&gt; array('13', '154', '127', '162', '123', '167', '159', '121','18675','18676','18677','18678','18679','18680','18681','18682','18683','18684','18685','18687','18688','18689','18690','18691','18692','18693','18695','18696','18697','18699','18700','18701','18702','18703','18704','18694','18709','18705','18710','18706','18707','18718','18719','18720','18721','18722','18723','18724','18725','18726','18711','18727','18728','18729','18730','18731','18732','18716','18733','18734','18712','18735','18736','18737','18738','18739','18740','18741','18742','18743','18744','18745','18746','18717','18747','18686','18708','18748','18713','18749','18750','18751','18714','18752','18698','18753','18754','18755','18757','18758','18759','18760','18715','18761','18762','18756'),\n);\n$wp_query = new WP_Query( $custom_args );\nget_header();\nget_template_part('template-parts/headers/header', 'listing');\n?&gt;\n\n&lt;div class=\"container\"&gt;\n &lt;ul class=\"row listing-items\"&gt;\n &lt;?php\n if ( $wp_query-&gt;have_posts() ) {\n while ( $wp_query-&gt;have_posts() ) :\n $wp_query-&gt;the_post();\n ?&gt;\n &lt;li class=\"listing-item col-12 col-sm-12 col-md-12 col-lg-6 col-xl-6\"&gt;\n &lt;a href=\"&lt;?php get_the_permalink(); ?&gt;\"&gt;Serrurier &lt;?php the_title();?&gt;&lt;/a&gt;&lt;/li&gt;\n &lt;?php\n endwhile;\n wp_reset_postdata(); // reset the query\n }\n ?&gt;\n &lt;/ul&gt;\n\n &lt;div class=\"row pagination\"&gt;\n &lt;?php $paginationArgs = array(\n 'base' =&gt; get_pagenum_link(1) . '%_%',\n 'format' =&gt; 'page/%#%/',\n 'total' =&gt; $wp_query-&gt;max_num_pages,\n 'current' =&gt; $paged,\n 'show_all' =&gt; true,\n 'end_size' =&gt; 1,\n 'mid_size' =&gt; 1,\n 'prev_next' =&gt; True,\n 'prev_text' =&gt; __('&amp;laquo;'),\n 'next_text' =&gt; __('&amp;raquo;'),\n 'type' =&gt; 'plain',\n 'add_args' =&gt; false,\n 'add_fragment' =&gt; ''\n );\n ?&gt;\n &lt;div class=\"col-12 heading\"&gt;\n &lt;span&gt;Page &lt;?php echo $paged; ?&gt; sur &lt;?php echo $wp_query-&gt;max_num_pages; ?&gt;&lt;/span&gt;\n &lt;/div&gt;\n\n &lt;div class=\"col-12 items\"&gt;\n &lt;?php echo paginate_links($paginationArgs); ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n\n&lt;/div&gt;\n\n&lt;?php\nget_footer();\n?&gt;\n</code></pre>\n" }, { "answer_id": 407984, "author": "Niki Mihaylov", "author_id": 224360, "author_profile": "https://wordpress.stackexchange.com/users/224360", "pm_score": 0, "selected": false, "text": "<p>I've been looking at the same thing but in my case I was not able to call the query before get_header() so I've found another solution here: <a href=\"https://easywpcode.com/wordpress-add-rel-prev-next-meta-tags-for-custom-query-loop/\" rel=\"nofollow noreferrer\">https://easywpcode.com/wordpress-add-rel-prev-next-meta-tags-for-custom-query-loop/</a></p>\n<p>I'm pasting it here in case is removed for some reason:</p>\n<blockquote>\n<p>When we use custom query loop in wordpress, we lose SEO befenits such as the rel prev/next meta tags that’s in the and improves how Google reads our website.</p>\n</blockquote>\n<blockquote>\n<p>This code will read the custom query pagination and will display those tags in the head section of the pages.</p>\n</blockquote>\n<blockquote>\n<p>Paste this into your theme’s functions.php and edit the following attributes:</p>\n</blockquote>\n<blockquote>\n<p>Instead of “22” (the first “if”) – change to your custom blog page.\n“posts_per_page” is now “10”. Change this number according to your posts_per_page pagination links in your custom blog page.\n(Optional) If our custom query reads another post type but the regular “post”, change the “post_type” parameter to your cpt name instead of “post”.</p>\n</blockquote>\n<pre><code>add_action( 'wp_head', 'rel_next_prev' );\nfunction rel_next_prev(){\n \n global $paged;\n \n if ( get_the_ID() == 22 )\n {\n $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;\n \n $data= new WP_Query(array(\n 'post_type'=&gt;'post', // your post type name\n 'posts_per_page' =&gt; 10, // post per page\n 'paged' =&gt; $paged,\n ));\n \n if($data-&gt;have_posts()) {\n \n $total_pages = $data-&gt;max_num_pages;\n \n if ($total_pages &gt; 1){\n $current_page = max(1, get_query_var('paged'));\n }\n \n if ($total_pages &gt; $paged) { $next_num = $paged + 1; }\n if ($paged &gt; 1) { $prev_num = $paged - 1; }\n \n if ( $prev_num ) { ?&gt;\n \n &lt;link rel=&quot;prev&quot; href=&quot;&lt;?php echo get_pagenum_link( $paged - 1 ); ?&gt;&quot; /&gt;\n &lt;?php } if ( $next_num ) { ?&gt;\n \n &lt;link rel=&quot;next&quot; href=&quot;&lt;?php echo get_pagenum_link( $paged +1 ); ?&gt;&quot; /&gt;\n &lt;?php\n }\n \n }\n \n }\n}\n</code></pre>\n" } ]
2018/06/27
[ "https://wordpress.stackexchange.com/questions/307109", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98907/" ]
I have a custom page template defined and working properly. On this specific page, I want to list a lot of links, and paginate them, to display 100 links per page. Here is the code in my template file, working exactly like I want ``` <div class="container"> <ul class="row listing-items"> <?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $custom_args = array( 'post_type' => 'page', 'posts_per_page' => 90, 'paged' => $paged, 'order' => 'ASC', 'orderby' => 'title', 'post__not_in' => array('6','6371','9522','5038','6380','9521','6385','9276','4159','4087','4085','4082'), 'post_parent__in' => array('13', '154', '127', '162', '123', '167', '159', '121','18675','18676','18677','18678','18679','18680','18681','18682','18683','18684','18685','18687','18688','18689','18690','18691','18692','18693','18695','18696','18697','18699','18700','18701','18702','18703','18704','18694','18709','18705','18710','18706','18707','18718','18719','18720','18721','18722','18723','18724','18725','18726','18711','18727','18728','18729','18730','18731','18732','18716','18733','18734','18712','18735','18736','18737','18738','18739','18740','18741','18742','18743','18744','18745','18746','18717','18747','18686','18708','18748','18713','18749','18750','18751','18714','18752','18698','18753','18754','18755','18757','18758','18759','18760','18715','18761','18762','18756'), ); $wp_query = new WP_Query( $custom_args ); if ( $wp_query->have_posts() ) { while ( $wp_query->have_posts() ) : $wp_query->the_post(); echo '<li class="listing-item col-12 col-sm-12 col-md-12 col-lg-6 col-xl-6">'; echo '<a href="'.get_the_permalink().'">Voiture '.get_the_title().'</a></li>'; endwhile; wp_reset_postdata(); } ?> </ul> ``` Now, for SEO purposes, I want to add in my header rel Next and Prev, so Google understand the pagination and can understand which page is the current one, and which page is next and prev. Here is my code in functions.php ``` function rel_next_prev() { global $paged; if ( get_previous_posts_link() ) { echo '<link rel="prev" href="'.get_pagenum_link( $paged - 1 ).'" />'; } if ( get_next_posts_link() ) { echo '<link rel="next" href="'.get_pagenum_link( $paged + 1 ).'" />'; } } add_action( 'wp_head', 'rel_next_prev' ); ``` Unfortunately, this is partially working. I always get the Rel Prev link in the header, but is not currently based on the query I did. Let me explain: When my query is set, I have 19 pages, under this format: ``` http://localhost:3000/villes/page/2/ ``` So If I change the URL to be (404) ``` http://localhost:3000/villes/page/222/ ``` I still get rel Prev with 221 in the header. *So to resume:* **How do I properly set rel next/prev in the header based on the current query I'm doing?** Thanks!
After a huge night overthinking this, and thanks to Joost de Valk (Yoast SEO plugin author), I found the solution. As per this thread: <https://github.com/Yoast/wordpress-seo/issues/437> , what I want to achieve the way I do, **is undoable, or at least, a very bad practice.** If you want your custom query to have the default pagination and rel next prev in the header, you need to call it before `get_header();` THEORIC SOLUTION ================ To make your custom query work with default WP and Yoast functions, you need to: 1. Put your query **BEFORE** `get_header();` 2. Be sure your query has the default name provided by WP, which is `$wp_query` 3. That being said, you will need to create a specific page template for your query, so you can set your query before getting the header. PRACTIC SOLUTION ================ For the previous code I had, which was working with `get_template_part();`. 1. Create a custom page-template, refering to the page ID or the page slug. More on this here: <https://developer.wordpress.org/themes/template-files-section/page-template-files/> 2. Set your custom query before the `get_header();` function. 3. Be sure to re-adapt your code, so it displays the way you want. Here is my code, which is working as expected. **Be sure to keep the** `rel_next_prev();` **function I placed in my functions.php** Final Result: ``` <?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $custom_args = array( 'post_type' => 'page', 'posts_per_page' => 90, 'paged' => $paged, 'order' => 'ASC', 'orderby' => 'title', 'post__not_in' => array('6','6371','9522','5038','6380','9521','6385','9276','4159','4087','4085','4082'), 'post_parent__in' => array('13', '154', '127', '162', '123', '167', '159', '121','18675','18676','18677','18678','18679','18680','18681','18682','18683','18684','18685','18687','18688','18689','18690','18691','18692','18693','18695','18696','18697','18699','18700','18701','18702','18703','18704','18694','18709','18705','18710','18706','18707','18718','18719','18720','18721','18722','18723','18724','18725','18726','18711','18727','18728','18729','18730','18731','18732','18716','18733','18734','18712','18735','18736','18737','18738','18739','18740','18741','18742','18743','18744','18745','18746','18717','18747','18686','18708','18748','18713','18749','18750','18751','18714','18752','18698','18753','18754','18755','18757','18758','18759','18760','18715','18761','18762','18756'), ); $wp_query = new WP_Query( $custom_args ); get_header(); get_template_part('template-parts/headers/header', 'listing'); ?> <div class="container"> <ul class="row listing-items"> <?php if ( $wp_query->have_posts() ) { while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?> <li class="listing-item col-12 col-sm-12 col-md-12 col-lg-6 col-xl-6"> <a href="<?php get_the_permalink(); ?>">Serrurier <?php the_title();?></a></li> <?php endwhile; wp_reset_postdata(); // reset the query } ?> </ul> <div class="row pagination"> <?php $paginationArgs = array( 'base' => get_pagenum_link(1) . '%_%', 'format' => 'page/%#%/', 'total' => $wp_query->max_num_pages, 'current' => $paged, 'show_all' => true, 'end_size' => 1, 'mid_size' => 1, 'prev_next' => True, 'prev_text' => __('&laquo;'), 'next_text' => __('&raquo;'), 'type' => 'plain', 'add_args' => false, 'add_fragment' => '' ); ?> <div class="col-12 heading"> <span>Page <?php echo $paged; ?> sur <?php echo $wp_query->max_num_pages; ?></span> </div> <div class="col-12 items"> <?php echo paginate_links($paginationArgs); ?> </div> </div> </div> <?php get_footer(); ?> ```
307,113
<p>I have disabled the author pages on my WordPress blog using the Yoast SEO plugin, but I saw that when I click the author name, it just redirects me to the homepage. Can I change the URL myblog.com/author/me directly to myblog.com, without a 301 redirect? Thanks!</p>
[ { "answer_id": 307114, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": false, "text": "<p>Disabling the author pages is a 'good thing'. A 'bad actor' can enumerate your users, or even get your admin user (which is user id 1) with a simple query on any page. So redirecting author requests is a good idea - and a good security measure. (As is never having a user called 'admin', especially if it has admin privileges.)</p>\n\n<p>For instance, an attacker could use the xmlprc.prg page to post multiple requests to any page. They could look through x number of author id's and get a list of the login names of all the user ids. Then use that list to try to get into the admin pages. </p>\n\n<p>I suspect that the Yoast plugin is redirecting author requests. The code to redirect author requests to the home page will look like this:</p>\n\n<pre><code>function wp_redirect_if_author_query() {\n\n $is_author_set = get_query_var( 'author', '' );\n if ( $is_author_set != '' &amp;&amp; !is_admin()) {\n wp_redirect( home_url(), 301 ); // send them somewhere else\n exit;\n }\n}\nadd_action( 'template_redirect', 'wp_redirect_if_author_query' );\n</code></pre>\n\n<p>Put a variation of this code (with the redirect you want to have) in your Child Theme's functions.php file. Or in a simple plugin. (I have a customized personal plugin where I do all sorts of standard settings, including those related to security.) You might need to give a higher priority to the add_action (the optional third parameter, which defaults to 10) to override what the Yoast plugin is doing.</p>\n" }, { "answer_id": 332161, "author": "Nigel Carr", "author_id": 163511, "author_profile": "https://wordpress.stackexchange.com/users/163511", "pm_score": 0, "selected": false, "text": "<p>In Yoast just select:</p>\n\n<p>Author Archives - enabled\nShow in search results - disabled</p>\n\n<p>Better than mucking around with code. </p>\n" }, { "answer_id": 388052, "author": "Shawn W", "author_id": 63357, "author_profile": "https://wordpress.stackexchange.com/users/63357", "pm_score": 1, "selected": false, "text": "<p>If a 301 redirect is not needed, one option is using JS to make the redirect.</p>\n<pre><code>;(function( $ ){\n$(function() {\n /**\n * Redirect on path match\n * @param The current window url\n * @return New url\n */\n\n const URLSearchParams = window.URLSearchParams;\n const urlParams = new URLSearchParams(window.location.search);\n const myParam = urlParams;\n\n let replacer = (function (myParam) {\n let newURL = `/`;\n if (window.location.href.indexOf('author/me') &gt; -1) {\n window.location.replace(newURL);\n } else if (!myParam) {\n return undefined;\n }\n })((myParam));\n });\n})( jQuery );\n</code></pre>\n" }, { "answer_id": 388062, "author": "Robert Went", "author_id": 99385, "author_profile": "https://wordpress.stackexchange.com/users/99385", "pm_score": 0, "selected": false, "text": "<p>You should find the code in your theme that is outputting the link and then remove it to just show the name of the author as text.</p>\n<p>If there are no links to the author pages and they are redirected/noindexed if anyone guesses at them anyway then there isn't a problem.</p>\n" } ]
2018/06/27
[ "https://wordpress.stackexchange.com/questions/307113", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145970/" ]
I have disabled the author pages on my WordPress blog using the Yoast SEO plugin, but I saw that when I click the author name, it just redirects me to the homepage. Can I change the URL myblog.com/author/me directly to myblog.com, without a 301 redirect? Thanks!
Disabling the author pages is a 'good thing'. A 'bad actor' can enumerate your users, or even get your admin user (which is user id 1) with a simple query on any page. So redirecting author requests is a good idea - and a good security measure. (As is never having a user called 'admin', especially if it has admin privileges.) For instance, an attacker could use the xmlprc.prg page to post multiple requests to any page. They could look through x number of author id's and get a list of the login names of all the user ids. Then use that list to try to get into the admin pages. I suspect that the Yoast plugin is redirecting author requests. The code to redirect author requests to the home page will look like this: ``` function wp_redirect_if_author_query() { $is_author_set = get_query_var( 'author', '' ); if ( $is_author_set != '' && !is_admin()) { wp_redirect( home_url(), 301 ); // send them somewhere else exit; } } add_action( 'template_redirect', 'wp_redirect_if_author_query' ); ``` Put a variation of this code (with the redirect you want to have) in your Child Theme's functions.php file. Or in a simple plugin. (I have a customized personal plugin where I do all sorts of standard settings, including those related to security.) You might need to give a higher priority to the add\_action (the optional third parameter, which defaults to 10) to override what the Yoast plugin is doing.
307,155
<p>I could use another set of eyes on this one...its been a little bit of time since I last created a Wordpress theme. I can't figure out what I'm doing wrong here.</p> <p>I created a custom post type (journal) and set up a loop on a custom template, which I set on the homepage.<br> I then have single-journal.php template for the individual post types.<br> The Journal CPT posts show up fine in my home page template, the url/permalink looks correct on inspection. However, when I click through on any of them (I have three at the moment), they all show the content of the latest post. The url/permalink comes up correct in the url bar too, but the content is wrong. Heres some code: This is the loop on the home page template:</p> <pre><code>&lt;div class="post-slider"&gt; &lt;?php $args = array('post_type' =&gt; 'journal', 'posts_per_page' =&gt; -1, 'post_status' =&gt; 'publish', 'orderby' =&gt; 'date', 'order' =&gt; 'DESC'); $loop = new WP_Query($args); if ( $loop-&gt;have_posts() ) : while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;div class="post-card"&gt; &lt;div class="post-card-inner"&gt; &lt;?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" rel="bookmark" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;"&gt; &lt;p&gt;&lt;?php the_title(); ?&gt;&lt;/p&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php // End the loop. endwhile; else: ?&gt; &lt;h1&gt;No posts here!&lt;/h1&gt; &lt;?php endif; wp_reset_postdata(); ?&gt; &lt;/div&gt; </code></pre> <p>This is the loop from single-journal.php:</p> <pre><code> &lt;?php $args = array('post_type' =&gt; 'journal', 'showposts' =&gt; 1, 'post_status' =&gt; 'publish', 'orderby' =&gt; 'date', 'order' =&gt; 'DESC'); $loop = new WP_Query($args); if ( $loop-&gt;have_posts() ) : while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;?php get_template_part( 'content', get_post_format() ); ?&gt; &lt;!--- Add authorname taxonomy --&gt; &lt;?php the_terms( $post-&gt;ID, 'authorname', 'Author: ', ', ', ' ' ); ?&gt; &lt;hr/&gt; &lt;nav class="nav-single"&gt; &lt;h3 class="assistive-text"&gt;&lt;?php _e( 'Post navigation', 'twentytwelve' ); ?&gt;&lt;/h3&gt; &lt;span class="nav-previous"&gt;&lt;?php previous_post_link( '%link', '&lt;span class="meta-nav"&gt;' . _x( '&amp;larr;', 'Previous post link', 'twentytwelve' ) . '&lt;/span&gt; %title' ); ?&gt;&lt;/span&gt; &lt;span class="nav-next"&gt;&lt;?php next_post_link( '%link', '%title &lt;span class="meta-nav"&gt;' . _x( '&amp;rarr;', 'Next post link', 'twentytwelve' ) . '&lt;/span&gt;' ); ?&gt;&lt;/span&gt; &lt;/nav&gt;&lt;!-- .nav-single --&gt; &lt;?php comments_template( '', true ); ?&gt; &lt;?php endwhile; endif; wp_reset_postdata();// end of the loop. ?&gt; </code></pre> <p>This is the custom post type:</p> <pre><code>/* ** Journal Entry ** */ function journal_entry() { // creating (registering) the custom type register_post_type( 'journal', array( 'labels' =&gt; array( 'name' =&gt; __( 'Journal Entry' ), 'singular_name' =&gt; __( 'Journal Entry' ), 'add_new' =&gt; __( 'Add New Journal Entry' ), 'add_new_item' =&gt; __( 'Add New Journal Entry' ), 'edit_item' =&gt; __( 'Edit Journal Entry' ), 'new_item' =&gt; __( 'Add New Journal Entry' ), 'view_item' =&gt; __( 'View Journal Entry' ), 'search_items' =&gt; __( 'Search Journal Entry' ), 'not_found' =&gt; __( 'No Journal Entry found' ), 'not_found_in_trash' =&gt; __( 'No Journal Entry found in trash' ), 'menu_name' =&gt; _x( 'Journal Entry', 'journal' ), ), //'taxonomies' =&gt; array('category'), 'public' =&gt; true, 'exclude_from_search' =&gt; false, 'publicly_queryable' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'thumbnail', 'custom-fields' ), 'capability_type' =&gt; 'post', 'rewrite' =&gt; array("slug" =&gt; "journal"), // Permalinks format 'has_archive' =&gt; true, 'query_var' =&gt; true, 'menu_position' =&gt; 5, 'menu_icon' =&gt; 'dashicons-book-alt', /* the icon for the custom post type menu */ //'register_meta_box_cb' =&gt; 'add_team_members_metaboxes' //'yarpp_support' =&gt; true ) ); /* end of register post type */ /* this adds your post categories to your custom post type */ //register_taxonomy_for_object_type( 'category', 'stories' ); /* this adds your post tags to your custom post type */ //register_taxonomy_for_object_type( 'post_tag', 'custom_post_faq' ); } add_action( 'init', 'journal_entry'); function journal_taxonomy() { register_taxonomy( 'journal_categories', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces). 'journal', //post type name array( 'hierarchical' =&gt; true, 'label' =&gt; 'Custom Categories', //Display name 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'journal-categories', // This controls the base slug that will display before each term 'with_front' =&gt; false // Don't display the category base before ) ) ); } add_action( 'init', 'journal_taxonomy'); </code></pre>
[ { "answer_id": 307157, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>The Main Query already contains the correct post, but you are creating a new query and asking for a single post ordered by date, which will always give you the latest post.</p>\n\n<p>Remove your custom query code and just run the default loop:</p>\n\n<pre><code>if( have_posts() ) : while( have_posts() ) : the_post(); \n // your template tags here\nendwhile; endif;\n</code></pre>\n\n<p>This will output the correct post from the global <code>$wp_query</code>.</p>\n" }, { "answer_id": 307158, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You shouldn't be using custom queries in these templates. The main query (using <code>have_posts();</code>, <code>the_post();</code> etc. without <code>$loop</code>) is already set up with the correct posts for these templates.</p>\n\n<p>Look at the custom query you're using on the single template:</p>\n\n<pre><code>$args = array('post_type' =&gt; 'journal', \n 'showposts' =&gt; 1,\n 'post_status' =&gt; 'publish',\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC'); \n $loop = new WP_Query($args);\n</code></pre>\n\n<p>That's a query for the latest journal post. So of that's what you're going to see when you use <code>$loop-&gt;the_post()</code>. Also, <code>showposts</code> is deprecated. Use <code>posts_per_page</code> instead.</p>\n\n<p>So this:</p>\n\n<pre><code>if ( $loop-&gt;have_posts() ) : while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt;\n</code></pre>\n\n<p>Needs to be:</p>\n\n<pre><code>if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt;\n</code></pre>\n" } ]
2018/06/28
[ "https://wordpress.stackexchange.com/questions/307155", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64900/" ]
I could use another set of eyes on this one...its been a little bit of time since I last created a Wordpress theme. I can't figure out what I'm doing wrong here. I created a custom post type (journal) and set up a loop on a custom template, which I set on the homepage. I then have single-journal.php template for the individual post types. The Journal CPT posts show up fine in my home page template, the url/permalink looks correct on inspection. However, when I click through on any of them (I have three at the moment), they all show the content of the latest post. The url/permalink comes up correct in the url bar too, but the content is wrong. Heres some code: This is the loop on the home page template: ``` <div class="post-slider"> <?php $args = array('post_type' => 'journal', 'posts_per_page' => -1, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC'); $loop = new WP_Query($args); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="post-card"> <div class="post-card-inner"> <?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?> <a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"> <p><?php the_title(); ?></p> </a> </div> </div> <?php // End the loop. endwhile; else: ?> <h1>No posts here!</h1> <?php endif; wp_reset_postdata(); ?> </div> ``` This is the loop from single-journal.php: ``` <?php $args = array('post_type' => 'journal', 'showposts' => 1, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC'); $loop = new WP_Query($args); if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <!--- Add authorname taxonomy --> <?php the_terms( $post->ID, 'authorname', 'Author: ', ', ', ' ' ); ?> <hr/> <nav class="nav-single"> <h3 class="assistive-text"><?php _e( 'Post navigation', 'twentytwelve' ); ?></h3> <span class="nav-previous"><?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '&larr;', 'Previous post link', 'twentytwelve' ) . '</span> %title' ); ?></span> <span class="nav-next"><?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '&rarr;', 'Next post link', 'twentytwelve' ) . '</span>' ); ?></span> </nav><!-- .nav-single --> <?php comments_template( '', true ); ?> <?php endwhile; endif; wp_reset_postdata();// end of the loop. ?> ``` This is the custom post type: ``` /* ** Journal Entry ** */ function journal_entry() { // creating (registering) the custom type register_post_type( 'journal', array( 'labels' => array( 'name' => __( 'Journal Entry' ), 'singular_name' => __( 'Journal Entry' ), 'add_new' => __( 'Add New Journal Entry' ), 'add_new_item' => __( 'Add New Journal Entry' ), 'edit_item' => __( 'Edit Journal Entry' ), 'new_item' => __( 'Add New Journal Entry' ), 'view_item' => __( 'View Journal Entry' ), 'search_items' => __( 'Search Journal Entry' ), 'not_found' => __( 'No Journal Entry found' ), 'not_found_in_trash' => __( 'No Journal Entry found in trash' ), 'menu_name' => _x( 'Journal Entry', 'journal' ), ), //'taxonomies' => array('category'), 'public' => true, 'exclude_from_search' => false, 'publicly_queryable' => true, 'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields' ), 'capability_type' => 'post', 'rewrite' => array("slug" => "journal"), // Permalinks format 'has_archive' => true, 'query_var' => true, 'menu_position' => 5, 'menu_icon' => 'dashicons-book-alt', /* the icon for the custom post type menu */ //'register_meta_box_cb' => 'add_team_members_metaboxes' //'yarpp_support' => true ) ); /* end of register post type */ /* this adds your post categories to your custom post type */ //register_taxonomy_for_object_type( 'category', 'stories' ); /* this adds your post tags to your custom post type */ //register_taxonomy_for_object_type( 'post_tag', 'custom_post_faq' ); } add_action( 'init', 'journal_entry'); function journal_taxonomy() { register_taxonomy( 'journal_categories', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces). 'journal', //post type name array( 'hierarchical' => true, 'label' => 'Custom Categories', //Display name 'query_var' => true, 'rewrite' => array( 'slug' => 'journal-categories', // This controls the base slug that will display before each term 'with_front' => false // Don't display the category base before ) ) ); } add_action( 'init', 'journal_taxonomy'); ```
You shouldn't be using custom queries in these templates. The main query (using `have_posts();`, `the_post();` etc. without `$loop`) is already set up with the correct posts for these templates. Look at the custom query you're using on the single template: ``` $args = array('post_type' => 'journal', 'showposts' => 1, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC'); $loop = new WP_Query($args); ``` That's a query for the latest journal post. So of that's what you're going to see when you use `$loop->the_post()`. Also, `showposts` is deprecated. Use `posts_per_page` instead. So this: ``` if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> ``` Needs to be: ``` if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> ```
307,159
<p>I am setting up non-for-profit domestic violence support website and struggle to find a way to create active category parent and it children links in pages sidebar.</p> <p>What is the ideal solution to dynamically display category parent and it's children?</p>
[ { "answer_id": 307157, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>The Main Query already contains the correct post, but you are creating a new query and asking for a single post ordered by date, which will always give you the latest post.</p>\n\n<p>Remove your custom query code and just run the default loop:</p>\n\n<pre><code>if( have_posts() ) : while( have_posts() ) : the_post(); \n // your template tags here\nendwhile; endif;\n</code></pre>\n\n<p>This will output the correct post from the global <code>$wp_query</code>.</p>\n" }, { "answer_id": 307158, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You shouldn't be using custom queries in these templates. The main query (using <code>have_posts();</code>, <code>the_post();</code> etc. without <code>$loop</code>) is already set up with the correct posts for these templates.</p>\n\n<p>Look at the custom query you're using on the single template:</p>\n\n<pre><code>$args = array('post_type' =&gt; 'journal', \n 'showposts' =&gt; 1,\n 'post_status' =&gt; 'publish',\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC'); \n $loop = new WP_Query($args);\n</code></pre>\n\n<p>That's a query for the latest journal post. So of that's what you're going to see when you use <code>$loop-&gt;the_post()</code>. Also, <code>showposts</code> is deprecated. Use <code>posts_per_page</code> instead.</p>\n\n<p>So this:</p>\n\n<pre><code>if ( $loop-&gt;have_posts() ) : while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt;\n</code></pre>\n\n<p>Needs to be:</p>\n\n<pre><code>if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt;\n</code></pre>\n" } ]
2018/06/28
[ "https://wordpress.stackexchange.com/questions/307159", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145989/" ]
I am setting up non-for-profit domestic violence support website and struggle to find a way to create active category parent and it children links in pages sidebar. What is the ideal solution to dynamically display category parent and it's children?
You shouldn't be using custom queries in these templates. The main query (using `have_posts();`, `the_post();` etc. without `$loop`) is already set up with the correct posts for these templates. Look at the custom query you're using on the single template: ``` $args = array('post_type' => 'journal', 'showposts' => 1, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC'); $loop = new WP_Query($args); ``` That's a query for the latest journal post. So of that's what you're going to see when you use `$loop->the_post()`. Also, `showposts` is deprecated. Use `posts_per_page` instead. So this: ``` if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> ``` Needs to be: ``` if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> ```
307,209
<p>First of all, I tried searching and working on this, but couldn't create the logic or method to do this.</p> <p>I'm trying to display <code>users</code> and <code>custom post type</code> content together into a single <code>loop</code>. I can get the value of <code>custom post type</code> using <code>WP_Query</code> and <code>users</code> using <code>WP_USER_Query</code>. and I can display them simultaneously. But then the posts and users won't be mixed in the order of date.</p> <p>I'm not sure if I can achieve this via custom <code>query</code>. My knowledge and experience is limited on this part. </p> <p>Can anyone help me put in the right direction about how I can achieve this?</p> <hr> <p>// Edit and Update</p> <p>Thank you all for your comment, I believe I gave the half of the idea of what I really need and how I'm trying to achieve it. So I'll begin with the idea/scenario.</p> <p>General Idea: </p> <ol> <li>I have Custom post type, let's call it "assignment" and "projects".</li> <li>I have users on the site, let's call them "teacher" and "student".</li> <li>multiple teachers can assign "assignment" and "projects" to multiple students.</li> <li>Now, I have a "Directory" page, on which I wish to display all (teacher, student, assignments, and projects).</li> <li>On the frontend, I wish to display each cpt entry and users in thumbnail view like the 4x4 grid.</li> </ol> <p>Now, I have create a page-template called <code>directory.php</code> and used the following loop to display only cpt <code>assignment</code> and <code>projects</code>.</p> <pre><code>$args = array( 'post_type' =&gt; array('assigment', 'project'), 'post_status' =&gt; 'publish', 'order' =&gt; 'ASC' ); $query = new WP_query( $args ); </code></pre> <p>and looped it like this</p> <pre><code>&lt;?php if ( $query-&gt;have_posts() ) : ?&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); get_template_part( 'template-parts/content', get_post_type() ); endwhile; the_posts_navigation(); else : get_template_part( 'template-parts/content', 'none' ); endif; wp_reset_postdata(); ?&gt; </code></pre> <p>the code is working, but please focus on the syntax error if any. now the part of users. I wrote it like this.</p> <pre><code>$user = new WP_User_Query(array('role'=&gt; 'teacher')); if (!empty($user)) { foreach ($user as $teacher) { echo $teacher-&gt;first_name; } } </code></pre> <p>you get the basic idea of how I can use the users. </p> <p><strong>The main Question</strong></p> <p>How can I merge Users within the post loop, so users and posts display in a grid of 4x4 and order by timestamps?</p> <p>For example, we have the following with the date of creation.</p> <p>Teach A ( 10 Jun, 2018 ) Teach B ( 12 Jun, 2018 ) Stud C ( 15 Jun, 2018 ) Assign 1 ( 16 Jun, 2018 ) Assign 2 ( 18 Jun, 2018 ) Stud D ( 20 Jun, 2018 ) Proj 1 ( 22 Jun, 2018 )</p> <p>and then I display in the 4x4 grid like this.</p> <p>Teach A Teach B Stud C Assign 1 Assign 2 Stud D Proj 1</p> <p>Please let me know if it's still confusing. </p>
[ { "answer_id": 307518, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>You can not merge two different queries when the returned type is an object, because they have different methods and properties. Instead, you can get them as an array. Then you can merge them and compare the dates. For this, I'm going to use <code>get_posts()</code> over <code>WP_Query()</code>, and <code>get_users()</code> over <code>WP_User_Query()</code> to achieve this.</p>\n\n<p>The code itself should be self explanatory.</p>\n\n<pre><code>// Get a list of users\n$users = get_users ();\n\n// Get an array of posts. Don't forget to set the args\n$posts = get_posts();\n\n// Let's merge these two\n$users_posts = array_merge( $users, $posts );\n\n// Now, let's sort both of them based on \n// their dates. a user object holds the date\n// as `user_registered`, while a post object\n// holds the date as `post_date`. We use the\n// usort() function to do so.\nusort( $users_posts, \"sort_users_and_posts\" );\n\n// Function to sort the array\nfunction sort_users_and_posts( $a, $b ){\n\n // Here's the tricky part. We need to get the\n // date based on the object type, and then compare them.\n\n // Get the date for first element\n if( $a instanceof WP_User ){\n $first_element_date = strtotime ( $a-&gt;user_registered );\n } else {\n $first_element_date = strtotime ( $a-&gt;post_date );\n }\n\n // Get the date for second element\n if( $b instanceof WP_User ){\n $second_element_date = strtotime ( $b-&gt;user_registered );\n } else {\n $second_element_date = strtotime ( $b-&gt;post_date );\n }\n\n // Now let's compare the dates\n\n // If the dates are the same\n if ( $first_element_date == $second_element_date ) return 0;\n\n // If one is bigger than the other\n return ( $first_element_date &lt; $second_element_date ) ? -1 : 1;\n\n}\n\n// Now, we run a foreach loop and output the date.\n// We need to check again whether the object is an\n// instance of WP_Post or WP_User\nforeach ( $users_posts as $object ) {\n if( $object instanceof WP_Post ){\n // This is a post\n } else {\n // This is a user\n }\n}\n</code></pre>\n" }, { "answer_id": 307587, "author": "kierzniak", "author_id": 132363, "author_profile": "https://wordpress.stackexchange.com/users/132363", "pm_score": 2, "selected": false, "text": "<p>You can create additional two custom post types teacher and student which will inherit from your WordPress user.</p>\n\n<pre><code> +------+\n +----+ User +----+\n | +------+ |\n | |\n | |\n v v\n+----+----+ +----+----+ +---------+ +------------+\n| Teacher | | Student | | Project | | Assignment |\n+---------+ +---------+ +---------+ +------------+\n</code></pre>\n\n<p>You can relate WordPress user with teacher/student post type using post meta fields.</p>\n\n<p>This data structure will allow you to create a single loop for all of your resources.</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; array( 'teacher', 'student', 'assigment', 'project' ),\n 'order' =&gt; 'ASC'\n);\n\n$query = new WP_query( $args );\n</code></pre>\n" } ]
2018/06/28
[ "https://wordpress.stackexchange.com/questions/307209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/110899/" ]
First of all, I tried searching and working on this, but couldn't create the logic or method to do this. I'm trying to display `users` and `custom post type` content together into a single `loop`. I can get the value of `custom post type` using `WP_Query` and `users` using `WP_USER_Query`. and I can display them simultaneously. But then the posts and users won't be mixed in the order of date. I'm not sure if I can achieve this via custom `query`. My knowledge and experience is limited on this part. Can anyone help me put in the right direction about how I can achieve this? --- // Edit and Update Thank you all for your comment, I believe I gave the half of the idea of what I really need and how I'm trying to achieve it. So I'll begin with the idea/scenario. General Idea: 1. I have Custom post type, let's call it "assignment" and "projects". 2. I have users on the site, let's call them "teacher" and "student". 3. multiple teachers can assign "assignment" and "projects" to multiple students. 4. Now, I have a "Directory" page, on which I wish to display all (teacher, student, assignments, and projects). 5. On the frontend, I wish to display each cpt entry and users in thumbnail view like the 4x4 grid. Now, I have create a page-template called `directory.php` and used the following loop to display only cpt `assignment` and `projects`. ``` $args = array( 'post_type' => array('assigment', 'project'), 'post_status' => 'publish', 'order' => 'ASC' ); $query = new WP_query( $args ); ``` and looped it like this ``` <?php if ( $query->have_posts() ) : ?> <?php while ( $query->have_posts() ) : $query->the_post(); get_template_part( 'template-parts/content', get_post_type() ); endwhile; the_posts_navigation(); else : get_template_part( 'template-parts/content', 'none' ); endif; wp_reset_postdata(); ?> ``` the code is working, but please focus on the syntax error if any. now the part of users. I wrote it like this. ``` $user = new WP_User_Query(array('role'=> 'teacher')); if (!empty($user)) { foreach ($user as $teacher) { echo $teacher->first_name; } } ``` you get the basic idea of how I can use the users. **The main Question** How can I merge Users within the post loop, so users and posts display in a grid of 4x4 and order by timestamps? For example, we have the following with the date of creation. Teach A ( 10 Jun, 2018 ) Teach B ( 12 Jun, 2018 ) Stud C ( 15 Jun, 2018 ) Assign 1 ( 16 Jun, 2018 ) Assign 2 ( 18 Jun, 2018 ) Stud D ( 20 Jun, 2018 ) Proj 1 ( 22 Jun, 2018 ) and then I display in the 4x4 grid like this. Teach A Teach B Stud C Assign 1 Assign 2 Stud D Proj 1 Please let me know if it's still confusing.
You can not merge two different queries when the returned type is an object, because they have different methods and properties. Instead, you can get them as an array. Then you can merge them and compare the dates. For this, I'm going to use `get_posts()` over `WP_Query()`, and `get_users()` over `WP_User_Query()` to achieve this. The code itself should be self explanatory. ``` // Get a list of users $users = get_users (); // Get an array of posts. Don't forget to set the args $posts = get_posts(); // Let's merge these two $users_posts = array_merge( $users, $posts ); // Now, let's sort both of them based on // their dates. a user object holds the date // as `user_registered`, while a post object // holds the date as `post_date`. We use the // usort() function to do so. usort( $users_posts, "sort_users_and_posts" ); // Function to sort the array function sort_users_and_posts( $a, $b ){ // Here's the tricky part. We need to get the // date based on the object type, and then compare them. // Get the date for first element if( $a instanceof WP_User ){ $first_element_date = strtotime ( $a->user_registered ); } else { $first_element_date = strtotime ( $a->post_date ); } // Get the date for second element if( $b instanceof WP_User ){ $second_element_date = strtotime ( $b->user_registered ); } else { $second_element_date = strtotime ( $b->post_date ); } // Now let's compare the dates // If the dates are the same if ( $first_element_date == $second_element_date ) return 0; // If one is bigger than the other return ( $first_element_date < $second_element_date ) ? -1 : 1; } // Now, we run a foreach loop and output the date. // We need to check again whether the object is an // instance of WP_Post or WP_User foreach ( $users_posts as $object ) { if( $object instanceof WP_Post ){ // This is a post } else { // This is a user } } ```
307,239
<p>Just starting to play with Gutenberg block development, and I am building a very simple button (yes I know buttons are already included, but this block will have lots of settings and classes not included in the core block).</p> <p>Seem's pretty strait forward, but when I save the block and reload, I get a validation error and the "This block appears to have been modified externally" message.</p> <pre><code>registerBlockType('franklin/button', { title: 'Button', keywords: ['button' ], icon: 'admin-links', category: 'layout', attributes: { text: { source: 'text', selector: '.button-text' }, }, edit({attributes, setAttributes }) { return ( &lt;div class="guttenberg-usa-button"&gt; &lt;button class="usa-button"&gt; &lt;PlainText onChange={ content =&gt; setAttributes({ text: content }) } value={ attributes.text } placeholder="Your button text" className="button-text" /&gt; &lt;/button&gt; &lt;/div&gt; ); }, save({attributes}) { return ( &lt;button class="usa-button"&gt; { attributes.text } &lt;/button&gt; ); } }); </code></pre> <p>So in the editor, I'll add my block, modify the (button) text, save, and reload where I get the This block appears to have been modified externally" message.</p> <p>Console shows the following error</p> <pre><code>Expected: &lt;button class="usa-button" class="wp-block-franklin-button"&gt;&lt;/button&gt; Actual: &lt;button class="usa-button" class="wp-block-franklin-button"&gt;testest&lt;/button&gt; </code></pre> <p>I must be missing some fundamental concept or something, but I thought the save() function determines what gets displayed on the frontend which btw, looks as expected.</p>
[ { "answer_id": 307518, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>You can not merge two different queries when the returned type is an object, because they have different methods and properties. Instead, you can get them as an array. Then you can merge them and compare the dates. For this, I'm going to use <code>get_posts()</code> over <code>WP_Query()</code>, and <code>get_users()</code> over <code>WP_User_Query()</code> to achieve this.</p>\n\n<p>The code itself should be self explanatory.</p>\n\n<pre><code>// Get a list of users\n$users = get_users ();\n\n// Get an array of posts. Don't forget to set the args\n$posts = get_posts();\n\n// Let's merge these two\n$users_posts = array_merge( $users, $posts );\n\n// Now, let's sort both of them based on \n// their dates. a user object holds the date\n// as `user_registered`, while a post object\n// holds the date as `post_date`. We use the\n// usort() function to do so.\nusort( $users_posts, \"sort_users_and_posts\" );\n\n// Function to sort the array\nfunction sort_users_and_posts( $a, $b ){\n\n // Here's the tricky part. We need to get the\n // date based on the object type, and then compare them.\n\n // Get the date for first element\n if( $a instanceof WP_User ){\n $first_element_date = strtotime ( $a-&gt;user_registered );\n } else {\n $first_element_date = strtotime ( $a-&gt;post_date );\n }\n\n // Get the date for second element\n if( $b instanceof WP_User ){\n $second_element_date = strtotime ( $b-&gt;user_registered );\n } else {\n $second_element_date = strtotime ( $b-&gt;post_date );\n }\n\n // Now let's compare the dates\n\n // If the dates are the same\n if ( $first_element_date == $second_element_date ) return 0;\n\n // If one is bigger than the other\n return ( $first_element_date &lt; $second_element_date ) ? -1 : 1;\n\n}\n\n// Now, we run a foreach loop and output the date.\n// We need to check again whether the object is an\n// instance of WP_Post or WP_User\nforeach ( $users_posts as $object ) {\n if( $object instanceof WP_Post ){\n // This is a post\n } else {\n // This is a user\n }\n}\n</code></pre>\n" }, { "answer_id": 307587, "author": "kierzniak", "author_id": 132363, "author_profile": "https://wordpress.stackexchange.com/users/132363", "pm_score": 2, "selected": false, "text": "<p>You can create additional two custom post types teacher and student which will inherit from your WordPress user.</p>\n\n<pre><code> +------+\n +----+ User +----+\n | +------+ |\n | |\n | |\n v v\n+----+----+ +----+----+ +---------+ +------------+\n| Teacher | | Student | | Project | | Assignment |\n+---------+ +---------+ +---------+ +------------+\n</code></pre>\n\n<p>You can relate WordPress user with teacher/student post type using post meta fields.</p>\n\n<p>This data structure will allow you to create a single loop for all of your resources.</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; array( 'teacher', 'student', 'assigment', 'project' ),\n 'order' =&gt; 'ASC'\n);\n\n$query = new WP_query( $args );\n</code></pre>\n" } ]
2018/06/28
[ "https://wordpress.stackexchange.com/questions/307239", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/19536/" ]
Just starting to play with Gutenberg block development, and I am building a very simple button (yes I know buttons are already included, but this block will have lots of settings and classes not included in the core block). Seem's pretty strait forward, but when I save the block and reload, I get a validation error and the "This block appears to have been modified externally" message. ``` registerBlockType('franklin/button', { title: 'Button', keywords: ['button' ], icon: 'admin-links', category: 'layout', attributes: { text: { source: 'text', selector: '.button-text' }, }, edit({attributes, setAttributes }) { return ( <div class="guttenberg-usa-button"> <button class="usa-button"> <PlainText onChange={ content => setAttributes({ text: content }) } value={ attributes.text } placeholder="Your button text" className="button-text" /> </button> </div> ); }, save({attributes}) { return ( <button class="usa-button"> { attributes.text } </button> ); } }); ``` So in the editor, I'll add my block, modify the (button) text, save, and reload where I get the This block appears to have been modified externally" message. Console shows the following error ``` Expected: <button class="usa-button" class="wp-block-franklin-button"></button> Actual: <button class="usa-button" class="wp-block-franklin-button">testest</button> ``` I must be missing some fundamental concept or something, but I thought the save() function determines what gets displayed on the frontend which btw, looks as expected.
You can not merge two different queries when the returned type is an object, because they have different methods and properties. Instead, you can get them as an array. Then you can merge them and compare the dates. For this, I'm going to use `get_posts()` over `WP_Query()`, and `get_users()` over `WP_User_Query()` to achieve this. The code itself should be self explanatory. ``` // Get a list of users $users = get_users (); // Get an array of posts. Don't forget to set the args $posts = get_posts(); // Let's merge these two $users_posts = array_merge( $users, $posts ); // Now, let's sort both of them based on // their dates. a user object holds the date // as `user_registered`, while a post object // holds the date as `post_date`. We use the // usort() function to do so. usort( $users_posts, "sort_users_and_posts" ); // Function to sort the array function sort_users_and_posts( $a, $b ){ // Here's the tricky part. We need to get the // date based on the object type, and then compare them. // Get the date for first element if( $a instanceof WP_User ){ $first_element_date = strtotime ( $a->user_registered ); } else { $first_element_date = strtotime ( $a->post_date ); } // Get the date for second element if( $b instanceof WP_User ){ $second_element_date = strtotime ( $b->user_registered ); } else { $second_element_date = strtotime ( $b->post_date ); } // Now let's compare the dates // If the dates are the same if ( $first_element_date == $second_element_date ) return 0; // If one is bigger than the other return ( $first_element_date < $second_element_date ) ? -1 : 1; } // Now, we run a foreach loop and output the date. // We need to check again whether the object is an // instance of WP_Post or WP_User foreach ( $users_posts as $object ) { if( $object instanceof WP_Post ){ // This is a post } else { // This is a user } } ```
307,259
<p>I've just checked a double click on my form that inserts new user meta, which actually inserted it twice! The problem is, I actually need the values to be non-unique so I can insert multiple times. </p> <p>My aim is simple, to capture post the data from the form into the <code>user_meta</code>table only once from the form, but it seems to insert twice, three times... As many times as I click the submit button.</p> <p>I've tried this Javascript:</p> <pre><code>var wasSubmitted = false; function checkBeforeSubmit(){ if(!wasSubmitted) { wasSubmitted = true; return wasSubmitted; } return false; } </code></pre> <p>And nothing happened, I'm wondering, how do I do this with PHP? Or even a bit of Javascript that will actually work.</p> <p>Ideally, I don't want to use jQuery, I prefer simple JS.</p>
[ { "answer_id": 307264, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 2, "selected": false, "text": "<p>Dunno if you looked at add_user_meta, but it takes an optional fourth parameter.</p>\n\n<pre><code>function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false )\n</code></pre>\n\n<p>Send \"true\" to the $unique value and it won't insert it twice.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_user_meta/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_user_meta/</a></p>\n" }, { "answer_id": 321896, "author": "not_a_generic_user", "author_id": 155923, "author_profile": "https://wordpress.stackexchange.com/users/155923", "pm_score": 0, "selected": false, "text": "<p>It will be far less effective trying to do it in JS than on the backend. Let JS call your script all you like, just have PHP prevent the duplicates. Unfortunately, there doesn't seem to be a built-in method. You'll have to check manually, but it's not super hard. Instead of:</p>\n\n<pre><code>add_user_meta($userid,$yourkey,$valuetoadd);\n</code></pre>\n\n<p>Do this:</p>\n\n<pre><code>$yourkey_arr = get_user_meta($user_id,'yourkey');\nif (!in_array($valuetoadd,$yourkey_arr))\n add_user_meta($user_id,'yourkey',$valuetoadd);\n</code></pre>\n" }, { "answer_id": 408559, "author": "Faraz Ahmad", "author_id": 183383, "author_profile": "https://wordpress.stackexchange.com/users/183383", "pm_score": 0, "selected": false, "text": "<p>If someone is still looking for a solution, then they can try this (it worked for me)</p>\n<pre><code>delete_user_meta($user_id, $meta_key, 'your_new_meta_value');\nadd_user_meta($user_id, $meta_key, 'your_new_meta_value');\n</code></pre>\n<p>That is, use <code>delete_user_meta()</code> function with your new-meta-value. If the meta value already existed, it would delete it. Then you use <code>add_user_meta()</code> to add it.</p>\n" } ]
2018/06/28
[ "https://wordpress.stackexchange.com/questions/307259", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146035/" ]
I've just checked a double click on my form that inserts new user meta, which actually inserted it twice! The problem is, I actually need the values to be non-unique so I can insert multiple times. My aim is simple, to capture post the data from the form into the `user_meta`table only once from the form, but it seems to insert twice, three times... As many times as I click the submit button. I've tried this Javascript: ``` var wasSubmitted = false; function checkBeforeSubmit(){ if(!wasSubmitted) { wasSubmitted = true; return wasSubmitted; } return false; } ``` And nothing happened, I'm wondering, how do I do this with PHP? Or even a bit of Javascript that will actually work. Ideally, I don't want to use jQuery, I prefer simple JS.
Dunno if you looked at add\_user\_meta, but it takes an optional fourth parameter. ``` function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) ``` Send "true" to the $unique value and it won't insert it twice. <https://developer.wordpress.org/reference/functions/add_user_meta/>
307,307
<ul> <li>I'm using Advanced Custom Fields.</li> <li>I have a registered <code>bookitall_roomstype</code> custom post type. </li> <li>I have a registered <code>bookitall_bookings</code> as another custom post type.</li> <li>In the bookitall_bookings there is a field called <code>bookitall_roomstype</code> that is stored as a <code>pagelink</code> (acf "type"). (This looks like a permalink to the actual roomtype (It's NOT stored as a title/name)</li> </ul> <p>I'm setting up certain columns (and their values) to be shown. Now I want the roomtype's name to be shown. I'm doing like below...</p> <p><strong>This is a snippet of my code. This snippet retrieves the NAME <code>roomtype_name</code> of the pagelink-type <code>bookitall_roomstype</code></strong>:</p> <pre><code>$allfields_currentpost = get_fields(); $args = array( 'posts_per_page' =&gt; -1, 'offset' =&gt; 0, 'orderby' =&gt; 'ID', 'order' =&gt; 'ASC', 'post_type' =&gt; 'bookitall_roomtypes' ); $roomtypes = get_posts( $args ); $pagelink = get_field('bookitall_roomstype'); //pagelink acf type $roomtypes_slugs = array(); foreach ( $roomtypes as $r ) { $roomtypes_slugs[] = get_permalink( $r-&gt;ID); } $arrkey = (array_search($pagelink, $roomtypes_slugs)); $roomtype_name = ''; if ( $arrkey !== false ) { $roomtype_name = $roomtypes[$arrkey]-&gt;post_title; } </code></pre> <p><strong><em>The above do actually work</em></strong> (I put it here if someone have the same issue and I also <strong>want to know if there is a better/simpler way of achieving above?</strong> (getting the roomtype's name from current post)</p> <p>I've tried to use <code>url to postid( $pagelink )</code> and <code>get_page_by_path( $pagelink )</code> but those only returns 0 (which means no object is returned). If a post had been returned I could use <code>$post-&gt;post_title</code>.</p> <p>UPDATE: <strong>New code</strong> (thanks to @Milo !!!):</p> <pre><code>$allfields_currentpost = get_fields(false, false); $roomtype_id = $allfields_currentpost['bookitall_roomstype']; $roomtype_name = get_the_title($roomtype_id); </code></pre> <p>(I'm jusing the other field values from the current post as well, therefore I'm using <code>get_fields()</code> instead of <code>get_field()</code>)</p>
[ { "answer_id": 307319, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>You shouldn't need to get all <code>bookitall_roomstype</code> in lines 2-9 of your code. You really only want to pull room types that are assigned to the current <code>bookitall_bookings</code> CPT.</p>\n\n<p>As far as the \"pagelink\" field, this seems like an unsafe way of calling the information. What if a permalink changed someday? It seems like it would be both safer and more efficient to save post IDs instead of permalinks as the <code>bookitall_roomtypes</code> field.</p>\n\n<p>With that in mind, and also to make it clearer <code>bookitall_roomstype</code> CPT name is not the same as <code>bookitall_roomtypes</code> custom field, I would suggest something like this:</p>\n\n<pre><code>// pull an ACF field that has the post ID saved\n$room_type_ids = get_field('bookitall_room_type_ids');\n// create an empty array to hold room type details\n$room_types = array();\nforeach($room_type_ids as $room) {\n // save the permalink\n $room_types[][0] = get_the_permalink($room);\n // save the name\n $room_types[][1] = get_the_title($room);\n}\n// now you can loop through the room types to display as you wish\n// this just links the name to the permalink, but you can add whatever\n// markup you need\nforeach($room_types as $room_details) {\n echo '&lt;a href=\"' . $room_details[0] . '\"&gt;' . $room_details[1] . '&lt;/a&gt;';\n}\n</code></pre>\n\n<p>This way you're only pulling the minimum information required, and not every single roomtype, followed by each roomtype's details, only then to check whether you need those particular details for the current post or not. :)</p>\n" }, { "answer_id": 307321, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://www.advancedcustomfields.com/resources/page-link/\" rel=\"nofollow noreferrer\">The page link field</a> actually stores the post ID, which gets formatted internally by the <code>get_field</code> function on output. The 3rd argument for <code>get_field</code> lets you disable that output formatting so you just get the ID back, which you can then use to get title and permalink for that post:</p>\n\n<pre><code>$post_id = get_field( 'bookitall_roomstype', false, false );\nif( $post_id ):\n echo get_the_permalink( $post_id );\n echo get_the_title( $post_id );\nendif;\n</code></pre>\n" } ]
2018/06/29
[ "https://wordpress.stackexchange.com/questions/307307", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38848/" ]
* I'm using Advanced Custom Fields. * I have a registered `bookitall_roomstype` custom post type. * I have a registered `bookitall_bookings` as another custom post type. * In the bookitall\_bookings there is a field called `bookitall_roomstype` that is stored as a `pagelink` (acf "type"). (This looks like a permalink to the actual roomtype (It's NOT stored as a title/name) I'm setting up certain columns (and their values) to be shown. Now I want the roomtype's name to be shown. I'm doing like below... **This is a snippet of my code. This snippet retrieves the NAME `roomtype_name` of the pagelink-type `bookitall_roomstype`**: ``` $allfields_currentpost = get_fields(); $args = array( 'posts_per_page' => -1, 'offset' => 0, 'orderby' => 'ID', 'order' => 'ASC', 'post_type' => 'bookitall_roomtypes' ); $roomtypes = get_posts( $args ); $pagelink = get_field('bookitall_roomstype'); //pagelink acf type $roomtypes_slugs = array(); foreach ( $roomtypes as $r ) { $roomtypes_slugs[] = get_permalink( $r->ID); } $arrkey = (array_search($pagelink, $roomtypes_slugs)); $roomtype_name = ''; if ( $arrkey !== false ) { $roomtype_name = $roomtypes[$arrkey]->post_title; } ``` ***The above do actually work*** (I put it here if someone have the same issue and I also **want to know if there is a better/simpler way of achieving above?** (getting the roomtype's name from current post) I've tried to use `url to postid( $pagelink )` and `get_page_by_path( $pagelink )` but those only returns 0 (which means no object is returned). If a post had been returned I could use `$post->post_title`. UPDATE: **New code** (thanks to @Milo !!!): ``` $allfields_currentpost = get_fields(false, false); $roomtype_id = $allfields_currentpost['bookitall_roomstype']; $roomtype_name = get_the_title($roomtype_id); ``` (I'm jusing the other field values from the current post as well, therefore I'm using `get_fields()` instead of `get_field()`)
[The page link field](https://www.advancedcustomfields.com/resources/page-link/) actually stores the post ID, which gets formatted internally by the `get_field` function on output. The 3rd argument for `get_field` lets you disable that output formatting so you just get the ID back, which you can then use to get title and permalink for that post: ``` $post_id = get_field( 'bookitall_roomstype', false, false ); if( $post_id ): echo get_the_permalink( $post_id ); echo get_the_title( $post_id ); endif; ```
307,310
<p>We recently implemented a stock quote system, where a user can enter a stock symbol and it will return all sorts of financial values.</p> <p>I have a template made up that displays the financial widgets, and when a user enters a ticker symbol it runs some JS with the callback url being my template. In this example, it is something like this.</p> <p><a href="https://www.stocktrades.ca/quote/?qm_symbol=AAPL" rel="nofollow noreferrer">https://www.stocktrades.ca/quote/?qm_symbol=AAPL</a></p> <p>What my issue is, is the title is currently blank. When a user inputs a symbol, the page title in the browser is simply “Quote -” Instead, I want it to be “Quote – XXXX” with XXXX being the stock ticker they entered.</p> <p>What is the easiest way to go about this? I know it’s probably really simple, but I am stumped</p>
[ { "answer_id": 307319, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 1, "selected": false, "text": "<p>You shouldn't need to get all <code>bookitall_roomstype</code> in lines 2-9 of your code. You really only want to pull room types that are assigned to the current <code>bookitall_bookings</code> CPT.</p>\n\n<p>As far as the \"pagelink\" field, this seems like an unsafe way of calling the information. What if a permalink changed someday? It seems like it would be both safer and more efficient to save post IDs instead of permalinks as the <code>bookitall_roomtypes</code> field.</p>\n\n<p>With that in mind, and also to make it clearer <code>bookitall_roomstype</code> CPT name is not the same as <code>bookitall_roomtypes</code> custom field, I would suggest something like this:</p>\n\n<pre><code>// pull an ACF field that has the post ID saved\n$room_type_ids = get_field('bookitall_room_type_ids');\n// create an empty array to hold room type details\n$room_types = array();\nforeach($room_type_ids as $room) {\n // save the permalink\n $room_types[][0] = get_the_permalink($room);\n // save the name\n $room_types[][1] = get_the_title($room);\n}\n// now you can loop through the room types to display as you wish\n// this just links the name to the permalink, but you can add whatever\n// markup you need\nforeach($room_types as $room_details) {\n echo '&lt;a href=\"' . $room_details[0] . '\"&gt;' . $room_details[1] . '&lt;/a&gt;';\n}\n</code></pre>\n\n<p>This way you're only pulling the minimum information required, and not every single roomtype, followed by each roomtype's details, only then to check whether you need those particular details for the current post or not. :)</p>\n" }, { "answer_id": 307321, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://www.advancedcustomfields.com/resources/page-link/\" rel=\"nofollow noreferrer\">The page link field</a> actually stores the post ID, which gets formatted internally by the <code>get_field</code> function on output. The 3rd argument for <code>get_field</code> lets you disable that output formatting so you just get the ID back, which you can then use to get title and permalink for that post:</p>\n\n<pre><code>$post_id = get_field( 'bookitall_roomstype', false, false );\nif( $post_id ):\n echo get_the_permalink( $post_id );\n echo get_the_title( $post_id );\nendif;\n</code></pre>\n" } ]
2018/06/29
[ "https://wordpress.stackexchange.com/questions/307310", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146068/" ]
We recently implemented a stock quote system, where a user can enter a stock symbol and it will return all sorts of financial values. I have a template made up that displays the financial widgets, and when a user enters a ticker symbol it runs some JS with the callback url being my template. In this example, it is something like this. <https://www.stocktrades.ca/quote/?qm_symbol=AAPL> What my issue is, is the title is currently blank. When a user inputs a symbol, the page title in the browser is simply “Quote -” Instead, I want it to be “Quote – XXXX” with XXXX being the stock ticker they entered. What is the easiest way to go about this? I know it’s probably really simple, but I am stumped
[The page link field](https://www.advancedcustomfields.com/resources/page-link/) actually stores the post ID, which gets formatted internally by the `get_field` function on output. The 3rd argument for `get_field` lets you disable that output formatting so you just get the ID back, which you can then use to get title and permalink for that post: ``` $post_id = get_field( 'bookitall_roomstype', false, false ); if( $post_id ): echo get_the_permalink( $post_id ); echo get_the_title( $post_id ); endif; ```
307,345
<p>The following <em>works</em> but isn't up to snuff with <a href="https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards" rel="nofollow noreferrer">PHP Code Sniffer WordPress coding standards</a> </p> <pre><code>&lt;?php esc_html_e( ADDRESS, 'wprig' ); ?&gt; </code></pre> <p>Linter yells at me with:</p> <blockquote> <p>[WordPress.WP.I18n.NonSingularStringLiteralText] The $text arg must be a single string literal, not "ADDRESS". </p> </blockquote> <p>The following, for aforementioned error, also don't work:</p> <pre><code>&lt;?php esc_html_e( (string)ADDRESS, 'wprig' ); ?&gt; &lt;?php esc_html_e( strval(ADDRESS), 'wprig' ); ?&gt; &lt;?php esc_attr_e( ADDRESS, 'wprig' ); ?&gt; </code></pre> <p>I know <a href="https://vip.wordpress.com/2014/06/20/the-importance-of-escaping-all-the-things/" rel="nofollow noreferrer">constants can be exploited</a> so it is needed. Any way to make this work besides <code>//phpcs:ignore</code>, or is this not good practice and I should redo my use of constants?</p>
[ { "answer_id": 307349, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 5, "selected": true, "text": "<p>You cannot use constants or anything other than actual strings with translation functions.</p>\n\n<p>This is because the code that reads your code, and produces the translatable strings does not actually <em>run</em> your code, it is <em>reading</em> your code.</p>\n\n<p>Here is a more detailed post on the topic:</p>\n\n<p><a href=\"http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/\" rel=\"noreferrer\">http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/</a></p>\n\n<p>But the short version is this:</p>\n\n<p>This is wrong:</p>\n\n<pre><code>&lt;?php esc_html_e( ADDRESS, 'wprig' ); ?&gt;\n</code></pre>\n\n<p>Nothing will make that right except this:</p>\n\n<pre><code>&lt;?php esc_html_e( 'Actual String here', 'wprig' ); ?&gt;\n</code></pre>\n" }, { "answer_id": 406395, "author": "ecairol", "author_id": 176470, "author_profile": "https://wordpress.stackexchange.com/users/176470", "pm_score": 0, "selected": false, "text": "<p>I was having a hard time finding the proper solution if it wasn't a constant.</p>\n<p>This works for a variable and the <code>value</code> attribute:</p>\n<pre><code>&lt;input type=&quot;hidden&quot; value=&quot;&lt;?php echo esc_attr( $image_id ); ?&gt;&quot;&gt;\n</code></pre>\n" }, { "answer_id": 408858, "author": "Rishita Raha", "author_id": 224934, "author_profile": "https://wordpress.stackexchange.com/users/224934", "pm_score": 0, "selected": false, "text": "<p>According to the documentation of WordPress,</p>\n<blockquote>\n<p>a variable and should not be part of the translation</p>\n</blockquote>\n<p>Thus, you need to use printf instead of _e (echo). Thus the <code>&lt;?php esc_html_e( ADDRESS, 'wprig' ); ?&gt;</code> will be</p>\n<pre><code>esc_html(\n printf(\n __( '%s', 'wprig' ),\n ADDRESS // it can simply be a normal variable \n )\n\n);\n</code></pre>\n<p><a href=\"https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/#variables\" rel=\"nofollow noreferrer\">Documentation from WordPress</a></p>\n" } ]
2018/06/29
[ "https://wordpress.stackexchange.com/questions/307345", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132362/" ]
The following *works* but isn't up to snuff with [PHP Code Sniffer WordPress coding standards](https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards) ``` <?php esc_html_e( ADDRESS, 'wprig' ); ?> ``` Linter yells at me with: > > [WordPress.WP.I18n.NonSingularStringLiteralText] The $text arg must be a single string literal, not "ADDRESS". > > > The following, for aforementioned error, also don't work: ``` <?php esc_html_e( (string)ADDRESS, 'wprig' ); ?> <?php esc_html_e( strval(ADDRESS), 'wprig' ); ?> <?php esc_attr_e( ADDRESS, 'wprig' ); ?> ``` I know [constants can be exploited](https://vip.wordpress.com/2014/06/20/the-importance-of-escaping-all-the-things/) so it is needed. Any way to make this work besides `//phpcs:ignore`, or is this not good practice and I should redo my use of constants?
You cannot use constants or anything other than actual strings with translation functions. This is because the code that reads your code, and produces the translatable strings does not actually *run* your code, it is *reading* your code. Here is a more detailed post on the topic: <http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/> But the short version is this: This is wrong: ``` <?php esc_html_e( ADDRESS, 'wprig' ); ?> ``` Nothing will make that right except this: ``` <?php esc_html_e( 'Actual String here', 'wprig' ); ?> ```
307,362
<p>You know how all these websites send out links to their new users for them to verify their Email address? I'm trying to set up something like this but after some research I still haven't found a good explanation on how to implement this.</p> <p>I'm open for plugin recommendations, however most of the plugins I found have a ton of other features that I don't really need.</p> <p>Without using a plugin, how would I go about adding this to my code?</p> <p>My approach would be to add a 'Email not verified' attribute to the user meta after signup and send out an email with some kind of verification key to the user. How can I verify if the user actually clicked on that link though?</p> <p>Thanks for any advice</p>
[ { "answer_id": 307367, "author": "Akshat", "author_id": 114978, "author_profile": "https://wordpress.stackexchange.com/users/114978", "pm_score": 5, "selected": true, "text": "<p>You can use <code>user_register</code> hook</p>\n\n<pre><code>add_action( 'user_register', 'my_registration', 10, 2 );\nfunction my_registration( $user_id ) {\n // get user data\n $user_info = get_userdata($user_id);\n // create md5 code to verify later\n $code = md5(time());\n // make it into a code to send it to user via email\n $string = array('id'=&gt;$user_id, 'code'=&gt;$code);\n // create the activation code and activation status\n update_user_meta($user_id, 'account_activated', 0);\n update_user_meta($user_id, 'activation_code', $code);\n // create the url\n $url = get_site_url(). '/my-account/?act=' .base64_encode( serialize($string));\n // basically we will edit here to make this nicer\n $html = 'Please click the following links &lt;br/&gt;&lt;br/&gt; &lt;a href=\"'.$url.'\"&gt;'.$url.'&lt;/a&gt;';\n // send an email out to user\n wp_mail( $user_info-&gt;user_email, __('Email Subject','text-domain') , $html);\n}\n</code></pre>\n\n<p>You can check for <code>$_GET['act']</code> and then activate if that's a valid key by updating the meta value <code>account_activated</code>. You can use <code>wp_authenticate_user</code> hook to verify activation status every time when user tries to login.</p>\n\n<p>Snippet to validate:</p>\n\n<pre><code>add_action( 'init', 'verify_user_code' );\nfunction verify_user_code(){\n if(isset($_GET['act'])){\n $data = unserialize(base64_decode($_GET['act']));\n $code = get_user_meta($data['id'], 'activation_code', true);\n // verify whether the code given is the same as ours\n if($code == $data['code']){\n // update the user meta\n update_user_meta($data['id'], 'is_activated', 1);\n wc_add_notice( __( '&lt;strong&gt;Success:&lt;/strong&gt; Your account has been activated! ', 'text-domain' ) );\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 363860, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Guys I think the above method introduces security vulnerabilities that do not need to be there.</p>\n<p>The primary goal of email verification is that we want people who signup to provide a real email address that they own or at least have access to. We do not want people signing up with lets say a random email address that someone else owns, for instance your email address.</p>\n<p>The above code has vulnerabilities that could enable a hacker to register a random email address someone else owns and then relevantly easily brute force the $user_id value and the $code value on your email verification page.</p>\n<p><strong>1st vulnerability</strong></p>\n<p>You are using $user_id. Now I know this value could be any number of things but typically this is going to be an integer especially if using wordpress which is circa 30% of the websites on the internet and looking at the above php code it is indeed based on wordpress. The hacker is either given their $user_id as part of the signup process or else they guess their $user_id via brute force just going up sequentially starting at the number 1 and continuing 2 , 3, 4, 5, 6 ..... they will guess their $user_id in less than a day perhaps in even in less than an hour if your website does not have that many members.</p>\n<p><strong>2nd vulnerability</strong></p>\n<p>You are creating a $code using the MD5 hashing function and the time of signup. The hacker knows what time they signed up. Let's say the hacker signs-up at 3pm. Now all the hacker has to do is MD5 hash times from 2.55pm to 3.05pm and they will brute force the $code in less than an hour.</p>\n<p><strong>Looking at the above the hacker can just brute force the $user_id and $code in less than a day and verify an email address that they do not own</strong></p>\n<p>tut tut tut</p>\n<p>A better approach would be to generate a $code with the rand() function using uppercase (A-Z) and lower case (a-z), numbers (0-9) and special characters e.g. (!&amp;#). That MD5 hashing function is only using numbers 0-9 and lower case letters a-f and they way ye are using it based on the time of signup is making it incredibly easy to narrow down and brute force attack.</p>\n<p>I have written the below PHP code the generate a random $code with Uppercase Letters/Lowercase Letters/Intergers/Special Characters. Don't make it so easy for hackers guys.</p>\n<pre class=\"lang-php prettyprint-override\"><code>function generateRandomString($stringLength){\n //specify characters to be used in generating random string, do not specify any characters that wordpress does not allow in the creation.\n $characters = &quot;0123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_[]{}!@$%^*().,&gt;=-;|:?&quot;;\n\n //get the total length of specified characters to be used in generating random string\n $charactersLength = strlen($characters);\n\n //declare a string that we will use to create the random string \n $randomString = '';\n\n for ($i = 0; $i &lt; $stringLength; $i++) {\n //generate random characters\n $randomCharacter = $characters[rand(0, $charactersLength - 1)];\n //add the random characters to the random string\n $randomString .= $randomCharacter;\n };\n\n //sanitize_user, just in case \n $sanRandomString = sanitize_user($randomString);\n\n //check that random string contains Uppercase/Lowercase/Intergers/Special Char and that it is the correct length\n if ( (preg_match('([a-zA-Z].*[0-9]|[0-9].*[a-zA-Z].*[_\\W])', $sanRandomString)==1) &amp;&amp; (strlen($sanRandomString)==$stringLength) )\n {\n //return the random string if it meets the complexity criteria \n return $sanRandomString;\n } else {\n // if the random string does not meet minimium criteria call function again \n return call_user_func(&quot;generateRandomString&quot;,($stringLength) );\n }\n}//end of generateRandomString function\n\n//call the function to generate a random string with Uppercase Letters/Lowercase Letters/Intergers/Special Characters \n//into the function we pass the length of string we require, in this exampe it will generate a string 32 characters long\n$code = generateRandomString(32);\n\necho $code;\n</code></pre>\n" } ]
2018/06/30
[ "https://wordpress.stackexchange.com/questions/307362", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145115/" ]
You know how all these websites send out links to their new users for them to verify their Email address? I'm trying to set up something like this but after some research I still haven't found a good explanation on how to implement this. I'm open for plugin recommendations, however most of the plugins I found have a ton of other features that I don't really need. Without using a plugin, how would I go about adding this to my code? My approach would be to add a 'Email not verified' attribute to the user meta after signup and send out an email with some kind of verification key to the user. How can I verify if the user actually clicked on that link though? Thanks for any advice
You can use `user_register` hook ``` add_action( 'user_register', 'my_registration', 10, 2 ); function my_registration( $user_id ) { // get user data $user_info = get_userdata($user_id); // create md5 code to verify later $code = md5(time()); // make it into a code to send it to user via email $string = array('id'=>$user_id, 'code'=>$code); // create the activation code and activation status update_user_meta($user_id, 'account_activated', 0); update_user_meta($user_id, 'activation_code', $code); // create the url $url = get_site_url(). '/my-account/?act=' .base64_encode( serialize($string)); // basically we will edit here to make this nicer $html = 'Please click the following links <br/><br/> <a href="'.$url.'">'.$url.'</a>'; // send an email out to user wp_mail( $user_info->user_email, __('Email Subject','text-domain') , $html); } ``` You can check for `$_GET['act']` and then activate if that's a valid key by updating the meta value `account_activated`. You can use `wp_authenticate_user` hook to verify activation status every time when user tries to login. Snippet to validate: ``` add_action( 'init', 'verify_user_code' ); function verify_user_code(){ if(isset($_GET['act'])){ $data = unserialize(base64_decode($_GET['act'])); $code = get_user_meta($data['id'], 'activation_code', true); // verify whether the code given is the same as ours if($code == $data['code']){ // update the user meta update_user_meta($data['id'], 'is_activated', 1); wc_add_notice( __( '<strong>Success:</strong> Your account has been activated! ', 'text-domain' ) ); } } } ```
307,416
<p>How can I enable shortcodes on a custom post type that doesn't use <code>the_content()</code> or <code>get_the_content()</code>? In the template file it uses</p> <pre><code>&lt;?php echo nl2br( $post-&gt;post_content ); ?&gt; </code></pre> <p>to get the content from the backend like any other post or page would. I have tried using</p> <pre><code>&lt;?php echo do_shortcode(get_post_field('post_content', $postid)); ?&gt; </code></pre> <p>which works but the shortcode itself is still displaying for example:</p> <pre><code>[gallery columns="4" link="file" ids="1,2,3,4"] </code></pre> <p>displays above the gallery photos.</p>
[ { "answer_id": 307446, "author": "Mammaltron", "author_id": 88160, "author_profile": "https://wordpress.stackexchange.com/users/88160", "pm_score": -1, "selected": false, "text": "<p>Use <code>apply_filters()</code> to let WordPress process the shortcodes in your content. </p>\n\n<p><code>&lt;?php echo apply_filters('the_content', $post-&gt;post_content); ?&gt;</code> </p>\n" }, { "answer_id": 307525, "author": "Peter", "author_id": 86094, "author_profile": "https://wordpress.stackexchange.com/users/86094", "pm_score": -1, "selected": true, "text": "<p>For my particular situation the answer was to replace <code>&lt;?php echo nl2br( $post-&gt;post_content ); ?&gt;</code> with <code>&lt;?php echo $content; ?&gt;</code> which allowed all shortcodes to work as expected.</p>\n" }, { "answer_id": 307533, "author": "Muhammad Tahseen ur Rehman", "author_id": 146048, "author_profile": "https://wordpress.stackexchange.com/users/146048", "pm_score": 1, "selected": false, "text": "<p><strong>Shortcodes</strong> really should run in <strong>custom post types</strong>. Essentially a custom post type is a post. So it sounds like there is a problem filtering shortcodes somewhere.</p>\n\n<p>What is likely happening is that you are using <strong>get_the_content() rather than the_content()</strong> which doesn't filter. Where and how are you displaying the content for the custom post type?</p>\n\n<p>If this is the case, please use get_the_content() function in this way to apply appropriate filtering.</p>\n\n<pre><code>&lt;?php apply_filters('the_content',get_the_content( $more_link_text, \n $stripteaser, $more_file )) ?&gt;\n</code></pre>\n\n<p><strong>Visit this link for more detail about your Problem</strong></p>\n\n<p><a href=\"https://premium.wpmudev.org/forums/topic/enable-shortcodes-on-custom-post-types\" rel=\"nofollow noreferrer\">wpmudev</a></p>\n" }, { "answer_id": 360117, "author": "CJWEB", "author_id": 130150, "author_profile": "https://wordpress.stackexchange.com/users/130150", "pm_score": 2, "selected": false, "text": "<p>I had similar problem because I was rendering content like this:</p>\n\n<pre><code>echo get_the_content();\n</code></pre>\n\n<p>Instead of:</p>\n\n<pre><code>the_content();\n</code></pre>\n\n<p>The 2nd function must include the shortcode filter.</p>\n" } ]
2018/07/01
[ "https://wordpress.stackexchange.com/questions/307416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86094/" ]
How can I enable shortcodes on a custom post type that doesn't use `the_content()` or `get_the_content()`? In the template file it uses ``` <?php echo nl2br( $post->post_content ); ?> ``` to get the content from the backend like any other post or page would. I have tried using ``` <?php echo do_shortcode(get_post_field('post_content', $postid)); ?> ``` which works but the shortcode itself is still displaying for example: ``` [gallery columns="4" link="file" ids="1,2,3,4"] ``` displays above the gallery photos.
For my particular situation the answer was to replace `<?php echo nl2br( $post->post_content ); ?>` with `<?php echo $content; ?>` which allowed all shortcodes to work as expected.
307,484
<p>I am trying to build a plugin, in the plugin I want the admin to be able to send data to database and let the user view the data in the front end, but I am still having problems with sending data to database</p> <p>I am trying to validate this code to keep it safe from injection This is my code </p> <pre><code>&lt;?php if (!empty($_POST)) { global $wpdb; $table = wp_save; $data = array( 'name' =&gt; $_POST['yourname'], 'chord' =&gt; $_POST['number'] ); $format = array( '%s', '%s' ); $success=$wpdb-&gt;insert( $table, $data, $format ); if($success){ echo 'data has been save' ; } } else { ?&gt; &lt;form method="post"&gt; &lt;input type="text" name="yourname"&gt; &lt;textarea name="number"&gt;&lt;/textarea&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;?php } ?&gt; </code></pre>
[ { "answer_id": 307487, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<pre><code>$table = wp_save;\n</code></pre>\n\n<p>This is setting <code>$table</code> to a PHP <a href=\"http://php.net/manual/en/language.constants.php\" rel=\"nofollow noreferrer\">constant</a> <code>wp_save</code>. If I had to guess I'd say you don't actually have a constant by that name, and just meant to set the table name to <code>wp_save</code>. To do that you need to put the table name between quotes, so that it's a <a href=\"http://php.net/manual/en/language.types.string.php\" rel=\"nofollow noreferrer\">String</a>:</p>\n\n<pre><code>$table = 'wp_save';\n</code></pre>\n\n<p>However, given that WordPress users can change the <code>wp_</code> prefix in the database to whatever they like, you should use <code>$wpdb-&gt;prefix</code> to use the correct prefix as set by the user:</p>\n\n<pre><code>$table = $wpdb-&gt;prefix . 'save';\n</code></pre>\n\n<p>Before diving in too deep on building a plugin though, I'd suggest brushing up on the basics of PHP so that you know the difference between the different types of values, like Strings and Constants. Ultimately everything you're going to be doing in the back-end is PHP, and the fundamentals don't differ just because it's WordPress.</p>\n" }, { "answer_id": 307490, "author": "Кристиян Кацаров", "author_id": 140118, "author_profile": "https://wordpress.stackexchange.com/users/140118", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php\nif (!empty($_POST)) {\n global $wpdb;\n $table = $wpdb-&gt;prefix . 'wp_save'; //wp_save or save only?\n $data = array(\n 'name' =&gt; $_POST['yourname'],\n 'chord' =&gt; $_POST['number']\n );\n $format = array(\n '%s',\n '%s'\n );\n $success = $wpdb-&gt;insert($table, $data, $format);\n if ($success) {\n echo 'data has been save';\n }\n} else {\n?&gt;\n &lt;form method=\"post\"&gt;\n &lt;input type=\"text\" name=\"yourname\"&gt;\n &lt;textarea name=\"number\"&gt;&lt;/textarea&gt;\n &lt;input type=\"submit\"&gt;\n &lt;/form&gt;\n &lt;?php\n}\n?&gt;\n</code></pre>\n\n<p>Hope this helps</p>\n" } ]
2018/07/02
[ "https://wordpress.stackexchange.com/questions/307484", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146214/" ]
I am trying to build a plugin, in the plugin I want the admin to be able to send data to database and let the user view the data in the front end, but I am still having problems with sending data to database I am trying to validate this code to keep it safe from injection This is my code ``` <?php if (!empty($_POST)) { global $wpdb; $table = wp_save; $data = array( 'name' => $_POST['yourname'], 'chord' => $_POST['number'] ); $format = array( '%s', '%s' ); $success=$wpdb->insert( $table, $data, $format ); if($success){ echo 'data has been save' ; } } else { ?> <form method="post"> <input type="text" name="yourname"> <textarea name="number"></textarea> <input type="submit"> </form> <?php } ?> ```
``` $table = wp_save; ``` This is setting `$table` to a PHP [constant](http://php.net/manual/en/language.constants.php) `wp_save`. If I had to guess I'd say you don't actually have a constant by that name, and just meant to set the table name to `wp_save`. To do that you need to put the table name between quotes, so that it's a [String](http://php.net/manual/en/language.types.string.php): ``` $table = 'wp_save'; ``` However, given that WordPress users can change the `wp_` prefix in the database to whatever they like, you should use `$wpdb->prefix` to use the correct prefix as set by the user: ``` $table = $wpdb->prefix . 'save'; ``` Before diving in too deep on building a plugin though, I'd suggest brushing up on the basics of PHP so that you know the difference between the different types of values, like Strings and Constants. Ultimately everything you're going to be doing in the back-end is PHP, and the fundamentals don't differ just because it's WordPress.
307,521
<p>I have registered a widget in order to allow users to filter posts by category or write something in the search box, the problem is that my 'blog' page is 'home.php' because it is a single-page-site (in index.php I am loading all the content), when I pick up a category or click on search button it redirects to index.php, instead of remaining in home.php.</p> <p>How can I change that behaviour?</p>
[ { "answer_id": 307487, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<pre><code>$table = wp_save;\n</code></pre>\n\n<p>This is setting <code>$table</code> to a PHP <a href=\"http://php.net/manual/en/language.constants.php\" rel=\"nofollow noreferrer\">constant</a> <code>wp_save</code>. If I had to guess I'd say you don't actually have a constant by that name, and just meant to set the table name to <code>wp_save</code>. To do that you need to put the table name between quotes, so that it's a <a href=\"http://php.net/manual/en/language.types.string.php\" rel=\"nofollow noreferrer\">String</a>:</p>\n\n<pre><code>$table = 'wp_save';\n</code></pre>\n\n<p>However, given that WordPress users can change the <code>wp_</code> prefix in the database to whatever they like, you should use <code>$wpdb-&gt;prefix</code> to use the correct prefix as set by the user:</p>\n\n<pre><code>$table = $wpdb-&gt;prefix . 'save';\n</code></pre>\n\n<p>Before diving in too deep on building a plugin though, I'd suggest brushing up on the basics of PHP so that you know the difference between the different types of values, like Strings and Constants. Ultimately everything you're going to be doing in the back-end is PHP, and the fundamentals don't differ just because it's WordPress.</p>\n" }, { "answer_id": 307490, "author": "Кристиян Кацаров", "author_id": 140118, "author_profile": "https://wordpress.stackexchange.com/users/140118", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php\nif (!empty($_POST)) {\n global $wpdb;\n $table = $wpdb-&gt;prefix . 'wp_save'; //wp_save or save only?\n $data = array(\n 'name' =&gt; $_POST['yourname'],\n 'chord' =&gt; $_POST['number']\n );\n $format = array(\n '%s',\n '%s'\n );\n $success = $wpdb-&gt;insert($table, $data, $format);\n if ($success) {\n echo 'data has been save';\n }\n} else {\n?&gt;\n &lt;form method=\"post\"&gt;\n &lt;input type=\"text\" name=\"yourname\"&gt;\n &lt;textarea name=\"number\"&gt;&lt;/textarea&gt;\n &lt;input type=\"submit\"&gt;\n &lt;/form&gt;\n &lt;?php\n}\n?&gt;\n</code></pre>\n\n<p>Hope this helps</p>\n" } ]
2018/07/02
[ "https://wordpress.stackexchange.com/questions/307521", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137882/" ]
I have registered a widget in order to allow users to filter posts by category or write something in the search box, the problem is that my 'blog' page is 'home.php' because it is a single-page-site (in index.php I am loading all the content), when I pick up a category or click on search button it redirects to index.php, instead of remaining in home.php. How can I change that behaviour?
``` $table = wp_save; ``` This is setting `$table` to a PHP [constant](http://php.net/manual/en/language.constants.php) `wp_save`. If I had to guess I'd say you don't actually have a constant by that name, and just meant to set the table name to `wp_save`. To do that you need to put the table name between quotes, so that it's a [String](http://php.net/manual/en/language.types.string.php): ``` $table = 'wp_save'; ``` However, given that WordPress users can change the `wp_` prefix in the database to whatever they like, you should use `$wpdb->prefix` to use the correct prefix as set by the user: ``` $table = $wpdb->prefix . 'save'; ``` Before diving in too deep on building a plugin though, I'd suggest brushing up on the basics of PHP so that you know the difference between the different types of values, like Strings and Constants. Ultimately everything you're going to be doing in the back-end is PHP, and the fundamentals don't differ just because it's WordPress.
307,539
<p>Is is safe to edit language files from wp-content/languages/plugins/woocommerce-ro_RO.mo(.po) ? I'm asking this because I don't want them to be overriden on plugin update. Sorry if dumb question.</p>
[ { "answer_id": 307487, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<pre><code>$table = wp_save;\n</code></pre>\n\n<p>This is setting <code>$table</code> to a PHP <a href=\"http://php.net/manual/en/language.constants.php\" rel=\"nofollow noreferrer\">constant</a> <code>wp_save</code>. If I had to guess I'd say you don't actually have a constant by that name, and just meant to set the table name to <code>wp_save</code>. To do that you need to put the table name between quotes, so that it's a <a href=\"http://php.net/manual/en/language.types.string.php\" rel=\"nofollow noreferrer\">String</a>:</p>\n\n<pre><code>$table = 'wp_save';\n</code></pre>\n\n<p>However, given that WordPress users can change the <code>wp_</code> prefix in the database to whatever they like, you should use <code>$wpdb-&gt;prefix</code> to use the correct prefix as set by the user:</p>\n\n<pre><code>$table = $wpdb-&gt;prefix . 'save';\n</code></pre>\n\n<p>Before diving in too deep on building a plugin though, I'd suggest brushing up on the basics of PHP so that you know the difference between the different types of values, like Strings and Constants. Ultimately everything you're going to be doing in the back-end is PHP, and the fundamentals don't differ just because it's WordPress.</p>\n" }, { "answer_id": 307490, "author": "Кристиян Кацаров", "author_id": 140118, "author_profile": "https://wordpress.stackexchange.com/users/140118", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php\nif (!empty($_POST)) {\n global $wpdb;\n $table = $wpdb-&gt;prefix . 'wp_save'; //wp_save or save only?\n $data = array(\n 'name' =&gt; $_POST['yourname'],\n 'chord' =&gt; $_POST['number']\n );\n $format = array(\n '%s',\n '%s'\n );\n $success = $wpdb-&gt;insert($table, $data, $format);\n if ($success) {\n echo 'data has been save';\n }\n} else {\n?&gt;\n &lt;form method=\"post\"&gt;\n &lt;input type=\"text\" name=\"yourname\"&gt;\n &lt;textarea name=\"number\"&gt;&lt;/textarea&gt;\n &lt;input type=\"submit\"&gt;\n &lt;/form&gt;\n &lt;?php\n}\n?&gt;\n</code></pre>\n\n<p>Hope this helps</p>\n" } ]
2018/07/02
[ "https://wordpress.stackexchange.com/questions/307539", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115614/" ]
Is is safe to edit language files from wp-content/languages/plugins/woocommerce-ro\_RO.mo(.po) ? I'm asking this because I don't want them to be overriden on plugin update. Sorry if dumb question.
``` $table = wp_save; ``` This is setting `$table` to a PHP [constant](http://php.net/manual/en/language.constants.php) `wp_save`. If I had to guess I'd say you don't actually have a constant by that name, and just meant to set the table name to `wp_save`. To do that you need to put the table name between quotes, so that it's a [String](http://php.net/manual/en/language.types.string.php): ``` $table = 'wp_save'; ``` However, given that WordPress users can change the `wp_` prefix in the database to whatever they like, you should use `$wpdb->prefix` to use the correct prefix as set by the user: ``` $table = $wpdb->prefix . 'save'; ``` Before diving in too deep on building a plugin though, I'd suggest brushing up on the basics of PHP so that you know the difference between the different types of values, like Strings and Constants. Ultimately everything you're going to be doing in the back-end is PHP, and the fundamentals don't differ just because it's WordPress.
307,542
<p>It can be sometimes bothersome when, in the Discussion (Comments) dashboard, where the admin can see a list of comments, moving the mouse over a link will cause a preview of that link. Sometimes the preview gets in the way of looking at the comment. This is especially true with spam comments.</p> <p>And I am also concerned that a link to a page/site that had some 'bad' code would cause a compromise of my site. </p> <p>Is there a way to disable this 'feature'? Not sure where it is coming from.</p>
[ { "answer_id": 338830, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>This is still happening in WP5.2.1. You can verify it by looking at your spam messages (via the Admin, Comments screen) and hovering over a link. When you do wo, a box will pop up with the content of that link.</p>\n<p>Using the Inspector, I found the HREF code on the link in the spam comment is similar to this (I obfuscated the domain but left the rest) (and not sure how to wrap the code block below)</p>\n<pre><code> &lt;a href=&quot;http://Www.example.com/__media__/js/netsoltrademark.php?d=malyj.info%2F__media__%2Fjs%example.php%3Fd%3D3win8.city%2Findex.php%2Fdownload%2F29-ntc33&quot;\n target=&quot;_blank&quot; rel=&quot;external nofollow&quot;&gt;\nhttp://Www.example.com/__media__/js/netsoltrademark.php?d=malyj.info%2F__media__%2Fjs%2Fexample.php%3Fd%3D3win8.city%2Findex.php%2Fdownload%2F29-ntc33&lt;/a&gt;\n</code></pre>\n<p>And the CSS for the <code>:after</code> element, which comes from Akismet (which is why you only see it on Akismet-caught spam, using the latest version of Akismet), in <code>akismet.css</code> line 42:</p>\n<pre><code>table.comments td.comment p a::after {\n\n content: attr(href);\n color: #aaa;\n display: inline-block;\n padding: 0 1ex;\n\n}\n</code></pre>\n<p>So the <code>content</code> element of the CSS is displaying the content in the link. And note that the example link above is a php file. Which is concerning....since clicking on the link appears to call some 'download' process. (I have not looked into the code of the link, nor clicked on it.)</p>\n<p>....but not as concerning as if the example block was some JS. And more concerning if the JS is trying to do some exploit on your computer - which I don't think would require a click, just a hover to execute. <strong>YIKES!</strong></p>\n<p>So, the cause seems to be the CSS that Akismet is using is displaying the links' content.</p>\n<p>And that doesn't look very safe. Akismet <strong>should not</strong> be using the <code>content</code> element in the :after CSS block.</p>\n<p>** <strong>ADDED 4 Jan 2020</strong> **</p>\n<p>The answer above (marked as correct) is the solution to the problem. But it should not be necessary to 'filter' that action. That preview should be off by default in the Akismet code. Having that feature on by default is a security risk, IMHO.</p>\n<p>(Marked correct answer <a href=\"https://wordpress.stackexchange.com/a/380836/29416\">https://wordpress.stackexchange.com/a/380836/29416</a> )</p>\n" }, { "answer_id": 339945, "author": "Remi Loisel", "author_id": 169663, "author_profile": "https://wordpress.stackexchange.com/users/169663", "pm_score": 2, "selected": false, "text": "<p>This annoying thing is introduced by Akismet.</p>\n\n<p>in <code>wp_content/plugins/akismet/_inc/akismet.js</code> line 89 (akismet 4.1.2)\ninsert a \"return;\" just after </p>\n\n<pre><code>86: // Show a preview image of the hovered URL. Applies to author URLs and URLs inside the comments.\n87: $( '#the-comment-list' ).on( 'mouseover', mshotEnabledLinkSelector, function () {\n88: clearTimeout( mshotRemovalTimer ); \n89: return;\n</code></pre>\n" }, { "answer_id": 380836, "author": "Jani Uusitalo", "author_id": 68562, "author_profile": "https://wordpress.stackexchange.com/users/68562", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://wordpress.org/support/topic/how-to-disable-mshots-service/#post-12939728\" rel=\"nofollow noreferrer\">Since version 4.1.6</a>, Akismet has a filter which <a href=\"https://wordpress.org/support/topic/how-to-disable-mshots-service/#post-12944077\" rel=\"nofollow noreferrer\">allows you to disable these &quot;mShots&quot;</a> (the site preview popups):</p>\n<pre><code>&lt;?php\nfunction disable_akismet_mshots( $value ) {\n return false;\n}\nadd_filter( 'akismet_enable_mshots', 'disable_akismet_mshots' );\n</code></pre>\n" } ]
2018/07/02
[ "https://wordpress.stackexchange.com/questions/307542", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/29416/" ]
It can be sometimes bothersome when, in the Discussion (Comments) dashboard, where the admin can see a list of comments, moving the mouse over a link will cause a preview of that link. Sometimes the preview gets in the way of looking at the comment. This is especially true with spam comments. And I am also concerned that a link to a page/site that had some 'bad' code would cause a compromise of my site. Is there a way to disable this 'feature'? Not sure where it is coming from.
[Since version 4.1.6](https://wordpress.org/support/topic/how-to-disable-mshots-service/#post-12939728), Akismet has a filter which [allows you to disable these "mShots"](https://wordpress.org/support/topic/how-to-disable-mshots-service/#post-12944077) (the site preview popups): ``` <?php function disable_akismet_mshots( $value ) { return false; } add_filter( 'akismet_enable_mshots', 'disable_akismet_mshots' ); ```
307,580
<p>I'm working on a Plugin for the WordPress Customizer and need to call a function when the previewer has loaded. Is there an event or an other method that tells me the preview is loaded?</p> <p>If have tried:</p> <pre><code>jQuery(window).load (function() { // Customizer loaded... wp.customize.previewer.bind( 'refresh', function() { // doesn't seem to work ?! alert ('Previewer has loaded'); } } </code></pre> <p>I've also tried <code>wp.customizer.bind('refresh', function (){</code></p> <p>Is there no event that gets fired when the preview is loaded? The refresh event gets fired when the previewer gets refreshed.</p> <p>Any ideas?</p>
[ { "answer_id": 307901, "author": "Milli", "author_id": 146281, "author_profile": "https://wordpress.stackexchange.com/users/146281", "pm_score": 0, "selected": false, "text": "<p>I haven't found an Customizer API event for when the preview has loaded. Here is a solution with the on load event on the iframe:</p>\n\n<pre><code>// Assures that the code gets runned once per load.\nvar code_has_run = false;\n\nfunction preview_loader(){\n // When the customizer has loaded the iframe does not\n // exist yet. This checks if the iframe exists.\n\n if (jQuery('#customize-preview iframe').length &gt; 0){ \n\n // When iframe/preview has loaded.\n jQuery('#customize-preview iframe').on('load', function (){\n\n // Wait a little until old frame is removed.\n setTimeout(function (){\n if (code_has_run == false){\n // Code to be run when preview has loaded and is ready.\n alert('Preview loaded');\n }\n code_has_run = true;\n\n // Wait until multiple load events are finished. \n setTimeout(function(){\n code_has_run = false;\n }, 1000);\n }, 1000); \n });\n }\n}\n\njQuery(window).load (function() { // Customizer loaded...\n\n //Call preview_loader if the preview loads under 500ms.\n preview_loader();\n\n setInterval(preview_loader, 500); \n}\n</code></pre>\n" }, { "answer_id": 308219, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 3, "selected": true, "text": "<p>Yes, this is the way to detect when the preview has loaded:</p>\n\n<pre><code>wp.customize.bind( 'ready', function() {\n wp.customize.previewer.bind( 'ready', function( message ) {\n console.info( 'Preview is loaded' );\n } );\n} );\n</code></pre>\n\n<p>This JS code should be enqueued at the <code>customize_controls_enqueue_scripts</code> action with <code>customize-controls</code> script as its dependency.</p>\n" } ]
2018/07/03
[ "https://wordpress.stackexchange.com/questions/307580", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146281/" ]
I'm working on a Plugin for the WordPress Customizer and need to call a function when the previewer has loaded. Is there an event or an other method that tells me the preview is loaded? If have tried: ``` jQuery(window).load (function() { // Customizer loaded... wp.customize.previewer.bind( 'refresh', function() { // doesn't seem to work ?! alert ('Previewer has loaded'); } } ``` I've also tried `wp.customizer.bind('refresh', function (){` Is there no event that gets fired when the preview is loaded? The refresh event gets fired when the previewer gets refreshed. Any ideas?
Yes, this is the way to detect when the preview has loaded: ``` wp.customize.bind( 'ready', function() { wp.customize.previewer.bind( 'ready', function( message ) { console.info( 'Preview is loaded' ); } ); } ); ``` This JS code should be enqueued at the `customize_controls_enqueue_scripts` action with `customize-controls` script as its dependency.
307,591
<p>I want to use a fallback image if no featured image is set. I'm using the following code, but the image is not shown...</p> <pre><code>&lt;?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?&gt; &lt;?php the_post_thumbnail( array(334, 259) ); // Declare pixel size you need inside the array ?&gt; &lt;?php else : // No thumbnail? Showing default is better UX than no image. ?&gt; &lt;img src="/wp/wp-content/themes/klicknet-theme/images/testbild.png" alt="testbild" width="334" height="259" title="Bild: &lt;?php the_title(); ?&gt;"&gt; &lt;?php endif; ?&gt; </code></pre> <p>Any ideas why?</p>
[ { "answer_id": 307621, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>Your code looks OK and it should work just fine. But there are some things you can (and you should) fix.</p>\n\n<h2>1. You don't use absolute URL for your fallback image</h2>\n\n<p>You pass <code>/wp/wp-content/themes/klicknet-theme/images/testbild.png</code> as src of your image. It would be much better and more secure if you'd use WP functions in there. For example like so:</p>\n\n<pre><code>&lt;img src=\"&lt;?php bloginfo('template_url'); ?&gt;/images/testbild.png\"&gt;\n</code></pre>\n\n<h2>2. You don't escape the title properly</h2>\n\n<p>In your fallback image you use <code>the_title()</code> in title attribute. But you don't escape it as an attribute. If the title contains <code>\"</code> character, it will break your HTML. Another problem is that the title can contain HTML tags, and they will be printed in your attribute.</p>\n\n<p>If you want to use title as attribute, you should use <a href=\"https://codex.wordpress.org/Function_Reference/the_title_attribute\" rel=\"nofollow noreferrer\"><code>the_title_attribute</code></a> function instead. So the fixed version of that line can look something like this:</p>\n\n<pre><code>&lt;img src=\"&lt;?php bloginfo('template_url'); ?&gt;/images/testbild.png\" alt=\"testbild\" width=\"334\" height=\"259\" title=\"&lt;?php the_title_attribute( array( 'before' =&gt; 'Bild: ', 'after' =&gt; '' ) ); ?&gt;\"&gt; \n</code></pre>\n" }, { "answer_id": 383049, "author": "jave.web", "author_id": 45050, "author_profile": "https://wordpress.stackexchange.com/users/45050", "pm_score": 0, "selected": false, "text": "<p>You could add a filter to provide custom <code>&lt;img&gt;</code> html when there's a thumbnail missing.</p>\n<p><strong>Note</strong>, that although you <strong>don't <em>have to</em> anymore</strong> this still allows you to use <code>has_post_thumbnail()</code> if necessary, because <code>has_post_thumbnail()</code> is based on <code>get_post_thumbnail_id()</code>, meaning it checks if there really was any image set to that post.</p>\n<h2><code>functions.php</code></h2>\n<pre><code>// fallback thumbnail\n// note, that this still allows you to check has_post_thumbnail() !\n// (since it correctly checks if ID is set, not the actual output :))\nadd_filter('post_thumbnail_html', function ($html) {\n if (! empty($html)) return $html; // FILTER ! MUST RETURN!\n return '&lt;img src=&quot;' . get_stylesheet_directory_uri() . '/images/fallback.png' . '&quot;&gt;';\n}, 999, 1);\n</code></pre>\n<p>Just to be clear, this code assumes you have an <code>images</code> directory in your theme with a <code>fallback.png</code> insside it :) !\n<br>If you are expecting child themes, but the fallback image should come from your parent theme, then replace <a href=\"https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_stylesheet_directory_uri()</code></a> with <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\"><code>get_template_directory_uri()</code></a></p>\n<h2>Any template code:</h2>\n<pre><code>&lt;?php the_post_thumbnail( ... ); ?&gt;\n</code></pre>\n" } ]
2018/07/03
[ "https://wordpress.stackexchange.com/questions/307591", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82174/" ]
I want to use a fallback image if no featured image is set. I'm using the following code, but the image is not shown... ``` <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?> <?php the_post_thumbnail( array(334, 259) ); // Declare pixel size you need inside the array ?> <?php else : // No thumbnail? Showing default is better UX than no image. ?> <img src="/wp/wp-content/themes/klicknet-theme/images/testbild.png" alt="testbild" width="334" height="259" title="Bild: <?php the_title(); ?>"> <?php endif; ?> ``` Any ideas why?
Your code looks OK and it should work just fine. But there are some things you can (and you should) fix. 1. You don't use absolute URL for your fallback image ----------------------------------------------------- You pass `/wp/wp-content/themes/klicknet-theme/images/testbild.png` as src of your image. It would be much better and more secure if you'd use WP functions in there. For example like so: ``` <img src="<?php bloginfo('template_url'); ?>/images/testbild.png"> ``` 2. You don't escape the title properly -------------------------------------- In your fallback image you use `the_title()` in title attribute. But you don't escape it as an attribute. If the title contains `"` character, it will break your HTML. Another problem is that the title can contain HTML tags, and they will be printed in your attribute. If you want to use title as attribute, you should use [`the_title_attribute`](https://codex.wordpress.org/Function_Reference/the_title_attribute) function instead. So the fixed version of that line can look something like this: ``` <img src="<?php bloginfo('template_url'); ?>/images/testbild.png" alt="testbild" width="334" height="259" title="<?php the_title_attribute( array( 'before' => 'Bild: ', 'after' => '' ) ); ?>"> ```
307,636
<p>When i try to install a website that i got as an duplicator archive i get the following error at the very last step of the installation:</p> <p><a href="https://i.stack.imgur.com/oIbB7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oIbB7.jpg" alt="enter image description here"></a> I am using the latest version of xampp on my local machine which has 16GB of DDR4. These are the relevant values in my PHP.INI</p> <pre><code>memory_limit=1024M max_execution_time=300 post_max_size=32M </code></pre>
[ { "answer_id": 307605, "author": "WebElaine", "author_id": 102815, "author_profile": "https://wordpress.stackexchange.com/users/102815", "pm_score": 2, "selected": false, "text": "<p>You can't add additional \"folders\" in the post editing screen. You would need to change your permalink structure, so that Posts include the Category in the URL. In Settings > Permalinks, choose \"Custom Structure\" and paste</p>\n\n<p><code>/%category%/%postname%/</code></p>\n\n<p>Keep in mind this will change all your Post URLs, so you'll need to add redirects. Also keep in mind small tweaks to permalinks like this don't often give you a big SEO boost so depending on how many posts you would need to redirect, it may be worth investing more effort into optimizing the on-page content rather than changing permalinks.</p>\n" }, { "answer_id": 307654, "author": "GDY", "author_id": 52227, "author_profile": "https://wordpress.stackexchange.com/users/52227", "pm_score": 0, "selected": false, "text": "<p>I've stumbled across this problem yesterday and used <a href=\"https://de.wordpress.org/plugins/custom-permalinks/\" rel=\"nofollow noreferrer\">this plugin</a> to great effect (Wich is not related to me in any way).</p>\n\n<p>This allows you to create completely custom permalinks for posts and categories.</p>\n" } ]
2018/07/04
[ "https://wordpress.stackexchange.com/questions/307636", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122013/" ]
When i try to install a website that i got as an duplicator archive i get the following error at the very last step of the installation: [![enter image description here](https://i.stack.imgur.com/oIbB7.jpg)](https://i.stack.imgur.com/oIbB7.jpg) I am using the latest version of xampp on my local machine which has 16GB of DDR4. These are the relevant values in my PHP.INI ``` memory_limit=1024M max_execution_time=300 post_max_size=32M ```
You can't add additional "folders" in the post editing screen. You would need to change your permalink structure, so that Posts include the Category in the URL. In Settings > Permalinks, choose "Custom Structure" and paste `/%category%/%postname%/` Keep in mind this will change all your Post URLs, so you'll need to add redirects. Also keep in mind small tweaks to permalinks like this don't often give you a big SEO boost so depending on how many posts you would need to redirect, it may be worth investing more effort into optimizing the on-page content rather than changing permalinks.
307,640
<p>Created my first custom theme from scratch and I'm trying to do a listing of all posts with the same tag.</p> <p>In <code>tag.php</code> I display all posts with that specific tag via a <code>WP_Query</code> and I'm trying to implement the pagination for that listing (using <code>paginate_links()</code>). Page links seem to be outputted correctly. Also the first page looks good.</p> <p>What I don't understand is that when I go on to the next tag page (or to any of the page links outputted from my <code>tag.php</code> template e.g. <code>http://127.0.0.1/wp_site/tag/test_tag/page/2/</code>) the content from <code>index.php</code> is being displayed.</p> <p>What am I actually missing for displaying the subsequent tag pages correctly?</p> <h2><code>tag.php</code> template CODE:</h2> <pre><code>&lt;?php get_header(); ?&gt; &lt;div class=&quot;&quot;&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 if (have_posts()) : ?&gt; &lt;article id=&quot;post-&lt;?php the_ID(); ?&gt;&quot; &lt;?php post_class(); ?&gt;&gt; &lt;header class=&quot;entry-header&quot;&gt; &lt;h1 class=&quot;entry-title&quot;&gt;Other entries related to &amp;#39;&lt;?php single_tag_title(); ?&gt;&amp;#39;&lt;/h1&gt; &lt;/header&gt;&lt;!-- .entry-header --&gt; &lt;div class=&quot;entry-content&quot;&gt;&lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;/article&gt;&lt;!-- #post-## --&gt; &lt;div&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;?php $tagId = get_queried_object()-&gt;term_id; $postType = get_post_type(); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php $htmlOutput = ''; /* the 'terms' ID is the testimonial category parent id */ $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $args = [ 'post_type' =&gt; 'testimonials-widget', 'tag_id' =&gt; $tagId, 'posts_per_page' =&gt; 3, 'paged' =&gt; $paged, 'tax_query' =&gt; [ [ 'taxonomy' =&gt; 'category', 'field' =&gt; 'term_id', 'terms' =&gt; '8', ] ], ]; $post_query = new WP_Query($args); $contentHtml = ''; if($post_query-&gt;have_posts() ) { $posts = $post_query-&gt;posts; foreach($posts as $post) { // generate html output } } wp_reset_postdata(); echo $contentHtml; ?&gt; &lt;/div&gt; &lt;div class=&quot;mainContentWrapperCls&quot;&gt; &lt;?php echo paginate_links( array( 'base' =&gt; str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ), 'total' =&gt; $post_query-&gt;max_num_pages, 'current' =&gt; max( 1, get_query_var( 'paged' ) ), 'format' =&gt; '?paged=%#%', 'show_all' =&gt; false, 'type' =&gt; 'plain', 'end_size' =&gt; 2, 'mid_size' =&gt; 1, 'prev_next' =&gt; true, 'prev_text' =&gt; sprintf( '&lt;i&gt;&lt;/i&gt; %1$s', __( '&amp;lt;&amp;lt; Previous page', 'text-domain' ) ), 'next_text' =&gt; sprintf( '%1$s &lt;i&gt;&lt;/i&gt;', __( 'Next page &amp;gt;&amp;gt;', 'text-domain' ) ), 'add_args' =&gt; false, 'add_fragment' =&gt; '', ) ); ?&gt; &lt;/div&gt; &lt;?php else : ?&gt; &lt;h1&gt;No posts were found.&lt;/h1&gt; &lt;?php endif; ?&gt; &lt;/main&gt;&lt;!-- #main --&gt; &lt;/div&gt;&lt;!-- #primary --&gt; &lt;/div&gt;&lt;!-- .wrap --&gt; &lt;?php get_footer(); ?&gt; </code></pre> <blockquote> <p><em><strong>Note:</strong></em> I created a new query with <code>WP_Query</code> in <code>tag.php</code>. The reason why I did this is because I didn't know how to generate the type of pagination I needed (<code>&lt;Prev 1 2 3 Next&gt;</code> style) via <code>paginate_links()</code>, with the main query.</p> </blockquote> <h2>Theme <code>functions.php</code> CODE:</h2> <pre><code>&lt;?php function myCustomThemeScriptEnqueue() { // Theme stylesheet, js wp_enqueue_style('myCustomTheme-style', get_stylesheet_uri(), array(), '1.0.0', 'all'); } function myCustomThemeThemeSetup() { add_theme_support('menus'); add_post_type_support( 'page', 'excerpt' ); } function nllTagFilter($query) { if ($query-&gt;is_main_query()) { if ($query-&gt;is_tag) { $post_types = get_post_types(); $query-&gt;set('post_type', $post_types); } } } add_action('pre_get_posts','nllTagFilter'); add_action('wp_enqueue_scripts', 'myCustomThemeScriptEnqueue'); add_action('init', 'myCustomThemeThemeSetup'); add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 150, 150 ); ?&gt; </code></pre> <p>This is my theme's file-structure so far:</p> <p><a href="https://i.stack.imgur.com/PzHKj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PzHKj.png" alt="custom theme file structure" /></a></p>
[ { "answer_id": 307663, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 2, "selected": true, "text": "<h2>Overall CODE issues:</h2>\n\n<p>Your CODE is so wrong in so many ways that I shouldn't even attempt to address them here. I suggest you study <a href=\"https://developer.wordpress.org/themes/\" rel=\"nofollow noreferrer\">Official WordPress Theme Handbook</a> properly before doing these sort of customizations.</p>\n\n<p>For the sake of the context, I'm ignoring other issues within your CODE and touching only the issues below:</p>\n\n<h2>1. Why <code>index.php</code> template is being loaded?</h2>\n\n<p>First of all, you are getting wrong pagination from your erroneous CODE (check the explanation below). So apart from the first tag page, all the other tag pages are nonexistent (i.e. you need to add more posts to the tag to get more tag pages).</p>\n\n<p>Secondly, According to WordPress Template loading rules, <code>404.php</code> template should be loaded for those non-existing tag pages (as you probably know, in HTTP, 404 is the <strong>Page Not Found Error CODE</strong>). However, since you don't have a <code>404.php</code> template in your theme, <code>index.php</code> template is being loaded, as it is the <strong>ultimate fallback template</strong> in a WordPress theme.</p>\n\n<p>Now, if you create a <code>404.php</code> template, then you'll see that it'll be loaded instead of <code>index.php</code> for those non-existing tag pages.</p>\n\n<p>Study <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">WordPress Template Hierarchy</a> properly for a better understanding of how different templates are loaded for different content.</p>\n\n<h2>2. Fixing the wrong pagination:</h2>\n\n<p>As I said above, you're getting nonexistent tag page numbers within your pagination. To remove those nonexistent page numbers from the pagination, you need to delete the</p>\n\n<pre><code>'total' =&gt; $post_query-&gt;max_num_pages\n</code></pre>\n\n<p>line from the <code>paginate_links</code> function call in <code>tag.php</code> template file.</p>\n\n<p>The reason is:</p>\n\n<ol>\n<li><p><code>$post_query</code> is your custom query, not the main query that should determine the number of pages the tag archive has. You even used <code>wp_reset_postdata()</code> before <code>paginate_links</code> function call, so no reason to use that variable here.</p></li>\n<li><p>The <code>total</code> parameter of the <code>paginate_links</code> function by default gets the value of the main WP_Query's <code>max_num_pages</code> property. So deleting it will automatically provide the correct value for the pagination from the main WP_Query object.</p></li>\n</ol>\n\n<h2>3. Pagination without new <code>WP_Query</code>:</h2>\n\n<p>In the comments you said:</p>\n\n<blockquote>\n <p>The reason why I did this is because I didn't know how to generate the type of pagination I needed (<code>&lt;Prev 1 2 3 Next&gt;</code> style) via <code>paginate_links()</code>, with the main query.</p>\n</blockquote>\n\n<p>Well, you don't need a completely new <code>WP_Query</code> just for a different pagination style. In fact, the <code>paginate_links()</code> function don't need the main <code>WP_Query</code> object at all!</p>\n\n<p>So all you need for your desired pagination style is:</p>\n\n<pre><code>echo paginate_links( array(\n 'end_size' =&gt; 2,\n 'mid_size' =&gt; 1,\n 'prev_text' =&gt; __( '&amp;lt;&amp;lt; Previous page', 'text-domain' ),\n 'next_text' =&gt; __( 'Next page &amp;gt;&amp;gt;', 'text-domain' ) \n) );\n</code></pre>\n\n<p>All the other values are being collected by default (including the main <code>WP_Query</code> object)! So you can remove your new <code>WP_Query</code> object in the <code>tag.php</code> template entirely. Check the <a href=\"https://developer.wordpress.org/reference/functions/paginate_links/\" rel=\"nofollow noreferrer\"><code>paginate_links</code> documentation</a>.</p>\n\n<p>Having said that, there can be only one more thing you may want (judging from your comments):</p>\n\n<h2>4. Control the number of posts per tag page:</h2>\n\n<p>You don't need a new <code>WP_Query</code> for this either. This can be easily achieved from the following CODE in <code>functions.php</code>:</p>\n\n<pre><code>function tag_post_per_page_filter( $query ) { \n if ( $query-&gt;is_main_query() ) { \n if ( $query-&gt;is_tag ) { \n $query-&gt;set( 'posts_per_page', 3 );\n } \n } \n} \n\nadd_action('pre_get_posts','tag_post_per_page_filter');\n</code></pre>\n\n<p>Basically it sets the <code>posts_per_page</code> to <code>3</code> in the main <code>WP_Query</code> object for the tag pages. That's all.</p>\n" }, { "answer_id": 403438, "author": "jeffkee", "author_id": 1631, "author_profile": "https://wordpress.stackexchange.com/users/1631", "pm_score": 0, "selected": false, "text": "<p>One thing to add, in case it's helpful to others: If you pass the 'total' argument, it will display more pages than necessary. :</p>\n<pre><code>$args = array('total'=&gt;20);\n</code></pre>\n<p>On the blog top page (index.php), I had limited the display to 20 pages tops (this client has hundreds of articles). 5 was too little - wanted to make sure Google picks up more than that.</p>\n<p>However, when i copied this to tag.php or category.php to achieve exactly what the OP wanted to achieve, I left those variables in by default. I figured even if i set the max to 20, it would show less if there's less articles, right? <strong>Wrong</strong>.</p>\n<p>It turns out that if I ask for 20 pages displayed, even if there's 5 pages worth of articles under a certain category, it just overrides that.</p>\n<p>When I hit page 6 within a specific category, it would display the contents of my 404.php because there was no more than 25 articles under a certain category (5 per page is the display limit).</p>\n<p>I assumed: &quot;Oh it must be loading the pagination count for ALL articles on the blog, not just this category!&quot; I went in a wild goose chase looking for answers on how I can limit this function to show the current category pages only.</p>\n<p>Fayaz's words above gave me the hint I needed:</p>\n<blockquote>\n<p>Well, you don't need a completely new WP_Query just for a different pagination style. In fact, the paginate_links() function don't need the main WP_Query object at all! Commenting out the 'total' array key did the trick.</p>\n</blockquote>\n<pre><code>&lt;?php\n $pages_args = array(\n 'prev_next'=&gt;false,\n // 'total'=&gt;20\n );\n\n $pagelinks = paginate_links($pages_args);\n echo $pagelinks;\n ?&gt;\n</code></pre>\n" } ]
2018/07/04
[ "https://wordpress.stackexchange.com/questions/307640", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133712/" ]
Created my first custom theme from scratch and I'm trying to do a listing of all posts with the same tag. In `tag.php` I display all posts with that specific tag via a `WP_Query` and I'm trying to implement the pagination for that listing (using `paginate_links()`). Page links seem to be outputted correctly. Also the first page looks good. What I don't understand is that when I go on to the next tag page (or to any of the page links outputted from my `tag.php` template e.g. `http://127.0.0.1/wp_site/tag/test_tag/page/2/`) the content from `index.php` is being displayed. What am I actually missing for displaying the subsequent tag pages correctly? `tag.php` template CODE: ------------------------ ``` <?php get_header(); ?> <div class=""> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php if (have_posts()) : ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <h1 class="entry-title">Other entries related to &#39;<?php single_tag_title(); ?>&#39;</h1> </header><!-- .entry-header --> <div class="entry-content"></div><!-- .entry-content --> </article><!-- #post-## --> <div> <?php while (have_posts()) : the_post(); ?> <?php $tagId = get_queried_object()->term_id; $postType = get_post_type(); ?> <?php endwhile; ?> <?php $htmlOutput = ''; /* the 'terms' ID is the testimonial category parent id */ $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $args = [ 'post_type' => 'testimonials-widget', 'tag_id' => $tagId, 'posts_per_page' => 3, 'paged' => $paged, 'tax_query' => [ [ 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => '8', ] ], ]; $post_query = new WP_Query($args); $contentHtml = ''; if($post_query->have_posts() ) { $posts = $post_query->posts; foreach($posts as $post) { // generate html output } } wp_reset_postdata(); echo $contentHtml; ?> </div> <div class="mainContentWrapperCls"> <?php echo paginate_links( array( 'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ), 'total' => $post_query->max_num_pages, 'current' => max( 1, get_query_var( 'paged' ) ), 'format' => '?paged=%#%', 'show_all' => false, 'type' => 'plain', 'end_size' => 2, 'mid_size' => 1, 'prev_next' => true, 'prev_text' => sprintf( '<i></i> %1$s', __( '&lt;&lt; Previous page', 'text-domain' ) ), 'next_text' => sprintf( '%1$s <i></i>', __( 'Next page &gt;&gt;', 'text-domain' ) ), 'add_args' => false, 'add_fragment' => '', ) ); ?> </div> <?php else : ?> <h1>No posts were found.</h1> <?php endif; ?> </main><!-- #main --> </div><!-- #primary --> </div><!-- .wrap --> <?php get_footer(); ?> ``` > > ***Note:*** I created a new query with `WP_Query` in `tag.php`. The reason why I did this is because I didn't know how to generate the type of pagination I needed (`<Prev 1 2 3 Next>` style) via `paginate_links()`, with the main query. > > > Theme `functions.php` CODE: --------------------------- ``` <?php function myCustomThemeScriptEnqueue() { // Theme stylesheet, js wp_enqueue_style('myCustomTheme-style', get_stylesheet_uri(), array(), '1.0.0', 'all'); } function myCustomThemeThemeSetup() { add_theme_support('menus'); add_post_type_support( 'page', 'excerpt' ); } function nllTagFilter($query) { if ($query->is_main_query()) { if ($query->is_tag) { $post_types = get_post_types(); $query->set('post_type', $post_types); } } } add_action('pre_get_posts','nllTagFilter'); add_action('wp_enqueue_scripts', 'myCustomThemeScriptEnqueue'); add_action('init', 'myCustomThemeThemeSetup'); add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 150, 150 ); ?> ``` This is my theme's file-structure so far: [![custom theme file structure](https://i.stack.imgur.com/PzHKj.png)](https://i.stack.imgur.com/PzHKj.png)
Overall CODE issues: -------------------- Your CODE is so wrong in so many ways that I shouldn't even attempt to address them here. I suggest you study [Official WordPress Theme Handbook](https://developer.wordpress.org/themes/) properly before doing these sort of customizations. For the sake of the context, I'm ignoring other issues within your CODE and touching only the issues below: 1. Why `index.php` template is being loaded? -------------------------------------------- First of all, you are getting wrong pagination from your erroneous CODE (check the explanation below). So apart from the first tag page, all the other tag pages are nonexistent (i.e. you need to add more posts to the tag to get more tag pages). Secondly, According to WordPress Template loading rules, `404.php` template should be loaded for those non-existing tag pages (as you probably know, in HTTP, 404 is the **Page Not Found Error CODE**). However, since you don't have a `404.php` template in your theme, `index.php` template is being loaded, as it is the **ultimate fallback template** in a WordPress theme. Now, if you create a `404.php` template, then you'll see that it'll be loaded instead of `index.php` for those non-existing tag pages. Study [WordPress Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) properly for a better understanding of how different templates are loaded for different content. 2. Fixing the wrong pagination: ------------------------------- As I said above, you're getting nonexistent tag page numbers within your pagination. To remove those nonexistent page numbers from the pagination, you need to delete the ``` 'total' => $post_query->max_num_pages ``` line from the `paginate_links` function call in `tag.php` template file. The reason is: 1. `$post_query` is your custom query, not the main query that should determine the number of pages the tag archive has. You even used `wp_reset_postdata()` before `paginate_links` function call, so no reason to use that variable here. 2. The `total` parameter of the `paginate_links` function by default gets the value of the main WP\_Query's `max_num_pages` property. So deleting it will automatically provide the correct value for the pagination from the main WP\_Query object. 3. Pagination without new `WP_Query`: ------------------------------------- In the comments you said: > > The reason why I did this is because I didn't know how to generate the type of pagination I needed (`<Prev 1 2 3 Next>` style) via `paginate_links()`, with the main query. > > > Well, you don't need a completely new `WP_Query` just for a different pagination style. In fact, the `paginate_links()` function don't need the main `WP_Query` object at all! So all you need for your desired pagination style is: ``` echo paginate_links( array( 'end_size' => 2, 'mid_size' => 1, 'prev_text' => __( '&lt;&lt; Previous page', 'text-domain' ), 'next_text' => __( 'Next page &gt;&gt;', 'text-domain' ) ) ); ``` All the other values are being collected by default (including the main `WP_Query` object)! So you can remove your new `WP_Query` object in the `tag.php` template entirely. Check the [`paginate_links` documentation](https://developer.wordpress.org/reference/functions/paginate_links/). Having said that, there can be only one more thing you may want (judging from your comments): 4. Control the number of posts per tag page: -------------------------------------------- You don't need a new `WP_Query` for this either. This can be easily achieved from the following CODE in `functions.php`: ``` function tag_post_per_page_filter( $query ) { if ( $query->is_main_query() ) { if ( $query->is_tag ) { $query->set( 'posts_per_page', 3 ); } } } add_action('pre_get_posts','tag_post_per_page_filter'); ``` Basically it sets the `posts_per_page` to `3` in the main `WP_Query` object for the tag pages. That's all.
307,650
<p>The default menu classes in WordPress are pretty useful. But one problem that i stumble over from time to time is with categories as subitems in menus. For example the following menu structure:</p> <ul> <li>Page 1</li> <li>Page 2 <ul> <li>Category 1</li> </ul></li> <li>Page 3</li> </ul> <p>So when <code>Category 1</code> is active <code>Page 2</code> gets <code>.current-menu-ancestor</code> which is fine … but as soon as a post of <code>Category 1</code> is viewed <code>Page 2</code> has no specific classes … But <code>Category 1</code> has <code>.current-menu-ancestor</code> as expected.</p> <p><strong>So finally here's the question: How do i assign a class for these <code>.current-post-ancestor</code> parents?</strong></p> <p>I'm searching for a PHP solution. Javascript/jQuery is pretty clear … here is a jQuery solution for better understanding what i want to do (And for those who have the same problem and are happy with a JS solution):</p> <pre><code>jQuery( 'li.current-post-ancestor' ).parents( 'li.menu-item' ).addClass( 'current-menu-ancestor' ); </code></pre>
[ { "answer_id": 307656, "author": "mcgoo", "author_id": 146340, "author_profile": "https://wordpress.stackexchange.com/users/146340", "pm_score": 0, "selected": false, "text": "<p>You could use <a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/Walker</a>, and if you want to detect active parent you could use. </p>\n\n<pre><code>if ( in_array( 'current-menu-ancestor', $classes) ) {\n $class_names .= ' is-active';\n}\n</code></pre>\n" }, { "answer_id": 316895, "author": "Raitul Islam", "author_id": 152296, "author_profile": "https://wordpress.stackexchange.com/users/152296", "pm_score": 1, "selected": false, "text": "<p>This is probably what you are looking for ..</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );\nfunction add_menu_parent_class( $items ) {\n\n $parents = array();\n foreach ( $items as $item ) {\n if ( in_array('current-post-ancestor', $item-&gt;classes) ) {\n $parents[] = $item-&gt;menu_item_parent;\n }\n }\n\n foreach ( $items as $item ) {\n if ( in_array( $item-&gt;ID, $parents ) ) {\n $item-&gt;classes[] = 'current-menu-ancestor'; \n }\n }\n\n return $items; \n}\n</code></pre>\n\n<p>It will add a class to <strong>current post ancestor</strong> menu item parent. I have tried this in my theme and it is working perfectly.</p>\n" }, { "answer_id": 351537, "author": "Sohel Khan", "author_id": 177587, "author_profile": "https://wordpress.stackexchange.com/users/177587", "pm_score": -1, "selected": false, "text": "<p>You can simply use the currently active class and his parent to add class.</p>\n\n<pre><code>jQuery( 'li.menu-item.active' ).parents().addClass( 'current-menu-ancestor' );\n</code></pre>\n" } ]
2018/07/04
[ "https://wordpress.stackexchange.com/questions/307650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52227/" ]
The default menu classes in WordPress are pretty useful. But one problem that i stumble over from time to time is with categories as subitems in menus. For example the following menu structure: * Page 1 * Page 2 + Category 1 * Page 3 So when `Category 1` is active `Page 2` gets `.current-menu-ancestor` which is fine … but as soon as a post of `Category 1` is viewed `Page 2` has no specific classes … But `Category 1` has `.current-menu-ancestor` as expected. **So finally here's the question: How do i assign a class for these `.current-post-ancestor` parents?** I'm searching for a PHP solution. Javascript/jQuery is pretty clear … here is a jQuery solution for better understanding what i want to do (And for those who have the same problem and are happy with a JS solution): ``` jQuery( 'li.current-post-ancestor' ).parents( 'li.menu-item' ).addClass( 'current-menu-ancestor' ); ```
This is probably what you are looking for .. ``` add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' ); function add_menu_parent_class( $items ) { $parents = array(); foreach ( $items as $item ) { if ( in_array('current-post-ancestor', $item->classes) ) { $parents[] = $item->menu_item_parent; } } foreach ( $items as $item ) { if ( in_array( $item->ID, $parents ) ) { $item->classes[] = 'current-menu-ancestor'; } } return $items; } ``` It will add a class to **current post ancestor** menu item parent. I have tried this in my theme and it is working perfectly.
307,699
<p>I've been trying to solve this myself for hours but I can't figure out where I am going wrong.</p> <p>I have a custom registration form on my website and I would like to add a checkbox for users to sign up for the newsletter.</p> <p>I went through the <a href="https://beta.docs.mailpoet.com/article/195-add-subscribers-through-your-own-form-or-plugin" rel="nofollow noreferrer">Mailpoet Docs</a> and tried everything that they describe there but something is not working for me. </p> <p>The user is being signed up successfully but never gets added to my mainling list. Here's my code</p> <pre><code>function newsletterSignUp(){ $subscriber_data = array( 'email' =&gt; sanitize_text_field($_POST['email']), 'first_name' =&gt; sanitize_text_field($_POST['first_name']), 'last_name' =&gt; sanitize_text_field($_POST['last_name']) ); $list = \MailPoet\API\API::MP('v1')-&gt;getLists()[0][id]; //Returns the ID of the list that I want to assign subscribers to try { $subscriber = \MailPoet\API\API::MP('v1')-&gt;addSubscriber($subscriber_data, $list, $options); } catch(Exception $exception) { // return $exception-&gt;getMessage(); } } </code></pre> <p>I am calling this function like this:</p> <pre><code>if(isset($_POST['submit'])){ // Some other code to sign up the user if(isset($_POST['subscribe'])){ //The name of my checkbox input newsletterSignUp(); } } </code></pre> <p>Any help will be greatly appreciated!!</p>
[ { "answer_id": 307656, "author": "mcgoo", "author_id": 146340, "author_profile": "https://wordpress.stackexchange.com/users/146340", "pm_score": 0, "selected": false, "text": "<p>You could use <a href=\"https://codex.wordpress.org/Class_Reference/Walker\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/Walker</a>, and if you want to detect active parent you could use. </p>\n\n<pre><code>if ( in_array( 'current-menu-ancestor', $classes) ) {\n $class_names .= ' is-active';\n}\n</code></pre>\n" }, { "answer_id": 316895, "author": "Raitul Islam", "author_id": 152296, "author_profile": "https://wordpress.stackexchange.com/users/152296", "pm_score": 1, "selected": false, "text": "<p>This is probably what you are looking for ..</p>\n\n<pre><code>add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );\nfunction add_menu_parent_class( $items ) {\n\n $parents = array();\n foreach ( $items as $item ) {\n if ( in_array('current-post-ancestor', $item-&gt;classes) ) {\n $parents[] = $item-&gt;menu_item_parent;\n }\n }\n\n foreach ( $items as $item ) {\n if ( in_array( $item-&gt;ID, $parents ) ) {\n $item-&gt;classes[] = 'current-menu-ancestor'; \n }\n }\n\n return $items; \n}\n</code></pre>\n\n<p>It will add a class to <strong>current post ancestor</strong> menu item parent. I have tried this in my theme and it is working perfectly.</p>\n" }, { "answer_id": 351537, "author": "Sohel Khan", "author_id": 177587, "author_profile": "https://wordpress.stackexchange.com/users/177587", "pm_score": -1, "selected": false, "text": "<p>You can simply use the currently active class and his parent to add class.</p>\n\n<pre><code>jQuery( 'li.menu-item.active' ).parents().addClass( 'current-menu-ancestor' );\n</code></pre>\n" } ]
2018/07/04
[ "https://wordpress.stackexchange.com/questions/307699", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145115/" ]
I've been trying to solve this myself for hours but I can't figure out where I am going wrong. I have a custom registration form on my website and I would like to add a checkbox for users to sign up for the newsletter. I went through the [Mailpoet Docs](https://beta.docs.mailpoet.com/article/195-add-subscribers-through-your-own-form-or-plugin) and tried everything that they describe there but something is not working for me. The user is being signed up successfully but never gets added to my mainling list. Here's my code ``` function newsletterSignUp(){ $subscriber_data = array( 'email' => sanitize_text_field($_POST['email']), 'first_name' => sanitize_text_field($_POST['first_name']), 'last_name' => sanitize_text_field($_POST['last_name']) ); $list = \MailPoet\API\API::MP('v1')->getLists()[0][id]; //Returns the ID of the list that I want to assign subscribers to try { $subscriber = \MailPoet\API\API::MP('v1')->addSubscriber($subscriber_data, $list, $options); } catch(Exception $exception) { // return $exception->getMessage(); } } ``` I am calling this function like this: ``` if(isset($_POST['submit'])){ // Some other code to sign up the user if(isset($_POST['subscribe'])){ //The name of my checkbox input newsletterSignUp(); } } ``` Any help will be greatly appreciated!!
This is probably what you are looking for .. ``` add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' ); function add_menu_parent_class( $items ) { $parents = array(); foreach ( $items as $item ) { if ( in_array('current-post-ancestor', $item->classes) ) { $parents[] = $item->menu_item_parent; } } foreach ( $items as $item ) { if ( in_array( $item->ID, $parents ) ) { $item->classes[] = 'current-menu-ancestor'; } } return $items; } ``` It will add a class to **current post ancestor** menu item parent. I have tried this in my theme and it is working perfectly.
307,713
<p>I have a custom post type <code>mycpt</code> and I'm trying to allow for a variable to be appended onto the end of the URL right after the post name slug, like this:</p> <pre><code>www.site.com/mycpt/the-name-of-my-post/var-value-here/ </code></pre> <p>I've been searching around, and the only examples I can find don't use the post name/slug in the URL, but rather taxonomies, so I'm not sure what the correct way to do it is. Here is what I'm trying now, but it's treating the URL with the variable as a separate page type (it's loading a default template rather than the template my custom post type uses).</p> <pre><code>add_action( 'init', function() { add_rewrite_tag( '%my_var%', '([^/]*)' ); add_rewrite_rule( '^mycpt/(.*)/([^/]*)/?', 'index.php?post_type=mycpt&amp;my_var=$matches[1]', 'top' ); }, 10, 0 ); </code></pre> <p>I also tried changing <code>$matches[1]</code> to <code>$matches[2]</code> since I thought maybe the wildcard for the post name/slug was the first match, but that didn't work either.</p> <p>Can anybody see what I'm doing wrong here?</p>
[ { "answer_id": 307715, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>As a temporary solution you can try using free plugin : <a href=\"https://wordpress.org/plugins/custom-post-type-permalinks/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/custom-post-type-permalinks/</a></p>\n" }, { "answer_id": 307890, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>Here's a complete working example that adds a post type, with extra rule to capture an additional parameter:</p>\n\n<pre><code>function wpd_post_type_and_rule() {\n register_post_type( 'mycpt',\n array(\n 'labels' =&gt; array(\n 'name' =&gt; __( 'mycpt' ),\n ),\n 'public' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'mycpt' ),\n )\n );\n add_rewrite_tag( '%mycpt_var%', '([^/]*)' );\n add_rewrite_rule(\n '^mycpt/([^/]*)/([^/]*)/?$',\n 'index.php?mycpt=$matches[1]&amp;mycpt_var=$matches[2]',\n 'top'\n );\n}\nadd_action( 'init', 'wpd_post_type_and_rule' );\n</code></pre>\n\n<p>After adding this and flushing rewrite rules, you'll have both</p>\n\n<pre><code>www.site.com/mycpt/the-name-of-my-post/\n</code></pre>\n\n<p>and</p>\n\n<pre><code>www.site.com/mycpt/the-name-of-my-post/var-value-here/\n</code></pre>\n\n<p>You can get the value of <code>mycpt_var</code> in the template with:</p>\n\n<pre><code>echo get_query_var( 'mycpt_var' );\n</code></pre>\n" } ]
2018/07/04
[ "https://wordpress.stackexchange.com/questions/307713", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63238/" ]
I have a custom post type `mycpt` and I'm trying to allow for a variable to be appended onto the end of the URL right after the post name slug, like this: ``` www.site.com/mycpt/the-name-of-my-post/var-value-here/ ``` I've been searching around, and the only examples I can find don't use the post name/slug in the URL, but rather taxonomies, so I'm not sure what the correct way to do it is. Here is what I'm trying now, but it's treating the URL with the variable as a separate page type (it's loading a default template rather than the template my custom post type uses). ``` add_action( 'init', function() { add_rewrite_tag( '%my_var%', '([^/]*)' ); add_rewrite_rule( '^mycpt/(.*)/([^/]*)/?', 'index.php?post_type=mycpt&my_var=$matches[1]', 'top' ); }, 10, 0 ); ``` I also tried changing `$matches[1]` to `$matches[2]` since I thought maybe the wildcard for the post name/slug was the first match, but that didn't work either. Can anybody see what I'm doing wrong here?
Here's a complete working example that adds a post type, with extra rule to capture an additional parameter: ``` function wpd_post_type_and_rule() { register_post_type( 'mycpt', array( 'labels' => array( 'name' => __( 'mycpt' ), ), 'public' => true, 'rewrite' => array( 'slug' => 'mycpt' ), ) ); add_rewrite_tag( '%mycpt_var%', '([^/]*)' ); add_rewrite_rule( '^mycpt/([^/]*)/([^/]*)/?$', 'index.php?mycpt=$matches[1]&mycpt_var=$matches[2]', 'top' ); } add_action( 'init', 'wpd_post_type_and_rule' ); ``` After adding this and flushing rewrite rules, you'll have both ``` www.site.com/mycpt/the-name-of-my-post/ ``` and ``` www.site.com/mycpt/the-name-of-my-post/var-value-here/ ``` You can get the value of `mycpt_var` in the template with: ``` echo get_query_var( 'mycpt_var' ); ```
307,783
<p>I built a page with Elementor, and I want to use it as my home page. When I use a static home page with my theme, it still gets wrapped with the header, footer, and content container, which I don't want in this case.</p> <p>I've built a simple <code>front-page.php</code> template to try to just output the contents of this page.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html &lt;?php language_attributes(); ?&gt; class="no-js no-svg"&gt; &lt;head&gt; &lt;meta charset="&lt;?php bloginfo( 'charset' ); ?&gt;"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="profile" href="http://gmpg.org/xfn/11"&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class(); ?&gt;&gt; &lt;?php $page = get_page_by_path( 'home' ); $content = apply_filters('the_content', $page-&gt;post_content); echo $content; get_footer(); ?&gt; &lt;/body&gt; &lt;?php wp_footer(); ?&gt; </code></pre> <p>This works to output the <em>content</em>, but I don't get the styles and my posts widgets are MIA. How can I modify this template to also get the styles and so that all the widgets will be present?</p>
[ { "answer_id": 370754, "author": "Maduka Jayalath", "author_id": 110601, "author_profile": "https://wordpress.stackexchange.com/users/110601", "pm_score": 3, "selected": false, "text": "<p>Here is the way,</p>\n<pre><code>$contentElementor = &quot;&quot;;\n\nif (class_exists(&quot;\\\\Elementor\\\\Plugin&quot;)) {\n $post_ID = 124;\n $pluginElementor = \\Elementor\\Plugin::instance();\n $contentElementor = $pluginElementor-&gt;frontend-&gt;get_builder_content($post_ID);\n}\n\necho $contentElementor;\n</code></pre>\n" }, { "answer_id": 397829, "author": "ttn_", "author_id": 91856, "author_profile": "https://wordpress.stackexchange.com/users/91856", "pm_score": 1, "selected": false, "text": "<p><code>get_builder_content</code> is an internal method, please use <code>get_builder_content_for_display()</code>.</p>\n<pre><code>$frontend = new \\Elementor\\Frontend();\n$page_id = 100;\n\necho $frontend-&gt;get_builder_content_for_display( $page_id, $with_css = true );\n</code></pre>\n" } ]
2018/07/05
[ "https://wordpress.stackexchange.com/questions/307783", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31649/" ]
I built a page with Elementor, and I want to use it as my home page. When I use a static home page with my theme, it still gets wrapped with the header, footer, and content container, which I don't want in this case. I've built a simple `front-page.php` template to try to just output the contents of this page. ``` <!DOCTYPE html> <html <?php language_attributes(); ?> class="no-js no-svg"> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="profile" href="http://gmpg.org/xfn/11"> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <?php $page = get_page_by_path( 'home' ); $content = apply_filters('the_content', $page->post_content); echo $content; get_footer(); ?> </body> <?php wp_footer(); ?> ``` This works to output the *content*, but I don't get the styles and my posts widgets are MIA. How can I modify this template to also get the styles and so that all the widgets will be present?
Here is the way, ``` $contentElementor = ""; if (class_exists("\\Elementor\\Plugin")) { $post_ID = 124; $pluginElementor = \Elementor\Plugin::instance(); $contentElementor = $pluginElementor->frontend->get_builder_content($post_ID); } echo $contentElementor; ```
307,794
<p>I have the following problem when I am validating a field with the Advanced Custom Fields plugin in wordpress. What happens is that the field is validated correctly but the error appears on a new page instead of going out on the same page above the field to which I am validating. The code to validate is the following:</p> <pre><code>function validate_fields_contact() { add_filter('acf/validate_value/name=phone_contact', 'validate_phone_number', 10, 4); } function validate_phone_number($valid, $value, $field, $input) { if (!$valid) { return $valid; } if(!preg_match("/^\+XX(\s|\d){8,12}$/", $value)) { return __('Incorrect Format.'); } return true; } </code></pre> <p><strong>It should be like that:</strong> </p> <p><a href="https://i.stack.imgur.com/1r7Bm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1r7Bm.png" alt="enter image description here"></a></p> <p><strong>This is what happens</strong></p> <p><a href="https://i.stack.imgur.com/0Po9Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Po9Y.png" alt="enter image description here"></a></p>
[ { "answer_id": 319945, "author": "Kostiantyn Petlia", "author_id": 104932, "author_profile": "https://wordpress.stackexchange.com/users/104932", "pm_score": 3, "selected": true, "text": "<p>I did have the same issue. And I wasted enough time for the answer.</p>\n\n<p>At first be sure that:</p>\n\n<p>The ajax request isn't failed and happens. So, check:</p>\n\n<ol>\n<li>Is acf_form_head() before get_header() and run before any html is output?</li>\n<li>Does your theme contain call to wp_head()?</li>\n<li>Does your theme contain call to wp_foot()?</li>\n<li>Are your deferring the loading of JavaScript or otherwise altering the way that JavaScript is loaded on the page?</li>\n</ol>\n\n<p>(Look at <a href=\"https://support.advancedcustomfields.com/forums/topic/my-acf_form-is-saving-to-the-database-but-not-showing-up-in-the-admin-panel-unde/\" rel=\"nofollow noreferrer\">this ACF support topic</a> too. If you use acf_form() for creating new user look at <a href=\"https://support.advancedcustomfields.com/forums/topic/create-new-user-with-acf_form/\" rel=\"nofollow noreferrer\">this topic</a>).</p>\n\n<p>But in my case the root was is_admin() in this line into the 'acf/validate_value' hook:</p>\n\n<pre><code>if ( ! $valid || is_admin() ) { return $valid; }\n</code></pre>\n\n<p><strong>Because is_admin() returns 'true' by AJAX requests</strong>. As a result, the validate function didn't work.</p>\n\n<p>Hope it will helpfully for somebody.</p>\n" }, { "answer_id": 387744, "author": "RCNeil", "author_id": 12294, "author_profile": "https://wordpress.stackexchange.com/users/12294", "pm_score": 0, "selected": false, "text": "<p>If anyone stumbles upon this later -- in my case it was because I had an <code>admin_init</code> hook to prevent access to <code>wp-admin</code> for a certain role (which is why we usually have a front end ACF form anyway right?) and it would produce an error when trying to run <code>admin-ajax.php</code>. ACF uses that file for AJAX validation so when you run some sort of &quot;prevent wp-admin&quot; hook, that stops ACF validation, too.</p>\n<p>So, the hook interfering was:</p>\n<pre><code>add_action( 'admin_init', 'custom_no_admin_access', 100 );\nfunction custom_no_admin_access() {\n global $current_user;\n $user_roles = $current_user-&gt;roles;\n $user_role = array_shift($user_roles);\n if($user_role === 'special-role'){\n exit( wp_redirect(home_url()));\n }\n}\n</code></pre>\n<p>and I turned it into:</p>\n<pre><code>add_action( 'admin_init', 'custom_no_admin_access', 100 );\nfunction custom_no_admin_access() {\n global $current_user;\n $user_roles = $current_user-&gt;roles;\n $user_role = array_shift($user_roles);\n if($user_role === 'special-role' &amp;&amp; $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php'){\n exit( wp_redirect(home_url()));\n }\n}\n</code></pre>\n<p>A big help for troubleshooting was using Chrome's Inspector to track the network requests. Go to the Network tab and check &quot;Preserve Log&quot; so you can see the history of requests. Try to submit the form and I could see it was redirecting to the home page (which my <code>admin_init</code> hook says to do when attempting to use admin-ajax.php) before failing the validation.</p>\n<p>Hope that helps!</p>\n" }, { "answer_id": 406422, "author": "Alex Lana", "author_id": 222833, "author_profile": "https://wordpress.stackexchange.com/users/222833", "pm_score": 0, "selected": false, "text": "<p>Two days searching for the fix to the same problem... It looks like the <code>acf_form_head()</code> is not necessary in the validation and the error, in my case, is there. So I add this <code>if</code> and the magic happened.</p>\n<pre><code>function acf_inscs_head () {\n if ( !wp_doing_ajax() ) // avoid to load acf_form_head() on validation\n acf_form_head();\n}\nadd_action( 'init', 'acf_inscs_head', -1 );\n</code></pre>\n" } ]
2018/07/05
[ "https://wordpress.stackexchange.com/questions/307794", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/144662/" ]
I have the following problem when I am validating a field with the Advanced Custom Fields plugin in wordpress. What happens is that the field is validated correctly but the error appears on a new page instead of going out on the same page above the field to which I am validating. The code to validate is the following: ``` function validate_fields_contact() { add_filter('acf/validate_value/name=phone_contact', 'validate_phone_number', 10, 4); } function validate_phone_number($valid, $value, $field, $input) { if (!$valid) { return $valid; } if(!preg_match("/^\+XX(\s|\d){8,12}$/", $value)) { return __('Incorrect Format.'); } return true; } ``` **It should be like that:** [![enter image description here](https://i.stack.imgur.com/1r7Bm.png)](https://i.stack.imgur.com/1r7Bm.png) **This is what happens** [![enter image description here](https://i.stack.imgur.com/0Po9Y.png)](https://i.stack.imgur.com/0Po9Y.png)
I did have the same issue. And I wasted enough time for the answer. At first be sure that: The ajax request isn't failed and happens. So, check: 1. Is acf\_form\_head() before get\_header() and run before any html is output? 2. Does your theme contain call to wp\_head()? 3. Does your theme contain call to wp\_foot()? 4. Are your deferring the loading of JavaScript or otherwise altering the way that JavaScript is loaded on the page? (Look at [this ACF support topic](https://support.advancedcustomfields.com/forums/topic/my-acf_form-is-saving-to-the-database-but-not-showing-up-in-the-admin-panel-unde/) too. If you use acf\_form() for creating new user look at [this topic](https://support.advancedcustomfields.com/forums/topic/create-new-user-with-acf_form/)). But in my case the root was is\_admin() in this line into the 'acf/validate\_value' hook: ``` if ( ! $valid || is_admin() ) { return $valid; } ``` **Because is\_admin() returns 'true' by AJAX requests**. As a result, the validate function didn't work. Hope it will helpfully for somebody.
307,795
<p>I’m looking to add Instagram to my follow buttons, and on the settings pages it tells me:</p> <p>You can setup Instagram, YouTube, Snapchat, and other buttons in an AddToAny Follow widget.</p> <p>Add the “AddToAny Follow” widget in Customize or Widgets.</p> <p>But in the AddToAny Follow Widget i’ve got linkedin, twitter and facebook. No trace of instagram, that is what I’m trying to add. (<a href="https://imgur.com/a/FEXOQYI" rel="nofollow noreferrer">https://imgur.com/a/FEXOQYI</a>)</p> <p>What am I not understanding here?</p>
[ { "answer_id": 319945, "author": "Kostiantyn Petlia", "author_id": 104932, "author_profile": "https://wordpress.stackexchange.com/users/104932", "pm_score": 3, "selected": true, "text": "<p>I did have the same issue. And I wasted enough time for the answer.</p>\n\n<p>At first be sure that:</p>\n\n<p>The ajax request isn't failed and happens. So, check:</p>\n\n<ol>\n<li>Is acf_form_head() before get_header() and run before any html is output?</li>\n<li>Does your theme contain call to wp_head()?</li>\n<li>Does your theme contain call to wp_foot()?</li>\n<li>Are your deferring the loading of JavaScript or otherwise altering the way that JavaScript is loaded on the page?</li>\n</ol>\n\n<p>(Look at <a href=\"https://support.advancedcustomfields.com/forums/topic/my-acf_form-is-saving-to-the-database-but-not-showing-up-in-the-admin-panel-unde/\" rel=\"nofollow noreferrer\">this ACF support topic</a> too. If you use acf_form() for creating new user look at <a href=\"https://support.advancedcustomfields.com/forums/topic/create-new-user-with-acf_form/\" rel=\"nofollow noreferrer\">this topic</a>).</p>\n\n<p>But in my case the root was is_admin() in this line into the 'acf/validate_value' hook:</p>\n\n<pre><code>if ( ! $valid || is_admin() ) { return $valid; }\n</code></pre>\n\n<p><strong>Because is_admin() returns 'true' by AJAX requests</strong>. As a result, the validate function didn't work.</p>\n\n<p>Hope it will helpfully for somebody.</p>\n" }, { "answer_id": 387744, "author": "RCNeil", "author_id": 12294, "author_profile": "https://wordpress.stackexchange.com/users/12294", "pm_score": 0, "selected": false, "text": "<p>If anyone stumbles upon this later -- in my case it was because I had an <code>admin_init</code> hook to prevent access to <code>wp-admin</code> for a certain role (which is why we usually have a front end ACF form anyway right?) and it would produce an error when trying to run <code>admin-ajax.php</code>. ACF uses that file for AJAX validation so when you run some sort of &quot;prevent wp-admin&quot; hook, that stops ACF validation, too.</p>\n<p>So, the hook interfering was:</p>\n<pre><code>add_action( 'admin_init', 'custom_no_admin_access', 100 );\nfunction custom_no_admin_access() {\n global $current_user;\n $user_roles = $current_user-&gt;roles;\n $user_role = array_shift($user_roles);\n if($user_role === 'special-role'){\n exit( wp_redirect(home_url()));\n }\n}\n</code></pre>\n<p>and I turned it into:</p>\n<pre><code>add_action( 'admin_init', 'custom_no_admin_access', 100 );\nfunction custom_no_admin_access() {\n global $current_user;\n $user_roles = $current_user-&gt;roles;\n $user_role = array_shift($user_roles);\n if($user_role === 'special-role' &amp;&amp; $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php'){\n exit( wp_redirect(home_url()));\n }\n}\n</code></pre>\n<p>A big help for troubleshooting was using Chrome's Inspector to track the network requests. Go to the Network tab and check &quot;Preserve Log&quot; so you can see the history of requests. Try to submit the form and I could see it was redirecting to the home page (which my <code>admin_init</code> hook says to do when attempting to use admin-ajax.php) before failing the validation.</p>\n<p>Hope that helps!</p>\n" }, { "answer_id": 406422, "author": "Alex Lana", "author_id": 222833, "author_profile": "https://wordpress.stackexchange.com/users/222833", "pm_score": 0, "selected": false, "text": "<p>Two days searching for the fix to the same problem... It looks like the <code>acf_form_head()</code> is not necessary in the validation and the error, in my case, is there. So I add this <code>if</code> and the magic happened.</p>\n<pre><code>function acf_inscs_head () {\n if ( !wp_doing_ajax() ) // avoid to load acf_form_head() on validation\n acf_form_head();\n}\nadd_action( 'init', 'acf_inscs_head', -1 );\n</code></pre>\n" } ]
2018/07/05
[ "https://wordpress.stackexchange.com/questions/307795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8895/" ]
I’m looking to add Instagram to my follow buttons, and on the settings pages it tells me: You can setup Instagram, YouTube, Snapchat, and other buttons in an AddToAny Follow widget. Add the “AddToAny Follow” widget in Customize or Widgets. But in the AddToAny Follow Widget i’ve got linkedin, twitter and facebook. No trace of instagram, that is what I’m trying to add. (<https://imgur.com/a/FEXOQYI>) What am I not understanding here?
I did have the same issue. And I wasted enough time for the answer. At first be sure that: The ajax request isn't failed and happens. So, check: 1. Is acf\_form\_head() before get\_header() and run before any html is output? 2. Does your theme contain call to wp\_head()? 3. Does your theme contain call to wp\_foot()? 4. Are your deferring the loading of JavaScript or otherwise altering the way that JavaScript is loaded on the page? (Look at [this ACF support topic](https://support.advancedcustomfields.com/forums/topic/my-acf_form-is-saving-to-the-database-but-not-showing-up-in-the-admin-panel-unde/) too. If you use acf\_form() for creating new user look at [this topic](https://support.advancedcustomfields.com/forums/topic/create-new-user-with-acf_form/)). But in my case the root was is\_admin() in this line into the 'acf/validate\_value' hook: ``` if ( ! $valid || is_admin() ) { return $valid; } ``` **Because is\_admin() returns 'true' by AJAX requests**. As a result, the validate function didn't work. Hope it will helpfully for somebody.
307,916
<p>I've just installed a fresh install of WordPress and before doing anything else I've tried to setup a multisite, which I would like to do with subdirectories. </p> <p>But when I click on Network Setup I get the notification: </p> <blockquote> <p>Because your installation is not new, the sites in your WordPress network must use sub-domains. The main site in a sub-directory installation will need to use a modified permalink structure, potentially breaking existing links.</p> </blockquote> <p>Can anyone tell me what I'm doing wrong, or what I need to change to allow subdirectories?</p>
[ { "answer_id": 307955, "author": "Robert Gres", "author_id": 146551, "author_profile": "https://wordpress.stackexchange.com/users/146551", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://premium.wpmudev.org/forums/topic/enabling-network-because-your-install-is-not-new-the-sites-in-your-wordpress-network-must-use-sub-domains\" rel=\"nofollow noreferrer\">This thread</a> might be helpful.</p>\n\n<p>In essence: try to delete sample post and page.</p>\n" }, { "answer_id": 359552, "author": "Shahzaib Chadhar", "author_id": 183408, "author_profile": "https://wordpress.stackexchange.com/users/183408", "pm_score": 3, "selected": true, "text": "<p>You don't need to do anything just past this code in your activated theme's <code>functions.php</code></p>\n\n<pre><code>add_filter( 'allow_subdirectory_install', '__return_true' );\n</code></pre>\n" } ]
2018/07/07
[ "https://wordpress.stackexchange.com/questions/307916", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/59568/" ]
I've just installed a fresh install of WordPress and before doing anything else I've tried to setup a multisite, which I would like to do with subdirectories. But when I click on Network Setup I get the notification: > > Because your installation is not new, the sites in your WordPress > network must use sub-domains. The main site in a sub-directory > installation will need to use a modified permalink structure, > potentially breaking existing links. > > > Can anyone tell me what I'm doing wrong, or what I need to change to allow subdirectories?
You don't need to do anything just past this code in your activated theme's `functions.php` ``` add_filter( 'allow_subdirectory_install', '__return_true' ); ```
307,920
<p>I want to remove tag, category classes from Post Titles of my WordPress blog. On the frontend, Wordpress generates extra classes for every single article title.</p> <p>For Example, <a href="https://examsmate.in/indian-army-preparation-tips/" rel="nofollow noreferrer">this article</a>, has these article title classes "category-tips-guides" "tag-indian-army" as displayed in the following image:</p> <p><a href="https://i.stack.imgur.com/J2Aqi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J2Aqi.png" alt="enter image description here"></a></p> <p>I have tried the following snippet to remove some extra classes (<a href="https://wordpress.stackexchange.com/questions/302055/remove-classes-from-post-class?rq=1">shared on this page</a>) and it works:</p> <pre><code>function lsmwp_remove_postclasses($classes, $class, $post_id) { $classes = array_diff( $classes, array( 'hentry', 'type-' . get_post_type($post_id), 'status-' . get_post_status($post_id), ) ); return $classes; add_filter('post_class', 'lsmwp_remove_postclasses', 10, 3); </code></pre> <p>But the issue with this code is that it doesn't remove any Tag, Category classes as I want.</p> <p><strong>Some References to post_class:</strong></p> <ol> <li><a href="https://codex.wordpress.org/Function_Reference/post_class" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/post_class</a></li> <li><a href="https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/post-template.php#L0" rel="nofollow noreferrer">https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/post-template.php#L0</a></li> </ol>
[ { "answer_id": 307955, "author": "Robert Gres", "author_id": 146551, "author_profile": "https://wordpress.stackexchange.com/users/146551", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://premium.wpmudev.org/forums/topic/enabling-network-because-your-install-is-not-new-the-sites-in-your-wordpress-network-must-use-sub-domains\" rel=\"nofollow noreferrer\">This thread</a> might be helpful.</p>\n\n<p>In essence: try to delete sample post and page.</p>\n" }, { "answer_id": 359552, "author": "Shahzaib Chadhar", "author_id": 183408, "author_profile": "https://wordpress.stackexchange.com/users/183408", "pm_score": 3, "selected": true, "text": "<p>You don't need to do anything just past this code in your activated theme's <code>functions.php</code></p>\n\n<pre><code>add_filter( 'allow_subdirectory_install', '__return_true' );\n</code></pre>\n" } ]
2018/07/07
[ "https://wordpress.stackexchange.com/questions/307920", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146528/" ]
I want to remove tag, category classes from Post Titles of my WordPress blog. On the frontend, Wordpress generates extra classes for every single article title. For Example, [this article](https://examsmate.in/indian-army-preparation-tips/), has these article title classes "category-tips-guides" "tag-indian-army" as displayed in the following image: [![enter image description here](https://i.stack.imgur.com/J2Aqi.png)](https://i.stack.imgur.com/J2Aqi.png) I have tried the following snippet to remove some extra classes ([shared on this page](https://wordpress.stackexchange.com/questions/302055/remove-classes-from-post-class?rq=1)) and it works: ``` function lsmwp_remove_postclasses($classes, $class, $post_id) { $classes = array_diff( $classes, array( 'hentry', 'type-' . get_post_type($post_id), 'status-' . get_post_status($post_id), ) ); return $classes; add_filter('post_class', 'lsmwp_remove_postclasses', 10, 3); ``` But the issue with this code is that it doesn't remove any Tag, Category classes as I want. **Some References to post\_class:** 1. <https://codex.wordpress.org/Function_Reference/post_class> 2. <https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/post-template.php#L0>
You don't need to do anything just past this code in your activated theme's `functions.php` ``` add_filter( 'allow_subdirectory_install', '__return_true' ); ```
307,930
<p>Problem:</p> <ul> <li>I need to associate to every PostType a Company(done with Taxonomy, taxonomy is a huge list of Companies)</li> <li>A company can be a Producer or a Developer</li> <li>I need to Select a Producer on the PostType</li> <li>I need to Select a Developer on the PostType</li> </ul> <p>As you understand you can have the same Company as Developer and Producer</p> <p><strong>Solution ?</strong></p> <p>Unfortunately i find myself like a fish out of water. Wordpress is the perfect CMS for this Job but for this task, ehmmm, i dont know :/ According my background i can associate a Company to a Post Type (Company will be the Taxonomy). But after ? How to do an intermediate Association (every Company can be a Developer, Publisher or Both) ?</p> <p>P.S I Dont need meta fields (i need to insert at least 2000 companies if not more than that, custom fields will slow down hard i think the queries if i start to search a developer who has done x PostType)</p> <p>Thanks in advance to each of you for your time, I do not owe you a beer, I owe you a ticket for the World Cup final if you give me a hand, I'm banging my head against the wall two days for that ...... :/ :D</p>
[ { "answer_id": 307955, "author": "Robert Gres", "author_id": 146551, "author_profile": "https://wordpress.stackexchange.com/users/146551", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://premium.wpmudev.org/forums/topic/enabling-network-because-your-install-is-not-new-the-sites-in-your-wordpress-network-must-use-sub-domains\" rel=\"nofollow noreferrer\">This thread</a> might be helpful.</p>\n\n<p>In essence: try to delete sample post and page.</p>\n" }, { "answer_id": 359552, "author": "Shahzaib Chadhar", "author_id": 183408, "author_profile": "https://wordpress.stackexchange.com/users/183408", "pm_score": 3, "selected": true, "text": "<p>You don't need to do anything just past this code in your activated theme's <code>functions.php</code></p>\n\n<pre><code>add_filter( 'allow_subdirectory_install', '__return_true' );\n</code></pre>\n" } ]
2018/07/07
[ "https://wordpress.stackexchange.com/questions/307930", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146538/" ]
Problem: * I need to associate to every PostType a Company(done with Taxonomy, taxonomy is a huge list of Companies) * A company can be a Producer or a Developer * I need to Select a Producer on the PostType * I need to Select a Developer on the PostType As you understand you can have the same Company as Developer and Producer **Solution ?** Unfortunately i find myself like a fish out of water. Wordpress is the perfect CMS for this Job but for this task, ehmmm, i dont know :/ According my background i can associate a Company to a Post Type (Company will be the Taxonomy). But after ? How to do an intermediate Association (every Company can be a Developer, Publisher or Both) ? P.S I Dont need meta fields (i need to insert at least 2000 companies if not more than that, custom fields will slow down hard i think the queries if i start to search a developer who has done x PostType) Thanks in advance to each of you for your time, I do not owe you a beer, I owe you a ticket for the World Cup final if you give me a hand, I'm banging my head against the wall two days for that ...... :/ :D
You don't need to do anything just past this code in your activated theme's `functions.php` ``` add_filter( 'allow_subdirectory_install', '__return_true' ); ```
307,970
<p>I am making my theme. I am using wp_editor in front-end to submit post. </p> <p>I submit through wp_editor in the specific page, and this being displayed in single.php. At single.php I am using </p> <pre><code>&lt;?php the_content(); ?&gt; </code></pre> <p>The problem is when I put enter-key (like br tag) in a post that is several blank row, these blank rows are disappeared. All contents are shown without blank row. so it looks not cool. </p> <p>My first language is not English, so I am not sure that my expression is good to explain my intention. </p> <p>I mean, I want like this (A). but the content shows like (B). There's no blank rows.. </p> <p>(A) My name is mike. Hi. <br> Hahaha. you look nice.<br><br></p> <p>And what is you name?<br><br></p> <p>(B) My name is mike. Hi. <br> Hahaha. you look nice.<br> And what is you name?<br><br></p> <p>Can someone have any idea?</p> <p>Thank you.</p>
[ { "answer_id": 307955, "author": "Robert Gres", "author_id": 146551, "author_profile": "https://wordpress.stackexchange.com/users/146551", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://premium.wpmudev.org/forums/topic/enabling-network-because-your-install-is-not-new-the-sites-in-your-wordpress-network-must-use-sub-domains\" rel=\"nofollow noreferrer\">This thread</a> might be helpful.</p>\n\n<p>In essence: try to delete sample post and page.</p>\n" }, { "answer_id": 359552, "author": "Shahzaib Chadhar", "author_id": 183408, "author_profile": "https://wordpress.stackexchange.com/users/183408", "pm_score": 3, "selected": true, "text": "<p>You don't need to do anything just past this code in your activated theme's <code>functions.php</code></p>\n\n<pre><code>add_filter( 'allow_subdirectory_install', '__return_true' );\n</code></pre>\n" } ]
2018/07/08
[ "https://wordpress.stackexchange.com/questions/307970", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133185/" ]
I am making my theme. I am using wp\_editor in front-end to submit post. I submit through wp\_editor in the specific page, and this being displayed in single.php. At single.php I am using ``` <?php the_content(); ?> ``` The problem is when I put enter-key (like br tag) in a post that is several blank row, these blank rows are disappeared. All contents are shown without blank row. so it looks not cool. My first language is not English, so I am not sure that my expression is good to explain my intention. I mean, I want like this (A). but the content shows like (B). There's no blank rows.. (A) My name is mike. Hi. Hahaha. you look nice. And what is you name? (B) My name is mike. Hi. Hahaha. you look nice. And what is you name? Can someone have any idea? Thank you.
You don't need to do anything just past this code in your activated theme's `functions.php` ``` add_filter( 'allow_subdirectory_install', '__return_true' ); ```
308,021
<p>I'm trying to add a class to list blocks (<code>core/list</code>) in Gutenberg. Unfortunately, it looks like because some blocks like lists and paragraphs don't have the standard default class name of <code>wp-block-{name}</code> they can't be renamed using the <a href="https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/#blocks-getblockdefaultclassname" rel="noreferrer"><code>blocks.getBlockDefaultClassName</code></a> filter.</p> <p>To get around that, I've used the <code>blocks.getSaveContent.extraProps</code> filter, which seems to enable me to add a class to ALL the blocks that don't already have classes. Code below is how I got that working. It's adding <code>added-class-name</code> to blocks likes lists and paragraphs and so on. </p> <pre><code>function addBlockClassName( className ) { return Object.assign( className, { class: 'added-class-name' } ); } wp.hooks.addFilter( 'blocks.getSaveContent.extraProps', 'gdt-guten-plugin/add-block-class-name', addBlockClassName ); </code></pre> <p>And I'm enqueuing it like so:</p> <pre><code>function gdt_blocks_class_rename() { wp_enqueue_script( 'gdt-plugin-blacklist-blocks', get_stylesheet_directory_uri() . '/dist/guten-addons.js', array( 'wp-blocks' ) ); } add_action( 'enqueue_block_editor_assets', 'gdt_blocks_class_rename' ); </code></pre> <p>However, what I want to be able to do is add a class to <em>ONLY</em> list blocks? Can that be done at all?</p>
[ { "answer_id": 308044, "author": "Shibi", "author_id": 62500, "author_profile": "https://wordpress.stackexchange.com/users/62500", "pm_score": 4, "selected": false, "text": "<p>You have second and third arguments with this hook you can use the second to get the block type.</p>\n\n<p><a href=\"https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/\" rel=\"noreferrer\">https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/</a></p>\n\n<blockquote>\n <p>A filter that applies to all blocks returning a WP Element in the save\n function. This filter is used to add extra props to the root element\n of the save function. For example: to add a className, an id, or any\n valid prop for this element. <strong>It receives the current props of the save\n element, the block type and the block attributes as arguments.</strong></p>\n</blockquote>\n\n<pre><code>function addBlockClassName( props, blockType ) {\n if(blockType.name === 'core/list') {\n return Object.assign( props, { class: 'wp-block-list' } );\n }\n return props;\n}\n\nwp.hooks.addFilter(\n 'blocks.getSaveContent.extraProps',\n 'gdt-guten-plugin/add-block-class-name',\n addBlockClassName\n);\n</code></pre>\n" }, { "answer_id": 375192, "author": "MrVanilla", "author_id": 120657, "author_profile": "https://wordpress.stackexchange.com/users/120657", "pm_score": 3, "selected": true, "text": "<p>There are issues in the answer marked as correct. It will break the alignment class functionality, and is not actually adding to the classList, instead it is overriding it. And you will only be able to use that one solution for your whole theme.</p>\n<p>Instead you can use &quot;registerBlockStyle()&quot; to add a style variation to the list block, and set &quot;isDefault&quot; to true for it to use that class/style but still be able to skip using it, or add a multiple variations if you want.</p>\n<p>the wp.domReady() makes sure that it loads when it should and applies the changes</p>\n<pre><code>wp.domReady( () =&gt; {\n wp.blocks.registerBlockStyle( 'core/list', {\n name: 'custom-list-style',\n label: 'Custom list style',\n isDefault: true\n } );\n} );\n</code></pre>\n" } ]
2018/07/09
[ "https://wordpress.stackexchange.com/questions/308021", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17461/" ]
I'm trying to add a class to list blocks (`core/list`) in Gutenberg. Unfortunately, it looks like because some blocks like lists and paragraphs don't have the standard default class name of `wp-block-{name}` they can't be renamed using the [`blocks.getBlockDefaultClassName`](https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/#blocks-getblockdefaultclassname) filter. To get around that, I've used the `blocks.getSaveContent.extraProps` filter, which seems to enable me to add a class to ALL the blocks that don't already have classes. Code below is how I got that working. It's adding `added-class-name` to blocks likes lists and paragraphs and so on. ``` function addBlockClassName( className ) { return Object.assign( className, { class: 'added-class-name' } ); } wp.hooks.addFilter( 'blocks.getSaveContent.extraProps', 'gdt-guten-plugin/add-block-class-name', addBlockClassName ); ``` And I'm enqueuing it like so: ``` function gdt_blocks_class_rename() { wp_enqueue_script( 'gdt-plugin-blacklist-blocks', get_stylesheet_directory_uri() . '/dist/guten-addons.js', array( 'wp-blocks' ) ); } add_action( 'enqueue_block_editor_assets', 'gdt_blocks_class_rename' ); ``` However, what I want to be able to do is add a class to *ONLY* list blocks? Can that be done at all?
There are issues in the answer marked as correct. It will break the alignment class functionality, and is not actually adding to the classList, instead it is overriding it. And you will only be able to use that one solution for your whole theme. Instead you can use "registerBlockStyle()" to add a style variation to the list block, and set "isDefault" to true for it to use that class/style but still be able to skip using it, or add a multiple variations if you want. the wp.domReady() makes sure that it loads when it should and applies the changes ``` wp.domReady( () => { wp.blocks.registerBlockStyle( 'core/list', { name: 'custom-list-style', label: 'Custom list style', isDefault: true } ); } ); ```
308,029
<p>I want my user pay before every post publishing. I searched for some hooks that triggers before a post publishes, but all these hooks run after a post is successfully published and i don't want this. pre_post_update, publish_post, save_post and wp_insert_post are the available hooks. If there is not an action that runs before publishing post, how can i prevent publishing post is user don't pay when he wants to publish the post ?</p> <p><strong>Edit</strong>: Now i'm using this code for checking if a post is publishing, but this function is not working, i'm using this function in a custom plugin. </p> <pre><code>function af_check_payment( $new_status, $old_status, $post ) { if ( $new_status == 'publish' &amp;&amp; $old_status != 'publish' &amp;&amp; $post-&gt;post_type == 'barbershop' ) { wp_transition_post_status( 'pending', $old_status, $post ); echo 'At least i know its publishing'; } } add_action( 'transition_post_status', 'af_check_payment', 10, 3 ); </code></pre> <p>This function does not echo or change any post status. </p>
[ { "answer_id": 308044, "author": "Shibi", "author_id": 62500, "author_profile": "https://wordpress.stackexchange.com/users/62500", "pm_score": 4, "selected": false, "text": "<p>You have second and third arguments with this hook you can use the second to get the block type.</p>\n\n<p><a href=\"https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/\" rel=\"noreferrer\">https://wordpress.org/gutenberg/handbook/extensibility/extending-blocks/</a></p>\n\n<blockquote>\n <p>A filter that applies to all blocks returning a WP Element in the save\n function. This filter is used to add extra props to the root element\n of the save function. For example: to add a className, an id, or any\n valid prop for this element. <strong>It receives the current props of the save\n element, the block type and the block attributes as arguments.</strong></p>\n</blockquote>\n\n<pre><code>function addBlockClassName( props, blockType ) {\n if(blockType.name === 'core/list') {\n return Object.assign( props, { class: 'wp-block-list' } );\n }\n return props;\n}\n\nwp.hooks.addFilter(\n 'blocks.getSaveContent.extraProps',\n 'gdt-guten-plugin/add-block-class-name',\n addBlockClassName\n);\n</code></pre>\n" }, { "answer_id": 375192, "author": "MrVanilla", "author_id": 120657, "author_profile": "https://wordpress.stackexchange.com/users/120657", "pm_score": 3, "selected": true, "text": "<p>There are issues in the answer marked as correct. It will break the alignment class functionality, and is not actually adding to the classList, instead it is overriding it. And you will only be able to use that one solution for your whole theme.</p>\n<p>Instead you can use &quot;registerBlockStyle()&quot; to add a style variation to the list block, and set &quot;isDefault&quot; to true for it to use that class/style but still be able to skip using it, or add a multiple variations if you want.</p>\n<p>the wp.domReady() makes sure that it loads when it should and applies the changes</p>\n<pre><code>wp.domReady( () =&gt; {\n wp.blocks.registerBlockStyle( 'core/list', {\n name: 'custom-list-style',\n label: 'Custom list style',\n isDefault: true\n } );\n} );\n</code></pre>\n" } ]
2018/07/09
[ "https://wordpress.stackexchange.com/questions/308029", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136480/" ]
I want my user pay before every post publishing. I searched for some hooks that triggers before a post publishes, but all these hooks run after a post is successfully published and i don't want this. pre\_post\_update, publish\_post, save\_post and wp\_insert\_post are the available hooks. If there is not an action that runs before publishing post, how can i prevent publishing post is user don't pay when he wants to publish the post ? **Edit**: Now i'm using this code for checking if a post is publishing, but this function is not working, i'm using this function in a custom plugin. ``` function af_check_payment( $new_status, $old_status, $post ) { if ( $new_status == 'publish' && $old_status != 'publish' && $post->post_type == 'barbershop' ) { wp_transition_post_status( 'pending', $old_status, $post ); echo 'At least i know its publishing'; } } add_action( 'transition_post_status', 'af_check_payment', 10, 3 ); ``` This function does not echo or change any post status.
There are issues in the answer marked as correct. It will break the alignment class functionality, and is not actually adding to the classList, instead it is overriding it. And you will only be able to use that one solution for your whole theme. Instead you can use "registerBlockStyle()" to add a style variation to the list block, and set "isDefault" to true for it to use that class/style but still be able to skip using it, or add a multiple variations if you want. the wp.domReady() makes sure that it loads when it should and applies the changes ``` wp.domReady( () => { wp.blocks.registerBlockStyle( 'core/list', { name: 'custom-list-style', label: 'Custom list style', isDefault: true } ); } ); ```
308,126
<p>I am wondering whether it is possible to automatically add a class to a series of links based on the link text.</p> <p>The scenario is as follows:</p> <p>I am displaying a list of links on a page in Wordpress that link to other posts - in this case a custom post type for a schedule. The posts all have time based names, i.e. '12:23' '12:53' '13:23' and so on.</p> <p>This generates a list of links like this:</p> <pre><code>&lt;a href="departuretime/1223"&gt;12:23&lt;/a&gt; &lt;a href="departuretime/1253"&gt;12:53&lt;/a&gt; &lt;a href="departuretime/1323"&gt;13:23&lt;/a&gt; </code></pre> <p>Where each link links to a full custom post associated to display that schedule.</p> <p>I would like to format these links based on the current time and to do this I need the class to be automatically generated based on the link text.</p> <pre><code>&lt;a class='1223' href="departuretime/1223"&gt;12:23&lt;/a&gt; &lt;a class='1253' href="departuretime/1253"&gt;12:53&lt;/a&gt; &lt;a class='1323' href="departuretime/1323"&gt;13:23&lt;/a&gt; </code></pre> <p>Any help with this would be appreciated.</p>
[ { "answer_id": 308128, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>If you just want to do this for styling reasons it's not necessary to add a class, you can style based on the href attribute alone using an <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors\" rel=\"nofollow noreferrer\">attribute selector</a>. For example, to style a link where the href URL ends with <code>1253</code> you can use:</p>\n\n<pre><code>a[href$=\"1253\"] {\n color: red;\n}\n</code></pre>\n\n<p>On the off chance you have a different link that also ends in that number you could specify the styling for a link that ends in <code>1253</code> <em>and</em> starts with <code>departuretime</code>:</p>\n\n<pre><code>a[href^=\"departuretime\"][href$=\"1253\"] {\n color: red;\n}\n</code></pre>\n" }, { "answer_id": 308139, "author": "Drupalizeme", "author_id": 115005, "author_profile": "https://wordpress.stackexchange.com/users/115005", "pm_score": 1, "selected": true, "text": "<p>If I understand it correctly you want a visual indicator for departures relevant on the current time.</p>\n\n<p>One solution will be using Javascript and provide a way for the element to be identified as passed or active schedule time.</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;div id=\"myElement\"&gt;\n &lt;a href=\"https://myawesomenewsite.com/departuretime/1253\"&gt;1253&lt;/a&gt;\n &lt;a href=\"https://myawesomenewsite.com/departuretime/1255\"&gt;1255&lt;/a&gt;\n &lt;a href=\"https://myawesomenewsite.com/departuretime/0955\"&gt;0955&lt;/a&gt;\n &lt;a href=\"https://myawesomenewsite.com/departuretime/2213\"&gt;2213&lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p><strong>JAVASCRIPT</strong></p>\n\n<pre><code>// find elements\nvar rootElements = $(\"#myElement a\");\n\nrootElements.each(function(index, item){\n\n var url = item.href,\n arr_split = url.split(\"/\"),\n arr_index = arr_split.length-1,\n departureTime = arr_split[arr_index],\n date = new Date(),\n myTime = date.getHours()+''+date.getMinutes();\n\n //add your class like this\n item.classList.add(myTime);\n\n //but you can also spice it up a bit\nif(departureTime&gt;myTime){\n item.classList.add(\"you_have_time\");\n}else{\n item.classList.add(\"you_dont_have_time\");\n}\n\n});\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>.you_have_time{\n color:green;\n}\n\n.you_dont_have_time{\n color:red;\n}\n</code></pre>\n\n<p>And ofcourse the <a href=\"https://jsfiddle.net/pq4Lxug6/1/\" rel=\"nofollow noreferrer\">jsfiddle</a></p>\n" } ]
2018/07/10
[ "https://wordpress.stackexchange.com/questions/308126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146666/" ]
I am wondering whether it is possible to automatically add a class to a series of links based on the link text. The scenario is as follows: I am displaying a list of links on a page in Wordpress that link to other posts - in this case a custom post type for a schedule. The posts all have time based names, i.e. '12:23' '12:53' '13:23' and so on. This generates a list of links like this: ``` <a href="departuretime/1223">12:23</a> <a href="departuretime/1253">12:53</a> <a href="departuretime/1323">13:23</a> ``` Where each link links to a full custom post associated to display that schedule. I would like to format these links based on the current time and to do this I need the class to be automatically generated based on the link text. ``` <a class='1223' href="departuretime/1223">12:23</a> <a class='1253' href="departuretime/1253">12:53</a> <a class='1323' href="departuretime/1323">13:23</a> ``` Any help with this would be appreciated.
If I understand it correctly you want a visual indicator for departures relevant on the current time. One solution will be using Javascript and provide a way for the element to be identified as passed or active schedule time. **HTML** ``` <div id="myElement"> <a href="https://myawesomenewsite.com/departuretime/1253">1253</a> <a href="https://myawesomenewsite.com/departuretime/1255">1255</a> <a href="https://myawesomenewsite.com/departuretime/0955">0955</a> <a href="https://myawesomenewsite.com/departuretime/2213">2213</a> </div> ``` **JAVASCRIPT** ``` // find elements var rootElements = $("#myElement a"); rootElements.each(function(index, item){ var url = item.href, arr_split = url.split("/"), arr_index = arr_split.length-1, departureTime = arr_split[arr_index], date = new Date(), myTime = date.getHours()+''+date.getMinutes(); //add your class like this item.classList.add(myTime); //but you can also spice it up a bit if(departureTime>myTime){ item.classList.add("you_have_time"); }else{ item.classList.add("you_dont_have_time"); } }); ``` **CSS** ``` .you_have_time{ color:green; } .you_dont_have_time{ color:red; } ``` And ofcourse the [jsfiddle](https://jsfiddle.net/pq4Lxug6/1/)
308,150
<p>I want to create an Autocomplete function in WordPress. I want a search field from where <strong>username</strong> can be searched. I am using following JQuery UI. </p> <pre><code>&lt;label&gt;Users&lt;/label&gt; &lt;input type="text" name="user_name" id="user-name" /&gt; &lt;?php $get_arr_user = array('John', 'Rogers', 'Paul', 'Amanda', 'Peter'); ?&gt; &lt;script&gt; jQuery(document).ready(function($) { var availableTags = &lt;?php echo json_encode($get_arr_user); ?&gt;; $( "#user-name" ).autocomplete({ source: availableTags }); }); &lt;/script&gt; </code></pre> <p>My problem is that I am not able to get the list of <strong>Usernames</strong> in this format - <code>array('John', 'Rogers', 'Paul', 'Amanda', 'Peter');</code> How do I get that?</p>
[ { "answer_id": 308153, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow noreferrer\"><code>get_users</code></a> function will give you an array of user objects, from which you can extract an array of user names. Like this:</p>\n\n<pre><code>$args = array(); // define in case you want not all users but a selection\n$users = get_users( $args );\n$user_names = array();\nforeach ( $users as $user ) {\n $user_names[] = $user-&gt;user_login;\n}\n</code></pre>\n\n<p>Now <code>$user_names</code> is an array with login names. You can, off course, also use <code>user_nicename</code>, <code>last_name</code>, or whatever info is available in the <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow noreferrer\"><code>wp_user</code></a> object</p>\n" }, { "answer_id": 308154, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 2, "selected": false, "text": "<p>Look at <code>get_users()</code> function.</p>\n\n<pre><code>&lt;?php\n\n$users = get_users();\n\nforeach( $users as $user ) {\n // get user names from the object and add them to the array\n $get_arr_user[] = $user-&gt;display_name;\n}\n</code></pre>\n\n<p>And you'll get the array similar to following:</p>\n\n<pre><code>Array\n(\n [0] =&gt; John Doe\n [1] =&gt; Jane Doe\n [2] =&gt; Baby Doe\n)\n</code></pre>\n\n<p>I'm pretty sure you'll want to exclude admins, order names and so on. So, look at the <a href=\"https://codex.wordpress.org/Function_Reference/get_users\" rel=\"nofollow noreferrer\">documentation</a> to find out more <code>get_users()</code> arguments.</p>\n" }, { "answer_id": 308155, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 5, "selected": true, "text": "<p>The other answers are correct, but it's possible to achive the same thing with less code using <a href=\"https://codex.wordpress.org/Function_Reference/wp_list_pluck\" rel=\"noreferrer\"><code>wp_list_pluck()</code></a>:</p>\n\n<pre><code>$users = get_users();\n$user_names = wp_list_pluck( $users, 'display_name' );\n</code></pre>\n\n<p><code>wp_list_pluck()</code> used that way will get the <code>display_name</code> field of all the users in an array without needing to do a loop.</p>\n" } ]
2018/07/10
[ "https://wordpress.stackexchange.com/questions/308150", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124069/" ]
I want to create an Autocomplete function in WordPress. I want a search field from where **username** can be searched. I am using following JQuery UI. ``` <label>Users</label> <input type="text" name="user_name" id="user-name" /> <?php $get_arr_user = array('John', 'Rogers', 'Paul', 'Amanda', 'Peter'); ?> <script> jQuery(document).ready(function($) { var availableTags = <?php echo json_encode($get_arr_user); ?>; $( "#user-name" ).autocomplete({ source: availableTags }); }); </script> ``` My problem is that I am not able to get the list of **Usernames** in this format - `array('John', 'Rogers', 'Paul', 'Amanda', 'Peter');` How do I get that?
The other answers are correct, but it's possible to achive the same thing with less code using [`wp_list_pluck()`](https://codex.wordpress.org/Function_Reference/wp_list_pluck): ``` $users = get_users(); $user_names = wp_list_pluck( $users, 'display_name' ); ``` `wp_list_pluck()` used that way will get the `display_name` field of all the users in an array without needing to do a loop.
308,162
<p>I am using bootstrap to layout a simple webpage. I have also add some css (<code>@media (min-width: 1920px) {..}</code>) media queries which I use for different resolutions</p> <p>Now I hope WP has a hook which checks the media resolution so I can trim with more characters/words.</p> <pre><code>&lt;?php echo wp_trim_words(get_the_content(), 40, '...'); ?&gt; </code></pre> <p>vs</p> <pre><code> &lt;?php echo wp_trim_words(get_the_content(), 70, '...'); ?&gt; </code></pre> <p>In short, how can I output different text length based on browser resolutions?</p>
[ { "answer_id": 308165, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 0, "selected": false, "text": "<p>One way to find out if a specific function has hooks is to look it up on the <a href=\"https://developer.wordpress.org/reference/\" rel=\"nofollow noreferrer\">WordPress Code Reference</a>, usually just entering the function name and checkmark \"Hooks\". This will either take you directly to the <a href=\"https://developer.wordpress.org/reference/hooks/wp_trim_words/\" rel=\"nofollow noreferrer\">hook of the same name</a> or bring up a list of hooks that match the request.</p>\n\n<p>Additionally, you may go to <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/\" rel=\"nofollow noreferrer\">the function itself</a> by using the same method above and checkmark \"Function\". By navigating down the the <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_words/#source\" rel=\"nofollow noreferrer\">#Source section</a> you can click the <code>Expand full source code</code> link which will reveal the entire function and you can look through it for any hooks it may have.</p>\n\n<p>Finally, you wouldn't use PHP to check the browsers resolution, if you really need to do something like that you should be using Javascript or CSS (overflow: hidden?) but I wouldn't recommend doing something like that.</p>\n" }, { "answer_id": 308166, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>Browser resolution is set on the user end. Actually, the window may even be resized after the page has been loaded. Css media queries will deal with that on the user end.</p>\n\n<p>So, when the page is generated on the server side, the user window size is unknown and you cannot determine how many words to serve at that point. It has to be done on the user end.</p>\n\n<p>The easiest approach would be to include the longest excerpt and wrap the last 30 words in <code>&lt;span&gt;</code> tags, which you hide using css on smaller screens.</p>\n\n<p>A more complicated approach would be to detect screen size using jquery and then call the <a href=\"https://developer.wordpress.org/rest-api/\" rel=\"nofollow noreferrer\">rest api</a> to retrieve the relevant excerpt.</p>\n" }, { "answer_id": 308175, "author": "Den Isahac", "author_id": 113233, "author_profile": "https://wordpress.stackexchange.com/users/113233", "pm_score": -1, "selected": false, "text": "<p>Checking the browser resolution is done thru Javascript or in your case bootstrap has different media breakpoints which you can use to hide/show different length of excerpt</p>\n\n<h3>1. For small devices (landscape phones, 576px and up)</h3>\n\n<p><strong><code>@media (min-width: 576px) { ... }</code></strong></p>\n\n<pre><code>&lt;span class=\"d-none d-sm-block d-md-none\"&gt;\n &lt;?php echo wp_trim_words(get_the_content(), 40, '...'); ?&gt;\n&lt;/span&gt;\n</code></pre>\n\n<h3>2. For medium devices (tablets, 768px and up)</h3>\n\n<p><strong><code>@media (min-width: 768px) { ... }</code></strong></p>\n\n<pre><code>&lt;span class=\"d-none d-md-block d-lg-none\"&gt;\n &lt;?php echo wp_trim_words(get_the_content(), 50, '...'); ?&gt;\n&lt;/span&gt;\n</code></pre>\n\n<h3>3. For large devices (desktops, 992px and up)</h3>\n\n<p><strong><code>@media (min-width: 992px) { ... }</code></strong></p>\n\n<pre><code>&lt;span class=\"d-none d-lg-block d-xl-none\"&gt;\n &lt;?php echo wp_trim_words(get_the_content(), 60, '...'); ?&gt;\n&lt;/span&gt;\n</code></pre>\n\n<h3>4. For extra large devices (large desktops, 1200px and up)</h3>\n\n<p><strong><code>@media (min-width: 1200px) { ... }</code></strong></p>\n\n<pre><code>&lt;span class=\"d-none d-xl-block\"&gt;\n &lt;?php echo wp_trim_words(get_the_content(), 70, '...'); ?&gt;\n&lt;/span&gt;\n</code></pre>\n" } ]
2018/07/10
[ "https://wordpress.stackexchange.com/questions/308162", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9936/" ]
I am using bootstrap to layout a simple webpage. I have also add some css (`@media (min-width: 1920px) {..}`) media queries which I use for different resolutions Now I hope WP has a hook which checks the media resolution so I can trim with more characters/words. ``` <?php echo wp_trim_words(get_the_content(), 40, '...'); ?> ``` vs ``` <?php echo wp_trim_words(get_the_content(), 70, '...'); ?> ``` In short, how can I output different text length based on browser resolutions?
Browser resolution is set on the user end. Actually, the window may even be resized after the page has been loaded. Css media queries will deal with that on the user end. So, when the page is generated on the server side, the user window size is unknown and you cannot determine how many words to serve at that point. It has to be done on the user end. The easiest approach would be to include the longest excerpt and wrap the last 30 words in `<span>` tags, which you hide using css on smaller screens. A more complicated approach would be to detect screen size using jquery and then call the [rest api](https://developer.wordpress.org/rest-api/) to retrieve the relevant excerpt.
308,164
<p>How to remove elementor from wordpress admin menu. I have tried below option but it didnt work.</p> <pre><code>add_action( 'admin_menu', 'my_remove_menu_pages' ); function my_remove_menu_pages() { remove_menu_page( 'edit.php?post_type=elementor_library' ); //Elementor }; </code></pre>
[ { "answer_id": 308176, "author": "Amit Jugran", "author_id": 135161, "author_profile": "https://wordpress.stackexchange.com/users/135161", "pm_score": 0, "selected": false, "text": "<p>I have been able to do it using <code>'admin_init'</code> action. The correct code is below</p>\n\n<pre><code>add_action( 'admin_init', 'my_remove_menu_pages' );\nfunction my_remove_menu_pages() {\n\nglobal $user_ID;\n\nif ( current_user_can( 'subscriber' ) ) \n{\nremove_menu_page( 'edit.php?post_type=elementor_library' );\nremove_menu_page( 'elementor' );\n}\n}\n</code></pre>\n\n<p>However, I am not able to restrict it for a specific user role. The above code restricts it for all user roles, including admin.</p>\n\n<p>I am using a multisite install. so if anyone knows to restrict it for a user role on multisite install, please add the necessary bit of code.</p>\n\n<p>Thanks.</p>\n" }, { "answer_id": 314444, "author": "Marcos Goveia", "author_id": 150779, "author_profile": "https://wordpress.stackexchange.com/users/150779", "pm_score": -1, "selected": false, "text": "<p>This code works for admins only.</p>\n\n<pre><code>add_action( 'admin_init', 'my_remove_menu_pages' );\nfunction my_remove_menu_pages($query) {\n $current_user = wp_get_current_user();\n if($current_user-&gt;ID == 1) //Aqui é o meu ID. Vai ocultar a página pra todos menos pra esse ID\n return $query;\nremove_menu_page( 'edit.php?post_type=elementor_library' );\nremove_menu_page( 'elementor' );\n}\n</code></pre>\n" }, { "answer_id": 351658, "author": "aronmoshe_m", "author_id": 160880, "author_profile": "https://wordpress.stackexchange.com/users/160880", "pm_score": 2, "selected": false, "text": "<p>This would work for editors. You can swap the role in and out depending on which role you are trying to target (e.g., <code>editor</code>, <code>subscriber</code>, etc.). This would go in <code>functions.php</code> of your child theme.</p>\n\n<pre><code>function remove_menus(){\n// get current login user's role\n$roles = wp_get_current_user()-&gt;roles;\n\n// test role\nif( !in_array('editor',$roles)){\nreturn;\n}\n\n//remove menu from site backend.\nremove_menu_page( 'edit.php?post_type=elementor_library' ); // Elementor Templates\nremove_menu_page( 'elementor' ); // Elementor\n}\nadd_action( 'admin_menu', 'remove_menus' , 100 );\n</code></pre>\n" } ]
2018/07/10
[ "https://wordpress.stackexchange.com/questions/308164", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135161/" ]
How to remove elementor from wordpress admin menu. I have tried below option but it didnt work. ``` add_action( 'admin_menu', 'my_remove_menu_pages' ); function my_remove_menu_pages() { remove_menu_page( 'edit.php?post_type=elementor_library' ); //Elementor }; ```
This would work for editors. You can swap the role in and out depending on which role you are trying to target (e.g., `editor`, `subscriber`, etc.). This would go in `functions.php` of your child theme. ``` function remove_menus(){ // get current login user's role $roles = wp_get_current_user()->roles; // test role if( !in_array('editor',$roles)){ return; } //remove menu from site backend. remove_menu_page( 'edit.php?post_type=elementor_library' ); // Elementor Templates remove_menu_page( 'elementor' ); // Elementor } add_action( 'admin_menu', 'remove_menus' , 100 ); ```
308,236
<p>Is there any way to change the order of filters for e.g. the_content before they are applied? What I currently have is the following ideas:</p> <pre><code>/** * Print all filters for some hook. */ function print_filters_for( $hook = '' ) { global $wp_filter; if( empty( $hook ) || !isset( $wp_filter[$hook] ) ) return; print '&lt;pre&gt;'; print_r( $wp_filter[$hook] ); print '&lt;/pre&gt;'; } add_action('template_redirect','print_filters'); function print_filters() { print_r(print_filters_for('the_content'));die; } </code></pre> <p>This gives me the filters, but I can not think of any comfortable way to change their priorities.</p> <pre><code>add_filter( 'the_content', 'my_content_filter_priority_reorder', 0 ); function my_content_filter_priority_reorder($the_content) { // reorder filter priorities return $the_content; } </code></pre> <p>Has anybody already had this problem and knows how to possibly change this?</p>
[ { "answer_id": 308242, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>If you know the existing callback and priority you can just remove the filters and then add again at a different priority:</p>\n\n<pre><code>remove_filter( 'the_content', 'convert_smilies', 20 );\nadd_filter( 'the_content', 'convert_smilies', 30 );\n\nremove_filter( 'the_content', 'capital_P_dangit', 11 );\nadd_filter( 'the_content', 'capital_P_dangit', 20 );\n</code></pre>\n" }, { "answer_id": 398001, "author": "Sergio Zaharchenko", "author_id": 136533, "author_profile": "https://wordpress.stackexchange.com/users/136533", "pm_score": 0, "selected": false, "text": "<p>If you try to change the priority of the plain function, using <code>remove_filter()</code> =&gt; <code>add_filter()</code> pattern is okay. But if you try to change it for method callback, it might be a pain since you need to somehow get an object of this method. And in a lot of cases, it's impossible.</p>\n<p>I mean cases when the filter is created this way:</p>\n<pre><code>add_filter( 'the_content', array( $this, 'change_content' ) );\n</code></pre>\n<p>For such cases, it's better to change it manually by updating the <code>$wp_filter</code> variable.</p>\n<p>Here is a function for it:</p>\n<pre><code> /**\n * Changes the filter priority.\n *\n * @param string $hook_name\n * @param string $function_name Either function or method name\n * @param int $new_priority\n *\n * @return bool If it's changed correctly or not.\n */\n function change_filter_priority( $hook_name, $function_name, $new_priority ) {\n global $wp_filter;\n\n if ( empty( $wp_filter[ $hook_name ] ) ) {\n return false;\n }\n\n $hook = $wp_filter[ $hook_name ];\n\n foreach ( $hook-&gt;callbacks as $priority =&gt; $callbacks ) {\n foreach ( $callbacks as $callback_id =&gt; $callback ) {\n $current_function = $callback['function'];\n if ( is_array( $current_function ) ) { // case it's a function in the class.\n $current_function = $current_function[1];\n }\n\n if ( $function_name === $current_function ) {\n if ( $new_priority != $priority ) {\n $priority_existed = isset( $hook-&gt;callbacks[ $new_priority ] );\n $hook-&gt;callbacks[ $new_priority ][ $callback_id ] = $hook-&gt;callbacks[ $priority ][ $callback_id ];\n unset( $hook-&gt;callbacks[ $priority ][ $callback_id ] );\n if ( ! $priority_existed ) {\n ksort( $hook-&gt;callbacks, SORT_NUMERIC );\n }\n\n return true;\n }\n }\n }\n }\n\n return false;\n}\n</code></pre>\n<p>Usage example:</p>\n<pre><code>class My_Class {\n public function __construct() {\n add_filter( 'the_content', array( $this, 'change_content' ), 10 );\n }\n\n public function change_content() {\n return 'Hello World!';\n }\n}\n\nnew My_Class();\n\nchange_filter_priority( 'the_content', 'change_content', 11 );\n</code></pre>\n" } ]
2018/07/11
[ "https://wordpress.stackexchange.com/questions/308236", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12035/" ]
Is there any way to change the order of filters for e.g. the\_content before they are applied? What I currently have is the following ideas: ``` /** * Print all filters for some hook. */ function print_filters_for( $hook = '' ) { global $wp_filter; if( empty( $hook ) || !isset( $wp_filter[$hook] ) ) return; print '<pre>'; print_r( $wp_filter[$hook] ); print '</pre>'; } add_action('template_redirect','print_filters'); function print_filters() { print_r(print_filters_for('the_content'));die; } ``` This gives me the filters, but I can not think of any comfortable way to change their priorities. ``` add_filter( 'the_content', 'my_content_filter_priority_reorder', 0 ); function my_content_filter_priority_reorder($the_content) { // reorder filter priorities return $the_content; } ``` Has anybody already had this problem and knows how to possibly change this?
If you know the existing callback and priority you can just remove the filters and then add again at a different priority: ``` remove_filter( 'the_content', 'convert_smilies', 20 ); add_filter( 'the_content', 'convert_smilies', 30 ); remove_filter( 'the_content', 'capital_P_dangit', 11 ); add_filter( 'the_content', 'capital_P_dangit', 20 ); ```
308,271
<p>There is a site with WordPress installed and a theme selected. I have created an HTML page for the site, but it wasn't looking well with the theme. So, I want to put the page on the site without any theme, and just the way I wrote the code, without disabling the theme from any other pages.</p> <p>Is there an easy way to do it without messing with the theme? And if there isn't, then I am willing to modify theme files, but how should I go about it? </p>
[ { "answer_id": 308272, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 4, "selected": true, "text": "<p>There is, in fact, a way to do it without messing with the theme, let's say your WordPress is on <code>public_html/your_site</code>, now you want to create an HTML page that is on <code>your_site.com/mypage</code>, so instead of creating a page or post called <code>mypage</code> on your WordPress dashboard you are going to create a <strong>mypage.html</strong> and upload it to <code>public_html/your_site</code>, in case you want to get rid of the .html you can simply hide it from your <strong>.htaccess</strong> doing something like:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteRule ^([^\\.]+)$ $1.html [NC,L]\n</code></pre>\n\n<p>Keep in mind any tracking code you have on your WordPress, for example, Google Analytics, if you are using things like that you will have to add those codes to your HTML page as well.</p>\n" }, { "answer_id": 308273, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 2, "selected": false, "text": "<p>Just make a directory on the highest level and put your html file there. If you call it directly, you will bypass WordPress. Beware that this also means the file won't be found using WP's search function. Basically, for WP, it will be an external page.</p>\n" } ]
2018/07/11
[ "https://wordpress.stackexchange.com/questions/308271", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146759/" ]
There is a site with WordPress installed and a theme selected. I have created an HTML page for the site, but it wasn't looking well with the theme. So, I want to put the page on the site without any theme, and just the way I wrote the code, without disabling the theme from any other pages. Is there an easy way to do it without messing with the theme? And if there isn't, then I am willing to modify theme files, but how should I go about it?
There is, in fact, a way to do it without messing with the theme, let's say your WordPress is on `public_html/your_site`, now you want to create an HTML page that is on `your_site.com/mypage`, so instead of creating a page or post called `mypage` on your WordPress dashboard you are going to create a **mypage.html** and upload it to `public_html/your_site`, in case you want to get rid of the .html you can simply hide it from your **.htaccess** doing something like: ``` RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+)$ $1.html [NC,L] ``` Keep in mind any tracking code you have on your WordPress, for example, Google Analytics, if you are using things like that you will have to add those codes to your HTML page as well.
308,291
<p>I discovered after much painful debugging that requests to the the WP HTTP API (in this case, though <code>wp_remote_request()</code>) always ended up as <code>GET</code> method after being redirected, even if the method was something else in the initial request (in my case <code>PURGE</code> as used by the <a href="https://wordpress.org/plugins/varnish-http-purge/" rel="nofollow noreferrer">Varnish HTTP Purge plugin</a>)</p> <p>Normally this would apply to <code>POST</code> requests, where redirecting to a <code>GET</code> request of the same URL means completely obliterating the data being sent with the <code>POST</code>. In my case, using <code>PURGE</code> the outcome was that Apache was loading the actual URLs I was trying to purge, which wasn't what I wanted. </p> <p>The point being: Pretty much never will you want this to happen. Whatever method you use to send a request, you surely want that method to be used in the end. This behavior is confusing and annoying and will probably be experienced as inexplicable bugginess for most users (in my case, the bug took me years to track down, and had been slowing down my local dev site where I don't have Varnish installed). </p> <p>I'm posting this question so I can answer it myself in hopes people find it using Google in the future. The point is to be <strong>aware</strong> of this behavior so that if it is happening to you you can just find a way around it. </p>
[ { "answer_id": 308292, "author": "jerclarke", "author_id": 175, "author_profile": "https://wordpress.stackexchange.com/users/175", "pm_score": 1, "selected": true, "text": "<p>It turns out that as part of <code>class-request-&gt;parse_response()</code>, where redirections are handled for the various higher-level request functions (this is where it does the recursive requests for each subsequent hop) there's a weird hook thing that ends up running <code>WP_Http-&gt;browser_redirect_compatibility()</code> on the redirected request. </p>\n\n<p><code>browser_redirect_compatibility()</code> is pretty simple:</p>\n\n<pre><code>public static function browser_redirect_compatibility( $location, $headers, $data, &amp;$options, $original ) {\n // Browser compat\n if ( $original-&gt;status_code === 302 ) {\n $options['type'] = Requests::GET;\n }\n }\n</code></pre>\n\n<p>Basically, it just obliterates the method you chose as soon as theres a 302 redirection, replacing it with <code>GET</code>. They seem to assume they are converting a <code>POST</code> request, but as is clear from reading it, this will apply to ANY method other than <code>GET</code> which ends up being a 302. </p>\n\n<p>Notably though, this <strong>DOESN'T</strong> have any effect on 301 redirects, and seems to be related to an underlying crappiness of 302 as an error. You can read more about 302 and it's problems in [this previous question about a similar problem with <code>POST</code> requests getting converted to GET and losing their data](\n<a href=\"https://wordpress.stackexchange.com/questions/87515/temporary-redirect-prevents-getting-post-array/87528#87528\">Temporary redirect prevents getting $_POST array</a>)</p>\n\n<h2>Affects Apache but not Nginx?</h2>\n\n<p>This seems relevant: My local dev environment uses MAMP and the sites is hosted through Apache, and this insane problem is triggered. </p>\n\n<p>Our live site uses a Nginx->Varnish->Nginx setup, where for whatever reason, the same redirects were never <code>302</code> at all, but instead were <code>301</code> and thus worked correctly (they stayed as <code>PURGE</code> at the redirected location, which was the <code>https</code> version of the URL, rather than the <code>http</code> version).</p>\n\n<h2>So my recommendtaions to anyone having this problem:</h2>\n\n<ul>\n<li>Switch to Nginx completely as it seems to not use 302 for such redirects. Apache sux.</li>\n<li>Look for sources of 302 errors and reconfigure your server to use 301 instead</li>\n<li>Look for ways to avoid triggering redirects in the first place! (in our case, making sure the URLs were already <code>https</code> to start is an obvious improvement and will make our logs cleaner)</li>\n</ul>\n" }, { "answer_id": 308295, "author": "Danila Vershinin", "author_id": 93706, "author_profile": "https://wordpress.stackexchange.com/users/93706", "pm_score": 1, "selected": false, "text": "<p>The change of method to <code>GET</code> after redirect from <code>POST</code>, <code>PURGE</code>, <code>BAN</code> whatever, is perfectly legal and been there, and will be without Wordpress (it has nothing to do with it, really). Welcome to the <a href=\"https://www.rfc-editor.org/rfc/rfc7231#section-6.4.3\" rel=\"nofollow noreferrer\">World Wide Web</a>:</p>\n<blockquote>\n<p>Note: For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.</p>\n</blockquote>\n<p>As a matter of rule, don't expect a method to be kept after redirect, unless you're able to modify the client software to do so.</p>\n" } ]
2018/07/11
[ "https://wordpress.stackexchange.com/questions/308291", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/175/" ]
I discovered after much painful debugging that requests to the the WP HTTP API (in this case, though `wp_remote_request()`) always ended up as `GET` method after being redirected, even if the method was something else in the initial request (in my case `PURGE` as used by the [Varnish HTTP Purge plugin](https://wordpress.org/plugins/varnish-http-purge/)) Normally this would apply to `POST` requests, where redirecting to a `GET` request of the same URL means completely obliterating the data being sent with the `POST`. In my case, using `PURGE` the outcome was that Apache was loading the actual URLs I was trying to purge, which wasn't what I wanted. The point being: Pretty much never will you want this to happen. Whatever method you use to send a request, you surely want that method to be used in the end. This behavior is confusing and annoying and will probably be experienced as inexplicable bugginess for most users (in my case, the bug took me years to track down, and had been slowing down my local dev site where I don't have Varnish installed). I'm posting this question so I can answer it myself in hopes people find it using Google in the future. The point is to be **aware** of this behavior so that if it is happening to you you can just find a way around it.
It turns out that as part of `class-request->parse_response()`, where redirections are handled for the various higher-level request functions (this is where it does the recursive requests for each subsequent hop) there's a weird hook thing that ends up running `WP_Http->browser_redirect_compatibility()` on the redirected request. `browser_redirect_compatibility()` is pretty simple: ``` public static function browser_redirect_compatibility( $location, $headers, $data, &$options, $original ) { // Browser compat if ( $original->status_code === 302 ) { $options['type'] = Requests::GET; } } ``` Basically, it just obliterates the method you chose as soon as theres a 302 redirection, replacing it with `GET`. They seem to assume they are converting a `POST` request, but as is clear from reading it, this will apply to ANY method other than `GET` which ends up being a 302. Notably though, this **DOESN'T** have any effect on 301 redirects, and seems to be related to an underlying crappiness of 302 as an error. You can read more about 302 and it's problems in [this previous question about a similar problem with `POST` requests getting converted to GET and losing their data]( [Temporary redirect prevents getting $\_POST array](https://wordpress.stackexchange.com/questions/87515/temporary-redirect-prevents-getting-post-array/87528#87528)) Affects Apache but not Nginx? ----------------------------- This seems relevant: My local dev environment uses MAMP and the sites is hosted through Apache, and this insane problem is triggered. Our live site uses a Nginx->Varnish->Nginx setup, where for whatever reason, the same redirects were never `302` at all, but instead were `301` and thus worked correctly (they stayed as `PURGE` at the redirected location, which was the `https` version of the URL, rather than the `http` version). So my recommendtaions to anyone having this problem: ---------------------------------------------------- * Switch to Nginx completely as it seems to not use 302 for such redirects. Apache sux. * Look for sources of 302 errors and reconfigure your server to use 301 instead * Look for ways to avoid triggering redirects in the first place! (in our case, making sure the URLs were already `https` to start is an obvious improvement and will make our logs cleaner)
308,301
<p>I am creating a plugin that generates a theme, and so I want to have a checkbox at the end of the theme generation process that gives the possibility to activate the freshly created theme without having to do it manually. Is there any function that can do that?</p>
[ { "answer_id": 308302, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 1, "selected": false, "text": "<p>The only thing that comes to my mind is to do it from the database, so basically after you check the checkbox status, you will have to select the <code>wp_options</code> table, you will need to locate two rows <strong>template</strong> and <strong>stylesheet</strong>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ohCUL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ohCUL.png\" alt=\"enter image description here\"></a></p>\n\n<p>Then you will have to update <code>alexandria</code> for <code>youThemeName</code>. That query will look like this:</p>\n\n<pre><code>$query = \"UPDATE wp_options SET option_value='youThemeName' WHERE option_name='template' OR option_name='stylesheet';\";\n$wpdb-&gt;query($query);\n</code></pre>\n" }, { "answer_id": 308321, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>Of course there’s a function for that (<a href=\"https://codex.wordpress.org/Function_Reference/switch_theme\" rel=\"nofollow noreferrer\">Codex</a>):</p>\n\n<pre><code>switch_theme( $stylesheet )\n</code></pre>\n\n<p>It:</p>\n\n<blockquote>\n <p>Switches current theme to new template and stylesheet names. Accepts\n one argument: $stylesheet of the theme. ($stylesheet is the name of\n your folder slug. It's the same value that you'd use for a child\n theme, something like <code>twentythirteen</code>.) It also accepts an additional\n function signature of two arguments: $template then $stylesheet. This\n is for backwards compatibility.</p>\n</blockquote>\n\n<p>And why is that any better? WordPress uses filters and actions for many things. For example, when you switch the theme, the unused widgets will get saved, so you can restore them in new sidebars... All of that won’t be done, if you switch the theme directly in DB.</p>\n" } ]
2018/07/11
[ "https://wordpress.stackexchange.com/questions/308301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146776/" ]
I am creating a plugin that generates a theme, and so I want to have a checkbox at the end of the theme generation process that gives the possibility to activate the freshly created theme without having to do it manually. Is there any function that can do that?
Of course there’s a function for that ([Codex](https://codex.wordpress.org/Function_Reference/switch_theme)): ``` switch_theme( $stylesheet ) ``` It: > > Switches current theme to new template and stylesheet names. Accepts > one argument: $stylesheet of the theme. ($stylesheet is the name of > your folder slug. It's the same value that you'd use for a child > theme, something like `twentythirteen`.) It also accepts an additional > function signature of two arguments: $template then $stylesheet. This > is for backwards compatibility. > > > And why is that any better? WordPress uses filters and actions for many things. For example, when you switch the theme, the unused widgets will get saved, so you can restore them in new sidebars... All of that won’t be done, if you switch the theme directly in DB.
308,361
<p>I have a running site (Site A).</p> <p>I want to re-write the site fully to improve everything but, when I'm finished, I don't want to have to get everyone to sign up to the new site.</p> <p>I wondered if I could create an entirely new site on a different domain (Site B) with a clean install of Wordpress - and then when I'm finished developing the site copy over the following tables from Site A to Site B: wp_options wp_users wp_usermeta</p> <p>And would all my existing users then have full access to Site B (the new site) ?</p> <p>Or is there more to it than this?</p> <p>Thanks</p>
[ { "answer_id": 308302, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 1, "selected": false, "text": "<p>The only thing that comes to my mind is to do it from the database, so basically after you check the checkbox status, you will have to select the <code>wp_options</code> table, you will need to locate two rows <strong>template</strong> and <strong>stylesheet</strong>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ohCUL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ohCUL.png\" alt=\"enter image description here\"></a></p>\n\n<p>Then you will have to update <code>alexandria</code> for <code>youThemeName</code>. That query will look like this:</p>\n\n<pre><code>$query = \"UPDATE wp_options SET option_value='youThemeName' WHERE option_name='template' OR option_name='stylesheet';\";\n$wpdb-&gt;query($query);\n</code></pre>\n" }, { "answer_id": 308321, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>Of course there’s a function for that (<a href=\"https://codex.wordpress.org/Function_Reference/switch_theme\" rel=\"nofollow noreferrer\">Codex</a>):</p>\n\n<pre><code>switch_theme( $stylesheet )\n</code></pre>\n\n<p>It:</p>\n\n<blockquote>\n <p>Switches current theme to new template and stylesheet names. Accepts\n one argument: $stylesheet of the theme. ($stylesheet is the name of\n your folder slug. It's the same value that you'd use for a child\n theme, something like <code>twentythirteen</code>.) It also accepts an additional\n function signature of two arguments: $template then $stylesheet. This\n is for backwards compatibility.</p>\n</blockquote>\n\n<p>And why is that any better? WordPress uses filters and actions for many things. For example, when you switch the theme, the unused widgets will get saved, so you can restore them in new sidebars... All of that won’t be done, if you switch the theme directly in DB.</p>\n" } ]
2018/07/12
[ "https://wordpress.stackexchange.com/questions/308361", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39292/" ]
I have a running site (Site A). I want to re-write the site fully to improve everything but, when I'm finished, I don't want to have to get everyone to sign up to the new site. I wondered if I could create an entirely new site on a different domain (Site B) with a clean install of Wordpress - and then when I'm finished developing the site copy over the following tables from Site A to Site B: wp\_options wp\_users wp\_usermeta And would all my existing users then have full access to Site B (the new site) ? Or is there more to it than this? Thanks
Of course there’s a function for that ([Codex](https://codex.wordpress.org/Function_Reference/switch_theme)): ``` switch_theme( $stylesheet ) ``` It: > > Switches current theme to new template and stylesheet names. Accepts > one argument: $stylesheet of the theme. ($stylesheet is the name of > your folder slug. It's the same value that you'd use for a child > theme, something like `twentythirteen`.) It also accepts an additional > function signature of two arguments: $template then $stylesheet. This > is for backwards compatibility. > > > And why is that any better? WordPress uses filters and actions for many things. For example, when you switch the theme, the unused widgets will get saved, so you can restore them in new sidebars... All of that won’t be done, if you switch the theme directly in DB.
308,433
<p>I am creating a comparison table and the issue is in while loop i am not able to put the <code>"tr"</code> in proper place. I need layout like this</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;post title 1&lt;/td&gt; &lt;td&gt;post title 2&lt;/td&gt; &lt;td&gt;post title 3&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;post content 1&lt;/td&gt; &lt;td&gt;post content 2&lt;/td&gt; &lt;td&gt;post content 3&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;post author 1&lt;/td&gt; &lt;td&gt;post author 2&lt;/td&gt; &lt;td&gt;post author 3&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>How can i achieve that it's seems like no option see my code below</p> <pre><code>&lt;div class="acadp"&gt; &lt;table&gt; &lt;tr&gt; &lt;?php while( $acadp_query-&gt;have_posts() ) : $acadp_query-&gt;the_post(); ?&gt; &lt;td&gt;&lt;?php the_title(); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php the_content(); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php the_author(); ?&gt;&lt;/td&gt; &lt;?php endwhile; ?&gt; &lt;tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 308434, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>You need 3 separate loops. One for each row, with each post creating a new column:</p>\n\n<pre><code>&lt;div class=\"acadp\"&gt;\n &lt;table&gt;\n &lt;tr&gt;\n &lt;?php while( $acadp_query-&gt;have_posts() ) : $acadp_query-&gt;the_post(); ?&gt;\n &lt;td&gt;&lt;?php the_title(); ?&gt;&lt;/td&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/tr&gt;\n\n &lt;tr&gt;\n &lt;?php while( $acadp_query-&gt;have_posts() ) : $acadp_query-&gt;the_post(); ?&gt;\n &lt;td&gt;&lt;?php the_content(); ?&gt;&lt;/td&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/tr&gt;\n\n &lt;tr&gt;\n &lt;?php while( $acadp_query-&gt;have_posts() ) : $acadp_query-&gt;the_post(); ?&gt;\n &lt;td&gt;&lt;?php the_author(); ?&gt;&lt;/td&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;/div&gt;\n\n&lt;?php wp_reset_postdata(); ?&gt;\n</code></pre>\n" }, { "answer_id": 308508, "author": "Taj Khan", "author_id": 128610, "author_profile": "https://wordpress.stackexchange.com/users/128610", "pm_score": 2, "selected": true, "text": "<pre><code>&lt;div class=\"acadp\"&gt;\n&lt;?php \n$compare =[];\nwhile( $acadp_query-&gt;have_posts() ) {\n $acadp_query-&gt;the_post(); $post_meta = get_post_meta( $post-&gt;ID ); \n $category = wp_get_object_terms( $post-&gt;ID, 'acadp_categories' ); \n $compare['Title'][] = get_the_title();\n $compare['Manufacturer'][] = $category[0]-&gt;name; \n\n $compare['Image'][] = get_the_acadp_listing_thumbnail($post_meta);\n\n\n if( count( $fields ) ){\n foreach( $fields as $field ) {\n $value = $post_meta[ $field-&gt;ID ][0];\n $compare[$field-&gt;post_title][] = $value;\n }\n }\n\n $compare['URL'][] = \"&lt;a href='\".get_the_permalink().\"' class='btn btn-primary'&gt;View Details&lt;/a&gt;\";\n}\n\n?&gt;\n&lt;table class=\"table table-bordered\"&gt;\n&lt;?php foreach ($compare as $feature =&gt; $value): ?&gt;\n &lt;tr&gt;\n &lt;th&gt;&lt;?php echo $feature; ?&gt;&lt;/th&gt;\n &lt;td&gt;&lt;?php echo implode(\"&lt;/td&gt;&lt;td&gt;\",$value); ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n&lt;?php endforeach; ?&gt;\n&lt;/table&gt;\n&lt;/div&gt;\n&lt;!-- end of the loop --&gt;\n\n&lt;!-- Use reset postdata to restore orginal query --&gt;\n&lt;?php wp_reset_postdata(); ?&gt;\n</code></pre>\n" }, { "answer_id": 308571, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>In stead of echoing author, title and so on during the loop you can also store them in arrays. Then after the loop you can echo every array as a row in your table. </p>\n" } ]
2018/07/13
[ "https://wordpress.stackexchange.com/questions/308433", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/128610/" ]
I am creating a comparison table and the issue is in while loop i am not able to put the `"tr"` in proper place. I need layout like this ``` <table> <tr> <td>post title 1</td> <td>post title 2</td> <td>post title 3</td> </tr> <tr> <td>post content 1</td> <td>post content 2</td> <td>post content 3</td> </tr> <tr> <td>post author 1</td> <td>post author 2</td> <td>post author 3</td> </tr> </table> ``` How can i achieve that it's seems like no option see my code below ``` <div class="acadp"> <table> <tr> <?php while( $acadp_query->have_posts() ) : $acadp_query->the_post(); ?> <td><?php the_title(); ?></td> <td><?php the_content(); ?></td> <td><?php the_author(); ?></td> <?php endwhile; ?> <tr> </table> </div> <?php wp_reset_postdata(); ?> ```
``` <div class="acadp"> <?php $compare =[]; while( $acadp_query->have_posts() ) { $acadp_query->the_post(); $post_meta = get_post_meta( $post->ID ); $category = wp_get_object_terms( $post->ID, 'acadp_categories' ); $compare['Title'][] = get_the_title(); $compare['Manufacturer'][] = $category[0]->name; $compare['Image'][] = get_the_acadp_listing_thumbnail($post_meta); if( count( $fields ) ){ foreach( $fields as $field ) { $value = $post_meta[ $field->ID ][0]; $compare[$field->post_title][] = $value; } } $compare['URL'][] = "<a href='".get_the_permalink()."' class='btn btn-primary'>View Details</a>"; } ?> <table class="table table-bordered"> <?php foreach ($compare as $feature => $value): ?> <tr> <th><?php echo $feature; ?></th> <td><?php echo implode("</td><td>",$value); ?></td> </tr> <?php endforeach; ?> </table> </div> <!-- end of the loop --> <!-- Use reset postdata to restore orginal query --> <?php wp_reset_postdata(); ?> ```
308,439
<p>My version variable doesn't seem to be being applied within my enqueue functions (snippet below).</p> <pre><code>//version number $version = '1.0.0'; function frontend_styles($version) { wp_enqueue_style( 'frontend_styles', //reference get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source array(), //dependenices $version, //version number 'all' //media type ('all', 'screen', 'handheld', 'print') ); } </code></pre> <p>Is there a way of setting a global version number that could be applied to all styles?</p> <p>EDIT: Below is the actual source code.</p> <pre><code>//version number $version = '1.0.0'; //remove jquery scripts function remove_jquery() { wp_deregister_script('jquery'); wp_deregister_script('jquery-core'); wp_deregister_script('jquery-migrate'); } //remove embed scripts function remove_embed() { wp_deregister_script('wp-embed'); } //site styles function frontend_styles() { global $version; wp_enqueue_style( 'frontend_styles', //reference get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source array(), //dependenices $version, //version number 'all' //media type ('all', 'screen', 'handheld', 'print') ); } //admin_styles function backend_styles() { global $version; wp_enqueue_style( 'backend_styles', //reference get_stylesheet_directory_uri() . '/assets/css/admin.min.css', //source array(), //dependenices $version, //version number 'all' //media type ('all', 'screen', 'handheld', 'print') ); } //site scripts function frontend_scripts() { global $version; wp_enqueue_script( 'frontend_scripts', //reference get_stylesheet_directory_uri() . '/assets/js/app.min.js', //source array(), //dependencies $version, //version number true //load in footer ); //pass sylsheet uri to javascript variable in app.js $translation_array = array( 'get_stylesheet_directory_uri' =&gt; get_stylesheet_directory_uri() . '/', 'home_url' =&gt; home_url('/') ); wp_localize_script('frontend_scripts', 'php', $translation_array); } //admin scripts function backend_scripts() { global $version; wp_enqueue_script( 'backend_scripts', //reference get_stylesheet_directory_uri() . '/assets/js/admin.min.js', //source array(), //dependencies $version, //version number true //load in footer ); } </code></pre>
[ { "answer_id": 308440, "author": "Florian", "author_id": 52583, "author_profile": "https://wordpress.stackexchange.com/users/52583", "pm_score": 1, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>// global theme version\n$version = '1.0.0';\n\nfunction frontend_styles() {\n\n global $version;\n wp_enqueue_style(\n 'frontend_styles', //reference\n get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source\n array(), //dependenices\n $version, //version number\n 'all' //media type ('all', 'screen', 'handheld', 'print')\n );\n}\n</code></pre>\n" }, { "answer_id": 308441, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>Your variable is not defined within the <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\">scope</a> of the <code>frontend_styles()</code> function.</p>\n\n<p>If you define <code>$version</code> outside a function, in the <em>global</em> scope, you need to use the <code>global</code> keyword inside the function to access it:</p>\n\n<pre><code>//version number\n$version = '1.0.0';\n\nfunction frontend_styles() {\n global $version;\n\n wp_enqueue_style(\n 'frontend_styles', //reference\n get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source\n array(), //dependenices\n $version, //version number\n 'all' //media type ('all', 'screen', 'handheld', 'print')\n );\n}\n</code></pre>\n" } ]
2018/07/13
[ "https://wordpress.stackexchange.com/questions/308439", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141411/" ]
My version variable doesn't seem to be being applied within my enqueue functions (snippet below). ``` //version number $version = '1.0.0'; function frontend_styles($version) { wp_enqueue_style( 'frontend_styles', //reference get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source array(), //dependenices $version, //version number 'all' //media type ('all', 'screen', 'handheld', 'print') ); } ``` Is there a way of setting a global version number that could be applied to all styles? EDIT: Below is the actual source code. ``` //version number $version = '1.0.0'; //remove jquery scripts function remove_jquery() { wp_deregister_script('jquery'); wp_deregister_script('jquery-core'); wp_deregister_script('jquery-migrate'); } //remove embed scripts function remove_embed() { wp_deregister_script('wp-embed'); } //site styles function frontend_styles() { global $version; wp_enqueue_style( 'frontend_styles', //reference get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source array(), //dependenices $version, //version number 'all' //media type ('all', 'screen', 'handheld', 'print') ); } //admin_styles function backend_styles() { global $version; wp_enqueue_style( 'backend_styles', //reference get_stylesheet_directory_uri() . '/assets/css/admin.min.css', //source array(), //dependenices $version, //version number 'all' //media type ('all', 'screen', 'handheld', 'print') ); } //site scripts function frontend_scripts() { global $version; wp_enqueue_script( 'frontend_scripts', //reference get_stylesheet_directory_uri() . '/assets/js/app.min.js', //source array(), //dependencies $version, //version number true //load in footer ); //pass sylsheet uri to javascript variable in app.js $translation_array = array( 'get_stylesheet_directory_uri' => get_stylesheet_directory_uri() . '/', 'home_url' => home_url('/') ); wp_localize_script('frontend_scripts', 'php', $translation_array); } //admin scripts function backend_scripts() { global $version; wp_enqueue_script( 'backend_scripts', //reference get_stylesheet_directory_uri() . '/assets/js/admin.min.js', //source array(), //dependencies $version, //version number true //load in footer ); } ```
Try this ``` // global theme version $version = '1.0.0'; function frontend_styles() { global $version; wp_enqueue_style( 'frontend_styles', //reference get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source array(), //dependenices $version, //version number 'all' //media type ('all', 'screen', 'handheld', 'print') ); } ```
308,444
<p>I have been searching for theme developing info but all that are related to this subject are talking about a custom page at <code>page.php</code>.</p> <p>What I am trying to achieve is different. The scenario is that I have to create a page where the content is hard-coded, so I can have more creative freedom on the design. That is to say, I don't want to have it generated through adding pages from the CMS, since there are more restrictions to it.</p> <p>Can I create a new static <code>.php</code> (a <code>page.php</code> with specific content), and linked to it from menu nav bar? It is similar to making a static home page, but not a "home" page.</p>
[ { "answer_id": 308440, "author": "Florian", "author_id": 52583, "author_profile": "https://wordpress.stackexchange.com/users/52583", "pm_score": 1, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>// global theme version\n$version = '1.0.0';\n\nfunction frontend_styles() {\n\n global $version;\n wp_enqueue_style(\n 'frontend_styles', //reference\n get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source\n array(), //dependenices\n $version, //version number\n 'all' //media type ('all', 'screen', 'handheld', 'print')\n );\n}\n</code></pre>\n" }, { "answer_id": 308441, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>Your variable is not defined within the <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\">scope</a> of the <code>frontend_styles()</code> function.</p>\n\n<p>If you define <code>$version</code> outside a function, in the <em>global</em> scope, you need to use the <code>global</code> keyword inside the function to access it:</p>\n\n<pre><code>//version number\n$version = '1.0.0';\n\nfunction frontend_styles() {\n global $version;\n\n wp_enqueue_style(\n 'frontend_styles', //reference\n get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source\n array(), //dependenices\n $version, //version number\n 'all' //media type ('all', 'screen', 'handheld', 'print')\n );\n}\n</code></pre>\n" } ]
2018/07/13
[ "https://wordpress.stackexchange.com/questions/308444", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146878/" ]
I have been searching for theme developing info but all that are related to this subject are talking about a custom page at `page.php`. What I am trying to achieve is different. The scenario is that I have to create a page where the content is hard-coded, so I can have more creative freedom on the design. That is to say, I don't want to have it generated through adding pages from the CMS, since there are more restrictions to it. Can I create a new static `.php` (a `page.php` with specific content), and linked to it from menu nav bar? It is similar to making a static home page, but not a "home" page.
Try this ``` // global theme version $version = '1.0.0'; function frontend_styles() { global $version; wp_enqueue_style( 'frontend_styles', //reference get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source array(), //dependenices $version, //version number 'all' //media type ('all', 'screen', 'handheld', 'print') ); } ```
308,457
<p>I am currently using Wordpress and I have a problem. I'm trying to develop a code that shows an image or another image based on the value of the custom field</p> <p>In each product, for example, I have a variable called store_1 or store_2 apart from the main stock of the product.</p> <p>What I want to do is a custom function for wordpress in the custom fields of the product in which it shows one image or another depending on the total amount of the value that custom field has. In the following code that I provide, it is for the wordpress stock itself, where it shows 3 images depending on the amount that there is.</p> <p>For example, if there are more than five, it shows an image in green, if there are less than five, it shows an image in orange and if there is 0 or less than zero it shows an image in red.</p> <p>This same code, I would like to customize it in each of those variables that I will embed in the product.</p> <pre><code>add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2); </code></pre> <p>function wcs_custom_get_availability( $availability, $_product ) { global $product;</p> <pre><code>// Stock greater than 5 or enough stock if ( $_product-&gt;is_in_stock() ) { $availability['availability'] = __('&lt;img src="https://myweb.com/images/fullstock.png"&gt;','woocommerce'); } // Low stock &lt; 5 if ( $_product-&gt;is_in_stock() &amp;&amp; $product-&gt;get_stock_quantity() &lt;= 5 ) { $availability['availability'] = sprintf( __('&lt;img src="https://myweb.com/images/lowstock.png"&gt;', 'woocommerce'), $product-&gt;get_stock_quantity()); } // No stock if ( ! $_product-&gt;is_in_stock() ) { $availability['availability'] = __('&lt;img src="https://myweb.com/images/notock.png"&gt;', 'woocommerce'); } return $availability; </code></pre> <p>}</p> <p>And this is my problem, I do not know what code should be developed in the functions file of my wordpress but customized for that variable.</p> <p>Thank you I await your response</p>
[ { "answer_id": 308440, "author": "Florian", "author_id": 52583, "author_profile": "https://wordpress.stackexchange.com/users/52583", "pm_score": 1, "selected": false, "text": "<p>Try this</p>\n\n<pre><code>// global theme version\n$version = '1.0.0';\n\nfunction frontend_styles() {\n\n global $version;\n wp_enqueue_style(\n 'frontend_styles', //reference\n get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source\n array(), //dependenices\n $version, //version number\n 'all' //media type ('all', 'screen', 'handheld', 'print')\n );\n}\n</code></pre>\n" }, { "answer_id": 308441, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>Your variable is not defined within the <a href=\"http://php.net/manual/en/language.variables.scope.php\" rel=\"nofollow noreferrer\">scope</a> of the <code>frontend_styles()</code> function.</p>\n\n<p>If you define <code>$version</code> outside a function, in the <em>global</em> scope, you need to use the <code>global</code> keyword inside the function to access it:</p>\n\n<pre><code>//version number\n$version = '1.0.0';\n\nfunction frontend_styles() {\n global $version;\n\n wp_enqueue_style(\n 'frontend_styles', //reference\n get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source\n array(), //dependenices\n $version, //version number\n 'all' //media type ('all', 'screen', 'handheld', 'print')\n );\n}\n</code></pre>\n" } ]
2018/07/13
[ "https://wordpress.stackexchange.com/questions/308457", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146891/" ]
I am currently using Wordpress and I have a problem. I'm trying to develop a code that shows an image or another image based on the value of the custom field In each product, for example, I have a variable called store\_1 or store\_2 apart from the main stock of the product. What I want to do is a custom function for wordpress in the custom fields of the product in which it shows one image or another depending on the total amount of the value that custom field has. In the following code that I provide, it is for the wordpress stock itself, where it shows 3 images depending on the amount that there is. For example, if there are more than five, it shows an image in green, if there are less than five, it shows an image in orange and if there is 0 or less than zero it shows an image in red. This same code, I would like to customize it in each of those variables that I will embed in the product. ``` add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2); ``` function wcs\_custom\_get\_availability( $availability, $\_product ) { global $product; ``` // Stock greater than 5 or enough stock if ( $_product->is_in_stock() ) { $availability['availability'] = __('<img src="https://myweb.com/images/fullstock.png">','woocommerce'); } // Low stock < 5 if ( $_product->is_in_stock() && $product->get_stock_quantity() <= 5 ) { $availability['availability'] = sprintf( __('<img src="https://myweb.com/images/lowstock.png">', 'woocommerce'), $product->get_stock_quantity()); } // No stock if ( ! $_product->is_in_stock() ) { $availability['availability'] = __('<img src="https://myweb.com/images/notock.png">', 'woocommerce'); } return $availability; ``` } And this is my problem, I do not know what code should be developed in the functions file of my wordpress but customized for that variable. Thank you I await your response
Try this ``` // global theme version $version = '1.0.0'; function frontend_styles() { global $version; wp_enqueue_style( 'frontend_styles', //reference get_stylesheet_directory_uri() . '/assets/css/app.min.css', //source array(), //dependenices $version, //version number 'all' //media type ('all', 'screen', 'handheld', 'print') ); } ```
308,466
<p>I'm seeing a weird problem where if someone searches "Test Search" it's returning fine, but if someone searches "Test Search " it's returning some weird posts that don't seem relevant.</p> <p>How do I go about trimming white space from beginning and end of a search term?</p>
[ { "answer_id": 308474, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>In WordPress search terms are <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter\" rel=\"nofollow noreferrer\">handled as query variables</a>. This means that the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"nofollow noreferrer\"><code>request</code> filter</a> is available to change the variable before the actual database query. Like this:</p>\n\n<pre><code>add_filter ('request', 'wpse308466_filter_search_query');\nfunction wpse308466_filter_search_query ($request) {\n if (!is_admin) { // only do this on the front end\n ltrim ($request['s']); // strip all whitespaces from beginning of string\n rtrim ($request['s']); // strip all whitespaces from end of string\n }\n return $request;\n }\n</code></pre>\n" }, { "answer_id": 396929, "author": "Baras", "author_id": 134835, "author_profile": "https://wordpress.stackexchange.com/users/134835", "pm_score": 1, "selected": false, "text": "<p>I came across the same problem.<br />\nIn my opinion, this should be the default search behavior in WP.</p>\n<p>The solution is to filter the array of parsed query variables.<br />\nSee the documentation <a href=\"https://developer.wordpress.org/reference/hooks/request/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Add this to the <code>functions.php</code> file in your theme directory.</p>\n<pre><code>add_filter('request', function ($query_vars) {\n if (!is_admin() &amp;&amp; !empty($query_vars['s'])) {\n $query_vars['s'] = trim($query_vars['s']);\n }\n\n return $query_vars;\n});\n</code></pre>\n" } ]
2018/07/13
[ "https://wordpress.stackexchange.com/questions/308466", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75134/" ]
I'm seeing a weird problem where if someone searches "Test Search" it's returning fine, but if someone searches "Test Search " it's returning some weird posts that don't seem relevant. How do I go about trimming white space from beginning and end of a search term?
I came across the same problem. In my opinion, this should be the default search behavior in WP. The solution is to filter the array of parsed query variables. See the documentation [here](https://developer.wordpress.org/reference/hooks/request/). Add this to the `functions.php` file in your theme directory. ``` add_filter('request', function ($query_vars) { if (!is_admin() && !empty($query_vars['s'])) { $query_vars['s'] = trim($query_vars['s']); } return $query_vars; }); ```
308,470
<p>I'm fairly new to wordpress and the content management system. I've been following a couple of tutorials to get started. I've been searching for specifically how to include a date picker in the add new custom post type. </p> <p><a href="https://i.stack.imgur.com/sCISj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sCISj.png" alt="My Events Custom Post Type"></a></p> <p>I want to add an extra field in here for the user to select a date to specify when the event will take place. I don't want the user to manually type out the date through text but want to use a date picker, whether it be a normal html5 datepicker or a jquery one.</p> <p>The code i used to generate this is within the functions.php, I understand that this is probably not the best place to put all my code but i'm currently just experimenting for now but can't seem to find a solution to my problem.</p> <pre><code> /* Custom post types */ function awesome_custom_post_type () { $labels = array( 'name' =&gt; 'Events', 'singular_name' =&gt; 'Event', 'add_new' =&gt; 'Add Event', 'all_items' =&gt; 'All Events', 'add_new_item' =&gt; 'Add Event', 'edit_item' =&gt; 'Edit Event', 'new_item' =&gt; 'New Event', 'view_item' =&gt; 'View Event', 'search_item_label' =&gt; 'Search Events', 'not_found' =&gt; 'No Events Found', 'not_found_in_trash' =&gt; 'No Events Found in Trash', 'parent_item_colon' =&gt; 'Parent Event' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'has_archive' =&gt; true, 'publicly_queryable' =&gt; false, 'query_var' =&gt; true, 'rewrite' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'thumbnail', ), 'menu_icon' =&gt; 'dashicons-calendar-alt', 'menu_position' =&gt; 5, 'excluse_from_search' =&gt; true ); register_post_type( 'awesome_events', $args ); } add_action( 'init', 'awesome_custom_post_type' ); </code></pre> <p>Thanks in advance.</p>
[ { "answer_id": 308475, "author": "sunil", "author_id": 56910, "author_profile": "https://wordpress.stackexchange.com/users/56910", "pm_score": 1, "selected": false, "text": "<p>@vemuez</p>\n\n<p>you need to enqueue js and css files to admin_print_script and admin_print_style</p>\n\n<p>here is the example to how to do it </p>\n\n<pre><code>// Register datepicker ui for properties\n\nfunction admin_homes_for_sale_javascript()\n{\n global $post;\n if($post-&gt;post_type == 'homes-for-sale' &amp;&amp; is_admin()) {\n wp_enqueue_script('jquery-ui-datepicker', WP_CONTENT_URL . '/themes/yourthemename/js/jquery-ui-datepicker.min.js'); \n }\n}\nadd_action('admin_print_scripts', 'admin_homes_for_sale_javascript');\n\n// Register ui styles for properties\n\nfunction admin_homes_for_sale_styles(){\n global $post;\n if($post-&gt;post_type == 'homes-for-sale' &amp;&amp; is_admin()) {\n wp_enqueue_style('jquery-ui', WP_CONTENT_URL . '/themes/yourthemename/css/jquery-ui-1.8.11.custom.css'); \n }\n}\nadd_action('admin_print_styles', 'admin_homes_for_sale_styles');\n</code></pre>\n\n<p>or try this\n<a href=\"https://en.bainternet.info/how-i-add-a-wordpress-metabox/#toc-dn\" rel=\"nofollow noreferrer\">https://en.bainternet.info/how-i-add-a-wordpress-metabox/#toc-dn</a></p>\n" }, { "answer_id": 310202, "author": "Yussuf", "author_id": 146895, "author_profile": "https://wordpress.stackexchange.com/users/146895", "pm_score": 1, "selected": true, "text": "<p>With the help of sunil's answer I figured out exactly what I needed to do.</p>\n\n<p>I went and downloaded the free version of Metabox at <a href=\"https://wordpress.org/plugins/meta-box/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/meta-box/</a></p>\n\n<p>Once I downloaded it, I've placed it in <code>child-theme/external/meta-box</code>and referenced it from <code>child-theme/inc/events-custom-post-type.php</code>. </p>\n\n<p><code>events-custom-post-type.php</code> looks like this.</p>\n\n<p>\n\n<pre><code>require_once(get_stylesheet_directory() . '/external/meta-box/meta-box.php');\n\nfunction custom_events ()\n{\n $labels = array(\n 'name' =&gt; 'Events',\n 'singular_name' =&gt; 'Event',\n 'add_new' =&gt; 'Add Event',\n 'all_items' =&gt; 'All Events',\n 'add_new_item' =&gt; 'Add Event',\n 'edit_item' =&gt; 'Edit Event',\n 'new_item' =&gt; 'New Event',\n 'view_item' =&gt; 'View Event',\n 'search_item_label' =&gt; 'Search Events',\n 'not_found' =&gt; 'No Events Found',\n 'not_found_in_trash' =&gt; 'No Events Found in Trash',\n 'parent_item_colon' =&gt; 'Parent Event'\n );\n\n $args = array(\n 'labels' =&gt; $labels,\n 'public' =&gt; true,\n 'has_archive' =&gt; true,\n 'publicly_queryable' =&gt; false,\n 'query_var' =&gt; true,\n 'rewrite' =&gt; true,\n 'capability_type' =&gt; 'post',\n 'hierarchical' =&gt; true,\n 'supports' =&gt; array(\n 'title',\n 'editor',\n ),\n 'menu_icon' =&gt; 'dashicons-calendar-alt',\n 'menu_position' =&gt; 5,\n 'exclude_from_search' =&gt; true\n );\n\n register_post_type( 'custom_events_post_type', $args );\n}\n\nfunction prefix_register_meta_boxes_events( $meta_boxes ) {\n $prefix = 'custom_event_';\n\n $meta_boxes[] = array(\n 'id' =&gt; $prefix . 'details',\n 'title' =&gt; 'Event details',\n 'post_types' =&gt; 'custom_events_post_type',\n 'context' =&gt; 'normal',\n 'priority' =&gt; 'high',\n\n 'fields' =&gt; array(\n array(\n 'name' =&gt; 'Event date',\n 'desc' =&gt; 'Select event date',\n 'id' =&gt; $prefix . 'date',\n 'type' =&gt; 'date',\n ),\n array (\n 'name' =&gt; 'Event location',\n 'desc' =&gt; 'Location of the event',\n 'id' =&gt; $prefix . 'location',\n 'type' =&gt; 'text'\n )\n )\n );\n\n return $meta_boxes;\n}\n\nadd_action( 'init', 'custom_events' );\n\nadd_filter( 'rwmb_meta_boxes', 'prefix_register_meta_boxes_events' );\n</code></pre>\n\n<p>The <code>custom_events</code> function sets up the custom post type while the <code>prefix_register_meta_boxes_events</code> function sets up the custom field date picker.</p>\n\n<p>You just have to make sure that in <code>prefix_register_meta_boxes_events</code> function, where it says <code>post_types</code> to add what your own custom post type is registered as.</p>\n\n<p>After that, I just referenced this file in <code>child-theme/functions.php</code> like so.</p>\n\n<pre><code>require get_stylesheet_directory() . '/inc/events-custom-post-type.php';\n</code></pre>\n" } ]
2018/07/13
[ "https://wordpress.stackexchange.com/questions/308470", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146895/" ]
I'm fairly new to wordpress and the content management system. I've been following a couple of tutorials to get started. I've been searching for specifically how to include a date picker in the add new custom post type. [![My Events Custom Post Type](https://i.stack.imgur.com/sCISj.png)](https://i.stack.imgur.com/sCISj.png) I want to add an extra field in here for the user to select a date to specify when the event will take place. I don't want the user to manually type out the date through text but want to use a date picker, whether it be a normal html5 datepicker or a jquery one. The code i used to generate this is within the functions.php, I understand that this is probably not the best place to put all my code but i'm currently just experimenting for now but can't seem to find a solution to my problem. ``` /* Custom post types */ function awesome_custom_post_type () { $labels = array( 'name' => 'Events', 'singular_name' => 'Event', 'add_new' => 'Add Event', 'all_items' => 'All Events', 'add_new_item' => 'Add Event', 'edit_item' => 'Edit Event', 'new_item' => 'New Event', 'view_item' => 'View Event', 'search_item_label' => 'Search Events', 'not_found' => 'No Events Found', 'not_found_in_trash' => 'No Events Found in Trash', 'parent_item_colon' => 'Parent Event' ); $args = array( 'labels' => $labels, 'public' => true, 'has_archive' => true, 'publicly_queryable' => false, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => true, 'supports' => array( 'title', 'editor', 'thumbnail', ), 'menu_icon' => 'dashicons-calendar-alt', 'menu_position' => 5, 'excluse_from_search' => true ); register_post_type( 'awesome_events', $args ); } add_action( 'init', 'awesome_custom_post_type' ); ``` Thanks in advance.
With the help of sunil's answer I figured out exactly what I needed to do. I went and downloaded the free version of Metabox at <https://wordpress.org/plugins/meta-box/> Once I downloaded it, I've placed it in `child-theme/external/meta-box`and referenced it from `child-theme/inc/events-custom-post-type.php`. `events-custom-post-type.php` looks like this. ``` require_once(get_stylesheet_directory() . '/external/meta-box/meta-box.php'); function custom_events () { $labels = array( 'name' => 'Events', 'singular_name' => 'Event', 'add_new' => 'Add Event', 'all_items' => 'All Events', 'add_new_item' => 'Add Event', 'edit_item' => 'Edit Event', 'new_item' => 'New Event', 'view_item' => 'View Event', 'search_item_label' => 'Search Events', 'not_found' => 'No Events Found', 'not_found_in_trash' => 'No Events Found in Trash', 'parent_item_colon' => 'Parent Event' ); $args = array( 'labels' => $labels, 'public' => true, 'has_archive' => true, 'publicly_queryable' => false, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => true, 'supports' => array( 'title', 'editor', ), 'menu_icon' => 'dashicons-calendar-alt', 'menu_position' => 5, 'exclude_from_search' => true ); register_post_type( 'custom_events_post_type', $args ); } function prefix_register_meta_boxes_events( $meta_boxes ) { $prefix = 'custom_event_'; $meta_boxes[] = array( 'id' => $prefix . 'details', 'title' => 'Event details', 'post_types' => 'custom_events_post_type', 'context' => 'normal', 'priority' => 'high', 'fields' => array( array( 'name' => 'Event date', 'desc' => 'Select event date', 'id' => $prefix . 'date', 'type' => 'date', ), array ( 'name' => 'Event location', 'desc' => 'Location of the event', 'id' => $prefix . 'location', 'type' => 'text' ) ) ); return $meta_boxes; } add_action( 'init', 'custom_events' ); add_filter( 'rwmb_meta_boxes', 'prefix_register_meta_boxes_events' ); ``` The `custom_events` function sets up the custom post type while the `prefix_register_meta_boxes_events` function sets up the custom field date picker. You just have to make sure that in `prefix_register_meta_boxes_events` function, where it says `post_types` to add what your own custom post type is registered as. After that, I just referenced this file in `child-theme/functions.php` like so. ``` require get_stylesheet_directory() . '/inc/events-custom-post-type.php'; ```
308,497
<p>How can I copy the default styling for the admin and tell wordpress to use custom style instead of the default? Basically I want to change the colour and font without having to use !important syntax to force Wordpress to use it. </p>
[ { "answer_id": 308567, "author": "dhirenpatel22", "author_id": 124380, "author_profile": "https://wordpress.stackexchange.com/users/124380", "pm_score": 1, "selected": false, "text": "<p>Enqueue custom admin CSS file (custom-admin.css) in your WordPress backend using below function:</p>\n\n<pre><code>add_action('admin_print_styles', 'custom_admin_css');\nadd_action('wp_enqueue_scripts', 'custom_admin_css');\n\nfunction custom_admin_css() {\n if (is_admin()) {\n wp_enqueue_style(\"custom-admin-css\", get_bloginfo('template_directory'). \"/custom_admin.css\", false, false, \"all\");\n }\n}\n</code></pre>\n\n<p>Hope this works..!!</p>\n" }, { "answer_id": 337242, "author": "samurai_jane", "author_id": 167517, "author_profile": "https://wordpress.stackexchange.com/users/167517", "pm_score": 2, "selected": false, "text": "<p>As noted by @Fusion, this has changed beginning with version 5. In order to override admin styles for 5.*, you need a hook in <code>functions.php</code>, something like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function custom_admin() {\n $url = get_settings('siteurl');\n $url = $url . '/wp-content/themes/my-theme/wp-admin.css';\n echo '&lt;link rel=\"stylesheet\" type=\"text/css\" href=\"' . $url . '\" /&gt;';\n}\nadd_action('admin_head', 'custom_admin')\n</code></pre>\n\n<p>Sources:<br>\n<a href=\"https://codex.wordpress.org/Creating_Admin_Themes\" rel=\"nofollow noreferrer\">Wordpress Codex</a><br>\n<a href=\"https://www.isitwp.com/custom-admin-css/\" rel=\"nofollow noreferrer\">isitwp Snippet</a></p>\n\n<p>Please note the the <strong>isitwp Snippet</strong> erroneously mixes html entitites with angle brackets. You should use angle brackets not entitieis.</p>\n" }, { "answer_id": 359967, "author": "Tim", "author_id": 113538, "author_profile": "https://wordpress.stackexchange.com/users/113538", "pm_score": 0, "selected": false, "text": "<p>In <strong>WordPress 5.x</strong> you can use the following hooks to add CSS to either the admin pages or the post edit page.</p>\n<p><code>enqueue_block_editor_assets</code> to add your own styles to the Gutenberg page</p>\n<p><code>admin_enqueue_scripts</code> to add your own styles to the admin pages</p>\n<p>You can add the hooks in your <code>functions.php</code> theme file.</p>\n" } ]
2018/07/13
[ "https://wordpress.stackexchange.com/questions/308497", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146914/" ]
How can I copy the default styling for the admin and tell wordpress to use custom style instead of the default? Basically I want to change the colour and font without having to use !important syntax to force Wordpress to use it.
As noted by @Fusion, this has changed beginning with version 5. In order to override admin styles for 5.\*, you need a hook in `functions.php`, something like this: ```php function custom_admin() { $url = get_settings('siteurl'); $url = $url . '/wp-content/themes/my-theme/wp-admin.css'; echo '<link rel="stylesheet" type="text/css" href="' . $url . '" />'; } add_action('admin_head', 'custom_admin') ``` Sources: [Wordpress Codex](https://codex.wordpress.org/Creating_Admin_Themes) [isitwp Snippet](https://www.isitwp.com/custom-admin-css/) Please note the the **isitwp Snippet** erroneously mixes html entitites with angle brackets. You should use angle brackets not entitieis.
308,505
<p>What is the best approach to changing admin menu labels? As part of my first step in modifying the admin area, I would like to know how I can change <strong>WooCommerce</strong> label to <strong>Shop</strong>? </p>
[ { "answer_id": 308506, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 3, "selected": true, "text": "<p>In order to change the menu labels you will have to go to add this code into your <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'gettext', 'change_woocommerce_text' );\n\nfunction change_woocommerce_text( $translated ) \n{ \n $translated = str_replace( 'WooCommerce', 'Store', $translated );\n return $translated;\n}\n</code></pre>\n\n<p>Tested.</p>\n" }, { "answer_id": 308507, "author": "Quang Hoang", "author_id": 134874, "author_profile": "https://wordpress.stackexchange.com/users/134874", "pm_score": 2, "selected": false, "text": "<p>You can try this. (Exp: I have changed label 'Post' to 'Articles')</p>\n\n<pre><code>add_action( 'admin_menu', 'custom_change_admin_label', 99);\nfunction custom_change_admin_label() {\n global $menu;\n //global $submenu;\n $menu[5][0] = 'Articles';\n}\n</code></pre>\n\n<p>Screenshot: <a href=\"http://nimb.ws/jiIC91\" rel=\"nofollow noreferrer\">http://nimb.ws/jiIC91</a></p>\n" } ]
2018/07/14
[ "https://wordpress.stackexchange.com/questions/308505", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146914/" ]
What is the best approach to changing admin menu labels? As part of my first step in modifying the admin area, I would like to know how I can change **WooCommerce** label to **Shop**?
In order to change the menu labels you will have to go to add this code into your `functions.php`: ``` add_filter( 'gettext', 'change_woocommerce_text' ); function change_woocommerce_text( $translated ) { $translated = str_replace( 'WooCommerce', 'Store', $translated ); return $translated; } ``` Tested.
308,509
<p>In the <code>register_post_status</code>, I've already disabled <code>show_in_admin_all_list</code> &amp; <code>show_in_admin_status_list</code> for my custom status <code>my_hidden_status</code></p> <p>However, from the query log the post_status <code>my_hidden_status</code> is still not being filtered out (when loading edit.php)</p> <p>e.g.</p> <pre><code>SELECT post_status, COUNT( * ) AS num_posts FROM st_posts WHERE post_type = 'my_cpt' GROUP BY post_status; </code></pre> <p>The post_status I wanted to filter is actually over 90% of my CPT, so if the query is rewritten as</p> <pre><code>SELECT post_status, COUNT( * ) AS num_posts FROM st_posts WHERE post_type = 'my_cpt' AND post_status != 'my_hidden_status' GROUP BY post_status; </code></pre> <p>It can greatly improve performance.</p> <p>Is this a bug?</p>
[ { "answer_id": 308731, "author": "SeventhSteel", "author_id": 17276, "author_profile": "https://wordpress.stackexchange.com/users/17276", "pm_score": 1, "selected": false, "text": "<p>Is it a bug? It's doing a little more work than it has to, but it's not resulting in any unexpected output, and it avoids potential problems with other site setups. So I would say no (mostly).</p>\n\n<p>The query in question serves to count the number of posts found before displaying them on the edit screen. It counts all posts by status so that it has these numbers handy if the page needs them later.</p>\n\n<p>My hunch is that the query was kept simple on purpose to prevent the possibility of multiple little-used post statuses clogging and slowing down the query. For example, testing on phpMyAdmin, the base query took 0.0011 seconds with around 300 posts. Adding clauses to filter out 5 unused or little-used post statuses raised the time to 0.0024.</p>\n\n<p>In your situation, you're correct that filtering out 90% of potential results would speed up the query. You could try filtering it with the <a href=\"https://developer.wordpress.org/reference/hooks/query/\" rel=\"nofollow noreferrer\">query filter</a>.</p>\n\n<p>As a side note: while researching this I noticed that if <code>\"public\" =&gt; true</code> in <code>register_post_status</code>, it overrides the <code>show_in_admin_all_list</code> value and displays posts with that status on the edit screen. I'd call that part a bug, since in other <code>register_*</code> functions the more specific args tend to override the <code>public</code> arg.</p>\n" }, { "answer_id": 308840, "author": "Shazzad", "author_id": 42967, "author_profile": "https://wordpress.stackexchange.com/users/42967", "pm_score": 1, "selected": false, "text": "<p>The query you are looking to filter is actually called by <code>wp_count_posts</code> function. Only way to filter this query is by using <code>query</code> filter (found inside <code>wpdb</code> class <code>query</code> method).</p>\n\n<p>As the filter <code>query</code> is used for all of the mysql queries called with <code>$wpdb</code> instance, it would be better to register your filter from the exact place you need it. For that, add your filter on <code>load-edit.php</code> action.</p>\n\n<pre><code>/* register the filter from edit.php page (works for all post types) */\nadd_action('load-edit.php', 'wpse_initiate_filter');\nfunction wpse_initiate_filter($query) {\n add_filter('query', 'wpse_filter_posts_count_query');\n}\n\n/* modify original query to filter out my_hidden_status */\nfunction wpse_filter_posts_count_query($query) {\n if (strpos($query, 'SELECT post_status') === 0) {\n $query = str_replace(\" GROUP BY\", \" AND post_status != 'my_hidden_status' GROUP BY\", $query);\n }\n return $query;\n}\n</code></pre>\n" }, { "answer_id": 309197, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p><strong><em>TL;DR:</em></strong> It's not a bug (<em>as we generally understand it</em>), rather it's a feature that was <strong>never fully implemented</strong> in WordPress.</p>\n</blockquote>\n\n<hr>\n\n<h2>Status of <code>register_post_status()</code></h2>\n\n<p><code>register_post_status()</code> function was never fully implemented in WordPress. If you check WordPress <a href=\"https://codex.wordpress.org/Function_Reference/register_post_status\" rel=\"nofollow noreferrer\">Codex entry for register_post_status() function</a>, you'll see it's clearly mentioned in a notice:</p>\n\n<blockquote>\n <p><strong>NOTICE:</strong></p>\n \n <p>This function does NOT add the registered post status to the admin panel. This functionality is <strong>pending future development</strong>. Please refer to <a href=\"https://core.trac.wordpress.org/ticket/12706\" rel=\"nofollow noreferrer\">Trac Ticket #12706</a> . Consider the action hook <a href=\"http://core.trac.wordpress.org/browser/tags/3.5.1/wp-admin/includes/meta-boxes.php#L183\" rel=\"nofollow noreferrer\">post_submitbox_misc_actions</a> for adding this parameter.</p>\n</blockquote>\n\n<p>Also, if you visit the <a href=\"https://core.trac.wordpress.org/ticket/12706\" rel=\"nofollow noreferrer\">Related Ticket</a>, you'll see that the discussion to implement it fully is going on for over 8 years now (starting from March 2010)! However, since WordPress is open source community driven software &amp; there weren't a lot of volunteers willing to work on this feature, it's still pending proper implementation.</p>\n\n<p>The <a href=\"https://core.trac.wordpress.org/ticket/12706\" rel=\"nofollow noreferrer\">Trac Ticket #12706</a> states the following in the description:</p>\n\n<blockquote>\n <p>A developer should be able to register a custom post status using <strong>register_post_status()</strong>. The admin UI (including post submit box and quick edit) <strong>should reflect this new custom post status</strong>. Furthermore, there are many hard-coded references to 'draft' and 'pending' statuses in core that should properly use the post status API.</p>\n \n <p><strong>All existing arguments to register_post_status() should be fully implemented</strong>, should also support per-post-type arguments. As things get implemented across core, there will likely be a need for supporting capabilities and bits of API.</p>\n</blockquote>\n\n<p>Now if you look at the WordPress core CODE, you'll see that this description is still valid. That means:</p>\n\n<ul>\n<li><p>The admin UI (including post submit box and quick edit) <strong>doesn't reflect custom post status</strong>. Check <a href=\"https://github.com/WordPress/WordPress/blob/cd4c960a6c17e683bcc76f1efaadcb272955bb83/wp-admin/includes/meta-boxes.php#L91-L113\" rel=\"nofollow noreferrer\">this part of the CODE</a> in core:</p>\n\n<pre><code>&lt;?php _e( 'Status:' ); ?&gt; &lt;span id=\"post-status-display\"&gt;\n&lt;?php\n switch ( $post-&gt;post_status ) {\n case 'private':\n _e( 'Privately Published' );\n break;\n case 'publish':\n _e( 'Published' );\n break;\n case 'future':\n _e( 'Scheduled' );\n break;\n case 'pending':\n _e( 'Pending Review' );\n break;\n case 'draft':\n case 'auto-draft':\n _e( 'Draft' );\n break;\n }\n?&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>The CODE contains <strong>no action / filter hook for any custom post status</strong> or for any modification whatsoever. So the only logical way at the moment is to use some JavaScript to alter the UI implementation until this feature is implemented in WordPress core. </p></li>\n<li><p>All existing arguments to <strong><em>register_post_status()</em> is not yet fully implemented</strong> &amp; hence may look buggy.</p></li>\n<li><p>And a lot more discussion &amp; work is needed for the full implementation of the Post Status API.</p></li>\n</ul>\n\n<h2>What to do about this Lack of Feature or Bug?</h2>\n\n<p>Call it a lack of feature or call it a bug, the fact remains: there's a lot more work that needs to be done to complete the Post Status API. \nSo if this is too important for you, it's better to join in the discussion in the Support Ticket mentioned above to expedite the development process.</p>\n\n<p>Although the entire development process will need a lot of voluntary work, you can still comment on it about the argument <code>show_in_admin_all_list</code> not affecting the query, so that at least this part of the anomaly can be improved earlier than the rest of the Status API.</p>\n\n<h2>What to do until core doesn't implement the features properly?</h2>\n\n<p>As it is now, <code>show_in_admin_all_list</code> argument only affects the <code>All(*)</code> status header part of the All Posts Listing, for example:</p>\n\n<p><a href=\"https://i.stack.imgur.com/VqQXA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VqQXA.png\" alt=\"All Posts Listing Status Header (All Posts Selected)\"></a>\n<br><sub><strong>Image-1:</strong> All Posts Listing Status Header (All Posts Selected)</sub></p>\n\n<p>However, it doesn't affect the posts that appear in the list (although it should).</p>\n\n<p>To make sure that posts with your custom status <code>my_hidden_status</code> doesn't appear in the list as well, you need to set the <code>public</code> argument to <code>false</code>.</p>\n\n<p>This will make the <code>register_post_status()</code> function call look like the following:</p>\n\n<pre><code>register_post_status( 'my_hidden_status', array(\n 'label' =&gt; _x( 'My Hidden Status', 'post' ),\n 'public' =&gt; false,\n 'show_in_admin_all_list' =&gt; false, \n 'show_in_admin_status_list' =&gt; false,\n 'label_count' =&gt; _n_noop( 'My Hidden Status &lt;span class=\"count\"&gt;(%s)&lt;/span&gt;', 'My Hidden Status &lt;span class=\"count\"&gt;(%s)&lt;/span&gt;' )\n) );\n</code></pre>\n\n<p>This will show the correct count in <code>All(*)</code> status header and also remove the posts with <code>my_hidden_status</code> from the <code>All Posts</code> or <code>All {custom_post_type}</code> listing.</p>\n\n<p>Of course, this will essentially make posts with <code>my_hidden_status</code> inaccessible from WordPress Admin Panel. If that was the intent, then fine, otherwise, you may use the <code>show_in_admin_status_list</code> to show the posts with <code>my_hidden_status</code> in a separate listing header:</p>\n\n<pre><code>register_post_status( 'my_hidden_status', array(\n 'label' =&gt; _x( 'My Hidden Status', 'post' ),\n 'public' =&gt; false,\n 'show_in_admin_all_list' =&gt; false, \n 'show_in_admin_status_list' =&gt; true,\n 'label_count' =&gt; _n_noop( 'My Hidden Status &lt;span class=\"count\"&gt;(%s)&lt;/span&gt;', 'My Hidden Status &lt;span class=\"count\"&gt;(%s)&lt;/span&gt;' )\n) );\n</code></pre>\n\n<p>This will show the Post Lists with the status <code>my_hidden_status</code> in a separate header like the following:</p>\n\n<p><a href=\"https://i.stack.imgur.com/EF0wV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EF0wV.png\" alt=\"All Posts Listing Status Header (Custom Status Selected)\"></a>\n<br><sub><strong>Image-2:</strong> All Posts Listing Status Header (Custom Status Selected)</sub></p>\n\n<h2>DB Query Optimization Issue:</h2>\n\n<p>The related DB Query comes from <code>wp_count_posts()</code> function in <code>wp-includes/post.php</code> file. If you take a look at the <a href=\"https://github.com/WordPress/WordPress/blob/c9dce0606b0d7e6f494d4abe7b193ac046a322cd/wp-includes/post.php#L2457-L2467\" rel=\"nofollow noreferrer\">related CODE</a>, you'll see that the arguments from <code>register_post_status()</code> function are not implemented there. Also, there's no way to filter or extend this part of the core CODE either:</p>\n\n<pre><code>$query = \"SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb-&gt;posts} WHERE post_type = %s\";\nif ( 'readable' == $perm &amp;&amp; is_user_logged_in() ) {\n $post_type_object = get_post_type_object( $type );\n if ( ! current_user_can( $post_type_object-&gt;cap-&gt;read_private_posts ) ) {\n $query .= $wpdb-&gt;prepare(\n \" AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))\",\n get_current_user_id()\n );\n }\n}\n$query .= ' GROUP BY post_status';\n</code></pre>\n\n<p>Unless both <code>show_in_admin_all_list</code> and <code>show_in_admin_status_list</code> are set to <code>false</code> for a particular status, related posts shouldn't be removed from the query anyway. Otherwise WordPress will not be able to generate the proper <code>status header</code> (as shown in image-2).</p>\n\n<p>However, in the case where both <code>show_in_admin_all_list</code> and <code>show_in_admin_status_list</code> are set to <code>false</code>, WordPress doesn't need the count information for that custom status. So logically in this case you'll have a little query performance improvement with <code>AND post_status != 'my_hidden_status'</code> part, if you have a large number of posts (like Millions) and most of your posts (as you said 90%) are from that custom status.</p>\n\n<p>Still, there are two reasons why core may not update this part of the CODE even though there may be a little performance gain in your particular case:</p>\n\n<ol>\n<li><p><strong>WordPress Database uses an index named <code>type_status_date</code></strong> that indexes <code>wp-posts</code> table entries based on <code>post_type</code>, <code>post_status</code>, <code>post_date</code> and <code>ID</code> fields. <strong>So queries are fast enough even without the <code>AND post_status != 'my_hidden_status'</code> part</strong>.</p>\n\n<p>I've tested with 15K+ posts and it only takes a few milliseconds. Check <a href=\"https://dev.mysql.com/doc/refman/8.0/en/group-by-optimization.html\" rel=\"nofollow noreferrer\">this MySQL Document</a> for more information on GROUP BY Optimization with index. With some tweaks to MySQL index, you may even get better results without even changing WP Core. For example, adding another index with <code>post_type</code> and <code>post_status</code> column may give you a few milliseconds gain.</p></li>\n<li><p>Even though adding <code>AND post_status != 'my_hidden_status'</code> may make the query faster (merely by milliseconds) in your particular case, WordPress still may not update it, because WordPress will have to <strong>consider the possibility where a hidden custom status has only a few posts</strong>. In those cases, adding <code>AND post_status != 'my_hidden_status'</code> will actually make the query results a bit slower (only by a few milliseconds).</p></li>\n</ol>\n\n<p>So considering everything, WordPress may or may not update the query with <code>AND post_status != 'my_hidden_status'</code> when both <code>show_in_admin_all_list</code> and <code>show_in_admin_status_list</code> are set to <code>false</code> for a custom status. However, in my opinion, at least making the related query filterable will improve the flexibility for the developers.</p>\n" } ]
2018/07/14
[ "https://wordpress.stackexchange.com/questions/308509", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16037/" ]
In the `register_post_status`, I've already disabled `show_in_admin_all_list` & `show_in_admin_status_list` for my custom status `my_hidden_status` However, from the query log the post\_status `my_hidden_status` is still not being filtered out (when loading edit.php) e.g. ``` SELECT post_status, COUNT( * ) AS num_posts FROM st_posts WHERE post_type = 'my_cpt' GROUP BY post_status; ``` The post\_status I wanted to filter is actually over 90% of my CPT, so if the query is rewritten as ``` SELECT post_status, COUNT( * ) AS num_posts FROM st_posts WHERE post_type = 'my_cpt' AND post_status != 'my_hidden_status' GROUP BY post_status; ``` It can greatly improve performance. Is this a bug?
> > ***TL;DR:*** It's not a bug (*as we generally understand it*), rather it's a feature that was **never fully implemented** in WordPress. > > > --- Status of `register_post_status()` ---------------------------------- `register_post_status()` function was never fully implemented in WordPress. If you check WordPress [Codex entry for register\_post\_status() function](https://codex.wordpress.org/Function_Reference/register_post_status), you'll see it's clearly mentioned in a notice: > > **NOTICE:** > > > This function does NOT add the registered post status to the admin panel. This functionality is **pending future development**. Please refer to [Trac Ticket #12706](https://core.trac.wordpress.org/ticket/12706) . Consider the action hook [post\_submitbox\_misc\_actions](http://core.trac.wordpress.org/browser/tags/3.5.1/wp-admin/includes/meta-boxes.php#L183) for adding this parameter. > > > Also, if you visit the [Related Ticket](https://core.trac.wordpress.org/ticket/12706), you'll see that the discussion to implement it fully is going on for over 8 years now (starting from March 2010)! However, since WordPress is open source community driven software & there weren't a lot of volunteers willing to work on this feature, it's still pending proper implementation. The [Trac Ticket #12706](https://core.trac.wordpress.org/ticket/12706) states the following in the description: > > A developer should be able to register a custom post status using **register\_post\_status()**. The admin UI (including post submit box and quick edit) **should reflect this new custom post status**. Furthermore, there are many hard-coded references to 'draft' and 'pending' statuses in core that should properly use the post status API. > > > **All existing arguments to register\_post\_status() should be fully implemented**, should also support per-post-type arguments. As things get implemented across core, there will likely be a need for supporting capabilities and bits of API. > > > Now if you look at the WordPress core CODE, you'll see that this description is still valid. That means: * The admin UI (including post submit box and quick edit) **doesn't reflect custom post status**. Check [this part of the CODE](https://github.com/WordPress/WordPress/blob/cd4c960a6c17e683bcc76f1efaadcb272955bb83/wp-admin/includes/meta-boxes.php#L91-L113) in core: ``` <?php _e( 'Status:' ); ?> <span id="post-status-display"> <?php switch ( $post->post_status ) { case 'private': _e( 'Privately Published' ); break; case 'publish': _e( 'Published' ); break; case 'future': _e( 'Scheduled' ); break; case 'pending': _e( 'Pending Review' ); break; case 'draft': case 'auto-draft': _e( 'Draft' ); break; } ?> </span> ``` The CODE contains **no action / filter hook for any custom post status** or for any modification whatsoever. So the only logical way at the moment is to use some JavaScript to alter the UI implementation until this feature is implemented in WordPress core. * All existing arguments to ***register\_post\_status()* is not yet fully implemented** & hence may look buggy. * And a lot more discussion & work is needed for the full implementation of the Post Status API. What to do about this Lack of Feature or Bug? --------------------------------------------- Call it a lack of feature or call it a bug, the fact remains: there's a lot more work that needs to be done to complete the Post Status API. So if this is too important for you, it's better to join in the discussion in the Support Ticket mentioned above to expedite the development process. Although the entire development process will need a lot of voluntary work, you can still comment on it about the argument `show_in_admin_all_list` not affecting the query, so that at least this part of the anomaly can be improved earlier than the rest of the Status API. What to do until core doesn't implement the features properly? -------------------------------------------------------------- As it is now, `show_in_admin_all_list` argument only affects the `All(*)` status header part of the All Posts Listing, for example: [![All Posts Listing Status Header (All Posts Selected)](https://i.stack.imgur.com/VqQXA.png)](https://i.stack.imgur.com/VqQXA.png) **Image-1:** All Posts Listing Status Header (All Posts Selected) However, it doesn't affect the posts that appear in the list (although it should). To make sure that posts with your custom status `my_hidden_status` doesn't appear in the list as well, you need to set the `public` argument to `false`. This will make the `register_post_status()` function call look like the following: ``` register_post_status( 'my_hidden_status', array( 'label' => _x( 'My Hidden Status', 'post' ), 'public' => false, 'show_in_admin_all_list' => false, 'show_in_admin_status_list' => false, 'label_count' => _n_noop( 'My Hidden Status <span class="count">(%s)</span>', 'My Hidden Status <span class="count">(%s)</span>' ) ) ); ``` This will show the correct count in `All(*)` status header and also remove the posts with `my_hidden_status` from the `All Posts` or `All {custom_post_type}` listing. Of course, this will essentially make posts with `my_hidden_status` inaccessible from WordPress Admin Panel. If that was the intent, then fine, otherwise, you may use the `show_in_admin_status_list` to show the posts with `my_hidden_status` in a separate listing header: ``` register_post_status( 'my_hidden_status', array( 'label' => _x( 'My Hidden Status', 'post' ), 'public' => false, 'show_in_admin_all_list' => false, 'show_in_admin_status_list' => true, 'label_count' => _n_noop( 'My Hidden Status <span class="count">(%s)</span>', 'My Hidden Status <span class="count">(%s)</span>' ) ) ); ``` This will show the Post Lists with the status `my_hidden_status` in a separate header like the following: [![All Posts Listing Status Header (Custom Status Selected)](https://i.stack.imgur.com/EF0wV.png)](https://i.stack.imgur.com/EF0wV.png) **Image-2:** All Posts Listing Status Header (Custom Status Selected) DB Query Optimization Issue: ---------------------------- The related DB Query comes from `wp_count_posts()` function in `wp-includes/post.php` file. If you take a look at the [related CODE](https://github.com/WordPress/WordPress/blob/c9dce0606b0d7e6f494d4abe7b193ac046a322cd/wp-includes/post.php#L2457-L2467), you'll see that the arguments from `register_post_status()` function are not implemented there. Also, there's no way to filter or extend this part of the core CODE either: ``` $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s"; if ( 'readable' == $perm && is_user_logged_in() ) { $post_type_object = get_post_type_object( $type ); if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) { $query .= $wpdb->prepare( " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))", get_current_user_id() ); } } $query .= ' GROUP BY post_status'; ``` Unless both `show_in_admin_all_list` and `show_in_admin_status_list` are set to `false` for a particular status, related posts shouldn't be removed from the query anyway. Otherwise WordPress will not be able to generate the proper `status header` (as shown in image-2). However, in the case where both `show_in_admin_all_list` and `show_in_admin_status_list` are set to `false`, WordPress doesn't need the count information for that custom status. So logically in this case you'll have a little query performance improvement with `AND post_status != 'my_hidden_status'` part, if you have a large number of posts (like Millions) and most of your posts (as you said 90%) are from that custom status. Still, there are two reasons why core may not update this part of the CODE even though there may be a little performance gain in your particular case: 1. **WordPress Database uses an index named `type_status_date`** that indexes `wp-posts` table entries based on `post_type`, `post_status`, `post_date` and `ID` fields. **So queries are fast enough even without the `AND post_status != 'my_hidden_status'` part**. I've tested with 15K+ posts and it only takes a few milliseconds. Check [this MySQL Document](https://dev.mysql.com/doc/refman/8.0/en/group-by-optimization.html) for more information on GROUP BY Optimization with index. With some tweaks to MySQL index, you may even get better results without even changing WP Core. For example, adding another index with `post_type` and `post_status` column may give you a few milliseconds gain. 2. Even though adding `AND post_status != 'my_hidden_status'` may make the query faster (merely by milliseconds) in your particular case, WordPress still may not update it, because WordPress will have to **consider the possibility where a hidden custom status has only a few posts**. In those cases, adding `AND post_status != 'my_hidden_status'` will actually make the query results a bit slower (only by a few milliseconds). So considering everything, WordPress may or may not update the query with `AND post_status != 'my_hidden_status'` when both `show_in_admin_all_list` and `show_in_admin_status_list` are set to `false` for a custom status. However, in my opinion, at least making the related query filterable will improve the flexibility for the developers.
308,517
<p>I have following foreach loop code...</p> <pre><code>&lt;?php $usernames = $wpdb-&gt;get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" ); foreach ( $usernames as $username ) { echo $username-&gt;user_name; } ?&gt; </code></pre> <p>When I use <code>echo $username-&gt;user_name;</code> it displays all the usernames from the <code>user_name</code> column of database. I want to display only the first username from the list. How to do... Pl help... Thanks...</p>
[ { "answer_id": 308519, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 1, "selected": false, "text": "<pre><code>$usernames = $wpdb-&gt;get_results( \"SELECT user_name FROM wpxa_project_members WHERE project_id = 698 LIMIT 1\" \n</code></pre>\n" }, { "answer_id": 308526, "author": "Minesh", "author_id": 124069, "author_profile": "https://wordpress.stackexchange.com/users/124069", "pm_score": -1, "selected": true, "text": "<p>I have found the solution... Here it is...</p>\n\n<pre><code>&lt;?php\n\n$usernames = $wpdb-&gt;get_results( \"SELECT user_name FROM wpxa_project_members WHERE project_id = 698\" );\n\nforeach ( $usernames as $username ) \n{\n $member_username[] = $username-&gt;user_name;\n}\n\necho $member_username[0];\n\n?&gt;\n</code></pre>\n\n<p>Hope it may help other users.</p>\n" }, { "answer_id": 308529, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>It's a little bit hard to guess, what exactly are you trying to achieve, but... Based on your answer, here's much cleaner and more secure code, you can use:</p>\n\n<pre><code>global $wpdb;\n$usernames = $wpdb-&gt;get_results(\n $wpdb-&gt;prepare(\n \"SELECT user_name FROM {$wpdb-&gt;prefix}project_members WHERE project_id = %d\",\n 698\n )\n);\n\nif ( ! empty($usernames) ) {\n echo $usernames[0]-&gt;user_name;\n} else {\n // there are no users\n}\n</code></pre>\n" } ]
2018/07/14
[ "https://wordpress.stackexchange.com/questions/308517", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124069/" ]
I have following foreach loop code... ``` <?php $usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" ); foreach ( $usernames as $username ) { echo $username->user_name; } ?> ``` When I use `echo $username->user_name;` it displays all the usernames from the `user_name` column of database. I want to display only the first username from the list. How to do... Pl help... Thanks...
I have found the solution... Here it is... ``` <?php $usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" ); foreach ( $usernames as $username ) { $member_username[] = $username->user_name; } echo $member_username[0]; ?> ``` Hope it may help other users.
308,520
<p>I want to hide the navigation menu on a particular page. I know how to find the page id, but I am clueless about how to find the rest of the stuff, it would be great if someone could look into my blog's css from the link - idkwhereto.com</p> <p>Thanks.</p>
[ { "answer_id": 308519, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 1, "selected": false, "text": "<pre><code>$usernames = $wpdb-&gt;get_results( \"SELECT user_name FROM wpxa_project_members WHERE project_id = 698 LIMIT 1\" \n</code></pre>\n" }, { "answer_id": 308526, "author": "Minesh", "author_id": 124069, "author_profile": "https://wordpress.stackexchange.com/users/124069", "pm_score": -1, "selected": true, "text": "<p>I have found the solution... Here it is...</p>\n\n<pre><code>&lt;?php\n\n$usernames = $wpdb-&gt;get_results( \"SELECT user_name FROM wpxa_project_members WHERE project_id = 698\" );\n\nforeach ( $usernames as $username ) \n{\n $member_username[] = $username-&gt;user_name;\n}\n\necho $member_username[0];\n\n?&gt;\n</code></pre>\n\n<p>Hope it may help other users.</p>\n" }, { "answer_id": 308529, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>It's a little bit hard to guess, what exactly are you trying to achieve, but... Based on your answer, here's much cleaner and more secure code, you can use:</p>\n\n<pre><code>global $wpdb;\n$usernames = $wpdb-&gt;get_results(\n $wpdb-&gt;prepare(\n \"SELECT user_name FROM {$wpdb-&gt;prefix}project_members WHERE project_id = %d\",\n 698\n )\n);\n\nif ( ! empty($usernames) ) {\n echo $usernames[0]-&gt;user_name;\n} else {\n // there are no users\n}\n</code></pre>\n" } ]
2018/07/14
[ "https://wordpress.stackexchange.com/questions/308520", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146922/" ]
I want to hide the navigation menu on a particular page. I know how to find the page id, but I am clueless about how to find the rest of the stuff, it would be great if someone could look into my blog's css from the link - idkwhereto.com Thanks.
I have found the solution... Here it is... ``` <?php $usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" ); foreach ( $usernames as $username ) { $member_username[] = $username->user_name; } echo $member_username[0]; ?> ``` Hope it may help other users.
308,532
<p>For some reason, I have to unpublish certain posts every time wordpress loads. This is my code: </p> <pre><code>function af_change_post_status() { $notpayed_posts = new WP_Query( array( 'meta_key' =&gt; '_payment', 'meta_value' =&gt; '0' ) ); foreach ($notpayed_posts as $notpayed_post) { wp_transition_post_status( 'draft', $notpayed_post-&gt;post_status, $notpayed_post); } } add_action( 'init', 'af_change_post_status' ); </code></pre> <p>The query is correct and it's returning the posts I want, but the <code>wp_transition_post_status</code> function is not working and I don't know why? </p>
[ { "answer_id": 308533, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 1, "selected": false, "text": "<p>It's pretty simple error. You use <code>WP_Query</code> to get posts, but then you try to use that <code>WP_Query</code> object as an array, but this class doesn't implement iterator, AFAIR.</p>\n\n<pre><code>function af_change_post_status() {\n $notpayed_posts = new WP_Query( array(\n 'meta_key' =&gt; '_payment',\n 'meta_value' =&gt; '0'\n ) );\n\n foreach ($notpayed_posts-&gt;posts as $notpayed_post) {\n wp_transition_post_status( 'draft', $notpayed_post-&gt;post_status, $notpayed_post);\n }\n}\nadd_action( 'init', 'af_change_post_status' );\n</code></pre>\n\n<p>This should work better (if your query is correct).</p>\n" }, { "answer_id": 308535, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 3, "selected": true, "text": "<blockquote>\n <p>This function contains do_action() calls for post status transition\n action hooks. The order of the words in the function name might be\n confusing – <strong>it does not change the status of posts, it only calls\n actions that can be hooked into by plugin developers.</strong></p>\n</blockquote>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wp_transition_post_status\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_transition_post_status</a></p>\n\n<p>What you want is <code>wp_update_post</code>, you're also using <code>WP_Query</code> incorrectly:</p>\n\n<p>```\n $notpayed_posts = new WP_Query( array(\n 'meta_key' => '_payment',\n 'meta_value' => '0'\n ) );</p>\n\n<pre><code>while ($notpayed_posts-&gt;have_posts()) {\n $notpayed_posts-&gt;the_post();\n wp_update_post( array(\n 'ID' =&gt; get_the_ID(),\n 'post_status' =&gt; 'draft'\n ));\n}\nwp_reset_postdata();\n</code></pre>\n\n<p>Also, keep in mind that your query is an expensive/very slow post meta query, post meta isn't built for searching or queries where you're looking for posts. Consider a taxonomy term.</p>\n\n<p>You also do nothing to change the meta afterwards, so if there are 10 posts that match, then every page load will try to update 10 posts, even if they've already been updated! Either change the meta value with <code>update_post_meta</code> or check the post status in the query, e.g.</p>\n\n<pre><code>$notpayed_posts = new WP_Query( array(\n 'post_status' =&gt; 'publish',\n 'meta_key' =&gt; '_payment',\n 'meta_value' =&gt; '0'\n) );\n</code></pre>\n\n<p>Additionally, use a cron job, don't do it on every page load by using the <code>init</code> hook, it's very bad for performance and incompatible with page caching</p>\n" } ]
2018/07/14
[ "https://wordpress.stackexchange.com/questions/308532", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136480/" ]
For some reason, I have to unpublish certain posts every time wordpress loads. This is my code: ``` function af_change_post_status() { $notpayed_posts = new WP_Query( array( 'meta_key' => '_payment', 'meta_value' => '0' ) ); foreach ($notpayed_posts as $notpayed_post) { wp_transition_post_status( 'draft', $notpayed_post->post_status, $notpayed_post); } } add_action( 'init', 'af_change_post_status' ); ``` The query is correct and it's returning the posts I want, but the `wp_transition_post_status` function is not working and I don't know why?
> > This function contains do\_action() calls for post status transition > action hooks. The order of the words in the function name might be > confusing – **it does not change the status of posts, it only calls > actions that can be hooked into by plugin developers.** > > > <https://codex.wordpress.org/Function_Reference/wp_transition_post_status> What you want is `wp_update_post`, you're also using `WP_Query` incorrectly: ``` $notpayed\_posts = new WP\_Query( array( 'meta\_key' => '\_payment', 'meta\_value' => '0' ) ); ``` while ($notpayed_posts->have_posts()) { $notpayed_posts->the_post(); wp_update_post( array( 'ID' => get_the_ID(), 'post_status' => 'draft' )); } wp_reset_postdata(); ``` Also, keep in mind that your query is an expensive/very slow post meta query, post meta isn't built for searching or queries where you're looking for posts. Consider a taxonomy term. You also do nothing to change the meta afterwards, so if there are 10 posts that match, then every page load will try to update 10 posts, even if they've already been updated! Either change the meta value with `update_post_meta` or check the post status in the query, e.g. ``` $notpayed_posts = new WP_Query( array( 'post_status' => 'publish', 'meta_key' => '_payment', 'meta_value' => '0' ) ); ``` Additionally, use a cron job, don't do it on every page load by using the `init` hook, it's very bad for performance and incompatible with page caching
308,542
<p>Hi i'm just begining with wordpress so any help would be appreciated. I trying to get this working but the response data is undefined because of the 400 error. I've tried everything. Here's my code.</p> <pre><code>function simokydesigns_translate_scripts() { wp_enqueue_script('customjquery', get_template_directory_uri() .'/js/customjquery.js', array('jquery')); wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin- ajax.php' ) ); } add_action( 'wp_enqueue_scripts', 'simokydesigns_translate_scripts' ); function get_ajax_sidebar(){ get_sidebar(); } add_action('wp_ajax_get_ajax_sidebar', 'get_ajax_sidebar'); add_action('wp_ajax_nopriv_get_ajax_sidebar', 'get_ajax_sidebar'); //js/customjquery.js (function($) { $.ajax({ type: 'POST', // use $_POST method to submit data dataType: "html", url: ajaxurl, data: { 'action': 'get_ajax_sidebar', }, success:function(data) { alert('Got this from the server: ' + data); //$( '#widget-top' ).html( data ); }, error: function (data) { console.log('error' + data); } }); /*$( '#widget-top').append( "&lt;?php echo get_sidebar();?&gt;" );*/ })( jQuery ); </code></pre>
[ { "answer_id": 308544, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>This line break here:</p>\n\n<pre><code>wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin- \n ajax.php' ) );\n</code></pre>\n\n<p>Means that the AJAX URL isn't correct. Make sure there's no line break:</p>\n\n<pre><code>wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin-ajax.php' ) );\n</code></pre>\n\n<p>When I made this fix and tested your code worked just fine.</p>\n\n<p>But just as an aside, a <code>POST</code> request is inappropriate for this use case. You're <em>getting</em> data (in this case HTML for a sidebar), not submitting data, so a <code>GET</code> request should be used.</p>\n" }, { "answer_id": 327473, "author": "Arturo Gallegos", "author_id": 130585, "author_profile": "https://wordpress.stackexchange.com/users/130585", "pm_score": 1, "selected": false, "text": "<p>You have two problems \nin PHP you need change this</p>\n\n<p>is bad:</p>\n\n<pre><code>wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin- \n ajax.php' ) );\n</code></pre>\n\n<p>change to:</p>\n\n<pre><code>wp_localize_script( 'customjquery', 'my_custom_vars', ['ajax_url' =&gt; admin_url('admin-ajax.php')] );\n</code></pre>\n\n<p>and your javascript need this changes</p>\n\n<p>is bad:</p>\n\n<pre><code>$.ajax({\n type: 'POST', // use $_POST method to submit data\n dataType: \"html\",\n url: ajaxurl,\n</code></pre>\n\n<p>change to:</p>\n\n<pre><code>$.ajax({\n type: 'POST', // use $_POST method to submit data\n dataType: \"html\",\n url: my_custom_vars.ajax_url,\n</code></pre>\n" } ]
2018/07/14
[ "https://wordpress.stackexchange.com/questions/308542", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146939/" ]
Hi i'm just begining with wordpress so any help would be appreciated. I trying to get this working but the response data is undefined because of the 400 error. I've tried everything. Here's my code. ``` function simokydesigns_translate_scripts() { wp_enqueue_script('customjquery', get_template_directory_uri() .'/js/customjquery.js', array('jquery')); wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin- ajax.php' ) ); } add_action( 'wp_enqueue_scripts', 'simokydesigns_translate_scripts' ); function get_ajax_sidebar(){ get_sidebar(); } add_action('wp_ajax_get_ajax_sidebar', 'get_ajax_sidebar'); add_action('wp_ajax_nopriv_get_ajax_sidebar', 'get_ajax_sidebar'); //js/customjquery.js (function($) { $.ajax({ type: 'POST', // use $_POST method to submit data dataType: "html", url: ajaxurl, data: { 'action': 'get_ajax_sidebar', }, success:function(data) { alert('Got this from the server: ' + data); //$( '#widget-top' ).html( data ); }, error: function (data) { console.log('error' + data); } }); /*$( '#widget-top').append( "<?php echo get_sidebar();?>" );*/ })( jQuery ); ```
You have two problems in PHP you need change this is bad: ``` wp_localize_script( 'customjquery', 'ajaxurl', admin_url( 'admin- ajax.php' ) ); ``` change to: ``` wp_localize_script( 'customjquery', 'my_custom_vars', ['ajax_url' => admin_url('admin-ajax.php')] ); ``` and your javascript need this changes is bad: ``` $.ajax({ type: 'POST', // use $_POST method to submit data dataType: "html", url: ajaxurl, ``` change to: ``` $.ajax({ type: 'POST', // use $_POST method to submit data dataType: "html", url: my_custom_vars.ajax_url, ```
308,552
<p>I am trying to get product attribute slug. I have used below code but it display name. </p> <pre><code>echo $_product-&gt;get_attribute( 'pa_color' ); </code></pre> <p>I am working on woocommerce/cart/cart.php file in theme folder.</p> <p>Also I checked this is coming in anchor url of product image in cart page but not getting it</p> <p><strong>anchor url</strong>: <a href="https://example.com/productos/sweatshirt/?attribute_pa_color=aa2757&amp;attribute_pa_talla=m" rel="nofollow noreferrer">https://example.com/productos/sweatshirt/?attribute_pa_color=aa2757&amp;attribute_pa_talla=m</a></p> <p>I am working on this from today morning but I have not get success. Please guide. </p> <p><a href="https://i.stack.imgur.com/b63TS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b63TS.png" alt="enter image description here"></a></p>
[ { "answer_id": 308556, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 2, "selected": false, "text": "<pre><code>$att=$_product-&gt;get_attribute('pa_color');\n\n$values = wc_get_product_terms( $product-&gt;id, 'pa_color', array( 'fields' =&gt; 'all' ) );\nforeach($values as $val){\n echo \"&lt;pre&gt;\";\n var_dump($val-&gt;slug);\n echo \"&lt;/pre&gt;\";\n}\n</code></pre>\n" }, { "answer_id": 308637, "author": "Abhilesh Sharma", "author_id": 145656, "author_profile": "https://wordpress.stackexchange.com/users/145656", "pm_score": 4, "selected": true, "text": "<p>I got this....</p>\n\n<p>To get slug use:</p>\n\n<pre><code>$attributes = $_product-&gt;get_attributes();\n$pa_color = $attributes[\"pa_color\"];\n</code></pre>\n\n<p>Thanks to all for helping me.</p>\n" }, { "answer_id": 331399, "author": "Adam Pery", "author_id": 73243, "author_profile": "https://wordpress.stackexchange.com/users/73243", "pm_score": -1, "selected": false, "text": "<p>Use next:</p>\n\n<pre><code>$attribute-&gt;get_name()\n</code></pre>\n" } ]
2018/07/14
[ "https://wordpress.stackexchange.com/questions/308552", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145656/" ]
I am trying to get product attribute slug. I have used below code but it display name. ``` echo $_product->get_attribute( 'pa_color' ); ``` I am working on woocommerce/cart/cart.php file in theme folder. Also I checked this is coming in anchor url of product image in cart page but not getting it **anchor url**: <https://example.com/productos/sweatshirt/?attribute_pa_color=aa2757&attribute_pa_talla=m> I am working on this from today morning but I have not get success. Please guide. [![enter image description here](https://i.stack.imgur.com/b63TS.png)](https://i.stack.imgur.com/b63TS.png)
I got this.... To get slug use: ``` $attributes = $_product->get_attributes(); $pa_color = $attributes["pa_color"]; ``` Thanks to all for helping me.
308,580
<p>I want to know how to change the login label such as Username or Email Address to Username within the wp-login.php?</p>
[ { "answer_id": 308583, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": -1, "selected": false, "text": "<p>@William : although your solution may work, it's not the proper way (which is why you got a downvote).</p>\n\n<p>What you really want to do is customize the login page. Start here: <a href=\"https://codex.wordpress.org/Customizing_the_Login_Form\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Customizing_the_Login_Form</a> </p>\n\n<p>On that page, you'll find this suggested code:</p>\n\n<pre><code>&lt;?php\nif ( ! is_user_logged_in() ) { // Display WordPress login form:\n $args = array(\n 'redirect' =&gt; admin_url(), \n 'form_id' =&gt; 'loginform-custom',\n 'label_username' =&gt; __( 'Username custom text' ),\n 'label_password' =&gt; __( 'Password custom text' ),\n 'label_remember' =&gt; __( 'Remember Me custom text' ),\n 'label_log_in' =&gt; __( 'Log In custom text' ),\n 'remember' =&gt; true\n );\n wp_login_form( $args );\n} else { // If logged in:\n wp_loginout( home_url() ); // Display \"Log Out\" link.\n echo \" | \";\n wp_register('', ''); // Display \"Site Admin\" link.\n}\n?&gt;\n</code></pre>\n\n<p>Better to do it the right way, rather than some DOM kludge. IMHO.</p>\n\n<p><strong>Added</strong></p>\n\n<p>As mentioned in the link, you can use the above code to set the $args you want to use. Just use the filter:</p>\n\n<blockquote>\n <p>This login form has the filters: login_form_top, login_form_middle,\n and login_form_bottom. Each can print text in the form, as shown in\n the image on the right.</p>\n</blockquote>\n\n<p>See the link for details on that, and the image referenced.</p>\n\n<p>**Added **</p>\n\n<p>If you look at the wp_login_form() function, you will see the source code referenced here: <a href=\"https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/general-template.php#L0\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/4.9.7/src/wp-includes/general-template.php#L0</a> . </p>\n\n<p>At line 419, you will see this line:</p>\n\n<pre><code>$args = wp_parse_args( $args, apply_filters( 'login_form_defaults', $defaults ) );\n</code></pre>\n\n<p>which tells you that you can change the login form $args by using the </p>\n\n<pre><code>add_filter('login_form_defaults', 'your_login_form_fields_function');\n</code></pre>\n\n<p>So there is a filter that can be used to change the login form values (see this code for the $args parameters, shown in the wp_login_form function (see above source code reference, starting at line 390).</p>\n\n<p>Which answers the question: how to change the login form fields/descriptions, by using the appropriate filter. And also shows that if you dig into the code a bit, you can find filters that might help you with a question.</p>\n" }, { "answer_id": 308596, "author": "anmari", "author_id": 3569, "author_profile": "https://wordpress.stackexchange.com/users/3569", "pm_score": -1, "selected": false, "text": "<p>Another way to change the text for any wordpress text is to do a 'translation'. WP by default is in en-US, you could add (for example) en_AU (Ausatraian English). Any translations not provided, will use the default language. You could use any translation plugin or editor to create 'translations' just for the text's that you want to change. Basically give your website an 'accent' ;) </p>\n" }, { "answer_id": 308630, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 2, "selected": false, "text": "<p>All of these strings/labels are passed through translation functions, so you can use <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext\" rel=\"nofollow noreferrer\"><code>gettext</code></a> filter to modify them.</p>\n\n<pre><code>function change_labels( $translated_text, $text, $domain ) {\n if ( 'Username' === $text ) {\n $translated_text = 'Username new label';\n }\n return $translated_text;\n}\n\nfunction register_change_label_filter() {\n add_filter( 'gettext', 'change_labels', 20, 3 );\n}\nadd_action( 'login_head', 'register_change_labels_filter' );\n// this way our filter will work only on wp-login and not everywhere on site...\n</code></pre>\n" } ]
2018/07/14
[ "https://wordpress.stackexchange.com/questions/308580", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146914/" ]
I want to know how to change the login label such as Username or Email Address to Username within the wp-login.php?
All of these strings/labels are passed through translation functions, so you can use [`gettext`](https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext) filter to modify them. ``` function change_labels( $translated_text, $text, $domain ) { if ( 'Username' === $text ) { $translated_text = 'Username new label'; } return $translated_text; } function register_change_label_filter() { add_filter( 'gettext', 'change_labels', 20, 3 ); } add_action( 'login_head', 'register_change_labels_filter' ); // this way our filter will work only on wp-login and not everywhere on site... ```
308,591
<p>I have added custom field in woocommerce Products>General Tab. But I am not getting those custom fields value in response using following link:- <a href="http://yoursite.com/wp-json/wc/v2/products/" rel="nofollow noreferrer">http://yoursite.com/wp-json/wc/v2/products/</a></p> <p>My Code:-</p> <pre><code>//Display Fields add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' ); //Save Fields add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' ); function woo_add_custom_general_fields() { global $woocommerce, $post; echo '&lt;div class="options_group"&gt;' ; //Purchasing Cost woocommerce_wp_text_input( array( 'id' =&gt; 'purchasing_cost', 'placeholder' =&gt; 'Purchasing Cost', 'label' =&gt; __('Purchasing Cost', 'woocommerce'), 'type' =&gt; 'text', 'show_in_rest' =&gt; true, 'rest_base' =&gt; 'products', 'rest_controller_class' =&gt; 'WP_REST_Products_Controller', ) ); //OverHead woocommerce_wp_text_input( array( 'id' =&gt; 'overhead', 'placeholder' =&gt; 'Overhead', 'label' =&gt; __('Overhead', 'woocommerce'), 'type' =&gt; 'text', 'show_in_rest' =&gt; true, 'rest_base' =&gt; 'products', 'rest_controller_class' =&gt; 'WP_REST_Products_Controller', ) ); echo '&lt;/div&gt;'; } //To Save data function woo_add_custom_general_fields_save($post_id) { //Purchasing Cost $woocommerce_purchasing_cost_field = $_POST['purchasing_cost']; if (!empty($woocommerce_purchasing_cost_field)) update_post_meta($post_id, 'purchasing_cost', esc_attr($woocommerce_purchasing_cost_field)); //OverHead $woocommerce_overhead_field = $_POST['overhead']; if (!empty($woocommerce_overhead_field)) update_post_meta($post_id, 'overhead', esc_attr($woocommerce_overhead_field)); } </code></pre> <p>Thanks in Advance.</p>
[ { "answer_id": 308608, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 2, "selected": false, "text": "<p>You should ad the custom field to product API response, try this\n (untested)</p>\n\n<pre><code>add_filter( 'woocommerce_rest_prepare_product', 'custom_products_api_data', 90, 2 );\nfunction custom_products_api_data( $response, $post ) {\n\n// retrieve a custom field and add it to API response\n$response-&gt;data['purchasing_cost'] = get_post_meta( $post-&gt;ID, 'purchasing_cost', true );\n\nreturn $response;\n}\n</code></pre>\n" }, { "answer_id": 308674, "author": "MAYANK SONKAR", "author_id": 146897, "author_profile": "https://wordpress.stackexchange.com/users/146897", "pm_score": 1, "selected": false, "text": "<p>Answer to My Question</p>\n\n<pre><code>add_action( 'rest_api_init', 'slug_register_purchasing' );\n\nfunction slug_register_purchasing() {\n register_rest_field( 'product',\n 'purchasing_cost',\n array(\n 'get_callback' =&gt; 'slug_get_purchasing_cost',\n 'update_callback' =&gt; null,\n 'schema' =&gt; null,\n )\n );\n }\n\nfunction slug_get_purchasing_cost( $object, $field_name, $request ) {\n return get_post_meta( $object[ 'id' ], $field_name, true );\n}\n\nadd_action( 'rest_api_init', 'slug_register_overhead' );\n\nfunction slug_register_overhead() {\n register_rest_field( 'product',\n 'overhead',\n array(\n 'get_callback' =&gt; 'slug_get_overhead',\n 'update_callback' =&gt; null,\n 'schema' =&gt; null,\n )\n );\n}\n\n\n\nfunction slug_get_overhead( $object, $field_name, $request ) {\n return get_post_meta( $object[ 'id' ], $field_name, true );\n}\n</code></pre>\n\n<p>For Detailed Description \n<a href=\"http://v2.wp-api.org/extending/modifying/\" rel=\"nofollow noreferrer\">http://v2.wp-api.org/extending/modifying/</a> </p>\n" } ]
2018/07/15
[ "https://wordpress.stackexchange.com/questions/308591", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146897/" ]
I have added custom field in woocommerce Products>General Tab. But I am not getting those custom fields value in response using following link:- <http://yoursite.com/wp-json/wc/v2/products/> My Code:- ``` //Display Fields add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' ); //Save Fields add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' ); function woo_add_custom_general_fields() { global $woocommerce, $post; echo '<div class="options_group">' ; //Purchasing Cost woocommerce_wp_text_input( array( 'id' => 'purchasing_cost', 'placeholder' => 'Purchasing Cost', 'label' => __('Purchasing Cost', 'woocommerce'), 'type' => 'text', 'show_in_rest' => true, 'rest_base' => 'products', 'rest_controller_class' => 'WP_REST_Products_Controller', ) ); //OverHead woocommerce_wp_text_input( array( 'id' => 'overhead', 'placeholder' => 'Overhead', 'label' => __('Overhead', 'woocommerce'), 'type' => 'text', 'show_in_rest' => true, 'rest_base' => 'products', 'rest_controller_class' => 'WP_REST_Products_Controller', ) ); echo '</div>'; } //To Save data function woo_add_custom_general_fields_save($post_id) { //Purchasing Cost $woocommerce_purchasing_cost_field = $_POST['purchasing_cost']; if (!empty($woocommerce_purchasing_cost_field)) update_post_meta($post_id, 'purchasing_cost', esc_attr($woocommerce_purchasing_cost_field)); //OverHead $woocommerce_overhead_field = $_POST['overhead']; if (!empty($woocommerce_overhead_field)) update_post_meta($post_id, 'overhead', esc_attr($woocommerce_overhead_field)); } ``` Thanks in Advance.
You should ad the custom field to product API response, try this (untested) ``` add_filter( 'woocommerce_rest_prepare_product', 'custom_products_api_data', 90, 2 ); function custom_products_api_data( $response, $post ) { // retrieve a custom field and add it to API response $response->data['purchasing_cost'] = get_post_meta( $post->ID, 'purchasing_cost', true ); return $response; } ```
308,611
<p>I am using <code>save_post</code> for a function to send an email when a post is updated by a user. This is firing twice and I am aware this is due to the post revisions and autosaves. </p> <p>I have tried to prevent this from happening by wrapping my <code>wp_mail</code> within a conditional statement but this still fires twice. What adjustments do I need to make to ensure this only fires once when a user updates the post? </p> <pre><code>function updated_search_notification($post_id) { $post_type = get_post_type($post_id); if ($post_type === 'utility-search') { if ((wp_is_post_revision($post_id)) || (wp_is_post_autosave($post_id))) { // post is autosave } else { // Message Variables $siteurl = get_option('siteurl'); $post_url = '' . $siteurl . '/wp-admin/post.php?post=' . $post_id . '&amp;action=edit'; $new_search_name = ''; //$new_search_email = get_option( 'new_search_email' ); $new_search_email = '[email]'; $utility_search_customer = ''; $subject = 'Your search has been updated'; // Message Contents $message = "[Message Contents]"; // Send Email wp_mail($new_search_email, $subject, $message); } } } add_action('save_post', 'updated_search_notification', 10, 3); </code></pre>
[ { "answer_id": 308612, "author": "Atlas_Gondal", "author_id": 132879, "author_profile": "https://wordpress.stackexchange.com/users/132879", "pm_score": 0, "selected": false, "text": "<p>Try this piece of code inside your function:</p>\n\n<pre><code>if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) return;\n</code></pre>\n\n<p>Alternatively, you can use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/publish_post\" rel=\"nofollow noreferrer\">publish_post</a> hook. If you just want to trigger this function when the post status is publish.</p>\n" }, { "answer_id": 308623, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 4, "selected": true, "text": "<p>First, you can use this hook to target only one custom type:<br>\n<a href=\"https://developer.wordpress.org/reference/hooks/save_post_post-post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/save_post_post-post_type/</a></p>\n\n<p>This hook (and <code>save_post</code>) is called the first time when you click on \"new ...\" and then the hook is called with <code>$update = FALSE</code>. </p>\n\n<p>Then to send e-mail only when the object is updated, you can test <code>$update</code> like this: </p>\n\n<pre><code>const UTILITY_SEARCH_POST_TYPE = \"utility-search\";\n\n\nadd_action(\"save_post_\" . UTILITY_SEARCH_POST_TYPE, function ($post_ID, $post, $update) {\n\n if (wp_is_post_autosave($post_ID)) {\n return;\n }\n\n if (!$update) { // if new object\n return;\n }\n\n\n // preparing e-mail\n ...\n\n // sending e-mail\n wp_mail(...);\n\n\n}, 10, 3);\n</code></pre>\n" }, { "answer_id": 337417, "author": "Uriahs Victor", "author_id": 76433, "author_profile": "https://wordpress.stackexchange.com/users/76433", "pm_score": 3, "selected": false, "text": "<p>The approved answer didn't work for me. I ended up trying several conditionals and the email would still get sent twice:</p>\n\n<pre><code>function xxx_send_mail($id, $post, $update){ \n\n if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n\n if (wp_is_post_revision($id)) {\n return;\n }\n\n if (wp_is_post_autosave($id)) {\n return;\n }\n\n // if new post\n if (!$update) {\n return;\n }\n\n wp_mail('[email protected]', 'The subject', 'The message');\n }\nadd_action( 'save_post_{the_post_type}', 'xxx_send_mail', 10, 3 );\n</code></pre>\n\n<p>I ended up fixing this by adding a convinient function provided by WP called <a href=\"https://developer.wordpress.org/reference/functions/did_action/\" rel=\"noreferrer\">did_action()</a>:</p>\n\n<pre><code> function xxx_send_mail($id, $post, $update){ \n\n if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE ) {\n return;\n }\n\n if (wp_is_post_revision($id)) {\n return;\n }\n\n if (wp_is_post_autosave($id)) {\n return;\n }\n\n // if new post\n if (!$update) {\n return;\n }\n\n $times = did_action('save_post_{the_post_type}');\n if( $times === 1){\n wp_mail('[email protected]', 'The subject', 'The message');\n }\n }\nadd_action( 'save_post_{the_post_type}', 'xxx_send_mail', 10, 3 );\n</code></pre>\n\n<p>Hope this helps someone</p>\n" }, { "answer_id": 396549, "author": "Saqib", "author_id": 68054, "author_profile": "https://wordpress.stackexchange.com/users/68054", "pm_score": 2, "selected": false, "text": "<p>Already approved answers have not worked for me and comment from @Nico Pernice helped.</p>\n<p>If conditions in my code look like these:</p>\n<pre><code>function reset_cpt_expire( $post_id, $post, $update ){\n\n // Check if it is a REST Request\n if ( defined( 'REST_REQUEST' ) &amp;&amp; REST_REQUEST ) {\n return;\n }\n\n // Check if it is an autosave or a revision.\n if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {\n return;\n }\n\n // Check if it is a new post\n if ( ! $update ) {\n return;\n }\n\n // my reseting code...\n\n}\n\nadd_action( 'save_post_cpt', 'reset_cpt_expire', 10,3 );\n</code></pre>\n" }, { "answer_id": 414062, "author": "Azhar Khan", "author_id": 230198, "author_profile": "https://wordpress.stackexchange.com/users/230198", "pm_score": 0, "selected": false, "text": "<p>If you're having an issue where the publish_post hook is being triggered twice you can try using a global variable to keep track of whether the hook has already been triggered.</p>\n<pre><code>// Declare a global variable\nglobal $publish_post_hook_triggered;\n$publish_post_hook_triggered = false;\n\nadd_action('publish_post', 'my_publish_post_function');\n\nfunction my_publish_post_function($post_id) {\n // Check if the hook has already been triggered\n global $publish_post_hook_triggered;\n if ($publish_post_hook_triggered) {\n return;\n }\n // Set the global variable to indicate that the hook has been triggered\n $publish_post_hook_triggered = true;\n\n // Your code to run when the hook is triggered\n}\n</code></pre>\n" } ]
2018/07/15
[ "https://wordpress.stackexchange.com/questions/308611", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64567/" ]
I am using `save_post` for a function to send an email when a post is updated by a user. This is firing twice and I am aware this is due to the post revisions and autosaves. I have tried to prevent this from happening by wrapping my `wp_mail` within a conditional statement but this still fires twice. What adjustments do I need to make to ensure this only fires once when a user updates the post? ``` function updated_search_notification($post_id) { $post_type = get_post_type($post_id); if ($post_type === 'utility-search') { if ((wp_is_post_revision($post_id)) || (wp_is_post_autosave($post_id))) { // post is autosave } else { // Message Variables $siteurl = get_option('siteurl'); $post_url = '' . $siteurl . '/wp-admin/post.php?post=' . $post_id . '&action=edit'; $new_search_name = ''; //$new_search_email = get_option( 'new_search_email' ); $new_search_email = '[email]'; $utility_search_customer = ''; $subject = 'Your search has been updated'; // Message Contents $message = "[Message Contents]"; // Send Email wp_mail($new_search_email, $subject, $message); } } } add_action('save_post', 'updated_search_notification', 10, 3); ```
First, you can use this hook to target only one custom type: <https://developer.wordpress.org/reference/hooks/save_post_post-post_type/> This hook (and `save_post`) is called the first time when you click on "new ..." and then the hook is called with `$update = FALSE`. Then to send e-mail only when the object is updated, you can test `$update` like this: ``` const UTILITY_SEARCH_POST_TYPE = "utility-search"; add_action("save_post_" . UTILITY_SEARCH_POST_TYPE, function ($post_ID, $post, $update) { if (wp_is_post_autosave($post_ID)) { return; } if (!$update) { // if new object return; } // preparing e-mail ... // sending e-mail wp_mail(...); }, 10, 3); ```
308,656
<p>I am using WP_Query to loop a Custom Field, Custom Post Type that shows 6 Menu Icons across 6 horizontal fields. The icons do not show on the page. </p> <p>My query code is:</p> <pre><code>&lt;?php $loop = new WP_Query( array( 'post_type' =&gt; 'course_feature', 'orderby', =&gt; 'post_id', 'order' =&gt; 'ASC')); ?&gt; </code></pre> <p>code to show loop:</p> <pre><code>&lt;?php while( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;div class="col-sm-2"&gt; &lt;i class=&lt;?php the_field('course_feature_icon'); ?&gt;"&lt;/i&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; </code></pre>
[ { "answer_id": 308657, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>There's a missing opening quote and closing bracket on this line:</p>\n\n<pre><code>&lt;i class=&lt;?php the_field('course_feature_icon'); ?&gt;\"&lt;/i&gt;\n</code></pre>\n\n<p>Needs to be:</p>\n\n<pre><code>&lt;i class=\"&lt;?php the_field('course_feature_icon'); ?&gt;\"&gt;&lt;/i&gt;\n</code></pre>\n\n<p>That's all that's wrong with your code. It should then work assuming:</p>\n\n<ol>\n<li>You have a custom field, <code>course_feature_icon</code>, whose value is a valid CSS class.</li>\n<li>You have the necessary CSS to add an icon based on that class.</li>\n</ol>\n\n<p>One last suggestion though. For safety you should <a href=\"https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/\" rel=\"nofollow noreferrer\">escape</a> the field value before outputting it as a class:</p>\n\n<pre><code>&lt;i class=\"&lt;?php echo esc_attr( get_field('course_feature_icon') ); ?&gt;\"&gt;&lt;/i&gt;\n</code></pre>\n" }, { "answer_id": 308766, "author": "Gande", "author_id": 146589, "author_profile": "https://wordpress.stackexchange.com/users/146589", "pm_score": 0, "selected": false, "text": "<p>The icons still do not show. The course_features titles that appear beneath each icon shows, but the icons do not show.</p>\n\n<p>So, I have 6 columns of text, but the icons do not appear above the text. Not sure what to do … I tried the suggested edits. The icons do not show. </p>\n\n<p>I have them as a custom field group: course_feature_icon, field type: Radio button, choices: .ci ci-computer, and 5 additional names. (css icon sprite name). </p>\n" } ]
2018/07/16
[ "https://wordpress.stackexchange.com/questions/308656", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146589/" ]
I am using WP\_Query to loop a Custom Field, Custom Post Type that shows 6 Menu Icons across 6 horizontal fields. The icons do not show on the page. My query code is: ``` <?php $loop = new WP_Query( array( 'post_type' => 'course_feature', 'orderby', => 'post_id', 'order' => 'ASC')); ?> ``` code to show loop: ``` <?php while( $loop->have_posts() ) : $loop->the_post(); ?> <div class="col-sm-2"> <i class=<?php the_field('course_feature_icon'); ?>"</i> </div> <?php endwhile; ?> ```
There's a missing opening quote and closing bracket on this line: ``` <i class=<?php the_field('course_feature_icon'); ?>"</i> ``` Needs to be: ``` <i class="<?php the_field('course_feature_icon'); ?>"></i> ``` That's all that's wrong with your code. It should then work assuming: 1. You have a custom field, `course_feature_icon`, whose value is a valid CSS class. 2. You have the necessary CSS to add an icon based on that class. One last suggestion though. For safety you should [escape](https://developer.wordpress.org/themes/theme-security/data-sanitization-escaping/) the field value before outputting it as a class: ``` <i class="<?php echo esc_attr( get_field('course_feature_icon') ); ?>"></i> ```
308,661
<p>How can I change the menu icon (coming from external plugins, like WooCommerce) in wp-admin area with custom icon? (The menu-item is actually <code>post-type</code>, so there should be some <code>register_post_type</code> command i think).</p>
[ { "answer_id": 308665, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 0, "selected": false, "text": "<p>to add a custom image, you can use this code. the original image is set with CSS then you have to add custom CSS to remove that.</p>\n\n<pre><code>add_action(\"admin_menu\", function () {\n\n foreach ($GLOBALS[\"menu\"] as $position =&gt; $tab) {\n\n if (\"woocommerce\" === $tab[\"2\"]) {\n $GLOBALS[\"menu\"][$position][6] = \"http://server/image.png\";\n break;\n }\n\n }\n\n\n});\n</code></pre>\n" }, { "answer_id": 308668, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<p>WooCommerce styles the icon via this CSS file: <code>woocommerce/assets/css/menu.css</code>, and here's the corresponding code (<em>pretty-printed</em> or actually, I copied it from <a href=\"https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/assets/css/menu.scss#L17\" rel=\"nofollow noreferrer\"><code>woocommerce/assets/css/menu.scss</code></a>):</p>\n\n<pre><code>#adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before {\n font-family: 'WooCommerce' !important;\n content: '\\e03d';\n}\n</code></pre>\n\n<p>So you can change the <code>font-family</code> and the <code>content</code> (and other) properties to suit your custom icon.</p>\n\n<hr>\n\n<p>Below is an example of customizing the icon by changing it to use a <code>background-image</code>:</p>\n\n<pre><code>// We hook to the `admin_enqueue_scripts` action with a priority of `11`, where\n// at this point, the default CSS file should have been loaded. But you can or\n// should add the CSS rule to your custom CSS file; just make sure it's loaded\n// *after* the default CSS file.\nadd_action( 'admin_enqueue_scripts', function(){\n $css = &lt;&lt;&lt;EOT\n#adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before {\n content: ' ';\n background: url('https://png.icons8.com/dusk/2x/e-commerce.png') no-repeat center;\n background-size: contain;\n}\nEOT;\n\n wp_add_inline_style( 'woocommerce_admin_menu_styles', $css );\n}, 11 );\n</code></pre>\n\n<p>Note: The <code>menu.css</code> file is registered and queued in <a href=\"https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/includes/admin/class-wc-admin-assets.php#L28\" rel=\"nofollow noreferrer\"><code>WC_Admin_Assets::admin_styles()</code></a> with the handle/name of <code>woocommerce_admin_menu_styles</code>.</p>\n" } ]
2018/07/16
[ "https://wordpress.stackexchange.com/questions/308661", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146914/" ]
How can I change the menu icon (coming from external plugins, like WooCommerce) in wp-admin area with custom icon? (The menu-item is actually `post-type`, so there should be some `register_post_type` command i think).
WooCommerce styles the icon via this CSS file: `woocommerce/assets/css/menu.css`, and here's the corresponding code (*pretty-printed* or actually, I copied it from [`woocommerce/assets/css/menu.scss`](https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/assets/css/menu.scss#L17)): ``` #adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before { font-family: 'WooCommerce' !important; content: '\e03d'; } ``` So you can change the `font-family` and the `content` (and other) properties to suit your custom icon. --- Below is an example of customizing the icon by changing it to use a `background-image`: ``` // We hook to the `admin_enqueue_scripts` action with a priority of `11`, where // at this point, the default CSS file should have been loaded. But you can or // should add the CSS rule to your custom CSS file; just make sure it's loaded // *after* the default CSS file. add_action( 'admin_enqueue_scripts', function(){ $css = <<<EOT #adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before { content: ' '; background: url('https://png.icons8.com/dusk/2x/e-commerce.png') no-repeat center; background-size: contain; } EOT; wp_add_inline_style( 'woocommerce_admin_menu_styles', $css ); }, 11 ); ``` Note: The `menu.css` file is registered and queued in [`WC_Admin_Assets::admin_styles()`](https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/includes/admin/class-wc-admin-assets.php#L28) with the handle/name of `woocommerce_admin_menu_styles`.
308,695
<p>I have Used the function <code>dynamic_sidebar('sidebarId')</code> in the <code>sidebar.php</code> file.</p> <p>and all the functionality of the sidebar is Working succsessfully </p> <p>My Question is How To Change the Html of the sidebar widgets and add some classes in widget items To fit My Design ?</p> <p><a href="https://i.stack.imgur.com/Ka4ki.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ka4ki.png" alt="enter image description here"></a> Thank You in advance</p>
[ { "answer_id": 308665, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 0, "selected": false, "text": "<p>to add a custom image, you can use this code. the original image is set with CSS then you have to add custom CSS to remove that.</p>\n\n<pre><code>add_action(\"admin_menu\", function () {\n\n foreach ($GLOBALS[\"menu\"] as $position =&gt; $tab) {\n\n if (\"woocommerce\" === $tab[\"2\"]) {\n $GLOBALS[\"menu\"][$position][6] = \"http://server/image.png\";\n break;\n }\n\n }\n\n\n});\n</code></pre>\n" }, { "answer_id": 308668, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 1, "selected": false, "text": "<p>WooCommerce styles the icon via this CSS file: <code>woocommerce/assets/css/menu.css</code>, and here's the corresponding code (<em>pretty-printed</em> or actually, I copied it from <a href=\"https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/assets/css/menu.scss#L17\" rel=\"nofollow noreferrer\"><code>woocommerce/assets/css/menu.scss</code></a>):</p>\n\n<pre><code>#adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before {\n font-family: 'WooCommerce' !important;\n content: '\\e03d';\n}\n</code></pre>\n\n<p>So you can change the <code>font-family</code> and the <code>content</code> (and other) properties to suit your custom icon.</p>\n\n<hr>\n\n<p>Below is an example of customizing the icon by changing it to use a <code>background-image</code>:</p>\n\n<pre><code>// We hook to the `admin_enqueue_scripts` action with a priority of `11`, where\n// at this point, the default CSS file should have been loaded. But you can or\n// should add the CSS rule to your custom CSS file; just make sure it's loaded\n// *after* the default CSS file.\nadd_action( 'admin_enqueue_scripts', function(){\n $css = &lt;&lt;&lt;EOT\n#adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before {\n content: ' ';\n background: url('https://png.icons8.com/dusk/2x/e-commerce.png') no-repeat center;\n background-size: contain;\n}\nEOT;\n\n wp_add_inline_style( 'woocommerce_admin_menu_styles', $css );\n}, 11 );\n</code></pre>\n\n<p>Note: The <code>menu.css</code> file is registered and queued in <a href=\"https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/includes/admin/class-wc-admin-assets.php#L28\" rel=\"nofollow noreferrer\"><code>WC_Admin_Assets::admin_styles()</code></a> with the handle/name of <code>woocommerce_admin_menu_styles</code>.</p>\n" } ]
2018/07/16
[ "https://wordpress.stackexchange.com/questions/308695", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/142085/" ]
I have Used the function `dynamic_sidebar('sidebarId')` in the `sidebar.php` file. and all the functionality of the sidebar is Working succsessfully My Question is How To Change the Html of the sidebar widgets and add some classes in widget items To fit My Design ? [![enter image description here](https://i.stack.imgur.com/Ka4ki.png)](https://i.stack.imgur.com/Ka4ki.png) Thank You in advance
WooCommerce styles the icon via this CSS file: `woocommerce/assets/css/menu.css`, and here's the corresponding code (*pretty-printed* or actually, I copied it from [`woocommerce/assets/css/menu.scss`](https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/assets/css/menu.scss#L17)): ``` #adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before { font-family: 'WooCommerce' !important; content: '\e03d'; } ``` So you can change the `font-family` and the `content` (and other) properties to suit your custom icon. --- Below is an example of customizing the icon by changing it to use a `background-image`: ``` // We hook to the `admin_enqueue_scripts` action with a priority of `11`, where // at this point, the default CSS file should have been loaded. But you can or // should add the CSS rule to your custom CSS file; just make sure it's loaded // *after* the default CSS file. add_action( 'admin_enqueue_scripts', function(){ $css = <<<EOT #adminmenu #toplevel_page_woocommerce .menu-icon-generic div.wp-menu-image::before { content: ' '; background: url('https://png.icons8.com/dusk/2x/e-commerce.png') no-repeat center; background-size: contain; } EOT; wp_add_inline_style( 'woocommerce_admin_menu_styles', $css ); }, 11 ); ``` Note: The `menu.css` file is registered and queued in [`WC_Admin_Assets::admin_styles()`](https://plugins.trac.wordpress.org/browser/woocommerce/tags/3.4.3/includes/admin/class-wc-admin-assets.php#L28) with the handle/name of `woocommerce_admin_menu_styles`.
308,700
<p>My parent theme calls a function:</p> <pre><code>function get_nav_markup() { ob_start(); ?&gt; &lt;nav class="navbar navbar-toggleable-md navbar-inverse site-navbar" role="navigation"&gt; &lt;div class="container"&gt; &lt;?php if ( is_home() ): ?&gt; &lt;h1 class="navbar-brand mb-0"&gt; &lt;?php echo get_sitename_formatted(); ?&gt; &lt;/h1&gt; &lt;?php else: ?&gt; &lt;a href="&lt;?php echo bloginfo( 'url' ); ?&gt;" class="navbar-brand"&gt; &lt;?php echo get_sitename_formatted(); ?&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#header-menu" aria-controls="header-menu" aria-expanded="false" aria-label="Toggle navigation"&gt; &lt;span class="navbar-toggler-icon"&gt;&lt;/span&gt; &lt;/button&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'header-menu', 'depth' =&gt; 2, 'container' =&gt; 'div', 'container_class' =&gt; 'collapse navbar-collapse', 'container_id' =&gt; 'header-menu', 'menu_class' =&gt; 'nav navbar-nav ml-md-auto', ) ); ?&gt; &lt;/div&gt; &lt;/nav&gt; &lt;?php return ob_get_clean(); } </code></pre> <p>and then later uses it like so:</p> <pre><code>function get_header_markup() { global $post; echo get_nav_markup( $post ); $videos = get_header_videos( $post ); $images = get_header_images( $post ); if ( $videos || $images ) { echo get_header_media_markup( $post, $videos, $images ); } else { echo get_header_default_markup( $post ); } } </code></pre> <p>Is there anyway that I can overwrite get_nav_markup or at least append additional information immediately after it in my child theme? </p> <p>Given the way the parent theme function written I don't think I can. But I really need to be able to add some additional DIVs and PHP right after the /nav</p>
[ { "answer_id": 308702, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>No, it doesn't appear to be possible. At least not directly. You can replace functions in parent themes if they are wrapped in:</p>\n\n<pre><code>if ( ! function_exists( 'get_nav_markup' ) ) {\n}\n</code></pre>\n\n<p>Because child themes are loaded before the parent this gives you an opportunity to define <code>get_nav_markup()</code> before the parent theme is loaded. That <code>if</code> statement means that the parent function won't register the function if you already have in the child theme.</p>\n\n<p>If the parent theme had hooked the function with <code>add_action()</code>, like this:</p>\n\n<pre><code>add_action( 'hook_name', 'get_nav_markup' );\n</code></pre>\n\n<p>Then you could have replaced the function by writing your own and hooking it in place of the original function:</p>\n\n<pre><code>remove_action( 'hook_name', 'get_nav_markup' );\nadd_action( 'hook_name', 'my_get_nav_markup' );\n</code></pre>\n\n<p>So since the parent theme does not do either of these, your only option is to make the replacement at the template level. You will need to:</p>\n\n<ol>\n<li>Copy the <code>get_nav_markup()</code> function to your child theme, but rename it. Then make whatever change you want to make to it.</li>\n<li>Copy the <code>get_header_markup()</code> function to your child theme, rename it, and replace the reference to <code>get_nav_markup()</code> to the renamed and modified copy in your child theme.</li>\n<li>Find whichever template uses <code>get_header_markup()</code>, presumably header.php, copy it to your child theme, so that it replaces the parent theme's, and change the reference to <code>get_header_markup()</code> to your renamed and modified version.</li>\n</ol>\n" }, { "answer_id": 308706, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 1, "selected": false, "text": "<p>if <em>get_header_markup()</em> is used in a template page you can easily overwrite the template of the parent theme with a file named in the same way ( suppose the template file is <em>theme/template1.php</em> create a file named <em>child-theme/template1.php</em> in your child theme folder) and call a new custom function from there. </p>\n\n<pre><code>echo NEW_get_nav_markup( $post );\n</code></pre>\n\n<p>otherwise, you need to check if the <em>get_header_markup()</em> has been called via <em>add_action()</em> somewhere, in this case you can remove and add a new one</p>\n\n<pre><code>remove_action('called hook','get_header_markup', 10, 2);\nadd_action('called hook','NEW_get_header_markup', 10, 2);\n</code></pre>\n\n<p>if this is the case remember that to remove an action prevoiously added via add_action() you have to use same priority and arguments.</p>\n\n<p>In my experience, being a theme-based architecture (not plugin) it's almost always possible, starting from the template file that outputs contents, to find, way back, a point where overwrite the original functions using template files of the child theme.</p>\n" }, { "answer_id": 308710, "author": "yourenotthere", "author_id": 146418, "author_profile": "https://wordpress.stackexchange.com/users/146418", "pm_score": 1, "selected": true, "text": "<p>Ok so here is what I have decided given the situation. </p>\n\n<ol>\n<li>I have copied the header.php file into my child theme.</li>\n<li>I have changed the line in the header file from get_header_markup(); to get_header_markup_updated();</li>\n<li>I have then created a new function in my child themes function.php file called get_header_markup_updated.</li>\n<li>I started the function off my copying the existing one from the parent theme, but then added the code I needed... where I needed it. </li>\n</ol>\n\n<p>The result now looks like: </p>\n\n<pre><code>function get_header_markup_updated() {\n global $post;\n echo get_nav_markup( $post ); ?&gt;\n&lt;div class=\"breadcrumbnav\"&gt;\n &lt;!-- Inserted all my other code here --&gt; \n&lt;/div&gt;\n&lt;?php \n $videos = get_header_videos( $post );\n $images = get_header_images( $post );\n\n if ( $videos || $images ) {\n echo get_header_media_markup( $post, $videos, $images );\n }\n else {\n echo get_header_default_markup( $post );\n }\n}\n?&gt;\n</code></pre>\n\n<p>This seems to be working just fine. Hopefully this will also be the least obtrusive going forward. </p>\n" } ]
2018/07/16
[ "https://wordpress.stackexchange.com/questions/308700", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/146418/" ]
My parent theme calls a function: ``` function get_nav_markup() { ob_start(); ?> <nav class="navbar navbar-toggleable-md navbar-inverse site-navbar" role="navigation"> <div class="container"> <?php if ( is_home() ): ?> <h1 class="navbar-brand mb-0"> <?php echo get_sitename_formatted(); ?> </h1> <?php else: ?> <a href="<?php echo bloginfo( 'url' ); ?>" class="navbar-brand"> <?php echo get_sitename_formatted(); ?> </a> <?php endif; ?> <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#header-menu" aria-controls="header-menu" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <?php wp_nav_menu( array( 'theme_location' => 'header-menu', 'depth' => 2, 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'header-menu', 'menu_class' => 'nav navbar-nav ml-md-auto', ) ); ?> </div> </nav> <?php return ob_get_clean(); } ``` and then later uses it like so: ``` function get_header_markup() { global $post; echo get_nav_markup( $post ); $videos = get_header_videos( $post ); $images = get_header_images( $post ); if ( $videos || $images ) { echo get_header_media_markup( $post, $videos, $images ); } else { echo get_header_default_markup( $post ); } } ``` Is there anyway that I can overwrite get\_nav\_markup or at least append additional information immediately after it in my child theme? Given the way the parent theme function written I don't think I can. But I really need to be able to add some additional DIVs and PHP right after the /nav
Ok so here is what I have decided given the situation. 1. I have copied the header.php file into my child theme. 2. I have changed the line in the header file from get\_header\_markup(); to get\_header\_markup\_updated(); 3. I have then created a new function in my child themes function.php file called get\_header\_markup\_updated. 4. I started the function off my copying the existing one from the parent theme, but then added the code I needed... where I needed it. The result now looks like: ``` function get_header_markup_updated() { global $post; echo get_nav_markup( $post ); ?> <div class="breadcrumbnav"> <!-- Inserted all my other code here --> </div> <?php $videos = get_header_videos( $post ); $images = get_header_images( $post ); if ( $videos || $images ) { echo get_header_media_markup( $post, $videos, $images ); } else { echo get_header_default_markup( $post ); } } ?> ``` This seems to be working just fine. Hopefully this will also be the least obtrusive going forward.
308,730
<p>I'm trying to build functionality (using the Advanced Custom Fields plugin) to list information in a page template for all custom post types ('Product') that have specified taxonomies.</p> <p>This is my current stable code, which queries the Products, but only based on the taxonomy terms I hard-code:</p> <pre><code>$posts = get_posts(array( 'posts_per_page' =&gt; 10, 'post_type' =&gt; 'company_product', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'taxonomy', 'field' =&gt; 'slug', 'terms' =&gt; 'product1' ), )); </code></pre> <p>I've used ACF to set up functionality in the backend to select multiple taxonomies (via a repeater field) that I want to apply to the query, so that the admin can modify which Products are returned based on which taxonomies they have.</p> <p>I tried this:</p> <pre><code>$posts = get_posts(array( 'posts_per_page' =&gt; 10, 'post_type' =&gt; 'company_product', 'tax_query' =&gt; array( if( have_rows('category_taxonomies') ): while ( have_rows('category_taxonomies') ) : the_row(); array( 'taxonomy' =&gt; 'taxonomy', 'field' =&gt; 'slug', 'terms' =&gt; the_sub_field('category_taxonomy') ), endwhile; endif; )); </code></pre> <p>But received this error: <code>Parse error: syntax error, unexpected 'if' (T_IF), expecting ')' in</code>...</p> <p>As you can see, I'm trying to add an array to the tax_query for each taxonomy that's selected in the backend, but trying to put the if/while functions inside the array itself causes an error.</p> <p>I assumed the above method wouldn't work, but PHP isn't my expertise so I'm not sure where to go from here. Any help is appreciated.</p>
[ { "answer_id": 308738, "author": "Paul Elrich", "author_id": 146435, "author_profile": "https://wordpress.stackexchange.com/users/146435", "pm_score": -1, "selected": false, "text": "<p>If conditions don't run inside of arrays, so you will need to write separate arrays for each condition:</p>\n\n<pre><code>$posts = get_posts(if( have_rows('category_taxonomies') ){array(\n'posts_per_page' =&gt; 10,\n'post_type' =&gt; 'company_product',\n'tax_query' =&gt; array('taxonomy' =&gt; 'taxonomy',\n 'field' =&gt; 'slug',\n 'terms' =&gt; the_sub_field('category_taxonomy')),\n }else{array(\n 'posts_per_page' =&gt; 10,\n 'post_type' =&gt; 'company_product'\n )}\n));\n</code></pre>\n" }, { "answer_id": 308743, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 3, "selected": true, "text": "<p>OK, I have no idea how and why your code should work... It has nothing in common with correct PHP syntax... But it's pretty good pseudo-code, so I think I can guess, what you wanted to achieve...</p>\n\n<pre><code>$tax_query = array();\nif ( have_rows('category_taxonomies') ) {\n while ( have_rows('category_taxonomies') ) {\n the_row();\n $tax_query[] = array(\n 'taxonomy' =&gt; 'taxonomy', // &lt;- you should put real taxonomy name in here\n 'field' =&gt; 'slug',\n 'terms' =&gt; get_sub_field('category_taxonomy')\n );\n }\n}\n\n$posts = get_posts( array(\n 'posts_per_page' =&gt; 10,\n 'post_type' =&gt; 'company_product',\n 'tax_query' =&gt; $tax_query\n));\n</code></pre>\n" } ]
2018/07/16
[ "https://wordpress.stackexchange.com/questions/308730", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115332/" ]
I'm trying to build functionality (using the Advanced Custom Fields plugin) to list information in a page template for all custom post types ('Product') that have specified taxonomies. This is my current stable code, which queries the Products, but only based on the taxonomy terms I hard-code: ``` $posts = get_posts(array( 'posts_per_page' => 10, 'post_type' => 'company_product', 'tax_query' => array( array( 'taxonomy' => 'taxonomy', 'field' => 'slug', 'terms' => 'product1' ), )); ``` I've used ACF to set up functionality in the backend to select multiple taxonomies (via a repeater field) that I want to apply to the query, so that the admin can modify which Products are returned based on which taxonomies they have. I tried this: ``` $posts = get_posts(array( 'posts_per_page' => 10, 'post_type' => 'company_product', 'tax_query' => array( if( have_rows('category_taxonomies') ): while ( have_rows('category_taxonomies') ) : the_row(); array( 'taxonomy' => 'taxonomy', 'field' => 'slug', 'terms' => the_sub_field('category_taxonomy') ), endwhile; endif; )); ``` But received this error: `Parse error: syntax error, unexpected 'if' (T_IF), expecting ')' in`... As you can see, I'm trying to add an array to the tax\_query for each taxonomy that's selected in the backend, but trying to put the if/while functions inside the array itself causes an error. I assumed the above method wouldn't work, but PHP isn't my expertise so I'm not sure where to go from here. Any help is appreciated.
OK, I have no idea how and why your code should work... It has nothing in common with correct PHP syntax... But it's pretty good pseudo-code, so I think I can guess, what you wanted to achieve... ``` $tax_query = array(); if ( have_rows('category_taxonomies') ) { while ( have_rows('category_taxonomies') ) { the_row(); $tax_query[] = array( 'taxonomy' => 'taxonomy', // <- you should put real taxonomy name in here 'field' => 'slug', 'terms' => get_sub_field('category_taxonomy') ); } } $posts = get_posts( array( 'posts_per_page' => 10, 'post_type' => 'company_product', 'tax_query' => $tax_query )); ```
308,759
<p>I wanted to combine multiple categories in one Menu item</p> <p>I checked this dicussion, someone said:</p> <blockquote> <p>You'd have to make a custom link for that.</p> <p>Make your URL <a href="http://www.example.com/?cat=(id-white),(id-rabbit)" rel="nofollow noreferrer">http://www.example.com/?cat=(id-white),(id-rabbit)</a></p> </blockquote> <p>Below is my link but can't show the correct categories. ID is correct.</p> <p><a href="http://example.com/?cat=(id-32),(id-33)" rel="nofollow noreferrer">http://example.com/?cat=(id-32),(id-33)</a></p>
[ { "answer_id": 308770, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 2, "selected": false, "text": "<p>You misunderstood the quote, the URL needs to be</p>\n\n<pre><code>http://example.com/?cat=32,33\n</code></pre>\n\n<p>I just tested it and it seems to work. However, the title was only one of the categories' name, there might be other problems with this solution.</p>\n" }, { "answer_id": 308771, "author": "Anabik Chakraborty", "author_id": 147061, "author_profile": "https://wordpress.stackexchange.com/users/147061", "pm_score": 0, "selected": false, "text": "<p>Use the URL like this, it will show the content of both categories:</p>\n\n<pre><code>http://example.com/?cat=id-32+id-33\n</code></pre>\n" }, { "answer_id": 365628, "author": "Annika Nordin", "author_id": 187296, "author_profile": "https://wordpress.stackexchange.com/users/187296", "pm_score": 0, "selected": false, "text": "<p>This will show the content of both categories:</p>\n\n<pre><code>/product-category/spring-summer+pumps/\n</code></pre>\n" } ]
2018/07/17
[ "https://wordpress.stackexchange.com/questions/308759", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135792/" ]
I wanted to combine multiple categories in one Menu item I checked this dicussion, someone said: > > You'd have to make a custom link for that. > > > Make your URL <http://www.example.com/?cat=(id-white),(id-rabbit)> > > > Below is my link but can't show the correct categories. ID is correct. <http://example.com/?cat=(id-32),(id-33)>
You misunderstood the quote, the URL needs to be ``` http://example.com/?cat=32,33 ``` I just tested it and it seems to work. However, the title was only one of the categories' name, there might be other problems with this solution.
308,837
<p>I want the custom fields for PDF file upload on admin side for the post where i can select any PDF file for the any posts using custom code or any type of plugins.</p> <p>can you recommend me please by which my problem can be solved ?</p> <pre><code>&lt;?php $array=array('posts_per_page'=&gt;2, 'post_type'=&gt;'post'); $mypost=get_posts($array); //print_r($mypost); foreach($mypost as $values) { //print_r($mypost); echo "&lt;p&gt;" .$values-&gt;post_title."&lt;/p&gt;"; echo "&lt;p&gt;" .$values-&gt;post_content."&lt;/p&gt;"; echo "&lt;p&gt;" .get_the_post_thumbnail($values-&gt;ID, 'thumbnail', array( 'class' =&gt; 'thumbnail text-center' ))."&lt;/p&gt;"; echo '&lt;p&gt;' . date_i18n('d F Y', strtotime($values-&gt;post_date)) .'&lt;/p&gt; '; //$ca = get_the_category($values-&gt;ID); //print_r($ca); //echo $ca[0]-&gt;name; $pdf_file = get_field('pdf'); print_r($pdf_file); if( $file ) { echo '&lt;a href="'.$pdf_file.'"&gt;Download File&lt;/a&gt;'; } } ?&gt; </code></pre>
[ { "answer_id": 308839, "author": "dhirenpatel22", "author_id": 124380, "author_profile": "https://wordpress.stackexchange.com/users/124380", "pm_score": 3, "selected": true, "text": "<p>Follow below steps to create custom PDF upload field in custom post type:</p>\n\n<ol>\n<li>Install <a href=\"https://wordpress.org/plugins/advanced-custom-fields/\" rel=\"nofollow noreferrer\">Advance Custom Field</a> from wordpress.org</li>\n<li>Go to <strong>Custom Fields</strong> and click on <strong>Add New</strong> button.</li>\n<li>Follow instructions in below screenshot to add the custom field to upload PDF file.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/t63t9.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/t63t9.jpg\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"4\">\n<li><p>Use below code to display content on post type template.</p>\n\n<pre><code>$pdf_file = get_field('pdf_upload');\n\nif( $file ) {\n echo '&lt;a href=\"'.$pdf_file.'\"&gt;Download File&lt;/a&gt;';\n}\n</code></pre></li>\n</ol>\n\n<p>Reference Documentation: <a href=\"https://www.advancedcustomfields.com/resources/file/\" rel=\"nofollow noreferrer\">https://www.advancedcustomfields.com/resources/file/</a></p>\n\n<p>Hope this helps..!!</p>\n" }, { "answer_id": 308926, "author": "dhirenpatel22", "author_id": 124380, "author_profile": "https://wordpress.stackexchange.com/users/124380", "pm_score": 0, "selected": false, "text": "<p>Please find below code which I have corrected....there was just a minor issue with your code in If condition..</p>\n\n<pre><code>&lt;?php\n\n$array=array('posts_per_page'=&gt;2, 'post_type'=&gt;'post');\n$mypost=get_posts($array);\n//print_r($mypost);\nforeach($mypost as $values)\n{\n //print_r($mypost);\n\n\n\n\n echo \"&lt;p&gt;\" .$values-&gt;post_title.\"&lt;/p&gt;\";\n echo \"&lt;p&gt;\" .$values-&gt;post_content.\"&lt;/p&gt;\";\n echo \"&lt;p&gt;\" .get_the_post_thumbnail($values-&gt;ID, 'thumbnail', array( 'class' =&gt; 'thumbnail text-center' )).\"&lt;/p&gt;\";\n echo '&lt;p&gt;' . date_i18n('d F Y', strtotime($values-&gt;post_date)) .'&lt;/p&gt; ';\n //$ca = get_the_category($values-&gt;ID);\n //print_r($ca);\n //echo $ca[0]-&gt;name;\n $pdf_file = get_field('pdf');\n print_r($pdf_file);\n\n if( $pdf_file ) {\n echo '&lt;a href=\"'.$pdf_file.'\"&gt;Download File&lt;/a&gt;';\n }\n}\n\n ?&gt;\n</code></pre>\n" } ]
2018/07/17
[ "https://wordpress.stackexchange.com/questions/308837", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/144155/" ]
I want the custom fields for PDF file upload on admin side for the post where i can select any PDF file for the any posts using custom code or any type of plugins. can you recommend me please by which my problem can be solved ? ``` <?php $array=array('posts_per_page'=>2, 'post_type'=>'post'); $mypost=get_posts($array); //print_r($mypost); foreach($mypost as $values) { //print_r($mypost); echo "<p>" .$values->post_title."</p>"; echo "<p>" .$values->post_content."</p>"; echo "<p>" .get_the_post_thumbnail($values->ID, 'thumbnail', array( 'class' => 'thumbnail text-center' ))."</p>"; echo '<p>' . date_i18n('d F Y', strtotime($values->post_date)) .'</p> '; //$ca = get_the_category($values->ID); //print_r($ca); //echo $ca[0]->name; $pdf_file = get_field('pdf'); print_r($pdf_file); if( $file ) { echo '<a href="'.$pdf_file.'">Download File</a>'; } } ?> ```
Follow below steps to create custom PDF upload field in custom post type: 1. Install [Advance Custom Field](https://wordpress.org/plugins/advanced-custom-fields/) from wordpress.org 2. Go to **Custom Fields** and click on **Add New** button. 3. Follow instructions in below screenshot to add the custom field to upload PDF file. [![enter image description here](https://i.stack.imgur.com/t63t9.jpg)](https://i.stack.imgur.com/t63t9.jpg) 4. Use below code to display content on post type template. ``` $pdf_file = get_field('pdf_upload'); if( $file ) { echo '<a href="'.$pdf_file.'">Download File</a>'; } ``` Reference Documentation: <https://www.advancedcustomfields.com/resources/file/> Hope this helps..!!
308,854
<p>To start I've been searching through several questions and documentation pieces but it seems with WordPress' <code>v2</code> many of the old questions are no longer valid. What I am trying to do is get all posts or a singular post from a category in Postman instead of the common returned 10 posts without having to modify the API in functions.php.</p> <h2>tldr</h2> <p>I started with referencing the <a href="https://developer.wordpress.org/rest-api/" rel="noreferrer">REST API Handbook</a> and reviewing the <a href="https://developer.wordpress.org/rest-api/reference/posts/#schema" rel="noreferrer">schema</a> I saw <code>categories</code> and I can return the 10 latest categories using:</p> <pre><code>http://foobar.com/wp-json/wp/v2/posts/categories_name=hello </code></pre> <p>referencing the <a href="https://developer.wordpress.org/rest-api/reference/posts/#arguments" rel="noreferrer">arguments</a> I see <code>per_page</code> so I tried:</p> <pre><code>http://foobar.com/wp-json/wp/v2/posts/categories_name=hello?per_page=‌​1 </code></pre> <p>and it returns 10 posts from the category <code>hello</code> so I modified and tried:</p> <pre><code>http://foobar.com/wp-json/wp/v2/posts/categories_name=hello&amp;per_page=‌​1 </code></pre> <p>and I get an error returned:</p> <blockquote> <p>{ "code": "rest_invalid_param", "message": "Invalid parameter(s): per_page", "data": { "status": 400, "params": { "per_page": "per_page is not of type integer." } } }</p> </blockquote> <p>Searching through Google I <a href="https://stackoverflow.com/questions/20158417/how-to-retrieve-a-list-of-categories-tag-in-wordpress-rest-api">see How to retrieve a list of categories/ tag in Wordpress REST API</a> but the answers are based on <code>v1</code>.</p> <p>Trying <a href="https://stackoverflow.com/questions/29171854/wordpress-api-json-return-limit">Wordpress API JSON return limit</a> I use:</p> <pre><code>http://foobar.com/wp-json/wp/v2/posts/?per_page=‌​1 </code></pre> <p>and I get a singular post so I modified my attempt to:</p> <pre><code>http://foobar.com/wp-json/wp/v2/posts/?per_page=‌​1$categories_name=hello </code></pre> <p>It ignores the category type and returns the latest post. Reading <a href="https://wordpress.stackexchange.com/questions/274890/get-more-than-10-posts-in-a-specific-category-with-the-wordpress-api">Get more than 10 posts in a specific category with the WordPress API</a> I pulled the ID of a category (4) after using:</p> <pre><code>http://foobar.com/wp-json/wp/v2/categories </code></pre> <p>then coded:</p> <pre><code>http://foobar.com/wp-json/wp/v2/posts/?categories=4&amp;per_page=‌​1 </code></pre> <p>and I get:</p> <blockquote> <p>{ "code": "rest_invalid_param", "message": "Invalid parameter(s): per_page", "data": { "status": 400, "params": { "per_page": "per_page is not of type integer." } } }</p> </blockquote> <p>I thought I might be able to use <code>-1</code> similar to the development of a theme but I get an error.</p> <p>Other references I read are:</p> <ul> <li><a href="https://wordpress.stackexchange.com/questions/222547/wp-rest-api-retrieve-content-from-page">WP REST API - Retrieve content from page</a></li> <li><a href="http://v2.wp-api.org/reference/categories/" rel="noreferrer">WP REST API Category</a></li> <li><p>Found this <a href="https://github.com/WP-API/WP-API/issues/2949" rel="noreferrer">Since filter has been removed, how to get posts by category slug with same schema as v2/posts?</a> after reading <a href="https://stackoverflow.com/questions/38944843/search-post-by-categories-wordpress-wp-api">Search post by categories Wordpress WP-API</a></p></li> <li><p><a href="https://wordpress.stackexchange.com/questions/40839/how-to-get-all-posts-related-to-particular-category-name">How to get all posts related to particular category name?</a></p></li> </ul> <p>After reviewing the documentation on <a href="https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters" rel="noreferrer">Pagination</a> it seems to only work with the <code>post</code> and not any <code>category</code>. I can only get more than 10 posts if I use <code>/wp-json/wp/v2/posts?per_page=20</code>, too.</p> <h2>Question</h2> <p>When calling a site's WP API how can I control the <code>per_page</code> return of a category wether it be 1 post or all posts?</p>
[ { "answer_id": 308869, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>Pretty much all the URLs you are using are invalid in some way:</p>\n\n<pre><code>http://foobar.com/wp-json/wp/v2/posts/categories_name=hello\n</code></pre>\n\n<p><code>categories_name</code> is not a <a href=\"https://developer.wordpress.org/rest-api/reference/posts/#arguments\" rel=\"nofollow noreferrer\">valid argument</a> for listing posts, and even if it was you are missing the <code>?</code> part of the query string.</p>\n\n<pre><code>http://foobar.com/wp-json/wp/v2/posts/categories_name=hello?per_page=‌​1\n</code></pre>\n\n<p>This one is also missing the <code>?</code>. Query parameters on a URL, which the API uses for its arguments, need to start with <code>?</code>, with <code>&amp;</code> for additional parameters. A correctly formatted query string looks like this:</p>\n\n<pre><code>http://domain.com/path/?argument=value&amp;argument2=value2\n</code></pre>\n\n<p>So this one:</p>\n\n<pre><code>http://foobar.com/wp-json/wp/v2/posts/categories_name=hello&amp;per_page=‌​1\n</code></pre>\n\n<p>Is also missing the <code>?</code> but you've used <code>&amp;</code> correctly this time (though are still using the invalid <code>categories_name</code> argument).</p>\n\n<p>This one:</p>\n\n<pre><code>http://foobar.com/wp-json/wp/v2/posts/?per_page=‌​1$categories_name=hello\n</code></pre>\n\n<p>Is using a <code>$</code> for some reason. That's not a valid way to separate parameters in a query string (and still using the invalid <code>categories_name</code> argument).</p>\n\n<p>This one <em>is</em> correct:</p>\n\n<pre><code>http://foobar.com/wp-json/wp/v2/posts/?categories=4&amp;per_page=‌​1\n</code></pre>\n\n<p>But based on your comment:</p>\n\n<blockquote>\n <p>I thought I might be able to use -1 similar to the development of a\n theme but I get an error.</p>\n</blockquote>\n\n<p>It sounds like you <em>actually</em> tried:</p>\n\n<pre><code>http://foobar.com/wp-json/wp/v2/posts/?categories=4&amp;per_page=‌​-1\n</code></pre>\n\n<p>Which <em>won't</em> work, because <code>-1</code> is an invalid value. You can only retrieve between <code>1</code> and <code>100</code> results with the API.</p>\n" }, { "answer_id": 308900, "author": "user9447", "author_id": 25271, "author_profile": "https://wordpress.stackexchange.com/users/25271", "pm_score": 2, "selected": true, "text": "<p>After a few hours trying different permutations of how to get a return on categories I found my answer. To establish the listing of categories associated with <code>post</code> use:</p>\n\n<pre><code>/wp-json/wp/v2/categories/\n</code></pre>\n\n<p>I needed a particular category and the <code>id</code> of that category was <code>4</code> and the slug was called <code>foobar</code>.</p>\n\n<p>To get 1 post associated with the category <code>foobar</code> I had to use:</p>\n\n<pre><code>/wp-json/wp/v2/posts?categories=4&amp;per_page=1\n</code></pre>\n\n<p>To get 100 posts associated with the category <code>foobar</code> I used:</p>\n\n<pre><code>/wp-json/wp/v2/posts?categories=4&amp;per_page=100\n</code></pre>\n\n<p>and as I found out and it was also mentioned in the <a href=\"https://wordpress.stackexchange.com/a/308869/25271\">answer</a> my logic of using <code>-1</code> was incorrect, you can only use 1 to 100. As it was discussed in the comment on what to do if there are more than 100 posts, well you can call the page using <code>offset</code> and I found that under the documentation <a href=\"https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters\" rel=\"nofollow noreferrer\">Pagination</a>:</p>\n\n<pre><code>/wp-json/wp/v2/posts?categories=4&amp;offset=10&amp;per_page=1\n</code></pre>\n\n<p>so to get more than 100 you'd to build a loop in whatever language you wanted and push it to a file. To assist with the looping under <code>/wp-json/wp/v2/categories/</code> and when you reference the category you can reference the total count under <code>count</code> which is below the <code>id</code>.</p>\n" }, { "answer_id": 361103, "author": "TheTC", "author_id": 184568, "author_profile": "https://wordpress.stackexchange.com/users/184568", "pm_score": 1, "selected": false, "text": "<p>When doing \"per_page\" on the products/categories endpoint, the MAX you can use is 100. Anything more then that will cause the error Error: Invalid parameter(s): per_page [rest_invalid_param]</p>\n" } ]
2018/07/17
[ "https://wordpress.stackexchange.com/questions/308854", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25271/" ]
To start I've been searching through several questions and documentation pieces but it seems with WordPress' `v2` many of the old questions are no longer valid. What I am trying to do is get all posts or a singular post from a category in Postman instead of the common returned 10 posts without having to modify the API in functions.php. tldr ---- I started with referencing the [REST API Handbook](https://developer.wordpress.org/rest-api/) and reviewing the [schema](https://developer.wordpress.org/rest-api/reference/posts/#schema) I saw `categories` and I can return the 10 latest categories using: ``` http://foobar.com/wp-json/wp/v2/posts/categories_name=hello ``` referencing the [arguments](https://developer.wordpress.org/rest-api/reference/posts/#arguments) I see `per_page` so I tried: ``` http://foobar.com/wp-json/wp/v2/posts/categories_name=hello?per_page=‌​1 ``` and it returns 10 posts from the category `hello` so I modified and tried: ``` http://foobar.com/wp-json/wp/v2/posts/categories_name=hello&per_page=‌​1 ``` and I get an error returned: > > { > "code": "rest\_invalid\_param", > "message": "Invalid parameter(s): per\_page", > "data": { > "status": 400, > "params": { > "per\_page": "per\_page is not of type integer." > } > } } > > > Searching through Google I [see How to retrieve a list of categories/ tag in Wordpress REST API](https://stackoverflow.com/questions/20158417/how-to-retrieve-a-list-of-categories-tag-in-wordpress-rest-api) but the answers are based on `v1`. Trying [Wordpress API JSON return limit](https://stackoverflow.com/questions/29171854/wordpress-api-json-return-limit) I use: ``` http://foobar.com/wp-json/wp/v2/posts/?per_page=‌​1 ``` and I get a singular post so I modified my attempt to: ``` http://foobar.com/wp-json/wp/v2/posts/?per_page=‌​1$categories_name=hello ``` It ignores the category type and returns the latest post. Reading [Get more than 10 posts in a specific category with the WordPress API](https://wordpress.stackexchange.com/questions/274890/get-more-than-10-posts-in-a-specific-category-with-the-wordpress-api) I pulled the ID of a category (4) after using: ``` http://foobar.com/wp-json/wp/v2/categories ``` then coded: ``` http://foobar.com/wp-json/wp/v2/posts/?categories=4&per_page=‌​1 ``` and I get: > > { > "code": "rest\_invalid\_param", > "message": "Invalid parameter(s): per\_page", > "data": { > "status": 400, > "params": { > "per\_page": "per\_page is not of type integer." > } > } } > > > I thought I might be able to use `-1` similar to the development of a theme but I get an error. Other references I read are: * [WP REST API - Retrieve content from page](https://wordpress.stackexchange.com/questions/222547/wp-rest-api-retrieve-content-from-page) * [WP REST API Category](http://v2.wp-api.org/reference/categories/) * Found this [Since filter has been removed, how to get posts by category slug with same schema as v2/posts?](https://github.com/WP-API/WP-API/issues/2949) after reading [Search post by categories Wordpress WP-API](https://stackoverflow.com/questions/38944843/search-post-by-categories-wordpress-wp-api) * [How to get all posts related to particular category name?](https://wordpress.stackexchange.com/questions/40839/how-to-get-all-posts-related-to-particular-category-name) After reviewing the documentation on [Pagination](https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters) it seems to only work with the `post` and not any `category`. I can only get more than 10 posts if I use `/wp-json/wp/v2/posts?per_page=20`, too. Question -------- When calling a site's WP API how can I control the `per_page` return of a category wether it be 1 post or all posts?
After a few hours trying different permutations of how to get a return on categories I found my answer. To establish the listing of categories associated with `post` use: ``` /wp-json/wp/v2/categories/ ``` I needed a particular category and the `id` of that category was `4` and the slug was called `foobar`. To get 1 post associated with the category `foobar` I had to use: ``` /wp-json/wp/v2/posts?categories=4&per_page=1 ``` To get 100 posts associated with the category `foobar` I used: ``` /wp-json/wp/v2/posts?categories=4&per_page=100 ``` and as I found out and it was also mentioned in the [answer](https://wordpress.stackexchange.com/a/308869/25271) my logic of using `-1` was incorrect, you can only use 1 to 100. As it was discussed in the comment on what to do if there are more than 100 posts, well you can call the page using `offset` and I found that under the documentation [Pagination](https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/#pagination-parameters): ``` /wp-json/wp/v2/posts?categories=4&offset=10&per_page=1 ``` so to get more than 100 you'd to build a loop in whatever language you wanted and push it to a file. To assist with the looping under `/wp-json/wp/v2/categories/` and when you reference the category you can reference the total count under `count` which is below the `id`.
308,876
<p>My wordpress site dj.pyromusic.cn is based in China, on a chinese server. Somewhere in the theme, or the site, it is making a request to youtube which is obviously blocked here, causing the load time to be over 300 seconds before it times out.</p> <p>Here is a screenshot of the inspection:</p> <p><a href="https://i.stack.imgur.com/gbwB0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gbwB0.png" alt="enter image description here"></a></p> <p>Any ideas how I can block this request? </p>
[ { "answer_id": 308877, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 1, "selected": false, "text": "<p>The Youtube is called by a script named \"jquery.st.youtube.js\" which is located in your themes folder. You seem to use a premium theme named \"Wunder\" which effectively means you can do one of two things:</p>\n\n<p>1) You can edit the themes files directly, search for the enqueuing of the script jquery.st.youtube.js (most likely within the functions.php of the theme, but maybe somewhere else) and remove the line/turn the line into a comment. CAUTION: Do not do this if you plan to install updates to this theme. Whenever you update your theme, the changes you made are gone, so i would advise against this way. However, if the support cycle is over, you don't plan to update the theme and need a quick dirty fix RITE NAO, it is a possibility.</p>\n\n<p>2) You create a child theme (<a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Child_Themes</a>) of your premium theme. After that, find the handle which is used for enqueueing the \"jquery.st.youtube.js\"-Script. In the functions.php of your child-theme, you hook into the wp_enqueue_scripts action with a big priority like 1000 and use wp_dequeue_script to remove it from the action.</p>\n\n<p>Example:\nThe function in your premium theme where the scripts are enqueued MAY look like this:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'wunder_enqueue_scripts' );\n\nfunction wunder_enqueue_scripts(){\n wp_enqueue_script('wunder-youtube',\"jquery.st.youtube.js\",array('jquery'),\"\",true);\n..... (more scripts)\n}\n</code></pre>\n\n<p>In your child-themes functions.php, you can now insert a function to dequeue the script like this:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'remove_that_darn_youtube_scripts',1000 );\n\nfunction remove_that_darn_youtube_scripts(){\n wp_dequeue_script('wunder-youtube');\n\n}\n</code></pre>\n\n<p>If you don't understand what any of these functions do, then you can read up on <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">wp_enqueue_script</a> and <a href=\"https://codex.wordpress.org/Function_Reference/wp_dequeue_script\" rel=\"nofollow noreferrer\">wp_dequeue_script</a> in the wordpress codex (or you get someone to code for you ;) )</p>\n\n<p>While this is way more effort, i would suggest that you take route 2, as it is the \"correct\" way to do these things. Of Course, after you have built that child theme, you have to activate it for the changes to work.</p>\n\n<p>Last but not least: DON'T DO THIS ON LIVE! Get yourself a backup of the site, and do the changes on local/a subsite/some other webspace and TEST IT before you put it on the live site!</p>\n" }, { "answer_id": 308903, "author": "Spencer Tarring", "author_id": 147123, "author_profile": "https://wordpress.stackexchange.com/users/147123", "pm_score": 0, "selected": false, "text": "<p>OK, great I finally found the reference. It was in the file st.setup.php. I added a # to comment out the line, and it solved all the problems! Thank you and I will now try to create the child version.</p>\n" } ]
2018/07/18
[ "https://wordpress.stackexchange.com/questions/308876", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147123/" ]
My wordpress site dj.pyromusic.cn is based in China, on a chinese server. Somewhere in the theme, or the site, it is making a request to youtube which is obviously blocked here, causing the load time to be over 300 seconds before it times out. Here is a screenshot of the inspection: [![enter image description here](https://i.stack.imgur.com/gbwB0.png)](https://i.stack.imgur.com/gbwB0.png) Any ideas how I can block this request?
The Youtube is called by a script named "jquery.st.youtube.js" which is located in your themes folder. You seem to use a premium theme named "Wunder" which effectively means you can do one of two things: 1) You can edit the themes files directly, search for the enqueuing of the script jquery.st.youtube.js (most likely within the functions.php of the theme, but maybe somewhere else) and remove the line/turn the line into a comment. CAUTION: Do not do this if you plan to install updates to this theme. Whenever you update your theme, the changes you made are gone, so i would advise against this way. However, if the support cycle is over, you don't plan to update the theme and need a quick dirty fix RITE NAO, it is a possibility. 2) You create a child theme (<https://codex.wordpress.org/Child_Themes>) of your premium theme. After that, find the handle which is used for enqueueing the "jquery.st.youtube.js"-Script. In the functions.php of your child-theme, you hook into the wp\_enqueue\_scripts action with a big priority like 1000 and use wp\_dequeue\_script to remove it from the action. Example: The function in your premium theme where the scripts are enqueued MAY look like this: ``` add_action( 'wp_enqueue_scripts', 'wunder_enqueue_scripts' ); function wunder_enqueue_scripts(){ wp_enqueue_script('wunder-youtube',"jquery.st.youtube.js",array('jquery'),"",true); ..... (more scripts) } ``` In your child-themes functions.php, you can now insert a function to dequeue the script like this: ``` add_action( 'wp_enqueue_scripts', 'remove_that_darn_youtube_scripts',1000 ); function remove_that_darn_youtube_scripts(){ wp_dequeue_script('wunder-youtube'); } ``` If you don't understand what any of these functions do, then you can read up on [wp\_enqueue\_script](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) and [wp\_dequeue\_script](https://codex.wordpress.org/Function_Reference/wp_dequeue_script) in the wordpress codex (or you get someone to code for you ;) ) While this is way more effort, i would suggest that you take route 2, as it is the "correct" way to do these things. Of Course, after you have built that child theme, you have to activate it for the changes to work. Last but not least: DON'T DO THIS ON LIVE! Get yourself a backup of the site, and do the changes on local/a subsite/some other webspace and TEST IT before you put it on the live site!
308,909
<p>I have access to a single Linux/Apache server where I'm trying to deploy WordPress. For purposes of this error, I've tested it with the default twentyseventeen theme and all plugins disabled.</p> <p>When I go to any wp-admin page, logged in as an administrator, most of the icons from the left navigation are missing, checked checkboxes have no checks (for example), and the browser console fills with JavaScript errors.</p> <p>For example, on the dashboard page, none of the icons are visible and the error console reads like this:</p> <pre><code>Uncaught TypeError: a.widget is not a function at load-scripts.php?c=0&amp;load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&amp;load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&amp;load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&amp;ver=4.9.7:300 at load-scripts.php?c=0&amp;load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&amp;load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&amp;load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&amp;ver=4.9.7:300 at load-scripts.php?c=0&amp;load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&amp;load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&amp;load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&amp;ver=4.9.7:300 </code></pre> <p>When I look in the network tab in the browser (I've looked in Chrome, Safari, and Firefox, and the host has looked as well), all requests return a 200 status. It does not seem like any requests are being blocked, at least.</p> <p>If I add <code>SCRIPT_DEBUG=true</code> to the wp-config.php file, all these errors stop and the interface displays as it normally does.</p> <p>I've been unable to reproduce this issue locally, and my host appears to be unable to tell me what is wrong (although they do see it). What can I tell them to look into, and/or what can I look into?</p> <p>Update: to be more clear, my suspicion is that this could be a permissions issue on the server. Perhaps the server is unable to concatenate the files as WordPress expects. But the host has been unable to find anything to this effect, and I'm not knowledgeable enough about Linux/file permissions to know what to tell them to look for, or if that is even what is happening.</p>
[ { "answer_id": 308916, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 1, "selected": false, "text": "<p>Do you load own javascripts into the admin? If i recall correctly, if SCRIPT_DEBUG is set to true, the javascripts are not concenated, but loaded seperately. So if a custom javascript doesn't play well being concenated, this can lead to the whole concenated javascript being corrupt and not being run correctly. </p>\n\n<p>Try removing the added javascripts one by one and check if that changes anything.</p>\n" }, { "answer_id": 308920, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 1, "selected": false, "text": "<p>The only thing logically different in JavaScript when <code>SCRIPT_DEBUG</code> is set to <code>true</code> vs. <code>false</code> is: when <code>SCRIPT_DEBUG</code> is set to <code>true</code>, main JavaScript source files are being loaded and normally (when <code>SCRIPT_DEBUG</code> is set to <code>false</code>), the <strong>minified versions</strong> (e.g. <code>file.min.js</code>) are loaded with <strong>concatenation</strong> &amp; <strong>compression</strong>.</p>\n\n<p>So apparently, the minified versions of the JS files are causing problems. May be they are even corrupted.</p>\n\n<p>Replace WordPress core with the version from wordpress.org, may be this will fix the issues.</p>\n\n<blockquote>\n <p><strong>Note:</strong> Don't forget to clear browser cache when you're done doing this, wrong versions may be loaded from the cache otherwise.</p>\n</blockquote>\n" }, { "answer_id": 323062, "author": "Adon Irani", "author_id": 157062, "author_profile": "https://wordpress.stackexchange.com/users/157062", "pm_score": 0, "selected": false, "text": "<p>I'm experiencing the same issue on the latest Wordpress 5.0.1 but only on /wp-admin/*. Main site renders just fine.</p>\n\n<p>I found defining 'CONCATENATE_SCRIPTS' as false will also solve the issue, which means the minified scripts are actually OK. </p>\n\n<p>Not seeing any permissions issues either. Trying to investigate what exactly happens when scripts are concatenated -- </p>\n" } ]
2018/07/18
[ "https://wordpress.stackexchange.com/questions/308909", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41356/" ]
I have access to a single Linux/Apache server where I'm trying to deploy WordPress. For purposes of this error, I've tested it with the default twentyseventeen theme and all plugins disabled. When I go to any wp-admin page, logged in as an administrator, most of the icons from the left navigation are missing, checked checkboxes have no checks (for example), and the browser console fills with JavaScript errors. For example, on the dashboard page, none of the icons are visible and the error console reads like this: ``` Uncaught TypeError: a.widget is not a function at load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&ver=4.9.7:300 at load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&ver=4.9.7:300 at load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,wp-ajax-response,jquery-color,wp-lists,quicktags,jquery-query,admin-comments,jquery-ui-core,jquery-&load[]=ui-widget,jquery-ui-mouse,jquery-ui-sortable,postbox,underscore,wp-util,wp-a11y,dashboard,thickbox,plugin-install,updates,shortc&load[]=ode,media-upload,svg-painter,heartbeat,wp-auth-check,wplink,jquery-ui-position,jquery-ui-menu,jquery-ui-autocomplete&ver=4.9.7:300 ``` When I look in the network tab in the browser (I've looked in Chrome, Safari, and Firefox, and the host has looked as well), all requests return a 200 status. It does not seem like any requests are being blocked, at least. If I add `SCRIPT_DEBUG=true` to the wp-config.php file, all these errors stop and the interface displays as it normally does. I've been unable to reproduce this issue locally, and my host appears to be unable to tell me what is wrong (although they do see it). What can I tell them to look into, and/or what can I look into? Update: to be more clear, my suspicion is that this could be a permissions issue on the server. Perhaps the server is unable to concatenate the files as WordPress expects. But the host has been unable to find anything to this effect, and I'm not knowledgeable enough about Linux/file permissions to know what to tell them to look for, or if that is even what is happening.
Do you load own javascripts into the admin? If i recall correctly, if SCRIPT\_DEBUG is set to true, the javascripts are not concenated, but loaded seperately. So if a custom javascript doesn't play well being concenated, this can lead to the whole concenated javascript being corrupt and not being run correctly. Try removing the added javascripts one by one and check if that changes anything.
308,933
<p>I try this:</p> <pre><code>&lt;?php function get_ct($id){ $ct = apply_filters('the_content', get_post_field('post_content', $id)); return $ct; } $arr = array('post_content' =&gt; get_ct(126)); echo json_encode($arr); ?&gt; </code></pre> <p>but the post_content 's values ist null any suggestion? thanks</p>
[ { "answer_id": 308916, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 1, "selected": false, "text": "<p>Do you load own javascripts into the admin? If i recall correctly, if SCRIPT_DEBUG is set to true, the javascripts are not concenated, but loaded seperately. So if a custom javascript doesn't play well being concenated, this can lead to the whole concenated javascript being corrupt and not being run correctly. </p>\n\n<p>Try removing the added javascripts one by one and check if that changes anything.</p>\n" }, { "answer_id": 308920, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 1, "selected": false, "text": "<p>The only thing logically different in JavaScript when <code>SCRIPT_DEBUG</code> is set to <code>true</code> vs. <code>false</code> is: when <code>SCRIPT_DEBUG</code> is set to <code>true</code>, main JavaScript source files are being loaded and normally (when <code>SCRIPT_DEBUG</code> is set to <code>false</code>), the <strong>minified versions</strong> (e.g. <code>file.min.js</code>) are loaded with <strong>concatenation</strong> &amp; <strong>compression</strong>.</p>\n\n<p>So apparently, the minified versions of the JS files are causing problems. May be they are even corrupted.</p>\n\n<p>Replace WordPress core with the version from wordpress.org, may be this will fix the issues.</p>\n\n<blockquote>\n <p><strong>Note:</strong> Don't forget to clear browser cache when you're done doing this, wrong versions may be loaded from the cache otherwise.</p>\n</blockquote>\n" }, { "answer_id": 323062, "author": "Adon Irani", "author_id": 157062, "author_profile": "https://wordpress.stackexchange.com/users/157062", "pm_score": 0, "selected": false, "text": "<p>I'm experiencing the same issue on the latest Wordpress 5.0.1 but only on /wp-admin/*. Main site renders just fine.</p>\n\n<p>I found defining 'CONCATENATE_SCRIPTS' as false will also solve the issue, which means the minified scripts are actually OK. </p>\n\n<p>Not seeing any permissions issues either. Trying to investigate what exactly happens when scripts are concatenated -- </p>\n" } ]
2018/07/18
[ "https://wordpress.stackexchange.com/questions/308933", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147160/" ]
I try this: ``` <?php function get_ct($id){ $ct = apply_filters('the_content', get_post_field('post_content', $id)); return $ct; } $arr = array('post_content' => get_ct(126)); echo json_encode($arr); ?> ``` but the post\_content 's values ist null any suggestion? thanks
Do you load own javascripts into the admin? If i recall correctly, if SCRIPT\_DEBUG is set to true, the javascripts are not concenated, but loaded seperately. So if a custom javascript doesn't play well being concenated, this can lead to the whole concenated javascript being corrupt and not being run correctly. Try removing the added javascripts one by one and check if that changes anything.
308,941
<p>In August, GDPR requires all websites to have a cookie notification on every page. I am creating a custom post type plugin - but I'm having one problem. The content from the custom post type page isn't being pulled in - it's pulling in the content from the page it is on. If I click on the permalink of the notice page - the content displays exactly as I want it. My guess is, because the plugin is on every page "the_content();" pull in the content from the page they are on. I need to know how to work around this.</p> <p>Here is the code.</p> <p>THE PLUGIN CODE:</p> <pre><code>&lt;?php /** * Plugin Name: GDPR Cookie Notice * Description: Adds a Pop-up notice bar on the bottom of the page for GDPR notifications **/ defined( 'ABSPATH' ) or die( 'You Shall Not Pass!' ); function gdpr_create_post_type(){ $labels = array( 'name' =&gt; 'GDPR Notice', // =&gt; seperator for associative array key =&gt; value 'singular_name' =&gt; 'GDPR Notice', 'add_new' =&gt; 'Add New', 'add_new_item' =&gt; 'Add New GDPR Notice', 'edit_item' =&gt; 'Edit GDPR Notice', 'new_item' =&gt; 'New GDPR Notice', 'view_item' =&gt; 'View GDPR Notices', 'search_items' =&gt; 'Search GDPR Notices', 'not_found' =&gt; 'No GDPR Notices Found', 'not_found_in_trash' =&gt; 'No GDPR Notices Found in Trash' ); $args = array( 'labels' =&gt; $labels, 'has_archive' =&gt; false, // these will be used in pages 'public' =&gt; true, 'hierarchical' =&gt; true, // behave like a page 'rewrite' =&gt; array( 'with_front' =&gt; false, 'slug' =&gt; 'gdpr-notice' ), 'menu_icon' =&gt; 'dashicons-id-alt', 'supports' =&gt; array( 'title', 'author', 'editor', 'custom-fields', 'page-attributes' ) ); register_post_type('gdpr', $args); } add_action('init', 'gdpr_create_post_type'); </code></pre> <p>?></p> <p>THE HEADER.PHP FILE WHERE THE SINGLE PAGE TEMPLATE IS PULLED IN:</p> <pre><code>&lt;header&gt; ... main navigation code ... &lt;/header&gt; &lt;?php get_template_part('single', 'gdpr'); ?&gt; </code></pre> <p>THE SINGLE-GDPR.PHP FILE:</p> <pre><code>&lt;?php /* The file for the GDPR Cookie Notice post type, registered via a plugin */ ?&gt; &lt;div class="cookie-bar"&gt; &lt;section class="section float-me me-floated"&gt; &lt;div class="container"&gt; &lt;div class="row text-center"&gt; &lt;!-- I've added both editor and custom field filters to see if I can get even one to work --&gt; &lt;?php if ( have_posts()) : while ( have_posts()) : the_post(); the_content(); endwhile; endif; ?&gt; &lt;?php if ( have_posts()) : while ( have_posts()) : the_post(); echo get_post_meta($post-&gt;ID, 'notice', true); endwhile; endif; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;/div&gt; </code></pre> <p>WP ADMIN - GDPR Notice custom post type page</p> <p>I'm trying two options – just to see if I can get one to work</p> <p>WP Editor: Read our privacy policy to learn more about how we use cookies.</p> <p>Custom Field: Name: notice Value: Read our privacy policy to learn more about how we use cookies.</p> <p>Thanks for any help you can give.</p>
[ { "answer_id": 308916, "author": "HU is Sebastian", "author_id": 56587, "author_profile": "https://wordpress.stackexchange.com/users/56587", "pm_score": 1, "selected": false, "text": "<p>Do you load own javascripts into the admin? If i recall correctly, if SCRIPT_DEBUG is set to true, the javascripts are not concenated, but loaded seperately. So if a custom javascript doesn't play well being concenated, this can lead to the whole concenated javascript being corrupt and not being run correctly. </p>\n\n<p>Try removing the added javascripts one by one and check if that changes anything.</p>\n" }, { "answer_id": 308920, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 1, "selected": false, "text": "<p>The only thing logically different in JavaScript when <code>SCRIPT_DEBUG</code> is set to <code>true</code> vs. <code>false</code> is: when <code>SCRIPT_DEBUG</code> is set to <code>true</code>, main JavaScript source files are being loaded and normally (when <code>SCRIPT_DEBUG</code> is set to <code>false</code>), the <strong>minified versions</strong> (e.g. <code>file.min.js</code>) are loaded with <strong>concatenation</strong> &amp; <strong>compression</strong>.</p>\n\n<p>So apparently, the minified versions of the JS files are causing problems. May be they are even corrupted.</p>\n\n<p>Replace WordPress core with the version from wordpress.org, may be this will fix the issues.</p>\n\n<blockquote>\n <p><strong>Note:</strong> Don't forget to clear browser cache when you're done doing this, wrong versions may be loaded from the cache otherwise.</p>\n</blockquote>\n" }, { "answer_id": 323062, "author": "Adon Irani", "author_id": 157062, "author_profile": "https://wordpress.stackexchange.com/users/157062", "pm_score": 0, "selected": false, "text": "<p>I'm experiencing the same issue on the latest Wordpress 5.0.1 but only on /wp-admin/*. Main site renders just fine.</p>\n\n<p>I found defining 'CONCATENATE_SCRIPTS' as false will also solve the issue, which means the minified scripts are actually OK. </p>\n\n<p>Not seeing any permissions issues either. Trying to investigate what exactly happens when scripts are concatenated -- </p>\n" } ]
2018/07/18
[ "https://wordpress.stackexchange.com/questions/308941", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145059/" ]
In August, GDPR requires all websites to have a cookie notification on every page. I am creating a custom post type plugin - but I'm having one problem. The content from the custom post type page isn't being pulled in - it's pulling in the content from the page it is on. If I click on the permalink of the notice page - the content displays exactly as I want it. My guess is, because the plugin is on every page "the\_content();" pull in the content from the page they are on. I need to know how to work around this. Here is the code. THE PLUGIN CODE: ``` <?php /** * Plugin Name: GDPR Cookie Notice * Description: Adds a Pop-up notice bar on the bottom of the page for GDPR notifications **/ defined( 'ABSPATH' ) or die( 'You Shall Not Pass!' ); function gdpr_create_post_type(){ $labels = array( 'name' => 'GDPR Notice', // => seperator for associative array key => value 'singular_name' => 'GDPR Notice', 'add_new' => 'Add New', 'add_new_item' => 'Add New GDPR Notice', 'edit_item' => 'Edit GDPR Notice', 'new_item' => 'New GDPR Notice', 'view_item' => 'View GDPR Notices', 'search_items' => 'Search GDPR Notices', 'not_found' => 'No GDPR Notices Found', 'not_found_in_trash' => 'No GDPR Notices Found in Trash' ); $args = array( 'labels' => $labels, 'has_archive' => false, // these will be used in pages 'public' => true, 'hierarchical' => true, // behave like a page 'rewrite' => array( 'with_front' => false, 'slug' => 'gdpr-notice' ), 'menu_icon' => 'dashicons-id-alt', 'supports' => array( 'title', 'author', 'editor', 'custom-fields', 'page-attributes' ) ); register_post_type('gdpr', $args); } add_action('init', 'gdpr_create_post_type'); ``` ?> THE HEADER.PHP FILE WHERE THE SINGLE PAGE TEMPLATE IS PULLED IN: ``` <header> ... main navigation code ... </header> <?php get_template_part('single', 'gdpr'); ?> ``` THE SINGLE-GDPR.PHP FILE: ``` <?php /* The file for the GDPR Cookie Notice post type, registered via a plugin */ ?> <div class="cookie-bar"> <section class="section float-me me-floated"> <div class="container"> <div class="row text-center"> <!-- I've added both editor and custom field filters to see if I can get even one to work --> <?php if ( have_posts()) : while ( have_posts()) : the_post(); the_content(); endwhile; endif; ?> <?php if ( have_posts()) : while ( have_posts()) : the_post(); echo get_post_meta($post->ID, 'notice', true); endwhile; endif; ?> </div> </div> </section> </div> ``` WP ADMIN - GDPR Notice custom post type page I'm trying two options – just to see if I can get one to work WP Editor: Read our privacy policy to learn more about how we use cookies. Custom Field: Name: notice Value: Read our privacy policy to learn more about how we use cookies. Thanks for any help you can give.
Do you load own javascripts into the admin? If i recall correctly, if SCRIPT\_DEBUG is set to true, the javascripts are not concenated, but loaded seperately. So if a custom javascript doesn't play well being concenated, this can lead to the whole concenated javascript being corrupt and not being run correctly. Try removing the added javascripts one by one and check if that changes anything.
308,950
<p>I have a question about <a href="https://codex.wordpress.org/Post_Types#Custom_Post_Types" rel="nofollow noreferrer">this</a> documentation.</p> <p>Why would I register a Custom Post Type in the init function as the docs suggest? Is this only if I am not using a plugin?</p> <p>As I understand it, <a href="https://codex.wordpress.org/Plugin_API/Action_Reference/init" rel="nofollow noreferrer">init runs every-time WordPress runs/is-loaded</a> by the user. Doesn't this mean the site is needlessly re-registering a new post type on every visit? Why not (if building a plugin) register the post type in <code>require_once plugin_dir_path( __FILE__ )</code> just when the plugin activates?</p> <p>Wouldn't that also speed up the site? Or am I interpreting <code>init()</code> wrong? Surely the custom post type persists in the database somewhere so doesn't have to be called on every <code>init()</code>?</p> <p>Here is the Custom Post Type example from the docs, using <code>init()</code>:</p> <pre><code>function create_post_type() { register_post_type( 'acme_product', array( 'labels' =&gt; array( 'name' =&gt; __( 'Products' ), 'singular_name' =&gt; __( 'Product' ) ), 'public' =&gt; true, 'has_archive' =&gt; true, ) ); } add_action( 'init', 'create_post_type' ); </code></pre>
[ { "answer_id": 308951, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 3, "selected": true, "text": "<p><code>register_post_type</code> function should be executed every time a WP request is made. Default post types don't have this requirement. You can use your code as is, in MU plugin. Just create a <code>.PHP</code> file with this code, and place it in <code>mu-plugins</code> sub-folder of <code>wp-content</code>. You don't need to provide any standard plugin headers. </p>\n" }, { "answer_id": 308965, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Surely the custom post type persists in the database somewhere so\n doesn't have to be called on every init()?</p>\n</blockquote>\n\n<p>No, it's not. Why would it need to be? A custom post type is a handful of variables that WordPress will use to set up the UI for data saved with that post type in the database. </p>\n\n<p>If the data were going to change frequently, and the changes needed to be persistent, then storing in the database would be necessary, but post types do not change after development.</p>\n\n<p>Considering that, saving the settings for the post type in the database would only <em>hurt</em> performance, as WordPress would need to query the database just to get the settings for registered post types on every page load, which is slower than just executing the registration code each time (which remember is just a handful of variables).</p>\n\n<p>The most expensive part of registering a post type is generating its rewrite rules, which is why those <em>are</em> stored in the database, and the rewrite rules <em>should</em> be flushed on the activation and deactivation hooks.</p>\n" } ]
2018/07/18
[ "https://wordpress.stackexchange.com/questions/308950", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77764/" ]
I have a question about [this](https://codex.wordpress.org/Post_Types#Custom_Post_Types) documentation. Why would I register a Custom Post Type in the init function as the docs suggest? Is this only if I am not using a plugin? As I understand it, [init runs every-time WordPress runs/is-loaded](https://codex.wordpress.org/Plugin_API/Action_Reference/init) by the user. Doesn't this mean the site is needlessly re-registering a new post type on every visit? Why not (if building a plugin) register the post type in `require_once plugin_dir_path( __FILE__ )` just when the plugin activates? Wouldn't that also speed up the site? Or am I interpreting `init()` wrong? Surely the custom post type persists in the database somewhere so doesn't have to be called on every `init()`? Here is the Custom Post Type example from the docs, using `init()`: ``` function create_post_type() { register_post_type( 'acme_product', array( 'labels' => array( 'name' => __( 'Products' ), 'singular_name' => __( 'Product' ) ), 'public' => true, 'has_archive' => true, ) ); } add_action( 'init', 'create_post_type' ); ```
`register_post_type` function should be executed every time a WP request is made. Default post types don't have this requirement. You can use your code as is, in MU plugin. Just create a `.PHP` file with this code, and place it in `mu-plugins` sub-folder of `wp-content`. You don't need to provide any standard plugin headers.
308,953
<p>I am converting a static website made with Bootstrap in WordPress. Here is my bootstrap multilevel navigation menu code: </p> <pre><code>&lt;section class="menuBar"&gt; &lt;nav class="navbar navbar-expand-lg navbar-light" data-toggle="sticky-onscroll"&gt; &lt;div class="container"&gt; &lt;button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#mainNavbar" aria-controls="mainNavbar" aria-expanded="false" aria-label="Toggle navigation"&gt; &lt;span class="navbar-toggler-icon"&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class="navbar-collapse collapse" id="mainNavbar" style=""&gt; &lt;ul class="navbar-nav"&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" href="#"&gt;Home &lt;span class="sr-only"&gt;(current)&lt;/span&gt;&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item dropdown"&gt; &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt;Commercial Appliances&lt;/a&gt; &lt;ul class="dropdown-menu" aria-labelledby="navbarDropdown"&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Refrigeration&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Refrigerators&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Freezers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Walk-in Coolers/Refrigerators&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Walk-in Freezers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Commercial Freezers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Commercial Refrigerators&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Salad Bars&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Sandwich Coolers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Wine Coolers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Ice Machines&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Beer Coolers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Kegerators&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Flower Coolers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Remote Condensers&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Cooking Equipment&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Commercial Ovens&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Stoves/Ranges&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Cooktops&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Convection Ovens&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Salamander Ovens/Broilers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Double Ovens&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Grills&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Wall Ovens&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Microwaves&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Griddles&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Hot Plates&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Wok Ranges&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Warmers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Deep Fryers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Steam Table&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Ice Machines / Ice Makers&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Countertop&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Remote condenser&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Modular&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Under counter&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Water filters&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Commercial Dishwashers&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Door Type&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Conveyor Type&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Under counter&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Glasswasher&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;High Temperature Dishwashers&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Commercial Laundry&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Washers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Tumble Dryers (Gas/Electric)&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Coin-operated Washer / Dryer&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Ventilation / Exhaust&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Commercial Kitchen Hoods&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Exhaust Fans&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Direct Drive Fans&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Water Heaters&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Electric / Gas Tankless Heaters&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Electric / Gas Tank Heaters&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Garbage Disposals&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Food Wasters&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="nav-item dropdown"&gt; &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt;Residential Appliances&lt;/a&gt; &lt;ul class="dropdown-menu" aria-labelledby="navbarDropdown"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Refrigerators / Freezers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Wine Cooler&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Ice Makers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Washer Machine&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Gas / Electric Dryer&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Wall Ovens&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Double Ovens&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Ranges&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Cooktops&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Microwaves&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Dishwasher&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Garbage Disposal&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Vent Hood&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="nav-item dropdown"&gt; &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt;HVAC&lt;/a&gt; &lt;ul class="dropdown-menu" aria-labelledby="navbarDropdown"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Split system &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Minisplit Ductless systems&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Packaged System&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Gas / Electric Furnace&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Heat Pumps&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Evaporator Coils&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Thermostat&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="nav-item dropdown"&gt; &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt;Installation&lt;/a&gt; &lt;ul class="dropdown-menu" aria-labelledby="navbarDropdown"&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Refrigeration Equipment&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Walk-in Cooler Installation&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Ice Machine&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Cooking Equipment&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Commercial Dishwashers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item dropdown-toggle" href="#"&gt;Commercial Laundry&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Washers&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Dryers&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;HVAC&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Ventilation / Exhaust&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Water Heaters&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="dropdown-item" href="#"&gt;Garbage Disposals&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" href="maintenance-programs.php"&gt;Maintenance Programs&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" href="contact.php"&gt;Contact Us&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;a class="btn btn-red" href="#"&gt;Book Now&lt;/a&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/section&gt; </code></pre> <p>And it's working fine for me: <a href="https://i.stack.imgur.com/UCVhR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UCVhR.jpg" alt="enter image description here"></a></p> <p>But to in WordPress, I have used WP_Bootstrap_Navwalker() for the navigation menu. I have put depth => 3 but it's not showing multi level menu as expected. Here is my code: </p> <pre><code>&lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'primary', 'depth' =&gt; 3, 'container' =&gt; 'div', 'container_class' =&gt; 'collapse navbar-collapse', 'container_id' =&gt; 'mainNavbar', 'menu_class' =&gt; 'navbar-nav', 'fallback_cb' =&gt; 'WP_Bootstrap_Navwalker::fallback', 'walker' =&gt; new WP_Bootstrap_Navwalker() ) ); ?&gt; </code></pre> <p>But it's just working for dropdown only. It's not showing submenu of submenu. How can I fix this problem? </p> <p><a href="https://i.stack.imgur.com/ZuNdV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZuNdV.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 308957, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>Here some thing interesting for you</p>\n\n<p><strong>STEP 1</strong>\nadd a script to header like below ( it's always better go for the enqueue method . i need some one to help me with properly adding the below script in WordPress way .jquery should run before the second script> </p>\n\n<pre><code>&lt;script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n&lt;script&gt;\n$(document).ready(function () {\n$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {\n if (!$(this).next().hasClass('show')) {\n $(this).parents('.dropdown-menu').first().find('.show').removeClass(\"show\");\n }\n var $subMenu = $(this).next(\".dropdown-menu\");\n $subMenu.toggleClass('show');\n\n\n $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {\n $('.dropdown-submenu .show').removeClass(\"show\");\n });\n\n\n return false;\n});\n});\n\n&lt;/script&gt;\n</code></pre>\n\n<p><strong>STEP 2</strong>\nAdd the css like below :</p>\n\n<pre><code>.dropdown-submenu {\n position: relative;\n}\n\n.dropdown-submenu a::after {\n transform: rotate(-90deg);\n position: absolute;\n right: 6px;\n top: .8em;\n}\n\n.dropdown-submenu .dropdown-menu {\n top: 0;\n left: 100%;\n margin-left: .1rem;\n margin-right: .1rem;\n}\n/* to show the arrow */\n.dropdown-submenu a::after {\n transform: rotate(-90deg);\n position: absolute;\n right: 6px;\n top: .8em;\n}\n.dropdown-toggle a::after{\n transform: rotate(-90deg);\n position: absolute;\n right: 6px;\n top: .8em;\n}\n</code></pre>\n\n<p><strong>STEP 3</strong>\nNow go inside the walker class : \nsearch for <code>&amp;&amp; 0 === $depth</code> and remove it. Also make sure that<br>\n<code>'depth' =&gt; 3</code></p>\n\n<p>Now it should start showing the 3rd level menu . some additional css might be required.</p>\n\n<p>This is being added up in header :</p>\n\n<pre><code>wp_nav_menu( array(\n 'theme_location' =&gt; 'primary',\n 'depth' =&gt; 3,\n 'container' =&gt; 'div',\n 'container_class' =&gt; 'collapse navbar-collapse',\n 'container_id' =&gt; 'bs-example-navbar-collapse-1',\n 'menu_class' =&gt; 'nav navbar-nav',\n 'fallback_cb' =&gt; 'WP_Bootstrap_Navwalker::fallback',\n 'walker' =&gt; new WP_Bootstrap_Navwalker(),\n ) );\n</code></pre>\n" }, { "answer_id": 346457, "author": "Daniel Szantar", "author_id": 158360, "author_profile": "https://wordpress.stackexchange.com/users/158360", "pm_score": 0, "selected": false, "text": "<p>For me it works perfect when I remove this line of code:</p>\n\n<pre><code>if (!$(this).next().hasClass('show')) {\n $(this).parents('.dropdown-menu').first().find('.show').removeClass(\"show\");\n}\n</code></pre>\n" }, { "answer_id": 372981, "author": "Muhammad Kashif", "author_id": 193101, "author_profile": "https://wordpress.stackexchange.com/users/193101", "pm_score": 0, "selected": false, "text": "<p>as in bootstrap v4 the .dropdown-submenu class doesn't exist (atleast in mine it doesn't) so if you want for your sub-menus to closes when one click outside of the dropdown just change <code>.dropdown-submenu .show</code> to <code>.dropdown-menu .dropdown-menu.show</code> in the above solution,and make it like in the snippet below:</p>\n<pre><code>$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {\n if (!$(this).next().hasClass('show')) {\n $(this).parents('.dropdown-menu').first().find('.show').removeClass(&quot;show&quot;);\n }\n var $subMenu = $(this).next(&quot;.dropdown-menu&quot;);\n $subMenu.toggleClass('show');\n\n\n $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {\n $('.dropdown-menu .dropdown-menu.show').removeClass(&quot;show&quot;);\n });\n\n\n return false;\n});\n</code></pre>\n" } ]
2018/07/18
[ "https://wordpress.stackexchange.com/questions/308953", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/137372/" ]
I am converting a static website made with Bootstrap in WordPress. Here is my bootstrap multilevel navigation menu code: ``` <section class="menuBar"> <nav class="navbar navbar-expand-lg navbar-light" data-toggle="sticky-onscroll"> <div class="container"> <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#mainNavbar" aria-controls="mainNavbar" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse" id="mainNavbar" style=""> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Commercial Appliances</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item dropdown-toggle" href="#">Refrigeration</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Refrigerators</a></li> <li><a class="dropdown-item" href="#">Freezers</a></li> <li><a class="dropdown-item" href="#">Walk-in Coolers/Refrigerators</a></li> <li><a class="dropdown-item" href="#">Walk-in Freezers</a></li> <li><a class="dropdown-item" href="#">Commercial Freezers</a></li> <li><a class="dropdown-item" href="#">Commercial Refrigerators</a></li> <li><a class="dropdown-item" href="#">Salad Bars</a></li> <li><a class="dropdown-item" href="#">Sandwich Coolers</a></li> <li><a class="dropdown-item" href="#">Wine Coolers</a></li> <li><a class="dropdown-item" href="#">Ice Machines</a></li> <li><a class="dropdown-item" href="#">Beer Coolers</a></li> <li><a class="dropdown-item" href="#">Kegerators</a></li> <li><a class="dropdown-item" href="#">Flower Coolers</a></li> <li><a class="dropdown-item" href="#">Remote Condensers</a></li> </ul> </li> <li><a class="dropdown-item dropdown-toggle" href="#">Cooking Equipment</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Commercial Ovens</a></li> <li><a class="dropdown-item" href="#">Stoves/Ranges</a></li> <li><a class="dropdown-item" href="#">Cooktops</a></li> <li><a class="dropdown-item" href="#">Convection Ovens</a></li> <li><a class="dropdown-item" href="#">Salamander Ovens/Broilers</a></li> <li><a class="dropdown-item" href="#">Double Ovens</a></li> <li><a class="dropdown-item" href="#">Grills</a></li> <li><a class="dropdown-item" href="#">Wall Ovens</a></li> </ul> </li> <li><a class="dropdown-item" href="#">Microwaves</a></li> <li><a class="dropdown-item dropdown-toggle" href="#">Griddles</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Hot Plates</a></li> <li><a class="dropdown-item" href="#">Wok Ranges</a></li> <li><a class="dropdown-item" href="#">Warmers</a></li> <li><a class="dropdown-item" href="#">Deep Fryers</a></li> <li><a class="dropdown-item" href="#">Steam Table</a></li> </ul> </li> <li><a class="dropdown-item dropdown-toggle" href="#">Ice Machines / Ice Makers</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Countertop</a></li> <li><a class="dropdown-item" href="#">Remote condenser</a></li> <li><a class="dropdown-item" href="#">Modular</a></li> <li><a class="dropdown-item" href="#">Under counter</a></li> <li><a class="dropdown-item" href="#">Water filters</a></li> </ul> </li> <li><a class="dropdown-item dropdown-toggle" href="#">Commercial Dishwashers</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Door Type</a></li> <li><a class="dropdown-item" href="#">Conveyor Type</a></li> <li><a class="dropdown-item" href="#">Under counter</a></li> <li><a class="dropdown-item" href="#">Glasswasher</a></li> <li><a class="dropdown-item" href="#">High Temperature Dishwashers</a></li> </ul> </li> <li><a class="dropdown-item dropdown-toggle" href="#">Commercial Laundry</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Washers</a></li> <li><a class="dropdown-item" href="#">Tumble Dryers (Gas/Electric)</a></li> <li><a class="dropdown-item" href="#">Coin-operated Washer / Dryer</a></li> </ul> </li> <li><a class="dropdown-item dropdown-toggle" href="#">Ventilation / Exhaust</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Commercial Kitchen Hoods</a></li> <li><a class="dropdown-item" href="#">Exhaust Fans</a></li> <li><a class="dropdown-item" href="#">Direct Drive Fans</a></li> </ul> </li> <li><a class="dropdown-item dropdown-toggle" href="#">Water Heaters</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Electric / Gas Tankless Heaters</a></li> <li><a class="dropdown-item" href="#">Electric / Gas Tank Heaters</a></li> </ul> </li> <li><a class="dropdown-item dropdown-toggle" href="#">Garbage Disposals</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Food Wasters</a></li> </ul> </li> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Residential Appliances</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Refrigerators / Freezers</a></li> <li><a class="dropdown-item" href="#">Wine Cooler</a></li> <li><a class="dropdown-item" href="#">Ice Makers</a></li> <li><a class="dropdown-item" href="#">Washer Machine</a></li> <li><a class="dropdown-item" href="#">Gas / Electric Dryer</a></li> <li><a class="dropdown-item" href="#">Wall Ovens</a></li> <li><a class="dropdown-item" href="#">Double Ovens</a></li> <li><a class="dropdown-item" href="#">Ranges</a></li> <li><a class="dropdown-item" href="#">Cooktops</a></li> <li><a class="dropdown-item" href="#">Microwaves</a></li> <li><a class="dropdown-item" href="#">Dishwasher</a></li> <li><a class="dropdown-item" href="#">Garbage Disposal</a></li> <li><a class="dropdown-item" href="#">Vent Hood</a></li> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">HVAC</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Split system </a></li> <li><a class="dropdown-item" href="#">Minisplit Ductless systems</a></li> <li><a class="dropdown-item" href="#">Packaged System</a></li> <li><a class="dropdown-item" href="#">Gas / Electric Furnace</a></li> <li><a class="dropdown-item" href="#">Heat Pumps</a></li> <li><a class="dropdown-item" href="#">Evaporator Coils</a></li> <li><a class="dropdown-item" href="#">Thermostat</a></li> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Installation</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item dropdown-toggle" href="#">Refrigeration Equipment</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Walk-in Cooler Installation</a></li> <li><a class="dropdown-item" href="#">Ice Machine</a></li> </ul> </li> <li><a class="dropdown-item" href="#">Cooking Equipment</a></li> <li><a class="dropdown-item" href="#">Commercial Dishwashers</a></li> <li><a class="dropdown-item dropdown-toggle" href="#">Commercial Laundry</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Washers</a></li> <li><a class="dropdown-item" href="#">Dryers</a></li> </ul> </li> <li><a class="dropdown-item" href="#">HVAC</a></li> <li><a class="dropdown-item" href="#">Ventilation / Exhaust</a></li> <li><a class="dropdown-item" href="#">Water Heaters</a></li> <li><a class="dropdown-item" href="#">Garbage Disposals</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link" href="maintenance-programs.php">Maintenance Programs</a> </li> <li class="nav-item"> <a class="nav-link" href="contact.php">Contact Us</a> </li> </ul> </div> <a class="btn btn-red" href="#">Book Now</a> </div> </nav> </section> ``` And it's working fine for me: [![enter image description here](https://i.stack.imgur.com/UCVhR.jpg)](https://i.stack.imgur.com/UCVhR.jpg) But to in WordPress, I have used WP\_Bootstrap\_Navwalker() for the navigation menu. I have put depth => 3 but it's not showing multi level menu as expected. Here is my code: ``` <?php wp_nav_menu( array( 'theme_location' => 'primary', 'depth' => 3, 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'mainNavbar', 'menu_class' => 'navbar-nav', 'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback', 'walker' => new WP_Bootstrap_Navwalker() ) ); ?> ``` But it's just working for dropdown only. It's not showing submenu of submenu. How can I fix this problem? [![enter image description here](https://i.stack.imgur.com/ZuNdV.jpg)](https://i.stack.imgur.com/ZuNdV.jpg)
Here some thing interesting for you **STEP 1** add a script to header like below ( it's always better go for the enqueue method . i need some one to help me with properly adding the below script in WordPress way .jquery should run before the second script> ``` <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script> $(document).ready(function () { $('.dropdown-menu a.dropdown-toggle').on('click', function(e) { if (!$(this).next().hasClass('show')) { $(this).parents('.dropdown-menu').first().find('.show').removeClass("show"); } var $subMenu = $(this).next(".dropdown-menu"); $subMenu.toggleClass('show'); $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) { $('.dropdown-submenu .show').removeClass("show"); }); return false; }); }); </script> ``` **STEP 2** Add the css like below : ``` .dropdown-submenu { position: relative; } .dropdown-submenu a::after { transform: rotate(-90deg); position: absolute; right: 6px; top: .8em; } .dropdown-submenu .dropdown-menu { top: 0; left: 100%; margin-left: .1rem; margin-right: .1rem; } /* to show the arrow */ .dropdown-submenu a::after { transform: rotate(-90deg); position: absolute; right: 6px; top: .8em; } .dropdown-toggle a::after{ transform: rotate(-90deg); position: absolute; right: 6px; top: .8em; } ``` **STEP 3** Now go inside the walker class : search for `&& 0 === $depth` and remove it. Also make sure that `'depth' => 3` Now it should start showing the 3rd level menu . some additional css might be required. This is being added up in header : ``` wp_nav_menu( array( 'theme_location' => 'primary', 'depth' => 3, 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'bs-example-navbar-collapse-1', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback', 'walker' => new WP_Bootstrap_Navwalker(), ) ); ```
308,959
<p>I have a blog. My computer crashed months ago, my username is <code>admin</code> I have tried to recover my password but as it is lost create a new one, they sent a huge long address password will not let me copy and I just do not know what to do. I have recently paid for hosting the site again and can't use my dashboard.</p>
[ { "answer_id": 308957, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>Here some thing interesting for you</p>\n\n<p><strong>STEP 1</strong>\nadd a script to header like below ( it's always better go for the enqueue method . i need some one to help me with properly adding the below script in WordPress way .jquery should run before the second script> </p>\n\n<pre><code>&lt;script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n&lt;script&gt;\n$(document).ready(function () {\n$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {\n if (!$(this).next().hasClass('show')) {\n $(this).parents('.dropdown-menu').first().find('.show').removeClass(\"show\");\n }\n var $subMenu = $(this).next(\".dropdown-menu\");\n $subMenu.toggleClass('show');\n\n\n $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {\n $('.dropdown-submenu .show').removeClass(\"show\");\n });\n\n\n return false;\n});\n});\n\n&lt;/script&gt;\n</code></pre>\n\n<p><strong>STEP 2</strong>\nAdd the css like below :</p>\n\n<pre><code>.dropdown-submenu {\n position: relative;\n}\n\n.dropdown-submenu a::after {\n transform: rotate(-90deg);\n position: absolute;\n right: 6px;\n top: .8em;\n}\n\n.dropdown-submenu .dropdown-menu {\n top: 0;\n left: 100%;\n margin-left: .1rem;\n margin-right: .1rem;\n}\n/* to show the arrow */\n.dropdown-submenu a::after {\n transform: rotate(-90deg);\n position: absolute;\n right: 6px;\n top: .8em;\n}\n.dropdown-toggle a::after{\n transform: rotate(-90deg);\n position: absolute;\n right: 6px;\n top: .8em;\n}\n</code></pre>\n\n<p><strong>STEP 3</strong>\nNow go inside the walker class : \nsearch for <code>&amp;&amp; 0 === $depth</code> and remove it. Also make sure that<br>\n<code>'depth' =&gt; 3</code></p>\n\n<p>Now it should start showing the 3rd level menu . some additional css might be required.</p>\n\n<p>This is being added up in header :</p>\n\n<pre><code>wp_nav_menu( array(\n 'theme_location' =&gt; 'primary',\n 'depth' =&gt; 3,\n 'container' =&gt; 'div',\n 'container_class' =&gt; 'collapse navbar-collapse',\n 'container_id' =&gt; 'bs-example-navbar-collapse-1',\n 'menu_class' =&gt; 'nav navbar-nav',\n 'fallback_cb' =&gt; 'WP_Bootstrap_Navwalker::fallback',\n 'walker' =&gt; new WP_Bootstrap_Navwalker(),\n ) );\n</code></pre>\n" }, { "answer_id": 346457, "author": "Daniel Szantar", "author_id": 158360, "author_profile": "https://wordpress.stackexchange.com/users/158360", "pm_score": 0, "selected": false, "text": "<p>For me it works perfect when I remove this line of code:</p>\n\n<pre><code>if (!$(this).next().hasClass('show')) {\n $(this).parents('.dropdown-menu').first().find('.show').removeClass(\"show\");\n}\n</code></pre>\n" }, { "answer_id": 372981, "author": "Muhammad Kashif", "author_id": 193101, "author_profile": "https://wordpress.stackexchange.com/users/193101", "pm_score": 0, "selected": false, "text": "<p>as in bootstrap v4 the .dropdown-submenu class doesn't exist (atleast in mine it doesn't) so if you want for your sub-menus to closes when one click outside of the dropdown just change <code>.dropdown-submenu .show</code> to <code>.dropdown-menu .dropdown-menu.show</code> in the above solution,and make it like in the snippet below:</p>\n<pre><code>$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {\n if (!$(this).next().hasClass('show')) {\n $(this).parents('.dropdown-menu').first().find('.show').removeClass(&quot;show&quot;);\n }\n var $subMenu = $(this).next(&quot;.dropdown-menu&quot;);\n $subMenu.toggleClass('show');\n\n\n $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {\n $('.dropdown-menu .dropdown-menu.show').removeClass(&quot;show&quot;);\n });\n\n\n return false;\n});\n</code></pre>\n" } ]
2018/07/19
[ "https://wordpress.stackexchange.com/questions/308959", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147180/" ]
I have a blog. My computer crashed months ago, my username is `admin` I have tried to recover my password but as it is lost create a new one, they sent a huge long address password will not let me copy and I just do not know what to do. I have recently paid for hosting the site again and can't use my dashboard.
Here some thing interesting for you **STEP 1** add a script to header like below ( it's always better go for the enqueue method . i need some one to help me with properly adding the below script in WordPress way .jquery should run before the second script> ``` <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script> $(document).ready(function () { $('.dropdown-menu a.dropdown-toggle').on('click', function(e) { if (!$(this).next().hasClass('show')) { $(this).parents('.dropdown-menu').first().find('.show').removeClass("show"); } var $subMenu = $(this).next(".dropdown-menu"); $subMenu.toggleClass('show'); $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) { $('.dropdown-submenu .show').removeClass("show"); }); return false; }); }); </script> ``` **STEP 2** Add the css like below : ``` .dropdown-submenu { position: relative; } .dropdown-submenu a::after { transform: rotate(-90deg); position: absolute; right: 6px; top: .8em; } .dropdown-submenu .dropdown-menu { top: 0; left: 100%; margin-left: .1rem; margin-right: .1rem; } /* to show the arrow */ .dropdown-submenu a::after { transform: rotate(-90deg); position: absolute; right: 6px; top: .8em; } .dropdown-toggle a::after{ transform: rotate(-90deg); position: absolute; right: 6px; top: .8em; } ``` **STEP 3** Now go inside the walker class : search for `&& 0 === $depth` and remove it. Also make sure that `'depth' => 3` Now it should start showing the 3rd level menu . some additional css might be required. This is being added up in header : ``` wp_nav_menu( array( 'theme_location' => 'primary', 'depth' => 3, 'container' => 'div', 'container_class' => 'collapse navbar-collapse', 'container_id' => 'bs-example-navbar-collapse-1', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback', 'walker' => new WP_Bootstrap_Navwalker(), ) ); ```
308,970
<p>I have a widget located at <code>/child-theme/includes/custom-widget.php</code>.</p> <p>How do I call <code>register_widget</code> and reference that widget?</p> <p>I've tried something like the following inside <code>functions.php</code>:</p> <pre><code>function SER_register_widgets() { register_widget( 'includes/custom-widget.php' ); } add_action( 'widgets_init', 'SER_register_widgets' ); </code></pre> <p>but this does not work.</p> <p>Help appreciated.</p>
[ { "answer_id": 308972, "author": "maverick", "author_id": 132953, "author_profile": "https://wordpress.stackexchange.com/users/132953", "pm_score": 3, "selected": true, "text": "<p>include that file in your functions.php file like </p>\n\n<p><code>require_once('includes/custom-widgets.php');</code></p>\n\n<p>then you can call <code>add_action()</code> hook, in your case </p>\n\n<p><code>add_action('widgets_init', 'SER_register_widgets'); .</code></p>\n\n<p>the idea is to make that function ( ser_register_widgets ) visible in current php file ( functions.php file in this case )</p>\n" }, { "answer_id": 308973, "author": "Krzysiek Dróżdż", "author_id": 34172, "author_profile": "https://wordpress.stackexchange.com/users/34172", "pm_score": 0, "selected": false, "text": "<p>OK, that's not how PHP works... ;)</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/register_widget\" rel=\"nofollow noreferrer\"><code>register_widget</code></a> function gets exactly one param - widget class... You can't pass a file path as a class name... Of course you have to make sure, that such class exists (so you have to include file with that class).</p>\n\n<pre><code>include_once( 'includes/custom-widget.php' );\n\nfunction SER_register_widgets() { \n register_widget( 'My_Custom_Widget_Class' ); // &lt;-- change to real class\n}\nadd_action( 'widgets_init', 'SER_register_widgets' );\n</code></pre>\n" } ]
2018/07/19
[ "https://wordpress.stackexchange.com/questions/308970", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147186/" ]
I have a widget located at `/child-theme/includes/custom-widget.php`. How do I call `register_widget` and reference that widget? I've tried something like the following inside `functions.php`: ``` function SER_register_widgets() { register_widget( 'includes/custom-widget.php' ); } add_action( 'widgets_init', 'SER_register_widgets' ); ``` but this does not work. Help appreciated.
include that file in your functions.php file like `require_once('includes/custom-widgets.php');` then you can call `add_action()` hook, in your case `add_action('widgets_init', 'SER_register_widgets'); .` the idea is to make that function ( ser\_register\_widgets ) visible in current php file ( functions.php file in this case )
308,994
<p>I need to show the post featured image at the desired position on my theme template. At the same time, I need its width to be 300px and the height- adaptive.</p> <p>What code should I add to my template?</p>
[ { "answer_id": 308995, "author": "Guillermo Carone", "author_id": 76897, "author_profile": "https://wordpress.stackexchange.com/users/76897", "pm_score": 0, "selected": false, "text": "<p>f you want the width of the image to be fixed and the height to change you should look into creating a div and adding your image as a cover in the background, otherwise you will be deforming your image.</p>\n\n<p>Here is the code. You can also see it working here <a href=\"https://codepen.io/guillermo-carone/pen/zLKQON\" rel=\"nofollow noreferrer\">https://codepen.io/guillermo-carone/pen/zLKQON</a></p>\n\n<pre><code>&lt;style&gt;\n.post_snap {\n width: 300px;\n height: 75vh;\n}\n&lt;/style&gt;\n\n&lt;div class=\"post_snap\" style=\"background: url(http://mirlostudio.com/mission-3/wp-content/uploads/sites/28/2016/07/Look-Up-Architecture-17.jpg) no-repeat center; background-size: cover;\"&gt;\n</code></pre>\n\n<p></p>\n" }, { "answer_id": 308998, "author": "Shibi", "author_id": 62500, "author_profile": "https://wordpress.stackexchange.com/users/62500", "pm_score": 2, "selected": true, "text": "<p>You can create custom size image with <a href=\"https://developer.wordpress.org/reference/functions/add_image_size/\" rel=\"nofollow noreferrer\"><code>add_image_size()</code></a> in the functions.php</p>\n\n<pre><code>function add_custom_size_images() {\n // Add image size width 300 with unlimited height.\n add_image_size( 'featured-image-300', 300 );\n}\nadd_action( 'after_setup_theme', 'add_custom_size_images' );\n</code></pre>\n\n<p>And in the template to get the size that you created with <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow noreferrer\"><code>the_post_thumbnail()</code></a></p>\n\n<pre><code>the_post_thumbnail( 'featured-image-300' );\n</code></pre>\n\n<p><strong>Notice:</strong> If you want it to work with the old images that you uploaded already you need to regenarate the thumbnails. There are some plugins for this.</p>\n\n<p>Plugin for example <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/regenerate-thumbnails/</a></p>\n" } ]
2018/07/19
[ "https://wordpress.stackexchange.com/questions/308994", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/145504/" ]
I need to show the post featured image at the desired position on my theme template. At the same time, I need its width to be 300px and the height- adaptive. What code should I add to my template?
You can create custom size image with [`add_image_size()`](https://developer.wordpress.org/reference/functions/add_image_size/) in the functions.php ``` function add_custom_size_images() { // Add image size width 300 with unlimited height. add_image_size( 'featured-image-300', 300 ); } add_action( 'after_setup_theme', 'add_custom_size_images' ); ``` And in the template to get the size that you created with [`the_post_thumbnail()`](https://developer.wordpress.org/reference/functions/the_post_thumbnail/) ``` the_post_thumbnail( 'featured-image-300' ); ``` **Notice:** If you want it to work with the old images that you uploaded already you need to regenarate the thumbnails. There are some plugins for this. Plugin for example <https://wordpress.org/plugins/regenerate-thumbnails/>
309,007
<p>I have set up a custom post type, which user can edit from the frontend. I'm using <code>wp_delete_post()</code> to allow users to delete a post they created. It works, but the posts get deleted instead of being moved to trash.<p>I have tried moving a post to the bin via the backend and it works like you would expect it, the post is moved to the Bin. So I'm not sure why the <code>wp_delete_post</code> doesn't work the same way, but permanently removes the post instead.</p> <p>According to the WordPress Codex, the second parameter of the <code>wp_delete_post()</code> function is a boolean, which, if set to false, should move the post to trash, not permanently delete it. The second parameter is set to false by default, so this is my code: <p><code>wp_delete_post( $race-&gt;ID );</code></p><p>I'm aware that I can use the <code>wp_trash_post()</code> function instead (which is actually what I'm using now, since the <code>wp_delete_post</code>, doesn't do what I want it to do), but I would like to find out why the <code>wp_delete_post()</code> function doesn't work correctly.</p></p>
[ { "answer_id": 309013, "author": "Hồ Trọng Linh Ân", "author_id": 141631, "author_profile": "https://wordpress.stackexchange.com/users/141631", "pm_score": 4, "selected": true, "text": "<p>Following the line of code</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/post.php#L2467\" rel=\"noreferrer\">https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/post.php#L2467</a></p>\n\n<pre><code>if ( ! $force_delete &amp;&amp; ( 'post' === $post-&gt;post_type || 'page' === $post-&gt;post_type ) &amp;&amp; 'trash' !== get_post_status( $postid ) &amp;&amp; EMPTY_TRASH_DAYS ) {\n return wp_trash_post( $postid );\n}\n</code></pre>\n\n<p>the $force_delete just work with 'post' and 'page', it not work with custom post type</p>\n" }, { "answer_id": 358182, "author": "Antti Koskinen", "author_id": 144392, "author_profile": "https://wordpress.stackexchange.com/users/144392", "pm_score": 1, "selected": false, "text": "<p>The <code>wp_delete_post()</code> has <code>pre_delete_post</code> filter before the deletion takes place, which you can use to prevent custom post types from getting deleted.</p>\n\n<pre><code>function prevent_cpt_delete( $delete, $post, $force_delete ) {\n // Is it my post type someone is trying to delete?\n if ( 'my_post_type' === $post-&gt;post_type &amp;&amp; ! $force_delete ) {\n // Try to trash the cpt instead\n return wp_trash_post( $post-&gt;ID ); // returns (WP_Post|false|null) Post data on success, false or null on failure.\n }\n return $delete; \n}\nadd_filter('pre_delete_post', 'prevent_cpt_delete', 10, 3);\n</code></pre>\n" } ]
2018/07/19
[ "https://wordpress.stackexchange.com/questions/309007", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136877/" ]
I have set up a custom post type, which user can edit from the frontend. I'm using `wp_delete_post()` to allow users to delete a post they created. It works, but the posts get deleted instead of being moved to trash.I have tried moving a post to the bin via the backend and it works like you would expect it, the post is moved to the Bin. So I'm not sure why the `wp_delete_post` doesn't work the same way, but permanently removes the post instead. According to the WordPress Codex, the second parameter of the `wp_delete_post()` function is a boolean, which, if set to false, should move the post to trash, not permanently delete it. The second parameter is set to false by default, so this is my code: `wp_delete_post( $race->ID );` I'm aware that I can use the `wp_trash_post()` function instead (which is actually what I'm using now, since the `wp_delete_post`, doesn't do what I want it to do), but I would like to find out why the `wp_delete_post()` function doesn't work correctly.
Following the line of code <https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/post.php#L2467> ``` if ( ! $force_delete && ( 'post' === $post->post_type || 'page' === $post->post_type ) && 'trash' !== get_post_status( $postid ) && EMPTY_TRASH_DAYS ) { return wp_trash_post( $postid ); } ``` the $force\_delete just work with 'post' and 'page', it not work with custom post type
309,008
<p>I would like to do the following:</p> <p>Registered users in my wordpress application can receive messages. They can choose to receive messages in the following ways:</p> <ul> <li>The Wordpress application (Inbox system)</li> <li>SMS message</li> <li>Email</li> </ul> <p>I would like to use the <a href="https://nl.wordpress.org/plugins/front-end-pm/" rel="nofollow noreferrer">Front End PM plugin</a> to send messages in portal. For the sms messages I would use the <a href="https://nl.wordpress.org/plugins/wp-twilio-core/" rel="nofollow noreferrer">Twilio plugin</a>. </p> <p>So when they sent a message (functionality by Front end PM plugin) I would like to call another function in the Twilio plugin to send an SMS.</p> <p>What's the proper way to do this? I don't think editing the function in the Front End PM plugin is the correct way to do this? How should it be done?</p>
[ { "answer_id": 309383, "author": "Deleyna", "author_id": 147443, "author_profile": "https://wordpress.stackexchange.com/users/147443", "pm_score": 0, "selected": false, "text": "<p>Disclaimer: I'm a relatively new developer and don't know those plugins so my suggestions are general.</p>\n\n<p>You're right not to edit the existing functions.</p>\n\n<p>My thought would be to create your own plugin and look to see if there are any hooks that you can tie into in Front End PM plugin. See if you can add a filter (?) to piggy-back the Twilo function onto it.</p>\n\n<p>You'd need to have your plugin test to make sure both of the other plugins are available before trying to run. </p>\n\n<p>My gut tells me that this would be tremendously unstable, however.</p>\n\n<p>Less useful answer, but possibly better in the long run: consider contacting the developers of those plugins and seeing if they have any ideas.</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 309392, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": -1, "selected": false, "text": "<p>I would check if possible to intercept the \"send message\" button, call via javascript a custom ajax function that collects the necessary data and pass them to a function of the \"twilio plugin\" php classes to send also the SMS..not so easy without good programming skill though.</p>\n" }, { "answer_id": 309418, "author": "Levi Dulstein", "author_id": 101988, "author_profile": "https://wordpress.stackexchange.com/users/101988", "pm_score": 1, "selected": false, "text": "<p>I took a look at both plugins docs and it seems that this what you need can be done relatively easy, since both plugins provide nice action hooks here and there. </p>\n\n<p>According to WP Twilio docs you should be able to \"send a text message on virtually any WordPress action\"and they even provide a <a href=\"https://github.com/mohsinoffline/wp-twilio-core#example\" rel=\"nofollow noreferrer\">simple example of how to that.</a> I would try to use that function and hook it into the other plugin's action.</p>\n\n<p>As for Front End PM plugin there seems to be a n<a href=\"https://plugins.trac.wordpress.org/browser/front-end-pm/branches/5.1/functions.php#L972\" rel=\"nofollow noreferrer\">ice action hook</a>:</p>\n\n<p><code>do_action( 'fep_action_message_after_send', $message_id, $message, $inserted_message );</code></p>\n\n<p>It is executed every time a message is saved in DB after using the front-end UI, so it it seems like a perfect place to plug you SMS sending function in. You even get the message data inside that hook, pretty cool, we'll use that!</p>\n\n<p>So to sum up, I'd try something like this:</p>\n\n<ol>\n<li><p>Create a function that sends a SMS using Twilio's example, all the arguments are taken from the hook mentioned above:</p>\n\n<pre><code>function send_sms_with_twilio( $message_id, $message, $inserted_message ){\n // Now the $message should be an array with Front End PM data, \n // so just check the plugin's code to determine what data you want to pass to a text message.\n // i'll do a simple example:\n $sms_message = '';\n if ( is_array( $message ) &amp;&amp; ! empty( $message['message_title'] ) ) {\n $sms_message = sprintf( 'Hello mate, you have received a new PM titled \"%s\"', esc_html( $message['message_title'] ) );\n }\n\n // [message_to_id] key should contain WP users ID's, again - you should doublecheck that\n $receivers = ! empty( $message['message_to_id'] ) ? (array) $message['message_to_id'] : [];\n\n // Now I'm not sure where you keep phone numbers, but let's assume it's in user's meta, so I'll try this\n // assuming 'phone_number' is right meta key:\n foreach( $receivers as $receiver ){\n $to = get_user_meta( $receiver, 'phone_number', true );\n\n // Let's send this message finally! But only if we have a number and text.\n // you probably should do some additional validation here \n // to make sure that the phone number is properly formatted.\n if ( empty( $to ) || empty( $sms_message ) ) {\n return;\n }\n\n // this is Twilo's plugin function\n twl_send_sms( [\n 'number_to' =&gt; $to,\n 'message' =&gt; $sms_message,\n ] );\n }\n}\n</code></pre></li>\n<li><p>Now you can hook your function to Front End PM's hook:</p>\n\n<pre><code>add_action( 'fep_action_message_after_send', 'send_sms_with_twilio', 100, 3 );\n</code></pre></li>\n</ol>\n\n<p>Bear in mind that what I'm doing here is just a quick draft based on what I saw in plugins' code. I haven't tested it but it should give you a general idea how to tackle your issue.</p>\n\n<p>The question might be where to put that code - I think you could try in your theme's <code>functions.php</code> but only for testing purposes and when you are sure that both plugins are active. For production purposes, I would separate that as a third plugin and use <a href=\"https://codex.wordpress.org/Function_Reference/is_plugin_active\" rel=\"nofollow noreferrer\">is_plugin_active()</a> function to make sure that all the dependencies are in place.</p>\n" }, { "answer_id": 309433, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 3, "selected": true, "text": "<p>Levi Dulstein has a lot of righ, but in my opinion Front-end-pm uses two hooks to send messages:</p>\n\n<ul>\n<li>fep_save_message (from back-end)</li>\n<li>fep_action_message_after_send (from front-end)</li>\n</ul>\n\n<p>Before sending a email few things are checked, like publishig or sending status (includes/class-fep-emails.php):</p>\n\n<pre><code>function save_send_email( $postid, $post ) {\n if ( ! $post instanceof WP_Post ) {\n $post = get_post( $postid );\n }\n if ( 'publish' != $post-&gt;post_status ){\n return;\n } \n if ( get_post_meta( $postid, '_fep_email_sent', true ) ){\n return;\n }\n $this-&gt;send_email( $postid, $post );\n}\n</code></pre>\n\n<p>So, for test try add something like this to your plugin or theme:</p>\n\n<pre><code>function send_sms( $postid, $post ) {\n if ( ! $post instanceof WP_Post ) {\n $post = get_post( $postid );\n }\n if ( 'publish' != $post-&gt;post_status ){\n return;\n } \n if ( get_post_meta( $postid, '_fep_email_sent', true ) ){\n return;\n }\n // use Twilio plugin function twl_send_sms\n if( function_exists('twl_send_sms') ) {\n\n $participants = fep_get_participants( $postid );\n // check if recipients exists, for each get the phone number, \n // send message and mark sms as sent (or save sms send time)\n $args = array( \n 'message' =&gt; $post-&gt;post_title, // or $post-&gt;post_content\n ); \n foreach ($participants as $participant) {\n // get usermeta with phone number for $participant ID \n $args['number_to'] = '098765'; \n twl_send_sms( $args );\n }\n }\n}\nadd_action( 'fep_save_message', 'send_sms', 99, 2 ); //sending from back-end\nadd_action( 'fep_action_message_after_send , 'send_sms', 99, 2 ); //front-end\n</code></pre>\n\n<p>Sorry for my english. I hope you understand what I want to say.</p>\n" } ]
2018/07/19
[ "https://wordpress.stackexchange.com/questions/309008", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65180/" ]
I would like to do the following: Registered users in my wordpress application can receive messages. They can choose to receive messages in the following ways: * The Wordpress application (Inbox system) * SMS message * Email I would like to use the [Front End PM plugin](https://nl.wordpress.org/plugins/front-end-pm/) to send messages in portal. For the sms messages I would use the [Twilio plugin](https://nl.wordpress.org/plugins/wp-twilio-core/). So when they sent a message (functionality by Front end PM plugin) I would like to call another function in the Twilio plugin to send an SMS. What's the proper way to do this? I don't think editing the function in the Front End PM plugin is the correct way to do this? How should it be done?
Levi Dulstein has a lot of righ, but in my opinion Front-end-pm uses two hooks to send messages: * fep\_save\_message (from back-end) * fep\_action\_message\_after\_send (from front-end) Before sending a email few things are checked, like publishig or sending status (includes/class-fep-emails.php): ``` function save_send_email( $postid, $post ) { if ( ! $post instanceof WP_Post ) { $post = get_post( $postid ); } if ( 'publish' != $post->post_status ){ return; } if ( get_post_meta( $postid, '_fep_email_sent', true ) ){ return; } $this->send_email( $postid, $post ); } ``` So, for test try add something like this to your plugin or theme: ``` function send_sms( $postid, $post ) { if ( ! $post instanceof WP_Post ) { $post = get_post( $postid ); } if ( 'publish' != $post->post_status ){ return; } if ( get_post_meta( $postid, '_fep_email_sent', true ) ){ return; } // use Twilio plugin function twl_send_sms if( function_exists('twl_send_sms') ) { $participants = fep_get_participants( $postid ); // check if recipients exists, for each get the phone number, // send message and mark sms as sent (or save sms send time) $args = array( 'message' => $post->post_title, // or $post->post_content ); foreach ($participants as $participant) { // get usermeta with phone number for $participant ID $args['number_to'] = '098765'; twl_send_sms( $args ); } } } add_action( 'fep_save_message', 'send_sms', 99, 2 ); //sending from back-end add_action( 'fep_action_message_after_send , 'send_sms', 99, 2 ); //front-end ``` Sorry for my english. I hope you understand what I want to say.
309,043
<p>I have all terms in English and I am creating/duplicating the same ones for German language by using foreach on english terms and this way i create all terms for German language. </p> <p>The problem is when i need to assign an German term to its English version.</p> <p>I tried the trick with TRID like this: </p> <pre><code>$trid = $sitepress-&gt;get_element_trid($englist_term_id, "taxonomy_name"); $sitepress-&gt;set_element_language_details($new_term_id, "taxonomy_name", $trid, $lang_code, $sitepress-&gt;get_default_language()); </code></pre> <p>The problem is that $trid does not take any value (The first line of the above code)</p> <p>Probably there is some other way to accomplish this!</p>
[ { "answer_id": 309046, "author": "Agon Xheladini", "author_id": 86433, "author_profile": "https://wordpress.stackexchange.com/users/86433", "pm_score": 1, "selected": false, "text": "<p>Ok I found the solution. </p>\n\n<p>Actually taxonomy name on icl_translation table is stored with prefix called \"tax_\" which means taxonomy. The above code would work like this:</p>\n\n<pre><code>$trid = $sitepress-&gt;get_element_trid($englist_term_id, \"tax_taxonomy_name\");\n\n$sitepress-&gt;set_element_language_details($new_term_id, \"tax_taxonomy_name\", $trid, $lang_code, $sitepress-&gt;get_default_language());\n</code></pre>\n\n<p>The difference is tax_ prefix. </p>\n\n<p>Cheers!</p>\n" }, { "answer_id": 394054, "author": "Matthias Günter", "author_id": 83335, "author_profile": "https://wordpress.stackexchange.com/users/83335", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://wordpress.stackexchange.com/a/309046/83335\">@agon-xheladini</a> is totally correct with his answer.</p>\n<p>But this did not work for me as the <a href=\"https://wpml.org/wpml-hook/wpml_set_element_language_details/\" rel=\"nofollow noreferrer\">WPML API</a> wants to have the <a href=\"https://developer.wordpress.org/reference/classes/wp_term/\" rel=\"nofollow noreferrer\"><code>term_taxonomy_id</code></a> instead:</p>\n<blockquote>\n<p>element_id(bool) Use <strong>term_taxonomy_id for taxonomies</strong>, post_id for posts</p>\n</blockquote>\n<p>So, you should always ensure that you do not use the <code>term_id</code>:</p>\n<pre><code>$originalElementId = get_term($original_term_id)-&gt;term_taxonomy_id;\n\n$trid = $sitepress-&gt;get_element_trid($originalElementId, &quot;tax_&quot; . $taxonomy);\n$sitepress-&gt;set_element_language_details(\n get_term($new_term_id)-&gt;term_taxonomy_id,\n &quot;tax_&quot; . $taxonomy,\n $trid,\n $lang_code,\n $sitepress-&gt;get_default_language()\n);\n</code></pre>\n<p><strong>Why?</strong> <code>term_taxonomy_id</code> and <code>term_id</code> are stored in different WordPress database tables. For usual installations, they have both the same ID for the same term (auto-increment). But I had some installations where the auto increment was different (perhaps a tool &quot;cleared&quot; entries?).</p>\n" } ]
2018/07/19
[ "https://wordpress.stackexchange.com/questions/309043", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86433/" ]
I have all terms in English and I am creating/duplicating the same ones for German language by using foreach on english terms and this way i create all terms for German language. The problem is when i need to assign an German term to its English version. I tried the trick with TRID like this: ``` $trid = $sitepress->get_element_trid($englist_term_id, "taxonomy_name"); $sitepress->set_element_language_details($new_term_id, "taxonomy_name", $trid, $lang_code, $sitepress->get_default_language()); ``` The problem is that $trid does not take any value (The first line of the above code) Probably there is some other way to accomplish this!
Ok I found the solution. Actually taxonomy name on icl\_translation table is stored with prefix called "tax\_" which means taxonomy. The above code would work like this: ``` $trid = $sitepress->get_element_trid($englist_term_id, "tax_taxonomy_name"); $sitepress->set_element_language_details($new_term_id, "tax_taxonomy_name", $trid, $lang_code, $sitepress->get_default_language()); ``` The difference is tax\_ prefix. Cheers!
309,065
<p><strong>Background</strong></p> <p>I am using the theme Rookie from Sportpress.</p> <p>I created a child theme.</p> <p>Translation files are existing, especially german in my case.</p> <p>Wordpress is set to german language.</p> <p><strong>The Problem</strong></p> <p>Translation is working fine everywhere except on themes provided templates like the search results page content or pagination.</p> <p>Affected are the SRP title, nothing found page title and nothing found page content. They just stay in default english language. Pagination is affected too.</p> <p>The search form in the content of a nothing found page is translated fine. I guess because it's Wordpress default template.</p> <p><strong>Code</strong></p> <p>here some affected code lines from the parent theme.</p> <p>Search Title</p> <pre><code>&lt;h1 class="page-title entry-title"&gt;&lt;?php printf( __( 'Search Results for: %s', 'rookie' ), '&lt;span&gt;' . get_search_query() . '&lt;/span&gt;' ); ?&gt;&lt;/h1&gt; </code></pre> <p>Nothing Found title:</p> <pre><code>&lt;h1 class="page-title"&gt;&lt;?php _e( 'Nothing Found', 'rookie' ); ?&gt;&lt;/h1&gt; </code></pre> <p>Nothing found text:</p> <pre><code>&lt;p&gt;&lt;?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'rookie' ); ?&gt;&lt;/p&gt; </code></pre> <p>Pagination:</p> <pre><code>&lt;?php if ( get_next_posts_link() ) : ?&gt; &lt;div class="nav-previous"&gt;&lt;?php next_posts_link( __( '&lt;span class="meta-nav"&gt;&amp;larr;&lt;/span&gt; Older posts', 'rookie' ) ); ?&gt;&lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php if ( get_previous_posts_link() ) : ?&gt; &lt;div class="nav-next"&gt;&lt;?php previous_posts_link( __( 'Newer posts &lt;span class="meta-nav"&gt;&amp;rarr;&lt;/span&gt;', 'rookie' ) ); ?&gt;&lt;/div&gt; &lt;?php endif; ?&gt; </code></pre> <p><strong>Findings</strong></p> <p>I checked that the .mo entry for german is existing with the Loco translate plugin.</p> <p>I replaced the Search Result Title <code>Search Results for: %s</code> with the Category Title <code>Category: %s</code>, which gets translated on a category page (because category archive title is provided from Wordpress), but also not on the SRP!</p> <p><em>What could be a reason for this behaviour?</em></p> <p><strong>Workaround</strong></p> <p>the parent theme is loading the domain via <code>load_theme_textdomain( 'rookie', get_template_directory() . '/languages' );</code> and points to right location where all translation files (.pot, de_DE.po and de_DE.mo) are existing.</p> <p>I copied the relevant .po and .mo files over to wp-content/languages/themes/ directory and things are working now.</p> <p><em>But is this the real best solution?</em></p>
[ { "answer_id": 309077, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": -1, "selected": false, "text": "<p>Putting files in <code>wp-content/languages/themes/</code> is not a good idea because on the next update, the file will be overwritten.</p>\n\n<p>The best way to correct that is to put the .mo file in the child theme with the name <code>de_DE.mo</code>.<br>\nThen, if e.g. you put the file in the directory <code>wp-content/themes/rookie-child/languages</code>, put this code in <code>wp-content/themes/rookie-child/functions.php</code> : </p>\n\n<pre><code>add_action(\"after_setup_theme\", function () {\n\n load_theme_textdomain( 'rookie', get_stylesheet_directory() . '/languages' );\n\n\n}, 5);\n</code></pre>\n" }, { "answer_id": 310735, "author": "Tim", "author_id": 48306, "author_profile": "https://wordpress.stackexchange.com/users/48306", "pm_score": 0, "selected": false, "text": "<p>I downloaded the free Rookie parent theme and have no problem displaying translations of \"Search Results for: %s\" on a successful search results screen.</p>\n\n<p>This works in the WordPress languages folder at <code>wp-content/languages/themes/rookie-de_DE.mo</code> as well as Loco Translate's custom directory. It works there if the files are named correctly because the parent theme correctly loads the \"rookie\" text domain using \"load_theme_textdomain\".</p>\n\n<p>Are your files named correctly under the WordPress languages directory? Unlike the de_DE.mo file inside the theme folder, the system location requires the prefix so files should be named rookie-de_DE.mo</p>\n" } ]
2018/07/20
[ "https://wordpress.stackexchange.com/questions/309065", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136930/" ]
**Background** I am using the theme Rookie from Sportpress. I created a child theme. Translation files are existing, especially german in my case. Wordpress is set to german language. **The Problem** Translation is working fine everywhere except on themes provided templates like the search results page content or pagination. Affected are the SRP title, nothing found page title and nothing found page content. They just stay in default english language. Pagination is affected too. The search form in the content of a nothing found page is translated fine. I guess because it's Wordpress default template. **Code** here some affected code lines from the parent theme. Search Title ``` <h1 class="page-title entry-title"><?php printf( __( 'Search Results for: %s', 'rookie' ), '<span>' . get_search_query() . '</span>' ); ?></h1> ``` Nothing Found title: ``` <h1 class="page-title"><?php _e( 'Nothing Found', 'rookie' ); ?></h1> ``` Nothing found text: ``` <p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'rookie' ); ?></p> ``` Pagination: ``` <?php if ( get_next_posts_link() ) : ?> <div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts', 'rookie' ) ); ?></div> <?php endif; ?> <?php if ( get_previous_posts_link() ) : ?> <div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&rarr;</span>', 'rookie' ) ); ?></div> <?php endif; ?> ``` **Findings** I checked that the .mo entry for german is existing with the Loco translate plugin. I replaced the Search Result Title `Search Results for: %s` with the Category Title `Category: %s`, which gets translated on a category page (because category archive title is provided from Wordpress), but also not on the SRP! *What could be a reason for this behaviour?* **Workaround** the parent theme is loading the domain via `load_theme_textdomain( 'rookie', get_template_directory() . '/languages' );` and points to right location where all translation files (.pot, de\_DE.po and de\_DE.mo) are existing. I copied the relevant .po and .mo files over to wp-content/languages/themes/ directory and things are working now. *But is this the real best solution?*
I downloaded the free Rookie parent theme and have no problem displaying translations of "Search Results for: %s" on a successful search results screen. This works in the WordPress languages folder at `wp-content/languages/themes/rookie-de_DE.mo` as well as Loco Translate's custom directory. It works there if the files are named correctly because the parent theme correctly loads the "rookie" text domain using "load\_theme\_textdomain". Are your files named correctly under the WordPress languages directory? Unlike the de\_DE.mo file inside the theme folder, the system location requires the prefix so files should be named rookie-de\_DE.mo
309,106
<p>I have following piece of code, which inserts usernames and other details of users in the database. After inserting the usernames I want to email them using <code>wp_mail();</code>. I am unable to do so. How can I do this?</p> <pre><code>$member_details-&gt;user_login = array_map( 'sanitize_text_field', $_POST['user_login'] ); $member_details-&gt;user_role = array_map( 'sanitize_text_field', $_POST['user_role'] ); $member_details-&gt;status = array_map( 'sanitize_text_field', $_POST['status'] ); $member_details_encode = wp_json_encode( $member_details ); global $wpdb; $member_result = $wpdb-&gt;insert( 'wpxa_project_members', array( 'project_id' =&gt; $_SESSION['project_id'], 'author_id' =&gt; $post_author, 'member_details' =&gt; $member_details_encode ), array( '%d', '%d', '%s' ) ); </code></pre>
[ { "answer_id": 309144, "author": "LearntoExcel", "author_id": 97108, "author_profile": "https://wordpress.stackexchange.com/users/97108", "pm_score": -1, "selected": false, "text": "<p>Let us see what code you are trying. Assuming that the hook you have bound that function to is firing, you would insert this into your function, assuming you want to email the author.</p>\n\n<pre><code>wp_mail($to = $post_author, $subject = 'This is the subject', $message = 'This is the message');\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_mail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_mail/</a></p>\n\n<p>Edit:</p>\n\n<pre><code>$user = get_userdatabylogin($member_details-&gt;user_login);\n$user_id = $user-&gt;ID;\nwp_mail($user_id, 'This is the subject', 'This is the message');\n</code></pre>\n" }, { "answer_id": 328000, "author": "butlerblog", "author_id": 38603, "author_profile": "https://wordpress.stackexchange.com/users/38603", "pm_score": 0, "selected": false, "text": "<p>Assuming that <code>$member_details-&gt;user_login</code> is already a user in the <code>wp_users</code> table, then you could use the following to get their email address:</p>\n\n<p><code>$user = get_user_by( $member_details-&gt;user_login, 'login' );</code></p>\n\n<p>From there, you have the user's email address and can use <code>wp_mail()</code> to email them:</p>\n\n<pre><code>$subject = \"My email subject\";\n$message = \"My message body...\";\nwp_mail( $user-&gt;user_email, $subject, $message );\n</code></pre>\n" } ]
2018/07/20
[ "https://wordpress.stackexchange.com/questions/309106", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124069/" ]
I have following piece of code, which inserts usernames and other details of users in the database. After inserting the usernames I want to email them using `wp_mail();`. I am unable to do so. How can I do this? ``` $member_details->user_login = array_map( 'sanitize_text_field', $_POST['user_login'] ); $member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] ); $member_details->status = array_map( 'sanitize_text_field', $_POST['status'] ); $member_details_encode = wp_json_encode( $member_details ); global $wpdb; $member_result = $wpdb->insert( 'wpxa_project_members', array( 'project_id' => $_SESSION['project_id'], 'author_id' => $post_author, 'member_details' => $member_details_encode ), array( '%d', '%d', '%s' ) ); ```
Assuming that `$member_details->user_login` is already a user in the `wp_users` table, then you could use the following to get their email address: `$user = get_user_by( $member_details->user_login, 'login' );` From there, you have the user's email address and can use `wp_mail()` to email them: ``` $subject = "My email subject"; $message = "My message body..."; wp_mail( $user->user_email, $subject, $message ); ```
309,151
<p>I use the following code to change the title of WordPress <strong>posts</strong> and <strong>pages</strong>. But it changes nav menu item titles too, which I want to avoid.</p> <p>I want to change the title of posts and pages in: <strong>home page</strong>, all <strong>archive pages</strong> and all <strong>widgets</strong> (recent posts widget, random post widget, etc.) </p> <p>There are similar questions in both Stack Overflow and WP Stack Exchange suggesting to use <code>in_the_loop()</code> function. Unfortunately, it doesn't work for me, because if I place it, it also affects the sidebar widgets.</p> <p>That means, if I use <code>in_the_loop()</code> function, <code>the_title</code> filter does not affect <code>recent posts widget</code>, <code>random post widget</code> etc.</p> <p>So how can I apply <code>the_title</code> filter for just <code>post</code> and <code>page</code> titles, but not menu titles?</p> <pre><code>function pppp_title_update( $title, $id = null ) { if ( ! is_admin() ) { if(is_singular(array('post','page')) || is_archive() || is_home()){ if(in_the_loop()){ $current_post_id = get_the_ID(); $new_titile = get_post_meta($current_post_id, 'pp_new_title',true); return $new_titile; } } } return $title; } add_filter( 'the_title', 'pppp_title_update', 10, 2 ); </code></pre>
[ { "answer_id": 309154, "author": "anmari", "author_id": 3569, "author_profile": "https://wordpress.stackexchange.com/users/3569", "pm_score": -1, "selected": false, "text": "<p>If you have the post object (get_the_ID(); or $post->ID; are essentially the same) See <a href=\"https://stackoverflow.com/questions/22351038/get-the-current-page-id-inside-wordpress-plugin-page\">https://stackoverflow.com/questions/22351038/get-the-current-page-id-inside-wordpress-plugin-page</a>, then you should also be able to do use either <a href=\"https://developer.wordpress.org/reference/functions/get_post_type/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_post_type/</a> to check the type or </p>\n\n<pre><code>if (in_array($post-&gt;post_type, array('post', 'page')) {\n... swop the title\n}\n</code></pre>\n" }, { "answer_id": 309291, "author": "kierzniak", "author_id": 132363, "author_profile": "https://wordpress.stackexchange.com/users/132363", "pm_score": 3, "selected": false, "text": "<p>WordPress navigation editor has ability to change menu title regardless of the title of the post/page.</p>\n\n<p>If you need more automated solution code below will replace title of the post/page everywhere using <code>the_title</code> filter but restore default title of the menu item using <code>nav_menu_item_title</code> filter.</p>\n\n<pre><code>/**\n * Replace post/page title on home, single and archive pages.\n *\n * @param string $title Post title\n * @param int $post_id Post ID\n *\n * @return string New post tilte\n */\nfunction wpse_309151_get_replace_default_title_from_meta( $title, $post_id ) {\n\n $post_type = get_post_type( $post_id );\n\n if( !is_admin() &amp;&amp; ( $post_type === 'post' || $post_type === 'page' ) ) {\n\n $new_title = get_post_meta( $post_id, 'wpse_309151_post_title', true);\n\n if( $new_title &amp;&amp; !empty( $new_title ) ) {\n return $new_title;\n }\n }\n\n return $title;\n}\n\nadd_filter( 'the_title', 'wpse_309151_get_replace_default_title_from_meta', 10, 2 );\n\n/**\n * Restore default post/page title in navigation\n *\n * @param string $title The menu item's title.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n *\n * @return string Restored post title\n */\nfunction wpse_309151_get_restore_default_title_for_navigation( $title, $item, $args, $depth ) {\n\n // Remove filter to not affect title\n remove_filter( 'the_title', 'wpse_309151_get_replace_default_title_from_meta', 10, 2 );\n\n $post_id = $item-&gt;object_id;\n $title = get_the_title( $post_id );\n\n // Add the title filter back\n add_filter( 'the_title', 'wpse_309151_get_replace_default_title_from_meta', 10, 2 );\n\n return $title;\n}\n\nadd_filter( 'nav_menu_item_title', 'wpse_309151_get_restore_default_title_for_navigation', 10, 4 );\n</code></pre>\n" }, { "answer_id": 309356, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 6, "selected": true, "text": "<h2>Problem Description:</h2>\n\n<p>Let me rephrase the question first. You want to:</p>\n\n<ol>\n<li><p>Set new title to all <code>post</code> and <code>page</code> type from a meta field.</p></li>\n<li><p>You want this to happen everywhere (home page, single page, widgets etc.)</p></li>\n<li><p>However, you don't want this title change to happen if the title is on the Navigation Menu.</p></li>\n</ol>\n\n<h2>Solution:</h2>\n\n<p>Before I give you the CODE, let me explain a few points first (based on your CODE):</p>\n\n<h2>How to change titles of all posts and pages:</h2>\n\n<p>You already know the use of <code>the_title</code> filter. However, if you want to target all <code>post</code> and <code>page</code> type titles (but not custom post types), then your condition:</p>\n\n<pre><code>is_singular(array('post','page')) || is_archive() || is_home()\n</code></pre>\n\n<p>will not work. For example, it'll change custom post type on an archive page or the home page as well. This condition doesn't check if the title we are filtering is a <code>page</code> or <code>post</code> type. Instead, it checks if the page itself is either singular (<code>post</code> or <code>page</code>) or it's an archive (category, tag etc.) page or the home page. So custom post types in these pages also gets affected. Additionally, if there is a widget in a custom post type (singular) page, then by this logic, <code>page</code> or <code>post</code> titles in that widget will not be affected there.</p>\n\n<p>To fix that, we need a different check, like:</p>\n\n<pre><code>$post = get_post( $id );\nif ( $post instanceof WP_Post &amp;&amp; ( $post-&gt;post_type == 'post' || $post-&gt;post_type == 'page' ) )\n</code></pre>\n\n<h2>Why Navigation Menu title is also changed &amp; how to stop it:</h2>\n\n<p>WordPress applies <code>the_title</code> filter twice on the navigation menu items' title (if the menu items correspond to existing posts or pages).</p>\n\n<ol>\n<li><p>First as the corresponding post or page title. This happens in the <code>wp_setup_nav_menu_item()</code> function of <code>wp-includes/nav-menu.php</code> file.</p></li>\n<li><p>Then as the Menu item title itself. This happens in the <code>Walker_Nav_Menu</code> class.</p></li>\n</ol>\n\n<p>For your requirement, we need to stop the <code>the_title</code> filter both the times.</p>\n\n<p>Fortunately, WordPress has two filters: <code>pre_wp_nav_menu</code> fires before filtering menu titles and <code>wp_nav_menu_items</code> fires after filtering menu titles. So we can use these two filters to first remove the <code>the_title</code> filter for nav menu item titles and then add the <code>the_title</code> filter back again for other titles.</p>\n\n<h2>CODE</h2>\n\n<p>You may use the following CODE in the theme's <code>functions.php</code> file or as a separate plugin:</p>\n\n<pre><code>function wpse309151_title_update( $title, $id = null ) {\n if ( ! is_admin() &amp;&amp; ! is_null( $id ) ) {\n $post = get_post( $id );\n if ( $post instanceof WP_Post &amp;&amp; ( $post-&gt;post_type == 'post' || $post-&gt;post_type == 'page' ) ) {\n $new_titile = get_post_meta( $id, 'pp_new_title', true );\n if( ! empty( $new_titile ) ) {\n return $new_titile;\n }\n }\n }\n return $title;\n}\nadd_filter( 'the_title', 'wpse309151_title_update', 10, 2 );\n\nfunction wpse309151_remove_title_filter_nav_menu( $nav_menu, $args ) {\n // we are working with menu, so remove the title filter\n remove_filter( 'the_title', 'wpse309151_title_update', 10, 2 );\n return $nav_menu;\n}\n// this filter fires just before the nav menu item creation process\nadd_filter( 'pre_wp_nav_menu', 'wpse309151_remove_title_filter_nav_menu', 10, 2 );\n\nfunction wpse309151_add_title_filter_non_menu( $items, $args ) {\n // we are done working with menu, so add the title filter back\n add_filter( 'the_title', 'wpse309151_title_update', 10, 2 );\n return $items;\n}\n// this filter fires after nav menu item creation is done\nadd_filter( 'wp_nav_menu_items', 'wpse309151_add_title_filter_non_menu', 10, 2 );\n</code></pre>\n" } ]
2018/07/21
[ "https://wordpress.stackexchange.com/questions/309151", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106350/" ]
I use the following code to change the title of WordPress **posts** and **pages**. But it changes nav menu item titles too, which I want to avoid. I want to change the title of posts and pages in: **home page**, all **archive pages** and all **widgets** (recent posts widget, random post widget, etc.) There are similar questions in both Stack Overflow and WP Stack Exchange suggesting to use `in_the_loop()` function. Unfortunately, it doesn't work for me, because if I place it, it also affects the sidebar widgets. That means, if I use `in_the_loop()` function, `the_title` filter does not affect `recent posts widget`, `random post widget` etc. So how can I apply `the_title` filter for just `post` and `page` titles, but not menu titles? ``` function pppp_title_update( $title, $id = null ) { if ( ! is_admin() ) { if(is_singular(array('post','page')) || is_archive() || is_home()){ if(in_the_loop()){ $current_post_id = get_the_ID(); $new_titile = get_post_meta($current_post_id, 'pp_new_title',true); return $new_titile; } } } return $title; } add_filter( 'the_title', 'pppp_title_update', 10, 2 ); ```
Problem Description: -------------------- Let me rephrase the question first. You want to: 1. Set new title to all `post` and `page` type from a meta field. 2. You want this to happen everywhere (home page, single page, widgets etc.) 3. However, you don't want this title change to happen if the title is on the Navigation Menu. Solution: --------- Before I give you the CODE, let me explain a few points first (based on your CODE): How to change titles of all posts and pages: -------------------------------------------- You already know the use of `the_title` filter. However, if you want to target all `post` and `page` type titles (but not custom post types), then your condition: ``` is_singular(array('post','page')) || is_archive() || is_home() ``` will not work. For example, it'll change custom post type on an archive page or the home page as well. This condition doesn't check if the title we are filtering is a `page` or `post` type. Instead, it checks if the page itself is either singular (`post` or `page`) or it's an archive (category, tag etc.) page or the home page. So custom post types in these pages also gets affected. Additionally, if there is a widget in a custom post type (singular) page, then by this logic, `page` or `post` titles in that widget will not be affected there. To fix that, we need a different check, like: ``` $post = get_post( $id ); if ( $post instanceof WP_Post && ( $post->post_type == 'post' || $post->post_type == 'page' ) ) ``` Why Navigation Menu title is also changed & how to stop it: ----------------------------------------------------------- WordPress applies `the_title` filter twice on the navigation menu items' title (if the menu items correspond to existing posts or pages). 1. First as the corresponding post or page title. This happens in the `wp_setup_nav_menu_item()` function of `wp-includes/nav-menu.php` file. 2. Then as the Menu item title itself. This happens in the `Walker_Nav_Menu` class. For your requirement, we need to stop the `the_title` filter both the times. Fortunately, WordPress has two filters: `pre_wp_nav_menu` fires before filtering menu titles and `wp_nav_menu_items` fires after filtering menu titles. So we can use these two filters to first remove the `the_title` filter for nav menu item titles and then add the `the_title` filter back again for other titles. CODE ---- You may use the following CODE in the theme's `functions.php` file or as a separate plugin: ``` function wpse309151_title_update( $title, $id = null ) { if ( ! is_admin() && ! is_null( $id ) ) { $post = get_post( $id ); if ( $post instanceof WP_Post && ( $post->post_type == 'post' || $post->post_type == 'page' ) ) { $new_titile = get_post_meta( $id, 'pp_new_title', true ); if( ! empty( $new_titile ) ) { return $new_titile; } } } return $title; } add_filter( 'the_title', 'wpse309151_title_update', 10, 2 ); function wpse309151_remove_title_filter_nav_menu( $nav_menu, $args ) { // we are working with menu, so remove the title filter remove_filter( 'the_title', 'wpse309151_title_update', 10, 2 ); return $nav_menu; } // this filter fires just before the nav menu item creation process add_filter( 'pre_wp_nav_menu', 'wpse309151_remove_title_filter_nav_menu', 10, 2 ); function wpse309151_add_title_filter_non_menu( $items, $args ) { // we are done working with menu, so add the title filter back add_filter( 'the_title', 'wpse309151_title_update', 10, 2 ); return $items; } // this filter fires after nav menu item creation is done add_filter( 'wp_nav_menu_items', 'wpse309151_add_title_filter_non_menu', 10, 2 ); ```
309,177
<p>I have a query as shown below:</p> <pre><code>&lt;?php $query = new WP_Query( $wpplnum ); while( $query-&gt;have_posts() ): $query-&gt;the_post(); ?&gt; &lt;div class="carousel-item col-md-4 active"&gt; &lt;div class="card"&gt; &lt;img class="card-img-top img-fluid" src="http://placehold.it/800x600/f44242/fff" alt="Card image cap"&gt; &lt;div class="card-body"&gt; &lt;h4 class="card-title"&gt;Card 1&lt;/h4&gt; &lt;p class="card-text"&gt;This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.&lt;/p&gt; &lt;p class="card-text"&gt;&lt;small class="text-muted"&gt;Last updated 3 mins ago&lt;/small&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to add the <code>active</code> class only to the first loop item:</p> <p><strong><code>class="carousel-item col-md-4 active"</code></strong></p> <p>the remaining loop items will be without the <code>active</code> class:</p> <p><strong><code>class="carousel-item col-md-4"</code></strong></p>
[ { "answer_id": 309180, "author": "user141080", "author_id": 141080, "author_profile": "https://wordpress.stackexchange.com/users/141080", "pm_score": 0, "selected": false, "text": "<p>Do you mean something like the following?</p>\n\n<pre><code>$query = new WP_Query($wpplnum);\n\n$first = TRUE;\n\nwhile($query-&gt;have_posts()):$query-&gt;the_post();\n\n $class = \"\";\n if($first)\n {\n $class = \"active\";\n $first = FALSE;\n }\n?&gt;\n\n &lt;div class=\"carousel-item col-md-4 &lt;?php echo esc_attr( $class ); ?&gt;\"&gt;\n\n .....\n\n &lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 309181, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 3, "selected": true, "text": "<p><strong>I'd use the <code>current_post</code> property of the <code>WP_Query</code> class instance</strong>, which in your case is the <code>$query</code>. So here I check if <code>$query-&gt;current_post</code> is greater than or equals to <code>1</code>:</p>\n\n<pre><code>&lt;div class=\"carousel-item col-md-4 &lt;?php echo $query-&gt;current_post &gt;= 1 ? '' : 'active'; ?&gt;\"&gt;\n</code></pre>\n\n<p>Resource: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Properties\" rel=\"noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query#Properties</a></p>\n" } ]
2018/07/21
[ "https://wordpress.stackexchange.com/questions/309177", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I have a query as shown below: ``` <?php $query = new WP_Query( $wpplnum ); while( $query->have_posts() ): $query->the_post(); ?> <div class="carousel-item col-md-4 active"> <div class="card"> <img class="card-img-top img-fluid" src="http://placehold.it/800x600/f44242/fff" alt="Card image cap"> <div class="card-body"> <h4 class="card-title">Card 1</h4> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> </div> ``` I want to add the `active` class only to the first loop item: **`class="carousel-item col-md-4 active"`** the remaining loop items will be without the `active` class: **`class="carousel-item col-md-4"`**
**I'd use the `current_post` property of the `WP_Query` class instance**, which in your case is the `$query`. So here I check if `$query->current_post` is greater than or equals to `1`: ``` <div class="carousel-item col-md-4 <?php echo $query->current_post >= 1 ? '' : 'active'; ?>"> ``` Resource: <https://codex.wordpress.org/Class_Reference/WP_Query#Properties>
309,185
<p>so I am still quite new to wordpress development so don't rage and I am sorry if I did something really stupid.</p> <p>So I am having trouble with my CSS, for some reason it's not affecting the widget content output, which can be seen in the movieposterdisplay-class file. What I am trying to do is make the outputted youtube video auto size to fit the container using CSS. What I want to know is why the CSS isn't affecting the HTML code and a solution to fix it. Thanks in advance for any help.</p> <p>movieposterdisplayfile</p> <pre><code>require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay- scripts.php'); require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay- class.php'); function register_movieposterdisplay(){ register_widget('Movie_Poster_Display_Widget'); } add_action('widgets_init', 'register_movieposterdisplay'); </code></pre> <p>movieposterdisplay-scripts file</p> <pre><code>&lt;?php function mpd_add_scripts(){ wp_enqueue_style('mpd-main-style', plugins_url().'/movieposterdisplay/css/style.css'); wp_enqueue_script('mpd-main-style', plugins_url().'/movieposterdisplay/js/main.js'); } add_action('wp_enqueue_scripts', 'mpd_add_scripts'); </code></pre> <p>movieposterdisplay-class file (file contains the widget output)</p> <pre><code>&lt;?php class Movie_Poster_Display_Widget extends WP_Widget { function __construct() { parent::__construct( 'movieposterdisplay_widget', // Base ID esc_html__( 'Movie Widget', 'mpd_domain' ), // Name array( 'description' =&gt; esc_html__( 'Displays Movie/TV posters, overviews and trailers.', 'mpd_domain' ), ) ); } public function widget( $args, $instance) { echo $args['before_widget']; $trailer_key ="http://www.youtube.com/embed/" .$this-&gt;display_trailer($instance, $first_movie_result)."?enablejsapi=1"; ?&gt; &lt;div class="youtubeplayer"&gt; &lt;iframe id="player" type="text/html" src="&lt;?php echo $trailer_key;?&gt;" frameborder="0" allowfullscreen="allowfullscreen"&gt; &lt;/iframe&gt; &lt;/div&gt; &lt;?php echo $args['after_widget']; } </code></pre> <p>style.css</p> <pre><code>.youtubeplayer { position: relative; padding-bottom: 75%; padding-top: 25px; height: 0; border: 5px solid red; } .youtubeplayer iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } </code></pre>
[ { "answer_id": 309189, "author": "Shubham Vijay", "author_id": 28586, "author_profile": "https://wordpress.stackexchange.com/users/28586", "pm_score": -1, "selected": false, "text": "<p>Fortunately, it’s fairly easy to find and diagnose the problem. Go to any page on your site and, in Chrome, right-click and select “Inspect”. That will open up a new window with all kinds of code in it. Find the element and expand it. There, you’ll see a long list of elements. Those are your many stylesheets that are enqueued from a wide variety of sources. When done correctly, each should have an identifying ID. Most likely, you’ll notice that your plugin style is later in the than your theme style.</p>\n\n<p>Of note: You’ll also know you have this problem if you start to add CSS and find yourself having to add !important to all your styles. As a general rule, you shouldn’t ever need to do that as long as everything is enqueued correctly.</p>\n" }, { "answer_id": 309365, "author": "Dev john", "author_id": 147303, "author_profile": "https://wordpress.stackexchange.com/users/147303", "pm_score": 1, "selected": true, "text": "<p>The problem was due to an incorrect file path in the movieposterdisplay-scripts file. Whilst the file loaded correctly in the main php file\n <code>require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay- class.php');</code> \nas it already assigned the correct plugin folder name. It did not enqueue correctly as the code was <code>wp_enqueue_style('mpd-main-style', plugins_url().'/movieposterdisplay/css/style.css');</code> and I had previously changed the folder name. </p>\n\n<p>Hence I thought it was loading correctly and running fine, however it was only loading correctly.</p>\n" } ]
2018/07/21
[ "https://wordpress.stackexchange.com/questions/309185", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147303/" ]
so I am still quite new to wordpress development so don't rage and I am sorry if I did something really stupid. So I am having trouble with my CSS, for some reason it's not affecting the widget content output, which can be seen in the movieposterdisplay-class file. What I am trying to do is make the outputted youtube video auto size to fit the container using CSS. What I want to know is why the CSS isn't affecting the HTML code and a solution to fix it. Thanks in advance for any help. movieposterdisplayfile ``` require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay- scripts.php'); require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay- class.php'); function register_movieposterdisplay(){ register_widget('Movie_Poster_Display_Widget'); } add_action('widgets_init', 'register_movieposterdisplay'); ``` movieposterdisplay-scripts file ``` <?php function mpd_add_scripts(){ wp_enqueue_style('mpd-main-style', plugins_url().'/movieposterdisplay/css/style.css'); wp_enqueue_script('mpd-main-style', plugins_url().'/movieposterdisplay/js/main.js'); } add_action('wp_enqueue_scripts', 'mpd_add_scripts'); ``` movieposterdisplay-class file (file contains the widget output) ``` <?php class Movie_Poster_Display_Widget extends WP_Widget { function __construct() { parent::__construct( 'movieposterdisplay_widget', // Base ID esc_html__( 'Movie Widget', 'mpd_domain' ), // Name array( 'description' => esc_html__( 'Displays Movie/TV posters, overviews and trailers.', 'mpd_domain' ), ) ); } public function widget( $args, $instance) { echo $args['before_widget']; $trailer_key ="http://www.youtube.com/embed/" .$this->display_trailer($instance, $first_movie_result)."?enablejsapi=1"; ?> <div class="youtubeplayer"> <iframe id="player" type="text/html" src="<?php echo $trailer_key;?>" frameborder="0" allowfullscreen="allowfullscreen"> </iframe> </div> <?php echo $args['after_widget']; } ``` style.css ``` .youtubeplayer { position: relative; padding-bottom: 75%; padding-top: 25px; height: 0; border: 5px solid red; } .youtubeplayer iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } ```
The problem was due to an incorrect file path in the movieposterdisplay-scripts file. Whilst the file loaded correctly in the main php file `require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay- class.php');` as it already assigned the correct plugin folder name. It did not enqueue correctly as the code was `wp_enqueue_style('mpd-main-style', plugins_url().'/movieposterdisplay/css/style.css');` and I had previously changed the folder name. Hence I thought it was loading correctly and running fine, however it was only loading correctly.
309,190
<p>Wordpress Category Archive permalinks set up with %category% include the full category tree. I want to see only the leaf category in the URL, not the full tree.</p> <p>Example:</p> <pre><code>Wordpress Category: recipes &gt; baking &gt; bread current permalink for archive: domain.com/recipes/baking/bread desired permalink: domain.com/bread </code></pre> <p>I've been searching the web without any idea how to hook or filter this change into my wordpress code, so any ideas and help is highly welcome. thanks Jan</p>
[ { "answer_id": 309189, "author": "Shubham Vijay", "author_id": 28586, "author_profile": "https://wordpress.stackexchange.com/users/28586", "pm_score": -1, "selected": false, "text": "<p>Fortunately, it’s fairly easy to find and diagnose the problem. Go to any page on your site and, in Chrome, right-click and select “Inspect”. That will open up a new window with all kinds of code in it. Find the element and expand it. There, you’ll see a long list of elements. Those are your many stylesheets that are enqueued from a wide variety of sources. When done correctly, each should have an identifying ID. Most likely, you’ll notice that your plugin style is later in the than your theme style.</p>\n\n<p>Of note: You’ll also know you have this problem if you start to add CSS and find yourself having to add !important to all your styles. As a general rule, you shouldn’t ever need to do that as long as everything is enqueued correctly.</p>\n" }, { "answer_id": 309365, "author": "Dev john", "author_id": 147303, "author_profile": "https://wordpress.stackexchange.com/users/147303", "pm_score": 1, "selected": true, "text": "<p>The problem was due to an incorrect file path in the movieposterdisplay-scripts file. Whilst the file loaded correctly in the main php file\n <code>require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay- class.php');</code> \nas it already assigned the correct plugin folder name. It did not enqueue correctly as the code was <code>wp_enqueue_style('mpd-main-style', plugins_url().'/movieposterdisplay/css/style.css');</code> and I had previously changed the folder name. </p>\n\n<p>Hence I thought it was loading correctly and running fine, however it was only loading correctly.</p>\n" } ]
2018/07/21
[ "https://wordpress.stackexchange.com/questions/309190", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147308/" ]
Wordpress Category Archive permalinks set up with %category% include the full category tree. I want to see only the leaf category in the URL, not the full tree. Example: ``` Wordpress Category: recipes > baking > bread current permalink for archive: domain.com/recipes/baking/bread desired permalink: domain.com/bread ``` I've been searching the web without any idea how to hook or filter this change into my wordpress code, so any ideas and help is highly welcome. thanks Jan
The problem was due to an incorrect file path in the movieposterdisplay-scripts file. Whilst the file loaded correctly in the main php file `require_once(plugin_dir_path(__FILE__).'/includes/movieposterdisplay- class.php');` as it already assigned the correct plugin folder name. It did not enqueue correctly as the code was `wp_enqueue_style('mpd-main-style', plugins_url().'/movieposterdisplay/css/style.css');` and I had previously changed the folder name. Hence I thought it was loading correctly and running fine, however it was only loading correctly.