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
221,264
<p>I have a post type which I want to add some taxonomy values (tags)</p> <p>Example Post Type One</p> <ol> <li><strong>City</strong>: London, Paris</li> <li><strong>Color</strong>: Red, Yellow</li> <li><strong>Language</strong>: </li> </ol> <p>In the example above, Language doesn't have any value, therefore, I want to hide it.</p> <p>I have this code:</p> <pre><code>&lt;?php $lang= get_terms( 'lang' ); if ( !empty( $lang)) { echo '&lt;li&gt;&lt;strong&gt;Language:&lt;/strong&gt;'; the_terms( $post-&gt;ID, 'lang', ' ', ', ' ); echo '&lt;/li&gt;'; } ?&gt; </code></pre> <p>But <strong>Language</strong> will still appear even though I don't add any tags on it.</p>
[ { "answer_id": 221266, "author": "Jubayer Shamshed", "author_id": 90791, "author_profile": "https://wordpress.stackexchange.com/users/90791", "pm_score": 1, "selected": false, "text": "<p>In wordpress <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\">get_terms()</a> function returns (array/int/WP_Error) list of WP_Term instances and their children. Will return WP_Error, if any of $taxonomies do not exist.</p>\n\n<p>So you need no modify your if condition to following </p>\n\n<pre><code>if ( ! empty( $lang ) &amp;&amp; ! is_wp_error( $lang ) ){\n //your code....\n}\n</code></pre>\n\n<p>Hope it will solve your problem.</p>\n" }, { "answer_id": 221296, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a> return all the terms in the taxonomy regardless of the current post.\nSo if current post does not have <strong>lang</strong> terms still this condition <code>if ( !empty( $lang))</code> will be <code>true</code> thus it will display the text <strong>Language</strong>.</p>\n\n<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_term_list\" rel=\"nofollow\"><code>get_the_term_list</code></a> instead of <code>the_terms</code> which return the terms list instead of printing, so output can be used for both purpose.</p>\n\n<p>Example:-</p>\n\n<pre><code>$lang = get_the_term_list( get_the_ID(), 'lang', ' ', ', ' );\nif ( !empty( $lang)) {\n echo '&lt;li&gt;&lt;strong&gt;Language:&lt;/strong&gt;' . $lang . '&lt;/li&gt;';\n}\n</code></pre>\n\n<blockquote>\n <p>Note: Recommended approach is to use <code>get_the_ID()</code> instead of global\n <code>$post-&gt;ID</code></p>\n</blockquote>\n" } ]
2016/03/21
[ "https://wordpress.stackexchange.com/questions/221264", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/55160/" ]
I have a post type which I want to add some taxonomy values (tags) Example Post Type One 1. **City**: London, Paris 2. **Color**: Red, Yellow 3. **Language**: In the example above, Language doesn't have any value, therefore, I want to hide it. I have this code: ``` <?php $lang= get_terms( 'lang' ); if ( !empty( $lang)) { echo '<li><strong>Language:</strong>'; the_terms( $post->ID, 'lang', ' ', ', ' ); echo '</li>'; } ?> ``` But **Language** will still appear even though I don't add any tags on it.
[`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) return all the terms in the taxonomy regardless of the current post. So if current post does not have **lang** terms still this condition `if ( !empty( $lang))` will be `true` thus it will display the text **Language**. Use [`get_the_term_list`](https://codex.wordpress.org/Function_Reference/get_the_term_list) instead of `the_terms` which return the terms list instead of printing, so output can be used for both purpose. Example:- ``` $lang = get_the_term_list( get_the_ID(), 'lang', ' ', ', ' ); if ( !empty( $lang)) { echo '<li><strong>Language:</strong>' . $lang . '</li>'; } ``` > > Note: Recommended approach is to use `get_the_ID()` instead of global > `$post->ID` > > >
221,287
<p>I'm converting html into Wordpress theme. In the header I have a tel number and a button. Both are links, but styled differently.</p> <p>Do you think it would be better to make them a sidebar (widget area) or as settings in customizer? What should be the principle choosing between customiser or widget area.</p>
[ { "answer_id": 221266, "author": "Jubayer Shamshed", "author_id": 90791, "author_profile": "https://wordpress.stackexchange.com/users/90791", "pm_score": 1, "selected": false, "text": "<p>In wordpress <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\">get_terms()</a> function returns (array/int/WP_Error) list of WP_Term instances and their children. Will return WP_Error, if any of $taxonomies do not exist.</p>\n\n<p>So you need no modify your if condition to following </p>\n\n<pre><code>if ( ! empty( $lang ) &amp;&amp; ! is_wp_error( $lang ) ){\n //your code....\n}\n</code></pre>\n\n<p>Hope it will solve your problem.</p>\n" }, { "answer_id": 221296, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a> return all the terms in the taxonomy regardless of the current post.\nSo if current post does not have <strong>lang</strong> terms still this condition <code>if ( !empty( $lang))</code> will be <code>true</code> thus it will display the text <strong>Language</strong>.</p>\n\n<p>Use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_term_list\" rel=\"nofollow\"><code>get_the_term_list</code></a> instead of <code>the_terms</code> which return the terms list instead of printing, so output can be used for both purpose.</p>\n\n<p>Example:-</p>\n\n<pre><code>$lang = get_the_term_list( get_the_ID(), 'lang', ' ', ', ' );\nif ( !empty( $lang)) {\n echo '&lt;li&gt;&lt;strong&gt;Language:&lt;/strong&gt;' . $lang . '&lt;/li&gt;';\n}\n</code></pre>\n\n<blockquote>\n <p>Note: Recommended approach is to use <code>get_the_ID()</code> instead of global\n <code>$post-&gt;ID</code></p>\n</blockquote>\n" } ]
2016/03/21
[ "https://wordpress.stackexchange.com/questions/221287", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87738/" ]
I'm converting html into Wordpress theme. In the header I have a tel number and a button. Both are links, but styled differently. Do you think it would be better to make them a sidebar (widget area) or as settings in customizer? What should be the principle choosing between customiser or widget area.
[`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) return all the terms in the taxonomy regardless of the current post. So if current post does not have **lang** terms still this condition `if ( !empty( $lang))` will be `true` thus it will display the text **Language**. Use [`get_the_term_list`](https://codex.wordpress.org/Function_Reference/get_the_term_list) instead of `the_terms` which return the terms list instead of printing, so output can be used for both purpose. Example:- ``` $lang = get_the_term_list( get_the_ID(), 'lang', ' ', ', ' ); if ( !empty( $lang)) { echo '<li><strong>Language:</strong>' . $lang . '</li>'; } ``` > > Note: Recommended approach is to use `get_the_ID()` instead of global > `$post->ID` > > >
221,323
<p>I am writing a plugin for adding a custom field to the image attachment dialogue box, the plugin works for storing valid input data. I have a problem for showing the error message "This is not a valid URL".</p> <p>I think that I followed the <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/attachment_fields_to_save" rel="nofollow">documentation</a> correctly but maybe there is something that I still missing.</p> <pre class="lang-php prettyprint-override"><code>class my_plugin { public function __construct( ) { $this-&gt;url_pattern = "/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?" . "([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|" . "%[a-fA-f\d]{2,2})*)*(\?(&amp;?([-+_~.\\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]" . "|%[a-fA-f\d]{2,2})*)?$/"; add_filter("attachment_fields_to_edit", array($this, "videourl_image_attachment_fields_to_edit"), 10, 4); add_filter("attachment_fields_to_save", array($this, "videourl_image_attachment_fields_to_save"), 10, 5); } public function videourl_image_attachment_fields_to_edit($form_fields, $post) { $form_fields["videourl"]["label"] = __("Video URL"); $form_fields["videourl"]["helps"] = "Set a video URL for this image"; $form_fields["videourl"]["input"] = "text"; $form_fields["videourl"]["value"] = get_post_meta($post-&gt;ID, "_videourl", true); return $form_fields; } function videourl_image_attachment_fields_to_save($post, $attachment) { if( isset($attachment['videourl']) ){ if( mb_strlen ( trim($attachment['videourl']) ) &gt; 0 &amp;&amp; preg_match($this-&gt;url_pattern, trim($attachment['videourl']))){ update_post_meta($post['ID'], '_videourl', $attachment['videourl']); }elseif(mb_strlen ( trim($attachment['videourl']) ) == 0){ delete_post_meta($post['ID'], '_videourl'); }else{ $post['errors']['videourl']['errors'][] = __('This is not a valid URL.'); } } return $post; } } </code></pre>
[ { "answer_id": 221321, "author": "sankorati", "author_id": 90630, "author_profile": "https://wordpress.stackexchange.com/users/90630", "pm_score": 0, "selected": false, "text": "<p>Gzip compression is defined at server level, not in wp</p>\n" }, { "answer_id": 221330, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>The <code>enfoce_gzip</code> constant, and the other in the same group in your config, actually refer to how wordpress should serve admin side related JS and CSS, and it seems like you are interested in the front end.</p>\n\n<p>Setting gzip compression is something that you should do in your server configuration level (several options depending on the server, but for apache you will probably do it in the .htaccess file), the reason is that most files being served - CSS, JS, images, do not pass though wordpress code at all and therefor wordpress can not have any influence on how they are being served.</p>\n" } ]
2016/03/21
[ "https://wordpress.stackexchange.com/questions/221323", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91017/" ]
I am writing a plugin for adding a custom field to the image attachment dialogue box, the plugin works for storing valid input data. I have a problem for showing the error message "This is not a valid URL". I think that I followed the [documentation](https://codex.wordpress.org/Plugin_API/Filter_Reference/attachment_fields_to_save) correctly but maybe there is something that I still missing. ```php class my_plugin { public function __construct( ) { $this->url_pattern = "/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?" . "([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|" . "%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]" . "|%[a-fA-f\d]{2,2})*)?$/"; add_filter("attachment_fields_to_edit", array($this, "videourl_image_attachment_fields_to_edit"), 10, 4); add_filter("attachment_fields_to_save", array($this, "videourl_image_attachment_fields_to_save"), 10, 5); } public function videourl_image_attachment_fields_to_edit($form_fields, $post) { $form_fields["videourl"]["label"] = __("Video URL"); $form_fields["videourl"]["helps"] = "Set a video URL for this image"; $form_fields["videourl"]["input"] = "text"; $form_fields["videourl"]["value"] = get_post_meta($post->ID, "_videourl", true); return $form_fields; } function videourl_image_attachment_fields_to_save($post, $attachment) { if( isset($attachment['videourl']) ){ if( mb_strlen ( trim($attachment['videourl']) ) > 0 && preg_match($this->url_pattern, trim($attachment['videourl']))){ update_post_meta($post['ID'], '_videourl', $attachment['videourl']); }elseif(mb_strlen ( trim($attachment['videourl']) ) == 0){ delete_post_meta($post['ID'], '_videourl'); }else{ $post['errors']['videourl']['errors'][] = __('This is not a valid URL.'); } } return $post; } } ```
The `enfoce_gzip` constant, and the other in the same group in your config, actually refer to how wordpress should serve admin side related JS and CSS, and it seems like you are interested in the front end. Setting gzip compression is something that you should do in your server configuration level (several options depending on the server, but for apache you will probably do it in the .htaccess file), the reason is that most files being served - CSS, JS, images, do not pass though wordpress code at all and therefor wordpress can not have any influence on how they are being served.
221,333
<p>I am working on a wordpress site that has this short code, </p> <pre><code>[vc_single_image image="7004" css_animation="right-to-left" border_color="grey" img_link_target="_self" img_size="300px"] </code></pre> <p>I need to replicate that short code a few times but I can not figure out where the four digit number referencing the image comes from. </p> <p>I tried changing the <code>7004</code> to a image name and even tried the absolute path to the image. Nothing shows up when I do this not even a broken image. </p> <p>What is that number and how can I add a different image to this short code?</p>
[ { "answer_id": 221336, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>It's not easy to trace trough the code behind <code>[vc_single_image]</code>, because for start it uses the <a href=\"http://php.net/manual/en/function.extract.php\" rel=\"nofollow noreferrer\"><code>extract</code></a>, that's not recommended in WordPress or PHP in general.</p>\n\n<p>The <code>image</code> attribute value is stripped for non-integers into the <code>$img_id</code> variable.</p>\n\n<p>With your setup, there's a call to <code>wpb_getImageBySize( array( 'attach_id' =&gt; $img_id, ... )</code>, that seems to be a wrapper that includes:</p>\n\n<pre><code>wp_get_attachment_image_src( $attach_id, 'large' );\n</code></pre>\n\n<p>So this <code>image</code> attribute is the image attachment ID (integer), just as Nathan Powell mentioned.</p>\n\n<p>If we turn on the <em>backend editor</em> for the visual composer:</p>\n\n<p><a href=\"https://i.stack.imgur.com/dTKhx.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dTKhx.jpg\" alt=\"1\"></a></p>\n\n<p>with the code you posted, then we should get this kind of view:</p>\n\n<p><a href=\"https://i.stack.imgur.com/pcFHb.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pcFHb.jpg\" alt=\"2\"></a></p>\n\n<p>Click on the green pen and we should get the single image settings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/nKkVX.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nKkVX.jpg\" alt=\"3\"></a></p>\n\n<p>there it's easy to select the image attachment directly from the media library.</p>\n\n<p>If we don't wan't the visual setup, we can get the image attachment ID from various links in the Media library. For example when we edit an attachment, the url is:</p>\n\n<pre><code>/wp-admin/post.php?post=7004&amp;action=edit\n</code></pre>\n\n<p>or when we view the attachment details, the url is:</p>\n\n<pre><code>/wp-admin/upload.php?item=7004\n</code></pre>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 360462, "author": "Yohanim", "author_id": 155870, "author_profile": "https://wordpress.stackexchange.com/users/155870", "pm_score": 0, "selected": false, "text": "<p><b>Quick Solution</b></p>\n\n<p>For someone facing the same problem, I have found a quick solution to find attachment id. </p>\n\n<ol>\n<li>Open menu Media</li>\n<li>Select media do you wanted to know what the ID</li>\n<li>look at the URl, in my case <code>http://localhost/.../wp-admin/upload.php?item=1826</code></li>\n<li><p>Just using the item integer on your vc_single_image</p>\n\n<p>thanks to @birgire for the explanation</p>\n\n<p>[vc_single_image image=\"1826\" img_size=\"full\" alignment=\"center\"] </p></li>\n</ol>\n" } ]
2016/03/21
[ "https://wordpress.stackexchange.com/questions/221333", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88534/" ]
I am working on a wordpress site that has this short code, ``` [vc_single_image image="7004" css_animation="right-to-left" border_color="grey" img_link_target="_self" img_size="300px"] ``` I need to replicate that short code a few times but I can not figure out where the four digit number referencing the image comes from. I tried changing the `7004` to a image name and even tried the absolute path to the image. Nothing shows up when I do this not even a broken image. What is that number and how can I add a different image to this short code?
It's not easy to trace trough the code behind `[vc_single_image]`, because for start it uses the [`extract`](http://php.net/manual/en/function.extract.php), that's not recommended in WordPress or PHP in general. The `image` attribute value is stripped for non-integers into the `$img_id` variable. With your setup, there's a call to `wpb_getImageBySize( array( 'attach_id' => $img_id, ... )`, that seems to be a wrapper that includes: ``` wp_get_attachment_image_src( $attach_id, 'large' ); ``` So this `image` attribute is the image attachment ID (integer), just as Nathan Powell mentioned. If we turn on the *backend editor* for the visual composer: [![1](https://i.stack.imgur.com/dTKhx.jpg)](https://i.stack.imgur.com/dTKhx.jpg) with the code you posted, then we should get this kind of view: [![2](https://i.stack.imgur.com/pcFHb.jpg)](https://i.stack.imgur.com/pcFHb.jpg) Click on the green pen and we should get the single image settings: [![3](https://i.stack.imgur.com/nKkVX.jpg)](https://i.stack.imgur.com/nKkVX.jpg) there it's easy to select the image attachment directly from the media library. If we don't wan't the visual setup, we can get the image attachment ID from various links in the Media library. For example when we edit an attachment, the url is: ``` /wp-admin/post.php?post=7004&action=edit ``` or when we view the attachment details, the url is: ``` /wp-admin/upload.php?item=7004 ``` Hope it helps!
221,337
<p>I've blocked access to xmlrcp, and removed most everything that is generated in <code>wp_head</code>. However, I'm still getting notifications in the admin about comments being posted on posts even when there is no form on that page. How is this possible?</p> <p><strong>I'm thinking that this below would work:</strong></p> <pre><code>// Remove comment support add_action( 'init', function() { remove_post_type_support( 'page', 'comments' ); remove_post_type_support( 'post', 'comments' ); }); // Close open comments add_filter( 'comments_open', function( $open, $post_id ) { $post = get_post( $post_id ); if ( 'page' == $post-&gt;post_type || 'post' == $post-&gt;post_type ) $open = false; return $open; }, 10, 2 ); </code></pre> <p>However, whether the above works or not, I'm still wondering how someone/ or a spam bot is able to post a comment when there is no form or anything on the page.</p>
[ { "answer_id": 221342, "author": "Henry Ibinson", "author_id": 91023, "author_profile": "https://wordpress.stackexchange.com/users/91023", "pm_score": 0, "selected": false, "text": "<p>A small trick is checking your current theme and creating a new file comments.php (if you don't have). On this file, you just place this code:</p>\n\n<p><code>&lt;?php return false; ?&gt;</code></p>\n\n<p>It will prevent any bot to use your comment form for posting.</p>\n" }, { "answer_id": 221354, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>The visual representation of a comment form (or lack of it) do not have any impact on the ability to receive comments, and spammers usually don't care at all what is in your form. Wordpress have a well publicized end point to which all comments are being sent (and while I don't remember the detail off the top of my head right now) and spammers can post to that endpoint with enough details to make a proper comment, without even loading the post to which they comment to.</p>\n\n<p>One of the easy antispam steps against lazy spammers is to add an hidden field to the comment form and discard every comment which is submitted without it.</p>\n" } ]
2016/03/21
[ "https://wordpress.stackexchange.com/questions/221337", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38123/" ]
I've blocked access to xmlrcp, and removed most everything that is generated in `wp_head`. However, I'm still getting notifications in the admin about comments being posted on posts even when there is no form on that page. How is this possible? **I'm thinking that this below would work:** ``` // Remove comment support add_action( 'init', function() { remove_post_type_support( 'page', 'comments' ); remove_post_type_support( 'post', 'comments' ); }); // Close open comments add_filter( 'comments_open', function( $open, $post_id ) { $post = get_post( $post_id ); if ( 'page' == $post->post_type || 'post' == $post->post_type ) $open = false; return $open; }, 10, 2 ); ``` However, whether the above works or not, I'm still wondering how someone/ or a spam bot is able to post a comment when there is no form or anything on the page.
The visual representation of a comment form (or lack of it) do not have any impact on the ability to receive comments, and spammers usually don't care at all what is in your form. Wordpress have a well publicized end point to which all comments are being sent (and while I don't remember the detail off the top of my head right now) and spammers can post to that endpoint with enough details to make a proper comment, without even loading the post to which they comment to. One of the easy antispam steps against lazy spammers is to add an hidden field to the comment form and discard every comment which is submitted without it.
221,396
<p>I'm creating my own theme and I'm looking to add a featured image option by adding:</p> <pre><code>add_theme_support( $feature, $arguments ); </code></pre> <p>Into the <code>functions.php</code> file. When I do this I get this error:</p> <pre><code>add_theme_support( 'post-thumbnails' ); Warning: Cannot modify header information - headers already sent by (output started at /wp-content/themes/Precise/functions.php:3) in /wp-includes/pluggable.php on line 1228 </code></pre> <p>How can I fix this?</p>
[ { "answer_id": 221397, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>As user <a href=\"https://wordpress.stackexchange.com/users/76440/majick\">/u/majick</a> suggests in the comments below: the better option may be <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme\" rel=\"nofollow noreferrer\"><code>after_setup_theme</code></a> which looks like this:</p>\n\n<pre><code>function theme_setup() {\n add_theme_support( 'post-thumbnails' );\n}\nadd_action( 'after_setup_theme', 'theme_setup' );\n</code></pre>\n\n<hr>\n\n<p>Another options is to use <code>init</code>.</p>\n\n<pre><code>function theme_init() {\n add_theme_support( 'post-thumbnails' );\n}\nadd_action( 'init', 'theme_init' );\n</code></pre>\n\n<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/init\" rel=\"nofollow noreferrer\"><code>init</code></a> hook explicitly states:</p>\n\n<blockquote>\n <p>Fires after WordPress has finished loading <strong>but before any headers are sent</strong>.</p>\n</blockquote>\n" }, { "answer_id": 221402, "author": "DannyBoy", "author_id": 91011, "author_profile": "https://wordpress.stackexchange.com/users/91011", "pm_score": -1, "selected": false, "text": "<p>ok I changed line 1228 in the pluggable.php file from:</p>\n\n<pre><code>header(\"Location: $location\", true, $status);\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>header(\"Location: $location\", false, $status);\n</code></pre>\n\n<p>And it's done the trick. I now have the 'Featured Image' option in the screen options.</p>\n" } ]
2016/03/22
[ "https://wordpress.stackexchange.com/questions/221396", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91011/" ]
I'm creating my own theme and I'm looking to add a featured image option by adding: ``` add_theme_support( $feature, $arguments ); ``` Into the `functions.php` file. When I do this I get this error: ``` add_theme_support( 'post-thumbnails' ); Warning: Cannot modify header information - headers already sent by (output started at /wp-content/themes/Precise/functions.php:3) in /wp-includes/pluggable.php on line 1228 ``` How can I fix this?
As user [/u/majick](https://wordpress.stackexchange.com/users/76440/majick) suggests in the comments below: the better option may be [`after_setup_theme`](https://codex.wordpress.org/Plugin_API/Action_Reference/after_setup_theme) which looks like this: ``` function theme_setup() { add_theme_support( 'post-thumbnails' ); } add_action( 'after_setup_theme', 'theme_setup' ); ``` --- Another options is to use `init`. ``` function theme_init() { add_theme_support( 'post-thumbnails' ); } add_action( 'init', 'theme_init' ); ``` The [`init`](https://codex.wordpress.org/Plugin_API/Action_Reference/init) hook explicitly states: > > Fires after WordPress has finished loading **but before any headers are sent**. > > >
221,401
<p>I have created the code to loop through the product list and display the price</p> <pre><code> $args = array( 'post_type' =&gt; 'product', 'posts_per_page' =&gt; 100, 'product_cat' =&gt; 'hot-deals'); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); global $product; $xml .= '&lt;Original_price&gt;' . $product-&gt;get_display_price( $product-&gt;get_regular_price() ) . '&lt;/Original_price&gt;'; $xml .= '&lt;Discount_price&gt;' . $product-&gt;get_display_price() . '&lt;/Discount_price&gt;'; echo $product-&gt;get_price_html(); endwhile; wp_reset_query(); </code></pre> <p><code>get_price_html()</code> works perfectly and display the price like this:</p> <pre><code>From: $ 621 $ 559 </code></pre> <p>However , I would like to get the price separately </p> <p>I can get the sales price with </p> <pre><code>$product-&gt;get_display_price() </code></pre> <p>The problem is, I can not get the original price,</p> <p>I tried <code>$product-&gt;get_regular_price()</code> , that return nothing</p> <p>And I tried <code>$product-&gt;get_display_price( $product-&gt;get_regular_price() )</code>, that return the sales price</p> <p>So how to get the original price ? Thanks a lot.</p>
[ { "answer_id": 221409, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": false, "text": "<p>I'm pretty sure that the problem is, that the <code>WP_Query</code> returns <em>post objects</em>, which are not identical to Woocommerces <em>product objects</em>. While you are trying to get the product data by getting the according global, that won't work, especially because the query you are performing does nothing to that global. Now what I probably would do is, firstly, performing the query with the <code>fields</code> parameter set to <code>ids</code>. Secondly, when looping over the returned array of ids, I would suggest you get the <em>product object</em> with <code>wc_get_product()</code>, which should give you all the information you need.</p>\n\n<hr>\n\n<p><em>Note:</em> I answered this to enlighten about the difference in return between WordPress' and Woocommerces object. And to make clear, while <code>product</code> is a CPT it isn't necessarily optimally usable with WP's standard query. There is a strong argument though for your question being off topic, because it is about a third party plugin. Please take a look at our <a href=\"https://wordpress.stackexchange.com/help\">help center</a> to learn more about our site guidelines.</p>\n" }, { "answer_id": 284090, "author": "Oussama Bouthouri", "author_id": 76806, "author_profile": "https://wordpress.stackexchange.com/users/76806", "pm_score": -1, "selected": false, "text": "<p>To get the regular price inside the loop you can use:</p>\n\n<pre><code>get_post_meta( get_the_ID(), '_regular_price', true);\n</code></pre>\n\n<p>And for the sale price you can use:</p>\n\n<pre><code>get_post_meta( get_the_ID(), '_sale_price', true);\n</code></pre>\n" } ]
2016/03/22
[ "https://wordpress.stackexchange.com/questions/221401", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50421/" ]
I have created the code to loop through the product list and display the price ``` $args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'hot-deals'); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); global $product; $xml .= '<Original_price>' . $product->get_display_price( $product->get_regular_price() ) . '</Original_price>'; $xml .= '<Discount_price>' . $product->get_display_price() . '</Discount_price>'; echo $product->get_price_html(); endwhile; wp_reset_query(); ``` `get_price_html()` works perfectly and display the price like this: ``` From: $ 621 $ 559 ``` However , I would like to get the price separately I can get the sales price with ``` $product->get_display_price() ``` The problem is, I can not get the original price, I tried `$product->get_regular_price()` , that return nothing And I tried `$product->get_display_price( $product->get_regular_price() )`, that return the sales price So how to get the original price ? Thanks a lot.
I'm pretty sure that the problem is, that the `WP_Query` returns *post objects*, which are not identical to Woocommerces *product objects*. While you are trying to get the product data by getting the according global, that won't work, especially because the query you are performing does nothing to that global. Now what I probably would do is, firstly, performing the query with the `fields` parameter set to `ids`. Secondly, when looping over the returned array of ids, I would suggest you get the *product object* with `wc_get_product()`, which should give you all the information you need. --- *Note:* I answered this to enlighten about the difference in return between WordPress' and Woocommerces object. And to make clear, while `product` is a CPT it isn't necessarily optimally usable with WP's standard query. There is a strong argument though for your question being off topic, because it is about a third party plugin. Please take a look at our [help center](https://wordpress.stackexchange.com/help) to learn more about our site guidelines.
221,419
<p>I'm trying to implement a custom RSS feed that is formatted for podcasting and pulls in the audio file from an Advanced Custom Field. Basically I've been working off of the example provided here: <a href="https://css-tricks.com/roll-simple-wordpress-podcast-plugin/" rel="nofollow">https://css-tricks.com/roll-simple-wordpress-podcast-plugin/</a></p> <p>My plugin looks like this:</p> <pre><code>// add a custom RSS feed function podcast_rss(){ add_feed('podcast', 'run_podcast_rss'); } add_action('init', 'podcast_rss'); function run_podcast_rss(){ require_once( dirname( __FILE__ ) . '/feed-template.php' ); } </code></pre> <p>This seems pretty straightforward, but when I navigate in my browser to my new feed URL (<a href="http://example.com/feed/podcast/" rel="nofollow">http://example.com/feed/podcast/</a>) The browser tries to download a file. In Google Chrome, the console shows</p> <pre><code>Resource interpreted as Document but transferred with MIME type application/octet-stream: "http://example.com/feed/podcast/". </code></pre> <p>While in Firefox, when it attempts to download the file, it tells me it's a DMS file.</p> <p>I've tried clearing cache, checking for errors in the code, checking .htaccess for odd settings, setting headers; nothing seems to have an effect. In fact, I can comment out the require_once line and simply try to echo plain text. It still forces a download. I've put this on a different server and it behaves the same.</p> <p>I have a feeling it's something simple but I'm out of ideas. Any help?</p>
[ { "answer_id": 224174, "author": "eteubert", "author_id": 743, "author_profile": "https://wordpress.stackexchange.com/users/743", "pm_score": 2, "selected": true, "text": "<p>You need to explicitly set the Content Type, otherwise WordPress defaults to octet-stream for unknown feeds.</p>\n\n<pre><code>function run_podcast_rss(){\n header( 'Content-Type: application/rss+xml; charset=' . get_option( 'blog_charset' ), true );\n require_once( dirname( __FILE__ ) . '/feed-template.php' );\n}\n</code></pre>\n" }, { "answer_id": 354481, "author": "wsizoo", "author_id": 144094, "author_profile": "https://wordpress.stackexchange.com/users/144094", "pm_score": 0, "selected": false, "text": "<p>As @mrfolkblues pointed out you need to add a filter for the feed_content_type. The code below solved the file download issue for me.</p>\n\n<p>Code credit @swissspidy.\n<a href=\"https://core.trac.wordpress.org/ticket/36334#comment:7\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/36334#comment:7</a></p>\n\n<pre><code> &lt;?php\n// Example B:\n\nfunction trac_36334_add_superduperfeed() {\n add_feed( 'superduperfeed', 'trac_36334_superduperfeed_cb' );\n}\n\nadd_action( 'init', 'trac_36334_add_superduperfeed' );\n\nfunction trac_36334_superduperfeed_cb() {\n header( 'Content-Type: text/html' ); // or any other content type\n echo 'Do something...';\n}\n\nfunction trac_36334_superduperfeed_type( $content_type, $type ) {\n if ( 'superduperfeed' === $type ) {\n return feed_content_type( 'rss2' );\n }\n\n return $content_type;\n}\n\nadd_filter( 'feed_content_type', 'trac_36334_superduperfeed_type', 10, 2 );\n</code></pre>\n" } ]
2016/03/22
[ "https://wordpress.stackexchange.com/questions/221419", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91064/" ]
I'm trying to implement a custom RSS feed that is formatted for podcasting and pulls in the audio file from an Advanced Custom Field. Basically I've been working off of the example provided here: <https://css-tricks.com/roll-simple-wordpress-podcast-plugin/> My plugin looks like this: ``` // add a custom RSS feed function podcast_rss(){ add_feed('podcast', 'run_podcast_rss'); } add_action('init', 'podcast_rss'); function run_podcast_rss(){ require_once( dirname( __FILE__ ) . '/feed-template.php' ); } ``` This seems pretty straightforward, but when I navigate in my browser to my new feed URL (<http://example.com/feed/podcast/>) The browser tries to download a file. In Google Chrome, the console shows ``` Resource interpreted as Document but transferred with MIME type application/octet-stream: "http://example.com/feed/podcast/". ``` While in Firefox, when it attempts to download the file, it tells me it's a DMS file. I've tried clearing cache, checking for errors in the code, checking .htaccess for odd settings, setting headers; nothing seems to have an effect. In fact, I can comment out the require\_once line and simply try to echo plain text. It still forces a download. I've put this on a different server and it behaves the same. I have a feeling it's something simple but I'm out of ideas. Any help?
You need to explicitly set the Content Type, otherwise WordPress defaults to octet-stream for unknown feeds. ``` function run_podcast_rss(){ header( 'Content-Type: application/rss+xml; charset=' . get_option( 'blog_charset' ), true ); require_once( dirname( __FILE__ ) . '/feed-template.php' ); } ```
221,423
<p>I made my first WP plugin, it is a contact form - here is the code:</p> <pre><code>&lt;?php /* Plugin Name: Example Contact Form Plugin Plugin URI: http://example.com Description: Simple non-bloated WordPress Contact Form Version: 1.0 Author: Agbonghama Collins Author URI: http://w3guy.com */ function html_form_code() { echo '&lt;form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post"&gt;'; echo '&lt;p&gt;'; echo 'Your Name (required) &lt;br /&gt;'; echo '&lt;input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="' . ( isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : '' ) . '" size="40" /&gt;'; echo '&lt;/p&gt;'; echo '&lt;p&gt;'; echo 'Your Email (required) &lt;br /&gt;'; echo '&lt;input type="email" name="cf-email" value="' . ( isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : '' ) . '" size="40" /&gt;'; echo '&lt;/p&gt;'; echo '&lt;p&gt;'; echo 'Subject (required) &lt;br /&gt;'; echo '&lt;input type="text" name="cf-subject" pattern="[a-zA-Z ]+" value="' . ( isset( $_POST["cf-subject"] ) ? esc_attr( $_POST["cf-subject"] ) : '' ) . '" size="40" /&gt;'; echo '&lt;/p&gt;'; echo '&lt;p&gt;'; echo 'Your Message (required) &lt;br /&gt;'; echo '&lt;textarea rows="10" cols="35" name="cf-message"&gt;' . ( isset( $_POST["cf-message"] ) ? esc_attr( $_POST["cf-message"] ) : '' ) . '&lt;/textarea&gt;'; echo '&lt;/p&gt;'; echo '&lt;p&gt;&lt;input type="submit" name="cf-submitted" value="Send"/&gt;&lt;/p&gt;'; echo '&lt;/form&gt;'; } function deliver_mail() { // if the submit button is clicked, send the email if ( isset( $_POST['cf-submitted'] ) ) { // sanitize form values $name = sanitize_text_field( $_POST["cf-name"] ); $email = sanitize_email( $_POST["cf-email"] ); $subject = sanitize_text_field( $_POST["cf-subject"] ); $message = esc_textarea( $_POST["cf-message"] ); // get the blog administrator's email address $to = get_option( 'admin_email' ); $headers = "From: $name &lt;$email&gt;" . "\r\n"; // If email has been process for sending, display a success message if ( wp_mail( $to, $subject, $message, $headers ) ) { echo '&lt;div&gt;'; echo '&lt;p&gt;Thanks for contacting me, expect a response soon.&lt;/p&gt;'; echo '&lt;/div&gt;'; } else { echo 'An unexpected error occurred'; } } } function cf_shortcode() { ob_start(); deliver_mail(); html_form_code(); return ob_get_clean(); } add_shortcode( 'contact_form', 'cf_shortcode' ); ?&gt; </code></pre> <p><a href="http://www.sitepoint.com/build-your-own-wordpress-contact-form-plugin-in-5-minutes/" rel="nofollow">This</a> is the tutorial I used to make it.</p> <p>When I put <code>[contact_form]</code> in a post or on a page, nothing appears...no contact form.</p> <p>Why won't the form appear?</p>
[ { "answer_id": 224174, "author": "eteubert", "author_id": 743, "author_profile": "https://wordpress.stackexchange.com/users/743", "pm_score": 2, "selected": true, "text": "<p>You need to explicitly set the Content Type, otherwise WordPress defaults to octet-stream for unknown feeds.</p>\n\n<pre><code>function run_podcast_rss(){\n header( 'Content-Type: application/rss+xml; charset=' . get_option( 'blog_charset' ), true );\n require_once( dirname( __FILE__ ) . '/feed-template.php' );\n}\n</code></pre>\n" }, { "answer_id": 354481, "author": "wsizoo", "author_id": 144094, "author_profile": "https://wordpress.stackexchange.com/users/144094", "pm_score": 0, "selected": false, "text": "<p>As @mrfolkblues pointed out you need to add a filter for the feed_content_type. The code below solved the file download issue for me.</p>\n\n<p>Code credit @swissspidy.\n<a href=\"https://core.trac.wordpress.org/ticket/36334#comment:7\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/36334#comment:7</a></p>\n\n<pre><code> &lt;?php\n// Example B:\n\nfunction trac_36334_add_superduperfeed() {\n add_feed( 'superduperfeed', 'trac_36334_superduperfeed_cb' );\n}\n\nadd_action( 'init', 'trac_36334_add_superduperfeed' );\n\nfunction trac_36334_superduperfeed_cb() {\n header( 'Content-Type: text/html' ); // or any other content type\n echo 'Do something...';\n}\n\nfunction trac_36334_superduperfeed_type( $content_type, $type ) {\n if ( 'superduperfeed' === $type ) {\n return feed_content_type( 'rss2' );\n }\n\n return $content_type;\n}\n\nadd_filter( 'feed_content_type', 'trac_36334_superduperfeed_type', 10, 2 );\n</code></pre>\n" } ]
2016/03/22
[ "https://wordpress.stackexchange.com/questions/221423", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/55063/" ]
I made my first WP plugin, it is a contact form - here is the code: ``` <?php /* Plugin Name: Example Contact Form Plugin Plugin URI: http://example.com Description: Simple non-bloated WordPress Contact Form Version: 1.0 Author: Agbonghama Collins Author URI: http://w3guy.com */ function html_form_code() { echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">'; echo '<p>'; echo 'Your Name (required) <br />'; echo '<input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="' . ( isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : '' ) . '" size="40" />'; echo '</p>'; echo '<p>'; echo 'Your Email (required) <br />'; echo '<input type="email" name="cf-email" value="' . ( isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : '' ) . '" size="40" />'; echo '</p>'; echo '<p>'; echo 'Subject (required) <br />'; echo '<input type="text" name="cf-subject" pattern="[a-zA-Z ]+" value="' . ( isset( $_POST["cf-subject"] ) ? esc_attr( $_POST["cf-subject"] ) : '' ) . '" size="40" />'; echo '</p>'; echo '<p>'; echo 'Your Message (required) <br />'; echo '<textarea rows="10" cols="35" name="cf-message">' . ( isset( $_POST["cf-message"] ) ? esc_attr( $_POST["cf-message"] ) : '' ) . '</textarea>'; echo '</p>'; echo '<p><input type="submit" name="cf-submitted" value="Send"/></p>'; echo '</form>'; } function deliver_mail() { // if the submit button is clicked, send the email if ( isset( $_POST['cf-submitted'] ) ) { // sanitize form values $name = sanitize_text_field( $_POST["cf-name"] ); $email = sanitize_email( $_POST["cf-email"] ); $subject = sanitize_text_field( $_POST["cf-subject"] ); $message = esc_textarea( $_POST["cf-message"] ); // get the blog administrator's email address $to = get_option( 'admin_email' ); $headers = "From: $name <$email>" . "\r\n"; // If email has been process for sending, display a success message if ( wp_mail( $to, $subject, $message, $headers ) ) { echo '<div>'; echo '<p>Thanks for contacting me, expect a response soon.</p>'; echo '</div>'; } else { echo 'An unexpected error occurred'; } } } function cf_shortcode() { ob_start(); deliver_mail(); html_form_code(); return ob_get_clean(); } add_shortcode( 'contact_form', 'cf_shortcode' ); ?> ``` [This](http://www.sitepoint.com/build-your-own-wordpress-contact-form-plugin-in-5-minutes/) is the tutorial I used to make it. When I put `[contact_form]` in a post or on a page, nothing appears...no contact form. Why won't the form appear?
You need to explicitly set the Content Type, otherwise WordPress defaults to octet-stream for unknown feeds. ``` function run_podcast_rss(){ header( 'Content-Type: application/rss+xml; charset=' . get_option( 'blog_charset' ), true ); require_once( dirname( __FILE__ ) . '/feed-template.php' ); } ```
221,433
<p>I've built a custom query for geolocation searches. I'm saving lat and lng within each custom post type as a meta value. My query extension returns results successfully when lat and lng are the only search variables.</p> <p>Problem: I would like to also add tax_queries to my query to further select posts</p> <p><strong>Class to extend query:</strong></p> <pre><code>class WP_Query_Geo extends WP_Query { function __construct( $args = array() ) { if(!empty($args['lat'])) { $this-&gt;lat = $args['lat']; $this-&gt;lng = $args['lng']; $this-&gt;distance = $args['distance']; $this-&gt;lat_meta_name = $args[ 'lat_meta_name' ]; $this-&gt;lng_meta_name = $args[ 'lng_meta_name' ]; $this-&gt;orderby = $args[ 'orderby' ]; $this-&gt;unit_of_measure = 3959; add_filter('posts_fields', array($this, 'posts_fields')); add_filter('posts_join', array($this, 'posts_join')); add_filter('posts_where', array($this, 'posts_where')); add_filter('posts_orderby', array($this, 'posts_orderby')); } parent::query($args); remove_filter('posts_fields', array($this, 'posts_fields')); remove_filter('posts_join', array($this, 'posts_join')); remove_filter('posts_where', array($this, 'posts_where')); remove_filter('posts_orderby', array($this, 'posts_orderby')); } function posts_fields($fields) { global $wpdb; $fields = $wpdb-&gt;prepare(" $wpdb-&gt;posts.*, pm1.meta_value, pm2.meta_value, ACOS(SIN(RADIANS(%f))*SIN(RADIANS(pm1.meta_value))+COS(RADIANS(%f))*COS(RADIANS(pm1.meta_value))*COS(RADIANS(pm2.meta_value)-RADIANS(%f))) * %d AS distance ", $this-&gt;lat, $this-&gt;lat, $this-&gt;lng, $this-&gt;unit_of_measure); return $fields; } function posts_join($join) { global $wpdb; $join .= " INNER JOIN $wpdb-&gt;postmeta pm1 ON ($wpdb-&gt;posts.id = pm1.post_id AND pm1.meta_key = '".$this-&gt;lat_meta_name."')"; $join .= " INNER JOIN $wpdb-&gt;postmeta pm2 ON ($wpdb-&gt;posts.id = pm2.post_id AND pm2.meta_key = '".$this-&gt;lng_meta_name."')"; return $join; } function posts_where($where) { global $wpdb; $where .= $wpdb-&gt;prepare(" HAVING distance &lt; %d ", $this-&gt;distance); return $where; } function posts_orderby($orderby) { if($this-&gt;orderby == 'distance') $orderby = " distance ASC, " . $orderby; return $orderby; } } </code></pre> <p>&nbsp;</p> <p><strong>Query:</strong></p> <pre><code>$args = array( 'post_type' =&gt; 'custom', 'posts_per_page' =&gt; 15, 'post_status' =&gt; 'publish', 'paged' =&gt; $page, 'orderby' =&gt; 'distance', 'lat' =&gt; $lat, 'lng' =&gt; $lng, 'distance' =&gt; $distance, ); $the_query = new WP_Query_Geo( $args ); </code></pre> <p>&nbsp;</p> <p>The above works. As soon as I add a tax query I receive an error.</p> <p><strong>Example tax query:</strong></p> <pre><code> $tax_query_args = array( 'relation' =&gt; 'AND' ); $tax_to_push = array( 'taxonomy' =&gt; 'custom-tax', 'field' =&gt; 'id', 'terms' =&gt; array(1,2,3), 'operator' =&gt; 'IN' ); array_push($tax_query_args, $tax_to_push); $args['tax_query'] = $tax_query_args; </code></pre> <p>&nbsp;</p> <p><strong>Error Message:</strong></p> <pre><code>WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY wp_posts.ID ORDER BY distance ASC, wp_posts.post_date DESC LIMIT 0, 15' at line 4 for query SELECT SQL_CALC_FOUND_ROWS wp_posts.*, pm1.meta_value, pm2.meta_value,\n ACOS(SIN(RADIANS(42.407211))*SIN(RADIANS(pm1.meta_value))+COS(RADIANS(42.407211))*COS(RADIANS(pm1.meta_value))*COS(RADIANS(pm2.meta_value)-RADIANS(-71.382437))) * 3959 AS distance FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta pm1 ON (wp_posts.id = pm1.post_id AND pm1.meta_key = 'office_lat') INNER JOIN wp_postmeta pm2 ON (wp_posts.id = pm2.post_id AND pm2.meta_key = 'office_lng') WHERE 1=1 AND ( \n wp_term_relationships.term_taxonomy_id IN (26)\n) AND wp_posts.post_type = 'clinicians' AND ((wp_posts.post_status = 'publish')) HAVING distance &lt; 50 GROUP BY wp_posts.ID ORDER BY distance ASC, wp_posts.post_date DESC LIMIT 0, 15 </code></pre>
[ { "answer_id": 224174, "author": "eteubert", "author_id": 743, "author_profile": "https://wordpress.stackexchange.com/users/743", "pm_score": 2, "selected": true, "text": "<p>You need to explicitly set the Content Type, otherwise WordPress defaults to octet-stream for unknown feeds.</p>\n\n<pre><code>function run_podcast_rss(){\n header( 'Content-Type: application/rss+xml; charset=' . get_option( 'blog_charset' ), true );\n require_once( dirname( __FILE__ ) . '/feed-template.php' );\n}\n</code></pre>\n" }, { "answer_id": 354481, "author": "wsizoo", "author_id": 144094, "author_profile": "https://wordpress.stackexchange.com/users/144094", "pm_score": 0, "selected": false, "text": "<p>As @mrfolkblues pointed out you need to add a filter for the feed_content_type. The code below solved the file download issue for me.</p>\n\n<p>Code credit @swissspidy.\n<a href=\"https://core.trac.wordpress.org/ticket/36334#comment:7\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/36334#comment:7</a></p>\n\n<pre><code> &lt;?php\n// Example B:\n\nfunction trac_36334_add_superduperfeed() {\n add_feed( 'superduperfeed', 'trac_36334_superduperfeed_cb' );\n}\n\nadd_action( 'init', 'trac_36334_add_superduperfeed' );\n\nfunction trac_36334_superduperfeed_cb() {\n header( 'Content-Type: text/html' ); // or any other content type\n echo 'Do something...';\n}\n\nfunction trac_36334_superduperfeed_type( $content_type, $type ) {\n if ( 'superduperfeed' === $type ) {\n return feed_content_type( 'rss2' );\n }\n\n return $content_type;\n}\n\nadd_filter( 'feed_content_type', 'trac_36334_superduperfeed_type', 10, 2 );\n</code></pre>\n" } ]
2016/03/22
[ "https://wordpress.stackexchange.com/questions/221433", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/50043/" ]
I've built a custom query for geolocation searches. I'm saving lat and lng within each custom post type as a meta value. My query extension returns results successfully when lat and lng are the only search variables. Problem: I would like to also add tax\_queries to my query to further select posts **Class to extend query:** ``` class WP_Query_Geo extends WP_Query { function __construct( $args = array() ) { if(!empty($args['lat'])) { $this->lat = $args['lat']; $this->lng = $args['lng']; $this->distance = $args['distance']; $this->lat_meta_name = $args[ 'lat_meta_name' ]; $this->lng_meta_name = $args[ 'lng_meta_name' ]; $this->orderby = $args[ 'orderby' ]; $this->unit_of_measure = 3959; add_filter('posts_fields', array($this, 'posts_fields')); add_filter('posts_join', array($this, 'posts_join')); add_filter('posts_where', array($this, 'posts_where')); add_filter('posts_orderby', array($this, 'posts_orderby')); } parent::query($args); remove_filter('posts_fields', array($this, 'posts_fields')); remove_filter('posts_join', array($this, 'posts_join')); remove_filter('posts_where', array($this, 'posts_where')); remove_filter('posts_orderby', array($this, 'posts_orderby')); } function posts_fields($fields) { global $wpdb; $fields = $wpdb->prepare(" $wpdb->posts.*, pm1.meta_value, pm2.meta_value, ACOS(SIN(RADIANS(%f))*SIN(RADIANS(pm1.meta_value))+COS(RADIANS(%f))*COS(RADIANS(pm1.meta_value))*COS(RADIANS(pm2.meta_value)-RADIANS(%f))) * %d AS distance ", $this->lat, $this->lat, $this->lng, $this->unit_of_measure); return $fields; } function posts_join($join) { global $wpdb; $join .= " INNER JOIN $wpdb->postmeta pm1 ON ($wpdb->posts.id = pm1.post_id AND pm1.meta_key = '".$this->lat_meta_name."')"; $join .= " INNER JOIN $wpdb->postmeta pm2 ON ($wpdb->posts.id = pm2.post_id AND pm2.meta_key = '".$this->lng_meta_name."')"; return $join; } function posts_where($where) { global $wpdb; $where .= $wpdb->prepare(" HAVING distance < %d ", $this->distance); return $where; } function posts_orderby($orderby) { if($this->orderby == 'distance') $orderby = " distance ASC, " . $orderby; return $orderby; } } ``` **Query:** ``` $args = array( 'post_type' => 'custom', 'posts_per_page' => 15, 'post_status' => 'publish', 'paged' => $page, 'orderby' => 'distance', 'lat' => $lat, 'lng' => $lng, 'distance' => $distance, ); $the_query = new WP_Query_Geo( $args ); ``` The above works. As soon as I add a tax query I receive an error. **Example tax query:** ``` $tax_query_args = array( 'relation' => 'AND' ); $tax_to_push = array( 'taxonomy' => 'custom-tax', 'field' => 'id', 'terms' => array(1,2,3), 'operator' => 'IN' ); array_push($tax_query_args, $tax_to_push); $args['tax_query'] = $tax_query_args; ``` **Error Message:** ``` WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY wp_posts.ID ORDER BY distance ASC, wp_posts.post_date DESC LIMIT 0, 15' at line 4 for query SELECT SQL_CALC_FOUND_ROWS wp_posts.*, pm1.meta_value, pm2.meta_value,\n ACOS(SIN(RADIANS(42.407211))*SIN(RADIANS(pm1.meta_value))+COS(RADIANS(42.407211))*COS(RADIANS(pm1.meta_value))*COS(RADIANS(pm2.meta_value)-RADIANS(-71.382437))) * 3959 AS distance FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta pm1 ON (wp_posts.id = pm1.post_id AND pm1.meta_key = 'office_lat') INNER JOIN wp_postmeta pm2 ON (wp_posts.id = pm2.post_id AND pm2.meta_key = 'office_lng') WHERE 1=1 AND ( \n wp_term_relationships.term_taxonomy_id IN (26)\n) AND wp_posts.post_type = 'clinicians' AND ((wp_posts.post_status = 'publish')) HAVING distance < 50 GROUP BY wp_posts.ID ORDER BY distance ASC, wp_posts.post_date DESC LIMIT 0, 15 ```
You need to explicitly set the Content Type, otherwise WordPress defaults to octet-stream for unknown feeds. ``` function run_podcast_rss(){ header( 'Content-Type: application/rss+xml; charset=' . get_option( 'blog_charset' ), true ); require_once( dirname( __FILE__ ) . '/feed-template.php' ); } ```
221,466
<p>I wish to change/remove parts of the automatic post class function that's built in to wordpress, lets say when i make a post, the html code generated looks like this:</p> <pre><code>&lt;div id="post-106" class="contentmain fullwidth post-106 post type-post status-publish format-standard has-post-thumbnail hentry category-test category-test2 category-test3 category-test4 tag-testingtags1 tag-testingtags2 tag-testingtags3"&gt; </code></pre> <p>I wish to remove tags from being in this auto generated code (the tag-testingtags1,2,3), i cannot find which function in wordpress generates the code, anyone care to point me in the right direction? If it is a core file is there a simple way to exclude tags from being inserted into the code using some kind of filter hook in functions.php so i don't have to modify wp core files?</p>
[ { "answer_id": 224174, "author": "eteubert", "author_id": 743, "author_profile": "https://wordpress.stackexchange.com/users/743", "pm_score": 2, "selected": true, "text": "<p>You need to explicitly set the Content Type, otherwise WordPress defaults to octet-stream for unknown feeds.</p>\n\n<pre><code>function run_podcast_rss(){\n header( 'Content-Type: application/rss+xml; charset=' . get_option( 'blog_charset' ), true );\n require_once( dirname( __FILE__ ) . '/feed-template.php' );\n}\n</code></pre>\n" }, { "answer_id": 354481, "author": "wsizoo", "author_id": 144094, "author_profile": "https://wordpress.stackexchange.com/users/144094", "pm_score": 0, "selected": false, "text": "<p>As @mrfolkblues pointed out you need to add a filter for the feed_content_type. The code below solved the file download issue for me.</p>\n\n<p>Code credit @swissspidy.\n<a href=\"https://core.trac.wordpress.org/ticket/36334#comment:7\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/ticket/36334#comment:7</a></p>\n\n<pre><code> &lt;?php\n// Example B:\n\nfunction trac_36334_add_superduperfeed() {\n add_feed( 'superduperfeed', 'trac_36334_superduperfeed_cb' );\n}\n\nadd_action( 'init', 'trac_36334_add_superduperfeed' );\n\nfunction trac_36334_superduperfeed_cb() {\n header( 'Content-Type: text/html' ); // or any other content type\n echo 'Do something...';\n}\n\nfunction trac_36334_superduperfeed_type( $content_type, $type ) {\n if ( 'superduperfeed' === $type ) {\n return feed_content_type( 'rss2' );\n }\n\n return $content_type;\n}\n\nadd_filter( 'feed_content_type', 'trac_36334_superduperfeed_type', 10, 2 );\n</code></pre>\n" } ]
2016/03/23
[ "https://wordpress.stackexchange.com/questions/221466", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86334/" ]
I wish to change/remove parts of the automatic post class function that's built in to wordpress, lets say when i make a post, the html code generated looks like this: ``` <div id="post-106" class="contentmain fullwidth post-106 post type-post status-publish format-standard has-post-thumbnail hentry category-test category-test2 category-test3 category-test4 tag-testingtags1 tag-testingtags2 tag-testingtags3"> ``` I wish to remove tags from being in this auto generated code (the tag-testingtags1,2,3), i cannot find which function in wordpress generates the code, anyone care to point me in the right direction? If it is a core file is there a simple way to exclude tags from being inserted into the code using some kind of filter hook in functions.php so i don't have to modify wp core files?
You need to explicitly set the Content Type, otherwise WordPress defaults to octet-stream for unknown feeds. ``` function run_podcast_rss(){ header( 'Content-Type: application/rss+xml; charset=' . get_option( 'blog_charset' ), true ); require_once( dirname( __FILE__ ) . '/feed-template.php' ); } ```
221,481
<p>So inside this theme I'm making for a client there is a section inside the customizer that allows them to change a header on each individual page, my question is how do I fetch the alt tag of that Image?</p> <p>The Images are uploaded through the Media Library so the alt text has been set after the Image was uploaded.</p> <p>Below is what I have tried to fetch the Image alt tag</p> <pre><code>$img_id = get_post_thumbnail_id(get_the_ID()); $alt_text = get_post_meta($img_id , '_wp_attachment_image_alt', true); &lt;img src="&lt;?php echo get_theme_mod('about-header', get_stylesheet_directory_uri() . '/assests/imgs/placeholder.png'); ?&gt;" alt="&lt;?php echo $alt_text; ?&gt;"&gt; </code></pre> <p>For some reason it just doesn't seem to get the Images alt tag and I don't understand why</p> <p>Code for the Customizer (just in case I have to do something inside there)</p> <pre><code>$wp_customize-&gt;add_section('page_header', array( 'title' =&gt; __('Page Headers', 'bissell-theme'), 'priority' =&gt; 30, 'description' =&gt; __('Below are the options to change your header images for all your pages. Just simply click \'Select Image\' and choose a Image from the Media Libary or Upload one your self'), )); $wp_customize-&gt;add_setting('about-header'); $wp_customize-&gt;add_control(new WP_Customize_Image_Control($wp_customize, 'about_header_control', array( 'label' =&gt; __('About Us - Header'), 'section' =&gt; 'page_header', 'settings' =&gt; 'about-header', ))); </code></pre>
[ { "answer_id": 221517, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>I believe the problem may be with not providing arguments to the customizer <code>add_setting</code> call, especially since the type needs to be set to theme_mod...</p>\n\n<pre><code>$wp_customize-&gt;add_setting('about-header',array(\n 'type' =&gt; 'theme_mod', 'capability' =&gt; 'edit_theme_options', 'default' =&gt; '', 'transport' =&gt; 'refresh'\n) );\n</code></pre>\n" }, { "answer_id": 265245, "author": "DevTurtle", "author_id": 104438, "author_profile": "https://wordpress.stackexchange.com/users/104438", "pm_score": 1, "selected": false, "text": "<p>Ok I found the answer that no one has on the net I been looking for days now.</p>\n\n<p>Here is how I was able to do it. Hope this helps someone out there</p>\n\n<pre><code>// This is getting the image / url\n$feature1 = get_theme_mod('feature_image_1');\n\n// This is getting the post id\n$feature1_id = attachment_url_to_postid($feature1);\n\n// This is getting the alt text from the image that is set in the media area\n$image1_alt = get_post_meta( $feature1_id, '_wp_attachment_image_alt', true );\n</code></pre>\n\n<p>Markup</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo $feature1_url; ?&gt;\"&gt;&lt;img class=\"img-responsive center-block\" src=\"&lt;?php echo $feature1; ?&gt;\" alt=\"&lt;?php echo $image1_alt; ?&gt;\"&gt;&lt;/a&gt;\n</code></pre>\n" } ]
2016/03/23
[ "https://wordpress.stackexchange.com/questions/221481", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85776/" ]
So inside this theme I'm making for a client there is a section inside the customizer that allows them to change a header on each individual page, my question is how do I fetch the alt tag of that Image? The Images are uploaded through the Media Library so the alt text has been set after the Image was uploaded. Below is what I have tried to fetch the Image alt tag ``` $img_id = get_post_thumbnail_id(get_the_ID()); $alt_text = get_post_meta($img_id , '_wp_attachment_image_alt', true); <img src="<?php echo get_theme_mod('about-header', get_stylesheet_directory_uri() . '/assests/imgs/placeholder.png'); ?>" alt="<?php echo $alt_text; ?>"> ``` For some reason it just doesn't seem to get the Images alt tag and I don't understand why Code for the Customizer (just in case I have to do something inside there) ``` $wp_customize->add_section('page_header', array( 'title' => __('Page Headers', 'bissell-theme'), 'priority' => 30, 'description' => __('Below are the options to change your header images for all your pages. Just simply click \'Select Image\' and choose a Image from the Media Libary or Upload one your self'), )); $wp_customize->add_setting('about-header'); $wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'about_header_control', array( 'label' => __('About Us - Header'), 'section' => 'page_header', 'settings' => 'about-header', ))); ```
Ok I found the answer that no one has on the net I been looking for days now. Here is how I was able to do it. Hope this helps someone out there ``` // This is getting the image / url $feature1 = get_theme_mod('feature_image_1'); // This is getting the post id $feature1_id = attachment_url_to_postid($feature1); // This is getting the alt text from the image that is set in the media area $image1_alt = get_post_meta( $feature1_id, '_wp_attachment_image_alt', true ); ``` Markup ``` <a href="<?php echo $feature1_url; ?>"><img class="img-responsive center-block" src="<?php echo $feature1; ?>" alt="<?php echo $image1_alt; ?>"></a> ```
221,485
<p>In some cases it might be useful to use multiple post &amp; page parameters in your <code>WP_Query</code> object. In my case, I would like to display children of a parent page including the parent page itself.</p> <p>Visualization of what I want to achieve. Imagine the following pages hierarchically sorted as following:</p> <ul> <li>page A</li> <li><strong>page B</strong> <ul> <li><strong>Child page A</strong></li> <li><strong>Child page B</strong></li> <li><strong>Child page C</strong></li> </ul></li> <li>page C</li> </ul> <p>The <strong>bold list items</strong> are the posts/pages I want to retrieve.</p> <p>My first thoughts go out using these two parameters for <code>WP_Query</code>:</p> <pre><code>$args = array( 'post_id' =&gt; $parent-&gt;ID, 'post_parent' =&gt; $parent-&gt;ID, ); </code></pre> <p>Unfortunately, here it will only use one parameter. With the <code>$args</code> above (correct me if I'm wrong) it will output all children posts of the parent post and <strong>not</strong> the parent post itself as well.</p> <p>This problem might be solved by gathering all posts needed and putting them in parameter <code>post__in</code> like so:</p> <pre><code>$args = array( 'post__in' =&gt; $children_and_parent_ids, ); </code></pre> <p>However there is <a href="https://developer.wordpress.org/reference/functions/wp_list_pages/" rel="noreferrer"><code>wp_list_pages()</code></a> allowing you to <code>include</code> a post(s) and specify the post where you want to include the children of (<code>child_of</code>). Why is this not possible with <code>WP_Query</code>?</p> <p>An example of what I'm trying to achieve using <code>wp_list_pages()</code>:</p> <pre><code>wp_list_pages(array( 'include' =&gt; $parent-&gt;ID, 'child_of' =&gt; $parent-&gt;ID, )); </code></pre> <p>Have a look at <a href="https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters" rel="noreferrer">the documentation</a> of <code>WP_Query</code>.</p>
[ { "answer_id": 221490, "author": "Lalji Nakum", "author_id": 91099, "author_profile": "https://wordpress.stackexchange.com/users/91099", "pm_score": -1, "selected": false, "text": "<p>You can use <code>get_pages()</code> with <code>child_of</code> parameter like below : </p>\n\n<pre><code>&lt;?php\n get_pages( array(\n 'child_of' =&gt; $parent_page_id;\n ) );\n?&gt;\n</code></pre>\n" }, { "answer_id": 221496, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 3, "selected": false, "text": "<p>If all you want is results from the &quot;page&quot; post_type then do as @birgire suggested.</p>\n<p>Alternatively you can adapt the following to give you a similar result for not only the <code>page</code> <code>post_type</code> but any custom post type.</p>\n<pre><code>$parent = 2; //change as desired\n$type = 'page'; //change as desired\n\n$child_args = array( \n 'post_type' =&gt; $type, \n 'post_parent' =&gt; $parent \n);\n\n$ids = array( $parent );\n$ids = array_merge( $ids, array_keys( get_children( $child_args ) ));\n\n$query = new WP_Query( \n array( \n 'post_type' =&gt; 'page', \n 'post_status' =&gt; 'publish', \n 'post__in' =&gt; $ids, \n 'posts_per_page' =&gt; -1 \n ) \n);\n</code></pre>\n<p>The above is essentially the same thing as hooking onto the <code>posts_where</code> filter and parsing the SQL clause however, this achieves exactly the same thing.</p>\n" }, { "answer_id": 221502, "author": "luukvhoudt", "author_id": 44637, "author_profile": "https://wordpress.stackexchange.com/users/44637", "pm_score": 0, "selected": false, "text": "<p>Using <code>global $wpdb</code> combined with <code>[get_results()][1]</code> is an option as well. Performance wise I think this is the best solution since it only runs one query.</p>\n\n<p>Here is my final code.</p>\n\n<pre><code>&lt;ul class=\"tabs\"&gt;&lt;?php\n\n global $wpdb, $post;\n\n $parent = count(get_post_ancestors($post-&gt;ID))-1 &gt; 0 ? $post-&gt;post_parent : $post-&gt;ID;\n\n $sql = \"SELECT ID FROM `{$wpdb-&gt;prefix}posts`\";\n $sql.= \" WHERE ID='{$parent}' OR post_parent='{$parent}' AND post_type='page'\";\n $sql.= \" ORDER BY `menu_order` ASC\";\n\n $tabs = $wpdb-&gt;get_results($sql);\n\n $output = '';\n foreach ($tabs as $tab) {\n $current = $post-&gt;ID == $tab-&gt;ID ? ' class=\"active\"' : '';\n\n $output .= '&lt;li'.$current.'&gt;';\n $output .= empty($current) ? '&lt;a href=\"'.get_permalink($tab-&gt;ID).'\"&gt;' : '';\n $output .= get_the_post_thumbnail($tab-&gt;ID, 'menu-24x24');\n $output .= '&lt;span&gt;'.get_the_title($tab-&gt;ID).'&lt;/span&gt;';\n $output .= empty($current) ? '&lt;/a&gt;' : '';\n $output .= '&lt;/li&gt;';\n }\n print $output;\n\n?&gt;&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 221531, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>We can filter the <code>posts_where</code> clause of the generated SQL to also return the parent post/page and not just the parent's children. Here we will set our own custom argument called <code>wpse_include_parent</code>, which, when set to <code>true</code>, will alter the generated SQL accordingly.</p>\n\n<p>All we need to do inside our <code>posts_where</code> filter is to check if our custom argument is set and that the <code>post_parent</code> argument is set. We then get that value and pass it to the filter to extend our SQL query. What is nice here, <code>post_parent</code> excepts a single integer value, so we only need to validate the value as an integer. </p>\n\n<h2>THE QUERY</h2>\n\n<pre><code>$args = [\n 'wpse_include_parent' =&gt; true,\n 'post_parent' =&gt; 256,\n 'post_type' =&gt; 'page'\n // Add additional arguments\n];\n$q = new WP_Query( $args );\n</code></pre>\n\n<p>As you can see, we have set <code>'wpse_include_parent' =&gt; true</code> to \"activate\" our filter.</p>\n\n<h2>THE FILTER</h2>\n\n<pre><code>add_filter( 'posts_where', function ( $where, \\WP_Query $q ) use ( &amp;$wpdb )\n{\n if ( true !== $q-&gt;get( 'wpse_include_parent' ) )\n return $where;\n\n /**\n * Get the value passed to from the post parent and validate it\n * post_parent only accepts an integer value, so we only need to validate\n * the value as an integer\n */\n $post_parent = filter_var( $q-&gt;get( 'post_parent' ), FILTER_VALIDATE_INT );\n if ( !$post_parent )\n return $where;\n\n /** \n * Lets also include the parent in our query\n *\n * Because we have already validated the $post_parent value, we \n * do not need to use the prepare() method here\n */\n $where .= \" OR $wpdb-&gt;posts.ID = $post_parent\";\n\n return $where;\n}, 10, 2 );\n</code></pre>\n\n<p>You can extent this as you need and see fit, but this is the basic idea. This will return the parent passed to <code>post_parent</code> and it's children</p>\n" }, { "answer_id": 221534, "author": "EBennett", "author_id": 91050, "author_profile": "https://wordpress.stackexchange.com/users/91050", "pm_score": 0, "selected": false, "text": "<p>If I understand you correctly you want to get the ID's of both the parent and any subsequent children pages. Wordpress has functions that fetch the children of pages, such as this one: </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_page_children\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_page_children</a></p>\n\n<p>It is my understanding, that since you are performing a WP_Query, you are already fetching the ID's of the parent pages, so all you would need to do is pass in the relevant ID to the the above function to get what you desire.</p>\n\n<p>Note: I should point out that this function doesn't do a DB query, so better performance wise as you are only making on query to the DB.</p>\n" }, { "answer_id": 283646, "author": "egauvin", "author_id": 129683, "author_profile": "https://wordpress.stackexchange.com/users/129683", "pm_score": 1, "selected": false, "text": "<pre><code> $args = array(\n 'post_type' =&gt; 'tribe_events',\n 'posts_per_page' =&gt; '-1',\n 'orderby' =&gt; 'ID',\n 'order' =&gt; 'ASC',\n 'post_parent' =&gt; $postID,\n );\n\n $children = new WP_Query($args);\n $parent[] = get_post($postID);\n $family = array_merge($parent, $children-&gt;get_posts());\n</code></pre>\n\n<p>This seems to work. Comments?</p>\n" } ]
2016/03/23
[ "https://wordpress.stackexchange.com/questions/221485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44637/" ]
In some cases it might be useful to use multiple post & page parameters in your `WP_Query` object. In my case, I would like to display children of a parent page including the parent page itself. Visualization of what I want to achieve. Imagine the following pages hierarchically sorted as following: * page A * **page B** + **Child page A** + **Child page B** + **Child page C** * page C The **bold list items** are the posts/pages I want to retrieve. My first thoughts go out using these two parameters for `WP_Query`: ``` $args = array( 'post_id' => $parent->ID, 'post_parent' => $parent->ID, ); ``` Unfortunately, here it will only use one parameter. With the `$args` above (correct me if I'm wrong) it will output all children posts of the parent post and **not** the parent post itself as well. This problem might be solved by gathering all posts needed and putting them in parameter `post__in` like so: ``` $args = array( 'post__in' => $children_and_parent_ids, ); ``` However there is [`wp_list_pages()`](https://developer.wordpress.org/reference/functions/wp_list_pages/) allowing you to `include` a post(s) and specify the post where you want to include the children of (`child_of`). Why is this not possible with `WP_Query`? An example of what I'm trying to achieve using `wp_list_pages()`: ``` wp_list_pages(array( 'include' => $parent->ID, 'child_of' => $parent->ID, )); ``` Have a look at [the documentation](https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters) of `WP_Query`.
We can filter the `posts_where` clause of the generated SQL to also return the parent post/page and not just the parent's children. Here we will set our own custom argument called `wpse_include_parent`, which, when set to `true`, will alter the generated SQL accordingly. All we need to do inside our `posts_where` filter is to check if our custom argument is set and that the `post_parent` argument is set. We then get that value and pass it to the filter to extend our SQL query. What is nice here, `post_parent` excepts a single integer value, so we only need to validate the value as an integer. THE QUERY --------- ``` $args = [ 'wpse_include_parent' => true, 'post_parent' => 256, 'post_type' => 'page' // Add additional arguments ]; $q = new WP_Query( $args ); ``` As you can see, we have set `'wpse_include_parent' => true` to "activate" our filter. THE FILTER ---------- ``` add_filter( 'posts_where', function ( $where, \WP_Query $q ) use ( &$wpdb ) { if ( true !== $q->get( 'wpse_include_parent' ) ) return $where; /** * Get the value passed to from the post parent and validate it * post_parent only accepts an integer value, so we only need to validate * the value as an integer */ $post_parent = filter_var( $q->get( 'post_parent' ), FILTER_VALIDATE_INT ); if ( !$post_parent ) return $where; /** * Lets also include the parent in our query * * Because we have already validated the $post_parent value, we * do not need to use the prepare() method here */ $where .= " OR $wpdb->posts.ID = $post_parent"; return $where; }, 10, 2 ); ``` You can extent this as you need and see fit, but this is the basic idea. This will return the parent passed to `post_parent` and it's children
221,522
<p>I am facing some UI issues with my wordpress website. The newly added "Author" role is not able to see the formatting toolbar while writing the post. After debugging, I found a javascript error which I suppose is due to the update of version 4.4.2.</p> <p>The error (below snip) is this:</p> <pre><code>Refused to execute script from 'http://www.faksite.com/wp-admin/admin-ajax.php?action=themeSome_shortcode_editor_plugin&amp;wp-mce-4208-20151113' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. </code></pre> <p>Cant figure out what is the issue.</p> <p><a href="https://i.stack.imgur.com/Tgtyp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tgtyp.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 221877, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>The error is most likely correct (and is most likely related to browser upgrade than any WP version change) and your theme/plugin does fishy things. The ajax enedpoint should be uses to return data - html/json/xml. </p>\n\n<p>Wordpress will use the text/html mime type for all responses from the ajax endpoint without any simple way I can see to override it.</p>\n\n<p>In addition to your existing problem, the ajax endpoint is blocked to search engines so you might be hurting your SEO if this code is used on the front end.</p>\n\n<p>If it is not a theme you develop yourself, you should contact the theme/plugin author to fix the issue.</p>\n" }, { "answer_id": 252810, "author": "T.Todua", "author_id": 33667, "author_profile": "https://wordpress.stackexchange.com/users/33667", "pm_score": 0, "selected": false, "text": "<h1>Be aware of malicious script!</h1>\n\n<p>1) Can you tell us, which site is that exactly?</p>\n\n<p>There is a big chance, that you have a fishy theme or plugin installed, which tries to send some data to 3rd party site, and it may inject malicious scripts on your site... </p>\n\n<p>2) Even if you trust your plugins/theme, check, which one fires that line is not needed at all. Find out and disable the plugin that does that.</p>\n\n<p>3) <strong>IN CASE YOU TRUST WHAT HAPPENS WITH YOU</strong>, then you should go to that <code>faksite.com</code> and in output of <code>ajax</code> call, insert special <code>header(content-type: text/javascript)</code> before output.</p>\n" } ]
2016/03/23
[ "https://wordpress.stackexchange.com/questions/221522", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56575/" ]
I am facing some UI issues with my wordpress website. The newly added "Author" role is not able to see the formatting toolbar while writing the post. After debugging, I found a javascript error which I suppose is due to the update of version 4.4.2. The error (below snip) is this: ``` Refused to execute script from 'http://www.faksite.com/wp-admin/admin-ajax.php?action=themeSome_shortcode_editor_plugin&wp-mce-4208-20151113' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. ``` Cant figure out what is the issue. [![enter image description here](https://i.stack.imgur.com/Tgtyp.jpg)](https://i.stack.imgur.com/Tgtyp.jpg)
The error is most likely correct (and is most likely related to browser upgrade than any WP version change) and your theme/plugin does fishy things. The ajax enedpoint should be uses to return data - html/json/xml. Wordpress will use the text/html mime type for all responses from the ajax endpoint without any simple way I can see to override it. In addition to your existing problem, the ajax endpoint is blocked to search engines so you might be hurting your SEO if this code is used on the front end. If it is not a theme you develop yourself, you should contact the theme/plugin author to fix the issue.
221,552
<p>I'm fairly new to WP development, however as far as I can see I've followed the correct procedure in my custom archive page (below). If I remove the check for <code>is_main_query()</code> it wipes the menus out and likely a lot of other data is lost due to the filter being applied. </p> <p>Adding debug code shows that <code>is_main_query()</code> is never returned as true? What am I doing wrong?</p> <p>My build is WP 4.4 with the "Avada" theme and I'm also making use of the <em>ACF Advanced Custom Fields</em> to add custom meta data to my posts.</p> <p>Any help is really appreciated, thanks!</p> <pre><code>&lt;?php $has_searchform = true; get_header(); ?&gt; &lt;div id="content" &lt;?php Avada()-&gt;layout-&gt;add_class( 'content_class' ); ?&gt; &lt;?php Avada()-&gt;layout-&gt;add_style( 'content_style' ); ?&gt;&gt; &lt;?php function my_pre_get_posts( $query ) { //* if within admin, return if ( is_admin() ) { echo "Admin returning"; return; } //* if not main query, return else if ( ! $query-&gt;is_main_query() ) { echo "Not main query"; return; } else if ( $query-&gt;is_main_query() ) { echo "Main query called"; if( (isset($_GET['fs_date_from']) &amp;&amp; $_GET['fs_date_from'] != '') || (isset($_GET['fs_date_to']) &amp;&amp; $_GET['fs_date_to'] != '') || (isset($_GET['fs_music_genre']) &amp;&amp; $_GET['fs_music_genre'] != '') || (isset($_GET['fs_keyword']) &amp;&amp; $_GET['fs_keyword'] != '') || (isset($_GET['fs_country']) &amp;&amp; $_GET['fs_country'] != '') || (isset($_GET['fs_festival_category']) &amp;&amp; $_GET['fs_festival_category'] != '')) { if(isset($_GET['fs_date_from']) &amp;&amp; $_GET['fs_date_from'] != '') { $date_from = date('Ymd',strtotime(sanitize_text_field($_GET['fs_date_from']))); $search_array['fs_date_from'] = array( 'key' =&gt; 'start_date', 'value' =&gt; $date_from, 'compare' =&gt; '&gt;=' ); } if(isset($_GET['fs_date_to']) &amp;&amp; $_GET['fs_date_to'] != '') { $date_to = date('Ymd',strtotime(sanitize_text_field($_GET['fs_date_to']))); $search_array['fs_date_to'] = array('key' =&gt; 'end_date', 'value' =&gt; $date_to, 'compare' =&gt; '&lt;='); } $keyword = sanitize_text_field($_GET['fs_keyword']); if($keyword != '') { $query-&gt;set('s',$keyword); } if(isset($_GET['fs_country']) &amp;&amp; $_GET['fs_country'] != '') { $country = sanitize_text_field($_GET['fs_country']); $search_array['fs_country'] = array('key' =&gt; 'fs_country', 'value' =&gt; $country, 'compare' =&gt; '='); } $music_genre = sanitize_text_field($_GET['fs_music_genre']); if($music_genre != '') { $tax_query['music_genre'] = array( 'taxonomy' =&gt; 'music_genre', 'field' =&gt; 'id', 'terms' =&gt; array($music_genre), 'operator' =&gt; 'IN'); } $festival_category = sanitize_text_field($_GET['fs_festival_category']); if($festival_category != '') { $tax_query['fs_festival_category'] = array( 'taxonomy' =&gt; 'festival_category', 'field' =&gt; 'id', 'terms' =&gt; array($festival_category), 'operator' =&gt; 'IN'); } print_r($search_array); $search_array['relation'] = (($date_from != '' &amp;&amp; $date_to != '')? "AND" : ""); $query-&gt;set('posts_per_page', 10); $query-&gt;set('post_type' , 'festival'); $query-&gt;set('meta_query' , $search_array); $query-&gt;set('tax_query' , $tax_query); } else { echo "Woop"; $query-&gt;set('posts_per_page', 10); $query-&gt;set('post_type' , 'festival'); } } } add_action('pre_get_posts', 'my_pre_get_posts'); if( have_posts() ) { echo "&lt;div class='row fusion-row'&gt; &lt;div class='col-sm-12'&gt; "; fusion_pagination($pages = '', $range = 2); echo " &lt;/div&gt; &lt;/div&gt;"; while(have_posts()) { the_post(); //setup_postdata( $post ); $image = get_field('header_image'); $image_url = $image['sizes']['medium_large']; $date_format = 'dS \o\f F Y'; /*if(get_field('start_date') != '') { $start_date = DateTime::createFromFormat('Ymd', get_field('start_date')); } else { $start_date = ''; } if(get_field('end_date') != '') { $end_date = DateTime::createFromFormat('Ymd', get_field('end_date')); } else { $end_date = ''; }*/ $start_date = get_field('start_date'); $end_date = get_field('end_date'); $vibe = substr(get_field('vibe'), 0,250)."..."; $location = get_field('location'); $country = get_field('country'); //print_r($post); $price = get_min_price(get_the_ID()); echo "&lt;div class='row fusion-row result_row' onclick=\"javascript:window.location.href='". get_permalink() ."'; return false;\"&gt; &lt;div class='col-sm-5 result_thumbnail' style='background: url(\"". $image_url ."\") center center no-repeat;'&gt; &lt;/div&gt; &lt;div class='col-sm-7'&gt; &lt;h3 class='result_title'&gt;&lt;a href='". get_permalink() ."'&gt;".get_the_title()."&lt;/a&gt;&lt;/h3&gt; &lt;h4 class='result_location'&gt;$location" . (($location != '' &amp;&amp; $country != '')? "," : "") . " $country&lt;/h4&gt; &lt;div class='result_vibe'&gt; ". $vibe ." &lt;/div&gt; &lt;/div&gt; &lt;div class='result_bottom_row col-sm-7'&gt; &lt;div class='result_dates'&gt; "; if($start_date != '') { echo $start_date; } echo ((get_field('start_date') != '' &amp;&amp; get_field('end_date') != '')? " - " : ""); if($end_date != '') { echo $end_date; } echo " &lt;/div&gt; &lt;div class='result_price'&gt; $price &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; "; } fusion_pagination($pages = '', $range = 2); } else { echo "&lt;p&gt;Sorry, no Festivals match your search.&lt;/p&gt;"; } ?&gt; &lt;/div&gt; &lt;?php do_action( 'fusion_after_content' ); ?&gt; &lt;?php get_footer(); // Omit closing PHP tag to avoid "Headers already sent" issues. </code></pre>
[ { "answer_id": 221556, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 1, "selected": false, "text": "<p>The action hook <code>pre_get_posts</code> is called well before the page template is rendered. Move <code>add_action('pre_get_posts', 'my_pre_get_posts');</code> and your <code>my_pre_get_posts()</code> function to your theme's <code>functions.php</code> file.</p>\n" }, { "answer_id": 221589, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 0, "selected": false, "text": "<p>A few notes on your code here:</p>\n\n<ul>\n<li><p>Never add business logic in templates. Templates should never be used to compute any kind of logic, templates should only display the results from that logic. In short, templates should know function names, that's it. The function itself should be defined in a plugin or in your theme's functions files</p></li>\n<li><p>By the time the template is set (<em>via <code>template_include</code></em>), the main query has already executed and just a distant memory. By now, the main query cannot be altered. That is why your action has no affect on the main query. As I stated, functions, including filters and actions should be in a plugin or functions file</p></li>\n<li><p>Instead of doing <code>isset($_GET['fs_date_from']) &amp;&amp; $_GET['fs_date_from'] != '')</code> every time you need it, you can simply do the following with <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow\"><code>filter_input</code></a>, which will take care of checking if the var is set and will return the value if it is. You can additionally set a filter which will take care of sanitation for you</p>\n\n<pre><code>$fs_date_from = filter_input( \n INPUT_GET, // $_GET Global , for $_POST it will be INPUT_POST\n 'fs_date_from', // Name of the variable\n FILTER_SANITIZE_STRING // Type of filter to use to validate/sanitize\n);\n</code></pre>\n\n<p>You can now just check if <code>$fs_date_from</code> has a value</p>\n\n<pre><code>if ( $fs_date_from ) {\n // Do something\n}\n</code></pre>\n\n<p>You can also look into <a href=\"http://php.net/manual/en/function.filter-input-array.php\" rel=\"nofollow\"><code>filter_input_array</code></a> to handle multiple <code>$_GET</code> variable values</p></li>\n</ul>\n" }, { "answer_id": 221612, "author": "Paul Cullen", "author_id": 91132, "author_profile": "https://wordpress.stackexchange.com/users/91132", "pm_score": 1, "selected": true, "text": "<p>Thanks for all your help.</p>\n\n<p>The key issues where that i needed to post the code in the functions.php file and needed to amend the if statement to read:</p>\n\n<pre><code>$query-&gt;is_main_query() &amp;&amp; is_post_type_archive( 'festival' )\n</code></pre>\n\n<p>So that it would only effect my custom post type.</p>\n\n<p>Thanks!</p>\n" } ]
2016/03/23
[ "https://wordpress.stackexchange.com/questions/221552", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91132/" ]
I'm fairly new to WP development, however as far as I can see I've followed the correct procedure in my custom archive page (below). If I remove the check for `is_main_query()` it wipes the menus out and likely a lot of other data is lost due to the filter being applied. Adding debug code shows that `is_main_query()` is never returned as true? What am I doing wrong? My build is WP 4.4 with the "Avada" theme and I'm also making use of the *ACF Advanced Custom Fields* to add custom meta data to my posts. Any help is really appreciated, thanks! ``` <?php $has_searchform = true; get_header(); ?> <div id="content" <?php Avada()->layout->add_class( 'content_class' ); ?> <?php Avada()->layout->add_style( 'content_style' ); ?>> <?php function my_pre_get_posts( $query ) { //* if within admin, return if ( is_admin() ) { echo "Admin returning"; return; } //* if not main query, return else if ( ! $query->is_main_query() ) { echo "Not main query"; return; } else if ( $query->is_main_query() ) { echo "Main query called"; if( (isset($_GET['fs_date_from']) && $_GET['fs_date_from'] != '') || (isset($_GET['fs_date_to']) && $_GET['fs_date_to'] != '') || (isset($_GET['fs_music_genre']) && $_GET['fs_music_genre'] != '') || (isset($_GET['fs_keyword']) && $_GET['fs_keyword'] != '') || (isset($_GET['fs_country']) && $_GET['fs_country'] != '') || (isset($_GET['fs_festival_category']) && $_GET['fs_festival_category'] != '')) { if(isset($_GET['fs_date_from']) && $_GET['fs_date_from'] != '') { $date_from = date('Ymd',strtotime(sanitize_text_field($_GET['fs_date_from']))); $search_array['fs_date_from'] = array( 'key' => 'start_date', 'value' => $date_from, 'compare' => '>=' ); } if(isset($_GET['fs_date_to']) && $_GET['fs_date_to'] != '') { $date_to = date('Ymd',strtotime(sanitize_text_field($_GET['fs_date_to']))); $search_array['fs_date_to'] = array('key' => 'end_date', 'value' => $date_to, 'compare' => '<='); } $keyword = sanitize_text_field($_GET['fs_keyword']); if($keyword != '') { $query->set('s',$keyword); } if(isset($_GET['fs_country']) && $_GET['fs_country'] != '') { $country = sanitize_text_field($_GET['fs_country']); $search_array['fs_country'] = array('key' => 'fs_country', 'value' => $country, 'compare' => '='); } $music_genre = sanitize_text_field($_GET['fs_music_genre']); if($music_genre != '') { $tax_query['music_genre'] = array( 'taxonomy' => 'music_genre', 'field' => 'id', 'terms' => array($music_genre), 'operator' => 'IN'); } $festival_category = sanitize_text_field($_GET['fs_festival_category']); if($festival_category != '') { $tax_query['fs_festival_category'] = array( 'taxonomy' => 'festival_category', 'field' => 'id', 'terms' => array($festival_category), 'operator' => 'IN'); } print_r($search_array); $search_array['relation'] = (($date_from != '' && $date_to != '')? "AND" : ""); $query->set('posts_per_page', 10); $query->set('post_type' , 'festival'); $query->set('meta_query' , $search_array); $query->set('tax_query' , $tax_query); } else { echo "Woop"; $query->set('posts_per_page', 10); $query->set('post_type' , 'festival'); } } } add_action('pre_get_posts', 'my_pre_get_posts'); if( have_posts() ) { echo "<div class='row fusion-row'> <div class='col-sm-12'> "; fusion_pagination($pages = '', $range = 2); echo " </div> </div>"; while(have_posts()) { the_post(); //setup_postdata( $post ); $image = get_field('header_image'); $image_url = $image['sizes']['medium_large']; $date_format = 'dS \o\f F Y'; /*if(get_field('start_date') != '') { $start_date = DateTime::createFromFormat('Ymd', get_field('start_date')); } else { $start_date = ''; } if(get_field('end_date') != '') { $end_date = DateTime::createFromFormat('Ymd', get_field('end_date')); } else { $end_date = ''; }*/ $start_date = get_field('start_date'); $end_date = get_field('end_date'); $vibe = substr(get_field('vibe'), 0,250)."..."; $location = get_field('location'); $country = get_field('country'); //print_r($post); $price = get_min_price(get_the_ID()); echo "<div class='row fusion-row result_row' onclick=\"javascript:window.location.href='". get_permalink() ."'; return false;\"> <div class='col-sm-5 result_thumbnail' style='background: url(\"". $image_url ."\") center center no-repeat;'> </div> <div class='col-sm-7'> <h3 class='result_title'><a href='". get_permalink() ."'>".get_the_title()."</a></h3> <h4 class='result_location'>$location" . (($location != '' && $country != '')? "," : "") . " $country</h4> <div class='result_vibe'> ". $vibe ." </div> </div> <div class='result_bottom_row col-sm-7'> <div class='result_dates'> "; if($start_date != '') { echo $start_date; } echo ((get_field('start_date') != '' && get_field('end_date') != '')? " - " : ""); if($end_date != '') { echo $end_date; } echo " </div> <div class='result_price'> $price </div> </div> </div> "; } fusion_pagination($pages = '', $range = 2); } else { echo "<p>Sorry, no Festivals match your search.</p>"; } ?> </div> <?php do_action( 'fusion_after_content' ); ?> <?php get_footer(); // Omit closing PHP tag to avoid "Headers already sent" issues. ```
Thanks for all your help. The key issues where that i needed to post the code in the functions.php file and needed to amend the if statement to read: ``` $query->is_main_query() && is_post_type_archive( 'festival' ) ``` So that it would only effect my custom post type. Thanks!
221,553
<p>I have very little space to host my WordPress website. That is why I want all my media files are stored in the cloud like dropbox, google drive etc.</p> <p>For example, if a user wants to upload an image from the front-end using the common upload file button, then the image file is automatically stored directly to the cloud.</p> <p>or</p> <p>the image file will first stored in the upload folder then automatically moved into the cloud. So then my upload folder will always empty in order to save my very little space.</p> <p>How can I do this?</p>
[ { "answer_id": 221556, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 1, "selected": false, "text": "<p>The action hook <code>pre_get_posts</code> is called well before the page template is rendered. Move <code>add_action('pre_get_posts', 'my_pre_get_posts');</code> and your <code>my_pre_get_posts()</code> function to your theme's <code>functions.php</code> file.</p>\n" }, { "answer_id": 221589, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 0, "selected": false, "text": "<p>A few notes on your code here:</p>\n\n<ul>\n<li><p>Never add business logic in templates. Templates should never be used to compute any kind of logic, templates should only display the results from that logic. In short, templates should know function names, that's it. The function itself should be defined in a plugin or in your theme's functions files</p></li>\n<li><p>By the time the template is set (<em>via <code>template_include</code></em>), the main query has already executed and just a distant memory. By now, the main query cannot be altered. That is why your action has no affect on the main query. As I stated, functions, including filters and actions should be in a plugin or functions file</p></li>\n<li><p>Instead of doing <code>isset($_GET['fs_date_from']) &amp;&amp; $_GET['fs_date_from'] != '')</code> every time you need it, you can simply do the following with <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow\"><code>filter_input</code></a>, which will take care of checking if the var is set and will return the value if it is. You can additionally set a filter which will take care of sanitation for you</p>\n\n<pre><code>$fs_date_from = filter_input( \n INPUT_GET, // $_GET Global , for $_POST it will be INPUT_POST\n 'fs_date_from', // Name of the variable\n FILTER_SANITIZE_STRING // Type of filter to use to validate/sanitize\n);\n</code></pre>\n\n<p>You can now just check if <code>$fs_date_from</code> has a value</p>\n\n<pre><code>if ( $fs_date_from ) {\n // Do something\n}\n</code></pre>\n\n<p>You can also look into <a href=\"http://php.net/manual/en/function.filter-input-array.php\" rel=\"nofollow\"><code>filter_input_array</code></a> to handle multiple <code>$_GET</code> variable values</p></li>\n</ul>\n" }, { "answer_id": 221612, "author": "Paul Cullen", "author_id": 91132, "author_profile": "https://wordpress.stackexchange.com/users/91132", "pm_score": 1, "selected": true, "text": "<p>Thanks for all your help.</p>\n\n<p>The key issues where that i needed to post the code in the functions.php file and needed to amend the if statement to read:</p>\n\n<pre><code>$query-&gt;is_main_query() &amp;&amp; is_post_type_archive( 'festival' )\n</code></pre>\n\n<p>So that it would only effect my custom post type.</p>\n\n<p>Thanks!</p>\n" } ]
2016/03/23
[ "https://wordpress.stackexchange.com/questions/221553", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89982/" ]
I have very little space to host my WordPress website. That is why I want all my media files are stored in the cloud like dropbox, google drive etc. For example, if a user wants to upload an image from the front-end using the common upload file button, then the image file is automatically stored directly to the cloud. or the image file will first stored in the upload folder then automatically moved into the cloud. So then my upload folder will always empty in order to save my very little space. How can I do this?
Thanks for all your help. The key issues where that i needed to post the code in the functions.php file and needed to amend the if statement to read: ``` $query->is_main_query() && is_post_type_archive( 'festival' ) ``` So that it would only effect my custom post type. Thanks!
221,585
<p>I have a text widget, in it i just place there an iframe.</p> <p>A few days ago i wanted to override this widget on mobile browsers and add a background of an image on mobile browsers, luckily i used <a href="https://woorkup.com/hide-wordpress-widgets-mobile-devices/" rel="nofollow">How to hide widget on mobile</a> , i changed the code from that link instead of hiding the widget on mobile i simply give it a background image.</p> <p>Now my questions is how can i add an onclick function to this widget, for example when this widget is clicked on a mobile browser i call a shortcode.</p> <p>Any code examples of how to add some javascript to a text widget so that when it is clicked i call a shortcode. </p>
[ { "answer_id": 221556, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 1, "selected": false, "text": "<p>The action hook <code>pre_get_posts</code> is called well before the page template is rendered. Move <code>add_action('pre_get_posts', 'my_pre_get_posts');</code> and your <code>my_pre_get_posts()</code> function to your theme's <code>functions.php</code> file.</p>\n" }, { "answer_id": 221589, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 0, "selected": false, "text": "<p>A few notes on your code here:</p>\n\n<ul>\n<li><p>Never add business logic in templates. Templates should never be used to compute any kind of logic, templates should only display the results from that logic. In short, templates should know function names, that's it. The function itself should be defined in a plugin or in your theme's functions files</p></li>\n<li><p>By the time the template is set (<em>via <code>template_include</code></em>), the main query has already executed and just a distant memory. By now, the main query cannot be altered. That is why your action has no affect on the main query. As I stated, functions, including filters and actions should be in a plugin or functions file</p></li>\n<li><p>Instead of doing <code>isset($_GET['fs_date_from']) &amp;&amp; $_GET['fs_date_from'] != '')</code> every time you need it, you can simply do the following with <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow\"><code>filter_input</code></a>, which will take care of checking if the var is set and will return the value if it is. You can additionally set a filter which will take care of sanitation for you</p>\n\n<pre><code>$fs_date_from = filter_input( \n INPUT_GET, // $_GET Global , for $_POST it will be INPUT_POST\n 'fs_date_from', // Name of the variable\n FILTER_SANITIZE_STRING // Type of filter to use to validate/sanitize\n);\n</code></pre>\n\n<p>You can now just check if <code>$fs_date_from</code> has a value</p>\n\n<pre><code>if ( $fs_date_from ) {\n // Do something\n}\n</code></pre>\n\n<p>You can also look into <a href=\"http://php.net/manual/en/function.filter-input-array.php\" rel=\"nofollow\"><code>filter_input_array</code></a> to handle multiple <code>$_GET</code> variable values</p></li>\n</ul>\n" }, { "answer_id": 221612, "author": "Paul Cullen", "author_id": 91132, "author_profile": "https://wordpress.stackexchange.com/users/91132", "pm_score": 1, "selected": true, "text": "<p>Thanks for all your help.</p>\n\n<p>The key issues where that i needed to post the code in the functions.php file and needed to amend the if statement to read:</p>\n\n<pre><code>$query-&gt;is_main_query() &amp;&amp; is_post_type_archive( 'festival' )\n</code></pre>\n\n<p>So that it would only effect my custom post type.</p>\n\n<p>Thanks!</p>\n" } ]
2016/03/24
[ "https://wordpress.stackexchange.com/questions/221585", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91150/" ]
I have a text widget, in it i just place there an iframe. A few days ago i wanted to override this widget on mobile browsers and add a background of an image on mobile browsers, luckily i used [How to hide widget on mobile](https://woorkup.com/hide-wordpress-widgets-mobile-devices/) , i changed the code from that link instead of hiding the widget on mobile i simply give it a background image. Now my questions is how can i add an onclick function to this widget, for example when this widget is clicked on a mobile browser i call a shortcode. Any code examples of how to add some javascript to a text widget so that when it is clicked i call a shortcode.
Thanks for all your help. The key issues where that i needed to post the code in the functions.php file and needed to amend the if statement to read: ``` $query->is_main_query() && is_post_type_archive( 'festival' ) ``` So that it would only effect my custom post type. Thanks!
221,618
<p>I have a custom post type that looks like:</p> <pre><code>register_post_type( 'letters', array( 'labels' =&gt; array( 'all_items' =&gt; __( 'All Letters', 'text_domain' ), 'name' =&gt; __( 'Letters' ), 'search_items' =&gt; __('Search Letters'), 'singular_name' =&gt; __( 'Letter' ), ), 'has_archive' =&gt; true, 'menu_icon' =&gt; 'dashicons-media-document', 'menu_position'=&gt; 5, 'public' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'letters'), 'supports' =&gt; array( 'title', 'editor', 'author' ), ) ); </code></pre> <p>Then, I have a custom taxonomy that looks like:</p> <pre><code>function create_letter_taxonomies() { $labels = array( 'add_new_item' =&gt; __( 'Add New Tag' ), 'add_or_remove_items' =&gt; __( 'Add or remove tags' ), 'all_items' =&gt; __( 'All Tags' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used tags' ), 'edit_item' =&gt; __( 'Edit Tag' ), 'menu_name' =&gt; __( 'Tags' ), 'name' =&gt; _x( 'Tags', 'tag' ), 'new_item_name' =&gt; __( 'New Tag Name' ), 'parent_item' =&gt; null, 'parent_item_colon' =&gt; null, 'popular_items' =&gt; __( 'Popular Tags' ), 'search_items' =&gt; __( 'Search Tags' ), 'separate_items_with_commas' =&gt; __( 'Separate tags with commas' ), 'singular_name' =&gt; _x( 'Tag', 'tag' ), 'update_item' =&gt; __( 'Update Tag' ), ); register_taxonomy('letter_tags','letters', array( 'hierarchical' =&gt; false, 'labels' =&gt; $labels, 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'tags' ), 'show_admin_column' =&gt; true, 'show_ui' =&gt; true, 'update_count_callback' =&gt; '_update_post_term_count', ) ); } </code></pre> <p>What I am struggling with is how the taxonomy is working with my template. Through the admin panel I can add tags for my custom post type. <a href="http://joshrodg.com/hallmark/letters/" rel="nofollow">http://joshrodg.com/hallmark/letters/</a> works but <a href="http://joshrodg.com/hallmark/letters/tags/moore/" rel="nofollow">http://joshrodg.com/hallmark/letters/tags/moore/</a> doesn't work and <a href="http://joshrodg.com/hallmark/letters/tags/kenya/" rel="nofollow">http://joshrodg.com/hallmark/letters/tags/kenya/</a> doesn't work.</p> <p>The archive page I have is: <code>taxonomy-letter_tags.php</code>...am I missing something? I am trying to understand why I'm getting a 404 instead of seeing the <code>taxonomy-letter_tags.php</code> template?</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 221556, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 1, "selected": false, "text": "<p>The action hook <code>pre_get_posts</code> is called well before the page template is rendered. Move <code>add_action('pre_get_posts', 'my_pre_get_posts');</code> and your <code>my_pre_get_posts()</code> function to your theme's <code>functions.php</code> file.</p>\n" }, { "answer_id": 221589, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 0, "selected": false, "text": "<p>A few notes on your code here:</p>\n\n<ul>\n<li><p>Never add business logic in templates. Templates should never be used to compute any kind of logic, templates should only display the results from that logic. In short, templates should know function names, that's it. The function itself should be defined in a plugin or in your theme's functions files</p></li>\n<li><p>By the time the template is set (<em>via <code>template_include</code></em>), the main query has already executed and just a distant memory. By now, the main query cannot be altered. That is why your action has no affect on the main query. As I stated, functions, including filters and actions should be in a plugin or functions file</p></li>\n<li><p>Instead of doing <code>isset($_GET['fs_date_from']) &amp;&amp; $_GET['fs_date_from'] != '')</code> every time you need it, you can simply do the following with <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow\"><code>filter_input</code></a>, which will take care of checking if the var is set and will return the value if it is. You can additionally set a filter which will take care of sanitation for you</p>\n\n<pre><code>$fs_date_from = filter_input( \n INPUT_GET, // $_GET Global , for $_POST it will be INPUT_POST\n 'fs_date_from', // Name of the variable\n FILTER_SANITIZE_STRING // Type of filter to use to validate/sanitize\n);\n</code></pre>\n\n<p>You can now just check if <code>$fs_date_from</code> has a value</p>\n\n<pre><code>if ( $fs_date_from ) {\n // Do something\n}\n</code></pre>\n\n<p>You can also look into <a href=\"http://php.net/manual/en/function.filter-input-array.php\" rel=\"nofollow\"><code>filter_input_array</code></a> to handle multiple <code>$_GET</code> variable values</p></li>\n</ul>\n" }, { "answer_id": 221612, "author": "Paul Cullen", "author_id": 91132, "author_profile": "https://wordpress.stackexchange.com/users/91132", "pm_score": 1, "selected": true, "text": "<p>Thanks for all your help.</p>\n\n<p>The key issues where that i needed to post the code in the functions.php file and needed to amend the if statement to read:</p>\n\n<pre><code>$query-&gt;is_main_query() &amp;&amp; is_post_type_archive( 'festival' )\n</code></pre>\n\n<p>So that it would only effect my custom post type.</p>\n\n<p>Thanks!</p>\n" } ]
2016/03/24
[ "https://wordpress.stackexchange.com/questions/221618", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I have a custom post type that looks like: ``` register_post_type( 'letters', array( 'labels' => array( 'all_items' => __( 'All Letters', 'text_domain' ), 'name' => __( 'Letters' ), 'search_items' => __('Search Letters'), 'singular_name' => __( 'Letter' ), ), 'has_archive' => true, 'menu_icon' => 'dashicons-media-document', 'menu_position'=> 5, 'public' => true, 'rewrite' => array('slug' => 'letters'), 'supports' => array( 'title', 'editor', 'author' ), ) ); ``` Then, I have a custom taxonomy that looks like: ``` function create_letter_taxonomies() { $labels = array( 'add_new_item' => __( 'Add New Tag' ), 'add_or_remove_items' => __( 'Add or remove tags' ), 'all_items' => __( 'All Tags' ), 'choose_from_most_used' => __( 'Choose from the most used tags' ), 'edit_item' => __( 'Edit Tag' ), 'menu_name' => __( 'Tags' ), 'name' => _x( 'Tags', 'tag' ), 'new_item_name' => __( 'New Tag Name' ), 'parent_item' => null, 'parent_item_colon' => null, 'popular_items' => __( 'Popular Tags' ), 'search_items' => __( 'Search Tags' ), 'separate_items_with_commas' => __( 'Separate tags with commas' ), 'singular_name' => _x( 'Tag', 'tag' ), 'update_item' => __( 'Update Tag' ), ); register_taxonomy('letter_tags','letters', array( 'hierarchical' => false, 'labels' => $labels, 'query_var' => true, 'rewrite' => array( 'slug' => 'tags' ), 'show_admin_column' => true, 'show_ui' => true, 'update_count_callback' => '_update_post_term_count', ) ); } ``` What I am struggling with is how the taxonomy is working with my template. Through the admin panel I can add tags for my custom post type. <http://joshrodg.com/hallmark/letters/> works but <http://joshrodg.com/hallmark/letters/tags/moore/> doesn't work and <http://joshrodg.com/hallmark/letters/tags/kenya/> doesn't work. The archive page I have is: `taxonomy-letter_tags.php`...am I missing something? I am trying to understand why I'm getting a 404 instead of seeing the `taxonomy-letter_tags.php` template? Thanks, Josh
Thanks for all your help. The key issues where that i needed to post the code in the functions.php file and needed to amend the if statement to read: ``` $query->is_main_query() && is_post_type_archive( 'festival' ) ``` So that it would only effect my custom post type. Thanks!
221,640
<p>I would like to add "back buttons" to every page in my Wordpress site..and I'd like it to appear at the top of each page. How do I code that and where is it placed on the page code? thank you, Lori</p>
[ { "answer_id": 221644, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 2, "selected": false, "text": "<p>You can use following code. I trust you can style the link to look like button :)</p>\n\n<pre><code>if( wp_get_referer() )\n echo '&lt;a href=\"'&lt;?php wp_get_referer() ?&gt; '\" &gt;BACK&lt;/a&gt;';\n</code></pre>\n" }, { "answer_id": 221653, "author": "Jevuska", "author_id": 18731, "author_profile": "https://wordpress.stackexchange.com/users/18731", "pm_score": 2, "selected": false, "text": "<p><strong>Back Button</strong></p>\n\n<p>I combine @ItsMePN answer with how WordPress handling back page on error page - <code>wp_die</code>. It's <strong>JavaScript</strong>. <code>onclick='javascript:history.back()'</code></p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/functions.php#L2537\" rel=\"nofollow\">https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/functions.php#L2537</a></p>\n\n<p>Add into theme <strong>functions.php</strong></p>\n\n<pre><code>add_action( 'back_button', 'wpse221640_back_button' );\nfunction wpse221640_back_button()\n{\n if ( wp_get_referer() )\n {\n $back_text = __( '&amp;laquo; Back' );\n $button = \"\\n&lt;button id='my-back-button' class='btn button my-back-button' onclick='javascript:history.back()'&gt;$back_text&lt;/button&gt;\";\n echo ( $button );\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Add into theme <strong>header.php</strong> after <code>&lt;body&gt;</code></p>\n\n<pre><code>&lt;?php do_action('back_button'); ?&gt;\n</code></pre>\n" } ]
2016/03/24
[ "https://wordpress.stackexchange.com/questions/221640", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91185/" ]
I would like to add "back buttons" to every page in my Wordpress site..and I'd like it to appear at the top of each page. How do I code that and where is it placed on the page code? thank you, Lori
You can use following code. I trust you can style the link to look like button :) ``` if( wp_get_referer() ) echo '<a href="'<?php wp_get_referer() ?> '" >BACK</a>'; ```
221,667
<p>I'm using isotope to filter a custom post type. But I only want the child taxonomies of 2 particular parents. I have it working nicely for one parent, but I'm not sure how to modify the array to allow for 2 parents.</p> <pre><code>$terms = get_terms('speight_plans', array('parent' =&gt; 16)); // you can use any taxonomy, instead of just 'category' $count = count($terms); //How many are they? if ( $count &gt; 0 ){ //If there are more than 0 terms foreach ( $terms as $term ) { //for each term: echo '&lt;button class="button" data-filter=".'.$term-&gt;slug.'"&gt;' . $term-&gt;name . '&lt;/button&gt;'; //create a list item with the current term slug for sorting, and name for label } } </code></pre> <p>I tried doing </p> <pre><code>array('parent' =&gt; 16, 15)); </code></pre> <p>But that still only showed the children of parent 16.</p> <p>Any help you can afford would be much appreciated.</p>
[ { "answer_id": 221688, "author": "Tung Du", "author_id": 83304, "author_profile": "https://wordpress.stackexchange.com/users/83304", "pm_score": 0, "selected": false, "text": "<p>I can think about the <code>get_term_children()</code> function. You can use that function two times to retrieve 2 array of child terms id of two parent terms. Then you can merge them to one array and pass that array to <code>get_terms</code></p>\n\n<pre><code>get_terms('speight_plans', array('include' =&gt; $child_terms_arr));\n</code></pre>\n" }, { "answer_id": 221698, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>We can filter the generated SQL query through the <a href=\"https://developer.wordpress.org/reference/hooks/terms_clauses/\" rel=\"nofollow\"><code>terms_clauses</code> filter</a> before the SQL query is executed. What we will be doing is to introduce a new parameter called <code>wpse_parents</code> which will accept an array of parent term ID's to get children from. Note, this new parameter works exactly the same as the build-in parameter, <code>parent</code>, as it will return only direct children of the parent.</p>\n\n<h2>THE FILTER</h2>\n\n<p>The code is commented for easy understanding and basic description of what a particular piece of code is doing. Note, all code requires at least PHP 5.4</p>\n\n<pre><code>add_filter( 'terms_clauses', function ( $pieces, $taxonomies, $args )\n{\n // Bail if we are not currently handling our specified taxonomy\n if ( !in_array( 'speight_plans', $taxonomies ) )\n return $pieces;\n\n // Check if our custom argument, 'wpse_parents' is set, if not, bail\n if ( !isset ( $args['wpse_parents'] )\n || !is_array( $args['wpse_parents'] )\n ) \n return $pieces;\n\n // If 'wpse_parents' is set, make sure that 'parent' and 'child_of' is not set\n if ( $args['parent']\n || $args['child_of']\n )\n return $pieces;\n\n // Validate the array as an array of integers\n $parents = array_map( 'intval', $args['wpse_parents'] );\n\n // Loop through $parents and set the WHERE clause accordingly\n $where = [];\n foreach ( $parents as $parent ) {\n // Make sure $parent is not 0, if so, skip and continue\n if ( 0 === $parent )\n continue;\n\n $where[] = \" tt.parent = '$parent'\";\n }\n\n if ( !$where )\n return $pieces;\n\n $where_string = implode( ' OR ', $where );\n $pieces['where'] .= \" AND ( $where_string ) \";\n\n return $pieces;\n}, 10, 3 );\n</code></pre>\n\n<p>Just a note, the filter is build in such a way that it does not allow the <code>parent</code> and <code>child_of</code> parameters being set. If any of those parameters are set, the filter bails early and is not applied</p>\n\n<h2>BASIC USAGE</h2>\n\n<p>If you need to query child terms from terms 15 and 16, you can run the following query to achieve your goal</p>\n\n<pre><code>$args = [\n 'wpse_parents' =&gt; [15, 16]\n];\n$terms = get_terms( 'speight_plans', $args );\n</code></pre>\n" } ]
2016/03/24
[ "https://wordpress.stackexchange.com/questions/221667", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88351/" ]
I'm using isotope to filter a custom post type. But I only want the child taxonomies of 2 particular parents. I have it working nicely for one parent, but I'm not sure how to modify the array to allow for 2 parents. ``` $terms = get_terms('speight_plans', array('parent' => 16)); // you can use any taxonomy, instead of just 'category' $count = count($terms); //How many are they? if ( $count > 0 ){ //If there are more than 0 terms foreach ( $terms as $term ) { //for each term: echo '<button class="button" data-filter=".'.$term->slug.'">' . $term->name . '</button>'; //create a list item with the current term slug for sorting, and name for label } } ``` I tried doing ``` array('parent' => 16, 15)); ``` But that still only showed the children of parent 16. Any help you can afford would be much appreciated.
We can filter the generated SQL query through the [`terms_clauses` filter](https://developer.wordpress.org/reference/hooks/terms_clauses/) before the SQL query is executed. What we will be doing is to introduce a new parameter called `wpse_parents` which will accept an array of parent term ID's to get children from. Note, this new parameter works exactly the same as the build-in parameter, `parent`, as it will return only direct children of the parent. THE FILTER ---------- The code is commented for easy understanding and basic description of what a particular piece of code is doing. Note, all code requires at least PHP 5.4 ``` add_filter( 'terms_clauses', function ( $pieces, $taxonomies, $args ) { // Bail if we are not currently handling our specified taxonomy if ( !in_array( 'speight_plans', $taxonomies ) ) return $pieces; // Check if our custom argument, 'wpse_parents' is set, if not, bail if ( !isset ( $args['wpse_parents'] ) || !is_array( $args['wpse_parents'] ) ) return $pieces; // If 'wpse_parents' is set, make sure that 'parent' and 'child_of' is not set if ( $args['parent'] || $args['child_of'] ) return $pieces; // Validate the array as an array of integers $parents = array_map( 'intval', $args['wpse_parents'] ); // Loop through $parents and set the WHERE clause accordingly $where = []; foreach ( $parents as $parent ) { // Make sure $parent is not 0, if so, skip and continue if ( 0 === $parent ) continue; $where[] = " tt.parent = '$parent'"; } if ( !$where ) return $pieces; $where_string = implode( ' OR ', $where ); $pieces['where'] .= " AND ( $where_string ) "; return $pieces; }, 10, 3 ); ``` Just a note, the filter is build in such a way that it does not allow the `parent` and `child_of` parameters being set. If any of those parameters are set, the filter bails early and is not applied BASIC USAGE ----------- If you need to query child terms from terms 15 and 16, you can run the following query to achieve your goal ``` $args = [ 'wpse_parents' => [15, 16] ]; $terms = get_terms( 'speight_plans', $args ); ```
221,672
<p>I have a custom post type that im trying to limit results in search. </p> <p>The CPT is a deal/coupon, with a start and end date for each of the deals. </p> <p>What I'm trying to do is only show these posts in search:</p> <ol> <li>For non-recurring events....Show posts where the end date is today or after todays today.</li> </ol> <p><strong>OR</strong></p> <ol start="2"> <li>For recurring events, limit it to show only events with an end date between today which does not exceed 7 days.</li> </ol> <p>Each of these queries works perfectly on their own, but I cant combine them together...</p> <pre><code>function search_pre_get_posts( $query ) { if ( $query-&gt;is_search() &amp;&amp; $query-&gt;is_main_query() ) { $recurring_count = am_get_recurring_count($post-&gt;ID); // Show non-recurring events with end date of today or after if ($recurring_count == 0){ $currentdate = date('Y-m-d'); $query-&gt;set( 'meta_query', array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'am_enddate', 'compare' =&gt; '&gt;=', 'value' =&gt; $currentdate, ), array( 'key' =&gt; 'am_enddate', 'compare' =&gt; 'NOT EXISTS', ) ) ); $query-&gt;set( 'orderby', 'meta_value' ); $query-&gt;set( 'order', 'ASC' ); } else { // Show recurring events with end date of today or after, that doesnt exceed 7 days. $currentdate = date('Y-m-d'); $enddate = strtotime(date('Y-m-d') . "+7 days"); $enddate = date('Y-m-d',$enddate); $query-&gt;set( 'meta_query', array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'am_enddate', 'compare' =&gt; 'NOT EXISTS', ), array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'am_enddate', 'compare' =&gt; '&gt;=', 'value' =&gt; $currentdate, ), array( 'key' =&gt; 'am_enddate', 'compare' =&gt; '&lt;=', 'value' =&gt; $enddate, ) ) ) ); $query-&gt;set( 'orderby', 'meta_value' ); $query-&gt;set( 'order', 'ASC' ); } } } add_action( 'pre_get_posts', 'search_pre_get_posts' ); </code></pre>
[ { "answer_id": 221688, "author": "Tung Du", "author_id": 83304, "author_profile": "https://wordpress.stackexchange.com/users/83304", "pm_score": 0, "selected": false, "text": "<p>I can think about the <code>get_term_children()</code> function. You can use that function two times to retrieve 2 array of child terms id of two parent terms. Then you can merge them to one array and pass that array to <code>get_terms</code></p>\n\n<pre><code>get_terms('speight_plans', array('include' =&gt; $child_terms_arr));\n</code></pre>\n" }, { "answer_id": 221698, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>We can filter the generated SQL query through the <a href=\"https://developer.wordpress.org/reference/hooks/terms_clauses/\" rel=\"nofollow\"><code>terms_clauses</code> filter</a> before the SQL query is executed. What we will be doing is to introduce a new parameter called <code>wpse_parents</code> which will accept an array of parent term ID's to get children from. Note, this new parameter works exactly the same as the build-in parameter, <code>parent</code>, as it will return only direct children of the parent.</p>\n\n<h2>THE FILTER</h2>\n\n<p>The code is commented for easy understanding and basic description of what a particular piece of code is doing. Note, all code requires at least PHP 5.4</p>\n\n<pre><code>add_filter( 'terms_clauses', function ( $pieces, $taxonomies, $args )\n{\n // Bail if we are not currently handling our specified taxonomy\n if ( !in_array( 'speight_plans', $taxonomies ) )\n return $pieces;\n\n // Check if our custom argument, 'wpse_parents' is set, if not, bail\n if ( !isset ( $args['wpse_parents'] )\n || !is_array( $args['wpse_parents'] )\n ) \n return $pieces;\n\n // If 'wpse_parents' is set, make sure that 'parent' and 'child_of' is not set\n if ( $args['parent']\n || $args['child_of']\n )\n return $pieces;\n\n // Validate the array as an array of integers\n $parents = array_map( 'intval', $args['wpse_parents'] );\n\n // Loop through $parents and set the WHERE clause accordingly\n $where = [];\n foreach ( $parents as $parent ) {\n // Make sure $parent is not 0, if so, skip and continue\n if ( 0 === $parent )\n continue;\n\n $where[] = \" tt.parent = '$parent'\";\n }\n\n if ( !$where )\n return $pieces;\n\n $where_string = implode( ' OR ', $where );\n $pieces['where'] .= \" AND ( $where_string ) \";\n\n return $pieces;\n}, 10, 3 );\n</code></pre>\n\n<p>Just a note, the filter is build in such a way that it does not allow the <code>parent</code> and <code>child_of</code> parameters being set. If any of those parameters are set, the filter bails early and is not applied</p>\n\n<h2>BASIC USAGE</h2>\n\n<p>If you need to query child terms from terms 15 and 16, you can run the following query to achieve your goal</p>\n\n<pre><code>$args = [\n 'wpse_parents' =&gt; [15, 16]\n];\n$terms = get_terms( 'speight_plans', $args );\n</code></pre>\n" } ]
2016/03/24
[ "https://wordpress.stackexchange.com/questions/221672", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77113/" ]
I have a custom post type that im trying to limit results in search. The CPT is a deal/coupon, with a start and end date for each of the deals. What I'm trying to do is only show these posts in search: 1. For non-recurring events....Show posts where the end date is today or after todays today. **OR** 2. For recurring events, limit it to show only events with an end date between today which does not exceed 7 days. Each of these queries works perfectly on their own, but I cant combine them together... ``` function search_pre_get_posts( $query ) { if ( $query->is_search() && $query->is_main_query() ) { $recurring_count = am_get_recurring_count($post->ID); // Show non-recurring events with end date of today or after if ($recurring_count == 0){ $currentdate = date('Y-m-d'); $query->set( 'meta_query', array( 'relation' => 'OR', array( 'key' => 'am_enddate', 'compare' => '>=', 'value' => $currentdate, ), array( 'key' => 'am_enddate', 'compare' => 'NOT EXISTS', ) ) ); $query->set( 'orderby', 'meta_value' ); $query->set( 'order', 'ASC' ); } else { // Show recurring events with end date of today or after, that doesnt exceed 7 days. $currentdate = date('Y-m-d'); $enddate = strtotime(date('Y-m-d') . "+7 days"); $enddate = date('Y-m-d',$enddate); $query->set( 'meta_query', array( 'relation' => 'OR', array( 'key' => 'am_enddate', 'compare' => 'NOT EXISTS', ), array( 'relation' => 'AND', array( 'key' => 'am_enddate', 'compare' => '>=', 'value' => $currentdate, ), array( 'key' => 'am_enddate', 'compare' => '<=', 'value' => $enddate, ) ) ) ); $query->set( 'orderby', 'meta_value' ); $query->set( 'order', 'ASC' ); } } } add_action( 'pre_get_posts', 'search_pre_get_posts' ); ```
We can filter the generated SQL query through the [`terms_clauses` filter](https://developer.wordpress.org/reference/hooks/terms_clauses/) before the SQL query is executed. What we will be doing is to introduce a new parameter called `wpse_parents` which will accept an array of parent term ID's to get children from. Note, this new parameter works exactly the same as the build-in parameter, `parent`, as it will return only direct children of the parent. THE FILTER ---------- The code is commented for easy understanding and basic description of what a particular piece of code is doing. Note, all code requires at least PHP 5.4 ``` add_filter( 'terms_clauses', function ( $pieces, $taxonomies, $args ) { // Bail if we are not currently handling our specified taxonomy if ( !in_array( 'speight_plans', $taxonomies ) ) return $pieces; // Check if our custom argument, 'wpse_parents' is set, if not, bail if ( !isset ( $args['wpse_parents'] ) || !is_array( $args['wpse_parents'] ) ) return $pieces; // If 'wpse_parents' is set, make sure that 'parent' and 'child_of' is not set if ( $args['parent'] || $args['child_of'] ) return $pieces; // Validate the array as an array of integers $parents = array_map( 'intval', $args['wpse_parents'] ); // Loop through $parents and set the WHERE clause accordingly $where = []; foreach ( $parents as $parent ) { // Make sure $parent is not 0, if so, skip and continue if ( 0 === $parent ) continue; $where[] = " tt.parent = '$parent'"; } if ( !$where ) return $pieces; $where_string = implode( ' OR ', $where ); $pieces['where'] .= " AND ( $where_string ) "; return $pieces; }, 10, 3 ); ``` Just a note, the filter is build in such a way that it does not allow the `parent` and `child_of` parameters being set. If any of those parameters are set, the filter bails early and is not applied BASIC USAGE ----------- If you need to query child terms from terms 15 and 16, you can run the following query to achieve your goal ``` $args = [ 'wpse_parents' => [15, 16] ]; $terms = get_terms( 'speight_plans', $args ); ```
221,700
<p>I have tried so many solutions for this but I can't figure it out. Here is a simplified version of the plugin code:</p> <pre><code>class YITH_Vendors_Frontend_Premium extends YITH_Vendors_Frontend { public function __construct() { add_action( 'woocommerce_register_form', array( $this, 'register_form' ) ); } </code></pre> <p>So I want to remove this action from my child themes function.php.</p> <p>The problem is the class is not instanced via a variable. Instead it is instanced like this:</p> <pre><code>class YITH_Vendors_Premium extends YITH_Vendors { public function __construct() { public function init() { $this-&gt;frontend = new YITH_Vendors_Frontend_Premium(); } } } </code></pre> <p>This class however is never being instanced via variable. Instead there is a function that instances it:</p> <pre><code>function YITH_Vendors() { if ( defined( 'YITH_WPV_PREMIUM' ) ) { return YITH_Vendors_Premium::instance(); } return YITH_Vendors::instance(); } </code></pre> <p>And then it's just called like that:</p> <pre><code>YITH_Vendors(); </code></pre> <p>I tried all these but no chance:</p> <pre><code>remove_action( 'woocommerce_register_form', array( "YITH_Vendors_Frontend", 'register_form' ), 999 ); remove_action( 'woocommerce_register_form', array( "YITH_Vendors_Frontend_Premium", 'register_form' ), 999 ); remove_action( 'woocommerce_register_form', array( "YITH_Vendors", 'register_form' ), 999 ); remove_action( 'woocommerce_register_form', array( "YITH_Vendors_Premium", 'register_form' ), 999 ); </code></pre> <p>Please help! Thanks!</p>
[ { "answer_id": 221688, "author": "Tung Du", "author_id": 83304, "author_profile": "https://wordpress.stackexchange.com/users/83304", "pm_score": 0, "selected": false, "text": "<p>I can think about the <code>get_term_children()</code> function. You can use that function two times to retrieve 2 array of child terms id of two parent terms. Then you can merge them to one array and pass that array to <code>get_terms</code></p>\n\n<pre><code>get_terms('speight_plans', array('include' =&gt; $child_terms_arr));\n</code></pre>\n" }, { "answer_id": 221698, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>We can filter the generated SQL query through the <a href=\"https://developer.wordpress.org/reference/hooks/terms_clauses/\" rel=\"nofollow\"><code>terms_clauses</code> filter</a> before the SQL query is executed. What we will be doing is to introduce a new parameter called <code>wpse_parents</code> which will accept an array of parent term ID's to get children from. Note, this new parameter works exactly the same as the build-in parameter, <code>parent</code>, as it will return only direct children of the parent.</p>\n\n<h2>THE FILTER</h2>\n\n<p>The code is commented for easy understanding and basic description of what a particular piece of code is doing. Note, all code requires at least PHP 5.4</p>\n\n<pre><code>add_filter( 'terms_clauses', function ( $pieces, $taxonomies, $args )\n{\n // Bail if we are not currently handling our specified taxonomy\n if ( !in_array( 'speight_plans', $taxonomies ) )\n return $pieces;\n\n // Check if our custom argument, 'wpse_parents' is set, if not, bail\n if ( !isset ( $args['wpse_parents'] )\n || !is_array( $args['wpse_parents'] )\n ) \n return $pieces;\n\n // If 'wpse_parents' is set, make sure that 'parent' and 'child_of' is not set\n if ( $args['parent']\n || $args['child_of']\n )\n return $pieces;\n\n // Validate the array as an array of integers\n $parents = array_map( 'intval', $args['wpse_parents'] );\n\n // Loop through $parents and set the WHERE clause accordingly\n $where = [];\n foreach ( $parents as $parent ) {\n // Make sure $parent is not 0, if so, skip and continue\n if ( 0 === $parent )\n continue;\n\n $where[] = \" tt.parent = '$parent'\";\n }\n\n if ( !$where )\n return $pieces;\n\n $where_string = implode( ' OR ', $where );\n $pieces['where'] .= \" AND ( $where_string ) \";\n\n return $pieces;\n}, 10, 3 );\n</code></pre>\n\n<p>Just a note, the filter is build in such a way that it does not allow the <code>parent</code> and <code>child_of</code> parameters being set. If any of those parameters are set, the filter bails early and is not applied</p>\n\n<h2>BASIC USAGE</h2>\n\n<p>If you need to query child terms from terms 15 and 16, you can run the following query to achieve your goal</p>\n\n<pre><code>$args = [\n 'wpse_parents' =&gt; [15, 16]\n];\n$terms = get_terms( 'speight_plans', $args );\n</code></pre>\n" } ]
2016/03/25
[ "https://wordpress.stackexchange.com/questions/221700", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/56526/" ]
I have tried so many solutions for this but I can't figure it out. Here is a simplified version of the plugin code: ``` class YITH_Vendors_Frontend_Premium extends YITH_Vendors_Frontend { public function __construct() { add_action( 'woocommerce_register_form', array( $this, 'register_form' ) ); } ``` So I want to remove this action from my child themes function.php. The problem is the class is not instanced via a variable. Instead it is instanced like this: ``` class YITH_Vendors_Premium extends YITH_Vendors { public function __construct() { public function init() { $this->frontend = new YITH_Vendors_Frontend_Premium(); } } } ``` This class however is never being instanced via variable. Instead there is a function that instances it: ``` function YITH_Vendors() { if ( defined( 'YITH_WPV_PREMIUM' ) ) { return YITH_Vendors_Premium::instance(); } return YITH_Vendors::instance(); } ``` And then it's just called like that: ``` YITH_Vendors(); ``` I tried all these but no chance: ``` remove_action( 'woocommerce_register_form', array( "YITH_Vendors_Frontend", 'register_form' ), 999 ); remove_action( 'woocommerce_register_form', array( "YITH_Vendors_Frontend_Premium", 'register_form' ), 999 ); remove_action( 'woocommerce_register_form', array( "YITH_Vendors", 'register_form' ), 999 ); remove_action( 'woocommerce_register_form', array( "YITH_Vendors_Premium", 'register_form' ), 999 ); ``` Please help! Thanks!
We can filter the generated SQL query through the [`terms_clauses` filter](https://developer.wordpress.org/reference/hooks/terms_clauses/) before the SQL query is executed. What we will be doing is to introduce a new parameter called `wpse_parents` which will accept an array of parent term ID's to get children from. Note, this new parameter works exactly the same as the build-in parameter, `parent`, as it will return only direct children of the parent. THE FILTER ---------- The code is commented for easy understanding and basic description of what a particular piece of code is doing. Note, all code requires at least PHP 5.4 ``` add_filter( 'terms_clauses', function ( $pieces, $taxonomies, $args ) { // Bail if we are not currently handling our specified taxonomy if ( !in_array( 'speight_plans', $taxonomies ) ) return $pieces; // Check if our custom argument, 'wpse_parents' is set, if not, bail if ( !isset ( $args['wpse_parents'] ) || !is_array( $args['wpse_parents'] ) ) return $pieces; // If 'wpse_parents' is set, make sure that 'parent' and 'child_of' is not set if ( $args['parent'] || $args['child_of'] ) return $pieces; // Validate the array as an array of integers $parents = array_map( 'intval', $args['wpse_parents'] ); // Loop through $parents and set the WHERE clause accordingly $where = []; foreach ( $parents as $parent ) { // Make sure $parent is not 0, if so, skip and continue if ( 0 === $parent ) continue; $where[] = " tt.parent = '$parent'"; } if ( !$where ) return $pieces; $where_string = implode( ' OR ', $where ); $pieces['where'] .= " AND ( $where_string ) "; return $pieces; }, 10, 3 ); ``` Just a note, the filter is build in such a way that it does not allow the `parent` and `child_of` parameters being set. If any of those parameters are set, the filter bails early and is not applied BASIC USAGE ----------- If you need to query child terms from terms 15 and 16, you can run the following query to achieve your goal ``` $args = [ 'wpse_parents' => [15, 16] ]; $terms = get_terms( 'speight_plans', $args ); ```
221,704
<p>I have a single page for my products where all products get listed. This is how i've archieved it:</p> <pre><code>&lt;ul class="produkte"&gt; &lt;?php $args = array( 'post_type' =&gt; 'produkte', 'posts_per_page' =&gt; 30 ); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); echo '&lt;li class="produkt"&gt;'; echo '&lt;a href="' . get_permalink() . '"&gt;'; echo '&lt;div class="produkt-info"&gt;'; the_title('&lt;h3&gt;', '&lt;/h3&gt;'); if (has_post_thumbnail()) { echo '&lt;figure class="imgBox"&gt;'; the_post_thumbnail('full', array('class' =&gt; 'img-resp') ); echo "&lt;/figure&gt;"; } echo '&lt;/div&gt;'; echo '&lt;/a&gt;'; echo '&lt;/li&gt;'; endwhile; ?&gt; &lt;/ul&gt; </code></pre> <p>I decided that i want to set the post thumbnail as the background-image of the li.produkt. When i do something like this:</p> <pre><code>echo '&lt;li class="produkt" style="background: url('.the_post_thumbnail().')"&gt;'; </code></pre> <p>The page generates an image-element above the li-element. What am i doing wrong??</p>
[ { "answer_id": 221706, "author": "Tung Du", "author_id": 83304, "author_profile": "https://wordpress.stackexchange.com/users/83304", "pm_score": 4, "selected": true, "text": "<p>The problem here is <code>the_post_thumbnail()</code> doesn't return image url but the img tag.</p>\n\n<p>You can use this code</p>\n\n<pre><code>$url = wp_get_attachment_url( get_post_thumbnail_id($post-&gt;ID) );\necho '&lt;li class=\"produkt\" style=\"background: url('. $url.')\"&gt;';\n</code></pre>\n" }, { "answer_id": 221710, "author": "WP-Silver", "author_id": 5344, "author_profile": "https://wordpress.stackexchange.com/users/5344", "pm_score": 2, "selected": false, "text": "<p>Per WordPress Codex the the_post_thumbnail() function <strong><em>Display the post thumbnail.</em></strong> <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/the_post_thumbnail/</a> But this output the whole image tag and not just the src, which in your case is needed.</p>\n\n<p>Instead you should use the wp_get_attachment_image_src() function which <strong><em>Retrieve an image to represent an attachment.</em></strong>. <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n\n<p>So i suggest to try something like this:</p>\n\n<pre><code>//this retrieve the full version of image\n$image_data = wp_get_attachment_image_src ( get_the_post_thumbnail( $post-&gt;ID), 'full' );\n$image_url = $image_data[0];\necho '&lt;li class=\"produkt\" style=\"background: url('. $image_url .')\"&gt;';\n</code></pre>\n" }, { "answer_id": 303651, "author": "mspseudolus", "author_id": 96386, "author_profile": "https://wordpress.stackexchange.com/users/96386", "pm_score": 3, "selected": false, "text": "<p>There is now the <code>get_the_post_thumbnail_url</code> function provided in WordPress.</p>\n\n<p>Usage example from the codex:</p>\n\n<p><code>$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');</code></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/</a></p>\n" }, { "answer_id": 379102, "author": "Pedro Marques", "author_id": 121157, "author_profile": "https://wordpress.stackexchange.com/users/121157", "pm_score": 0, "selected": false, "text": "<p>Try using background-size: cover, background-position: center and background-size: 300px 100px;</p>\n<pre><code>&lt;?php\necho '&lt;li class=&quot;produkt&quot; style=&quot;background-image: url('&lt;?php the_post_thumbnail_url(); ?&gt;'); background-size: cover; background-position: center; background-repeat: no-repeat; background-size: 300px 100px;&quot;&gt;';\n?&gt;\n</code></pre>\n" }, { "answer_id": 383119, "author": "yasinedr", "author_id": 201700, "author_profile": "https://wordpress.stackexchange.com/users/201700", "pm_score": 0, "selected": false, "text": "<p>simply echo the post thumbnail url :</p>\n<p><code>&lt;li class=&quot;produkt&quot; style=&quot;background-image: url(&lt;?php echo the_post_thumbnail_url(); ?&gt;);&quot;&gt;&gt;&lt;/li&gt;</code></p>\n" } ]
2016/03/25
[ "https://wordpress.stackexchange.com/questions/221704", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/79865/" ]
I have a single page for my products where all products get listed. This is how i've archieved it: ``` <ul class="produkte"> <?php $args = array( 'post_type' => 'produkte', 'posts_per_page' => 30 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); echo '<li class="produkt">'; echo '<a href="' . get_permalink() . '">'; echo '<div class="produkt-info">'; the_title('<h3>', '</h3>'); if (has_post_thumbnail()) { echo '<figure class="imgBox">'; the_post_thumbnail('full', array('class' => 'img-resp') ); echo "</figure>"; } echo '</div>'; echo '</a>'; echo '</li>'; endwhile; ?> </ul> ``` I decided that i want to set the post thumbnail as the background-image of the li.produkt. When i do something like this: ``` echo '<li class="produkt" style="background: url('.the_post_thumbnail().')">'; ``` The page generates an image-element above the li-element. What am i doing wrong??
The problem here is `the_post_thumbnail()` doesn't return image url but the img tag. You can use this code ``` $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); echo '<li class="produkt" style="background: url('. $url.')">'; ```
221,716
<p>I want to organize data on my website the following way. I am not sure how it can be done. Do it need to make a custom post type or taxonomy to organize data like this. </p> <p>Help and guidance will be appreciated. </p> <pre><code>home - incubators - incubators name - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup - incubators name - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup - incubators name - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup </code></pre> <p>Sample URLs = www.abc.com/incubators/ycombinator/airbnb</p> <p>Sample URLs = www.abc.com/incubators/ycombinator/quora</p> <p>Sample URLs = www.abc.com/incubators/ycombinator/springtees</p> <p>as recommended by some of the members. I have made a taxonomy of incubators. </p> <pre><code>// Register Custom Taxonomy function custom_taxonomy() { $labels = array( 'name' =&gt; _x( 'Incubators', 'Taxonomy General Name', 'text_domain' ), 'singular_name' =&gt; _x( 'Incubator', 'Taxonomy Singular Name', 'text_domain' ), 'menu_name' =&gt; __( 'Incubators', 'text_domain' ), 'all_items' =&gt; __( 'All Incubators', 'text_domain' ), 'parent_item' =&gt; __( 'Parent Incubator', 'text_domain' ), 'parent_item_colon' =&gt; __( 'Parent Incubator:', 'text_domain' ), 'new_item_name' =&gt; __( 'New Incubator Name', 'text_domain' ), 'add_new_item' =&gt; __( 'Add New Incubator', 'text_domain' ), 'edit_item' =&gt; __( 'Edit Incubator', 'text_domain' ), 'update_item' =&gt; __( 'Update Incubator', 'text_domain' ), 'view_item' =&gt; __( 'View Incubator', 'text_domain' ), 'separate_items_with_commas' =&gt; __( 'Separate items with commas', 'text_domain' ), 'add_or_remove_items' =&gt; __( 'Add or remove items', 'text_domain' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used', 'text_domain' ), 'popular_items' =&gt; __( 'Popular Items', 'text_domain' ), 'search_items' =&gt; __( 'Search Items', 'text_domain' ), 'not_found' =&gt; __( 'Not Found', 'text_domain' ), 'no_terms' =&gt; __( 'No items', 'text_domain' ), 'items_list' =&gt; __( 'Items list', 'text_domain' ), 'items_list_navigation' =&gt; __( 'Items list navigation', 'text_domain' ), ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_tagcloud' =&gt; true, ); register_taxonomy( 'Incubator', array( 'post' ), $args ); } add_action( 'init', 'custom_taxonomy', 0 ); </code></pre> <p>Now the issue is, I am seeing it like a category in the All Posts section. Where as, the Incubators archive section should have links to all incubators. And each incubator should have a separate details page. At each details page, there should be a list of incubated startups in the bottom. </p>
[ { "answer_id": 221706, "author": "Tung Du", "author_id": 83304, "author_profile": "https://wordpress.stackexchange.com/users/83304", "pm_score": 4, "selected": true, "text": "<p>The problem here is <code>the_post_thumbnail()</code> doesn't return image url but the img tag.</p>\n\n<p>You can use this code</p>\n\n<pre><code>$url = wp_get_attachment_url( get_post_thumbnail_id($post-&gt;ID) );\necho '&lt;li class=\"produkt\" style=\"background: url('. $url.')\"&gt;';\n</code></pre>\n" }, { "answer_id": 221710, "author": "WP-Silver", "author_id": 5344, "author_profile": "https://wordpress.stackexchange.com/users/5344", "pm_score": 2, "selected": false, "text": "<p>Per WordPress Codex the the_post_thumbnail() function <strong><em>Display the post thumbnail.</em></strong> <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/the_post_thumbnail/</a> But this output the whole image tag and not just the src, which in your case is needed.</p>\n\n<p>Instead you should use the wp_get_attachment_image_src() function which <strong><em>Retrieve an image to represent an attachment.</em></strong>. <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/</a></p>\n\n<p>So i suggest to try something like this:</p>\n\n<pre><code>//this retrieve the full version of image\n$image_data = wp_get_attachment_image_src ( get_the_post_thumbnail( $post-&gt;ID), 'full' );\n$image_url = $image_data[0];\necho '&lt;li class=\"produkt\" style=\"background: url('. $image_url .')\"&gt;';\n</code></pre>\n" }, { "answer_id": 303651, "author": "mspseudolus", "author_id": 96386, "author_profile": "https://wordpress.stackexchange.com/users/96386", "pm_score": 3, "selected": false, "text": "<p>There is now the <code>get_the_post_thumbnail_url</code> function provided in WordPress.</p>\n\n<p>Usage example from the codex:</p>\n\n<p><code>$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');</code></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/</a></p>\n" }, { "answer_id": 379102, "author": "Pedro Marques", "author_id": 121157, "author_profile": "https://wordpress.stackexchange.com/users/121157", "pm_score": 0, "selected": false, "text": "<p>Try using background-size: cover, background-position: center and background-size: 300px 100px;</p>\n<pre><code>&lt;?php\necho '&lt;li class=&quot;produkt&quot; style=&quot;background-image: url('&lt;?php the_post_thumbnail_url(); ?&gt;'); background-size: cover; background-position: center; background-repeat: no-repeat; background-size: 300px 100px;&quot;&gt;';\n?&gt;\n</code></pre>\n" }, { "answer_id": 383119, "author": "yasinedr", "author_id": 201700, "author_profile": "https://wordpress.stackexchange.com/users/201700", "pm_score": 0, "selected": false, "text": "<p>simply echo the post thumbnail url :</p>\n<p><code>&lt;li class=&quot;produkt&quot; style=&quot;background-image: url(&lt;?php echo the_post_thumbnail_url(); ?&gt;);&quot;&gt;&gt;&lt;/li&gt;</code></p>\n" } ]
2016/03/25
[ "https://wordpress.stackexchange.com/questions/221716", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24020/" ]
I want to organize data on my website the following way. I am not sure how it can be done. Do it need to make a custom post type or taxonomy to organize data like this. Help and guidance will be appreciated. ``` home - incubators - incubators name - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup - incubators name - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup - incubators name - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup - incubated startup ``` Sample URLs = www.abc.com/incubators/ycombinator/airbnb Sample URLs = www.abc.com/incubators/ycombinator/quora Sample URLs = www.abc.com/incubators/ycombinator/springtees as recommended by some of the members. I have made a taxonomy of incubators. ``` // Register Custom Taxonomy function custom_taxonomy() { $labels = array( 'name' => _x( 'Incubators', 'Taxonomy General Name', 'text_domain' ), 'singular_name' => _x( 'Incubator', 'Taxonomy Singular Name', 'text_domain' ), 'menu_name' => __( 'Incubators', 'text_domain' ), 'all_items' => __( 'All Incubators', 'text_domain' ), 'parent_item' => __( 'Parent Incubator', 'text_domain' ), 'parent_item_colon' => __( 'Parent Incubator:', 'text_domain' ), 'new_item_name' => __( 'New Incubator Name', 'text_domain' ), 'add_new_item' => __( 'Add New Incubator', 'text_domain' ), 'edit_item' => __( 'Edit Incubator', 'text_domain' ), 'update_item' => __( 'Update Incubator', 'text_domain' ), 'view_item' => __( 'View Incubator', 'text_domain' ), 'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ), 'add_or_remove_items' => __( 'Add or remove items', 'text_domain' ), 'choose_from_most_used' => __( 'Choose from the most used', 'text_domain' ), 'popular_items' => __( 'Popular Items', 'text_domain' ), 'search_items' => __( 'Search Items', 'text_domain' ), 'not_found' => __( 'Not Found', 'text_domain' ), 'no_terms' => __( 'No items', 'text_domain' ), 'items_list' => __( 'Items list', 'text_domain' ), 'items_list_navigation' => __( 'Items list navigation', 'text_domain' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, ); register_taxonomy( 'Incubator', array( 'post' ), $args ); } add_action( 'init', 'custom_taxonomy', 0 ); ``` Now the issue is, I am seeing it like a category in the All Posts section. Where as, the Incubators archive section should have links to all incubators. And each incubator should have a separate details page. At each details page, there should be a list of incubated startups in the bottom.
The problem here is `the_post_thumbnail()` doesn't return image url but the img tag. You can use this code ``` $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); echo '<li class="produkt" style="background: url('. $url.')">'; ```
221,727
<p>I want to add an additional header to outgoing emails on my sites, so I can easily determine which site sent a given email. (I put a standard functionality plugin on all of my sites, so this is easy enough to do, and configuring my email client to filter and otherwise act on this header would be an amazing time-saver.)</p> <p>I thought this would be a simple matter of plugging into the <code>wp_mail</code> function, but evidently it isn't.</p> <p>First, I tried this:</p> <pre><code>add_filter('wp_mail', 'ws_add_site_header'); function ws_add_site_header() { return array('headers' =&gt; 'X-WU-Site: ' . parse_url(get_site_url(), PHP_URL_HOST)); } </code></pre> <p>Here, my array took precedence over anything else that modified the mail settings (say, Gravity Forms), so HTML emails started showing up as bare HTML and not nicely-formatted. Makes sense, since the Content-type: header that GF added was scrubbed. But my header was added to the email. Since others also depend on receiving pretty emails (all my sites' content developers and end-users, among others I'm sure), that isn't acceptable.</p> <p>One of my colleagues then suggested routing my stuff through wp_parse_args(), thus:</p> <pre><code>add_filter('wp_mail', 'ws_add_site_header'); function ws_add_site_header($args) { $new_header = array('headers' =&gt; 'X-WU-Site: ' . parse_url(get_site_url(), PHP_URL_HOST)); return wp_parse_args($args, $new_header); } </code></pre> <p>With that, it's as if my function doesn't exist -- my header isn't added, but neither are others' headers and mail settings stripped.</p> <p>What's the correct way to add a header to an outgoing email, without scrambling up any other filters that might exist?</p>
[ { "answer_id": 221728, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 2, "selected": false, "text": "<p>PHP <code>headers</code> are strings. You can not parse them as array. You need to add you additional header as string with <code>\\r\\n</code> to make sure it is added in next line.</p>\n\n<p>Example:</p>\n\n<pre><code>add_filter('wp_mail', 'ws_add_site_header', 99);\nfunction ws_add_site_header($args) {\n $args['headers'] .= !empty($args['headers']) ? \"\\r\\n\" : '';\n $args['headers'] .= 'X-WU-Site: ' . parse_url(get_site_url(), PHP_URL_HOST);\n return $args;\n}\n</code></pre>\n\n<p>Also please note add you additional headers at last with priority <code>99</code> so no other plugin can replace it if it is not checking that headers already present. If needed make it <code>999</code>.</p>\n" }, { "answer_id": 221731, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p>Here's an alternative using directly the <code>AddCustomHeader</code> method of the <code>PHPMailer</code> instance:</p>\n\n<pre><code>/**\n * Add a custom header.\n * $name value can be overloaded to contain\n * both header name and value (name:value)\n * @access public\n * @param string $name Custom header name\n * @param string $value Header value\n * @return void\n */\npublic function addCustomHeader($name, $value = null)\n{\n if ($value === null) {\n // Value passed in as name:value\n $this-&gt;CustomHeader[] = explode(':', $name, 2);\n } else {\n $this-&gt;CustomHeader[] = array($name, $value);\n }\n}\n</code></pre>\n\n<p>Here we can see that there are two ways to use it:</p>\n\n<h2>Example #1:</h2>\n\n<p>Here we only pass the header information in the <code>$name</code> input string, that's seperated with <code>:</code></p>\n\n<pre><code>add_action( 'phpmailer_init', function( $phpmailer )\n{ \n $phpmailer-&gt;AddCustomHeader( \n 'X-WU-Site: ' . parse_url( get_site_url(), PHP_URL_HOST ) \n ); \n} );\n</code></pre>\n\n<h2>Example #2:</h2>\n\n<p>Here are both <code>$name</code> and <code>$value</code> non-empty:</p>\n\n<pre><code>add_action( 'phpmailer_init', function( $phpmailer )\n{ \n $phpmailer-&gt;AddCustomHeader( \n 'X-WU-Site', parse_url( get_site_url(), PHP_URL_HOST ) \n ); \n} );\n</code></pre>\n" }, { "answer_id": 221747, "author": "David E. Smith", "author_id": 67104, "author_profile": "https://wordpress.stackexchange.com/users/67104", "pm_score": 4, "selected": true, "text": "<p>Thanks to the above, I've realized my central mistake -- I didn't quite realize that the arguments being passed in were a multi-dimensional array.</p>\n\n<p>For now, I've re-implemented the function thus:</p>\n\n<pre><code>function ws_add_site_header($email) {\n $email['headers'][] = 'X-WU-Site: ' . parse_url(get_site_url(), PHP_URL_HOST) ;\n return $email; \n}\n</code></pre>\n\n<p>My reading of the wp_mail() source (see: <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/pluggable.php#L235\">https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/pluggable.php#L235</a>) leads me to believe that the headers component can be an array, or a big string, or possibly some horrific mish-mash of the two, but that using an array is probably the safer/more correct option.</p>\n\n<p>I do like the various phpmailer answers, but it just seems a bit cleaner to try to do things using WordPress' built-ins.</p>\n" } ]
2016/03/25
[ "https://wordpress.stackexchange.com/questions/221727", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67104/" ]
I want to add an additional header to outgoing emails on my sites, so I can easily determine which site sent a given email. (I put a standard functionality plugin on all of my sites, so this is easy enough to do, and configuring my email client to filter and otherwise act on this header would be an amazing time-saver.) I thought this would be a simple matter of plugging into the `wp_mail` function, but evidently it isn't. First, I tried this: ``` add_filter('wp_mail', 'ws_add_site_header'); function ws_add_site_header() { return array('headers' => 'X-WU-Site: ' . parse_url(get_site_url(), PHP_URL_HOST)); } ``` Here, my array took precedence over anything else that modified the mail settings (say, Gravity Forms), so HTML emails started showing up as bare HTML and not nicely-formatted. Makes sense, since the Content-type: header that GF added was scrubbed. But my header was added to the email. Since others also depend on receiving pretty emails (all my sites' content developers and end-users, among others I'm sure), that isn't acceptable. One of my colleagues then suggested routing my stuff through wp\_parse\_args(), thus: ``` add_filter('wp_mail', 'ws_add_site_header'); function ws_add_site_header($args) { $new_header = array('headers' => 'X-WU-Site: ' . parse_url(get_site_url(), PHP_URL_HOST)); return wp_parse_args($args, $new_header); } ``` With that, it's as if my function doesn't exist -- my header isn't added, but neither are others' headers and mail settings stripped. What's the correct way to add a header to an outgoing email, without scrambling up any other filters that might exist?
Thanks to the above, I've realized my central mistake -- I didn't quite realize that the arguments being passed in were a multi-dimensional array. For now, I've re-implemented the function thus: ``` function ws_add_site_header($email) { $email['headers'][] = 'X-WU-Site: ' . parse_url(get_site_url(), PHP_URL_HOST) ; return $email; } ``` My reading of the wp\_mail() source (see: <https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/pluggable.php#L235>) leads me to believe that the headers component can be an array, or a big string, or possibly some horrific mish-mash of the two, but that using an array is probably the safer/more correct option. I do like the various phpmailer answers, but it just seems a bit cleaner to try to do things using WordPress' built-ins.
221,730
<p>I need to get attachment images with horizontal orientation. I tried to use <code>Meta_Query</code> but I don't know how to compare two values (<strong>width</strong> and <strong>height</strong>) from one associative array that is in <code>wp_postmeta</code> table. I don't have any specific values of width and height, I only need to compare this values which is in associative array.</p> <p>Also tried to do this with <code>$wpdb</code> custom query: </p> <pre><code>$attach_ids = $wpdb-&gt;query( " SELECT wp_posts.ID FROM wp_posts, wp_postmeta WHERE EXISTS (SELECT * FROM wp_postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value= ???) AND wp_posts.ID = wp_postmeta.post_id AND wp_posts.post_type = 'attachment' AND wp_posts.post_mime_type = 'image/jpeg' ORDER BY RAND() LIMIT 0, 6" ); </code></pre> <p>Can anyone understand my problem and help? P.S. Sorry for my English.</p>
[ { "answer_id": 221728, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 2, "selected": false, "text": "<p>PHP <code>headers</code> are strings. You can not parse them as array. You need to add you additional header as string with <code>\\r\\n</code> to make sure it is added in next line.</p>\n\n<p>Example:</p>\n\n<pre><code>add_filter('wp_mail', 'ws_add_site_header', 99);\nfunction ws_add_site_header($args) {\n $args['headers'] .= !empty($args['headers']) ? \"\\r\\n\" : '';\n $args['headers'] .= 'X-WU-Site: ' . parse_url(get_site_url(), PHP_URL_HOST);\n return $args;\n}\n</code></pre>\n\n<p>Also please note add you additional headers at last with priority <code>99</code> so no other plugin can replace it if it is not checking that headers already present. If needed make it <code>999</code>.</p>\n" }, { "answer_id": 221731, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": false, "text": "<p>Here's an alternative using directly the <code>AddCustomHeader</code> method of the <code>PHPMailer</code> instance:</p>\n\n<pre><code>/**\n * Add a custom header.\n * $name value can be overloaded to contain\n * both header name and value (name:value)\n * @access public\n * @param string $name Custom header name\n * @param string $value Header value\n * @return void\n */\npublic function addCustomHeader($name, $value = null)\n{\n if ($value === null) {\n // Value passed in as name:value\n $this-&gt;CustomHeader[] = explode(':', $name, 2);\n } else {\n $this-&gt;CustomHeader[] = array($name, $value);\n }\n}\n</code></pre>\n\n<p>Here we can see that there are two ways to use it:</p>\n\n<h2>Example #1:</h2>\n\n<p>Here we only pass the header information in the <code>$name</code> input string, that's seperated with <code>:</code></p>\n\n<pre><code>add_action( 'phpmailer_init', function( $phpmailer )\n{ \n $phpmailer-&gt;AddCustomHeader( \n 'X-WU-Site: ' . parse_url( get_site_url(), PHP_URL_HOST ) \n ); \n} );\n</code></pre>\n\n<h2>Example #2:</h2>\n\n<p>Here are both <code>$name</code> and <code>$value</code> non-empty:</p>\n\n<pre><code>add_action( 'phpmailer_init', function( $phpmailer )\n{ \n $phpmailer-&gt;AddCustomHeader( \n 'X-WU-Site', parse_url( get_site_url(), PHP_URL_HOST ) \n ); \n} );\n</code></pre>\n" }, { "answer_id": 221747, "author": "David E. Smith", "author_id": 67104, "author_profile": "https://wordpress.stackexchange.com/users/67104", "pm_score": 4, "selected": true, "text": "<p>Thanks to the above, I've realized my central mistake -- I didn't quite realize that the arguments being passed in were a multi-dimensional array.</p>\n\n<p>For now, I've re-implemented the function thus:</p>\n\n<pre><code>function ws_add_site_header($email) {\n $email['headers'][] = 'X-WU-Site: ' . parse_url(get_site_url(), PHP_URL_HOST) ;\n return $email; \n}\n</code></pre>\n\n<p>My reading of the wp_mail() source (see: <a href=\"https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/pluggable.php#L235\">https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/pluggable.php#L235</a>) leads me to believe that the headers component can be an array, or a big string, or possibly some horrific mish-mash of the two, but that using an array is probably the safer/more correct option.</p>\n\n<p>I do like the various phpmailer answers, but it just seems a bit cleaner to try to do things using WordPress' built-ins.</p>\n" } ]
2016/03/25
[ "https://wordpress.stackexchange.com/questions/221730", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91227/" ]
I need to get attachment images with horizontal orientation. I tried to use `Meta_Query` but I don't know how to compare two values (**width** and **height**) from one associative array that is in `wp_postmeta` table. I don't have any specific values of width and height, I only need to compare this values which is in associative array. Also tried to do this with `$wpdb` custom query: ``` $attach_ids = $wpdb->query( " SELECT wp_posts.ID FROM wp_posts, wp_postmeta WHERE EXISTS (SELECT * FROM wp_postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value= ???) AND wp_posts.ID = wp_postmeta.post_id AND wp_posts.post_type = 'attachment' AND wp_posts.post_mime_type = 'image/jpeg' ORDER BY RAND() LIMIT 0, 6" ); ``` Can anyone understand my problem and help? P.S. Sorry for my English.
Thanks to the above, I've realized my central mistake -- I didn't quite realize that the arguments being passed in were a multi-dimensional array. For now, I've re-implemented the function thus: ``` function ws_add_site_header($email) { $email['headers'][] = 'X-WU-Site: ' . parse_url(get_site_url(), PHP_URL_HOST) ; return $email; } ``` My reading of the wp\_mail() source (see: <https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/pluggable.php#L235>) leads me to believe that the headers component can be an array, or a big string, or possibly some horrific mish-mash of the two, but that using an array is probably the safer/more correct option. I do like the various phpmailer answers, but it just seems a bit cleaner to try to do things using WordPress' built-ins.
221,751
<p>Similar to the question over at <a href="https://wordpress.stackexchange.com/questions/72547/get-wp-logout-url-function-to-work-on-external-non-wordpress-page">Get wp_logout_url function to work on external (non-Wordpress) page</a></p> <p>The problem I am facing is the fact the subdomain is on a different server so I am unable to include/require the <code>wp-blog-header.php</code> file.</p> <p>Is there a way that I can whitelist domains that can allow instant logouts, like you can for the <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/allowed_redirect_hosts" rel="nofollow noreferrer">redirect whitelist</a>.</p> <p>If not, how can I allow subdomains (it has remote sql access) to create a valid logout link that bypasses the "Are you sure you want to logout" notice.</p> <h1>Re: @SatbirKira</h1> <p>Does this like a logical work around to make sure the logout is "valid" to a certain degree:</p> <ul> <li>Set the logout URL every 24 hours to have a query string with a random string appended to it for example: <code>http://website.com/custom_logout.php?confirm=sj239ks</code>, followed by <code>http://website.com/custom_logout.php?confirm=32k9la3</code></li> </ul> <p>Each time it changes it would edit a specific file (custom_logout.php on the other server OR a txt/ini file on its own server OR other server) and create an array/list of strings</p> <pre><code>$confirmkeys = array("sj239ks", "32k9la3"); </code></pre> <p>or</p> <pre><code>[confirmkeys] confirm[] = sj239ks confirm[] = 32k9la3 </code></pre> <p>It would only ever have 2 confirm keys in the file, one for 24 hours ago (just incase someone has the page still open) and one for the current 24 hours)</p> <p><strong>I guess the same thing could be done individually instead of globally but is there much need for that?</strong></p> <ul> <li><p>Edit <code>custom_logout.php</code> to add a check to see if <code>$_SERVER['HTTP_REFERER']</code> is coming from the same domain (all subdomains). If it is then set <code>matching_referer</code> to true. If not set the variable to false.</p></li> <li><p>Edit <code>custom_logout.php</code> to add a check to see if the query string matches against one stored inside a specific file. (easiest to do with a txt/ini file on the secondary server?) If it matches then set <code>matching_confirm</code> to true. If not set the variable to false.</p></li> <li><p>Edit <code>custom_logout.php</code> and make it so as long if one (any) of the checks are true for it to logout cleanly, if they are both false logout with the warning by sending them to the <code>/wp-login.php?action=logout</code> page?</p></li> </ul>
[ { "answer_id": 253805, "author": "Satbir Kira", "author_id": 80800, "author_profile": "https://wordpress.stackexchange.com/users/80800", "pm_score": 2, "selected": true, "text": "<p>You can create a file called custom_logout.php and place it in the root wordpress directory. This contains </p>\n\n<pre><code>&lt;?php \n require_once(\"wp-load.php\"); //load wordpress\n wp_logout(); //logout\n exit(); //end page\n?&gt;\n</code></pre>\n\n<p>Then in your subdomain site open the url with an anchor tag </p>\n\n<pre><code>&lt;a href=\"http://youwebsite.com/custom_logout.php\"&gt;Logout&lt;/a&gt;\n</code></pre>\n\n<p>You can't create a whitelist easily because it would involve checking where the user is coming from using $_SERVER['HTTP_REFERER'] which is unreliable(usually null). There is no simple solution for this unfortunately.</p>\n\n<p><strong>Reply To Your Edit</strong></p>\n\n<p>You are completely free to implement the temporary key approach if that is a responsible compromise. However, instead of two random keys you can send a md5 hash of the current day. Use an identical secret salt on both servers. Now you can simply recompute yesterday's hash and the current day's in custom_logout.php and compare it to the get variable that is incoming. It eliminates the need for a txt/ini file.</p>\n" }, { "answer_id": 254092, "author": "shramee", "author_id": 92887, "author_profile": "https://wordpress.stackexchange.com/users/92887", "pm_score": 2, "selected": false, "text": "<p>Assuming you are the administrator of both sites...</p>\n\n<p>Add admin ajax handler in your main wp site...</p>\n\n<pre><code>add_action( 'wp_ajax_logout', 'my_logout_callback' );\nfunction my_logout_callback() {\n wp_logout(); // Log out\n header('Location: http://www.example.com/successfully-logged-out');// Maybe redirect user somewhere?\n wp_die();\n}\n</code></pre>\n\n<p>In your subdomain site link to main site's admin ajax handler...</p>\n\n<pre><code>&lt;a href='//example.com/wp-admin/admin-ajax.php?action=logout'&gt;Logout&lt;/a&gt;\n</code></pre>\n" } ]
2016/03/25
[ "https://wordpress.stackexchange.com/questions/221751", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91245/" ]
Similar to the question over at [Get wp\_logout\_url function to work on external (non-Wordpress) page](https://wordpress.stackexchange.com/questions/72547/get-wp-logout-url-function-to-work-on-external-non-wordpress-page) The problem I am facing is the fact the subdomain is on a different server so I am unable to include/require the `wp-blog-header.php` file. Is there a way that I can whitelist domains that can allow instant logouts, like you can for the [redirect whitelist](https://codex.wordpress.org/Plugin_API/Filter_Reference/allowed_redirect_hosts). If not, how can I allow subdomains (it has remote sql access) to create a valid logout link that bypasses the "Are you sure you want to logout" notice. Re: @SatbirKira =============== Does this like a logical work around to make sure the logout is "valid" to a certain degree: * Set the logout URL every 24 hours to have a query string with a random string appended to it for example: `http://website.com/custom_logout.php?confirm=sj239ks`, followed by `http://website.com/custom_logout.php?confirm=32k9la3` Each time it changes it would edit a specific file (custom\_logout.php on the other server OR a txt/ini file on its own server OR other server) and create an array/list of strings ``` $confirmkeys = array("sj239ks", "32k9la3"); ``` or ``` [confirmkeys] confirm[] = sj239ks confirm[] = 32k9la3 ``` It would only ever have 2 confirm keys in the file, one for 24 hours ago (just incase someone has the page still open) and one for the current 24 hours) **I guess the same thing could be done individually instead of globally but is there much need for that?** * Edit `custom_logout.php` to add a check to see if `$_SERVER['HTTP_REFERER']` is coming from the same domain (all subdomains). If it is then set `matching_referer` to true. If not set the variable to false. * Edit `custom_logout.php` to add a check to see if the query string matches against one stored inside a specific file. (easiest to do with a txt/ini file on the secondary server?) If it matches then set `matching_confirm` to true. If not set the variable to false. * Edit `custom_logout.php` and make it so as long if one (any) of the checks are true for it to logout cleanly, if they are both false logout with the warning by sending them to the `/wp-login.php?action=logout` page?
You can create a file called custom\_logout.php and place it in the root wordpress directory. This contains ``` <?php require_once("wp-load.php"); //load wordpress wp_logout(); //logout exit(); //end page ?> ``` Then in your subdomain site open the url with an anchor tag ``` <a href="http://youwebsite.com/custom_logout.php">Logout</a> ``` You can't create a whitelist easily because it would involve checking where the user is coming from using $\_SERVER['HTTP\_REFERER'] which is unreliable(usually null). There is no simple solution for this unfortunately. **Reply To Your Edit** You are completely free to implement the temporary key approach if that is a responsible compromise. However, instead of two random keys you can send a md5 hash of the current day. Use an identical secret salt on both servers. Now you can simply recompute yesterday's hash and the current day's in custom\_logout.php and compare it to the get variable that is incoming. It eliminates the need for a txt/ini file.
221,760
<p>I have a function that stores the "like" status for a post as post meta. I want to associate that "like" with the user that liked it, so I setup a custom field called "like_status_{user_id}" (where {user_id} is the id of the currently logged in user) which I store as a 0 or 1. So for a post with several "likes" there would be several meta values in the db that are setup like this:</p> <pre><code>'meta_key' = 'like_status_0' 'meta_value' = 1 'meta_key' = 'like_status_2' 'meta_value' = 1 'meta_key' = 'like_status_34' 'meta_value' = 1 </code></pre> <p>....and so on.</p> <p>There are potentially thousands of likes on a specific post. How would I run a query that showed if someone else also liked that post?</p> <p>I was thinking something like this:</p> <pre><code>$query = new WP_Query(array( 'meta_key' =&gt; 'like_status_{user_id}', 'meta_value' =&gt; 1, )); </code></pre> <p>I'm trying to push a notification to everyone who has liked a post when someone else likes that post...something like, "Hey, someone else liked that post you liked. You should go check it out!" But I need a way to find out if anyone else has liked that post and if so, who they would be so I could notify them.</p> <p>If it's not possible, could you suggest a better way of storing this data as post_meta while still keeping the efficiency of quickly updating a single user's like status on a post?</p>
[ { "answer_id": 221763, "author": "LonnyLot", "author_id": 20697, "author_profile": "https://wordpress.stackexchange.com/users/20697", "pm_score": -1, "selected": false, "text": "<p>Per the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query#Accepted_Arguments\" rel=\"nofollow\">WP_Meta_Query</a> documentation you can use the <code>compare</code> argument in the <code>meta_query</code> argument of WP_Query. However, you can only compare on the <code>value</code> and not the <code>key</code> so you may want to re-think how you structure this.</p>\n\n<p>A <code>like</code> argument would look like this:</p>\n\n<pre><code>$arguments = array(\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'foo',\n 'value' =&gt; 'ba',\n 'compare' =&gt; 'LIKE'\n )\n )\n);\n\n$query = new WP_Query($arguments);\n</code></pre>\n\n<p>Given that you can't do a 'LIKE' search on the <code>key</code> I'd suggest you add the liked posts in the user meta and do a <a href=\"https://codex.wordpress.org/Class_Reference/WP_User_Query\" rel=\"nofollow\">WP_User_Query</a> search for users who have liked that post:</p>\n\n<pre><code>$arguments = array(\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'liked_post',\n 'value' =&gt; '&lt;post_id&gt;'\n )\n )\n);\n\n$users = new WP_User_Query($arguments);\n</code></pre>\n" }, { "answer_id": 221766, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": false, "text": "<p>It is quite difficult to concretely answer your question. The first part is easy though. I recently did something <a href=\"https://stackoverflow.com/a/35310763/1908141\">similar on stackoverflow</a></p>\n\n<p>Meta keys are are compared and match exactly. <code>WP_Query</code> have no means to adjust this behavior with a simple parameter, but we can always introduce one ourselves and then adjust the <code>posts_where</code> clause to do a <code>LIKE</code> comparison on meta keys.</p>\n\n<h2>THE FILTER</h2>\n\n<p>This is just a basic filter, adjust it as needed. </p>\n\n<pre><code>add_filter( 'posts_where', function ( $where, \\WP_Query $q )\n{ \n // Check for our custom query var\n if ( true !== $q-&gt;get( 'wildcard_on_key' ) )\n return $where;\n\n // Lets filter the clause\n $where = str_replace( 'meta_key =', 'meta_key LIKE', $where );\n\n return $where;\n}, 10, 2 );\n</code></pre>\n\n<p>As you can see, the filter is only fired when we set our new custom parameter, <code>wildcard_on_key</code> to <code>true</code>. When this checks out, we simply change the <code>=</code> comparator to the <code>LIKE</code> comparator</p>\n\n<p>Just a note on this, <code>LIKE</code> comparisons are inherently more expensive to run that other comparisons</p>\n\n<h2>THE QUERY</h2>\n\n<p>You can simply query your posts as follow to get all posts with meta keys <code>like_status_{user_id}</code></p>\n\n<pre><code>$args = [\n 'wildcard_on_key' =&gt; true,\n 'meta_query' =&gt; [\n [\n 'key' =&gt; 'like_status_',\n 'value' =&gt; 1,\n ]\n ]\n];\n$query = new WP_Query( $args );\n</code></pre>\n\n<h2>OTHER QUESTION</h2>\n\n<p>Custom fields does not have impact on performance, you can read my post on this subject <a href=\"https://wordpress.stackexchange.com/a/167151/31545\">here</a>. I am however troubled by that you say each post can have hundreds or thousands of likes. This can hit you on performance getting and caching such a large amount of custom field data. It can also clog your db with a huge amount of unnecessary custom field data which makes it quite hard to maintain.</p>\n\n<p>I am not a very big fan of storing serialized data in custom fields as one cannot search or order by serialized data. I would however suggest storing all the user ID's in an array under one custom field. You can simply just update the array with the user ID when a user like a post. Getting the custom field data and looping over the array of ID's and doing something with the ID's are easy. Just have a look at <code>get_post_meta()</code> </p>\n\n<p>Updating a custom field is also easy. For that, you will need to look into <a href=\"https://developer.wordpress.org/reference/functions/update_post_meta/\" rel=\"noreferrer\"><code>update_post_meta()</code></a>, I do not know how you create your custom fields, but <code>update_post_meta()</code> is definitely something you would want to use.</p>\n\n<p>If you need to send emails or push notifications when a custom field is updated, you have the following hooks available to work with. (<em>See <a href=\"https://developer.wordpress.org/reference/functions/update_metadata/\" rel=\"noreferrer\"><code>update_metadata()</code></a> for context</em>)</p>\n\n<ul>\n<li><p><a href=\"https://developer.wordpress.org/reference/hooks/update_postmeta/\" rel=\"noreferrer\">update_postmeta</a></p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/hooks/updated_meta_type_meta/\" rel=\"noreferrer\">updated_{$meta_type}_meta</a></p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/hooks/updated_postmeta/\" rel=\"noreferrer\">updated_postmeta</a></p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/hooks/update_meta_type_meta/\" rel=\"noreferrer\">update_{$meta_type}_meta</a></p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/hooks/update_meta_type_metadata/\" rel=\"noreferrer\">update_{$meta_type}_metadata</a></p></li>\n</ul>\n\n<h2>CONCLUSION</h2>\n\n<p>Just before I post this, again, before you go the serialized route, make sure that you would not need to sort by the sorted data or search for particular data inside the serialized data.</p>\n" }, { "answer_id": 221768, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 4, "selected": true, "text": "<p>Unfortunately you cannot perform a <code>meta_query</code> using a <code>LIKE</code> comparison on the <code>meta_key</code> value when using <code>WP_Query</code>. I've been down this road...</p>\n<p>Instead you have a couple other options if you want to maintain like status relationships as post meta and not user meta and or meta in a custom table.</p>\n<h2>Option 1</h2>\n<ul>\n<li>requires no modification of your meta schema</li>\n<li>uses <code>wpdb</code> class to perform a custom query</li>\n</ul>\n<p>Example:</p>\n<pre><code>//when a user likes a post...\n$current_user_id = get_current_user_id();\nadd_post_meta($current_user_id, &quot;like_status_{$current_user_id}&quot;, 1, false);\n\n//later in the request...\nglobal $wpdb;\n\n$results = $wpdb-&gt;get_results(\n &quot;\n SELECT meta_key \n FROM {$wpdb-&gt;prefix}postmeta \n WHERE meta_key \n LIKE 'like_status_%'\n &quot;,\n ARRAY_N\n);\n\n$results = array_map(function($value){\n\n return (int) str_replace('like_status_', '', $value[0]);\n\n}, $results);\n\narray_walk($results, function($notify_user_id, $key){\n\n //apply to all users except the user who just liked the post\n if ( $notify_user_id !== $current_user_id ) {\n //notify logic here... \n }\n\n});\n</code></pre>\n<p><sub> Note: logic could be simplified further if you wish.</sub></p>\n<h2>Option 2</h2>\n<ul>\n<li>requires you change your meta schema</li>\n<li>requires you store the user id as the meta value</li>\n<li>allows you to use <code>WP_Query</code> along with <code>meta_query</code></li>\n</ul>\n<p>Option 2 requires that you change your meta key from <code>like_status_{user_id}</code> to something universal such as <code>like_status</code> or <code>liked_by_user_id</code> where in turn instead of storing the value of <code>1</code> against the key, you instead store the user's id as the value.</p>\n<pre><code>//when a user likes a post...\n$current_user_id = get_current_user_id();\nadd_post_meta($current_user_id, &quot;liked_by_user_id&quot;, $current_user_id, false);\n\n//later in the request\n$args = array(\n 'post_type' =&gt; 'post', //or a post type of your choosing\n 'posts_per_page' =&gt; -1,\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'liked_by_user_id',\n 'value' =&gt; 0,\n 'type' =&gt; 'numeric'\n 'compare' =&gt; '&gt;'\n )\n )\n);\n\n$query = new WP_Query($args); \n\narray_walk($query-&gt;posts, function($post, $key){\n\n $user_ids = get_post_meta($post-&gt;ID, 'liked_by_user_id');\n\n array_walk($user_ids, function($notify_user_id, $key){\n \n //notify all users except the user who just like the post\n if ( $notify_user_id !== $current_user_id ) {\n \n //notify logic here...\n //get user e.g. $user = get_user_by('id', $notify_user_id);\n \n }\n\n });\n\n});\n</code></pre>\n" }, { "answer_id": 221780, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": false, "text": "<p>If later on you want to extend this, with more detailed statistics, features, etc, then yet another alternative could be: <strong>custom table(s)</strong></p>\n\n<ul>\n<li><p><em>pros</em>: Tailored to your needs and can be <em>indexed</em> for better performance. </p></li>\n<li><p><em>cons</em>: More work</p></li>\n</ul>\n\n<p>There might also be a workaround using a custom taxonomy, that could give better query performance than post meta queries, due to how the core tables are indexed.</p>\n\n<blockquote>\n <p>I'm trying to push a notification to everyone who has liked a post\n when someone else likes that post...something like, \"Hey, someone else\n liked that post you liked. You should go check it out!\" But I need a\n way to find out if anyone else has liked that post and if so, who they\n would be so I could notify them.</p>\n</blockquote>\n\n<p>Not sure what kind of notifications you mean here, but this can quickly get bulky.</p>\n\n<p><strong>Example</strong>: A user that likes ~ 1000 posts and each post gets ~ 1000 likes, then there are 1M notifications in the pipes, only for that user! If these are email notifications then the host provider might not be happy and the user would go crazy. That might also be expensive with a 3rd party email service.</p>\n" }, { "answer_id": 330083, "author": "K. Tromp", "author_id": 119355, "author_profile": "https://wordpress.stackexchange.com/users/119355", "pm_score": 3, "selected": false, "text": "<p>Since wordpress 5.1 it is possible now to use meta query like:\n<img src=\"https://i.stack.imgur.com/NzgSg.jpg\" alt=\"enter image description here\"></p>\n" } ]
2016/03/26
[ "https://wordpress.stackexchange.com/questions/221760", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17864/" ]
I have a function that stores the "like" status for a post as post meta. I want to associate that "like" with the user that liked it, so I setup a custom field called "like\_status\_{user\_id}" (where {user\_id} is the id of the currently logged in user) which I store as a 0 or 1. So for a post with several "likes" there would be several meta values in the db that are setup like this: ``` 'meta_key' = 'like_status_0' 'meta_value' = 1 'meta_key' = 'like_status_2' 'meta_value' = 1 'meta_key' = 'like_status_34' 'meta_value' = 1 ``` ....and so on. There are potentially thousands of likes on a specific post. How would I run a query that showed if someone else also liked that post? I was thinking something like this: ``` $query = new WP_Query(array( 'meta_key' => 'like_status_{user_id}', 'meta_value' => 1, )); ``` I'm trying to push a notification to everyone who has liked a post when someone else likes that post...something like, "Hey, someone else liked that post you liked. You should go check it out!" But I need a way to find out if anyone else has liked that post and if so, who they would be so I could notify them. If it's not possible, could you suggest a better way of storing this data as post\_meta while still keeping the efficiency of quickly updating a single user's like status on a post?
Unfortunately you cannot perform a `meta_query` using a `LIKE` comparison on the `meta_key` value when using `WP_Query`. I've been down this road... Instead you have a couple other options if you want to maintain like status relationships as post meta and not user meta and or meta in a custom table. Option 1 -------- * requires no modification of your meta schema * uses `wpdb` class to perform a custom query Example: ``` //when a user likes a post... $current_user_id = get_current_user_id(); add_post_meta($current_user_id, "like_status_{$current_user_id}", 1, false); //later in the request... global $wpdb; $results = $wpdb->get_results( " SELECT meta_key FROM {$wpdb->prefix}postmeta WHERE meta_key LIKE 'like_status_%' ", ARRAY_N ); $results = array_map(function($value){ return (int) str_replace('like_status_', '', $value[0]); }, $results); array_walk($results, function($notify_user_id, $key){ //apply to all users except the user who just liked the post if ( $notify_user_id !== $current_user_id ) { //notify logic here... } }); ``` Note: logic could be simplified further if you wish. Option 2 -------- * requires you change your meta schema * requires you store the user id as the meta value * allows you to use `WP_Query` along with `meta_query` Option 2 requires that you change your meta key from `like_status_{user_id}` to something universal such as `like_status` or `liked_by_user_id` where in turn instead of storing the value of `1` against the key, you instead store the user's id as the value. ``` //when a user likes a post... $current_user_id = get_current_user_id(); add_post_meta($current_user_id, "liked_by_user_id", $current_user_id, false); //later in the request $args = array( 'post_type' => 'post', //or a post type of your choosing 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'liked_by_user_id', 'value' => 0, 'type' => 'numeric' 'compare' => '>' ) ) ); $query = new WP_Query($args); array_walk($query->posts, function($post, $key){ $user_ids = get_post_meta($post->ID, 'liked_by_user_id'); array_walk($user_ids, function($notify_user_id, $key){ //notify all users except the user who just like the post if ( $notify_user_id !== $current_user_id ) { //notify logic here... //get user e.g. $user = get_user_by('id', $notify_user_id); } }); }); ```
221,769
<p>I want to set a number of plugin options set to blank if they are not defined so I can avoid the PHP notices.</p> <p>What is a better way of writing this code?</p> <pre><code>$options = get_option('plugin_options'); // Add new plugin options defaults here if( !isset( $options['plugin_option_1'] ) ) $options['plugin_option_1'] = ''; if( !isset( $options['plugin_option_2'] ) ) $options['plugin_option_2'] = ''; if( !isset( $options['plugin_option_3'] ) ) $options['plugin_option_3'] = ''; if( !isset( $options['plugin_option_4'] ) ) $options['plugin_option_4'] = ''; if( !isset( $options['plugin_option_5'] ) ) $options['plugin_option_5'] = ''; </code></pre> <p>New options would need to be added in future updates to the plugin.</p>
[ { "answer_id": 221771, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 1, "selected": false, "text": "<p>Example:</p>\n\n<pre><code>/**\n* assume $options only has three keys defined\n* \n* array(\n* 'plugin_option_1',\n* 'plugin_option_2',\n* 'plugin_option_3',\n* )\n*/\n$options = get_options('my_options');\n\n$schema = array(\n 'plugin_option_1',\n 'plugin_option_2',\n 'plugin_option_3',\n 'plugin_option_4',\n 'plugin_option_5',\n 'plugin_option_8',\n 'plugin_option_9',\n 'plugin_option_10',\n);\n\nforeach ( $schema as $option ) {\n\n if ( ! array_key_exists($option, $options) ) {\n $options[$option] = '';\n }\n\n}\n</code></pre>\n\n<p>Albeit the above example shows you one way to simplify the process, I don't understand why you would be checking for the existence of an undefined key and then assigning it an empty value unless you specifically need to return a sane default? </p>\n\n<p>Why can't you just do...?</p>\n\n<pre><code>if ( !empty($options['some_key']) ) {\n //do my logic...\n}\n</code></pre>\n" }, { "answer_id": 221774, "author": "engelen", "author_id": 40403, "author_profile": "https://wordpress.stackexchange.com/users/40403", "pm_score": 3, "selected": true, "text": "<p>WordPress provides a default method, <a href=\"http://php.net/manual/en/function.array-merge.php\" rel=\"nofollow\"><code>wp_parse_args</code></a>, to combine a set of default options and a user-defined set of options. This method uses PHP's native <a href=\"http://php.net/manual/en/function.array-merge.php\" rel=\"nofollow\"><code>array_merge</code></a> for arrays, but also works when either of the two option sets is an object or a WordPress <a href=\"https://developer.wordpress.org/reference/functions/wp_parse_str/\" rel=\"nofollow\">options string</a>.</p>\n\n<p>You simply provide an array of default options and an array of set options, and WordPress fills the options that are missing in the options set by their default value.</p>\n\n<p>You can find this code, adjusted for your example, below:</p>\n\n<pre><code>$options = get_option( 'plugin_options' );\n$options_default = array(\n 'plugin_option_1' =&gt; '',\n 'plugin_option_2' =&gt; '',\n 'plugin_option_3' =&gt; '',\n 'plugin_option_4' =&gt; '',\n 'plugin_option_5' =&gt; ''\n);\n\n$options = wp_parse_args( $options, $options_default );\n</code></pre>\n" }, { "answer_id": 221788, "author": "Jevuska", "author_id": 18731, "author_profile": "https://wordpress.stackexchange.com/users/18731", "pm_score": 0, "selected": false, "text": "<p>Since you have plugin options in array ( with keys ), lets assume your scenario like this:</p>\n\n<p>Your <strong>old</strong> option is <code>$old = get_option( 'plugin_options' );</code>contain this:</p>\n\n<pre><code>$old = array(\n 'plugin_option_1' =&gt; '1',\n 'plugin_option_2' =&gt; '2',\n 'plugin_option_3' =&gt; '3',\n 'plugin_option_4' =&gt; '4',\n 'plugin_option_5' =&gt; '5'\n);\n</code></pre>\n\n<p>Your <strong>new</strong> option is <code>$new</code> contain this array for updated:</p>\n\n<pre><code>$new = array(\n 'plugin_option_2' =&gt; '9',\n 'plugin_option_5' =&gt; '10'\n);\n</code></pre>\n\n<p><strong>Now on plugin update</strong> </p>\n\n<pre><code>foreach ( $old as $key =&gt; $value )\n $old[ $key ] = ( ! isset( $new[ $key ] ) ) ? '' : $new[ $key ];\n\nupdate_option( 'plugin_options', $old );\n</code></pre>\n\n<p><strong>With PHP 7</strong></p>\n\n<pre><code>foreach ( $old as $key =&gt; $value )\n $old[ $key ] = ( $new[ $key ] ) ?? '';\n\nupdate_option( 'plugin_options', $old );\n</code></pre>\n\n<p><strong>Result on</strong> <code>print_r( $old )</code>:</p>\n\n<pre><code>Array\n(\n [plugin_option_1] =&gt; \n [plugin_option_2] =&gt; 9\n [plugin_option_3] =&gt; \n [plugin_option_4] =&gt; \n [plugin_option_5] =&gt; 10\n)\n</code></pre>\n" } ]
2016/03/26
[ "https://wordpress.stackexchange.com/questions/221769", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70831/" ]
I want to set a number of plugin options set to blank if they are not defined so I can avoid the PHP notices. What is a better way of writing this code? ``` $options = get_option('plugin_options'); // Add new plugin options defaults here if( !isset( $options['plugin_option_1'] ) ) $options['plugin_option_1'] = ''; if( !isset( $options['plugin_option_2'] ) ) $options['plugin_option_2'] = ''; if( !isset( $options['plugin_option_3'] ) ) $options['plugin_option_3'] = ''; if( !isset( $options['plugin_option_4'] ) ) $options['plugin_option_4'] = ''; if( !isset( $options['plugin_option_5'] ) ) $options['plugin_option_5'] = ''; ``` New options would need to be added in future updates to the plugin.
WordPress provides a default method, [`wp_parse_args`](http://php.net/manual/en/function.array-merge.php), to combine a set of default options and a user-defined set of options. This method uses PHP's native [`array_merge`](http://php.net/manual/en/function.array-merge.php) for arrays, but also works when either of the two option sets is an object or a WordPress [options string](https://developer.wordpress.org/reference/functions/wp_parse_str/). You simply provide an array of default options and an array of set options, and WordPress fills the options that are missing in the options set by their default value. You can find this code, adjusted for your example, below: ``` $options = get_option( 'plugin_options' ); $options_default = array( 'plugin_option_1' => '', 'plugin_option_2' => '', 'plugin_option_3' => '', 'plugin_option_4' => '', 'plugin_option_5' => '' ); $options = wp_parse_args( $options, $options_default ); ```
221,773
<p>I'm not sure why this is not working as its a very simple query. It works when i pull all posts including pending, but not when i want to get posts that are only published.</p> <p>I have a function to get posts. I pass in a bool variable. If its true, i want to pull all posts from a custom post type called books, including ones that are pending/draft. If false i only want the published posts. I see no issues with the code, but it wont work.</p> <pre><code>$args = array( 'post_type' =&gt; 'book', 'showposts' =&gt; -1, 'tax_query' =&gt; array('relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'book-category', 'field' =&gt; 'term_id', 'terms' =&gt; $termid) ), 'orderby' =&gt; 'date', 'order' =&gt; 'ASC' ); if($getpending == true) $args["post_status"] = "any"; else $args["post_status"] = "publish"; $posts = query_posts($args); </code></pre>
[ { "answer_id": 221775, "author": "engelen", "author_id": 40403, "author_profile": "https://wordpress.stackexchange.com/users/40403", "pm_score": 3, "selected": true, "text": "<p>First off, you probably shouldn't be using <code>query_posts</code>, which modifies WordPress' main loop and is unsuited for pretty much any purpose (read <a href=\"https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts\">When should you use WP_Query vs query_posts() vs get_posts()?</a> for more info). There are numerous reasons why <code>query_posts</code> wouldn't work as expected in this case.</p>\n\n<p>WordPress has two proper approaches to fetching posts: the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\"><code>WP_Query</code></a> object and the <a href=\"https://codex.wordpress.org/Template_Tags/get_posts\" rel=\"nofollow noreferrer\"><code>get_posts</code></a> function. They work very similarly, with <code>get_posts</code> using <code>WP_Query</code> internally. However, as one would expect, <code>WP_Query</code> allows for more control.</p>\n\n<p>For your case, <code>get_posts</code> should work (as there is no further flaw in the code you posted).</p>\n" }, { "answer_id": 221779, "author": "WP-Silver", "author_id": 5344, "author_profile": "https://wordpress.stackexchange.com/users/5344", "pm_score": 0, "selected": false, "text": "<p>Try using a custom query instead <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/WP_Query</a> as using query_posts() <a href=\"https://codex.wordpress.org/Function_Reference/query_posts\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/query_posts</a> isn't meant to be used by plugins or themes.</p>\n\n<p>Replace your code with this one:</p>\n\n<pre><code>$args = array( \n 'post_type' =&gt; 'book',\n 'posts_per_page' =&gt; -1,\n 'tax_query' =&gt; array(\n 'relation' =&gt; 'AND',\n array( 'taxonomy' =&gt; 'book-category', \n 'field' =&gt; 'term_id', \n 'terms' =&gt; $termid\n )\n ),\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'ASC'\n );\n\n if($getpending == true) \n $args[\"post_status\"] = \"any\";\n else \n $args[\"post_status\"] = \"publish\";\n\n $ustom_posts = new WP_Query($args);\n if($ustom_posts-&gt;have_posts())\n {\n $ustom_posts-&gt;the_post();\n\n //echo $post-&gt;post_title; \n //your further code\n }\n</code></pre>\n" }, { "answer_id": 221846, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>Apart from the use of <code>query_posts</code>, you have another issue, and that is the local use of global <code>$posts</code> variable. <code>$posts</code> is the global used to hold the main query's posts array. Never use global variables as local variables. Changing global variables is really bad as you break their original and intended values, which is really hard to debug. Instead of using <code>$posts</code>, use a custom variable like <code>$posts_array</code>.</p>\n\n<p>You most probably also do not need the custom query, but if you do, use <code>WP_Query</code> or <code>get_posts()</code>, never use <code>query_posts</code>. I have discussed everything in detail in <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">this post</a> which also linked to a couple of very important posts.</p>\n\n<p>Just to quickly touch on few other points:</p>\n\n<ul>\n<li><p>You should really work on your code's indentation and separation. Your code is a bit hard to read and to debug when you cram so many things into one long line. </p></li>\n<li><p>You should be careful setting <code>post_status</code> to <code>any</code> as this will expose <code>private</code> posts to non logged in users, it will also show <code>future</code> posts which is not published yet. This might also expose custom statuses that you would not want to show. Rather explicitly set the post statuses you need.</p>\n\n<p>From <code>query.php</code></p>\n\n<pre><code>if ( in_array( 'any', $q_status ) ) {\n foreach ( get_post_stati( array( 'exclude_from_search' =&gt; true ) ) as $status ) {\n if ( ! in_array( $status, $q_status ) ) {\n $e_status[] = \"$wpdb-&gt;posts.post_status &lt;&gt; '$status'\";\n }\n }\n} else {\n</code></pre>\n\n<p>Note: <code>'exclude_from_search' =&gt; true</code> means only <code>trash</code> and <code>auto-draft</code> are excluded from <code>any</code></p></li>\n<li><p><code>showposts</code> have been dropped in favor of <code>posts_per_page</code>. It is not depreciated, but if used, it gets converted into <code>posts_per_page</code>, so why not use <code>posts_per_page</code> from the start</p>\n\n<pre><code>if ( isset($q['showposts']) &amp;&amp; $q['showposts'] ) {\n $q['showposts'] = (int) $q['showposts'];\n $q['posts_per_page'] = $q['showposts'];\n}\n</code></pre></li>\n<li><p>You don't need to set arguments to their default values. You can simply leave that out and save extra space and time</p></li>\n</ul>\n\n<p>If this is a secondary query, you can probably look at something like the following: (<em>Requires PHP 5.4+</em>)</p>\n\n<pre><code>$args = [\n 'post_type' =&gt; 'book',\n 'posts_per_page' =&gt; -1,\n 'order' =&gt; 'ASC'\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; 'book-category', \n 'terms' =&gt; $termid\n ]\n ],\n];\n\nif ( true == $getpending ) {\n if ( is_user_logged_in() ) { // This can be adjusted to match core\n $args[\"post_status\"] = ['publish', 'private', 'draft'];\n } else {\n $args[\"post_status\"] = ['publish', 'draft'];\n }\n}\n\n$posts_array = WP_Query( $args );\n</code></pre>\n\n<p>I do believe, looking at the <code>terms</code> value in you <code>tax_query</code>, this might be the main query. If so, you should really look into <code>pre_get_posts</code> to alter the main query</p>\n" } ]
2016/03/26
[ "https://wordpress.stackexchange.com/questions/221773", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190834/" ]
I'm not sure why this is not working as its a very simple query. It works when i pull all posts including pending, but not when i want to get posts that are only published. I have a function to get posts. I pass in a bool variable. If its true, i want to pull all posts from a custom post type called books, including ones that are pending/draft. If false i only want the published posts. I see no issues with the code, but it wont work. ``` $args = array( 'post_type' => 'book', 'showposts' => -1, 'tax_query' => array('relation' => 'AND', array( 'taxonomy' => 'book-category', 'field' => 'term_id', 'terms' => $termid) ), 'orderby' => 'date', 'order' => 'ASC' ); if($getpending == true) $args["post_status"] = "any"; else $args["post_status"] = "publish"; $posts = query_posts($args); ```
First off, you probably shouldn't be using `query_posts`, which modifies WordPress' main loop and is unsuited for pretty much any purpose (read [When should you use WP\_Query vs query\_posts() vs get\_posts()?](https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts) for more info). There are numerous reasons why `query_posts` wouldn't work as expected in this case. WordPress has two proper approaches to fetching posts: the [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query) object and the [`get_posts`](https://codex.wordpress.org/Template_Tags/get_posts) function. They work very similarly, with `get_posts` using `WP_Query` internally. However, as one would expect, `WP_Query` allows for more control. For your case, `get_posts` should work (as there is no further flaw in the code you posted).
221,791
<p>I have problem displaying child page content on parent page (both static). I can display other page content but only if on same level. It dosent work in relation parent - child. </p> <pre><code>&lt;?php $investor_content_query = new WP_Query( array( 'pagename' =&gt; 'current', 'post_parent' =&gt; 'investor-relations' ) ); if ( $investor_content_query-&gt;have_posts() ) { while ( $investor_content_query-&gt;have_posts() ) { $investor_content_query-&gt;the_post(); the_content(); } } wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 221792, "author": "frogg3862", "author_id": 83367, "author_profile": "https://wordpress.stackexchange.com/users/83367", "pm_score": 1, "selected": false, "text": "<p>You were being too specific/not passing the correct parameters into your <code>wp_query</code>.\nThis should get you what you're looking for:</p>\n\n<pre><code>&lt;?php\n$current_page_id = get_the_id();\n$investor_content_query = new WP_Query( 'post_parent'=&gt; $current_page_id ) );\nif ( $investor_content_query-&gt;have_posts() ) {\n while ( $investor_content_query-&gt;have_posts() ) {\n $investor_content_query-&gt;the_post();\n the_content();\n }\n}\nwp_reset_postdata();\n?&gt;\n</code></pre>\n" }, { "answer_id": 221796, "author": "Maciek Wrona", "author_id": 89711, "author_profile": "https://wordpress.stackexchange.com/users/89711", "pm_score": 1, "selected": true, "text": "<p>Ok, i found solution. What I really needed was parent page slug in \"pagename\" argument. </p>\n\n<pre><code>'pagename'=&gt; 'investor-relations/current'\n</code></pre>\n\n<p><em>And working solution:</em></p>\n\n<pre><code>&lt;?php\n $investor_content_query = new WP_Query( array(\n 'pagename'=&gt; 'investor-relations/current'\n ) );\n if ( $investor_content_query-&gt;have_posts() ) {\n while ( $investor_content_query-&gt;have_posts() )\n {\n $investor_content_query-&gt;the_post();\n the_content();\n }\n }\n wp_reset_postdata();\n?&gt;\n</code></pre>\n" } ]
2016/03/26
[ "https://wordpress.stackexchange.com/questions/221791", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89711/" ]
I have problem displaying child page content on parent page (both static). I can display other page content but only if on same level. It dosent work in relation parent - child. ``` <?php $investor_content_query = new WP_Query( array( 'pagename' => 'current', 'post_parent' => 'investor-relations' ) ); if ( $investor_content_query->have_posts() ) { while ( $investor_content_query->have_posts() ) { $investor_content_query->the_post(); the_content(); } } wp_reset_postdata(); ?> ```
Ok, i found solution. What I really needed was parent page slug in "pagename" argument. ``` 'pagename'=> 'investor-relations/current' ``` *And working solution:* ``` <?php $investor_content_query = new WP_Query( array( 'pagename'=> 'investor-relations/current' ) ); if ( $investor_content_query->have_posts() ) { while ( $investor_content_query->have_posts() ) { $investor_content_query->the_post(); the_content(); } } wp_reset_postdata(); ?> ```
221,800
<p>I want to display image title and caption inside a <code>&lt;p&gt;</code> tag in single post in <code>the_content()</code> function for every image that has one. So for example if I add gallery, and define title for every image, I want to have above every image it's title displayed, and below every image it's caption displayed, and also for all single images if they have title defined. To visually express it: <a href="https://i.stack.imgur.com/FHzHU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FHzHU.png" alt="enter image description here"></a></p>
[ { "answer_id": 221807, "author": "SBP", "author_id": 91269, "author_profile": "https://wordpress.stackexchange.com/users/91269", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://wordpress.stackexchange.com/questions/74515/add-filter-and-changing-output-captions-of-image-gallery\">The answer is here</a> but you will need to edit the code and extract only what you need.</p>\n\n<p>see the last lines of code, the title is wrapped in a h3 tag.</p>\n" }, { "answer_id": 221815, "author": "SBP", "author_id": 91269, "author_profile": "https://wordpress.stackexchange.com/users/91269", "pm_score": 1, "selected": true, "text": "<p>I got a few minutes and made the custom code for you.\nCopy and paste this in your themes functions.php</p>\n\n<pre><code>remove_shortcode('gallery', 'gallery_shortcode');\nadd_shortcode('gallery', 'gallery_shortcode_custom');\nfunction gallery_shortcode_custom( $attr ) {\n $post = get_post();\n\n static $instance = 0;\n $instance++;\n\n if ( ! empty( $attr['ids'] ) ) {\n // 'ids' is explicitly ordered, unless you specify otherwise.\n if ( empty( $attr['orderby'] ) ) {\n $attr['orderby'] = 'post__in';\n }\n $attr['include'] = $attr['ids'];\n }\n\n /**\n * Filter the default gallery shortcode output.\n *\n * If the filtered output isn't empty, it will be used instead of generating\n * the default gallery template.\n *\n * @since 2.5.0\n * @since 4.2.0 The `$instance` parameter was added.\n *\n * @see gallery_shortcode()\n *\n * @param string $output The gallery output. Default empty.\n * @param array $attr Attributes of the gallery shortcode.\n * @param int $instance Unique numeric ID of this gallery shortcode instance.\n */\n $output = apply_filters( 'post_gallery', '', $attr, $instance );\n if ( $output != '' ) {\n return $output;\n }\n\n $html5 = current_theme_supports( 'html5', 'gallery' );\n $atts = shortcode_atts( array(\n 'order' =&gt; 'ASC',\n 'orderby' =&gt; 'menu_order ID',\n 'id' =&gt; $post ? $post-&gt;ID : 0,\n 'itemtag' =&gt; $html5 ? 'figure' : 'dl',\n 'icontag' =&gt; $html5 ? 'div' : 'dt',\n 'captiontag' =&gt; $html5 ? 'figcaption' : 'dd',\n 'columns' =&gt; 3,\n 'size' =&gt; 'thumbnail',\n 'include' =&gt; '',\n 'exclude' =&gt; '',\n 'link' =&gt; ''\n ), $attr, 'gallery' );\n\n $id = intval( $atts['id'] );\n\n if ( ! empty( $atts['include'] ) ) {\n $_attachments = get_posts( array( 'include' =&gt; $atts['include'], 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; $atts['order'], 'orderby' =&gt; $atts['orderby'] ) );\n\n $attachments = array();\n foreach ( $_attachments as $key =&gt; $val ) {\n $attachments[$val-&gt;ID] = $_attachments[$key];\n }\n } elseif ( ! empty( $atts['exclude'] ) ) {\n $attachments = get_children( array( 'post_parent' =&gt; $id, 'exclude' =&gt; $atts['exclude'], 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; $atts['order'], 'orderby' =&gt; $atts['orderby'] ) );\n } else {\n $attachments = get_children( array( 'post_parent' =&gt; $id, 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; $atts['order'], 'orderby' =&gt; $atts['orderby'] ) );\n }\n\n if ( empty( $attachments ) ) {\n return '';\n }\n\n if ( is_feed() ) {\n $output = \"\\n\";\n foreach ( $attachments as $att_id =&gt; $attachment ) {\n $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . \"\\n\";\n }\n return $output;\n }\n\n $itemtag = tag_escape( $atts['itemtag'] );\n $captiontag = tag_escape( $atts['captiontag'] );\n $icontag = tag_escape( $atts['icontag'] );\n $valid_tags = wp_kses_allowed_html( 'post' );\n if ( ! isset( $valid_tags[ $itemtag ] ) ) {\n $itemtag = 'dl';\n }\n if ( ! isset( $valid_tags[ $captiontag ] ) ) {\n $captiontag = 'dd';\n }\n if ( ! isset( $valid_tags[ $icontag ] ) ) {\n $icontag = 'dt';\n }\n\n $columns = intval( $atts['columns'] );\n $itemwidth = $columns &gt; 0 ? floor(100/$columns) : 100;\n $float = is_rtl() ? 'right' : 'left';\n\n $selector = \"gallery-{$instance}\";\n\n $gallery_style = '';\n\n /**\n * Filter whether to print default gallery styles.\n *\n * @since 3.1.0\n *\n * @param bool $print Whether to print default gallery styles.\n * Defaults to false if the theme supports HTML5 galleries.\n * Otherwise, defaults to true.\n */\n if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {\n $gallery_style = \"\n &lt;style type='text/css'&gt;\n #{$selector} {\n margin: auto;\n }\n #{$selector} .gallery-item {\n float: {$float};\n margin-top: 10px;\n text-align: center;\n width: {$itemwidth}%;\n }\n #{$selector} img {\n border: 2px solid #cfcfcf;\n }\n #{$selector} .gallery-caption {\n margin-left: 0;\n }\n /* see gallery_shortcode() in wp-includes/media.php */\n &lt;/style&gt;\\n\\t\\t\";\n }\n\n $size_class = sanitize_html_class( $atts['size'] );\n $gallery_div = \"&lt;div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'&gt;\";\n\n /**\n * Filter the default gallery shortcode CSS styles.\n *\n * @since 2.5.0\n *\n * @param string $gallery_style Default CSS styles and opening HTML div container\n * for the gallery shortcode output.\n */\n $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );\n\n $i = 0;\n foreach ( $attachments as $id =&gt; $attachment ) {\n\n $attr = ( trim( $attachment-&gt;post_excerpt ) ) ? array( 'aria-describedby' =&gt; \"$selector-$id\" ) : '';\n if ( ! empty( $atts['link'] ) &amp;&amp; 'file' === $atts['link'] ) {\n $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );\n } elseif ( ! empty( $atts['link'] ) &amp;&amp; 'none' === $atts['link'] ) {\n $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );\n } else {\n $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );\n }\n $image_meta = wp_get_attachment_metadata( $id );\n\n $orientation = '';\n if ( isset( $image_meta['height'], $image_meta['width'] ) ) {\n $orientation = ( $image_meta['height'] &gt; $image_meta['width'] ) ? 'portrait' : 'landscape';\n }\n $output .= \"&lt;{$itemtag} class='gallery-item'&gt;\";\n $output .= \"&lt;p&gt;$attachment-&gt;post_title&lt;/p&gt;\";\n $output .= \"\n &lt;{$icontag} class='gallery-icon {$orientation}'&gt;\n $image_output\n &lt;/{$icontag}&gt;\";\n if ( $captiontag &amp;&amp; trim($attachment-&gt;post_excerpt) ) {\n $output .= \"\n &lt;p&gt;\n \" . wptexturize($attachment-&gt;post_excerpt) . \"\n &lt;/p&gt;\";\n }\n $output .= \"&lt;/{$itemtag}&gt;\";\n if ( ! $html5 &amp;&amp; $columns &gt; 0 &amp;&amp; ++$i % $columns == 0 ) {\n $output .= '&lt;br style=\"clear: both\" /&gt;';\n }\n }\n\n if ( ! $html5 &amp;&amp; $columns &gt; 0 &amp;&amp; $i % $columns !== 0 ) {\n $output .= \"\n &lt;br style='clear: both' /&gt;\";\n }\n\n $output .= \"\n &lt;/div&gt;\\n\";\n\n return $output;\n}\n</code></pre>\n\n<p>If you need to add a custom class to your p tag modify</p>\n\n<pre><code>$output .= \"&lt;p&gt;$attachment-&gt;post_title&lt;/p&gt;\";\n</code></pre>\n\n<p>and</p>\n\n<pre><code>&lt;p&gt;\n \" . wptexturize($attachment-&gt;post_excerpt) . \"\n&lt;/p&gt;\";\n</code></pre>\n" } ]
2016/03/26
[ "https://wordpress.stackexchange.com/questions/221800", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70495/" ]
I want to display image title and caption inside a `<p>` tag in single post in `the_content()` function for every image that has one. So for example if I add gallery, and define title for every image, I want to have above every image it's title displayed, and below every image it's caption displayed, and also for all single images if they have title defined. To visually express it: [![enter image description here](https://i.stack.imgur.com/FHzHU.png)](https://i.stack.imgur.com/FHzHU.png)
I got a few minutes and made the custom code for you. Copy and paste this in your themes functions.php ``` remove_shortcode('gallery', 'gallery_shortcode'); add_shortcode('gallery', 'gallery_shortcode_custom'); function gallery_shortcode_custom( $attr ) { $post = get_post(); static $instance = 0; $instance++; if ( ! empty( $attr['ids'] ) ) { // 'ids' is explicitly ordered, unless you specify otherwise. if ( empty( $attr['orderby'] ) ) { $attr['orderby'] = 'post__in'; } $attr['include'] = $attr['ids']; } /** * Filter the default gallery shortcode output. * * If the filtered output isn't empty, it will be used instead of generating * the default gallery template. * * @since 2.5.0 * @since 4.2.0 The `$instance` parameter was added. * * @see gallery_shortcode() * * @param string $output The gallery output. Default empty. * @param array $attr Attributes of the gallery shortcode. * @param int $instance Unique numeric ID of this gallery shortcode instance. */ $output = apply_filters( 'post_gallery', '', $attr, $instance ); if ( $output != '' ) { return $output; } $html5 = current_theme_supports( 'html5', 'gallery' ); $atts = shortcode_atts( array( 'order' => 'ASC', 'orderby' => 'menu_order ID', 'id' => $post ? $post->ID : 0, 'itemtag' => $html5 ? 'figure' : 'dl', 'icontag' => $html5 ? 'div' : 'dt', 'captiontag' => $html5 ? 'figcaption' : 'dd', 'columns' => 3, 'size' => 'thumbnail', 'include' => '', 'exclude' => '', 'link' => '' ), $attr, 'gallery' ); $id = intval( $atts['id'] ); if ( ! empty( $atts['include'] ) ) { $_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) ); $attachments = array(); foreach ( $_attachments as $key => $val ) { $attachments[$val->ID] = $_attachments[$key]; } } elseif ( ! empty( $atts['exclude'] ) ) { $attachments = get_children( array( 'post_parent' => $id, 'exclude' => $atts['exclude'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) ); } else { $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) ); } if ( empty( $attachments ) ) { return ''; } if ( is_feed() ) { $output = "\n"; foreach ( $attachments as $att_id => $attachment ) { $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n"; } return $output; } $itemtag = tag_escape( $atts['itemtag'] ); $captiontag = tag_escape( $atts['captiontag'] ); $icontag = tag_escape( $atts['icontag'] ); $valid_tags = wp_kses_allowed_html( 'post' ); if ( ! isset( $valid_tags[ $itemtag ] ) ) { $itemtag = 'dl'; } if ( ! isset( $valid_tags[ $captiontag ] ) ) { $captiontag = 'dd'; } if ( ! isset( $valid_tags[ $icontag ] ) ) { $icontag = 'dt'; } $columns = intval( $atts['columns'] ); $itemwidth = $columns > 0 ? floor(100/$columns) : 100; $float = is_rtl() ? 'right' : 'left'; $selector = "gallery-{$instance}"; $gallery_style = ''; /** * Filter whether to print default gallery styles. * * @since 3.1.0 * * @param bool $print Whether to print default gallery styles. * Defaults to false if the theme supports HTML5 galleries. * Otherwise, defaults to true. */ if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) { $gallery_style = " <style type='text/css'> #{$selector} { margin: auto; } #{$selector} .gallery-item { float: {$float}; margin-top: 10px; text-align: center; width: {$itemwidth}%; } #{$selector} img { border: 2px solid #cfcfcf; } #{$selector} .gallery-caption { margin-left: 0; } /* see gallery_shortcode() in wp-includes/media.php */ </style>\n\t\t"; } $size_class = sanitize_html_class( $atts['size'] ); $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>"; /** * Filter the default gallery shortcode CSS styles. * * @since 2.5.0 * * @param string $gallery_style Default CSS styles and opening HTML div container * for the gallery shortcode output. */ $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div ); $i = 0; foreach ( $attachments as $id => $attachment ) { $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : ''; if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) { $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr ); } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) { $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr ); } else { $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr ); } $image_meta = wp_get_attachment_metadata( $id ); $orientation = ''; if ( isset( $image_meta['height'], $image_meta['width'] ) ) { $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape'; } $output .= "<{$itemtag} class='gallery-item'>"; $output .= "<p>$attachment->post_title</p>"; $output .= " <{$icontag} class='gallery-icon {$orientation}'> $image_output </{$icontag}>"; if ( $captiontag && trim($attachment->post_excerpt) ) { $output .= " <p> " . wptexturize($attachment->post_excerpt) . " </p>"; } $output .= "</{$itemtag}>"; if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) { $output .= '<br style="clear: both" />'; } } if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) { $output .= " <br style='clear: both' />"; } $output .= " </div>\n"; return $output; } ``` If you need to add a custom class to your p tag modify ``` $output .= "<p>$attachment->post_title</p>"; ``` and ``` <p> " . wptexturize($attachment->post_excerpt) . " </p>"; ```
221,808
<p>I have created custom tables for performance reasons for products, carts, and notifications. I want to make these tables and their data available for normal CRUD via the WP REST API v2. How would I add custom tables (and their columns) to the API so that I could get/update those records?</p>
[ { "answer_id": 253047, "author": "Kosso", "author_id": 111022, "author_profile": "https://wordpress.stackexchange.com/users/111022", "pm_score": 1, "selected": false, "text": "<p>Rather than create custom database tables, you would be better off creating your own custom post types (within Wordpress - Since 4.7.+), along with whatever custom fields you need (as well as taxonomies).</p>\n\n<p>All this can be done as a plugin or via <code>functions.php</code> in a theme. </p>\n\n<p>Here's a very simple but thorough example of how to do this. </p>\n\n<p>It shows how to create a custom post type (called 'acme_products') and its custom fields with the ability for custom taxonomies (categories). All with REST API support built in. It will also show you how to customise the input (meta) boxes for the WP-Admin forms and the columns of the list pages. </p>\n\n<p><a href=\"https://gist.github.com/kosso/47004c9fa71920b441f3cd0c35894409\" rel=\"nofollow noreferrer\">https://gist.github.com/kosso/47004c9fa71920b441f3cd0c35894409</a></p>\n" }, { "answer_id": 263968, "author": "Simon H", "author_id": 70134, "author_profile": "https://wordpress.stackexchange.com/users/70134", "pm_score": 4, "selected": false, "text": "<p>I eventualy worked out a solution for my <code>restaurants</code> table, which sits alongside the <code>wp_*</code> tables in my WP database. Hope this helps</p>\n\n<pre><code>add_action( 'rest_api_init', function () {\n register_rest_route( 'restos/v1', '/all', array(\n 'methods' =&gt; 'GET',\n 'callback' =&gt; 'handle_get_all',\n 'permission_callback' =&gt; function () {\n return current_user_can( 'edit_others_posts' );\n }\n ) );\n} );\n\nfunction handle_get_all( $data ) {\n global $wpdb;\n $query = \"SELECT qname, rname, recommendation FROM `restaurants`\";\n $list = $wpdb-&gt;get_results($query);\n return $list;\n}\n</code></pre>\n\n<p>I have variations on this theme for all the CRUD actions I need</p>\n" }, { "answer_id": 400944, "author": "lortschi", "author_id": 217552, "author_profile": "https://wordpress.stackexchange.com/users/217552", "pm_score": 0, "selected": false, "text": "<p>It has just worked with the rest api v1 for me. The v2 declined the callback permission for selecting the table results. Here is an example endpoint for fetching from custom db table: domain.com/wp-json/test/v1/testing</p>\n<pre><code>add_action( 'rest_api_init', function () {\n $namespace = 'test/v1';\n $route = '/testing';\n\n register_rest_route($namespace, $route, array(\n 'methods' =&gt; WP_REST_Server::READABLE,\n 'callback' =&gt; function () {\n global $wpdb;\n $table = $wpdb-&gt;prefix . 'test';\n $query = &quot;SELECT name, color, etc.. FROM $table&quot;;\n $results = $wpdb-&gt;get_results($query);\n return $results;\n },\n 'permission_callback' =&gt; '__return_true',\n 'args' =&gt; array()\n ));\n });\n</code></pre>\n" } ]
2016/03/26
[ "https://wordpress.stackexchange.com/questions/221808", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17864/" ]
I have created custom tables for performance reasons for products, carts, and notifications. I want to make these tables and their data available for normal CRUD via the WP REST API v2. How would I add custom tables (and their columns) to the API so that I could get/update those records?
I eventualy worked out a solution for my `restaurants` table, which sits alongside the `wp_*` tables in my WP database. Hope this helps ``` add_action( 'rest_api_init', function () { register_rest_route( 'restos/v1', '/all', array( 'methods' => 'GET', 'callback' => 'handle_get_all', 'permission_callback' => function () { return current_user_can( 'edit_others_posts' ); } ) ); } ); function handle_get_all( $data ) { global $wpdb; $query = "SELECT qname, rname, recommendation FROM `restaurants`"; $list = $wpdb->get_results($query); return $list; } ``` I have variations on this theme for all the CRUD actions I need
221,811
<p>I want to use a function like this to allow access to the feeds from a variety of services but my knowledge of the security implications is limited. I think I'm being safe by limiting the access to feeds. </p> <p>What are the dangers (if any) I'm creating if I do this?</p> <pre><code>add_action( 'pre_get_posts', 'add_header_origin' ); function add_header_origin() { if (is_feed()){ header( 'Access-Control-Allow-Origin: *' ); } } </code></pre>
[ { "answer_id": 221926, "author": "Tom Woodward", "author_id": 82797, "author_profile": "https://wordpress.stackexchange.com/users/82797", "pm_score": 0, "selected": false, "text": "<p>I read <a href=\"https://stackoverflow.com/questions/15853633/is-there-any-secure-way-to-allow-cross-site-ajax-requests\">this post</a> as saying that as long as I'm not requiring login credentials (I'm not) that all is well. </p>\n" }, { "answer_id": 300188, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>You need to have a super great reason to disable CORS, as no real reason was given here the answer should be \"do not do it, it is not secure\".</p>\n\n<p>You assume that no one can craft a feed link which will give him a write access. This might be true, but you should not open holes in your security based on \"assuming\".</p>\n\n<p>In the very least, if some other domain needs \"AJAX\" access to your feeds, you should disable CORS only for that specific domain.</p>\n\n<p>In addition <code>pre_get_posts</code> is totally the wrong place to do it, and you should do it on <code>init</code>. The way your code is currently written it may disable CORS for pages which are not feed.</p>\n" }, { "answer_id": 393661, "author": "Alex Molodoi", "author_id": 210565, "author_profile": "https://wordpress.stackexchange.com/users/210565", "pm_score": 0, "selected": false, "text": "<p>Please be aware that setting <code>Access-Control-Allow-Origin: *</code> only instructs browsers if they're supposed to consume the response. That header has no effect on requests made server side (curl, python, node) regardless of this setting.</p>\n" } ]
2016/03/26
[ "https://wordpress.stackexchange.com/questions/221811", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82797/" ]
I want to use a function like this to allow access to the feeds from a variety of services but my knowledge of the security implications is limited. I think I'm being safe by limiting the access to feeds. What are the dangers (if any) I'm creating if I do this? ``` add_action( 'pre_get_posts', 'add_header_origin' ); function add_header_origin() { if (is_feed()){ header( 'Access-Control-Allow-Origin: *' ); } } ```
You need to have a super great reason to disable CORS, as no real reason was given here the answer should be "do not do it, it is not secure". You assume that no one can craft a feed link which will give him a write access. This might be true, but you should not open holes in your security based on "assuming". In the very least, if some other domain needs "AJAX" access to your feeds, you should disable CORS only for that specific domain. In addition `pre_get_posts` is totally the wrong place to do it, and you should do it on `init`. The way your code is currently written it may disable CORS for pages which are not feed.
221,850
<p>Just today I synchronized a development website database with a production website database. </p> <p>Now, my development website gives a "404 Not Found" error. The URL starts with HTTPS, and there is a red slash through the HTTPS text. The 404 page says "The server can not find the requested page: dev.greenbee-web.com/ilaimh/wp-admin/ (port 443). Apache Server at dev.greenbee-web.com Port 443".</p> <p>I did not realize that the production website uses HTTPS ( I am an employee and so I'm not the only one working on this website). This made the development website now use HTTPS, but I want it to use HTTP. I can't figure out where, in any of WordPress's configuration files, I can make the development website go back to using HTTP.</p> <p>Is there some setting in wp-config that is forcing my development site to use HTTPS? If not in wp-config, where is the setting that is forcing the site to use HTTPS?</p> <p>Thank you</p>
[ { "answer_id": 221970, "author": "Elektra", "author_id": 91391, "author_profile": "https://wordpress.stackexchange.com/users/91391", "pm_score": 3, "selected": false, "text": "<p>There are 2 things you must do.</p>\n\n<p>If you are using Apache server go to .htaccess and change the Rewrite and RewriteBase engine to </p>\n\n<pre><code>RewriteEngine On\n\nRewriteCond %{SERVER_PORT} ^443$\nRewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]\n\nRewriteBase /\nRewriteRule ^index.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</code></pre>\n\n<p>If you are using Nginx something like this should work</p>\n\n<pre><code>server {\n listen 80 443;\n server_name example.com;\n # add ssl settings\n return 301 https://example.com$request_uri;\n}\n</code></pre>\n\n<p>This would redirect the https to http </p>\n\n<p>and go to the database through phpmyadmin or whatever you use \ngo to wp_options and find and change the siteurl and home values from <a href=\"https://example.com\" rel=\"noreferrer\">https://example.com</a> to <a href=\"http://example.com\" rel=\"noreferrer\">http://example.com</a> </p>\n\n<p>Clean your cache and try again. It should work without problem.\nIf the site still asks for SSL check your wp-config.php file to see if it has this code </p>\n\n<pre><code>define('FORCE_SSL_ADMIN', true);\n</code></pre>\n\n<p>then change the 'true' to 'false'</p>\n\n<p>Hope this helps you.</p>\n" }, { "answer_id": 279093, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": -1, "selected": false, "text": "<p>Your development and staging enviroment should always match as much as possible the production enviroment. Not using the same protocol is a very big deviation which is not even justified in any way. </p>\n\n<p>Since it is your organization, just install the same certificate on your dev enviroment, or if it is bound to a specific IP for some reason, generate a new one for your dev enviroment.</p>\n" }, { "answer_id": 316785, "author": "haz", "author_id": 99009, "author_profile": "https://wordpress.stackexchange.com/users/99009", "pm_score": 2, "selected": false, "text": "<p>There's a couple of factors here.</p>\n\n<p>First of all, you might want to check the site settings in <strong>wp_options</strong> (or <strong>wp_X_options</strong> if you're in a multisite setup), especially the value of:</p>\n\n<ul>\n<li>home</li>\n<li>siteurl</li>\n</ul>\n\n<p>The other tables you want to check are:</p>\n\n<ul>\n<li>wp_blogs</li>\n<li>wp_domain_mapping</li>\n<li>wp_options</li>\n<li>wp_site</li>\n<li>wp_sitemeta</li>\n</ul>\n\n<p>I don't know what sort of system you guys use to sync your dev DB with prod, but we have an SQL script we run after we clone a subset of the prod database.</p>\n\n<pre><code>UPDATE wp_dev.wp_blogs SET domain = REPLACE(domain, \"https://produrl.com\", \"http://devurl.com\");\nUPDATE wp_dev.wp_domain_mapping SET domain = REPLACE(domain, \"https://produrl.com\", \"http://devurl.com\");\nUPDATE wp_dev.wp_options SET option_value = REPLACE(option_value, \"https://produrl.com\", \"http://devurl.com\");\nUPDATE wp_dev.wp_site SET domain = REPLACE(domain, \"https://produrl.com\", \"http://devurl.com\");\nUPDATE wp_dev.wp_sitemeta SET meta_value = REPLACE(meta_value, \"https://produrl.com\", \"http://devurl.com\");\n</code></pre>\n\n<p>Replace <code>wp_dev</code> with your local database, and <code>produrl.com</code> and <code>devurl.com</code> as necessary. But notice that this changes the internal URLs from HTTPS to HTTP.</p>\n\n<p>Finally, you may need to change your local WP config, and update these two settings:</p>\n\n<pre><code>define('FORCE_SSL_LOGIN', false);\ndefine('FORCE_SSL_ADMIN', false);\n</code></pre>\n" }, { "answer_id": 330557, "author": "Dave Jackson", "author_id": 162437, "author_profile": "https://wordpress.stackexchange.com/users/162437", "pm_score": 0, "selected": false, "text": "<p>Thank you Loic.\nIm using BackupBuddy to copy my active websites and restore on WAMP.\nOne of the sites kept trying to use HTTPS. Ive been trying to install a cert on local wamp without any luck.</p>\n\n<p>I did look at the directory of my locally restored site and removed the simple ssl folder.</p>\n\n<p>Boom. It works now and stays on HTTP</p>\n\n<p>Man that that was too easy. Thanks again.</p>\n" }, { "answer_id": 407053, "author": "Victor Pudeyev", "author_id": 223425, "author_profile": "https://wordpress.stackexchange.com/users/223425", "pm_score": 0, "selected": false, "text": "<p>If the load balancer terminates ssl (https), then wordpress will receive http traffic and redirect to https, even though the traffic to the LB is https, resulting in infinite redirect.</p>\n<p>To solve this, I have this in my wp-config.php:</p>\n<pre><code> $_SERVER['HTTPS'] = 'on';\n</code></pre>\n<p>Or slightly more complicated (for custom installs):</p>\n<pre><code> if (getenv('use_ssl')) {\n $_SERVER['HTTPS'] = 'on';\n }\n</code></pre>\n" } ]
2016/03/27
[ "https://wordpress.stackexchange.com/questions/221850", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75669/" ]
Just today I synchronized a development website database with a production website database. Now, my development website gives a "404 Not Found" error. The URL starts with HTTPS, and there is a red slash through the HTTPS text. The 404 page says "The server can not find the requested page: dev.greenbee-web.com/ilaimh/wp-admin/ (port 443). Apache Server at dev.greenbee-web.com Port 443". I did not realize that the production website uses HTTPS ( I am an employee and so I'm not the only one working on this website). This made the development website now use HTTPS, but I want it to use HTTP. I can't figure out where, in any of WordPress's configuration files, I can make the development website go back to using HTTP. Is there some setting in wp-config that is forcing my development site to use HTTPS? If not in wp-config, where is the setting that is forcing the site to use HTTPS? Thank you
There are 2 things you must do. If you are using Apache server go to .htaccess and change the Rewrite and RewriteBase engine to ``` RewriteEngine On RewriteCond %{SERVER_PORT} ^443$ RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L] RewriteBase / RewriteRule ^index.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] ``` If you are using Nginx something like this should work ``` server { listen 80 443; server_name example.com; # add ssl settings return 301 https://example.com$request_uri; } ``` This would redirect the https to http and go to the database through phpmyadmin or whatever you use go to wp\_options and find and change the siteurl and home values from <https://example.com> to <http://example.com> Clean your cache and try again. It should work without problem. If the site still asks for SSL check your wp-config.php file to see if it has this code ``` define('FORCE_SSL_ADMIN', true); ``` then change the 'true' to 'false' Hope this helps you.
221,858
<p>In wordpress, to use $ instead of jQuery prefix, i added the following code around all js code:</p> <pre><code>jQuery(function($) { ... }); </code></pre> <p>It works well, but i cannot call an object from another javascript file, the following problem persists:</p> <pre><code>Slider is not defined </code></pre> <p>This is my code:</p> <p><strong>file1.js</strong></p> <pre><code>jQuery(function($) { var slider = new Slider(); }); </code></pre> <p><strong>file2.js</strong></p> <pre><code>jQuery(function($) { function Slider() { this.nb_ele = 10; } }); </code></pre> <p>It seems that because the workspace of two js files is different so they can't call function from another one. Any solution?</p>
[ { "answer_id": 221863, "author": "Adam", "author_id": 66648, "author_profile": "https://wordpress.stackexchange.com/users/66648", "pm_score": 3, "selected": true, "text": "<p>The issue you have is that <code>Slider</code> is not accessible outside of its scope as that's defined by the <code>.ready()</code> though you've used shorthand for that. The function needs to be available in the global scope:</p>\n\n<p>file1.js</p>\n\n<pre><code>function Slider() {\n this.nb_ele = 10;\n}\n\njQuery(function($) {\n // ...\n});\n</code></pre>\n\n<p>file2.js</p>\n\n<pre><code>jQuery(function($) {\n var slider = new Slider();\n}); \n</code></pre>\n\n<p>If you want Slider to stay in the document ready, you'll need to use a function expression to add the function to the global object:</p>\n\n<pre><code>jQuery(function($) {\n window.Slider= function () {\n this.nb_ele = 10;\n };\n});\n</code></pre>\n\n<p>See Also: <a href=\"https://stackoverflow.com/questions/1449435/splitting-up-jquery-functions-across-files\">https://stackoverflow.com/questions/1449435/splitting-up-jquery-functions-across-files</a></p>\n" }, { "answer_id": 221864, "author": "LoicTheAztec", "author_id": 79855, "author_profile": "https://wordpress.stackexchange.com/users/79855", "pm_score": 2, "selected": false, "text": "<p>I had the same kind of problem. </p>\n\n<p>You can also solve it with:</p>\n\n<pre><code>var $ = jQuery.noConflict();\n$(document).ready(function(){\n\nyour code in here\n\n});\n</code></pre>\n\n<p>You need also to use that trick in all of your javascript files, i mean <code>var $ = jQuery.noConflict();</code>.</p>\n\n<p>After that <strong>Dammeul</strong> is right.</p>\n" } ]
2016/03/27
[ "https://wordpress.stackexchange.com/questions/221858", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85161/" ]
In wordpress, to use $ instead of jQuery prefix, i added the following code around all js code: ``` jQuery(function($) { ... }); ``` It works well, but i cannot call an object from another javascript file, the following problem persists: ``` Slider is not defined ``` This is my code: **file1.js** ``` jQuery(function($) { var slider = new Slider(); }); ``` **file2.js** ``` jQuery(function($) { function Slider() { this.nb_ele = 10; } }); ``` It seems that because the workspace of two js files is different so they can't call function from another one. Any solution?
The issue you have is that `Slider` is not accessible outside of its scope as that's defined by the `.ready()` though you've used shorthand for that. The function needs to be available in the global scope: file1.js ``` function Slider() { this.nb_ele = 10; } jQuery(function($) { // ... }); ``` file2.js ``` jQuery(function($) { var slider = new Slider(); }); ``` If you want Slider to stay in the document ready, you'll need to use a function expression to add the function to the global object: ``` jQuery(function($) { window.Slider= function () { this.nb_ele = 10; }; }); ``` See Also: <https://stackoverflow.com/questions/1449435/splitting-up-jquery-functions-across-files>
221,867
<p>I am literally pulling my hair out trying to figure this out. I have been at it for almost 12 hours now.</p> <p>Being new to PHP and theme development I am having a hard time understanding how to get <code>theme_options('value');</code> to display when putting in a PHP stylesheet.</p> <p>I have taken an example off a blog post I read <a href="https://josephscott.org/archives/2010/03/database-powered-css-in-wordpress-themes/" rel="nofollow">here</a> using the parse_request method.</p> <p>code in <code>header.php</code></p> <pre><code>&lt;link rel='stylesheet' type='text/css' href="&lt;?php echo get_template_directory() ?&gt;/css/theme_styles.php?my-custom-content=css" /&gt; </code></pre> <p>and in <code>theme-styles.php</code></p> <pre><code>&lt;?php add_action( 'parse_request', 'my_custom_wp_request' ); function my_custom_wp_request( $wp ) { if ( !empty( $_GET['my-custom-content'] ) &amp;&amp; $_GET['my-custom-content'] == 'css' ) { # get theme options header( 'Content-Type: text/css' ); ?&gt; a { color: &lt;?php echo get_option('some_other_option') ?&gt; !important; } &lt;?php exit; } } ?&gt; </code></pre> <p>That's all it says to do in the post so now I am lost. I have tried many other solutions that also did not work. Any help is appreciated!</p>
[ { "answer_id": 221868, "author": "Jevuska", "author_id": 18731, "author_profile": "https://wordpress.stackexchange.com/users/18731", "pm_score": 0, "selected": false, "text": "<h2>CSS customizable by manipulate parse_query</h2>\n<p><em>@Scott Reinmuth</em>, I think you misdirection about those tutorials, yes you use <a href=\"https://developer.wordpress.org/reference/hooks/parse_request/\" rel=\"nofollow noreferrer\"><code>parse_request</code></a> method.</p>\n<p>If you follow, this code is a hook with function and you need to put in <strong>functions.php</strong></p>\n<pre><code>&lt;?php\n add_action( 'parse_request', 'my_custom_wp_request' );\n function my_custom_wp_request( $wp ) {\n if ( !empty( $_GET['my-custom-content'] ) &amp;&amp; $_GET['my-custom-content'] == 'css' ) {\n # get theme options\n header( 'Content-Type: text/css' );\n?&gt;\na {color: &lt;?php echo get_option('some_other_option'); ?&gt; !important;}\n&lt;?php\n exit; \n }\n }\n?&gt;\n</code></pre>\n<p>And in <strong>header.php</strong> with this code ( without file <strong>/css/theme_styles.php</strong> ) to make a request with parameter <code>my-custom-content</code> and value <code>css</code>. Thats why we need a hook with function to make it work.</p>\n<pre><code>&lt;link rel='stylesheet' type='text/css' href=&quot;&lt;?php bloginfo( 'url' ); ?&gt;/?my-custom-content=css&quot; /&gt;\n</code></pre>\n<p>we done here.</p>\n<hr />\n<p>BUT if you need to use css in out side function, then you create <strong>custom-css.php</strong>. And your function in <strong>functions.php</strong> will be like this:</p>\n<pre><code>add_action( 'parse_request', 'my_custom_wp_request' );\nfunction my_custom_wp_request( $wp ) {\n if ( !empty( $_GET['my-custom-content'] ) &amp;&amp; $_GET['my-custom-content'] == 'css' ) {\n # get theme options\n header( 'Content-Type: text/css' );\n require dirname( __FILE__ ) . '/css/custom-css.php';\n exit;\n }\n} \n</code></pre>\n<p>and inside your <strong>custom-css.php</strong></p>\n<pre><code>a {\n color: &lt;?php echo get_option('some_other_option'); ?&gt; !important;\n} \n</code></pre>\n<p>In <strong>header.php</strong> still the same above.</p>\n<hr />\n<h3>Similar approach with validate</h3>\n<p>My similar approach with validate data. We just use file <code>functions.php</code> theme to add this code.</p>\n<pre><code>/** Enqueue style for custom css\n * we use parameter wpse_css and ( int ) 1 as value\n *\n */\nadd_action( 'wp_enqueue_scripts', 'wpse221867_enqueue_style', 99 );\nfunction wpse221867_enqueue_style()\n{\n /** check url ssl */\n $url = ( is_ssl() ) ?\n home_url( '/', 'https' ) : home_url( '/' );\n \n /** Register and enqueue wpse_style_php\n * Build query with wpse_css as parameter, 1 as number to validation\n *\n */\n wp_register_style( 'wpse_style_php',\n add_query_arg( array(\n 'wpse_css' =&gt; ( int ) 1\n ), $url ),\n array(), //your style handled\n null, //remove wp version\n 'all' //media\n );\n wp_enqueue_style( 'wpse_style_php' );\n}\n\n/** Fire parse_request with function wpse221867_print_css\n * Generate css in PHP\n *\n * @return string CSS Content\n */\nadd_action( 'parse_request', 'wpse221867_print_css' );\nfunction wpse221867_print_css()\n{\n /** validate query on input */\n $css = filter_input( INPUT_GET, 'wpse_css', FILTER_VALIDATE_INT );\n \n if ( ! $css || ( int ) 1 != $css )\n return;\n \n ob_start();\n header( 'Content-type: text/css' );\n \n /** wpse_option_settings contain css in an array i.e\n * array( 'wpse_css_content' =&gt; 'a{color:#ececec}' )\n *\n */\n $options = get_option( 'wpse_option_settings' );\n $raw_css = ( isset( $options['wpse_css_content'] ) )\n ? $options['wpse_css_content'] : '';\n \n /** sanitize for output */\n $content = wp_kses( $raw_css,\n array( '\\'', '\\&quot;' )\n );\n $content = str_replace( '&amp;gt;', '&gt;', $content );\n echo $content; // output\n die();\n}\n</code></pre>\n<blockquote>\n<p>IMHO, this method not recommended, especially for performance issue. Just use static css file, find another way to make it your css customizable, please take a look <a href=\"https://codex.wordpress.org/Function_Reference/wp_add_inline_style#Examples\" rel=\"nofollow noreferrer\"><code>wp_add_inline_style</code></a> ( example available ) and <a href=\"https://codex.wordpress.org/Function_Reference/get_theme_mod\" rel=\"nofollow noreferrer\"><code>get_theme_mod</code></a>.</p>\n</blockquote>\n" }, { "answer_id": 221921, "author": "Scott Reinmuth", "author_id": 91310, "author_profile": "https://wordpress.stackexchange.com/users/91310", "pm_score": 2, "selected": false, "text": "<p>Although @Jevuska did solve my issue, I have found a much easier solution to adding dynamic CSS from my theme options page. Here we go!</p>\n\n<p>Add this to <strong>functions.php</strong></p>\n\n<pre><code>add_action('wp_head', 'my_custom_css');\nfunction my_custom_css(){\nrequire_once( get_template_directory() . '/css/theme-styles.php' );\n}\n</code></pre>\n\n<p>Now you can treat <strong>theme-styles.php</strong> as a normal CSS stylesheet</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;\na {\n color: &lt;?php echo get_option('some_other_option');?&gt; !important;\n}\n&lt;/style&gt;\n</code></pre>\n\n<p>Done! It was that simple.</p>\n" } ]
2016/03/28
[ "https://wordpress.stackexchange.com/questions/221867", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91310/" ]
I am literally pulling my hair out trying to figure this out. I have been at it for almost 12 hours now. Being new to PHP and theme development I am having a hard time understanding how to get `theme_options('value');` to display when putting in a PHP stylesheet. I have taken an example off a blog post I read [here](https://josephscott.org/archives/2010/03/database-powered-css-in-wordpress-themes/) using the parse\_request method. code in `header.php` ``` <link rel='stylesheet' type='text/css' href="<?php echo get_template_directory() ?>/css/theme_styles.php?my-custom-content=css" /> ``` and in `theme-styles.php` ``` <?php add_action( 'parse_request', 'my_custom_wp_request' ); function my_custom_wp_request( $wp ) { if ( !empty( $_GET['my-custom-content'] ) && $_GET['my-custom-content'] == 'css' ) { # get theme options header( 'Content-Type: text/css' ); ?> a { color: <?php echo get_option('some_other_option') ?> !important; } <?php exit; } } ?> ``` That's all it says to do in the post so now I am lost. I have tried many other solutions that also did not work. Any help is appreciated!
Although @Jevuska did solve my issue, I have found a much easier solution to adding dynamic CSS from my theme options page. Here we go! Add this to **functions.php** ``` add_action('wp_head', 'my_custom_css'); function my_custom_css(){ require_once( get_template_directory() . '/css/theme-styles.php' ); } ``` Now you can treat **theme-styles.php** as a normal CSS stylesheet ``` <style type="text/css"> a { color: <?php echo get_option('some_other_option');?> !important; } </style> ``` Done! It was that simple.
221,880
<p>I am trying to create a part on my wordpress theme that will only display one featured post. I have installed this plugin - <a href="https://wordpress.org/plugins/featured-post/" rel="nofollow">https://wordpress.org/plugins/featured-post/</a> . </p> <p>I know I am supposed to integrate <code>&lt;?php query_posts($query_string."&amp;featured=yes");</code> somewhere into the loop to output the featured post. I tried modifying the code from my existing loop that displays regular posts but the results show the featured post repeated many times.</p> <p>This is the loop I am trying to use that displays the featured post but repeats it a ton of times. How can I get it to only display once?</p> <pre><code>&lt;?php if ( have_posts() ) { while ( have_posts() ) { the_post(); query_posts($query_string . "&amp;featured=yes"); the_author(); if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php the_excerpt();?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; Read More.... &lt;/a&gt; &lt;?php } // end while } // end if ?&gt; </code></pre>
[ { "answer_id": 221882, "author": "Mehul Gohil", "author_id": 37768, "author_profile": "https://wordpress.stackexchange.com/users/37768", "pm_score": 0, "selected": false, "text": "<p>I have just simplified my code. Add a custom field with name \"_featured\" with Yes and No Radio Button and add dummy 5 posts and from which make one post to be featured to Yes and then use below code to display featured post.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 5,\n 'post_status' =&gt; 'publish',\n 'post_type' =&gt; 'post',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; '_featured',\n 'value' =&gt; 'yes'\n )\n )\n);\n\n$the_query = new WP_Query( $args );\n// The Loop\nif ( $the_query-&gt;have_posts() ) {\n echo '&lt;ul&gt;';\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n echo '&lt;li&gt;' . get_the_title() . '&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;';\n} else {\n // no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 221884, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 1, "selected": false, "text": "<p><code>query_posts()</code> can alter the WP query even when it is executed and it should be placed at least before you start the loop i.e. <code>have_posts()</code>. Currently you are placing it after setting up post data i.e. <code>the_post()</code>. Which is resulting in unexpected behavior.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>global $query_string; //Get current query arguments\nquery_posts($query_string.\"&amp;featured=yes\");\n\nif (have_posts()) {\n while (have_posts()) {\n the_post(); ?&gt; \n\n &lt;? php the_author(); ?&gt;\n\n &lt;? php\n if (has_post_thumbnail()) {\n the_post_thumbnail('thumbnail');\n } ?&gt;\n\n &lt;a href = \"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; \n &lt;?php the_excerpt(); ?&gt; \n &lt;a href = \"&lt;?php the_permalink(); ?&gt;\"&gt; Read More.... &lt;/a&gt; \n\n\n &lt;?php\n } // end while\n} // end if\n</code></pre>\n\n<blockquote>\n <p>NOTE: <code>query_posts()</code> is not recommended please ask plugin support to\n provide alternative way to use their plugin!</p>\n</blockquote>\n" } ]
2016/03/28
[ "https://wordpress.stackexchange.com/questions/221880", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91325/" ]
I am trying to create a part on my wordpress theme that will only display one featured post. I have installed this plugin - <https://wordpress.org/plugins/featured-post/> . I know I am supposed to integrate `<?php query_posts($query_string."&featured=yes");` somewhere into the loop to output the featured post. I tried modifying the code from my existing loop that displays regular posts but the results show the featured post repeated many times. This is the loop I am trying to use that displays the featured post but repeats it a ton of times. How can I get it to only display once? ``` <?php if ( have_posts() ) { while ( have_posts() ) { the_post(); query_posts($query_string . "&featured=yes"); the_author(); if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'); } ?> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php the_excerpt();?> <a href="<?php the_permalink(); ?>"> Read More.... </a> <?php } // end while } // end if ?> ```
`query_posts()` can alter the WP query even when it is executed and it should be placed at least before you start the loop i.e. `have_posts()`. Currently you are placing it after setting up post data i.e. `the_post()`. Which is resulting in unexpected behavior. **Example:** ``` global $query_string; //Get current query arguments query_posts($query_string."&featured=yes"); if (have_posts()) { while (have_posts()) { the_post(); ?> <? php the_author(); ?> <? php if (has_post_thumbnail()) { the_post_thumbnail('thumbnail'); } ?> <a href = "<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php the_excerpt(); ?> <a href = "<?php the_permalink(); ?>"> Read More.... </a> <?php } // end while } // end if ``` > > NOTE: `query_posts()` is not recommended please ask plugin support to > provide alternative way to use their plugin! > > >
221,896
<p>I'm trying to set up a form for people to fill in, however I want to split it up into sections so as to not create a long list of different details on just one page.</p> <p>For example:</p> <p>PAGE ONE Includes</p> <ul> <li>First Name:</li> <li>Last Name:</li> <li>Phone:</li> <li>Email:</li> <li>Start Date:</li> <li>Start Time:</li> <li>End Date:</li> <li>End Time:</li> <li>Address: (Multiple address lines)</li> </ul> <p>PAGE TWO Includes</p> <ul> <li>Coverage:</li> <li>Quantity:</li> <li>Subject Information: Etc, etc.</li> </ul> <p>I was wondering if anyone knew if it's possible to split these two steps on different pages whilst keeping the information placed for Page One, without having to send two separate emails.</p> <p>Thanks in advance!</p>
[ { "answer_id": 221882, "author": "Mehul Gohil", "author_id": 37768, "author_profile": "https://wordpress.stackexchange.com/users/37768", "pm_score": 0, "selected": false, "text": "<p>I have just simplified my code. Add a custom field with name \"_featured\" with Yes and No Radio Button and add dummy 5 posts and from which make one post to be featured to Yes and then use below code to display featured post.</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 5,\n 'post_status' =&gt; 'publish',\n 'post_type' =&gt; 'post',\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; '_featured',\n 'value' =&gt; 'yes'\n )\n )\n);\n\n$the_query = new WP_Query( $args );\n// The Loop\nif ( $the_query-&gt;have_posts() ) {\n echo '&lt;ul&gt;';\n while ( $the_query-&gt;have_posts() ) {\n $the_query-&gt;the_post();\n echo '&lt;li&gt;' . get_the_title() . '&lt;/li&gt;';\n }\n echo '&lt;/ul&gt;';\n} else {\n // no posts found\n}\n/* Restore original Post Data */\nwp_reset_postdata();\n</code></pre>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 221884, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 1, "selected": false, "text": "<p><code>query_posts()</code> can alter the WP query even when it is executed and it should be placed at least before you start the loop i.e. <code>have_posts()</code>. Currently you are placing it after setting up post data i.e. <code>the_post()</code>. Which is resulting in unexpected behavior.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>global $query_string; //Get current query arguments\nquery_posts($query_string.\"&amp;featured=yes\");\n\nif (have_posts()) {\n while (have_posts()) {\n the_post(); ?&gt; \n\n &lt;? php the_author(); ?&gt;\n\n &lt;? php\n if (has_post_thumbnail()) {\n the_post_thumbnail('thumbnail');\n } ?&gt;\n\n &lt;a href = \"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; \n &lt;?php the_excerpt(); ?&gt; \n &lt;a href = \"&lt;?php the_permalink(); ?&gt;\"&gt; Read More.... &lt;/a&gt; \n\n\n &lt;?php\n } // end while\n} // end if\n</code></pre>\n\n<blockquote>\n <p>NOTE: <code>query_posts()</code> is not recommended please ask plugin support to\n provide alternative way to use their plugin!</p>\n</blockquote>\n" } ]
2016/03/28
[ "https://wordpress.stackexchange.com/questions/221896", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91338/" ]
I'm trying to set up a form for people to fill in, however I want to split it up into sections so as to not create a long list of different details on just one page. For example: PAGE ONE Includes * First Name: * Last Name: * Phone: * Email: * Start Date: * Start Time: * End Date: * End Time: * Address: (Multiple address lines) PAGE TWO Includes * Coverage: * Quantity: * Subject Information: Etc, etc. I was wondering if anyone knew if it's possible to split these two steps on different pages whilst keeping the information placed for Page One, without having to send two separate emails. Thanks in advance!
`query_posts()` can alter the WP query even when it is executed and it should be placed at least before you start the loop i.e. `have_posts()`. Currently you are placing it after setting up post data i.e. `the_post()`. Which is resulting in unexpected behavior. **Example:** ``` global $query_string; //Get current query arguments query_posts($query_string."&featured=yes"); if (have_posts()) { while (have_posts()) { the_post(); ?> <? php the_author(); ?> <? php if (has_post_thumbnail()) { the_post_thumbnail('thumbnail'); } ?> <a href = "<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php the_excerpt(); ?> <a href = "<?php the_permalink(); ?>"> Read More.... </a> <?php } // end while } // end if ``` > > NOTE: `query_posts()` is not recommended please ask plugin support to > provide alternative way to use their plugin! > > >
221,923
<p>On a page in Wordpress, If I enter the following code:</p> <pre><code>var r='&lt;li&gt;&lt;a href="#"&gt;&lt;img src="' + slide.src + '" width="50" height="50" /&gt;&lt;/a&gt;&lt;/li&gt;'; </code></pre> <p>it is rendered in the browser as</p> <pre><code> var r=' &lt;li&gt;&lt;a href="#"&gt;&lt;img src="' + slide.src + '" width="50" height="50" /&gt;&lt;/a&gt;&lt;/li&gt; '; </code></pre> <p>and it gives me this error in FF Console <code>SyntaxError: unterminated string literal var r='</code></p> <p>This is a single-user blog, so I am "Administrator".</p> <p>How do I prevent Wordpress from fouling my code? </p>
[ { "answer_id": 221951, "author": "markratledge", "author_id": 268, "author_profile": "https://wordpress.stackexchange.com/users/268", "pm_score": 1, "selected": false, "text": "<p>You have to bracket the function in <code>&lt;script&gt;</code> tags and then either</p>\n\n<p>1) take all the whitespace out of the script so WordPress does not add <code>&lt;p&gt;</code> tags and then the JS will work, or</p>\n\n<p>2) disable <code>autop</code> in the post editor for all posts/pages\n(see <a href=\"http://codex.wordpress.org/Function_Reference/wpautop\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/wpautop</a> ) so WP doesn't add paragraph breaks, or</p>\n\n<p>3) do the following, which leaves <code>autop</code> enabled globally, but lets you disable it with and tags in individual posts and pages.</p>\n\n<p><strong>Add the function below to functions.php and use the two tags</strong></p>\n\n<p><code>&lt;!-- noformat on --&gt;</code> and <code>&lt;!-- noformat off --&gt;</code></p>\n\n<p><strong>in your page/post editor, i.e.</strong></p>\n\n<pre><code> text will be rendered *with* autop\n\n &lt;!-- noformat on --&gt;\n\n text will be rendered *without* autop\n\n &lt;!-- noformat off --&gt;\n\n text will be rendered *with* autop\n</code></pre>\n\n<p>Content outside of the two format tags will have autop enabled, as noted.</p>\n\n<p><strong>Add to functions.php of the theme:</strong></p>\n\n<pre><code>// &lt;!-- noformat on --&gt; and &lt;!-- noformat off --&gt; functions\n\nfunction newautop($text)\n{\n $newtext = \"\";\n $pos = 0;\n\n $tags = array('&lt;!-- noformat on --&gt;', '&lt;!-- noformat off --&gt;');\n $status = 0;\n\n while (!(($newpos = strpos($text, $tags[$status], $pos)) === FALSE))\n {\n $sub = substr($text, $pos, $newpos-$pos);\n\n if ($status)\n $newtext .= $sub;\n else\n $newtext .= convert_chars(wptexturize(wpautop($sub))); //Apply both functions (faster)\n\n $pos = $newpos+strlen($tags[$status]);\n\n $status = $status?0:1;\n }\n\n $sub = substr($text, $pos, strlen($text)-$pos);\n\n if ($status)\n $newtext .= $sub;\n else\n $newtext .= convert_chars(wptexturize(wpautop($sub))); //Apply both functions (faster)\n\n //To remove the tags\n $newtext = str_replace($tags[0], \"\", $newtext);\n $newtext = str_replace($tags[1], \"\", $newtext);\n\n return $newtext;\n}\n\nfunction newtexturize($text)\n{\n return $text; \n}\n\nfunction new_convert_chars($text)\n{\n return $text; \n}\n\nremove_filter('the_content', 'wpautop');\nadd_filter('the_content', 'newautop');\n\nremove_filter('the_content', 'wptexturize');\nadd_filter('the_content', 'newtexturize');\n\nremove_filter('the_content', 'convert_chars');\nadd_filter('the_content', 'new_convert_chars');\n</code></pre>\n" }, { "answer_id": 237636, "author": "Philipp", "author_id": 31140, "author_profile": "https://wordpress.stackexchange.com/users/31140", "pm_score": 2, "selected": false, "text": "<p><strong>The Problem</strong></p>\n\n<p>Really annoying! WordPress <code>wpautop</code> parses the whole page and adds line-breaks in HTML code after certain tags.\nUnfortunately WP does not recognize when HTML strings occur inside javascript and this can mess up the JS source code of your page!!</p>\n\n<pre><code>// This breaks your JS code:\n&lt;script&gt;\njson={\"html\":\"&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;\"};\n&lt;/script&gt;\n\n// After wpautop is done with your code it becomes invalid JSON/JS:\n&lt;script&gt;\njson={\"html\":\"&lt;ul&gt;\n&lt;li&gt;one&lt;/li&gt;\n&lt;li&gt;two&lt;/li&gt;\n&lt;/ul&gt;\"};\n&lt;/script&gt;\n</code></pre>\n\n<hr>\n\n<p><strong>★★ Easy solution ★★</strong> </p>\n\n<p><code>wpautop</code> has a small exception built in: It will not add line breaks inside <code>&lt;pre&gt;&lt;/pre&gt;</code> blocks :) We can use this to our advantage, simply by wrapping our <code>&lt;script&gt;</code> tags with <code>&lt;pre&gt;</code>:</p>\n\n<pre><code>// Simple solution!\n&lt;pre&gt;&lt;script&gt;\njson={\"html\":\"&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;\"};\n&lt;/script&gt;&lt;/pre&gt;\n\n// Extra: Add |style| to ensure the empty &lt;pre&gt; block is not rendered:\n&lt;pre style=\"display:none\"&gt;&lt;script&gt;\njson={\"html\":\"&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;\"};\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 326755, "author": "Dave", "author_id": 159921, "author_profile": "https://wordpress.stackexchange.com/users/159921", "pm_score": 3, "selected": false, "text": "<p>In the new WordPress (WP 5+) Editor - Gutenberg, you can use a \"Custom HTML\" block to prevent the automatic line breaks and paragraphs:</p>\n\n<p>on Visual Editor click + > Formatting > Custom HTML - and put your JavaScript in there</p>\n\n<p>on Code Editor enclose your JavaScript with <code>&lt;!-- wp:html --&gt; &lt;!-- /wp:html --&gt;</code></p>\n" }, { "answer_id": 330907, "author": "BaseZen", "author_id": 162643, "author_profile": "https://wordpress.stackexchange.com/users/162643", "pm_score": 0, "selected": false, "text": "<p>This is my version of <code>newautop</code> adapted from above:</p>\n\n<pre><code>function toggleable_autop($text, $filter_state = 'autop_enabled') {\n /* Each tag is associated with the key that will toggle the state from current */\n $filter_driver = [\n 'autop_enabled' =&gt; [ 'tag' =&gt; '&lt;!-- noformat on --&gt;', 'filter' =&gt; function($text) { return convert_chars(wptexturize(wpautop($text))); } ],\n 'autop_disabled' =&gt; [ 'tag' =&gt; '&lt;!-- noformat off --&gt;', 'filter' =&gt; function($text) { return $text; } ],\n ];\n\n if ( strlen($text) === 0 ) {\n return '';\n }\n\n $end_state_position = strpos($text, $filter_driver[$filter_state]['tag']);\n if ( $end_state_position === false ) {\n $end_state_position = strlen($text);\n }\n return $filter_driver[$filter_state]['filter'](substr($text, 0, $end_state_position))\n . toggleable_autop(\n substr($text, $end_state_position + strlen($filter_driver[$filter_state]['tag'])),\n $filter_state === 'autop_enabled' ? 'autop_disabled' : 'autop_enabled'\n );\n}\n</code></pre>\n" } ]
2016/03/28
[ "https://wordpress.stackexchange.com/questions/221923", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51358/" ]
On a page in Wordpress, If I enter the following code: ``` var r='<li><a href="#"><img src="' + slide.src + '" width="50" height="50" /></a></li>'; ``` it is rendered in the browser as ``` var r=' <li><a href="#"><img src="' + slide.src + '" width="50" height="50" /></a></li> '; ``` and it gives me this error in FF Console `SyntaxError: unterminated string literal var r='` This is a single-user blog, so I am "Administrator". How do I prevent Wordpress from fouling my code?
In the new WordPress (WP 5+) Editor - Gutenberg, you can use a "Custom HTML" block to prevent the automatic line breaks and paragraphs: on Visual Editor click + > Formatting > Custom HTML - and put your JavaScript in there on Code Editor enclose your JavaScript with `<!-- wp:html --> <!-- /wp:html -->`
221,930
<p>I'm trying to modify a theme to make it work with my custom fields (I'm using ACF for most of the data I put on pages) for a site with song lyrics on it. The original code was this:</p> <pre><code>$metro_creativex_posttitle = get_the_title(); $metro_creativex_feat_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'single-post-thumbnail' ); if(isset($metro_creativex_feat_image[0])): echo '&lt;div class="img"&gt;'.get_the_post_thumbnail().'&lt;/div&gt;'; endif; </code></pre> <p>It's a piece of the <code>content.php</code> that shows the posts in categories pages. Now, since my posts don't have any featured images but only one or two images via custom fields, my first intent is to replace the 'custom thumbnail' with the single cover art, so first thing first I replaced the <code>get_post_thumbnail</code> with a <code>get_field</code>, and it at least seems to detect whenever a song has or not a single cover picture:</p> <pre><code>$metro_creativex_posttitle = get_the_title(); $metro_creativex_feat_image = wp_get_attachment_image_src( $post-&gt;ID, get_field('sd_single_img'), 'single-post-thumbnail' ); if(isset($metro_creativex_feat_image[0])): echo '&lt;div class="img"&gt;'.get_the_post_thumbnail().'&lt;/div&gt;'; endif; </code></pre> <p>My main problem for now is that I can't understand what I have to write down on the <code>echo</code> to make it show the actual image and not only a blank space above the song title on the category menu: <a href="http://www.thenewblackgold.netsons.org/wp/category/songs/level-1/" rel="nofollow">Link to my page</a></p> <p>How can I fix it?</p>
[ { "answer_id": 221951, "author": "markratledge", "author_id": 268, "author_profile": "https://wordpress.stackexchange.com/users/268", "pm_score": 1, "selected": false, "text": "<p>You have to bracket the function in <code>&lt;script&gt;</code> tags and then either</p>\n\n<p>1) take all the whitespace out of the script so WordPress does not add <code>&lt;p&gt;</code> tags and then the JS will work, or</p>\n\n<p>2) disable <code>autop</code> in the post editor for all posts/pages\n(see <a href=\"http://codex.wordpress.org/Function_Reference/wpautop\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/wpautop</a> ) so WP doesn't add paragraph breaks, or</p>\n\n<p>3) do the following, which leaves <code>autop</code> enabled globally, but lets you disable it with and tags in individual posts and pages.</p>\n\n<p><strong>Add the function below to functions.php and use the two tags</strong></p>\n\n<p><code>&lt;!-- noformat on --&gt;</code> and <code>&lt;!-- noformat off --&gt;</code></p>\n\n<p><strong>in your page/post editor, i.e.</strong></p>\n\n<pre><code> text will be rendered *with* autop\n\n &lt;!-- noformat on --&gt;\n\n text will be rendered *without* autop\n\n &lt;!-- noformat off --&gt;\n\n text will be rendered *with* autop\n</code></pre>\n\n<p>Content outside of the two format tags will have autop enabled, as noted.</p>\n\n<p><strong>Add to functions.php of the theme:</strong></p>\n\n<pre><code>// &lt;!-- noformat on --&gt; and &lt;!-- noformat off --&gt; functions\n\nfunction newautop($text)\n{\n $newtext = \"\";\n $pos = 0;\n\n $tags = array('&lt;!-- noformat on --&gt;', '&lt;!-- noformat off --&gt;');\n $status = 0;\n\n while (!(($newpos = strpos($text, $tags[$status], $pos)) === FALSE))\n {\n $sub = substr($text, $pos, $newpos-$pos);\n\n if ($status)\n $newtext .= $sub;\n else\n $newtext .= convert_chars(wptexturize(wpautop($sub))); //Apply both functions (faster)\n\n $pos = $newpos+strlen($tags[$status]);\n\n $status = $status?0:1;\n }\n\n $sub = substr($text, $pos, strlen($text)-$pos);\n\n if ($status)\n $newtext .= $sub;\n else\n $newtext .= convert_chars(wptexturize(wpautop($sub))); //Apply both functions (faster)\n\n //To remove the tags\n $newtext = str_replace($tags[0], \"\", $newtext);\n $newtext = str_replace($tags[1], \"\", $newtext);\n\n return $newtext;\n}\n\nfunction newtexturize($text)\n{\n return $text; \n}\n\nfunction new_convert_chars($text)\n{\n return $text; \n}\n\nremove_filter('the_content', 'wpautop');\nadd_filter('the_content', 'newautop');\n\nremove_filter('the_content', 'wptexturize');\nadd_filter('the_content', 'newtexturize');\n\nremove_filter('the_content', 'convert_chars');\nadd_filter('the_content', 'new_convert_chars');\n</code></pre>\n" }, { "answer_id": 237636, "author": "Philipp", "author_id": 31140, "author_profile": "https://wordpress.stackexchange.com/users/31140", "pm_score": 2, "selected": false, "text": "<p><strong>The Problem</strong></p>\n\n<p>Really annoying! WordPress <code>wpautop</code> parses the whole page and adds line-breaks in HTML code after certain tags.\nUnfortunately WP does not recognize when HTML strings occur inside javascript and this can mess up the JS source code of your page!!</p>\n\n<pre><code>// This breaks your JS code:\n&lt;script&gt;\njson={\"html\":\"&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;\"};\n&lt;/script&gt;\n\n// After wpautop is done with your code it becomes invalid JSON/JS:\n&lt;script&gt;\njson={\"html\":\"&lt;ul&gt;\n&lt;li&gt;one&lt;/li&gt;\n&lt;li&gt;two&lt;/li&gt;\n&lt;/ul&gt;\"};\n&lt;/script&gt;\n</code></pre>\n\n<hr>\n\n<p><strong>★★ Easy solution ★★</strong> </p>\n\n<p><code>wpautop</code> has a small exception built in: It will not add line breaks inside <code>&lt;pre&gt;&lt;/pre&gt;</code> blocks :) We can use this to our advantage, simply by wrapping our <code>&lt;script&gt;</code> tags with <code>&lt;pre&gt;</code>:</p>\n\n<pre><code>// Simple solution!\n&lt;pre&gt;&lt;script&gt;\njson={\"html\":\"&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;\"};\n&lt;/script&gt;&lt;/pre&gt;\n\n// Extra: Add |style| to ensure the empty &lt;pre&gt; block is not rendered:\n&lt;pre style=\"display:none\"&gt;&lt;script&gt;\njson={\"html\":\"&lt;ul&gt;&lt;li&gt;one&lt;/li&gt;&lt;li&gt;two&lt;/li&gt;&lt;/ul&gt;\"};\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 326755, "author": "Dave", "author_id": 159921, "author_profile": "https://wordpress.stackexchange.com/users/159921", "pm_score": 3, "selected": false, "text": "<p>In the new WordPress (WP 5+) Editor - Gutenberg, you can use a \"Custom HTML\" block to prevent the automatic line breaks and paragraphs:</p>\n\n<p>on Visual Editor click + > Formatting > Custom HTML - and put your JavaScript in there</p>\n\n<p>on Code Editor enclose your JavaScript with <code>&lt;!-- wp:html --&gt; &lt;!-- /wp:html --&gt;</code></p>\n" }, { "answer_id": 330907, "author": "BaseZen", "author_id": 162643, "author_profile": "https://wordpress.stackexchange.com/users/162643", "pm_score": 0, "selected": false, "text": "<p>This is my version of <code>newautop</code> adapted from above:</p>\n\n<pre><code>function toggleable_autop($text, $filter_state = 'autop_enabled') {\n /* Each tag is associated with the key that will toggle the state from current */\n $filter_driver = [\n 'autop_enabled' =&gt; [ 'tag' =&gt; '&lt;!-- noformat on --&gt;', 'filter' =&gt; function($text) { return convert_chars(wptexturize(wpautop($text))); } ],\n 'autop_disabled' =&gt; [ 'tag' =&gt; '&lt;!-- noformat off --&gt;', 'filter' =&gt; function($text) { return $text; } ],\n ];\n\n if ( strlen($text) === 0 ) {\n return '';\n }\n\n $end_state_position = strpos($text, $filter_driver[$filter_state]['tag']);\n if ( $end_state_position === false ) {\n $end_state_position = strlen($text);\n }\n return $filter_driver[$filter_state]['filter'](substr($text, 0, $end_state_position))\n . toggleable_autop(\n substr($text, $end_state_position + strlen($filter_driver[$filter_state]['tag'])),\n $filter_state === 'autop_enabled' ? 'autop_disabled' : 'autop_enabled'\n );\n}\n</code></pre>\n" } ]
2016/03/28
[ "https://wordpress.stackexchange.com/questions/221930", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91366/" ]
I'm trying to modify a theme to make it work with my custom fields (I'm using ACF for most of the data I put on pages) for a site with song lyrics on it. The original code was this: ``` $metro_creativex_posttitle = get_the_title(); $metro_creativex_feat_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); if(isset($metro_creativex_feat_image[0])): echo '<div class="img">'.get_the_post_thumbnail().'</div>'; endif; ``` It's a piece of the `content.php` that shows the posts in categories pages. Now, since my posts don't have any featured images but only one or two images via custom fields, my first intent is to replace the 'custom thumbnail' with the single cover art, so first thing first I replaced the `get_post_thumbnail` with a `get_field`, and it at least seems to detect whenever a song has or not a single cover picture: ``` $metro_creativex_posttitle = get_the_title(); $metro_creativex_feat_image = wp_get_attachment_image_src( $post->ID, get_field('sd_single_img'), 'single-post-thumbnail' ); if(isset($metro_creativex_feat_image[0])): echo '<div class="img">'.get_the_post_thumbnail().'</div>'; endif; ``` My main problem for now is that I can't understand what I have to write down on the `echo` to make it show the actual image and not only a blank space above the song title on the category menu: [Link to my page](http://www.thenewblackgold.netsons.org/wp/category/songs/level-1/) How can I fix it?
In the new WordPress (WP 5+) Editor - Gutenberg, you can use a "Custom HTML" block to prevent the automatic line breaks and paragraphs: on Visual Editor click + > Formatting > Custom HTML - and put your JavaScript in there on Code Editor enclose your JavaScript with `<!-- wp:html --> <!-- /wp:html -->`
221,941
<p>I have added the following code in my <code>functions.php</code> </p> <pre><code>add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 150, 150); </code></pre> <p>My posts display with a thumbnail with the 150x150 dimensions. However, I'd like to change the size. When I change the 150 by 150 in the <code>set_post_thumbnail_size</code> to 200 or any other number, it doesn't actually change the size of my thumbnails. I tried going into media settings and change the size there. In the media settings I can shrink the size, but if I try to change it to 200 or 300 it doesn't actually have any impact.</p> <p>Any idea how I can modify it? </p>
[ { "answer_id": 221954, "author": "Nathan Powell", "author_id": 27196, "author_profile": "https://wordpress.stackexchange.com/users/27196", "pm_score": 1, "selected": false, "text": "<p>The code you are using is correct. The problem is that you are looking at <code>thumbnail</code>s that have already been created. As @Loius mentioned you will need to use <a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow\">Regenerate Thumbnails</a> to see the effect. Why core has not implemented this is beyond me.</p>\n" }, { "answer_id": 317570, "author": "user2584538", "author_id": 85766, "author_profile": "https://wordpress.stackexchange.com/users/85766", "pm_score": 0, "selected": false, "text": "<p><strong>Define your own image sizes</strong></p>\n\n<p>If you need your post thumbnail 50px by 50px without cropping the image as well without distorting it. Here is the solution. These all definitions should define in <code>functions.php</code> file.</p>\n\n<p><code>set_post_thumbnail_size( 50, 50 );</code> // 50 pixels wide by 50 pixels tall, resize mode</p>\n\n<p>As well as you can crop the image as you want. Here is an example for cropping.</p>\n\n<p><code>set_post_thumbnail_size( 50, 50, array( 'top', 'left') );</code> // 50 pixels wide by 50 pixels tall, crop from the top left corner</p>\n\n<p>In the array have pass the where to crop. This will crop the image starting from top left corner. If you need to crop the image from the center, just pass <code>array( 'center', 'center' )</code> . This will crop the image from the center.</p>\n\n<p>Not only these. You can define your own thumbnail name and define the sizes. Assume I need to create a thumbnail image for books category. Therefore I need an image 200px width and height should be auto . Lets see how to do this.</p>\n\n<p><code>add_image_size( 'books', 200, 9999 );</code> //200 pixels wide (and unlimited height)</p>\n\n<p>This will resize the book category image to 200px width and auto height.</p>\n\n<p>You can call this image</p>\n\n<pre><code>&lt;?php the_post_thumbnail( 'books' ); ?&gt;\n</code></pre>\n\n<p>In a proper way you can call this image,</p>\n\n<pre><code>&lt;?php\nif(has_post_thumbnail( 'books' )) {\nthe_post_thumbnail( 'books' );\n}\n?&gt;\n</code></pre>\n\n<p>This will load the image where you define the code and it will be 200px wide and height is relative to the width.</p>\n\n<p>Assume you’re wanting to add this Featured Images for books and all posts except other all custom post types. How to do this. See the code below. It’ll enable the Featured Image for all the posts and custom post type called books only.</p>\n\n<pre><code>add_theme_support( 'post-thumbnails', array( 'post', 'books' ) );\n</code></pre>\n\n<p>Source from <a href=\"https://nerodev.com/creating-post-thumbnails-in-wordpress/\" rel=\"nofollow noreferrer\">nerodev</a></p>\n" } ]
2016/03/28
[ "https://wordpress.stackexchange.com/questions/221941", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91325/" ]
I have added the following code in my `functions.php` ``` add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 150, 150); ``` My posts display with a thumbnail with the 150x150 dimensions. However, I'd like to change the size. When I change the 150 by 150 in the `set_post_thumbnail_size` to 200 or any other number, it doesn't actually change the size of my thumbnails. I tried going into media settings and change the size there. In the media settings I can shrink the size, but if I try to change it to 200 or 300 it doesn't actually have any impact. Any idea how I can modify it?
The code you are using is correct. The problem is that you are looking at `thumbnail`s that have already been created. As @Loius mentioned you will need to use [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/) to see the effect. Why core has not implemented this is beyond me.
221,989
<p>I work on a theme that displays <strong>3 columns</strong> with images, so the size for thumbnails on large displays will be 360x240px.</p> <p>When resized, on some <strong>mobile</strong> devices, like iPhone, there will be just <strong>1 column</strong> with images, which may result that the <strong>featured image will be larger</strong> than 360px in width.</p> <p>Now, in order to maintain a good PageSpeed score, I don't want to load a larger image size on desktop computers and scale it via CSS, but on mobile devices I need the Featured Image to be larger, like 640x426px.</p> <p>The problem in using the same image size on mobile devices is that it may not be large enough to fill 1 column, and would leave some <strong>empty space</strong> next to it.</p> <p>I've registered 2 new image sizes, but it seems that the <code>the_post_thumbnail()</code> function always picks the wrong one.</p> <pre><code>add_image_size( 'loop', 360, 240, true ); add_image_size( 'loop-mobile', 640, 426, true ); </code></pre> <p>I've tried different methods, and none of them is close to what I need: </p> <ol> <li><p><code>the_post_thumbnail();</code></p> <p>In this case the image is too small on mobile devices </p></li> <li><p><code>the_post_thumbnail('loop-mobile');</code></p> <p>In this case it will always load the larger version 640x426px, which affects the PageSpeed score </p></li> <li><p><code>the_post_thumbnail(array(640,426));</code></p> <p>Same problem with PageSpeed score.</p></li> </ol> <p>Thanks for help!</p> <p><a href="https://i.stack.imgur.com/CvDb8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CvDb8.png" alt="3 column on desktop"></a></p> <p><a href="https://i.stack.imgur.com/5bVWS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5bVWS.png" alt="1 column on mobile"></a></p>
[ { "answer_id": 221999, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Your problem comes from not doing responsive design. Responsive design should leave everything to be decided at the client side, attempts to serve something that will match all screen sizes at the server code will usually fail or prevent you from using caching.</p>\n\n<p>The ideal solution is the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Example_3_Using_the_srcset_attribute\" rel=\"nofollow\">srcset</a> attribute <sup><a href=\"http://w3c.github.io/html/semantics-embedded-content.html#element-attrdef-img-srcset\" rel=\"nofollow\">W3C HTML 5+ docs</a></sup>, unfortionatly its default <a href=\"https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/\" rel=\"nofollow\">implementation in wordpress</a> sucks and you will need to use relevant API to have it match the images as you want them to be, where you want them to be.</p>\n\n<p>Note: srcset is just a recommendation to the browser it does not have to follow, if you do not want to leave it to the mercy of browsers, you will need to find a JS library that does similar things.</p>\n" }, { "answer_id": 232811, "author": "Andy Macaulay-Brook", "author_id": 94267, "author_profile": "https://wordpress.stackexchange.com/users/94267", "pm_score": 2, "selected": false, "text": "<p>The answer is to use WP's responsive images, customising the sizes attribute to suit your use case.</p>\n\n<p>Reading between the lines, I'm assuming here that you are using a responsive design approach to show the different layouts at different widths.</p>\n\n<p>The easiest way is to start by making yourself a replacement template tag function for <code>the_post_thumbnail</code>:</p>\n\n<pre><code>function wpse_221989_the_post_thumbnail( $size, $attr ) {\n the_post_thumbnail( $size, $attr );\n}\n</code></pre>\n\n<p>Where you call <code>the_post_thumbnail</code> in your templates, call <code>wpse_221989_the_post_thumbnail</code> instead. Why do we do it like this? WP doesn't give you any context on the filter hooks to modify <code>srcset</code> and <code>sizes</code> attributes for responsive images, so we are making our own context with the <code>wpse_221989_the_post_thumbnail</code> wrapper function.</p>\n\n<p>So far, nothing clever, but now we can build upon this function to:</p>\n\n<p>1 - draw on a set of image sizes</p>\n\n<p>2 - ask the browser to choose a suitable image depending upon your responsive breakpoint for this particular use case</p>\n\n<p>1 - In your instance, where your image versions are all the same aspect ratio, WP handles things for us. Using a built-in image call like <code>the_post_thumbnail</code> will build a <code>srcset</code> attribute from every image size you have with the same aspect ratio as the image specified in the <code>$size</code> parameter. You can use <code>add_image_size</code> to create additional versions large enough for high density displays too. WP's match on aspect ratio allows for small rounding errors, so both the sizes in your question should be matched OK.</p>\n\n<p>2 - To get the browser to choose the right image size for the space, you will need a custom <code>sizes</code> attribute. WP's default <code>sizes</code> attribute assumes that you want an image to be full browser width, but no wider than the image's natural width. In your design, narrower screens need the larger image and then above a certain breakpoint you want to choose the smaller image width.</p>\n\n<p>So, assuming from your image sizes that your breakpoint is at <code>640px</code>, we'd want a <code>sizes</code> attribute a bit like this: <code>(min-width: 640px) 33.333vw, 100vw</code></p>\n\n<p>What this says to the browser is for windows of <code>640px</code> width and over, choose the image from the <code>srcset</code> list that best matches a third of the window width. For other window widths (&lt; 640px) choose an image from the list that best fits the full window width.</p>\n\n<p>To put that into code we make a new function to return the attribute and build it into our wrapper function:</p>\n\n<pre><code>function wpse_221989_sizes() {\n\n return \"(min-width: 640px) 33.333vw, 100vw\";\n\n}\n\nfunction wpse_221989_the_post_thumbnail( $size, $attr ) {\n\n add_filter( 'wp_calculate_image_sizes', 'wpse_221989_sizes', 10 , 2 );\n the_post_thumbnail( $size, $attr );\n remove_filter( 'wp_calculate_image_sizes', 'wpse_221989_sizes', 10 );\n\n}\n</code></pre>\n\n<p>Now when your theme template calls <code>wpse_221989_the_post_thumbnail</code> our custom <code>sizes</code> attribute will be substituted for the default. By hooking into the filter before calling <code>the_post_thumbnail</code> and unhooking immediately after we make our custom template tag function sensitive to the context of your question without upsetting any sizes attributes generated on images in other parts of your theme.</p>\n\n<p>You can build upon this by putting in conditional checks on <code>$size</code> to choose different rules for the various image versions you've created for your theme to use.</p>\n\n<p>If Google Pagespeed is important to you then test to see that it is obeying your <code>srcset</code> and <code>sizes</code> attributes. If not, then use <code>add_image_size</code> to make a size that just fits the Pagespeed window and use that size in your calls to <code>wpse_221989_the_post_thumbnail</code> so that it is put into the <code>src</code> attribute. On my sites I use a 1024px image as the default which seems to keep both desktop and mobile Pagespeed analyses happy.</p>\n" } ]
2016/03/29
[ "https://wordpress.stackexchange.com/questions/221989", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9162/" ]
I work on a theme that displays **3 columns** with images, so the size for thumbnails on large displays will be 360x240px. When resized, on some **mobile** devices, like iPhone, there will be just **1 column** with images, which may result that the **featured image will be larger** than 360px in width. Now, in order to maintain a good PageSpeed score, I don't want to load a larger image size on desktop computers and scale it via CSS, but on mobile devices I need the Featured Image to be larger, like 640x426px. The problem in using the same image size on mobile devices is that it may not be large enough to fill 1 column, and would leave some **empty space** next to it. I've registered 2 new image sizes, but it seems that the `the_post_thumbnail()` function always picks the wrong one. ``` add_image_size( 'loop', 360, 240, true ); add_image_size( 'loop-mobile', 640, 426, true ); ``` I've tried different methods, and none of them is close to what I need: 1. `the_post_thumbnail();` In this case the image is too small on mobile devices 2. `the_post_thumbnail('loop-mobile');` In this case it will always load the larger version 640x426px, which affects the PageSpeed score 3. `the_post_thumbnail(array(640,426));` Same problem with PageSpeed score. Thanks for help! [![3 column on desktop](https://i.stack.imgur.com/CvDb8.png)](https://i.stack.imgur.com/CvDb8.png) [![1 column on mobile](https://i.stack.imgur.com/5bVWS.png)](https://i.stack.imgur.com/5bVWS.png)
The answer is to use WP's responsive images, customising the sizes attribute to suit your use case. Reading between the lines, I'm assuming here that you are using a responsive design approach to show the different layouts at different widths. The easiest way is to start by making yourself a replacement template tag function for `the_post_thumbnail`: ``` function wpse_221989_the_post_thumbnail( $size, $attr ) { the_post_thumbnail( $size, $attr ); } ``` Where you call `the_post_thumbnail` in your templates, call `wpse_221989_the_post_thumbnail` instead. Why do we do it like this? WP doesn't give you any context on the filter hooks to modify `srcset` and `sizes` attributes for responsive images, so we are making our own context with the `wpse_221989_the_post_thumbnail` wrapper function. So far, nothing clever, but now we can build upon this function to: 1 - draw on a set of image sizes 2 - ask the browser to choose a suitable image depending upon your responsive breakpoint for this particular use case 1 - In your instance, where your image versions are all the same aspect ratio, WP handles things for us. Using a built-in image call like `the_post_thumbnail` will build a `srcset` attribute from every image size you have with the same aspect ratio as the image specified in the `$size` parameter. You can use `add_image_size` to create additional versions large enough for high density displays too. WP's match on aspect ratio allows for small rounding errors, so both the sizes in your question should be matched OK. 2 - To get the browser to choose the right image size for the space, you will need a custom `sizes` attribute. WP's default `sizes` attribute assumes that you want an image to be full browser width, but no wider than the image's natural width. In your design, narrower screens need the larger image and then above a certain breakpoint you want to choose the smaller image width. So, assuming from your image sizes that your breakpoint is at `640px`, we'd want a `sizes` attribute a bit like this: `(min-width: 640px) 33.333vw, 100vw` What this says to the browser is for windows of `640px` width and over, choose the image from the `srcset` list that best matches a third of the window width. For other window widths (< 640px) choose an image from the list that best fits the full window width. To put that into code we make a new function to return the attribute and build it into our wrapper function: ``` function wpse_221989_sizes() { return "(min-width: 640px) 33.333vw, 100vw"; } function wpse_221989_the_post_thumbnail( $size, $attr ) { add_filter( 'wp_calculate_image_sizes', 'wpse_221989_sizes', 10 , 2 ); the_post_thumbnail( $size, $attr ); remove_filter( 'wp_calculate_image_sizes', 'wpse_221989_sizes', 10 ); } ``` Now when your theme template calls `wpse_221989_the_post_thumbnail` our custom `sizes` attribute will be substituted for the default. By hooking into the filter before calling `the_post_thumbnail` and unhooking immediately after we make our custom template tag function sensitive to the context of your question without upsetting any sizes attributes generated on images in other parts of your theme. You can build upon this by putting in conditional checks on `$size` to choose different rules for the various image versions you've created for your theme to use. If Google Pagespeed is important to you then test to see that it is obeying your `srcset` and `sizes` attributes. If not, then use `add_image_size` to make a size that just fits the Pagespeed window and use that size in your calls to `wpse_221989_the_post_thumbnail` so that it is put into the `src` attribute. On my sites I use a 1024px image as the default which seems to keep both desktop and mobile Pagespeed analyses happy.
222,012
<p>Several years ago, not really having a handle on the best practice for running a MultiSite network, I often network activated plugins. Later I realized this was a mistake because not all the sites used some of the plugins. So I have unnecessary scripts and stylesheets on several sites. </p> <p>What I've started doing for those unwanted plugin resources is <code>wp_dequeue_style( 'style-sheet' );</code> and <code>wp_deregister_style( 'style-sheet' );</code> in child-theme functions.php </p> <p>My problem is that it doesn't work for all plugins. For example, <a href="https://wordpress.org/plugins/advanced-recent-posts/" rel="nofollow">https://wordpress.org/plugins/advanced-recent-posts/</a> is not following my function. I thought perhaps I would try to <code>remove_action();</code> but I am not familiar with how this exactly works. </p> <p>Here's what I'm working with in my functions.php and it works for other style-sheets.</p> <pre><code>function remove_unwanted_stylesheets() { wp_dequeue_style( 'wp-advanced-rp-css' ); wp_deregister_style( 'wp-advanced-rp-css' ); } add_action( 'wp_enqueue_scripts', 'remove_unwanted_stylesheets', 999 ); </code></pre> <p>The plugin enqueue and add action is as follows.</p> <pre><code>function add_advanced_recent_posts_widget_stylesheet() { $plugin_dir = 'advanced-recent-posts-widget'; if ( @file_exists( STYLESHEETPATH . '/advanced-recent-posts-widget.css' ) ) $mycss_file = get_stylesheet_directory_uri() . '/advanced-recent-posts-widget.css'; elseif ( @file_exists( TEMPLATEPATH . '/advanced-recent-posts-widget.css' ) ) $mycss_file = get_template_directory_uri() . '/advanced-recent-posts-widget.css'; else $mycss_file = plugins_url( 'css/advanced-recent-posts-widget.css',dirname(__FILE__) ); wp_register_style( 'wp-advanced-rp-css', $mycss_file ); wp_enqueue_style( 'wp-advanced-rp-css' ); } add_action('wp_print_styles', 'add_advanced_recent_posts_widget_stylesheet'); </code></pre> <p>Any insight into how I can effectively dequeue and unregister the stylesheet for this plugin is greatly appreciated.</p>
[ { "answer_id": 222015, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>Your issue is timing. If you check out <a href=\"https://wordpress.stackexchange.com/a/21579/847\">this answer for detailed order</a> you'll see that <code>wp_print_styles</code> occurs <em>after</em> <code>wp_enqueue_scripts</code>. So the earliest your dequeue would work in this case is <code>wp_print_styles</code> at 11 priority.</p>\n\n<p>Really it's unconventional of that plugin's author to register at that point. <code>wp_enqueue_scripts</code> is intended hooks for that exactly so that others don't have troubles like this.</p>\n" }, { "answer_id": 222016, "author": "Jarod Thornton", "author_id": 44017, "author_profile": "https://wordpress.stackexchange.com/users/44017", "pm_score": 2, "selected": true, "text": "<p>Going off of the plugins source code I simply copied then changed the <code>add_action();</code> to <code>remove_action();</code> in my child-themes function.php</p>\n\n<pre><code>add_action('wp_print_styles', 'add_advanced_recent_posts_widget_stylesheet');\n</code></pre>\n\n<p>Replace <code>add</code> with <code>remove</code>.</p>\n\n<pre><code>remove_action('wp_print_styles','add_advanced_recent_posts_widget_stylesheet');\n</code></pre>\n\n<p>So simple. Now I know.</p>\n" } ]
2016/03/29
[ "https://wordpress.stackexchange.com/questions/222012", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44017/" ]
Several years ago, not really having a handle on the best practice for running a MultiSite network, I often network activated plugins. Later I realized this was a mistake because not all the sites used some of the plugins. So I have unnecessary scripts and stylesheets on several sites. What I've started doing for those unwanted plugin resources is `wp_dequeue_style( 'style-sheet' );` and `wp_deregister_style( 'style-sheet' );` in child-theme functions.php My problem is that it doesn't work for all plugins. For example, <https://wordpress.org/plugins/advanced-recent-posts/> is not following my function. I thought perhaps I would try to `remove_action();` but I am not familiar with how this exactly works. Here's what I'm working with in my functions.php and it works for other style-sheets. ``` function remove_unwanted_stylesheets() { wp_dequeue_style( 'wp-advanced-rp-css' ); wp_deregister_style( 'wp-advanced-rp-css' ); } add_action( 'wp_enqueue_scripts', 'remove_unwanted_stylesheets', 999 ); ``` The plugin enqueue and add action is as follows. ``` function add_advanced_recent_posts_widget_stylesheet() { $plugin_dir = 'advanced-recent-posts-widget'; if ( @file_exists( STYLESHEETPATH . '/advanced-recent-posts-widget.css' ) ) $mycss_file = get_stylesheet_directory_uri() . '/advanced-recent-posts-widget.css'; elseif ( @file_exists( TEMPLATEPATH . '/advanced-recent-posts-widget.css' ) ) $mycss_file = get_template_directory_uri() . '/advanced-recent-posts-widget.css'; else $mycss_file = plugins_url( 'css/advanced-recent-posts-widget.css',dirname(__FILE__) ); wp_register_style( 'wp-advanced-rp-css', $mycss_file ); wp_enqueue_style( 'wp-advanced-rp-css' ); } add_action('wp_print_styles', 'add_advanced_recent_posts_widget_stylesheet'); ``` Any insight into how I can effectively dequeue and unregister the stylesheet for this plugin is greatly appreciated.
Going off of the plugins source code I simply copied then changed the `add_action();` to `remove_action();` in my child-themes function.php ``` add_action('wp_print_styles', 'add_advanced_recent_posts_widget_stylesheet'); ``` Replace `add` with `remove`. ``` remove_action('wp_print_styles','add_advanced_recent_posts_widget_stylesheet'); ``` So simple. Now I know.
222,038
<p>I have a PHP script running in WordPress, that uses a <code>WP_Query</code> to get the posts from one of my subdomains and return it as a JSON string. The script only receives the post data if I call it using the correct subdomain.</p> <p>For example, if I go to <code>news.example.com/api/news.php</code>, the JSON prints correctly, but if I go to <code>www.example.com/api/news.php</code> it only prints an empty array. </p> <p>How can I call a single script that will get data from a subdomain, even if I call it using the main domain? Or even better, if I call it from any subdomain? </p>
[ { "answer_id": 222015, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 0, "selected": false, "text": "<p>Your issue is timing. If you check out <a href=\"https://wordpress.stackexchange.com/a/21579/847\">this answer for detailed order</a> you'll see that <code>wp_print_styles</code> occurs <em>after</em> <code>wp_enqueue_scripts</code>. So the earliest your dequeue would work in this case is <code>wp_print_styles</code> at 11 priority.</p>\n\n<p>Really it's unconventional of that plugin's author to register at that point. <code>wp_enqueue_scripts</code> is intended hooks for that exactly so that others don't have troubles like this.</p>\n" }, { "answer_id": 222016, "author": "Jarod Thornton", "author_id": 44017, "author_profile": "https://wordpress.stackexchange.com/users/44017", "pm_score": 2, "selected": true, "text": "<p>Going off of the plugins source code I simply copied then changed the <code>add_action();</code> to <code>remove_action();</code> in my child-themes function.php</p>\n\n<pre><code>add_action('wp_print_styles', 'add_advanced_recent_posts_widget_stylesheet');\n</code></pre>\n\n<p>Replace <code>add</code> with <code>remove</code>.</p>\n\n<pre><code>remove_action('wp_print_styles','add_advanced_recent_posts_widget_stylesheet');\n</code></pre>\n\n<p>So simple. Now I know.</p>\n" } ]
2016/03/29
[ "https://wordpress.stackexchange.com/questions/222038", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91436/" ]
I have a PHP script running in WordPress, that uses a `WP_Query` to get the posts from one of my subdomains and return it as a JSON string. The script only receives the post data if I call it using the correct subdomain. For example, if I go to `news.example.com/api/news.php`, the JSON prints correctly, but if I go to `www.example.com/api/news.php` it only prints an empty array. How can I call a single script that will get data from a subdomain, even if I call it using the main domain? Or even better, if I call it from any subdomain?
Going off of the plugins source code I simply copied then changed the `add_action();` to `remove_action();` in my child-themes function.php ``` add_action('wp_print_styles', 'add_advanced_recent_posts_widget_stylesheet'); ``` Replace `add` with `remove`. ``` remove_action('wp_print_styles','add_advanced_recent_posts_widget_stylesheet'); ``` So simple. Now I know.
222,090
<p><code>get_theme_mod</code> is returning cached content: this code:</p> <pre><code>$parallax_one_logos = get_theme_mod('parallax_one_logos_content', json_encode( array( array("image_url" =&gt; parallax_get_file('/images/companies/1.png') ,"link" =&gt; "#" ), array("image_url" =&gt; parallax_get_file('/images/companies/2.png') ,"link" =&gt; "#" )) ) ); </code></pre> <p>And this code, containing a bollocks <code>test</code> value.</p> <pre><code>get_theme_mod('parallax_one_logos_content', json_encode('test')) </code></pre> <p><strong>Return the same value.</strong><br> I have:</p> <ol> <li>Shut Down Apache</li> <li>Shut Down MySql</li> <li>Tried Ctrl-F5</li> </ol> <p>I am at a loss as to how to remove / clear the cache that <code>get_theme_mod</code> uses.<br> If it helps I am using <code>XAMPP</code> on windows 10.</p> <p>Thanks</p>
[ { "answer_id": 222094, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": true, "text": "<p>If the theme mod option has a value in database, your code is working just fine as it should return the value in database and ignore the second parameter. The second parameter is the default value to be used if there is no value is set. And the value is stored in database.</p>\n\n<p>The problem is that you are wrong considering that the values of the theme mod are cached in database, <strong>they are stored in database</strong>, not cached; the query to get them from database can be cached but if you need to update the value of a theme mod, you have to update the value already stored in database. You can do it using <a href=\"https://codex.wordpress.org/Function_Reference/set_theme_mod\" rel=\"nofollow\"><code>set_theme_mod()</code></a>:</p>\n\n<pre><code>set_theme_mod( 'parallax_one_logos_content', 'new value' );\n</code></pre>\n" }, { "answer_id": 222098, "author": "Jim", "author_id": 91460, "author_profile": "https://wordpress.stackexchange.com/users/91460", "pm_score": -1, "selected": false, "text": "<p>You can execute this command in mysql / workbench / phpAdmin etc to remove all the stored mod data from the database.</p>\n\n<pre><code>SET SQL_SAFE_UPDATES=0;\ndelete from wp_options where option_name like '%theme_mod%'\n</code></pre>\n\n<p>Regards<br>\nCraig.</p>\n" } ]
2016/03/30
[ "https://wordpress.stackexchange.com/questions/222090", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91460/" ]
`get_theme_mod` is returning cached content: this code: ``` $parallax_one_logos = get_theme_mod('parallax_one_logos_content', json_encode( array( array("image_url" => parallax_get_file('/images/companies/1.png') ,"link" => "#" ), array("image_url" => parallax_get_file('/images/companies/2.png') ,"link" => "#" )) ) ); ``` And this code, containing a bollocks `test` value. ``` get_theme_mod('parallax_one_logos_content', json_encode('test')) ``` **Return the same value.** I have: 1. Shut Down Apache 2. Shut Down MySql 3. Tried Ctrl-F5 I am at a loss as to how to remove / clear the cache that `get_theme_mod` uses. If it helps I am using `XAMPP` on windows 10. Thanks
If the theme mod option has a value in database, your code is working just fine as it should return the value in database and ignore the second parameter. The second parameter is the default value to be used if there is no value is set. And the value is stored in database. The problem is that you are wrong considering that the values of the theme mod are cached in database, **they are stored in database**, not cached; the query to get them from database can be cached but if you need to update the value of a theme mod, you have to update the value already stored in database. You can do it using [`set_theme_mod()`](https://codex.wordpress.org/Function_Reference/set_theme_mod): ``` set_theme_mod( 'parallax_one_logos_content', 'new value' ); ```
222,100
<p>Just like in topic I try to order posts from category by date and comment_count but code below doesn't work:</p> <pre><code>&lt;?php //get post from current category $category = get_the_category(); $category_ID = $category[0]-&gt;term_id; $args = array( 'cat' =&gt; $category_ID, //limit posts to 3 'posts_per_page' =&gt; 3, 'ignore_sticky_posts' =&gt; true, //order post by date and comments 'orderby' =&gt; array( 'date' =&gt; 'DESC', 'comment_count' =&gt; 'DESC', ), ); $the_query = new WP_Query($args); ?&gt; </code></pre> <p>Posts are ordered only by date</p>
[ { "answer_id": 222104, "author": "engelen", "author_id": 40403, "author_profile": "https://wordpress.stackexchange.com/users/40403", "pm_score": 2, "selected": true, "text": "<p>The query you currently have will order the posts by their <code>post_date</code> property, which is an SQL column of the type <code>datetime</code>. This type stores the date, but also the time (hours, minutes and seconds). The second sorting option, <code>comment_count</code>, is only applied to posts with the same timestamp, i.e. that were posted at the exact same second in time.</p>\n\n<p>So, the solution to your problem is to sort by post <em>date</em> instead of <em>datetime</em>. To do so, you can filter the <code>orderby</code> query part in <code>WP_Query</code> using the filter <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_orderby\" rel=\"nofollow\"><code>posts_orderby</code></a>. With this filter, you can replace the SQL <code>ORDER</code> clauses to use the day instead of the datetime.</p>\n\n<p>The code below does this: it adds a function to the filter <code>posts_orderby</code> which replaces the <code>{$wpdb-&gt;posts}.post_date</code> (e.g. <code>wp_posts.post_date</code>) by <code>CAST({$wpdb-&gt;posts}.post_date AS DATE)</code>, which casts the datetime field to <code>YYYY-MM-DD</code> format. After executing the query, it removes the filter, ensuring that other queries are not affected.</p>\n\n<pre><code>function wpse222104_query_orderby_day( $orderby, $query ) {\n global $wpdb;\n\n return str_replace( \"{$wpdb-&gt;posts}.post_date\", \"CAST({$wpdb-&gt;posts}.post_date AS DATE)\", $orderby );\n}\n\n// Add the filter to change the ORDER clause\nadd_filter( 'posts_orderby', 'wpse222104_query_orderby_day', 10, 2 );\n\n// Run the query with the filters\n$query = new WP_Query( $args );\n\n// Remove the filter\nremove_filter( 'posts_orderby', 'wpse222104_query_orderby_day' );\n</code></pre>\n\n<p>This assumes the same <code>$args</code> that you already had: there was nothing wrong with them.</p>\n\n<h2>Testing the code</h2>\n\n<p>Testing the code shows that the <code>ORDER BY</code> clause is correctly changed: the original clause was</p>\n\n<pre><code>wp_posts.post_date DESC, wp_posts.comment_count DESC\n</code></pre>\n\n<p>whereas the new one is</p>\n\n<pre><code>CAST(wp_posts.post_date AS DATE) DESC, wp_posts.comment_count DESC\n</code></pre>\n\n<h2>Example</h2>\n\n<p>The precise time the post was published will now not be considered in sorting: only the date it was posted will. For example, consider the following posts:</p>\n\n<pre><code>Title Date Comment count\nExample Post 2014-12-16 10:12:16 6\nAnother one 2014-12-16 21:50:07 4\nYet Another 2012-08-02 11:15:20 25\n</code></pre>\n\n<p>Here, your original query would return the posts in the order</p>\n\n<ol>\n<li>Another one</li>\n<li>Example post</li>\n<li>Yet another</li>\n</ol>\n\n<p>Whereas the new code would return the posts in order</p>\n\n<ol>\n<li>Example post</li>\n<li>Another one</li>\n<li>Yet another</li>\n</ol>\n\n<p>as \"Example post\" and \"Another one\" were posted on the same day, but \"Example post\" has more comments.</p>\n" }, { "answer_id": 222105, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 0, "selected": false, "text": "<p>Looks like you are using pre-4.x version of WordPress. Older version does not support <code>array()</code> as <code>orderby</code> value. Use <code>'orderby' =&gt; 'date comment_count'</code> instead:</p>\n\n<pre><code>&lt;?php\n$category = get_the_category();\n$category_ID = $category[0]-&gt;term_id;\n$args = array(\n 'cat' =&gt; $category_ID,\n 'posts_per_page' =&gt; 3,\n 'ignore_sticky_posts' =&gt; true,\n 'orderby' =&gt; 'date comment_count', // date is primary\n 'order' =&gt; 'DESC' // not required because it's the default value\n);\n$the_query = new WP_Query($args);\n?&gt;\n</code></pre>\n" } ]
2016/03/30
[ "https://wordpress.stackexchange.com/questions/222100", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47607/" ]
Just like in topic I try to order posts from category by date and comment\_count but code below doesn't work: ``` <?php //get post from current category $category = get_the_category(); $category_ID = $category[0]->term_id; $args = array( 'cat' => $category_ID, //limit posts to 3 'posts_per_page' => 3, 'ignore_sticky_posts' => true, //order post by date and comments 'orderby' => array( 'date' => 'DESC', 'comment_count' => 'DESC', ), ); $the_query = new WP_Query($args); ?> ``` Posts are ordered only by date
The query you currently have will order the posts by their `post_date` property, which is an SQL column of the type `datetime`. This type stores the date, but also the time (hours, minutes and seconds). The second sorting option, `comment_count`, is only applied to posts with the same timestamp, i.e. that were posted at the exact same second in time. So, the solution to your problem is to sort by post *date* instead of *datetime*. To do so, you can filter the `orderby` query part in `WP_Query` using the filter [`posts_orderby`](https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_orderby). With this filter, you can replace the SQL `ORDER` clauses to use the day instead of the datetime. The code below does this: it adds a function to the filter `posts_orderby` which replaces the `{$wpdb->posts}.post_date` (e.g. `wp_posts.post_date`) by `CAST({$wpdb->posts}.post_date AS DATE)`, which casts the datetime field to `YYYY-MM-DD` format. After executing the query, it removes the filter, ensuring that other queries are not affected. ``` function wpse222104_query_orderby_day( $orderby, $query ) { global $wpdb; return str_replace( "{$wpdb->posts}.post_date", "CAST({$wpdb->posts}.post_date AS DATE)", $orderby ); } // Add the filter to change the ORDER clause add_filter( 'posts_orderby', 'wpse222104_query_orderby_day', 10, 2 ); // Run the query with the filters $query = new WP_Query( $args ); // Remove the filter remove_filter( 'posts_orderby', 'wpse222104_query_orderby_day' ); ``` This assumes the same `$args` that you already had: there was nothing wrong with them. Testing the code ---------------- Testing the code shows that the `ORDER BY` clause is correctly changed: the original clause was ``` wp_posts.post_date DESC, wp_posts.comment_count DESC ``` whereas the new one is ``` CAST(wp_posts.post_date AS DATE) DESC, wp_posts.comment_count DESC ``` Example ------- The precise time the post was published will now not be considered in sorting: only the date it was posted will. For example, consider the following posts: ``` Title Date Comment count Example Post 2014-12-16 10:12:16 6 Another one 2014-12-16 21:50:07 4 Yet Another 2012-08-02 11:15:20 25 ``` Here, your original query would return the posts in the order 1. Another one 2. Example post 3. Yet another Whereas the new code would return the posts in order 1. Example post 2. Another one 3. Yet another as "Example post" and "Another one" were posted on the same day, but "Example post" has more comments.
222,112
<p>I want to add custom classes to my menu items. For every subpage I show its siblings as a navigation:</p> <pre><code> global $post; if ( is_page() &amp;&amp; $post-&gt;post_parent ) { $args = array( 'sort_column' =&gt; 'menu_order', 'title_li' =&gt; '', 'child_of'=&gt; $post-&gt;post_parent ); $childpages = wp_list_pages($args ); } </code></pre> <p>This gives me a list with links. I want to give every anchor element the same custom class. How do I do that?</p>
[ { "answer_id": 222126, "author": "engelen", "author_id": 40403, "author_profile": "https://wordpress.stackexchange.com/users/40403", "pm_score": 2, "selected": false, "text": "<p>There is no good filter to add the CSS classes to the anchor (<code>&lt;a&gt;</code>) elements, but as you need it for CSS styling you can use the filter for the <code>&lt;li&gt;</code> elements. This filter is called <a href=\"https://developer.wordpress.org/reference/hooks/page_css_class/\" rel=\"nofollow\"><code>page_css_class</code></a>, which is, natively, used solely in listing pages through <code>wp_list_pages()</code>. It filters the classes used for the <code>li</code>-tags.</p>\n\n<p>To use this filter, simply hook into it:</p>\n\n<pre><code>function wpse222112_pagelist_item_css_classes( $classes ) {\n $classes[] = 'wpse222112-class';\n return $classes;\n}\n\nadd_filter( 'page_css_class', 'wpse222112_pagelist_item_css_classes' );\n</code></pre>\n\n<p>If you need it only for this menu, be sure to remove it after calling <code>wp_list_pages()</code> using</p>\n\n<pre><code>remove_filter( 'page_css_class', 'wpse222112_pagelist_item_css_classes' );\n</code></pre>\n\n<p>For the sake of completeness: there is also a filter for the entire output of the page list, which you would need to use if it were necessary to add a class to the anchor tags (which it isn't in your case). This filter is <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_list_pages\" rel=\"nofollow\"><code>wp_list_pages</code></a>.</p>\n" }, { "answer_id": 222132, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 1, "selected": true, "text": "<p>One of the ways is to extend <code>Walker_Page</code> class. See comment in the code to know where changes go.</p>\n\n<pre><code>class My_Siblings_CSS_Walker_Page extends Walker_Page {\n public function start_el( &amp;$output, $page, $depth = 0, $args = array(), $current_page = 0 ) {\n if ( $depth ) {\n $indent = str_repeat( \"\\t\", $depth );\n } else {\n $indent = '';\n }\n\n $css_class = array( 'page_item', 'page-item-' . $page-&gt;ID );\n\n if ( isset( $args['pages_with_children'][ $page-&gt;ID ] ) ) {\n $css_class[] = 'page_item_has_children';\n }\n\n if ( ! empty( $current_page ) ) {\n $_current_page = get_post( $current_page );\n if ( $_current_page &amp;&amp; in_array( $page-&gt;ID, $_current_page-&gt;ancestors ) ) {\n $css_class[] = 'current_page_ancestor';\n }\n if ( $page-&gt;ID == $current_page ) {\n $css_class[] = 'current_page_item';\n } elseif ( $_current_page &amp;&amp; $page-&gt;ID == $_current_page-&gt;post_parent ) {\n $css_class[] = 'current_page_parent';\n }\n } elseif ( $page-&gt;ID == get_option('page_for_posts') ) {\n $css_class[] = 'current_page_parent';\n }\n\n $css_classes = implode( ' ', apply_filters( 'page_css_class', $css_class, $page, $depth, $args, $current_page ) );\n\n if ( '' === $page-&gt;post_title ) {\n $page-&gt;post_title = sprintf( __( '#%d (no title)' ), $page-&gt;ID );\n }\n\n $args['link_before'] = empty( $args['link_before'] ) ? '' : $args['link_before'];\n $args['link_after'] = empty( $args['link_after'] ) ? '' : $args['link_after'];\n\n $output .= $indent . sprintf(\n // '&lt;li class=\"%s\"&gt;&lt;a href=\"%s\"&gt;%s%s%s&lt;/a&gt;', // before\n '&lt;li class=\"%s\"&gt;&lt;a href=\"%s\" class=\"my-custom-css-class\"&gt;%s%s%s&lt;/a&gt;', // after \n $css_classes,\n get_permalink( $page-&gt;ID ),\n $args['link_before'],\n apply_filters( 'the_title', $page-&gt;post_title, $page-&gt;ID ),\n $args['link_after']\n );\n\n if ( ! empty( $args['show_date'] ) ) {\n if ( 'modified' == $args['show_date'] ) {\n $time = $page-&gt;post_modified;\n } else {\n $time = $page-&gt;post_date;\n }\n\n $date_format = empty( $args['date_format'] ) ? '' : $args['date_format'];\n $output .= \" \" . mysql2date( $date_format, $time );\n }\n }\n}\n</code></pre>\n\n<p>Use this custom Walker in your template:</p>\n\n<pre><code>$args = array(\n 'sort_column' =&gt; 'menu_order',\n 'title_li' =&gt; '',\n 'child_of' =&gt; $post-&gt;post_parent\n 'walker' =&gt; new My_Siblings_CSS_Walker_Page() // use Walker here\n);\n// $childpages = wp_list_pages($args);\nwp_list_pages($args); // as you utilize default 'echo' parameter (true)\n</code></pre>\n\n<p>The way much easier is to use jQuery.</p>\n" } ]
2016/03/30
[ "https://wordpress.stackexchange.com/questions/222112", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11687/" ]
I want to add custom classes to my menu items. For every subpage I show its siblings as a navigation: ``` global $post; if ( is_page() && $post->post_parent ) { $args = array( 'sort_column' => 'menu_order', 'title_li' => '', 'child_of'=> $post->post_parent ); $childpages = wp_list_pages($args ); } ``` This gives me a list with links. I want to give every anchor element the same custom class. How do I do that?
One of the ways is to extend `Walker_Page` class. See comment in the code to know where changes go. ``` class My_Siblings_CSS_Walker_Page extends Walker_Page { public function start_el( &$output, $page, $depth = 0, $args = array(), $current_page = 0 ) { if ( $depth ) { $indent = str_repeat( "\t", $depth ); } else { $indent = ''; } $css_class = array( 'page_item', 'page-item-' . $page->ID ); if ( isset( $args['pages_with_children'][ $page->ID ] ) ) { $css_class[] = 'page_item_has_children'; } if ( ! empty( $current_page ) ) { $_current_page = get_post( $current_page ); if ( $_current_page && in_array( $page->ID, $_current_page->ancestors ) ) { $css_class[] = 'current_page_ancestor'; } if ( $page->ID == $current_page ) { $css_class[] = 'current_page_item'; } elseif ( $_current_page && $page->ID == $_current_page->post_parent ) { $css_class[] = 'current_page_parent'; } } elseif ( $page->ID == get_option('page_for_posts') ) { $css_class[] = 'current_page_parent'; } $css_classes = implode( ' ', apply_filters( 'page_css_class', $css_class, $page, $depth, $args, $current_page ) ); if ( '' === $page->post_title ) { $page->post_title = sprintf( __( '#%d (no title)' ), $page->ID ); } $args['link_before'] = empty( $args['link_before'] ) ? '' : $args['link_before']; $args['link_after'] = empty( $args['link_after'] ) ? '' : $args['link_after']; $output .= $indent . sprintf( // '<li class="%s"><a href="%s">%s%s%s</a>', // before '<li class="%s"><a href="%s" class="my-custom-css-class">%s%s%s</a>', // after $css_classes, get_permalink( $page->ID ), $args['link_before'], apply_filters( 'the_title', $page->post_title, $page->ID ), $args['link_after'] ); if ( ! empty( $args['show_date'] ) ) { if ( 'modified' == $args['show_date'] ) { $time = $page->post_modified; } else { $time = $page->post_date; } $date_format = empty( $args['date_format'] ) ? '' : $args['date_format']; $output .= " " . mysql2date( $date_format, $time ); } } } ``` Use this custom Walker in your template: ``` $args = array( 'sort_column' => 'menu_order', 'title_li' => '', 'child_of' => $post->post_parent 'walker' => new My_Siblings_CSS_Walker_Page() // use Walker here ); // $childpages = wp_list_pages($args); wp_list_pages($args); // as you utilize default 'echo' parameter (true) ``` The way much easier is to use jQuery.
222,121
<p>I want to get all the posts that do not contain the tag 'index'. How can it be done?</p> <p>I mean in the reverse of</p> <pre><code>get_posts(array('tag' =&gt; 'index')) </code></pre> <p>Thank you</p>
[ { "answer_id": 222123, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>You could try the <code>tax_query</code> with the <code>'NOT IN'</code> operator (untested)</p>\n\n<pre><code>$myposts = get_posts( \n [\n 'tax_query' =&gt; [\n [ \n 'taxonomy' =&gt; 'post_tag',\n 'terms' =&gt; [ 'index' ],\n 'field' =&gt; 'slug',\n 'operator' =&gt; 'NOT IN',\n ] \n ]\n ]\n);\n</code></pre>\n\n<p>where the taxonomy slug for <em>tags</em> is <code>post_tag</code>.</p>\n" }, { "answer_id": 222125, "author": "Kom", "author_id": 91476, "author_profile": "https://wordpress.stackexchange.com/users/91476", "pm_score": 0, "selected": false, "text": "<p>Per WordPress Codex you should use a custom query for any of post types interrogations. Presuming your taxonomy is 'post_tag' instead 'tag' use the following code:</p>\n\n<blockquote>\n <p>$args = array(<br>\n 'post_type' => 'post',<br>\n 'tax_query' => array(<br>\n array(<br>\n 'taxonomy' => 'post_tag',<br>\n 'field' => 'slug',<br>\n 'terms' => array('index'),<br>\n 'operator' => 'NOT IN' ))); </p>\n \n <p>$custom_query = new WP_Query( $args );\n while($custom_query->have_posts()) { $custom_query->the_post(); //your\n custom code\n }</p>\n</blockquote>\n" } ]
2016/03/30
[ "https://wordpress.stackexchange.com/questions/222121", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91474/" ]
I want to get all the posts that do not contain the tag 'index'. How can it be done? I mean in the reverse of ``` get_posts(array('tag' => 'index')) ``` Thank you
You could try the `tax_query` with the `'NOT IN'` operator (untested) ``` $myposts = get_posts( [ 'tax_query' => [ [ 'taxonomy' => 'post_tag', 'terms' => [ 'index' ], 'field' => 'slug', 'operator' => 'NOT IN', ] ] ] ); ``` where the taxonomy slug for *tags* is `post_tag`.
222,136
<p>Any idea how to check if the website is hidden from search engines? The reason is I want to show a big red banner at the top of the homepage when this option is checked because I always forget that this option is checked.</p>
[ { "answer_id": 222138, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>The setting is stored in the option <code>blog_public</code>.</p>\n\n<pre><code>if( 0 == get_option( 'blog_public' ) ){\n echo 'search engines discouraged';\n}\n</code></pre>\n" }, { "answer_id": 222140, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 1, "selected": false, "text": "<p>Pretty sure I <strike>stole</strike> borrowed the following piece of code from the very handy and <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow\">useful Yoast Plugin</a>:</p>\n\n<pre><code>/**\n * Check if Website is visible to Search Engines\n */\nfunction wpse_check_visibility() {\n if ( ! class_exists( 'WPSEO_Admin' ) ) {\n if ( '0' == get_option( 'blog_public' ) ) {\n add_action( 'admin_footer', 'wpse_private_wp_warning' );\n }\n }\n}\nadd_action( 'admin_init', 'wpse_check_visibility' );\n\n/**\n * If website is Private, show alert\n */\nfunction wpse_private_wp_warning() {\n if ( ( function_exists( 'is_network_admin' ) &amp;&amp; is_network_admin() ) ) {\n return;\n }\n\n echo '&lt;div id=\"robotsmessage\" class=\"error\"&gt;';\n echo '&lt;p&gt;&lt;strong&gt;' . __( 'Huge SEO Issue: You\\'re blocking access to robots.', 'wpse-seo' ) . '&lt;/strong&gt; ' . sprintf( __( 'You must %sgo to your Reading Settings%s and uncheck the box for Search Engine Visibility.', 'wordpress-seo' ), '&lt;a href=\"' . esc_url( admin_url( 'options-reading.php' ) ) . '\"&gt;', '&lt;/a&gt;' ) . '&lt;/p&gt;&lt;/div&gt;';\n}\n</code></pre>\n\n<p>Pretty much on <code>admin_init</code> we check if our site is private. If it is we're going to use the footer and WordPress alert styles to tell us that the site is private. The <code>WPSEO_Admin</code> is Yoast as I believe they will also tell you the site is private if it's installed so we don't want to step on their toes.</p>\n" }, { "answer_id": 312738, "author": "Jorge Casariego", "author_id": 137650, "author_profile": "https://wordpress.stackexchange.com/users/137650", "pm_score": 0, "selected": false, "text": "<p>Another way to see if your Website is hidden from Search Engines is going to Settings » Privacy Settings</p>\n\n<p>The Site Privacy setting controls who can view your site, allowing you to make the site private or public. To access this setting, go to <strong>My Site → Settings</strong> and look for Privacy.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8GL0Z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8GL0Z.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Privacy Options</strong></p>\n\n<ol>\n<li><p><strong>Public</strong>: This is the setting used by most sites. It allows everyone to read your site and enables your site to be included in search engine results and other content sites.</p></li>\n<li><p><strong>Hidden</strong>: If you want all human visitors to be able to read your blog, but want to block web crawlers for search engines, this is the setting for you. (Please note, however, that not all search engines respect this setting.)</p></li>\n<li><p><strong>Private</strong>: Select this option to make your site private. If you want specific people to be able to view it (and add comments, if you’ve enabled them), you’ll need to invite them to be a viewer.</p></li>\n</ol>\n" }, { "answer_id": 374681, "author": "herrfischer", "author_id": 67792, "author_profile": "https://wordpress.stackexchange.com/users/67792", "pm_score": 0, "selected": false, "text": "<p>Using this since Milos answer on every WordPress project as a handy snippet (put it right after the opening body tag):</p>\n<pre><code>&lt;?php if ( is_user_logged_in() ) { ?&gt;\n &lt;style&gt;\n a.searchengines_blocked {\n position: fixed;\n bottom: 0;\n left: 0;\n z-index: 99999;\n color: black !important;\n background-color: #ffcd1b !important;\n font-weight: normal;\n font-size: 1.8rem;\n padding: 6px 15px;\n text-align: center;\n vertical-align: middle;\n border-top-right-radius: 10px;\n }\n &lt;/style&gt;\n &lt;?php\n if( 0 == get_option( 'blog_public' ) ){\n echo '&lt;a href=&quot;./wp-admin/options-reading.php&quot; class=&quot;searchengines_blocked&quot;&gt;!G&lt;/a&gt;';\n }\n ?&gt;\n&lt;?php } ?&gt;\n</code></pre>\n" } ]
2016/03/30
[ "https://wordpress.stackexchange.com/questions/222136", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67792/" ]
Any idea how to check if the website is hidden from search engines? The reason is I want to show a big red banner at the top of the homepage when this option is checked because I always forget that this option is checked.
The setting is stored in the option `blog_public`. ``` if( 0 == get_option( 'blog_public' ) ){ echo 'search engines discouraged'; } ```
222,148
<p>Basically on my site I have a bunch of song lyrics and in a static page I want to show them listed by album <a href="http://www.thenewblackgold.netsons.org/wp/indexes/by-album/" rel="nofollow">Link to my website</a> and album position of the song and I have two custom fields with that data, <code>sd_album_title</code> and `sd_album_track_n.<br /> Plus some of the songs don't have an album yet, so both values are void, and I wish to list those ones at the foot of the others, sorted by alphabetical order. <br /> The latest thing I tried at least to sort everything by the two field is this one:</p> <pre><code>$key = 'sd_album_title'; $themeta = get_post_meta($post-&gt;ID, $key, TRUE); add_filter( 'pre_get_posts', 'my_get_posts' ); function my_get_posts( $query ) { if ($themeta != '') { $query-&gt;set( 'post_type', 'lyric' ); $query-&gt;set( 'meta_key', 'sd_album_title' ); $query-&gt;set( 'orderby', 'meta_value' ); $query-&gt;set( 'order', 'ASC' ); $query-&gt;set( 'meta_query', array( array( 'key' =&gt; 'sd_album_title' ), array( 'key' =&gt; 'sd_album_track_n', 'value' =&gt; 'target_value', 'compare' =&gt; '&gt;=', 'type' =&gt; 'numeric' ) )); } return $query; } $getlist= 'my_get_posts'; $posts = get_posts( $getlist ); </code></pre> <p>And my intention was to put an else at the end of it with an array ordered by title for the other songs, but it returns nothing as it is.<br /> Could something like this work with some corrections or am I on a totally wrong path?</p>
[ { "answer_id": 222153, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 2, "selected": true, "text": "<p>Why you are using <code>pre_get_posts</code> when using your own <code>get_posts()</code> ? You can just pass the argument list directly to <code>get_posts()</code>.</p>\n\n<p><code>orderby</code> can accept array of arguments and can order by multiple values.\nFirst name the indexes of meta queries array. This can be anything to use in orderby parameter. e.g.</p>\n\n<pre><code>'meta_query' =&gt; array(\n 'album_title_meta' =&gt; array(\n 'key' =&gt; 'sd_album_title',\n 'compare' =&gt; 'EXISTS',\n ),\n 'album_track_n_meta' =&gt; array(\n 'key' =&gt; 'sd_album_track_n',\n 'value' =&gt; 'target_value',\n 'compare' =&gt; '&gt;=',\n 'type' =&gt; 'numeric'\n )\n ),\n</code></pre>\n\n<p>Then pass an array in <code>orderby</code>, constructed using these keys!</p>\n\n<pre><code>'orderby' =&gt; array(\n 'album_title_meta' =&gt; 'ASC',\n 'album_track_n_meta' =&gt; 'DESC',\n ),\n</code></pre>\n\n<p>First, posts will be order by album title, ASC then track number, DESC.</p>\n\n<p><strong>The complete example:</strong></p>\n\n<pre><code>$my_args = array(\n 'post_type' =&gt; 'lyric',\n 'meta_query' =&gt; array(\n 'album_title_meta' =&gt; array(\n 'key' =&gt; 'sd_album_title',\n 'compare' =&gt; 'EXISTS',\n ),\n 'album_track_n_meta' =&gt; array(\n 'key' =&gt; 'sd_album_track_n',\n 'value' =&gt; 'target_value',\n 'compare' =&gt; '&gt;=',\n 'type' =&gt; 'numeric'\n )\n ),\n 'orderby' =&gt; array(\n 'album_title_meta' =&gt; 'ASC',\n 'album_track_n_meta' =&gt; 'DESC',\n ),\n);\n$getlist = get_posts($my_args);\n</code></pre>\n\n<blockquote>\n <p>NOTE: these syntax are only supported since WordPress <a href=\"https://codex.wordpress.org/Version_4.2\" rel=\"nofollow\">version\n 4.2</a></p>\n</blockquote>\n" }, { "answer_id": 222159, "author": "EliChan", "author_id": 91366, "author_profile": "https://wordpress.stackexchange.com/users/91366", "pm_score": 0, "selected": false, "text": "<p>Thanks to Sumit now it all works well!<br />\nFor anyone else that encounters the same problem: I also wished to put the singles (that don't have any album or album track data) at the bottom (even now I think I'll leave them at the top) and ordered by title. Instead of making an if / else, since the output should be different too, I decided to put two get_posts like this:</p>\n\n<pre><code>&lt;?php \n//LIST ORDERED BY ALBUM \n//SINGLES SECTION - SHOWS SINGLES SORTED BY TITLE (Singles category is the n. 47)\n$single_posts = get_posts( array(\n 'post_type' =&gt; 'lyric',\n 'category' =&gt; 47,\n 'posts_per_page' =&gt; -1,\n 'orderby'=&gt; 'title',\n 'order' =&gt; 'ASC' )\n );\n\nif( $single_posts ): ?&gt;\n\n &lt;ul&gt;\n\n &lt;?php foreach( $single_posts as $post ): \n\n setup_postdata( $post )\n\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" target=\"_blank\"&gt;[Single]&amp;nbsp;\n&lt;?php the_title(); ?&gt; (&lt;?php the_field('sd_song_time'); ?&gt;)&lt;/a&gt;\n &lt;/li&gt;\n\n &lt;?php endforeach; ?&gt;\n\n &lt;/ul&gt;\n\n &lt;?php wp_reset_postdata(); ?&gt;\n\n&lt;?php endif; ?&gt;\n&lt;?php \n//LIST ORDERED BY ALBUM \n//ALBUM SECTION - SHOWS ALBUMS SORTED BY TRACK N.\n$album_posts = array(\n 'post_type' =&gt; 'lyric',\n 'category__not_in' =&gt; 47,\n 'posts_per_page' =&gt; -1,\n 'meta_query' =&gt; array(\n 'album_title_meta' =&gt; array(\n 'key' =&gt; 'sd_album_title',\n 'compare' =&gt; 'EXISTS',\n ),\n 'album_track_n_meta' =&gt; array(\n 'key' =&gt; 'sd_album_track_n',\n 'value' =&gt; 'target_value',\n 'compare' =&gt; '&gt;=',\n 'type' =&gt; 'numeric'\n )\n ),\n 'orderby' =&gt; array(\n 'album_title_meta' =&gt; 'ASC',\n 'album_track_n_meta' =&gt; 'ASC',\n ),\n);\n\n$posts = get_posts( $album_posts );\n\nif( $posts ): ?&gt;\n\n &lt;ul&gt;\n\n &lt;?php foreach( $posts as $post ): \n\n setup_postdata( $post )\n\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" target=\"_blank\"&gt;\n&lt;?php the_field('sd_album_track_n'); ?&gt;.&amp;nbsp;&lt;?php the_field('sd_album_title'); ?&gt;:&amp;nbsp;&lt;?php the_title(); ?&gt; (&lt;?php the_field('sd_song_time'); ?&gt;)&lt;/a&gt;\n &lt;/li&gt;\n\n &lt;?php endforeach; ?&gt;\n\n &lt;/ul&gt;\n\n &lt;?php wp_reset_postdata(); ?&gt;\n\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>I know probably there are better ways to do this, but it works like a charm ;)</p>\n" } ]
2016/03/30
[ "https://wordpress.stackexchange.com/questions/222148", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91366/" ]
Basically on my site I have a bunch of song lyrics and in a static page I want to show them listed by album [Link to my website](http://www.thenewblackgold.netsons.org/wp/indexes/by-album/) and album position of the song and I have two custom fields with that data, `sd_album_title` and `sd\_album\_track\_n. Plus some of the songs don't have an album yet, so both values are void, and I wish to list those ones at the foot of the others, sorted by alphabetical order. The latest thing I tried at least to sort everything by the two field is this one: ``` $key = 'sd_album_title'; $themeta = get_post_meta($post->ID, $key, TRUE); add_filter( 'pre_get_posts', 'my_get_posts' ); function my_get_posts( $query ) { if ($themeta != '') { $query->set( 'post_type', 'lyric' ); $query->set( 'meta_key', 'sd_album_title' ); $query->set( 'orderby', 'meta_value' ); $query->set( 'order', 'ASC' ); $query->set( 'meta_query', array( array( 'key' => 'sd_album_title' ), array( 'key' => 'sd_album_track_n', 'value' => 'target_value', 'compare' => '>=', 'type' => 'numeric' ) )); } return $query; } $getlist= 'my_get_posts'; $posts = get_posts( $getlist ); ``` And my intention was to put an else at the end of it with an array ordered by title for the other songs, but it returns nothing as it is. Could something like this work with some corrections or am I on a totally wrong path?
Why you are using `pre_get_posts` when using your own `get_posts()` ? You can just pass the argument list directly to `get_posts()`. `orderby` can accept array of arguments and can order by multiple values. First name the indexes of meta queries array. This can be anything to use in orderby parameter. e.g. ``` 'meta_query' => array( 'album_title_meta' => array( 'key' => 'sd_album_title', 'compare' => 'EXISTS', ), 'album_track_n_meta' => array( 'key' => 'sd_album_track_n', 'value' => 'target_value', 'compare' => '>=', 'type' => 'numeric' ) ), ``` Then pass an array in `orderby`, constructed using these keys! ``` 'orderby' => array( 'album_title_meta' => 'ASC', 'album_track_n_meta' => 'DESC', ), ``` First, posts will be order by album title, ASC then track number, DESC. **The complete example:** ``` $my_args = array( 'post_type' => 'lyric', 'meta_query' => array( 'album_title_meta' => array( 'key' => 'sd_album_title', 'compare' => 'EXISTS', ), 'album_track_n_meta' => array( 'key' => 'sd_album_track_n', 'value' => 'target_value', 'compare' => '>=', 'type' => 'numeric' ) ), 'orderby' => array( 'album_title_meta' => 'ASC', 'album_track_n_meta' => 'DESC', ), ); $getlist = get_posts($my_args); ``` > > NOTE: these syntax are only supported since WordPress [version > 4.2](https://codex.wordpress.org/Version_4.2) > > >
222,172
<p>I have a daily wp schedule event. </p> <p>I know that it happens when a user visits the site and if a schedule time passes. </p> <p>If I started it on today 12 a.m. and if tomorrow first visitor comes tomorrow 1:20 a.m. that event happen tomorrow 1:20 a.m.. </p> <p>Day after day, it happens after 1.20 a.m. or after 12 a.m.? </p>
[ { "answer_id": 222250, "author": "David E. Smith", "author_id": 67104, "author_profile": "https://wordpress.stackexchange.com/users/67104", "pm_score": 3, "selected": true, "text": "<p><em>wp-cron</em> is often called a pseudo-cron, because it doesn't run on a strict schedule. If nobody visits the site, it doesn't run. If you schedule a wp-cron event to run, say, every 12 hours, it will run <em>at most</em> every 12 hours. But, if your site has very little traffic, there could be far more than 12 hours between runs.</p>\n\n<p>If you need an event to happen every 12 hours, or every day at the same time, you'll need to use something outside of WordPress. Common approaches to that include using the system task scheduler (on Linux, this is usually called \"cron\") or a third-party service like EasyCron.</p>\n\n<p>Assuming you're on a Linux server (by far the most common hosting environment), create a small shell script that looks like this:</p>\n\n<pre><code>#!/bin/bash\ncurl http://yoursite.name.com/wp-cron.php &gt;/dev/null\n</code></pre>\n\n<p>This will run the \"curl\" command, to load your site's wp-cron.php page, then immediately ignore the results (by dumping the output to /dev/null). You don't care about any output the page might have, and in fact there normally isn't any output. You just want to be sure the page is loaded.</p>\n\n<p>Then, add a line to your crontab (\"crontab -e\" will open the crontab file in your default editor, probably <em>vi</em>) that looks something like this:</p>\n\n<pre><code>0 0,12 * * * /home/user/touch-site.sh\n</code></pre>\n\n<p>(Obviously, modify the file location to wherever you put your script. Also, be sure the script is executable by running \"chmod 700 touch-site.sh\".)</p>\n\n<p>This example will visit your site daily, at noon and midnight (server time), and run the wp-cron script. For more details on how this file works, run \"man crontab\". </p>\n" }, { "answer_id": 222266, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 0, "selected": false, "text": "<p>To answer your this query</p>\n\n<blockquote>\n <p><em>@sumit Are you sure about that? One of my friend said that if today it happens in 1.20 a.m next day it will happen after 1.20 a.m, not the 12 a.m.</em></p>\n</blockquote>\n\n<p><strong>How it works:</strong></p>\n\n<ol>\n<li><p>You schedule an event using current time stamp i.e. 12:00 AM on Monday</p>\n\n<pre><code>wp_schedule_event(time(), 'daily', 'my_schedule_hook');\n</code></pre></li>\n<li><p>Someone visited the site on Monday at 1:20 AM.</p></li>\n</ol>\n\n<p>WP call this piece of code </p>\n\n<pre><code> if ( $schedule != false ) {\n $new_args = array($timestamp, $schedule, $hook, $v['args']);\n call_user_func_array('wp_reschedule_event', $new_args);\n }\n\n wp_unschedule_event( $timestamp, $hook, $v['args'] );\n\n /**\n * Fires scheduled events.\n *\n * @ignore\n * @since 2.1.0\n *\n * @param string $hook Name of the hook that was scheduled to be fired.\n * @param array $args The arguments to be passed to the hook.\n */\n do_action_ref_array( $hook, $v['args'] );\n</code></pre>\n\n<p>Here it is calling <code>wp_reschedule_event()</code> function which uses the same timestamp so the next schedule will be Tuesday 12:00 AM <strong>NOT</strong> 1:20 AM. Then it will call schedule action hook.</p>\n\n<ol start=\"3\">\n<li><p>Common mistake people do is they call <code>wp_schedule_event()</code> directly in <code>functions.php</code> so WP schedule event on every new timestamp. The correct way is check if schedule is there only then create it.</p>\n\n<pre><code>$my_schedule_hook = wp_next_scheduled('my_schedule_hook');\nif (!$my_schedule_hook) {\n wp_schedule_event(time(), 'daily', 'my_schedule_hook');\n}\n</code></pre></li>\n</ol>\n\n<p>Thus it will only go inside the <code>if</code> block only at first time when there will be no schedule at all.\nStill you can view all the schedule by this plugin <a href=\"https://wordpress.org/plugins/wp-crontrol/\" rel=\"nofollow\">WP Crontrol</a></p>\n" } ]
2016/03/31
[ "https://wordpress.stackexchange.com/questions/222172", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91136/" ]
I have a daily wp schedule event. I know that it happens when a user visits the site and if a schedule time passes. If I started it on today 12 a.m. and if tomorrow first visitor comes tomorrow 1:20 a.m. that event happen tomorrow 1:20 a.m.. Day after day, it happens after 1.20 a.m. or after 12 a.m.?
*wp-cron* is often called a pseudo-cron, because it doesn't run on a strict schedule. If nobody visits the site, it doesn't run. If you schedule a wp-cron event to run, say, every 12 hours, it will run *at most* every 12 hours. But, if your site has very little traffic, there could be far more than 12 hours between runs. If you need an event to happen every 12 hours, or every day at the same time, you'll need to use something outside of WordPress. Common approaches to that include using the system task scheduler (on Linux, this is usually called "cron") or a third-party service like EasyCron. Assuming you're on a Linux server (by far the most common hosting environment), create a small shell script that looks like this: ``` #!/bin/bash curl http://yoursite.name.com/wp-cron.php >/dev/null ``` This will run the "curl" command, to load your site's wp-cron.php page, then immediately ignore the results (by dumping the output to /dev/null). You don't care about any output the page might have, and in fact there normally isn't any output. You just want to be sure the page is loaded. Then, add a line to your crontab ("crontab -e" will open the crontab file in your default editor, probably *vi*) that looks something like this: ``` 0 0,12 * * * /home/user/touch-site.sh ``` (Obviously, modify the file location to wherever you put your script. Also, be sure the script is executable by running "chmod 700 touch-site.sh".) This example will visit your site daily, at noon and midnight (server time), and run the wp-cron script. For more details on how this file works, run "man crontab".
222,200
<p>I need to get the subscription key of a particular subscription to pass into a custom function. I have referenced the documentation where it shows how to get the key, but I have failed to integrate this into my code. So what my code does is, when a renewal is triggered, I hook into processed_subscription_payment with my function. So this code is run only when a subscription renewal is payed. Code is below.</p> <p>Documentation is here: <a href="https://docs.woothemes.com/document/subscriptions/develop/functions/management-functions/" rel="nofollow">https://docs.woothemes.com/document/subscriptions/develop/functions/management-functions/</a></p> <p>Code here (which resides in functions.php):</p> <pre><code>add_action( 'processed_subscription_payment', 'callupdater' ); function callupdater() { //need to get the subscription key here to pass to updatedays() $key = ..... updatedays(key); } function updatedays($subscription_key) { //do some tasks with the key } </code></pre> <p>Any help is very much appreciated. I am very new to PHP so excuse my ignorance.</p>
[ { "answer_id": 222240, "author": "nerdalert", "author_id": 91410, "author_profile": "https://wordpress.stackexchange.com/users/91410", "pm_score": 3, "selected": true, "text": "<p>I figured out the answer, so I thought I'd post it. My code looks like this now and it works:</p>\n\n<pre><code>add_action( 'processed_subscription_payment', 'updatedays', 10, 2 );\n\nfunction updatedays($user_id, $subscription_key)\n{ \n //do what I need to the sub key\n}\n</code></pre>\n\n<p>There really needs to be more examples on the Woothemes documentation though..</p>\n" }, { "answer_id": 249425, "author": "Diaz Adhyatma", "author_id": 109063, "author_profile": "https://wordpress.stackexchange.com/users/109063", "pm_score": 1, "selected": false, "text": "<p>As long as you can get Order Id, you can can use this code.</p>\n\n<pre><code>global $woocommerce;\n$order_id=12345;//PUT YOUR ORDER ID HERE\n$order = new WC_Order( $order_id );\nforeach ( WC_Subscriptions_Order::get_recurring_items( $order ) as $order_item ) {\n $subscription_key = WC_Subscriptions_Manager::get_subscription_key( $order-&gt;id, WC_Subscriptions_Order::get_items_product_id( $order_item ) );\n}\necho $subscription_key;\n</code></pre>\n" } ]
2016/03/31
[ "https://wordpress.stackexchange.com/questions/222200", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91410/" ]
I need to get the subscription key of a particular subscription to pass into a custom function. I have referenced the documentation where it shows how to get the key, but I have failed to integrate this into my code. So what my code does is, when a renewal is triggered, I hook into processed\_subscription\_payment with my function. So this code is run only when a subscription renewal is payed. Code is below. Documentation is here: <https://docs.woothemes.com/document/subscriptions/develop/functions/management-functions/> Code here (which resides in functions.php): ``` add_action( 'processed_subscription_payment', 'callupdater' ); function callupdater() { //need to get the subscription key here to pass to updatedays() $key = ..... updatedays(key); } function updatedays($subscription_key) { //do some tasks with the key } ``` Any help is very much appreciated. I am very new to PHP so excuse my ignorance.
I figured out the answer, so I thought I'd post it. My code looks like this now and it works: ``` add_action( 'processed_subscription_payment', 'updatedays', 10, 2 ); function updatedays($user_id, $subscription_key) { //do what I need to the sub key } ``` There really needs to be more examples on the Woothemes documentation though..
222,203
<p>I'm working on a page template and I need <code>the_title</code> to be separate from the page text. I'm not sure how to load <code>the_content</code> without it having the title. Can anyone help?</p>
[ { "answer_id": 222204, "author": "Marta", "author_id": 18097, "author_profile": "https://wordpress.stackexchange.com/users/18097", "pm_score": 0, "selected": false, "text": "<p>It's very possible that you have a function or a plugin that is inserting into your content the title.</p>\n\n<p>To check if that's right, try to use <code>get_the_content()</code>, it's a function that does not pass the content through the <code>the_content()</code>(important: <code>get_the_content()</code> will not expand shortcodes)</p>\n" }, { "answer_id": 223048, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 0, "selected": false, "text": "<p>The following code only load the content of page template</p>\n\n<pre><code>&lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post();\n the_content(); // show the content\n endwhile; else: ?&gt;\n &lt;p&gt;Sorry, no posts matched your criteria.&lt;/p&gt;\n &lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 223054, "author": "1Bladesforhire", "author_id": 81382, "author_profile": "https://wordpress.stackexchange.com/users/81382", "pm_score": 1, "selected": false, "text": "<pre><code> &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post();\n the_title( '&lt;h3&gt;', '&lt;/h3&gt;' );// puts the title in h3 tags\n\n the_content(); // adds the content\n endwhile; else: ?&gt;\n &lt;p&gt;Sorry, no posts matched your criteria.&lt;/p&gt;\n &lt;?php endif; ?&gt;\n</code></pre>\n\n<p>Notice that you can use the title function where you want as long as it is after the if/while/the_post and before the endwhile; This is how you retrieve the title and the content in separate areas. I can't comment on this part of stackexchange, but hope this helps.</p>\n" } ]
2016/03/31
[ "https://wordpress.stackexchange.com/questions/222203", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85626/" ]
I'm working on a page template and I need `the_title` to be separate from the page text. I'm not sure how to load `the_content` without it having the title. Can anyone help?
``` <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title( '<h3>', '</h3>' );// puts the title in h3 tags the_content(); // adds the content endwhile; else: ?> <p>Sorry, no posts matched your criteria.</p> <?php endif; ?> ``` Notice that you can use the title function where you want as long as it is after the if/while/the\_post and before the endwhile; This is how you retrieve the title and the content in separate areas. I can't comment on this part of stackexchange, but hope this helps.
222,205
<p>I am pretty new to WordPress API, loving it btw, I have a small project, adding a like button to the end of every post, pressing it makes user like the post, button changes to dislike, pressing again makes user dislike the post.</p> <p>Without the knowledge of WordPress API, I planned to create a table for my plugin in wpdb which I will store the post-id and user-ids. Plugin will know by querying the table if the user has already liked the post. But on the internet I found a lot of examples of like buttons, not creating a custom table and using update_post_meta, and if I understood right update_post_meta does not alter any table in the database or insert new rows. Because I tried some of the plugins which uses update_post_meta and after liking a post, my wp_posts and wp_postmeta tables does not change at all.</p> <p>My question is where exactly is post_meta stored, where does wordpress store the new custom field 'like_count' if I do this;</p> <pre><code>update_post_meta($post_id, 'like_count',1); </code></pre>
[ { "answer_id": 222210, "author": "Luis Alberto Gonzalez Noguera", "author_id": 91533, "author_profile": "https://wordpress.stackexchange.com/users/91533", "pm_score": 0, "selected": false, "text": "<p>The post meta (also known as custom fields) helps us to associate more content with a post. This content could be anything you want to associate with your post, in your case \"likes\".<br/>\nSo yes your wp_postmeta table should get modified when you use update_post_meta function.</p>\n\n<p>This is the structure of the wp_postmeta table</p>\n\n<pre>\nCREATE TABLE IF NOT EXISTS `wp_postmeta` (\n `meta_id` bigint(20) unsigned NOT NULL,\n `post_id` bigint(20) unsigned NOT NULL DEFAULT '0',\n `meta_key` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,\n `meta_value` longtext COLLATE utf8mb4_unicode_ci\n) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\n</pre>\n\n<p>meta_id is just an internal id<br/>\npost_id will be your post id that your adding your meta data or extra info to.<br/>\nmeta_key will be the key of your new info in your case will be something like 'likes'<br/>\nmeta_value will be the value in your case will be the user_id<br/></p>\n\n<p>So for any post you could have more than one row with likes, each row for each user that like the post.<br/></p>\n\n<p>Or if you just want to save the number of likes and don't care for the user. You can use a meta key like you said \"like_count\" and just update that value every time someone likes the post.</p>\n" }, { "answer_id": 222213, "author": "Arpita Hunka", "author_id": 86864, "author_profile": "https://wordpress.stackexchange.com/users/86864", "pm_score": 2, "selected": true, "text": "<p>Yes, we can use existing tables in WordPress for storing the values.<br>\nPost meta fields are stored in the <code>{$wpdb-&gt;prefix}_postmeta</code> table (depending on the table prefix; <code>wp_postmeta</code> by default). If the meta key <code>\"like_count\"</code> is already present in the table along with the post ID then <code>update_post_meta()</code> will update this, and otherwise this function will insert a new row with this key.</p>\n\n<p>For more reference you can check here : <a href=\"https://codex.wordpress.org/Function_Reference/update_post_meta\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/update_post_meta</a></p>\n" } ]
2016/03/31
[ "https://wordpress.stackexchange.com/questions/222205", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91527/" ]
I am pretty new to WordPress API, loving it btw, I have a small project, adding a like button to the end of every post, pressing it makes user like the post, button changes to dislike, pressing again makes user dislike the post. Without the knowledge of WordPress API, I planned to create a table for my plugin in wpdb which I will store the post-id and user-ids. Plugin will know by querying the table if the user has already liked the post. But on the internet I found a lot of examples of like buttons, not creating a custom table and using update\_post\_meta, and if I understood right update\_post\_meta does not alter any table in the database or insert new rows. Because I tried some of the plugins which uses update\_post\_meta and after liking a post, my wp\_posts and wp\_postmeta tables does not change at all. My question is where exactly is post\_meta stored, where does wordpress store the new custom field 'like\_count' if I do this; ``` update_post_meta($post_id, 'like_count',1); ```
Yes, we can use existing tables in WordPress for storing the values. Post meta fields are stored in the `{$wpdb->prefix}_postmeta` table (depending on the table prefix; `wp_postmeta` by default). If the meta key `"like_count"` is already present in the table along with the post ID then `update_post_meta()` will update this, and otherwise this function will insert a new row with this key. For more reference you can check here : <https://codex.wordpress.org/Function_Reference/update_post_meta>
222,219
<p>I want to display the post archives like seen in this picture. Shown by year and on click it should open up the months. I am not sure how to approach this, would you customize the standard WordPress Archives Widget?</p> <p><a href="https://i.stack.imgur.com/2bJDl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2bJDl.png" alt="enter image description here"></a></p>
[ { "answer_id": 222235, "author": "Isaac Lubow", "author_id": 2150, "author_profile": "https://wordpress.stackexchange.com/users/2150", "pm_score": -1, "selected": false, "text": "<p>The \"Archives\" Widget makes use of <a href=\"https://developer.wordpress.org/reference/functions/wp_get_archives/\" rel=\"nofollow\"><code>wp_get_archives()</code></a> which, given the correct arguments (specifically the <code>format</code> argument), can supply the markup you need. I'd say customizing that Widget is a good place to start.</p>\n" }, { "answer_id": 230622, "author": "Ciprian", "author_id": 7349, "author_profile": "https://wordpress.stackexchange.com/users/7349", "pm_score": 2, "selected": false, "text": "<p>I did this for a client and it looked like this:</p>\n<p>The PHP code:</p>\n<pre><code>&lt;dl class=&quot;tree-accordion&quot;&gt;\n &lt;?php\n $currentyear = date(&quot;Y&quot;);\n $years = range($currentyear, 1950);\n foreach($years as $year) { ?&gt;\n &lt;dt&gt;&lt;a href=&quot;&quot;&gt;&lt;i class=&quot;fa fa-fw fa-plus-square-o&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt; &lt;?php echo $year; ?&gt;&lt;/a&gt;&lt;/dt&gt;\n &lt;?php\n $archi = wp_get_archives('echo=0&amp;show_post_count=1&amp;type=monthly&amp;year=' . $year);\n $archi = explode('&lt;/li&gt;', $archi);\n $links = array();\n foreach($archi as $link) {\n $link = str_replace(array('&lt;li&gt;', &quot;\\n&quot;, &quot;\\t&quot;, &quot;\\s&quot;), '' , $link);\n if('' != $link)\n $links[] = $link;\n else\n continue;\n }\n $fliplinks = array_reverse($links);\n if(!empty($fliplinks)) {\n echo '&lt;dd&gt;';\n foreach($fliplinks as $link) {\n echo '&lt;span&gt;' . $link . '&lt;/span&gt;';\n }\n echo '&lt;/dd&gt;';\n } else {\n echo '&lt;dd class=&quot;tree-accordion-empty&quot;&gt;&lt;/dd&gt;';\n }\n ?&gt;\n &lt;?php } ?&gt;\n&lt;/dl&gt;\n</code></pre>\n<p>The archives override filter:</p>\n<pre><code>/*\n * Add filter to query archives by year\n */\nfunction newmarket_getarchives_filter($where, $args) {\n if(isset($args['year'])) {\n $where .= ' AND YEAR(post_date) = ' . intval($args['year']);\n }\n\n return $where;\n}\n\nadd_filter('getarchives_where', 'newmarket_getarchives_filter', 10, 2);\n</code></pre>\n<p>The CSS code:</p>\n<pre><code>.tree-accordion {\n line-height: 1.5;\n}\n.tree-accordion dt, .tree-accordion dd {}\n.tree-accordion dt a {\n display: block;\n}\n.tree-accordion .fa {\n color: #666666;\n}\n.tree-accordion dd a {}\n.tree-accordion dd span {\n display: block;\n}\n.tree-accordion dd {\n margin: 0 0 0 20px;\n}\n</code></pre>\n<p>The Javascript code:</p>\n<pre><code>jQuery(document).ready(function(){\n var allPanels = jQuery('.tree-accordion &gt; dd').hide();\n\n jQuery('.tree-accordion &gt; dt &gt; a').click(function() {\n $target = jQuery(this).parent().next();\n\n if(!$target.hasClass('active')) {\n allPanels.removeClass('active').slideUp();\n $target.addClass('active').slideDown(100);\n }\n\n return false;\n });\n\n jQuery('.tree-accordion-empty').prev().hide();\n});\n</code></pre>\n<p><strong>UPDATE:</strong> Remove year after month:</p>\n<p>Change this line:</p>\n<pre><code>$link = str_replace(array('&lt;li&gt;', &quot;\\n&quot;, &quot;\\t&quot;, &quot;\\s&quot;), '' , $link);\n</code></pre>\n<p>To:</p>\n<pre><code>$link = str_replace(array('&lt;li&gt;', &quot;\\n&quot;, &quot;\\t&quot;, &quot;\\s&quot;), '', $link);\n$link = str_replace($year, '', $link);\n</code></pre>\n<p>The final result:</p>\n<p><a href=\"https://i.stack.imgur.com/hbYth.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hbYth.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2016/03/31
[ "https://wordpress.stackexchange.com/questions/222219", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67074/" ]
I want to display the post archives like seen in this picture. Shown by year and on click it should open up the months. I am not sure how to approach this, would you customize the standard WordPress Archives Widget? [![enter image description here](https://i.stack.imgur.com/2bJDl.png)](https://i.stack.imgur.com/2bJDl.png)
I did this for a client and it looked like this: The PHP code: ``` <dl class="tree-accordion"> <?php $currentyear = date("Y"); $years = range($currentyear, 1950); foreach($years as $year) { ?> <dt><a href=""><i class="fa fa-fw fa-plus-square-o" aria-hidden="true"></i> <?php echo $year; ?></a></dt> <?php $archi = wp_get_archives('echo=0&show_post_count=1&type=monthly&year=' . $year); $archi = explode('</li>', $archi); $links = array(); foreach($archi as $link) { $link = str_replace(array('<li>', "\n", "\t", "\s"), '' , $link); if('' != $link) $links[] = $link; else continue; } $fliplinks = array_reverse($links); if(!empty($fliplinks)) { echo '<dd>'; foreach($fliplinks as $link) { echo '<span>' . $link . '</span>'; } echo '</dd>'; } else { echo '<dd class="tree-accordion-empty"></dd>'; } ?> <?php } ?> </dl> ``` The archives override filter: ``` /* * Add filter to query archives by year */ function newmarket_getarchives_filter($where, $args) { if(isset($args['year'])) { $where .= ' AND YEAR(post_date) = ' . intval($args['year']); } return $where; } add_filter('getarchives_where', 'newmarket_getarchives_filter', 10, 2); ``` The CSS code: ``` .tree-accordion { line-height: 1.5; } .tree-accordion dt, .tree-accordion dd {} .tree-accordion dt a { display: block; } .tree-accordion .fa { color: #666666; } .tree-accordion dd a {} .tree-accordion dd span { display: block; } .tree-accordion dd { margin: 0 0 0 20px; } ``` The Javascript code: ``` jQuery(document).ready(function(){ var allPanels = jQuery('.tree-accordion > dd').hide(); jQuery('.tree-accordion > dt > a').click(function() { $target = jQuery(this).parent().next(); if(!$target.hasClass('active')) { allPanels.removeClass('active').slideUp(); $target.addClass('active').slideDown(100); } return false; }); jQuery('.tree-accordion-empty').prev().hide(); }); ``` **UPDATE:** Remove year after month: Change this line: ``` $link = str_replace(array('<li>', "\n", "\t", "\s"), '' , $link); ``` To: ``` $link = str_replace(array('<li>', "\n", "\t", "\s"), '', $link); $link = str_replace($year, '', $link); ``` The final result: [![enter image description here](https://i.stack.imgur.com/hbYth.png)](https://i.stack.imgur.com/hbYth.png)
222,231
<p>I have this 'primary' menu with a few items in the CMS, which I can list nicely with this <strong>PHP code:</strong></p> <pre><code>$args = array( 'theme_location' =&gt; 'primary' ); wp_nav_menu( $args ); </code></pre> <p>The PHP outputs the menu with the <code>&lt;ul&gt;</code> tag. but, I want to use <strong>HTML</strong> that looks like this:</p> <pre><code>&lt;ul class="nav navbar-nav"&gt; &lt;!-- primary menu items --&gt; &lt;/ul&gt; </code></pre> <p>I'm looking for the right way to output my primary menu with the HTML from above.</p>
[ { "answer_id": 222232, "author": "Marttin Notta", "author_id": 91525, "author_profile": "https://wordpress.stackexchange.com/users/91525", "pm_score": 0, "selected": false, "text": "<p>From your question i'm guessing you don't want wrapping divs around your tags. To remove them just add that extra line to your <code>$args</code>. If this is not the answer can you please specify the problem.</p>\n\n<pre><code>$args = array(\n 'theme_location' =&gt; 'primary',\n 'container' =&gt; ''\n);\n\nwp_nav_menu( $args );\n</code></pre>\n" }, { "answer_id": 222233, "author": "Isaac Lubow", "author_id": 2150, "author_profile": "https://wordpress.stackexchange.com/users/2150", "pm_score": 2, "selected": true, "text": "<p>You can change the classes of the <code>&lt;ul&gt;</code> by adding <code>'menu_class'=&gt;'nav navbar-nav'</code> to your <code>$args</code> array. <em>Remember, this parameter overwrites all the classes, so add \"menu\" as well if you want many themes and plugins to work!</em></p>\n\n<p>If you don't want the outer <code>&lt;div&gt;</code>, you can \"unwrap\" the <code>&lt;ul&gt;</code> by adding <code>'container'=&gt;false</code>.</p>\n\n<pre><code>$args = array(\n 'theme_location' =&gt; 'primary',\n 'menu_class' =&gt; 'nav navbar-nav',\n 'container' =&gt; false,\n);\n</code></pre>\n\n<p>See the full reference <a href=\"https://developer.wordpress.org/reference/functions/wp_nav_menu/\" rel=\"nofollow\">here</a>.</p>\n" } ]
2016/03/31
[ "https://wordpress.stackexchange.com/questions/222231", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91540/" ]
I have this 'primary' menu with a few items in the CMS, which I can list nicely with this **PHP code:** ``` $args = array( 'theme_location' => 'primary' ); wp_nav_menu( $args ); ``` The PHP outputs the menu with the `<ul>` tag. but, I want to use **HTML** that looks like this: ``` <ul class="nav navbar-nav"> <!-- primary menu items --> </ul> ``` I'm looking for the right way to output my primary menu with the HTML from above.
You can change the classes of the `<ul>` by adding `'menu_class'=>'nav navbar-nav'` to your `$args` array. *Remember, this parameter overwrites all the classes, so add "menu" as well if you want many themes and plugins to work!* If you don't want the outer `<div>`, you can "unwrap" the `<ul>` by adding `'container'=>false`. ``` $args = array( 'theme_location' => 'primary', 'menu_class' => 'nav navbar-nav', 'container' => false, ); ``` See the full reference [here](https://developer.wordpress.org/reference/functions/wp_nav_menu/).
222,238
<p>I have two loops in home page (index.php)</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; 3, ); $another_query = new WP_Query($args); if( $another_query-&gt;have_posts() ) { $i = 0; while ($another_query-&gt;have_posts()) : $another_query-&gt;the_post(); ?&gt; &lt;?php if($i == 0) { ?&gt; &lt;div class="col s8"&gt; &lt;?php get_template_part( 'template-parts/content-magazine-grid-big', get_post_format() ); ?&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php if($i == 1 || $i == 2) { ?&gt; &lt;div class="col s4"&gt; &lt;?php get_template_part( 'template-parts/content-magazine-grid-small', get_post_format() ); ?&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php $i++; if($i != 0) { ?&gt; &lt;?php } ?&gt; &lt;?php endwhile; } wp_reset_postdata(); ?&gt; </code></pre> <p>And another one</p> <pre><code> &lt;?php $args = array( 'post_type' =&gt; 'post', 'paged' =&gt; $paged, 'posts_per_page' =&gt; 2, 'offset' =&gt; 3, 'orderby' =&gt; 'date', 'order' =&gt; 'DESC', ); $args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; $i=0; $query = new WP_Query($args); $temp_query = $wp_query; $wp_query = NULL; $wp_query = $query; while ($query-&gt;have_posts()) : $query-&gt;the_post(); ?&gt; &lt;?php get_template_part( 'template-parts/content-rest', get_post_format() ); ?&gt; &lt;?php $i++; endwhile; ?&gt; &lt;?php previous_posts_link();next_posts_link(); ?&gt; &lt;?php // Need this to reset the query $wp_query = NULL; $wp_query = $temp_query; ?&gt; </code></pre> <p>I want pagination on last loop.. But it's not working...</p>
[ { "answer_id": 222247, "author": "nicogaldo", "author_id": 87880, "author_profile": "https://wordpress.stackexchange.com/users/87880", "pm_score": 0, "selected": false, "text": "<p>I have not tried it, but I think it should be like this:</p>\n\n<pre><code>$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;\n$args = array(\n 'post_type' =&gt; 'post',\n 'paged' =&gt; $paged,\n 'posts_per_page' =&gt; 2,\n 'offset' =&gt; 3,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC'\n);\n</code></pre>\n" }, { "answer_id": 222256, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>You do need to run a custom query for your second loop. You can simply adjust the main query to your needs. It is always never a good idea to run custom queries in place of the main query. One big issue is always pagination, WordPress disregards all other queries, and only focus on the main query when it comes to page functionality. I have done a quite extensive post on this, so be sure to check it out <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">here</a></p>\n\n<p>We can drop the second query, and just use <code>pre_get_posts</code> to alter the main query. Because we use offset here, we need to manually calculate pagination as we are breaking <code>WP_Query</code>'s process which calculates pagination</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( $q-&gt;is_home() // Only target the home page\n &amp;&amp; $q-&gt;is_main_query() // Only target the main query\n ) {\n // Get the current page number\n $current_page = get_query_var( 'paged', 1 );\n // Set offset\n $offset = 3;\n // Set posts per page\n $ppp = 2;\n\n if ( !$q-&gt;is_paged() ) {\n // Set page one offset\n $q-&gt;set( 'offset', $offset );\n $q-&gt;set( 'posts_per_page', $ppp );\n } else {\n // Handle pagination for paged pages\n $offset = $offset + ( ( $current_page - 1 ) * $ppp );\n $q-&gt;set( 'offset', $offset );\n $q-&gt;set( 'posts_per_page', $ppp );\n }\n }\n});\n</code></pre>\n\n<p>You should now have your main query correctly paginated with one problem, the last page might, depending on the amount of posts, 404'ing. To adjust for that, we need to adjust the <code>$found_posts</code> property of the main query.</p>\n\n<pre><code>add_filter( 'found_posts', function ( $found_posts, $q ) \n{\n $offset = 3;\n\n if( $q-&gt;is_home() \n &amp;&amp; $q-&gt;is_main_query() \n ) {\n $found_posts = $found_posts - $offset;\n }\n\n return $found_posts;\n}, 10, 2 );\n</code></pre>\n\n<p>Needless to say, your main loop on your homepage should now just be as follow</p>\n\n<pre><code>if ( have_posts() ) :\n while ( have_posts()) : \n the_post(); \n\n get_template_part( 'template-parts/content-rest', get_post_format() );\n\n endwhile;\n previous_posts_link();\n next_posts_link();\nendif;\n</code></pre>\n" } ]
2016/03/31
[ "https://wordpress.stackexchange.com/questions/222238", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I have two loops in home page (index.php) ``` <?php $args = array( 'post_type' => 'post', 'posts_per_page' => 3, ); $another_query = new WP_Query($args); if( $another_query->have_posts() ) { $i = 0; while ($another_query->have_posts()) : $another_query->the_post(); ?> <?php if($i == 0) { ?> <div class="col s8"> <?php get_template_part( 'template-parts/content-magazine-grid-big', get_post_format() ); ?> </div> <?php } ?> <?php if($i == 1 || $i == 2) { ?> <div class="col s4"> <?php get_template_part( 'template-parts/content-magazine-grid-small', get_post_format() ); ?> </div> <?php } ?> <?php $i++; if($i != 0) { ?> <?php } ?> <?php endwhile; } wp_reset_postdata(); ?> ``` And another one ``` <?php $args = array( 'post_type' => 'post', 'paged' => $paged, 'posts_per_page' => 2, 'offset' => 3, 'orderby' => 'date', 'order' => 'DESC', ); $args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; $i=0; $query = new WP_Query($args); $temp_query = $wp_query; $wp_query = NULL; $wp_query = $query; while ($query->have_posts()) : $query->the_post(); ?> <?php get_template_part( 'template-parts/content-rest', get_post_format() ); ?> <?php $i++; endwhile; ?> <?php previous_posts_link();next_posts_link(); ?> <?php // Need this to reset the query $wp_query = NULL; $wp_query = $temp_query; ?> ``` I want pagination on last loop.. But it's not working...
You do need to run a custom query for your second loop. You can simply adjust the main query to your needs. It is always never a good idea to run custom queries in place of the main query. One big issue is always pagination, WordPress disregards all other queries, and only focus on the main query when it comes to page functionality. I have done a quite extensive post on this, so be sure to check it out [here](https://wordpress.stackexchange.com/a/155976/31545) We can drop the second query, and just use `pre_get_posts` to alter the main query. Because we use offset here, we need to manually calculate pagination as we are breaking `WP_Query`'s process which calculates pagination ``` add_action( 'pre_get_posts', function ( $q ) { if ( $q->is_home() // Only target the home page && $q->is_main_query() // Only target the main query ) { // Get the current page number $current_page = get_query_var( 'paged', 1 ); // Set offset $offset = 3; // Set posts per page $ppp = 2; if ( !$q->is_paged() ) { // Set page one offset $q->set( 'offset', $offset ); $q->set( 'posts_per_page', $ppp ); } else { // Handle pagination for paged pages $offset = $offset + ( ( $current_page - 1 ) * $ppp ); $q->set( 'offset', $offset ); $q->set( 'posts_per_page', $ppp ); } } }); ``` You should now have your main query correctly paginated with one problem, the last page might, depending on the amount of posts, 404'ing. To adjust for that, we need to adjust the `$found_posts` property of the main query. ``` add_filter( 'found_posts', function ( $found_posts, $q ) { $offset = 3; if( $q->is_home() && $q->is_main_query() ) { $found_posts = $found_posts - $offset; } return $found_posts; }, 10, 2 ); ``` Needless to say, your main loop on your homepage should now just be as follow ``` if ( have_posts() ) : while ( have_posts()) : the_post(); get_template_part( 'template-parts/content-rest', get_post_format() ); endwhile; previous_posts_link(); next_posts_link(); endif; ```
222,244
<p>Im trying to override the admin email template text "New customer order" to "New order" in function.php, but i can not finde any info on google. Can somebody please give me a hint! :)</p>
[ { "answer_id": 222247, "author": "nicogaldo", "author_id": 87880, "author_profile": "https://wordpress.stackexchange.com/users/87880", "pm_score": 0, "selected": false, "text": "<p>I have not tried it, but I think it should be like this:</p>\n\n<pre><code>$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;\n$args = array(\n 'post_type' =&gt; 'post',\n 'paged' =&gt; $paged,\n 'posts_per_page' =&gt; 2,\n 'offset' =&gt; 3,\n 'orderby' =&gt; 'date',\n 'order' =&gt; 'DESC'\n);\n</code></pre>\n" }, { "answer_id": 222256, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>You do need to run a custom query for your second loop. You can simply adjust the main query to your needs. It is always never a good idea to run custom queries in place of the main query. One big issue is always pagination, WordPress disregards all other queries, and only focus on the main query when it comes to page functionality. I have done a quite extensive post on this, so be sure to check it out <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">here</a></p>\n\n<p>We can drop the second query, and just use <code>pre_get_posts</code> to alter the main query. Because we use offset here, we need to manually calculate pagination as we are breaking <code>WP_Query</code>'s process which calculates pagination</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( $q-&gt;is_home() // Only target the home page\n &amp;&amp; $q-&gt;is_main_query() // Only target the main query\n ) {\n // Get the current page number\n $current_page = get_query_var( 'paged', 1 );\n // Set offset\n $offset = 3;\n // Set posts per page\n $ppp = 2;\n\n if ( !$q-&gt;is_paged() ) {\n // Set page one offset\n $q-&gt;set( 'offset', $offset );\n $q-&gt;set( 'posts_per_page', $ppp );\n } else {\n // Handle pagination for paged pages\n $offset = $offset + ( ( $current_page - 1 ) * $ppp );\n $q-&gt;set( 'offset', $offset );\n $q-&gt;set( 'posts_per_page', $ppp );\n }\n }\n});\n</code></pre>\n\n<p>You should now have your main query correctly paginated with one problem, the last page might, depending on the amount of posts, 404'ing. To adjust for that, we need to adjust the <code>$found_posts</code> property of the main query.</p>\n\n<pre><code>add_filter( 'found_posts', function ( $found_posts, $q ) \n{\n $offset = 3;\n\n if( $q-&gt;is_home() \n &amp;&amp; $q-&gt;is_main_query() \n ) {\n $found_posts = $found_posts - $offset;\n }\n\n return $found_posts;\n}, 10, 2 );\n</code></pre>\n\n<p>Needless to say, your main loop on your homepage should now just be as follow</p>\n\n<pre><code>if ( have_posts() ) :\n while ( have_posts()) : \n the_post(); \n\n get_template_part( 'template-parts/content-rest', get_post_format() );\n\n endwhile;\n previous_posts_link();\n next_posts_link();\nendif;\n</code></pre>\n" } ]
2016/03/31
[ "https://wordpress.stackexchange.com/questions/222244", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91547/" ]
Im trying to override the admin email template text "New customer order" to "New order" in function.php, but i can not finde any info on google. Can somebody please give me a hint! :)
You do need to run a custom query for your second loop. You can simply adjust the main query to your needs. It is always never a good idea to run custom queries in place of the main query. One big issue is always pagination, WordPress disregards all other queries, and only focus on the main query when it comes to page functionality. I have done a quite extensive post on this, so be sure to check it out [here](https://wordpress.stackexchange.com/a/155976/31545) We can drop the second query, and just use `pre_get_posts` to alter the main query. Because we use offset here, we need to manually calculate pagination as we are breaking `WP_Query`'s process which calculates pagination ``` add_action( 'pre_get_posts', function ( $q ) { if ( $q->is_home() // Only target the home page && $q->is_main_query() // Only target the main query ) { // Get the current page number $current_page = get_query_var( 'paged', 1 ); // Set offset $offset = 3; // Set posts per page $ppp = 2; if ( !$q->is_paged() ) { // Set page one offset $q->set( 'offset', $offset ); $q->set( 'posts_per_page', $ppp ); } else { // Handle pagination for paged pages $offset = $offset + ( ( $current_page - 1 ) * $ppp ); $q->set( 'offset', $offset ); $q->set( 'posts_per_page', $ppp ); } } }); ``` You should now have your main query correctly paginated with one problem, the last page might, depending on the amount of posts, 404'ing. To adjust for that, we need to adjust the `$found_posts` property of the main query. ``` add_filter( 'found_posts', function ( $found_posts, $q ) { $offset = 3; if( $q->is_home() && $q->is_main_query() ) { $found_posts = $found_posts - $offset; } return $found_posts; }, 10, 2 ); ``` Needless to say, your main loop on your homepage should now just be as follow ``` if ( have_posts() ) : while ( have_posts()) : the_post(); get_template_part( 'template-parts/content-rest', get_post_format() ); endwhile; previous_posts_link(); next_posts_link(); endif; ```
222,268
<p>I have an admin form for a plugin I am making. However, there are a couple of fields I need to add where the admin need to upload a document or image. When these files are uploaded, I do not want them to be added to the media library of WordPress as these files won't be used on any web pages. All I need is just the URL of where the file has been uploaded to on the server to use in the database. </p> <p>What would be the best way to achieve this?</p> <p>Thanks for your time!</p>
[ { "answer_id": 222270, "author": "dg4220", "author_id": 91201, "author_profile": "https://wordpress.stackexchange.com/users/91201", "pm_score": 0, "selected": false, "text": "<p>I think it depends on how you're handling the file input field in your form. I've used <a href=\"https://codex.wordpress.org/Function_Reference/wp_upload_bits\" rel=\"nofollow\">wp_upload_bits()</a> in a plugin with a custom post type that has file attachments. The file is attached and uploaded using a metabox for the CPT and wp_upload_bits is called in the 'save_file_function' function called with <code>add_action( 'save_post', 'save_file_function' );</code> This would all go in your main plugin .php file.</p>\n" }, { "answer_id": 222282, "author": "Patrick", "author_id": 65721, "author_profile": "https://wordpress.stackexchange.com/users/65721", "pm_score": 2, "selected": true, "text": "<h1>HTML</h1>\n<p>Okay, you'll of course want to set up an HTML file. I would use this code or something like it:</p>\n<pre><code>&lt;form action=&quot;upload.php&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;\n Select image to upload:\n &lt;input type=&quot;file&quot; name=&quot;fileToUpload&quot; id=&quot;fileToUpload&quot;&gt;\n &lt;input type=&quot;submit&quot; value=&quot;Upload Image&quot; name=&quot;submit&quot;&gt;\n&lt;/form&gt;\n</code></pre>\n<p>Of course, you don't have to use <code>upload.php</code> as your filename, that's just what w3schools used.</p>\n<h1>PHP</h1>\n<pre><code>&lt;?php\n$target_dir = &quot;your/file/upload/path&quot;;\n$target_file = $target_dir . basename($_FILES[&quot;fileToUpload&quot;][&quot;name&quot;]);\n$uploadOk = 1;\n$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);\n// Check if image file is a actual image or fake image\nif(isset($_POST[&quot;submit&quot;])) {\n $check = getimagesize($_FILES[&quot;fileToUpload&quot;][&quot;tmp_name&quot;]);\n if($check !== false) {\n echo &quot;File is an image - &quot; . $check[&quot;mime&quot;] . &quot;.&quot;;\n $uploadOk = 1;\n } else {\n echo &quot;File is not an image.&quot;;\n $uploadOk = 0;\n }\n}\n?&gt;\n</code></pre>\n<p>Change <code>$target_dir</code> to whatever directory you want the files to go into and there you go. There are of course many jQuery plugins to do this in a fancy or pretty way but this is the basics using jQuery.</p>\n<h2>Other information</h2>\n<hr />\n<p>Source of information: <a href=\"http://www.w3schools.com/php/php_file_upload.asp\" rel=\"nofollow noreferrer\">W3Schools</a></p>\n<p>A great Ajax file uploader script can be found here: <a href=\"http://demo.tutorialzine.com/2013/05/mini-ajax-file-upload-form/\" rel=\"nofollow noreferrer\">http://demo.tutorialzine.com/2013/05/mini-ajax-file-upload-form/</a></p>\n<p>A great jQuery file upload plugin can be found here:\n<a href=\"http://blueimp.github.io/jQuery-File-Upload/index.html\" rel=\"nofollow noreferrer\">http://blueimp.github.io/jQuery-File-Upload/index.html</a></p>\n<p>According to their website it supports:</p>\n<blockquote>\n<p>File Upload widget with multiple file selection, drag&amp;drop support,\nprogress bars, validation and preview images, audio and video for\njQuery. Supports cross-domain, chunked and resumable file uploads and\nclient-side image resizing. Works with any server-side platform (PHP,\nPython, Ruby on Rails, Java, Node.js, Go etc.) that supports standard\nHTML form file uploads.</p>\n</blockquote>\n" } ]
2016/03/31
[ "https://wordpress.stackexchange.com/questions/222268", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86404/" ]
I have an admin form for a plugin I am making. However, there are a couple of fields I need to add where the admin need to upload a document or image. When these files are uploaded, I do not want them to be added to the media library of WordPress as these files won't be used on any web pages. All I need is just the URL of where the file has been uploaded to on the server to use in the database. What would be the best way to achieve this? Thanks for your time!
HTML ==== Okay, you'll of course want to set up an HTML file. I would use this code or something like it: ``` <form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> ``` Of course, you don't have to use `upload.php` as your filename, that's just what w3schools used. PHP === ``` <?php $target_dir = "your/file/upload/path"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } ?> ``` Change `$target_dir` to whatever directory you want the files to go into and there you go. There are of course many jQuery plugins to do this in a fancy or pretty way but this is the basics using jQuery. Other information ----------------- --- Source of information: [W3Schools](http://www.w3schools.com/php/php_file_upload.asp) A great Ajax file uploader script can be found here: <http://demo.tutorialzine.com/2013/05/mini-ajax-file-upload-form/> A great jQuery file upload plugin can be found here: <http://blueimp.github.io/jQuery-File-Upload/index.html> According to their website it supports: > > File Upload widget with multiple file selection, drag&drop support, > progress bars, validation and preview images, audio and video for > jQuery. Supports cross-domain, chunked and resumable file uploads and > client-side image resizing. Works with any server-side platform (PHP, > Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard > HTML form file uploads. > > >
222,335
<p>I have stuck in serious problem. I want to create a document and upload a word doc from front end after user login. Logged in user is admin. The plugin bp-doc uses WordPress default media uploader to upload file. </p> <p>The plugin hits <code>.../wp-admin/async-upload.php</code>, but this throws an error <code>An error occurred in the upload. Please try again later</code>, after debuging in console I found <code>302 Moved Temporarily</code> error and in response there is WordPress login form.</p> <p>After doing some research I found another error, when I log in from frontend as an admin and goes back to <code>wp-admin</code> it logged me out and asks again to enter username and password.</p> <p>I unable to go through the errors, anyone can help me what may goes wrong?</p> <p>I uses the following code to login </p> <pre><code>$user_data = array(); $user_data['user_login'] = $username; $user_data['user_password'] = $password; $user_data['remember'] = $remember; $user = wp_signon( $user_data, false ); if ( is_wp_error($user) ) { $err = "&lt;strong&gt;ERROR!&lt;/strong&gt; Invalid username or password"; } else { wp_set_current_user( $user-&gt;ID); do_action('set_current_user'); global $current_user; get_currentuserinfo(); $redirect_to = home_url().'/members/'.$current_user-&gt;user_login.'/profile'; wp_redirect($redirect_to); exit; } </code></pre> <p>Live site url: <a href="https://www.group50.com/g50consultants" rel="nofollow">https://www.group50.com/g50consultants</a></p>
[ { "answer_id": 223002, "author": "Agustin Prosperi", "author_id": 91219, "author_profile": "https://wordpress.stackexchange.com/users/91219", "pm_score": 1, "selected": false, "text": "<p>Maybe your switching from https to http after login, you can try this plugin <a href=\"https://wordpress.org/plugins/https-redirection/\" rel=\"nofollow\">https://wordpress.org/plugins/https-redirection/</a> to redirect all your site to https, I used it once and also changed my site URL from http://... to https://.... in wodpress settings.</p>\n\n<p>I see that you can simplify your code in these lines:</p>\n\n<pre><code>else {\n $redirect_to = home_url().'/members/'.$user-&gt;user_login.'/profile'; \n wp_redirect($redirect_to);\n exit;\n}\n</code></pre>\n\n<p>Beacuse the wp_signon function create all the sessions and fill the current user functions.</p>\n" }, { "answer_id": 251989, "author": "Kudratullah", "author_id": 62726, "author_profile": "https://wordpress.stackexchange.com/users/62726", "pm_score": 2, "selected": false, "text": "<p>have you tried by setting the second argument of <code>wp_signon()</code> to <code>true</code> or blank?\nset false will prevent <code>wp_signon()</code> from setting secure cookie which is essential for accessing <code>wp-admin</code> if your using ssl.\ni have tested and <code>$user = wp_signon( $user_data, true );</code> works as expected.</p>\n" } ]
2016/04/01
[ "https://wordpress.stackexchange.com/questions/222335", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/53934/" ]
I have stuck in serious problem. I want to create a document and upload a word doc from front end after user login. Logged in user is admin. The plugin bp-doc uses WordPress default media uploader to upload file. The plugin hits `.../wp-admin/async-upload.php`, but this throws an error `An error occurred in the upload. Please try again later`, after debuging in console I found `302 Moved Temporarily` error and in response there is WordPress login form. After doing some research I found another error, when I log in from frontend as an admin and goes back to `wp-admin` it logged me out and asks again to enter username and password. I unable to go through the errors, anyone can help me what may goes wrong? I uses the following code to login ``` $user_data = array(); $user_data['user_login'] = $username; $user_data['user_password'] = $password; $user_data['remember'] = $remember; $user = wp_signon( $user_data, false ); if ( is_wp_error($user) ) { $err = "<strong>ERROR!</strong> Invalid username or password"; } else { wp_set_current_user( $user->ID); do_action('set_current_user'); global $current_user; get_currentuserinfo(); $redirect_to = home_url().'/members/'.$current_user->user_login.'/profile'; wp_redirect($redirect_to); exit; } ``` Live site url: <https://www.group50.com/g50consultants>
have you tried by setting the second argument of `wp_signon()` to `true` or blank? set false will prevent `wp_signon()` from setting secure cookie which is essential for accessing `wp-admin` if your using ssl. i have tested and `$user = wp_signon( $user_data, true );` works as expected.
222,347
<p>I would like to version control my WP sites with git. A big struggle I have with this is: how do you version control options/plugin settings in the database.</p> <p>I would like to don't touch the dashboard in the live site. Only the users should need to login in to write posts - but I as a developer would like to log in only to check if everything is working on the live machine. Is there a way to do this?</p> <p>I know that Drupal 8 has a build in configuration management - that's their solution. I also know "versionpress" and similar plugins. But they also version control the posts/pages/users etc. I don't need this. Example:</p> <pre><code>Update option 'site_url' to 'http://example.com'; Reset update option 'site_url' to 'http://noexample.com';``` </code></pre> <p>(the second line is to redo this step)</p> <p>I guess there are some things in ruby on rails or similar. Would be great to separate code/options/settings and content/media/user-generated-stuff.</p>
[ { "answer_id": 222358, "author": "Sumeet Shroff", "author_id": 85982, "author_profile": "https://wordpress.stackexchange.com/users/85982", "pm_score": 0, "selected": false, "text": "<p>Not sure of what u need but....</p>\n\n<ol>\n<li><p>Maybe your can track the activities by using a Activity log...\n<a href=\"https://wordpress.org/plugins/aryo-activity-log/\" rel=\"nofollow\">https://wordpress.org/plugins/aryo-activity-log/</a></p></li>\n<li><p>Most of these activities for \"insert options/pages/settings via code\" happen in the database.. you can use a cron to take a snapshot of the database and the compare the difference...</p></li>\n</ol>\n" }, { "answer_id": 222362, "author": "Jessica Guerard", "author_id": 91551, "author_profile": "https://wordpress.stackexchange.com/users/91551", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Failed plugin update? Mistakenly deleted post? Just undo it. Also,\n painless staging for WordPress (finally!), great backup &amp; team\n workflows, all powered by Git.</p>\n \n <p>Working on this next-gen thing for you, you can get Early Access and\n support us: <a href=\"http://versionpress.net/\" rel=\"nofollow\">http://versionpress.net/</a></p>\n</blockquote>\n\n<p>This seems to be something you could use for Version Control, BUT it seems like it's \"early access program\": <a href=\"http://docs.versionpress.net/en/getting-started/about-eap\" rel=\"nofollow\">http://docs.versionpress.net/en/getting-started/about-eap</a></p>\n\n<p>Other plugins: </p>\n\n<p><a href=\"https://wordpress.org/plugins/revisr/\" rel=\"nofollow\">https://wordpress.org/plugins/revisr/</a></p>\n\n<p><a href=\"https://www.presslabs.com/gitium/\" rel=\"nofollow\">https://www.presslabs.com/gitium/</a> - beta</p>\n" }, { "answer_id": 222525, "author": "Borek Bernard", "author_id": 12248, "author_profile": "https://wordpress.stackexchange.com/users/12248", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://wordpress.org/plugins/wp-cfm/\" rel=\"nofollow\">WP-CFM</a> is probably the closest to what you're looking for. Actually, it has been inspired by Drupal's Features module.</p>\n\n<p>From the plugin page:</p>\n\n<blockquote>\n <p>WP-CFM lets you copy database configuration to / from the filesystem. Easily deploy configuration changes without needing to copy the entire database.</p>\n</blockquote>\n\n<p>However, as someone who has spent the better part of the past few years working on the versioning solution for WordPress (I'm a co-creator of VersionPress), I can say that it's tricky to version-control only parts of the site. For example, a plugin might store some of its configuration in <code>wp_options</code>, some of it on the disk (in some PHP file, for instance) and some of it in postmeta or whatever. Full version control is hard (which is why VersionPress takes its time) but it's the only 100% reliable way.</p>\n\n<p>If you're sure you good with just <code>wp_options</code> (and some other tracked entities that WP-CFM provides; see the linked plugin page) then I agree that it's better to use the simpler tool.</p>\n" }, { "answer_id": 222528, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 0, "selected": false, "text": "<p>WordPress aside, if you're looking for a way to see what has changed in a MySQL database in a specific time frame, then <a href=\"http://dev.mysql.com/doc/refman/5.7/en/binary-log.html\" rel=\"nofollow\">binary logs</a> are your most reliable bet. These beasts will record every statement which alters your database in any way, allowing you to replay them (or a subset of them) on another database.</p>\n\n<p>They're perfect for audits, replication and point-in-time recovery. Not so good for \"merging changes\" to another database which may also have been altered, mostly because of <code>AUTO_INCREMENT</code> columns which will almost always cause conflicts. It's probably possible with a lot of manual work, but I wouldn't go there in a million years.</p>\n\n<p>With regards to WordPress, a neat trick is to keep your options under version control with... version control:</p>\n\n<pre><code>add_filter( 'pre_option_posts_per_page', function( $per_page ) {\n return 50;\n});\n</code></pre>\n\n<p>This way, regardless of your database, the <code>posts_per_page</code> option will always be 50. You can read more about the pre_option_* filter <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/pre_option_(option_name)\" rel=\"nofollow\">here</a>.</p>\n\n<p>And as many folks have already mentioned, there are plugins and tools specific to WordPress that attempt to provide some type of version control for WordPress content and settings. Another one worth mentioning is the pricey <a href=\"https://shop.crowdfavorite.com/ramp/\" rel=\"nofollow\">RAMP plugin</a> by Crowd Favorite.</p>\n\n<p>As Borek mentioned, it's very tricky to build reliability into such a tool, because of all the different and crazy things third-party plugins can do.</p>\n" } ]
2016/04/01
[ "https://wordpress.stackexchange.com/questions/222347", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83359/" ]
I would like to version control my WP sites with git. A big struggle I have with this is: how do you version control options/plugin settings in the database. I would like to don't touch the dashboard in the live site. Only the users should need to login in to write posts - but I as a developer would like to log in only to check if everything is working on the live machine. Is there a way to do this? I know that Drupal 8 has a build in configuration management - that's their solution. I also know "versionpress" and similar plugins. But they also version control the posts/pages/users etc. I don't need this. Example: ``` Update option 'site_url' to 'http://example.com'; Reset update option 'site_url' to 'http://noexample.com';``` ``` (the second line is to redo this step) I guess there are some things in ruby on rails or similar. Would be great to separate code/options/settings and content/media/user-generated-stuff.
[WP-CFM](https://wordpress.org/plugins/wp-cfm/) is probably the closest to what you're looking for. Actually, it has been inspired by Drupal's Features module. From the plugin page: > > WP-CFM lets you copy database configuration to / from the filesystem. Easily deploy configuration changes without needing to copy the entire database. > > > However, as someone who has spent the better part of the past few years working on the versioning solution for WordPress (I'm a co-creator of VersionPress), I can say that it's tricky to version-control only parts of the site. For example, a plugin might store some of its configuration in `wp_options`, some of it on the disk (in some PHP file, for instance) and some of it in postmeta or whatever. Full version control is hard (which is why VersionPress takes its time) but it's the only 100% reliable way. If you're sure you good with just `wp_options` (and some other tracked entities that WP-CFM provides; see the linked plugin page) then I agree that it's better to use the simpler tool.
222,348
<p>I wish to create different template pages for all Parent Categories and Subcategories. I was hoping to do it using the hierarchy (eg. something like <code>category-parent.php</code> and <code>category-sub.php</code>), but looking at the flow diagram I found, I don't think there's an option:</p> <p><a href="https://i.stack.imgur.com/GbVPA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GbVPA.png" alt="enter image description here"></a></p> <p>I could manually add a <code>category-$slug.php</code> for the parent categories (as these shouldn't be changing) and then just use <code>category.php</code> for everything else (ie. the subcategories), but is there a better way?</p>
[ { "answer_id": 222355, "author": "Sumeet Shroff", "author_id": 85982, "author_profile": "https://wordpress.stackexchange.com/users/85982", "pm_score": 0, "selected": false, "text": "<p>There is another way if you code the same in the <code>category.php</code> file.\nCheck if the category is a parent category. And if so, then display parent code. Otherwise show the child code. This way you do not need to create multiple files for each category.</p>\n\n<pre><code>$category = get_term(get_queried_object());\n\nif ( $category-&gt;category_parent &gt; 0 ) {\n // Is subcategory\n} else {\n // Is parent category\n}\n</code></pre>\n" }, { "answer_id": 222363, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 3, "selected": true, "text": "<p>You can do this using custom template and <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include\" rel=\"nofollow\"><code>template_include</code></a> filter.\n<code>category-parent.php</code> and <code>category-sub.php</code> both are not required. One can be <code>category.php</code> for parent categories and for child categories, you can use <code>custom-category-child.php</code> as <code>category-sub.php</code> is reserved for default hierarchy.</p>\n\n<ul>\n<li>First create a template file in theme <code>custom-category-child.php</code></li>\n<li>Then add this code to your theme <code>functions.php</code></li>\n</ul>\n\n<p><strong>Update</strong>: As Pieter suggested we can use <code>category_template</code> instead of <code>template_include</code> to save few lines. Additionally we should return current template when our custom template file is missing! </p>\n\n<p><strong>Read inline comments</strong></p>\n\n<pre><code>add_filter('category_template', 'custom_cat_templates');\n/**\n * Create custom template for child categroies\n * @param type $template\n * @return type\n */\nfunction custom_cat_templates($template) {\n $category = get_category(get_queried_object_id()); //Get the ID for current queried category\n if ( $category-&gt;category_parent &gt; 0 ) { //Check if it child category\n $sub_category_template = locate_template('custom-category-child.php'); //return our custom template\n $template = !empty($sub_category_template) ? $sub_category_template : $template; //return default template if custom templaet missing\n }\n\n return $template;\n}\n</code></pre>\n" }, { "answer_id": 222628, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 0, "selected": false, "text": "<p>If you do not want to take the <a href=\"https://wordpress.stackexchange.com/a/222363/31545\">scenic route posted by @Sumit (<em>which IMHO is a better solution</em>)</a> and need do do things inside the category template, you can do the following</p>\n\n<ul>\n<li><p>Get the queried object (<em>currently viewed category</em>). We will use <code>$GLOBALS['wp_the_query']-&gt;get_queried_object()</code> which is 99.9999% reliable opposed to <code>get_queried_object()</code> or even the suggested <code>get_the_category()</code>. You can read my interesting answer to the subject <a href=\"https://wordpress.stackexchange.com/a/220624/31545\">here</a></p></li>\n<li><p>Use <a href=\"https://developer.wordpress.org/reference/functions/get_term/\" rel=\"nofollow noreferrer\"><code>get_term()</code></a> to validate the term object (<em>you can also use <code>get_category()</code>, but is short, <code>get_category()</code> is just a wrapper for <code>get_term()</code></em>)</p></li>\n<li><p>From there, we can get the category parent and do what we need to do</p></li>\n</ul>\n\n<p>We can try the following:</p>\n\n<pre><code>// Get the current category object\n$category_object = get_term( $GLOBALS['wp_the_query']-&gt;get_queried_object() );\n\n// Run our logic according to the value of $parent\nif ( 0 === $category_object-&gt;parent ) {\n // Category is top level\n} else {\n // Category is a descendant\n}\n</code></pre>\n" } ]
2016/04/01
[ "https://wordpress.stackexchange.com/questions/222348", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4109/" ]
I wish to create different template pages for all Parent Categories and Subcategories. I was hoping to do it using the hierarchy (eg. something like `category-parent.php` and `category-sub.php`), but looking at the flow diagram I found, I don't think there's an option: [![enter image description here](https://i.stack.imgur.com/GbVPA.png)](https://i.stack.imgur.com/GbVPA.png) I could manually add a `category-$slug.php` for the parent categories (as these shouldn't be changing) and then just use `category.php` for everything else (ie. the subcategories), but is there a better way?
You can do this using custom template and [`template_include`](https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include) filter. `category-parent.php` and `category-sub.php` both are not required. One can be `category.php` for parent categories and for child categories, you can use `custom-category-child.php` as `category-sub.php` is reserved for default hierarchy. * First create a template file in theme `custom-category-child.php` * Then add this code to your theme `functions.php` **Update**: As Pieter suggested we can use `category_template` instead of `template_include` to save few lines. Additionally we should return current template when our custom template file is missing! **Read inline comments** ``` add_filter('category_template', 'custom_cat_templates'); /** * Create custom template for child categroies * @param type $template * @return type */ function custom_cat_templates($template) { $category = get_category(get_queried_object_id()); //Get the ID for current queried category if ( $category->category_parent > 0 ) { //Check if it child category $sub_category_template = locate_template('custom-category-child.php'); //return our custom template $template = !empty($sub_category_template) ? $sub_category_template : $template; //return default template if custom templaet missing } return $template; } ```
222,352
<p>I'm getting quite frustrated setting up the correct URL structure for a Cutom Post Type with a Custom taxonomy. </p> <p>I have a Custom Post Type called <code>courses</code> with a Custom Taxonomy called <code>course-type</code>. </p> <ol> <li><strong>The URL structure should be:</strong> <code>site.com/courses/course-type/course-single-post/</code>. </li> <li><strong>For example:</strong> <code>site.com/courses/science/rocket-to-the-moon/</code></li> </ol> <p>I've managed to achieve that however not all URL parts are behaving as it should.</p> <ul> <li><code>site.com/courses/</code> - returns a 404</li> <li><code>site.com/courses/science/</code> - Shows an archive page with all posts in side that custom taxonomy which is correct</li> <li><code>site.com/courses/science/rocket-to-the-moon/</code> - Shows the single Custom Post Type which is correct too</li> </ul> <p>I don't know why the <code>site.com/courses/</code> returns a 404 instead of showing an archive page listing all Custom Post Type's...?</p> <p><strong>This is the code that I've used:</strong></p> <pre><code>&lt;?php /*Courses Custom Post Type*/ function my_custom_post_courses() { $labels = array( 'name' =&gt; _x( 'Courses', 'post type general name' ), 'singular_name' =&gt; _x( 'Course', 'post type singular name' ), 'add_new' =&gt; _x( 'New course', 'reis' ), 'add_new_item' =&gt; __( 'Add new course' ), 'edit_item' =&gt; __( 'Edit course' ), 'new_item' =&gt; __( 'New item' ), 'all_items' =&gt; __( 'All courses' ), 'view_item' =&gt; __( 'View courses' ), 'search_items' =&gt; __( 'Search courses' ), 'not_found' =&gt; __( 'Nothing found ' ), 'not_found_in_trash' =&gt; __( 'Nothing found in the trash' ), 'parent_item_colon' =&gt; '', 'menu_name' =&gt; 'Courses' ); $args = array( 'labels' =&gt; $labels, 'description' =&gt; 'Enter a new course', 'public' =&gt; true, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ), 'has_archive' =&gt; true, 'hierarchical' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'courses/%course-type%','with_front' =&gt; false), 'query_var' =&gt; true, //'rewrite' =&gt; true, //'publicly_queryable' =&gt; false, ); register_post_type( 'courses', $args ); } add_action( 'init', 'my_custom_post_courses' ); /* Courses custom taxonomy */ function my_taxonomies_course_type() { $labels = array( 'name' =&gt; _x( 'Course type', 'taxonomy general name' ), 'singular_name' =&gt; _x( 'Course type', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search course types' ), 'all_items' =&gt; __( 'All course types' ), 'parent_item' =&gt; __( 'Parent course type' ), 'parent_item_colon' =&gt; __( 'Parent course type:' ), 'edit_item' =&gt; __( 'Edit course type' ), 'update_item' =&gt; __( 'Update course type ' ), 'add_new_item' =&gt; __( 'Add new course type' ), 'new_item_name' =&gt; __( 'New course type' ), 'menu_name' =&gt; __( 'Course type' ), ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'query_var' =&gt; 'course-type', 'rewrite' =&gt; array('slug' =&gt; 'courses' ), '_builtin' =&gt; false, ); register_taxonomy( 'course-type', 'courses', $args ); } add_action( 'init', 'my_taxonomies_course_type', 0 ); /* Permalink filter Courses */ add_filter('post_link', 'course_permalink', 1, 3); add_filter('post_type_link', 'course_permalink', 1, 3); function course_permalink($permalink, $post_id, $leavename) { if (strpos($permalink, '%course-type%') === FALSE) return $permalink; // Get post $post = get_post($post_id); if (!$post) return $permalink; // Get taxonomy terms $terms = wp_get_object_terms($post-&gt;ID, 'course-type'); if (!is_wp_error($terms) &amp;&amp; !empty($terms) &amp;&amp; is_object($terms[0])) $taxonomy_slug = $terms[0]-&gt;slug; else $taxonomy_slug = 'no-course-type'; return str_replace('%course-type%', $taxonomy_slug, $permalink); } </code></pre>
[ { "answer_id": 222372, "author": "Michael Ecklund", "author_id": 9579, "author_profile": "https://wordpress.stackexchange.com/users/9579", "pm_score": 0, "selected": false, "text": "<p>With your desired permalink URL structure ... WordPress is automatically handling the creation of rewrite rules for what you entered (<code>courses/%course-type%</code>) for your Post Type slug. Of course you have to modify the Post Type link to substitute the place holder with the actual value (as you've already done).</p>\n\n<p>However, WordPress isn't expecting that type of behavior in a Post Type slug. Typically WordPress would expect something simple like <code>courses</code> (instead of <code>courses/%course-type%</code>). </p>\n\n<p>That's okay though, WordPress allows us to adapt to almost any situation with it's amazing flexibility and customization features.</p>\n\n<p>All you need to do is adjust the rewrite rules to handle the \"base\" of your Post Type slug (<code>courses</code>).</p>\n\n<p>This can be done cleanly in two functions which could be pasted into your currently activated theme <code>functions.php</code> file (or more ideally ... into a plugin file.)</p>\n\n<h2>Step 1 - Adjust the rewrite rules.</h2>\n\n<p>In this step, you're requesting new rewrite rules to add into the existing rewrite rules. The new rewrite rules are created automatically in the <code>mbe_get_new_rewrite_rules();</code> function. </p>\n\n<pre><code>if ( ! function_exists( 'mbe_adjust_rewrite_rules' ) ) {\n\n function mbe_adjust_rewrite_rules( $rules ) {\n\n if ( ! function_exists( 'mbe_get_new_rewrite_rules' ) ) {\n return $rules;\n }\n\n $new_rules = mbe_get_new_rewrite_rules( 'courses' );\n\n return ( $new_rules + $rules );\n\n }\n\n add_action( 'rewrite_rules_array', 'mbe_adjust_rewrite_rules', 100 );\n\n}\n</code></pre>\n\n<h2>Step 2 - Create the new rewrite rules.</h2>\n\n<p>Please note: This function requires the name of the Post Type as a parameter.</p>\n\n<p>This function will take the specified Post Type name and automatically retrieve it's rewrite slug (specified during Post Type registration). </p>\n\n<p>This function will then continue to check for any slashes in the Post Type slug. If one is located, it will take everything before the first slash (AKA the base slug) and generate an appropriate rewrite rule for your Post Type's base slug. (Like it would have done if you just specified a simple rewrite slug of <code>courses</code> during Post Type registration instead of <code>courses/%course-type%</code>.)</p>\n\n<pre><code>if ( ! function_exists( 'mbe_get_new_rewrite_rules' ) ) {\n\n function mbe_get_new_rewrite_rules( $post_type = '' ) {\n\n $new_rules = array();\n\n $post_type_object = get_post_type_object( $post_type );\n\n if ( ! $post_type_object ) {\n return $new_rules;\n }\n\n $post_type_slug = $post_type_object-&gt;rewrite['slug'];\n $post_type_slug_base = substr( $post_type_slug, 0, strpos( $post_type_slug, '/' ) );\n\n if ( ! empty( $post_type_slug_base ) ) {\n $new_rules[\"{$post_type_slug_base}/?$\"] = \"index.php?post_type={$post_type}\";\n }\n\n return $new_rules;\n\n }\n\n}\n</code></pre>\n\n<p>There you have it. Three valid and functioning URLs. As per your request.</p>\n\n<ol>\n<li><code>domain.com/courses/</code></li>\n<li><code>domain.com/courses/course-type/</code></li>\n<li><code>domain.com/courses/course-type/course-name/</code></li>\n</ol>\n\n<p>Just remember to either programmatically flush rewrite rules, or to visit: <code>Dashboard -&gt; Settings -&gt; Permalinks</code> for the new rewrite rules to take effect.</p>\n" }, { "answer_id": 222375, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>Setting <code>has_archive</code> to <code>true</code> causes WordPress to generate a rewrite rule for the archive using the rewrite slug, which is not what you want in your case. Instead, explicitly specify the archive slug as a string and the correct rules will be generated:</p>\n\n<pre><code>$args = array(\n 'has_archive' =&gt; 'courses',\n 'rewrite' =&gt; array('slug' =&gt; 'courses/%course-type%','with_front' =&gt; false),\n // the rest of your args...\n);\nregister_post_type( 'courses', $args );\n</code></pre>\n" } ]
2016/04/01
[ "https://wordpress.stackexchange.com/questions/222352", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28103/" ]
I'm getting quite frustrated setting up the correct URL structure for a Cutom Post Type with a Custom taxonomy. I have a Custom Post Type called `courses` with a Custom Taxonomy called `course-type`. 1. **The URL structure should be:** `site.com/courses/course-type/course-single-post/`. 2. **For example:** `site.com/courses/science/rocket-to-the-moon/` I've managed to achieve that however not all URL parts are behaving as it should. * `site.com/courses/` - returns a 404 * `site.com/courses/science/` - Shows an archive page with all posts in side that custom taxonomy which is correct * `site.com/courses/science/rocket-to-the-moon/` - Shows the single Custom Post Type which is correct too I don't know why the `site.com/courses/` returns a 404 instead of showing an archive page listing all Custom Post Type's...? **This is the code that I've used:** ``` <?php /*Courses Custom Post Type*/ function my_custom_post_courses() { $labels = array( 'name' => _x( 'Courses', 'post type general name' ), 'singular_name' => _x( 'Course', 'post type singular name' ), 'add_new' => _x( 'New course', 'reis' ), 'add_new_item' => __( 'Add new course' ), 'edit_item' => __( 'Edit course' ), 'new_item' => __( 'New item' ), 'all_items' => __( 'All courses' ), 'view_item' => __( 'View courses' ), 'search_items' => __( 'Search courses' ), 'not_found' => __( 'Nothing found ' ), 'not_found_in_trash' => __( 'Nothing found in the trash' ), 'parent_item_colon' => '', 'menu_name' => 'Courses' ); $args = array( 'labels' => $labels, 'description' => 'Enter a new course', 'public' => true, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ), 'has_archive' => true, 'hierarchical' => true, 'rewrite' => array('slug' => 'courses/%course-type%','with_front' => false), 'query_var' => true, //'rewrite' => true, //'publicly_queryable' => false, ); register_post_type( 'courses', $args ); } add_action( 'init', 'my_custom_post_courses' ); /* Courses custom taxonomy */ function my_taxonomies_course_type() { $labels = array( 'name' => _x( 'Course type', 'taxonomy general name' ), 'singular_name' => _x( 'Course type', 'taxonomy singular name' ), 'search_items' => __( 'Search course types' ), 'all_items' => __( 'All course types' ), 'parent_item' => __( 'Parent course type' ), 'parent_item_colon' => __( 'Parent course type:' ), 'edit_item' => __( 'Edit course type' ), 'update_item' => __( 'Update course type ' ), 'add_new_item' => __( 'Add new course type' ), 'new_item_name' => __( 'New course type' ), 'menu_name' => __( 'Course type' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'query_var' => 'course-type', 'rewrite' => array('slug' => 'courses' ), '_builtin' => false, ); register_taxonomy( 'course-type', 'courses', $args ); } add_action( 'init', 'my_taxonomies_course_type', 0 ); /* Permalink filter Courses */ add_filter('post_link', 'course_permalink', 1, 3); add_filter('post_type_link', 'course_permalink', 1, 3); function course_permalink($permalink, $post_id, $leavename) { if (strpos($permalink, '%course-type%') === FALSE) return $permalink; // Get post $post = get_post($post_id); if (!$post) return $permalink; // Get taxonomy terms $terms = wp_get_object_terms($post->ID, 'course-type'); if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug; else $taxonomy_slug = 'no-course-type'; return str_replace('%course-type%', $taxonomy_slug, $permalink); } ```
Setting `has_archive` to `true` causes WordPress to generate a rewrite rule for the archive using the rewrite slug, which is not what you want in your case. Instead, explicitly specify the archive slug as a string and the correct rules will be generated: ``` $args = array( 'has_archive' => 'courses', 'rewrite' => array('slug' => 'courses/%course-type%','with_front' => false), // the rest of your args... ); register_post_type( 'courses', $args ); ```
222,452
<p>Till today I never used <code>header.php</code> and <code>footer.php</code> because my theme has multiple templates and I do not know how or where to place the CSS and JS files. Could someone please explain how to have a <code>header.php</code> and use <code>get_header();</code> but also include new CSS files depending on the template?</p> <p><strong>Normal Code</strong> <em>And how I see it</em></p> <pre><code>&lt;?php /* Template Name: Contact Template */ ?&gt; &lt;!-- HERE STARTS HEADER PHP? --&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Website&lt;/title&gt; &lt;link href="style.css" rel="stylesheet" type="text/css" /&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;!-- MENU AND STUFF --&gt; &lt;/header&gt; &lt;main&gt; &lt;!-- HERE STOPS HEADER PHP ? --&gt; &lt;!-- SOME CONTENT --&gt; &lt;!-- HERE STARTS FOOTER PHP? --&gt; &lt;/main&gt; &lt;footer&gt; &lt;!-- SOME CONTENT --&gt; &lt;/footer&gt; &lt;!-- HERE I PLACE MY JS FILES --&gt; &lt;/body&gt; &lt;/html&gt; &lt;!-- HERE STOPS FOOTER PHP? --&gt; </code></pre> <p>As you can see, where I place my CSS and JS files are in the <code>header.php</code> or <code>footer.php</code> so I can not add more depending on the template. How do you add CSS files if you use multiple templates?</p> <p>===================================================</p> <p><strong>Problem is almost solved. Just need to create an if/else statement to check the <code>Template Name:</code>.</strong></p>
[ { "answer_id": 222456, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 2, "selected": false, "text": "<p>Don't include CSS and JavaScript manually, there are special functions for this purpose. Modify this code to meet your requirements and put it to the <code>functions.php</code> of your theme.</p>\n\n<pre><code>&lt;?php\n$template_file_name = basename( get_page_template() ); // get template file name\n\nif('my_template.php' == $template_file_name) { // check file name\n wp_enqueue_style(\n 'my_style_name',\n '/path/to/style.css',\n array(), // dependencies\n NULL, // version\n all // media\n );\n enqueue_script(\n 'my_script_name',\n '/path/to/script.js',\n array(), // dependencies\n NULL, // version\n true // in footer\n );\n}\n</code></pre>\n\n<p>Minimal <code>header.php</code></p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;/head&gt;\n&lt;?php wp_head(); // this function will place your CSS here ?&gt;\n&lt;body&gt;\n</code></pre>\n\n<p>Minimal <code>footer.php</code></p>\n\n<pre><code>&lt;?php wp_footer(); // this function will place your JavaScript here?&gt;\n&lt;/body&gt;\n&lt;html&gt;\n</code></pre>\n\n<p>Minimal <code>my_template.php</code></p>\n\n<pre><code>&lt;?php\n/*\nTemplate Name: Contact Template\n*/\nget_header();\n// your content goes here\nget_footer();\n</code></pre>\n\n<p>For more information see:</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow\">wp_enqueue_style()</a></p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow\">enqueue_script()</a></p>\n\n<p><a href=\"https://codex.wordpress.org/Theme_Development\" rel=\"nofollow\">Theme Development</a></p>\n" }, { "answer_id": 222463, "author": "BrandonZ", "author_id": 91660, "author_profile": "https://wordpress.stackexchange.com/users/91660", "pm_score": 4, "selected": true, "text": "<p>Include CSS and JavaScipt in the <code>functions.php</code>. </p>\n\n<p>Create an empty PHP file, call it <code>header.php</code>, and yes <code>wp_head()</code> goes just before <code>&lt;/head&gt;</code> not before <code>&lt;body&gt;</code> tag.</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;Website&lt;/title&gt;\n &lt;link href=\"style.css\" rel=\"stylesheet\" type=\"text/css\" /&gt;\n &lt;?php wp_head(); ?&gt;\n&lt;/head&gt;\n</code></pre>\n\n<p>Create an empty PHP file, call it <code>footer.php</code> and place your footer there:</p>\n\n<pre><code> &lt;footer&gt;\n &lt;!-- SOME CONTENT --&gt;\n &lt;/footer&gt;\n&lt;!-- HERE I PLACE MY JS FILES --&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>In <code>functions.php</code>:</p>\n\n<pre><code>function my_scripts_styles() {\n\n wp_enqueue_script('jquery_flexslider_js', get_template_directory_uri() . '/js/jquery.flexslider.min.js', array('jquery'),'3.0.0', true );\n\n wp_enqueue_style('flexslider_css', get_template_directory_uri() . '/css/flexslider.css', false ,'3.0.0'); \n\n}\nadd_action('wp_enqueue_scripts', 'my_scripts_styles');\n</code></pre>\n\n<p>With <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow\"><code>wp_enqueue_script()</code></a> add JavaScript, the last argument <code>true</code> means it will be placed at the bottom. You need to give it a unique name e.g. <code>flexslider_js_my</code>. Include as many js files as you need.</p>\n\n<p>With <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow\"><code>wp_enqueue_style()</code></a> you add CSS files. The last argument <code>false</code> means it will be placed in the header. Give it a unique name, include as many as you need.</p>\n\n<p>The rest of your code stays in <code>index.php</code>. <code>header.php</code>, <code>footer.php</code>, <code>functions.php</code> they are all in the home directory where your <code>index.php</code> is.</p>\n\n<p><code>index.php</code>:</p>\n\n<pre><code>&lt;?php get_header(); ?&gt;\n&lt;body&gt;\n &lt;header&gt;\n &lt;!-- MENU AND STUFF --&gt;\n &lt;/header&gt;\n &lt;main&gt;\n &lt;!-- HERE STOPS HEADER PHP ? --&gt;\n\n &lt;!-- SOME CONTENT --&gt;\n\n &lt;!-- HERE STARTS FOOTER PHP? --&gt;\n &lt;/main&gt;\n &lt;footer&gt;\n &lt;!-- SOME CONTENT --&gt;\n &lt;/footer&gt;\n&lt;!-- HERE I PLACE MY JS FILES --&gt;\n&lt;/body&gt;\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>Btw, in your case you don't need to include <code>&lt;?php /* Template Name: Contact Template */ ?&gt;</code> at the top. You can do just like in my example.</p>\n\n<p>Update, the template name:</p>\n\n<p>In my case <a href=\"https://developer.wordpress.org/reference/functions/get_page_template/\" rel=\"nofollow\"><code>get_page_template()</code></a> will output the whole template path for example:</p>\n\n<blockquote>\n <p>/homepages/133/htdocs/dd/myheme/wp-content/themes/authentic/page.php </p>\n</blockquote>\n\n<p>where 'authentic' is my template name. So the <em>if</em> construct to include in <code>functions.php</code>:</p>\n\n<pre><code>$url = get_page_template();\n$parts = explode('/', $url);\n$name = $parts[count($parts) - 2];\n\nif('authentic' == $name) { \n\n wp_enqueue_style('homeCSS', get_template_directory_uri() . '/css/home.css', false ,'3.0.0'); \n\n}\n</code></pre>\n" } ]
2016/04/02
[ "https://wordpress.stackexchange.com/questions/222452", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87656/" ]
Till today I never used `header.php` and `footer.php` because my theme has multiple templates and I do not know how or where to place the CSS and JS files. Could someone please explain how to have a `header.php` and use `get_header();` but also include new CSS files depending on the template? **Normal Code** *And how I see it* ``` <?php /* Template Name: Contact Template */ ?> <!-- HERE STARTS HEADER PHP? --> <!DOCTYPE html> <html> <head> <title>Website</title> <link href="style.css" rel="stylesheet" type="text/css" /> <?php wp_head(); ?> </head> <body> <header> <!-- MENU AND STUFF --> </header> <main> <!-- HERE STOPS HEADER PHP ? --> <!-- SOME CONTENT --> <!-- HERE STARTS FOOTER PHP? --> </main> <footer> <!-- SOME CONTENT --> </footer> <!-- HERE I PLACE MY JS FILES --> </body> </html> <!-- HERE STOPS FOOTER PHP? --> ``` As you can see, where I place my CSS and JS files are in the `header.php` or `footer.php` so I can not add more depending on the template. How do you add CSS files if you use multiple templates? =================================================== **Problem is almost solved. Just need to create an if/else statement to check the `Template Name:`.**
Include CSS and JavaScipt in the `functions.php`. Create an empty PHP file, call it `header.php`, and yes `wp_head()` goes just before `</head>` not before `<body>` tag. ``` <!DOCTYPE html> <html> <head> <title>Website</title> <link href="style.css" rel="stylesheet" type="text/css" /> <?php wp_head(); ?> </head> ``` Create an empty PHP file, call it `footer.php` and place your footer there: ``` <footer> <!-- SOME CONTENT --> </footer> <!-- HERE I PLACE MY JS FILES --> </body> </html> ``` In `functions.php`: ``` function my_scripts_styles() { wp_enqueue_script('jquery_flexslider_js', get_template_directory_uri() . '/js/jquery.flexslider.min.js', array('jquery'),'3.0.0', true ); wp_enqueue_style('flexslider_css', get_template_directory_uri() . '/css/flexslider.css', false ,'3.0.0'); } add_action('wp_enqueue_scripts', 'my_scripts_styles'); ``` With [`wp_enqueue_script()`](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) add JavaScript, the last argument `true` means it will be placed at the bottom. You need to give it a unique name e.g. `flexslider_js_my`. Include as many js files as you need. With [`wp_enqueue_style()`](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) you add CSS files. The last argument `false` means it will be placed in the header. Give it a unique name, include as many as you need. The rest of your code stays in `index.php`. `header.php`, `footer.php`, `functions.php` they are all in the home directory where your `index.php` is. `index.php`: ``` <?php get_header(); ?> <body> <header> <!-- MENU AND STUFF --> </header> <main> <!-- HERE STOPS HEADER PHP ? --> <!-- SOME CONTENT --> <!-- HERE STARTS FOOTER PHP? --> </main> <footer> <!-- SOME CONTENT --> </footer> <!-- HERE I PLACE MY JS FILES --> </body> <?php get_footer(); ?> ``` Btw, in your case you don't need to include `<?php /* Template Name: Contact Template */ ?>` at the top. You can do just like in my example. Update, the template name: In my case [`get_page_template()`](https://developer.wordpress.org/reference/functions/get_page_template/) will output the whole template path for example: > > /homepages/133/htdocs/dd/myheme/wp-content/themes/authentic/page.php > > > where 'authentic' is my template name. So the *if* construct to include in `functions.php`: ``` $url = get_page_template(); $parts = explode('/', $url); $name = $parts[count($parts) - 2]; if('authentic' == $name) { wp_enqueue_style('homeCSS', get_template_directory_uri() . '/css/home.css', false ,'3.0.0'); } ```
222,498
<p>I have a custom post type called <code>shows</code> and taxonomy called <code>podcast</code>. Using <code>taxonomy-podcast.php</code>, I having hard time finding a function that will generate next/previous Term URL Archive.</p> <h2>For Example:</h2> <p>URL: url.com/podcast/example-term-2</p> <blockquote> <p><strong>Example Term 2</strong></p> <p>post 1,post 2,post 3</p> </blockquote> <p>Desired output</p> <pre><code>&lt; Previous Term(url.com/podcast/example-term-1) . . . . . | . . . . . Next Term(url.com/podcast/example-term-3)&gt; </code></pre>
[ { "answer_id": 222504, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>Something like this will do it, if you have a lot of terms it could be a rather expensive query though as it retrieves them all, can't see a way around that right now... (though you could cache all term results in a transient perhaps so it is not being done every pageload.)</p>\n\n<pre><code>function custom_term_navigation() {\n $thistermid = get_queried_object()-&gt;term_id;\n if (!is_numeric($thistermid)) {return;}\n\n // remove commenting to use transient storage\n // $terms = get_transient('all_podcast_terms');\n // if (!$terms) {\n $args = array('orderby'=&gt;'slug');\n $terms = get_terms('podcast',$args);\n // set_transient('all_podcast_terms',$terms,60*60);\n // }\n\n $termid = ''; $termslug = ''; $foundterm = false;\n foreach ($terms as $term) {\n $prevterm = $termslug;\n $termid = $term-&gt;term_id;\n if ($foundterm) {$nextterm = $term-&gt;slug; break;}\n if ($termid == $thistermid) {\n $foundterm = true; $previousterm = $prevterm;\n }\n $termslug = $term-&gt;slug;\n }\n\n $navigation = '';\n if ($previousterm != '') {\n $previoustermlink = get_term_link($previousterm,'podcast');\n $navigation .= \"\".$previoustermlink.\"' style='float:left; display:inline;'&gt;&amp;larr; Previous Term&lt;/a&gt;\";\n }\n if ($nexterm != '') {\n $nexttermlink = get_term_link($nexterm,'podcast');\n $navigation .= \"&lt;a href='\".$nextermlink.\"' style='float:right; display:inline;'&gt;Next Term &amp;rarr;&lt;/a&gt;\";\n }\n\n return $navigation;\n}\n</code></pre>\n" }, { "answer_id": 222537, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>It is quite possible to achieve this. What we need to do is</p>\n\n<ul>\n<li><p>Get all the terms sorted by slug (<em>or any other field desired</em>) associated with our taxonomy</p></li>\n<li><p>Get the current term object</p></li>\n<li><p>Determine where in the array our current term is</p></li>\n<li><p>Get the two adjacent terms (<em>if any</em>)</p></li>\n<li><p>Build the links to those term pages</p></li>\n</ul>\n\n<h2>THE FUNCTION</h2>\n\n<p>I have written a function to take care of this. It ids always important to keep business logic out of templates. Templates should only know function names and not the entire function. This way, you keep your templates clean and maintainable</p>\n\n<p>The function does require a minimum of PHP 5.4 and covers the basics, it is up to you to adjust it to your needs</p>\n\n<pre><code>function get_tax_navigation( $taxonomy = 'category' ) \n{\n // Make sure we are on a taxonomy term/category/tag archive page, if not, bail\n if ( 'category' === $taxonomy ) {\n if ( !is_category() )\n return false;\n } elseif ( 'post_tag' === $taxonomy ) {\n if ( !is_tag() )\n return false;\n } else {\n if ( !is_tax( $taxonomy ) )\n return false;\n }\n\n // Make sure the taxonomy is valid and sanitize the taxonomy\n if ( 'category' !== $taxonomy \n || 'post_tag' !== $taxonomy\n ) {\n $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );\n if ( !$taxonomy )\n return false;\n\n if ( !taxonomy_exists( $taxonomy ) )\n return false;\n }\n\n // Get the current term object\n $current_term = get_term( $GLOBALS['wp_the_query']-&gt;get_queried_object() );\n\n // Get all the terms ordered by slug \n $terms = get_terms( $taxonomy, ['orderby' =&gt; 'slug'] );\n\n // Make sure we have terms before we continue\n if ( !$terms ) \n return false;\n\n // Because empty terms stuffs around with array keys, lets reset them\n $terms = array_values( $terms );\n\n // Lets get all the term id's from the array of term objects\n $term_ids = wp_list_pluck( $terms, 'term_id' );\n\n /**\n * We now need to locate the position of the current term amongs the $term_ids array. \\\n * This way, we can now know which terms are adjacent to the current one\n */\n $current_term_position = array_search( $current_term-&gt;term_id, $term_ids );\n\n // Set default variables to hold the next and previous terms\n $previous_term = '';\n $next_term = '';\n\n // Get the previous term\n if ( 0 !== $current_term_position ) \n $previous_term = $terms[$current_term_position - 1];\n\n // Get the next term\n if ( intval( count( $term_ids ) - 1 ) !== $current_term_position ) \n $next_term = $terms[$current_term_position + 1];\n\n $link = [];\n // Build the links\n if ( $previous_term ) \n $link[] = 'Previous Term: &lt;a href=\"' . esc_url( get_term_link( $previous_term ) ) . '\"&gt;' . $previous_term-&gt;name . '&lt;/a&gt;';\n\n if ( $next_term ) \n $link[] = 'Next Term: &lt;a href=\"' . esc_url( get_term_link( $next_term ) ) . '\"&gt;' . $next_term-&gt;name . '&lt;/a&gt;';\n\n return implode( ' ...|... ', $link );\n}\n</code></pre>\n\n<h2>USAGE</h2>\n\n<p>You can now just use the function where needed as follow:</p>\n\n<pre><code>echo get_tax_navigation( 'podcast' );\n</code></pre>\n\n<h2>EDIT - from comments</h2>\n\n<blockquote>\n <p>Just two questions: (1)When we are at the last term, can we still make the Next Term: (URL to the First term) and vise versa? Basically an infinite term loop. (2)For theming purposes, how can I use this function to output NEXT and PREVIOUS urls individually? (eg. get_tax_navigation( 'podcast', 'previous' ) and get_tax_navigation( 'podcast', 'next' )</p>\n</blockquote>\n\n<ol>\n<li><p>When we are on the last of first term, all we need to do is either grab the first or last term depending on where we at. Obviously, when we are on the laste term, we will grab the first one, and vica-versa</p></li>\n<li><p>We can introduce a <code>$direction</code> parameter which accepts three values, an empty string, <code>previous</code> or <code>next</code></p></li>\n</ol>\n\n<p>Here is an example of what you can do. You can adjust it from here to suite your needs</p>\n\n<pre><code>function get_tax_navigation( $taxonomy = 'category', $direction = '' ) \n{\n // Make sure we are on a taxonomy term/category/tag archive page, if not, bail\n if ( 'category' === $taxonomy ) {\n if ( !is_category() )\n return false;\n } elseif ( 'post_tag' === $taxonomy ) {\n if ( !is_tag() )\n return false;\n } else {\n if ( !is_tax( $taxonomy ) )\n return false;\n }\n\n // Make sure the taxonomy is valid and sanitize the taxonomy\n if ( 'category' !== $taxonomy \n || 'post_tag' !== $taxonomy\n ) {\n $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );\n if ( !$taxonomy )\n return false;\n\n if ( !taxonomy_exists( $taxonomy ) )\n return false;\n }\n\n // Get the current term object\n $current_term = get_term( $GLOBALS['wp_the_query']-&gt;get_queried_object() );\n\n // Get all the terms ordered by slug \n $terms = get_terms( $taxonomy, ['orderby' =&gt; 'slug'] );\n\n // Make sure we have terms before we continue\n if ( !$terms ) \n return false;\n\n // Because empty terms stuffs around with array keys, lets reset them\n $terms = array_values( $terms );\n\n // Lets get all the term id's from the array of term objects\n $term_ids = wp_list_pluck( $terms, 'term_id' );\n\n /**\n * We now need to locate the position of the current term amongs the $term_ids array. \\\n * This way, we can now know which terms are adjacent to the current one\n */\n $current_term_position = array_search( $current_term-&gt;term_id, $term_ids );\n\n // Set default variables to hold the next and previous terms\n $previous_term = '';\n $next_term = '';\n\n // Get the previous term\n if ( 'previous' === $direction \n || !$direction\n ) {\n if ( 0 === $current_term_position ) {\n $previous_term = $terms[intval( count( $term_ids ) - 1 )];\n } else {\n $previous_term = $terms[$current_term_position - 1];\n }\n }\n\n // Get the next term\n if ( 'next' === $direction\n || !$direction\n ) {\n if ( intval( count( $term_ids ) - 1 ) === $current_term_position ) {\n $next_term = $terms[0];\n } else {\n $next_term = $terms[$current_term_position + 1];\n }\n }\n\n $link = [];\n // Build the links\n if ( $previous_term ) \n $link[] = 'Previous Term: &lt;a href=\"' . esc_url( get_term_link( $previous_term ) ) . '\"&gt;' . $previous_term-&gt;name . '&lt;/a&gt;';\n\n if ( $next_term ) \n $link[] = 'Next Term: &lt;a href=\"' . esc_url( get_term_link( $next_term ) ) . '\"&gt;' . $next_term-&gt;name . '&lt;/a&gt;';\n\n return implode( ' ...|... ', $link );\n}\n</code></pre>\n\n<p>You can use the code in three different ways</p>\n\n<ul>\n<li><p><code>echo get_tax_navigation( 'podcast' );</code> to display next and previous terms</p></li>\n<li><p><code>echo get_tax_navigation( 'podcast', 'previous' );</code> to display only the previous term</p></li>\n<li><p><code>echo get_tax_navigation( 'podcast', 'next' );</code> to display only the next term</p></li>\n</ul>\n" } ]
2016/04/03
[ "https://wordpress.stackexchange.com/questions/222498", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48726/" ]
I have a custom post type called `shows` and taxonomy called `podcast`. Using `taxonomy-podcast.php`, I having hard time finding a function that will generate next/previous Term URL Archive. For Example: ------------ URL: url.com/podcast/example-term-2 > > **Example Term 2** > > > post 1,post 2,post 3 > > > Desired output ``` < Previous Term(url.com/podcast/example-term-1) . . . . . | . . . . . Next Term(url.com/podcast/example-term-3)> ```
It is quite possible to achieve this. What we need to do is * Get all the terms sorted by slug (*or any other field desired*) associated with our taxonomy * Get the current term object * Determine where in the array our current term is * Get the two adjacent terms (*if any*) * Build the links to those term pages THE FUNCTION ------------ I have written a function to take care of this. It ids always important to keep business logic out of templates. Templates should only know function names and not the entire function. This way, you keep your templates clean and maintainable The function does require a minimum of PHP 5.4 and covers the basics, it is up to you to adjust it to your needs ``` function get_tax_navigation( $taxonomy = 'category' ) { // Make sure we are on a taxonomy term/category/tag archive page, if not, bail if ( 'category' === $taxonomy ) { if ( !is_category() ) return false; } elseif ( 'post_tag' === $taxonomy ) { if ( !is_tag() ) return false; } else { if ( !is_tax( $taxonomy ) ) return false; } // Make sure the taxonomy is valid and sanitize the taxonomy if ( 'category' !== $taxonomy || 'post_tag' !== $taxonomy ) { $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING ); if ( !$taxonomy ) return false; if ( !taxonomy_exists( $taxonomy ) ) return false; } // Get the current term object $current_term = get_term( $GLOBALS['wp_the_query']->get_queried_object() ); // Get all the terms ordered by slug $terms = get_terms( $taxonomy, ['orderby' => 'slug'] ); // Make sure we have terms before we continue if ( !$terms ) return false; // Because empty terms stuffs around with array keys, lets reset them $terms = array_values( $terms ); // Lets get all the term id's from the array of term objects $term_ids = wp_list_pluck( $terms, 'term_id' ); /** * We now need to locate the position of the current term amongs the $term_ids array. \ * This way, we can now know which terms are adjacent to the current one */ $current_term_position = array_search( $current_term->term_id, $term_ids ); // Set default variables to hold the next and previous terms $previous_term = ''; $next_term = ''; // Get the previous term if ( 0 !== $current_term_position ) $previous_term = $terms[$current_term_position - 1]; // Get the next term if ( intval( count( $term_ids ) - 1 ) !== $current_term_position ) $next_term = $terms[$current_term_position + 1]; $link = []; // Build the links if ( $previous_term ) $link[] = 'Previous Term: <a href="' . esc_url( get_term_link( $previous_term ) ) . '">' . $previous_term->name . '</a>'; if ( $next_term ) $link[] = 'Next Term: <a href="' . esc_url( get_term_link( $next_term ) ) . '">' . $next_term->name . '</a>'; return implode( ' ...|... ', $link ); } ``` USAGE ----- You can now just use the function where needed as follow: ``` echo get_tax_navigation( 'podcast' ); ``` EDIT - from comments -------------------- > > Just two questions: (1)When we are at the last term, can we still make the Next Term: (URL to the First term) and vise versa? Basically an infinite term loop. (2)For theming purposes, how can I use this function to output NEXT and PREVIOUS urls individually? (eg. get\_tax\_navigation( 'podcast', 'previous' ) and get\_tax\_navigation( 'podcast', 'next' ) > > > 1. When we are on the last of first term, all we need to do is either grab the first or last term depending on where we at. Obviously, when we are on the laste term, we will grab the first one, and vica-versa 2. We can introduce a `$direction` parameter which accepts three values, an empty string, `previous` or `next` Here is an example of what you can do. You can adjust it from here to suite your needs ``` function get_tax_navigation( $taxonomy = 'category', $direction = '' ) { // Make sure we are on a taxonomy term/category/tag archive page, if not, bail if ( 'category' === $taxonomy ) { if ( !is_category() ) return false; } elseif ( 'post_tag' === $taxonomy ) { if ( !is_tag() ) return false; } else { if ( !is_tax( $taxonomy ) ) return false; } // Make sure the taxonomy is valid and sanitize the taxonomy if ( 'category' !== $taxonomy || 'post_tag' !== $taxonomy ) { $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING ); if ( !$taxonomy ) return false; if ( !taxonomy_exists( $taxonomy ) ) return false; } // Get the current term object $current_term = get_term( $GLOBALS['wp_the_query']->get_queried_object() ); // Get all the terms ordered by slug $terms = get_terms( $taxonomy, ['orderby' => 'slug'] ); // Make sure we have terms before we continue if ( !$terms ) return false; // Because empty terms stuffs around with array keys, lets reset them $terms = array_values( $terms ); // Lets get all the term id's from the array of term objects $term_ids = wp_list_pluck( $terms, 'term_id' ); /** * We now need to locate the position of the current term amongs the $term_ids array. \ * This way, we can now know which terms are adjacent to the current one */ $current_term_position = array_search( $current_term->term_id, $term_ids ); // Set default variables to hold the next and previous terms $previous_term = ''; $next_term = ''; // Get the previous term if ( 'previous' === $direction || !$direction ) { if ( 0 === $current_term_position ) { $previous_term = $terms[intval( count( $term_ids ) - 1 )]; } else { $previous_term = $terms[$current_term_position - 1]; } } // Get the next term if ( 'next' === $direction || !$direction ) { if ( intval( count( $term_ids ) - 1 ) === $current_term_position ) { $next_term = $terms[0]; } else { $next_term = $terms[$current_term_position + 1]; } } $link = []; // Build the links if ( $previous_term ) $link[] = 'Previous Term: <a href="' . esc_url( get_term_link( $previous_term ) ) . '">' . $previous_term->name . '</a>'; if ( $next_term ) $link[] = 'Next Term: <a href="' . esc_url( get_term_link( $next_term ) ) . '">' . $next_term->name . '</a>'; return implode( ' ...|... ', $link ); } ``` You can use the code in three different ways * `echo get_tax_navigation( 'podcast' );` to display next and previous terms * `echo get_tax_navigation( 'podcast', 'previous' );` to display only the previous term * `echo get_tax_navigation( 'podcast', 'next' );` to display only the next term
222,501
<p>How can I apply this function to a single page ID:</p> <pre><code>function exclude_jobs_locations($args){ $exclude = "40"; $args["exclude"] = $exclude; return $args; } add_filter("sjb_job_location_filter_args","exclude_jobs_locations"); </code></pre> <p>Can I also exclude child categories when parent category is excluded?</p> <p>I've tried with:</p> <pre><code>function exclude_jobs_locations_uk($args){ if( is_page( 2094 ) ) { $exclude = "40"; $args["exclude"] = $exclude; } return $args; } add_filter("sjb_job_location_filter_args","exclude_jobs_locations_uk"); </code></pre> <p>But something goes wrong.</p> <p>I use this function to exclude category from:</p> <pre><code>// Creating list on non-empty job location $jobloc_select = wp_dropdown_categories(apply_filters('sjb_job_location_filter_args', array( 'show_option_none' =&gt; __('Location', 'simple-job-board'), 'hide_empty' =&gt; 0, 'name' =&gt; 'selected_location', 'orderby' =&gt; 'NAME', 'order' =&gt; 'ASC', 'class' =&gt; 'sjb-form-control', 'hierarchical' =&gt; TRUE, 'value_field' =&gt; 'slug', 'taxonomy' =&gt; 'jobpost_location', 'selected' =&gt; $selected_location, 'echo' =&gt; FALSE, ))); ?&gt; </code></pre>
[ { "answer_id": 222504, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>Something like this will do it, if you have a lot of terms it could be a rather expensive query though as it retrieves them all, can't see a way around that right now... (though you could cache all term results in a transient perhaps so it is not being done every pageload.)</p>\n\n<pre><code>function custom_term_navigation() {\n $thistermid = get_queried_object()-&gt;term_id;\n if (!is_numeric($thistermid)) {return;}\n\n // remove commenting to use transient storage\n // $terms = get_transient('all_podcast_terms');\n // if (!$terms) {\n $args = array('orderby'=&gt;'slug');\n $terms = get_terms('podcast',$args);\n // set_transient('all_podcast_terms',$terms,60*60);\n // }\n\n $termid = ''; $termslug = ''; $foundterm = false;\n foreach ($terms as $term) {\n $prevterm = $termslug;\n $termid = $term-&gt;term_id;\n if ($foundterm) {$nextterm = $term-&gt;slug; break;}\n if ($termid == $thistermid) {\n $foundterm = true; $previousterm = $prevterm;\n }\n $termslug = $term-&gt;slug;\n }\n\n $navigation = '';\n if ($previousterm != '') {\n $previoustermlink = get_term_link($previousterm,'podcast');\n $navigation .= \"\".$previoustermlink.\"' style='float:left; display:inline;'&gt;&amp;larr; Previous Term&lt;/a&gt;\";\n }\n if ($nexterm != '') {\n $nexttermlink = get_term_link($nexterm,'podcast');\n $navigation .= \"&lt;a href='\".$nextermlink.\"' style='float:right; display:inline;'&gt;Next Term &amp;rarr;&lt;/a&gt;\";\n }\n\n return $navigation;\n}\n</code></pre>\n" }, { "answer_id": 222537, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 4, "selected": true, "text": "<p>It is quite possible to achieve this. What we need to do is</p>\n\n<ul>\n<li><p>Get all the terms sorted by slug (<em>or any other field desired</em>) associated with our taxonomy</p></li>\n<li><p>Get the current term object</p></li>\n<li><p>Determine where in the array our current term is</p></li>\n<li><p>Get the two adjacent terms (<em>if any</em>)</p></li>\n<li><p>Build the links to those term pages</p></li>\n</ul>\n\n<h2>THE FUNCTION</h2>\n\n<p>I have written a function to take care of this. It ids always important to keep business logic out of templates. Templates should only know function names and not the entire function. This way, you keep your templates clean and maintainable</p>\n\n<p>The function does require a minimum of PHP 5.4 and covers the basics, it is up to you to adjust it to your needs</p>\n\n<pre><code>function get_tax_navigation( $taxonomy = 'category' ) \n{\n // Make sure we are on a taxonomy term/category/tag archive page, if not, bail\n if ( 'category' === $taxonomy ) {\n if ( !is_category() )\n return false;\n } elseif ( 'post_tag' === $taxonomy ) {\n if ( !is_tag() )\n return false;\n } else {\n if ( !is_tax( $taxonomy ) )\n return false;\n }\n\n // Make sure the taxonomy is valid and sanitize the taxonomy\n if ( 'category' !== $taxonomy \n || 'post_tag' !== $taxonomy\n ) {\n $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );\n if ( !$taxonomy )\n return false;\n\n if ( !taxonomy_exists( $taxonomy ) )\n return false;\n }\n\n // Get the current term object\n $current_term = get_term( $GLOBALS['wp_the_query']-&gt;get_queried_object() );\n\n // Get all the terms ordered by slug \n $terms = get_terms( $taxonomy, ['orderby' =&gt; 'slug'] );\n\n // Make sure we have terms before we continue\n if ( !$terms ) \n return false;\n\n // Because empty terms stuffs around with array keys, lets reset them\n $terms = array_values( $terms );\n\n // Lets get all the term id's from the array of term objects\n $term_ids = wp_list_pluck( $terms, 'term_id' );\n\n /**\n * We now need to locate the position of the current term amongs the $term_ids array. \\\n * This way, we can now know which terms are adjacent to the current one\n */\n $current_term_position = array_search( $current_term-&gt;term_id, $term_ids );\n\n // Set default variables to hold the next and previous terms\n $previous_term = '';\n $next_term = '';\n\n // Get the previous term\n if ( 0 !== $current_term_position ) \n $previous_term = $terms[$current_term_position - 1];\n\n // Get the next term\n if ( intval( count( $term_ids ) - 1 ) !== $current_term_position ) \n $next_term = $terms[$current_term_position + 1];\n\n $link = [];\n // Build the links\n if ( $previous_term ) \n $link[] = 'Previous Term: &lt;a href=\"' . esc_url( get_term_link( $previous_term ) ) . '\"&gt;' . $previous_term-&gt;name . '&lt;/a&gt;';\n\n if ( $next_term ) \n $link[] = 'Next Term: &lt;a href=\"' . esc_url( get_term_link( $next_term ) ) . '\"&gt;' . $next_term-&gt;name . '&lt;/a&gt;';\n\n return implode( ' ...|... ', $link );\n}\n</code></pre>\n\n<h2>USAGE</h2>\n\n<p>You can now just use the function where needed as follow:</p>\n\n<pre><code>echo get_tax_navigation( 'podcast' );\n</code></pre>\n\n<h2>EDIT - from comments</h2>\n\n<blockquote>\n <p>Just two questions: (1)When we are at the last term, can we still make the Next Term: (URL to the First term) and vise versa? Basically an infinite term loop. (2)For theming purposes, how can I use this function to output NEXT and PREVIOUS urls individually? (eg. get_tax_navigation( 'podcast', 'previous' ) and get_tax_navigation( 'podcast', 'next' )</p>\n</blockquote>\n\n<ol>\n<li><p>When we are on the last of first term, all we need to do is either grab the first or last term depending on where we at. Obviously, when we are on the laste term, we will grab the first one, and vica-versa</p></li>\n<li><p>We can introduce a <code>$direction</code> parameter which accepts three values, an empty string, <code>previous</code> or <code>next</code></p></li>\n</ol>\n\n<p>Here is an example of what you can do. You can adjust it from here to suite your needs</p>\n\n<pre><code>function get_tax_navigation( $taxonomy = 'category', $direction = '' ) \n{\n // Make sure we are on a taxonomy term/category/tag archive page, if not, bail\n if ( 'category' === $taxonomy ) {\n if ( !is_category() )\n return false;\n } elseif ( 'post_tag' === $taxonomy ) {\n if ( !is_tag() )\n return false;\n } else {\n if ( !is_tax( $taxonomy ) )\n return false;\n }\n\n // Make sure the taxonomy is valid and sanitize the taxonomy\n if ( 'category' !== $taxonomy \n || 'post_tag' !== $taxonomy\n ) {\n $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );\n if ( !$taxonomy )\n return false;\n\n if ( !taxonomy_exists( $taxonomy ) )\n return false;\n }\n\n // Get the current term object\n $current_term = get_term( $GLOBALS['wp_the_query']-&gt;get_queried_object() );\n\n // Get all the terms ordered by slug \n $terms = get_terms( $taxonomy, ['orderby' =&gt; 'slug'] );\n\n // Make sure we have terms before we continue\n if ( !$terms ) \n return false;\n\n // Because empty terms stuffs around with array keys, lets reset them\n $terms = array_values( $terms );\n\n // Lets get all the term id's from the array of term objects\n $term_ids = wp_list_pluck( $terms, 'term_id' );\n\n /**\n * We now need to locate the position of the current term amongs the $term_ids array. \\\n * This way, we can now know which terms are adjacent to the current one\n */\n $current_term_position = array_search( $current_term-&gt;term_id, $term_ids );\n\n // Set default variables to hold the next and previous terms\n $previous_term = '';\n $next_term = '';\n\n // Get the previous term\n if ( 'previous' === $direction \n || !$direction\n ) {\n if ( 0 === $current_term_position ) {\n $previous_term = $terms[intval( count( $term_ids ) - 1 )];\n } else {\n $previous_term = $terms[$current_term_position - 1];\n }\n }\n\n // Get the next term\n if ( 'next' === $direction\n || !$direction\n ) {\n if ( intval( count( $term_ids ) - 1 ) === $current_term_position ) {\n $next_term = $terms[0];\n } else {\n $next_term = $terms[$current_term_position + 1];\n }\n }\n\n $link = [];\n // Build the links\n if ( $previous_term ) \n $link[] = 'Previous Term: &lt;a href=\"' . esc_url( get_term_link( $previous_term ) ) . '\"&gt;' . $previous_term-&gt;name . '&lt;/a&gt;';\n\n if ( $next_term ) \n $link[] = 'Next Term: &lt;a href=\"' . esc_url( get_term_link( $next_term ) ) . '\"&gt;' . $next_term-&gt;name . '&lt;/a&gt;';\n\n return implode( ' ...|... ', $link );\n}\n</code></pre>\n\n<p>You can use the code in three different ways</p>\n\n<ul>\n<li><p><code>echo get_tax_navigation( 'podcast' );</code> to display next and previous terms</p></li>\n<li><p><code>echo get_tax_navigation( 'podcast', 'previous' );</code> to display only the previous term</p></li>\n<li><p><code>echo get_tax_navigation( 'podcast', 'next' );</code> to display only the next term</p></li>\n</ul>\n" } ]
2016/04/03
[ "https://wordpress.stackexchange.com/questions/222501", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90898/" ]
How can I apply this function to a single page ID: ``` function exclude_jobs_locations($args){ $exclude = "40"; $args["exclude"] = $exclude; return $args; } add_filter("sjb_job_location_filter_args","exclude_jobs_locations"); ``` Can I also exclude child categories when parent category is excluded? I've tried with: ``` function exclude_jobs_locations_uk($args){ if( is_page( 2094 ) ) { $exclude = "40"; $args["exclude"] = $exclude; } return $args; } add_filter("sjb_job_location_filter_args","exclude_jobs_locations_uk"); ``` But something goes wrong. I use this function to exclude category from: ``` // Creating list on non-empty job location $jobloc_select = wp_dropdown_categories(apply_filters('sjb_job_location_filter_args', array( 'show_option_none' => __('Location', 'simple-job-board'), 'hide_empty' => 0, 'name' => 'selected_location', 'orderby' => 'NAME', 'order' => 'ASC', 'class' => 'sjb-form-control', 'hierarchical' => TRUE, 'value_field' => 'slug', 'taxonomy' => 'jobpost_location', 'selected' => $selected_location, 'echo' => FALSE, ))); ?> ```
It is quite possible to achieve this. What we need to do is * Get all the terms sorted by slug (*or any other field desired*) associated with our taxonomy * Get the current term object * Determine where in the array our current term is * Get the two adjacent terms (*if any*) * Build the links to those term pages THE FUNCTION ------------ I have written a function to take care of this. It ids always important to keep business logic out of templates. Templates should only know function names and not the entire function. This way, you keep your templates clean and maintainable The function does require a minimum of PHP 5.4 and covers the basics, it is up to you to adjust it to your needs ``` function get_tax_navigation( $taxonomy = 'category' ) { // Make sure we are on a taxonomy term/category/tag archive page, if not, bail if ( 'category' === $taxonomy ) { if ( !is_category() ) return false; } elseif ( 'post_tag' === $taxonomy ) { if ( !is_tag() ) return false; } else { if ( !is_tax( $taxonomy ) ) return false; } // Make sure the taxonomy is valid and sanitize the taxonomy if ( 'category' !== $taxonomy || 'post_tag' !== $taxonomy ) { $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING ); if ( !$taxonomy ) return false; if ( !taxonomy_exists( $taxonomy ) ) return false; } // Get the current term object $current_term = get_term( $GLOBALS['wp_the_query']->get_queried_object() ); // Get all the terms ordered by slug $terms = get_terms( $taxonomy, ['orderby' => 'slug'] ); // Make sure we have terms before we continue if ( !$terms ) return false; // Because empty terms stuffs around with array keys, lets reset them $terms = array_values( $terms ); // Lets get all the term id's from the array of term objects $term_ids = wp_list_pluck( $terms, 'term_id' ); /** * We now need to locate the position of the current term amongs the $term_ids array. \ * This way, we can now know which terms are adjacent to the current one */ $current_term_position = array_search( $current_term->term_id, $term_ids ); // Set default variables to hold the next and previous terms $previous_term = ''; $next_term = ''; // Get the previous term if ( 0 !== $current_term_position ) $previous_term = $terms[$current_term_position - 1]; // Get the next term if ( intval( count( $term_ids ) - 1 ) !== $current_term_position ) $next_term = $terms[$current_term_position + 1]; $link = []; // Build the links if ( $previous_term ) $link[] = 'Previous Term: <a href="' . esc_url( get_term_link( $previous_term ) ) . '">' . $previous_term->name . '</a>'; if ( $next_term ) $link[] = 'Next Term: <a href="' . esc_url( get_term_link( $next_term ) ) . '">' . $next_term->name . '</a>'; return implode( ' ...|... ', $link ); } ``` USAGE ----- You can now just use the function where needed as follow: ``` echo get_tax_navigation( 'podcast' ); ``` EDIT - from comments -------------------- > > Just two questions: (1)When we are at the last term, can we still make the Next Term: (URL to the First term) and vise versa? Basically an infinite term loop. (2)For theming purposes, how can I use this function to output NEXT and PREVIOUS urls individually? (eg. get\_tax\_navigation( 'podcast', 'previous' ) and get\_tax\_navigation( 'podcast', 'next' ) > > > 1. When we are on the last of first term, all we need to do is either grab the first or last term depending on where we at. Obviously, when we are on the laste term, we will grab the first one, and vica-versa 2. We can introduce a `$direction` parameter which accepts three values, an empty string, `previous` or `next` Here is an example of what you can do. You can adjust it from here to suite your needs ``` function get_tax_navigation( $taxonomy = 'category', $direction = '' ) { // Make sure we are on a taxonomy term/category/tag archive page, if not, bail if ( 'category' === $taxonomy ) { if ( !is_category() ) return false; } elseif ( 'post_tag' === $taxonomy ) { if ( !is_tag() ) return false; } else { if ( !is_tax( $taxonomy ) ) return false; } // Make sure the taxonomy is valid and sanitize the taxonomy if ( 'category' !== $taxonomy || 'post_tag' !== $taxonomy ) { $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING ); if ( !$taxonomy ) return false; if ( !taxonomy_exists( $taxonomy ) ) return false; } // Get the current term object $current_term = get_term( $GLOBALS['wp_the_query']->get_queried_object() ); // Get all the terms ordered by slug $terms = get_terms( $taxonomy, ['orderby' => 'slug'] ); // Make sure we have terms before we continue if ( !$terms ) return false; // Because empty terms stuffs around with array keys, lets reset them $terms = array_values( $terms ); // Lets get all the term id's from the array of term objects $term_ids = wp_list_pluck( $terms, 'term_id' ); /** * We now need to locate the position of the current term amongs the $term_ids array. \ * This way, we can now know which terms are adjacent to the current one */ $current_term_position = array_search( $current_term->term_id, $term_ids ); // Set default variables to hold the next and previous terms $previous_term = ''; $next_term = ''; // Get the previous term if ( 'previous' === $direction || !$direction ) { if ( 0 === $current_term_position ) { $previous_term = $terms[intval( count( $term_ids ) - 1 )]; } else { $previous_term = $terms[$current_term_position - 1]; } } // Get the next term if ( 'next' === $direction || !$direction ) { if ( intval( count( $term_ids ) - 1 ) === $current_term_position ) { $next_term = $terms[0]; } else { $next_term = $terms[$current_term_position + 1]; } } $link = []; // Build the links if ( $previous_term ) $link[] = 'Previous Term: <a href="' . esc_url( get_term_link( $previous_term ) ) . '">' . $previous_term->name . '</a>'; if ( $next_term ) $link[] = 'Next Term: <a href="' . esc_url( get_term_link( $next_term ) ) . '">' . $next_term->name . '</a>'; return implode( ' ...|... ', $link ); } ``` You can use the code in three different ways * `echo get_tax_navigation( 'podcast' );` to display next and previous terms * `echo get_tax_navigation( 'podcast', 'previous' );` to display only the previous term * `echo get_tax_navigation( 'podcast', 'next' );` to display only the next term
222,526
<p>I need to move my simple <code>Wordpres</code> site from <code>www.mysite.oldplace.com</code> to <code>www.oldplace.com</code> in most as possible simple and native way. My simple site specification: WP 4.4.2 Twenty Twelve 1.9 theme Polylang plugin 1.8.4 </p> <p>I know that I can install some plugins that might do this job, but I'm not sure they really does this job well. I have heard something regarding searching and replacing site name in SQL backup/restore script. But I beleave that in our days this somehow should be solved with native WP tools. Please, describe me les paint full approach to this problem.</p>
[ { "answer_id": 222527, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 1, "selected": false, "text": "<p>Unfortunately there's nothing native in WordPress to handle searching and replacing your domain name across all your posts, options, etc.</p>\n\n<p>The closest you can get is WP-CLI's <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\">search-replace</a> command. It's not an official WordPress project, but it has quite a high adoption rate, it's very well maintained and available by default or on demand on many hosting platforms:</p>\n\n<pre><code>wp search-replace 'http://old-site.org' 'http://new-site.org'\n</code></pre>\n\n<p>Another popular option is <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow\">this</a> database search and replace script which, just like WP-CLI, correctly handles serialized data, which is important for WordPress because many options and meta values are stored as serialized arrays.</p>\n" }, { "answer_id": 222533, "author": "Laurence Tuck", "author_id": 1426, "author_profile": "https://wordpress.stackexchange.com/users/1426", "pm_score": 0, "selected": false, "text": "<p>You are probably going to need to copy everything to the new domain first if your host uses separate folders for sub domains. The least painful way of doing this is directly on the database, provided you are comfortable using phpmyadmin.\nYou can find and replace on each table using a mysql query and the query option in phpmyadmin:</p>\n\n<pre><code>update [table_name] set [field_name] = replace([field_name],'[string_to_find]','[string_to_replace]');\n</code></pre>\n\n<p>examples: </p>\n\n<pre><code>update wp_options set option_value = replace(option_value,'mysite.oldplace.com','oldplace.com');\n\nupdate wp_posts set post_content = replace(post_content,'mysite.oldplace.com','oldplace.com');\n\nupdate wp_postmeta set meta_value = replace(meta_value,'mysite.oldplace.com','oldplace.com');\n</code></pre>\n\n<p>The above queries should take care of the basic requirements to move your site. Plugins that create their own tables will need to edited in your wordpress backend.</p>\n" } ]
2016/04/03
[ "https://wordpress.stackexchange.com/questions/222526", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/74608/" ]
I need to move my simple `Wordpres` site from `www.mysite.oldplace.com` to `www.oldplace.com` in most as possible simple and native way. My simple site specification: WP 4.4.2 Twenty Twelve 1.9 theme Polylang plugin 1.8.4 I know that I can install some plugins that might do this job, but I'm not sure they really does this job well. I have heard something regarding searching and replacing site name in SQL backup/restore script. But I beleave that in our days this somehow should be solved with native WP tools. Please, describe me les paint full approach to this problem.
Unfortunately there's nothing native in WordPress to handle searching and replacing your domain name across all your posts, options, etc. The closest you can get is WP-CLI's [search-replace](http://wp-cli.org/commands/search-replace/) command. It's not an official WordPress project, but it has quite a high adoption rate, it's very well maintained and available by default or on demand on many hosting platforms: ``` wp search-replace 'http://old-site.org' 'http://new-site.org' ``` Another popular option is [this](https://interconnectit.com/products/search-and-replace-for-wordpress-databases/) database search and replace script which, just like WP-CLI, correctly handles serialized data, which is important for WordPress because many options and meta values are stored as serialized arrays.
222,535
<p>I am trying to build a simple Wordpress favourite post plugin that is scalable and could handle 1000s or 10000s of users or more.</p> <p>There are several different approaches that I have seen in other plugins and I would like to know which would be best practice from a scalability point of view, which means that size of the record or the number of records could be an issue.</p> <p>Problem: The basic idea is that there is a button on a post that a logged in user can click to favourite the post. This must then be stored in the database so that when the user goes to that post, they cannot favourite it again and also they can view a list of their favourited posts.</p> <p><strong>Option 1: Store in both user meta and post meta tables with serialised arrays</strong></p> <p>This is what the Wordpress Post Like System (<a href="https://hofmannsven.com/2013/laboratory/wordpress-post-like-system/" rel="nofollow">https://hofmannsven.com/2013/laboratory/wordpress-post-like-system/</a>) does. Following the click, the code retrieves _liked_posts meta key from the user meta table that stores in an array the post ids of the posts that the user has liked and it retrieves the _user_likes meta key from the post meta table that stores in an array the user ids of the users that have liked the post.</p> <p>The code then appends the current post id to the _liked_posts and the current user id to _user_likes. It also increments two further meta records: post like count and a user like count.</p> <p>What I like about this system is that it seems fairly simple, with only one record in user meta and one record in post meta storing who has liked what. What I don't like is that if you have many users liking the post or a user that likes many posts those meta value arrays could get very long, which I assume could cause problems?</p> <pre><code>$meta_POSTS = get_user_meta( $user_id, "_liked_posts" ); // post ids from user meta $meta_USERS = get_post_meta( $post_id, "_user_liked" ); // user ids from post meta $meta_POSTS['post-'.$post_id] = $post_id; // Add post id to user meta array $meta_USERS['user-'.$user_id] = $user_id; // add user id to post meta array update_post_meta( $post_id, "_user_liked", $meta_USERS ); // Add user ID to post meta update_user_meta( $user_id, "_liked_posts", $meta_POSTS ); // Add post ID to user meta </code></pre> <p><strong>Option 2: Add a record to user meta for each liked post</strong></p> <p>Following the click, the code checks if a record has already been inserted into user meta. If not, it adds a new record of the favourite. If it has, it does nothing.</p> <p>What I like about this system, is it is easy to query and generate statistics down the road as it is not tied up in serialised arrays. What I don't like is that if you have the user liking lots of posts you could hugely increase the number of records in the user meta table.</p> <pre><code>// Check if already favourited the post in User Meta // Not sure how you would do this with WP_Query or WP_User_Query, any suggestions? $favourited = WP_Query($args) if ($favourited-&gt;post_count == 0) { // Add user meta with favourite add_user_meta($userid, '_favourite_episode', $postid); } </code></pre> <p>So to conclude, what I am asking essentially is what is best practice here. Is it either:</p> <ul> <li>Having one large serialised array in a single meta key/value pair</li> <li>Having many meta/key value pairs with an integer in the meta value</li> <li>Is there another option I haven't considered?</li> </ul> <p><strong>EDIT:</strong> Following the answers given, I have decided that creating a custom table is the best way forward. I have found this tutorial that does pretty much what I want to do and in a much more extendable way so that I can add other actions as well as just 'favouriting'.</p> <p><a href="http://code.tutsplus.com/series/custom-database-tables--wp-33839" rel="nofollow">http://code.tutsplus.com/series/custom-database-tables--wp-33839</a></p>
[ { "answer_id": 222536, "author": "Marttin Notta", "author_id": 91525, "author_profile": "https://wordpress.stackexchange.com/users/91525", "pm_score": 0, "selected": false, "text": "<p><b>Option</b> 1 is not the best choice because serializing data means you must parse your SQL result to be readable and thus you can't take any advantages of SQL queries. </p>\n\n<p><b>Option</b> 2 would be the easiest way but if you have a lot of users that are liking a lot of posts then it starts to pollute user meta table.</p>\n\n<p><b>Option 3</b> what i would do, is create relational table between posts and users. Using relation table would be the easiest because then you can use SQL to do a lot of logic for you. For example you don't need to count how many likes one post has in PHP but instead run a query against SQL that does it for you and returns the result. Meaning it will be good for performance and if you uninstall the plugin then all you have to do is remove the table, simple and clean.</p>\n" }, { "answer_id": 222538, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": true, "text": "<p>You forgot option 3 - Add a special table in which the pair (user,post id) will be the index. Ok I am not a MySQL person so maybe it is too extreme, but maybe having two tables one with users as index and one with posts will be even better.</p>\n\n<p>The thing about performance is that there are rarely absolute solutions for everybody at anytime, and the \"best\" depends on your actual usage pattern, not the theoretical one. Or in other words, you are doing early optimization here.</p>\n\n<p>While option 2 seems to be faster for this specific information it will make the meta tables bigger and therefor is likely to slow down <strong>all</strong> requests to those tables (therefor the suggestion for option 3 which is very similar but do not impact other queries).</p>\n\n<p>Another issue you ignore here is the cost of data insert/update. This operation is much slower then a read and can not be cached. If you are going to have many likes at the same time, with option 2 you will lock the tables and requests will need to wait for others to complete and each insert will be slower while option 1 is likely to end in data corruption under naive implementation (two changes in the same time, at best only one of them will have impact).</p>\n\n<p>And then you should take into account what kind of caching will you do. With a good caching scheme the read time is a non issue.</p>\n\n<p>To conclude I wish that you will find this to be an actual problem that needs to be solved, till then just write proper api to access/change that data to hide the implementation detail so if it will become a problem you will be able to change the implementation without impacting the rest of your code.</p>\n" } ]
2016/04/03
[ "https://wordpress.stackexchange.com/questions/222535", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58447/" ]
I am trying to build a simple Wordpress favourite post plugin that is scalable and could handle 1000s or 10000s of users or more. There are several different approaches that I have seen in other plugins and I would like to know which would be best practice from a scalability point of view, which means that size of the record or the number of records could be an issue. Problem: The basic idea is that there is a button on a post that a logged in user can click to favourite the post. This must then be stored in the database so that when the user goes to that post, they cannot favourite it again and also they can view a list of their favourited posts. **Option 1: Store in both user meta and post meta tables with serialised arrays** This is what the Wordpress Post Like System (<https://hofmannsven.com/2013/laboratory/wordpress-post-like-system/>) does. Following the click, the code retrieves \_liked\_posts meta key from the user meta table that stores in an array the post ids of the posts that the user has liked and it retrieves the \_user\_likes meta key from the post meta table that stores in an array the user ids of the users that have liked the post. The code then appends the current post id to the \_liked\_posts and the current user id to \_user\_likes. It also increments two further meta records: post like count and a user like count. What I like about this system is that it seems fairly simple, with only one record in user meta and one record in post meta storing who has liked what. What I don't like is that if you have many users liking the post or a user that likes many posts those meta value arrays could get very long, which I assume could cause problems? ``` $meta_POSTS = get_user_meta( $user_id, "_liked_posts" ); // post ids from user meta $meta_USERS = get_post_meta( $post_id, "_user_liked" ); // user ids from post meta $meta_POSTS['post-'.$post_id] = $post_id; // Add post id to user meta array $meta_USERS['user-'.$user_id] = $user_id; // add user id to post meta array update_post_meta( $post_id, "_user_liked", $meta_USERS ); // Add user ID to post meta update_user_meta( $user_id, "_liked_posts", $meta_POSTS ); // Add post ID to user meta ``` **Option 2: Add a record to user meta for each liked post** Following the click, the code checks if a record has already been inserted into user meta. If not, it adds a new record of the favourite. If it has, it does nothing. What I like about this system, is it is easy to query and generate statistics down the road as it is not tied up in serialised arrays. What I don't like is that if you have the user liking lots of posts you could hugely increase the number of records in the user meta table. ``` // Check if already favourited the post in User Meta // Not sure how you would do this with WP_Query or WP_User_Query, any suggestions? $favourited = WP_Query($args) if ($favourited->post_count == 0) { // Add user meta with favourite add_user_meta($userid, '_favourite_episode', $postid); } ``` So to conclude, what I am asking essentially is what is best practice here. Is it either: * Having one large serialised array in a single meta key/value pair * Having many meta/key value pairs with an integer in the meta value * Is there another option I haven't considered? **EDIT:** Following the answers given, I have decided that creating a custom table is the best way forward. I have found this tutorial that does pretty much what I want to do and in a much more extendable way so that I can add other actions as well as just 'favouriting'. <http://code.tutsplus.com/series/custom-database-tables--wp-33839>
You forgot option 3 - Add a special table in which the pair (user,post id) will be the index. Ok I am not a MySQL person so maybe it is too extreme, but maybe having two tables one with users as index and one with posts will be even better. The thing about performance is that there are rarely absolute solutions for everybody at anytime, and the "best" depends on your actual usage pattern, not the theoretical one. Or in other words, you are doing early optimization here. While option 2 seems to be faster for this specific information it will make the meta tables bigger and therefor is likely to slow down **all** requests to those tables (therefor the suggestion for option 3 which is very similar but do not impact other queries). Another issue you ignore here is the cost of data insert/update. This operation is much slower then a read and can not be cached. If you are going to have many likes at the same time, with option 2 you will lock the tables and requests will need to wait for others to complete and each insert will be slower while option 1 is likely to end in data corruption under naive implementation (two changes in the same time, at best only one of them will have impact). And then you should take into account what kind of caching will you do. With a good caching scheme the read time is a non issue. To conclude I wish that you will find this to be an actual problem that needs to be solved, till then just write proper api to access/change that data to hide the implementation detail so if it will become a problem you will be able to change the implementation without impacting the rest of your code.
222,540
<p>On a fresh install, I want to move the upload folder to a subdomain (supposed to speed up download). My subdomain links to a folder called static. So I have: </p> <ul> <li>Home <ul> <li>wp <ul> <li>wp-admin</li> <li>wp-content</li> <li>wp-include</li> </ul></li> <li>static</li> </ul></li> </ul> <p>Now I need to tell WordPress where the upload folder is and define its URL. The <a href="http://codex.wordpress.org/Editing_wp-config.php#Moving_uploads_folder" rel="noreferrer">codex</a> says I should edit wp-config to define UPLOADS relative to ABSPAHT. But if I put <code>define( 'UPLOADS', '../static' );</code> of course URL in pages are like <code>//mydomain.tld/wp/../static/image.jpg</code> </p> <p>I've looked around, and found many different answers to that (filters, DB edit,...), some of them no longer true (since the media settings page no longer allows to change the upload folder) and some obviously wrong... I want to do it the right way.</p> <p>I went to the wp-admin/options.php page and set <code>upload_path = ../static</code> and <code>upload_url_path = http://static.mydomain.tld</code> and that seems to work. </p> <p><strong>But is that how it's supposed to be done?</strong> And if developpers have removed these options from the media settings page, isn't there a risk that the feature is later completely removed? </p>
[ { "answer_id": 222542, "author": "kovshenin", "author_id": 1316, "author_profile": "https://wordpress.stackexchange.com/users/1316", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>I went to the wp-admin/options.php page and set ... But is that how it's supposed to be done?</p>\n</blockquote>\n\n<p>Nope. You should never change anything in the WordPress core files because all your changes will be lost during the next update. You should use actions and filters instead:</p>\n\n<pre><code>add_filter( 'pre_option_upload_path', function( $upload_path ) {\n return '/path/to/static';\n});\n\nadd_filter( 'pre_option_upload_url_path', function( $upload_url_path ) {\n return 'http://static.example.org';\n});\n</code></pre>\n" }, { "answer_id": 323480, "author": "Kelly", "author_id": 94686, "author_profile": "https://wordpress.stackexchange.com/users/94686", "pm_score": 0, "selected": false, "text": "<p>I had a similar problem mapping subdomain media. <a href=\"https://wordpress.stackexchange.com/questions/77960/wordpress-3-5-setting-custom-full-url-path-to-files-in-the-media-library\">Asked &amp; Answered here</a>.<br> \nIn short, add to functions.php the following:<br></p>\n\n<pre><code>update_option('upload_url_path', '/wp-content/uploads');\n</code></pre>\n" }, { "answer_id": 361509, "author": "biziclop", "author_id": 975, "author_profile": "https://wordpress.stackexchange.com/users/975", "pm_score": 0, "selected": false, "text": "<p>If, for whatever reason you don't want to set the upload path options in the database or in your <code>functions.php</code>, you can still set the option filters in your <code>wp-config.php</code> like this (before calling any WordPress core file):</p>\n\n<pre><code>$GLOBALS['wp_filter']['pre_option_upload_path'][10][] = array(\n 'function' =&gt; function( $upload_path ){\n return '/path/to/static';\n },\n 'accepted_args' =&gt; 1,\n);\n\n$GLOBALS['wp_filter']['pre_option_upload_url_path'][10][] = array(\n 'function' =&gt; function( $upload_url_path ){\n return 'http://static.example.org';\n },\n 'accepted_args' =&gt; 1,\n);\n</code></pre>\n\n<p><code>WP_Hook::build_preinitialized_hooks</code> will properly update these array items to the actually used internal format.</p>\n" } ]
2016/04/03
[ "https://wordpress.stackexchange.com/questions/222540", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88773/" ]
On a fresh install, I want to move the upload folder to a subdomain (supposed to speed up download). My subdomain links to a folder called static. So I have: * Home + wp - wp-admin - wp-content - wp-include + static Now I need to tell WordPress where the upload folder is and define its URL. The [codex](http://codex.wordpress.org/Editing_wp-config.php#Moving_uploads_folder) says I should edit wp-config to define UPLOADS relative to ABSPAHT. But if I put `define( 'UPLOADS', '../static' );` of course URL in pages are like `//mydomain.tld/wp/../static/image.jpg` I've looked around, and found many different answers to that (filters, DB edit,...), some of them no longer true (since the media settings page no longer allows to change the upload folder) and some obviously wrong... I want to do it the right way. I went to the wp-admin/options.php page and set `upload_path = ../static` and `upload_url_path = http://static.mydomain.tld` and that seems to work. **But is that how it's supposed to be done?** And if developpers have removed these options from the media settings page, isn't there a risk that the feature is later completely removed?
> > I went to the wp-admin/options.php page and set ... But is that how it's supposed to be done? > > > Nope. You should never change anything in the WordPress core files because all your changes will be lost during the next update. You should use actions and filters instead: ``` add_filter( 'pre_option_upload_path', function( $upload_path ) { return '/path/to/static'; }); add_filter( 'pre_option_upload_url_path', function( $upload_url_path ) { return 'http://static.example.org'; }); ```
222,552
<p>I want to get all categories (custom taxonomy) in array from a specific post type. The taxonomy (category) registered for a specific post type only. And I want to retrieve all categories in an array. Be like -</p> <pre><code>array( 'Category Name 1' =&gt; 'slug-name-1', 'Category Name 2' =&gt; 'slug-name-2', 'Category Name 3' =&gt; 'slug-name-3', ); </code></pre> <p>It can be get category names by slug or id.</p>
[ { "answer_id": 222604, "author": "Luis Sanz", "author_id": 81084, "author_profile": "https://wordpress.stackexchange.com/users/81084", "pm_score": 1, "selected": false, "text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a> to retrieve the custom taxonomy terms and then build up a custom array to match the structure you want.</p>\n\n<p>Try this:</p>\n\n<pre><code>//Get the custom taxonomy terms\n$taxonomies = array(\n 'name' =&gt; 'your_custom_taxonomy' //Edit to match your needs\n);\n\n$taxonomy_terms = get_terms( $taxonomies );\n\n//This array will store the results\n$taxonomy_array = array();\n\n//Parse the terms\nforeach ( $taxonomy_terms as $taxonomy_term ) :\n\n //Get the taxonomy term name\n $taxonomy_term_name = $taxonomy_term-&gt;name;\n\n //Get the taxonomy term slug\n $taxonomy_term_slug = $taxonomy_term-&gt;slug;\n\n //Push the custom array\n $taxonomy_array[ $taxonomy_term_name ] = $taxonomy_term_slug;\n\nendforeach;\n</code></pre>\n\n<p>The data will be stored in <code>$taxonomy_array</code> following the format you provided. You can pass additional arguments to <code>get_terms()</code>, such as the order.</p>\n" }, { "answer_id": 306457, "author": "guido", "author_id": 98339, "author_profile": "https://wordpress.stackexchange.com/users/98339", "pm_score": 0, "selected": false, "text": "<p>If you want to retrieve all of the terms that are within all of the registered taxonomies for a specific post type you can use a function like the one below.</p>\n\n<pre><code>function termsByTaxonomiesPostType( $postType ) {\n\n if ( ! post_type_exists( $postType ) ) {\n return [];\n }\n\n $list = [];\n $taxonomies = get_object_taxonomies( $postType );\n\n if ( empty( $taxonomies ) ) {\n return [];\n }\n\n foreach ( $taxonomies as $taxonomy ) {\n $terms = get_terms( [\n 'taxonomy' =&gt; $taxonomy,\n 'fields' =&gt; 'all',\n ] );\n\n // Not an array if you pass 'count' as value for 'fields'.\n if ( ! is_array( $terms ) || is_wp_error( $terms ) ) {\n continue;\n }\n\n $list[ $taxonomy ] = [];\n\n // Note: if you want 'id=&gt;slug', 'id=&gt;name', 'names', 'id=&gt;parent', 'ids', 'slugs' only\n // You dont need to perform this.\n foreach ( $terms as $term ) {\n $list[ $taxonomy ] = array_merge(\n $list[ $taxonomy ],\n [\n $term-&gt;name =&gt; $term-&gt;slug,\n ]\n );\n }\n }\n\n return $list;\n}\n</code></pre>\n\n<p>You're list will contain a list of taxonomies and for each taxonomy a list of key => value pairs where the key is the <code>name</code> of the term and the value the <code>slug</code>.</p>\n\n<p>To note that if you want to retrieve 'id=>slug', 'id=>name', 'names', 'id=>parent', 'ids', 'slugs' only you don't need to perform an additional loop because WordPress will do it for you. </p>\n\n<p>To retrieve one of the associations listed above, just set the string as value for the key <code>fields</code>.</p>\n" } ]
2016/04/03
[ "https://wordpress.stackexchange.com/questions/222552", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81042/" ]
I want to get all categories (custom taxonomy) in array from a specific post type. The taxonomy (category) registered for a specific post type only. And I want to retrieve all categories in an array. Be like - ``` array( 'Category Name 1' => 'slug-name-1', 'Category Name 2' => 'slug-name-2', 'Category Name 3' => 'slug-name-3', ); ``` It can be get category names by slug or id.
You can use [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) to retrieve the custom taxonomy terms and then build up a custom array to match the structure you want. Try this: ``` //Get the custom taxonomy terms $taxonomies = array( 'name' => 'your_custom_taxonomy' //Edit to match your needs ); $taxonomy_terms = get_terms( $taxonomies ); //This array will store the results $taxonomy_array = array(); //Parse the terms foreach ( $taxonomy_terms as $taxonomy_term ) : //Get the taxonomy term name $taxonomy_term_name = $taxonomy_term->name; //Get the taxonomy term slug $taxonomy_term_slug = $taxonomy_term->slug; //Push the custom array $taxonomy_array[ $taxonomy_term_name ] = $taxonomy_term_slug; endforeach; ``` The data will be stored in `$taxonomy_array` following the format you provided. You can pass additional arguments to `get_terms()`, such as the order.
222,565
<p>I have two different files for the header in my theme. These are <code>header.php</code> and <code>header-full.php</code>. </p> <p>How can I load different CSS in different headers?</p> <p>I enqueue my CSS files in <code>function.php</code> like this:</p> <p><a href="https://i.stack.imgur.com/HE8U6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HE8U6.jpg" alt="enter image description here"></a> </p>
[ { "answer_id": 222575, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 1, "selected": true, "text": "<p>Enqueue style depending on a template filename:</p>\n\n<pre><code>if('header.php' == basename( get_page_template() ) { // check the template file name\n // enqueue header.php style here\n}\n\nif('header-full.php' == basename( get_page_template() ) { // check the template file name\n // enqueue header-full.php style here\n}\n</code></pre>\n\n<p><code>wp_enqueue_style</code> already registers a style so you don't need to register a style before enqueueing it except in very special cases. See <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow\">wp_enqueue_style</a>.</p>\n" }, { "answer_id": 222578, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 0, "selected": false, "text": "<p>If you want to stick with your enqueued files (probably a good idea <a href=\"https://wordpress.stackexchange.com/questions/49098/what-are-the-benefits-of-using-wp-enqueue-script\">as outlined here</a>), then - yes - you could add some conditionals in your functions.php such as:</p>\n\n<pre><code>if(some conditional) {\n// enqueue header.php style here\n}\n\nif(some other conditional) { \n// enqueue header-full.php style here\n}\n</code></pre>\n\n<p>Or, you don't have to enqueue them at all. You could just reference them in your two header files. Eg.in header.php put:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/bootstrap/css/custom.css\" type=\"text/css\" media=\"screen\" /&gt;\n</code></pre>\n\n<p>and in header-full.php put:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"&lt;?php echo get_stylesheet_directory_uri(); ?&gt;/bootstrap/css/full-header.css\" type=\"text/css\" media=\"screen\" /&gt;\n</code></pre>\n" }, { "answer_id": 223032, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": -1, "selected": false, "text": "<p>One simple way of doing it is by using a php function called \"basename\".</p>\n\n<p>If you have 2 header headerone.php, headertwo.php you can load different resources depending upon the name of the page you are viewing.</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n &lt;html&gt;\n &lt;head&gt;\n &lt;meta charset=\"utf-8\"/&gt;\n &lt;?php if(basename($_SERVER['PHP_SELF']) == 'headerone.php'){ ?&gt;\n &lt;link href=\"/includes/headerone.css\" rel=\"stylesheet\" media=\"all\"/&gt;\n &lt;?php }\n elseif(basename($_SERVER['PHP_SELF']) == 'headertwo.php'){\n ?&gt;\n &lt;link href=\"/includes/headertwo.css\" rel=\"stylesheet\" media=\"all\"/&gt;\n &lt;?php } ?&gt;\n &lt;/head&gt;\n&lt;body&gt;\n</code></pre>\n" } ]
2016/04/04
[ "https://wordpress.stackexchange.com/questions/222565", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91204/" ]
I have two different files for the header in my theme. These are `header.php` and `header-full.php`. How can I load different CSS in different headers? I enqueue my CSS files in `function.php` like this: [![enter image description here](https://i.stack.imgur.com/HE8U6.jpg)](https://i.stack.imgur.com/HE8U6.jpg)
Enqueue style depending on a template filename: ``` if('header.php' == basename( get_page_template() ) { // check the template file name // enqueue header.php style here } if('header-full.php' == basename( get_page_template() ) { // check the template file name // enqueue header-full.php style here } ``` `wp_enqueue_style` already registers a style so you don't need to register a style before enqueueing it except in very special cases. See [wp\_enqueue\_style](https://developer.wordpress.org/reference/functions/wp_enqueue_style/).
222,580
<p>i want to remove those <code>&lt;p&gt;</code> and <code>&lt;br/&gt;</code> tags from my contactform7 forms. now they have this wpcf7_autop which can be set to false when inserting:</p> <pre><code>define('WPCF7_AUTOP', false); </code></pre> <p>to wp-config.php</p> <p><strong>The problem is:</strong> I need this setting to be attached with my theme, so is it possible to some how do it through the functions.php file?</p>
[ { "answer_id": 222707, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 2, "selected": true, "text": "<ul>\n<li><p>You can try minify html from the contact form 7 </p></li>\n<li><p>To completely disable the wpautop filter, you can use:</p>\n\n<pre><code>remove_filter('the_content', 'wpautop');\n</code></pre></li>\n</ul>\n" }, { "answer_id": 296111, "author": "Gleb Kemarsky", "author_id": 93163, "author_profile": "https://wordpress.stackexchange.com/users/93163", "pm_score": 3, "selected": false, "text": "<p>If you have already upgraded CF7 to <a href=\"https://contactform7.com/2018/01/31/contact-form-7-50/\" rel=\"noreferrer\">version 5.0</a> or higher, then you can use the new hook:</p>\n\n<pre><code>add_filter( 'wpcf7_autop_or_not', '__return_false' );\n</code></pre>\n" }, { "answer_id": 307651, "author": "Eh Jewel", "author_id": 75264, "author_profile": "https://wordpress.stackexchange.com/users/75264", "pm_score": 2, "selected": false, "text": "<p>Use the following code to get ride of autop (automatic <code>&lt;p&gt;</code> tag) and line breaking tag (<code>&lt;br&gt;</code> tag).</p>\n\n<pre><code>&lt;?php\n// Remove auto p from Contact Form 7 shortcode output\nadd_filter('wpcf7_autop_or_not', 'wpcf7_autop_return_false');\nfunction wpcf7_autop_return_false() {\n return false;\n} \n</code></pre>\n\n<p>Add this code to your theme's <code>function.php</code> file.</p>\n" } ]
2016/04/04
[ "https://wordpress.stackexchange.com/questions/222580", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43619/" ]
i want to remove those `<p>` and `<br/>` tags from my contactform7 forms. now they have this wpcf7\_autop which can be set to false when inserting: ``` define('WPCF7_AUTOP', false); ``` to wp-config.php **The problem is:** I need this setting to be attached with my theme, so is it possible to some how do it through the functions.php file?
* You can try minify html from the contact form 7 * To completely disable the wpautop filter, you can use: ``` remove_filter('the_content', 'wpautop'); ```
222,608
<p>I wrote my first Plugin and have one issue, the content of my Plugin is shown on every page. So if I want to open my gallery it shows my plugin content.</p> <p><strong>myplugin.php</strong></p> <pre><code>&lt;?php /* * Plugin Name: Gw2 Event Timer * Plugin URI: http://localhost/wordpress * Description: T1Ein Guild Wars 2 Timer - beinhaltet alle Weltbosse und die neun HoT Gebiete * Version: 1.0 * Author: Niklas Grieger * Author URI: http://localhost/wordpress * License: No License */ $mm_plugin_basename = plugin_basename( __FILE__ ); function event_timer_head() { /** rtrim(get_settings('siteurl'), '/'): Gibt den Pfast .../wordpress zurück!!! **/ echo "&lt;link href='". rtrim(get_settings('siteurl'), '/') ."/wp-content/plugins/gw2eventtimer/style.css' rel='stylesheet' type='text/css' /&gt; &lt;script type='text/javascript' src='". rtrim(get_settings('siteurl'), '/') ."/wp-content/plugins/gw2eventtimer/js/js.js'&gt;&lt;/script&gt; &lt;script type='text/javascript' src='http://www.moongate.pl/event-timers/moment.min.js'&gt;&lt;/script&gt; "; } function event_timer_content($content) { $content="&lt;div id='event-wrapper' class='event-wrapper'&gt; &lt;div class='event-limit'&gt;&lt;span class='event-limit-text'&gt;Nächste&lt;/span&gt;&lt;/div&gt; &lt;div class='event-pointer'&gt;&lt;span class='event-pointer-time'&gt;00:00 UTC&lt;/span&gt;&lt;/div&gt; &lt;div style='height:10px; width:100%;'&gt;&lt;/div&gt; &lt;/div&gt;"; return strtolower($content); } function event_timer_title($title) { $title = str_replace(' ', ' ', $title); return $title; } function mh_load_my_script() { wp_enqueue_script( 'jquery' ); } add_action( 'wp_enqueue_scripts', 'mh_load_my_script' ); add_action('wp_head', 'event_timer_head'); add_filter('the_content', 'event_timer_content'); add_filter('the_title', 'event_timer_title'); ?&gt; </code></pre> <p>I want that <code>the_content</code> and <code>wp_head</code> only load if the page is active. If you need more information please tell me.</p> <p>Thanks.</p>
[ { "answer_id": 222610, "author": "Bruno Cantuaria", "author_id": 65717, "author_profile": "https://wordpress.stackexchange.com/users/65717", "pm_score": 1, "selected": true, "text": "<p>It's a common mistake about the difference of WordPress' Actions and Filters.</p>\n\n<ol>\n<li>Action is when you want something to happens besides the default.</li>\n<li>Filter is when you want something to happens instead the default.</li>\n</ol>\n\n<p>Knowing that, when you use an action, your output will be inserted in that action content. But when you use a filter, your output will replace that filter content.</p>\n\n<p>In the filter <code>the_content</code> you are replacing all the content from a post with your plugin content. So, the right way to fix it would be appending your content to the output, like <code>$content .= \"&lt;div&gt;...&lt;/div&gt;\";</code></p>\n" }, { "answer_id": 222613, "author": "dg4220", "author_id": 91201, "author_profile": "https://wordpress.stackexchange.com/users/91201", "pm_score": 1, "selected": false, "text": "<p>I think the easiest way to do this is to put call your action and filter hooks after checking the page</p>\n\n<pre><code>if ( is_page( 1 ) ) {\n add_action( 'wp_enqueue_scripts', 'mh_load_my_script' );\n add_action('wp_head', 'event_timer_head');\n add_filter('the_content', 'event_timer_content');\n add_filter('the_title', 'event_timer_title');\n}\n</code></pre>\n\n<p>Where 1 is the id of the page on which you want your timer.</p>\n\n<p>This does seems little over built for what you're trying to accomplish. I say this because your 'name' is wordpressbeginner, if you just want the timer on one page I would just paste the content of your $content variable in to a new post or page (make sure you select the 'text' tab of the editior rather than the 'Visual' tab) and your $title as the Title. Then <a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow\">register these scripts</a></p>\n\n<pre><code>&lt;link href='\". rtrim(get_settings('siteurl'), '/') .\"/wp-content/plugins/gw2eventtimer/style.css' rel='stylesheet' type='text/css' /&gt;\n&lt;script type='text/javascript' src='\". rtrim(get_settings('siteurl'), '/') .\"/wp-content/plugins/gw2eventtimer/js/js.js'&gt;&lt;/script&gt;\n&lt;script type='text/javascript' src='http://www.moongate.pl/event-timers/moment.min.js'&gt;&lt;/script&gt;\n</code></pre>\n\n<p>and <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow\">enqueue</a> them in this function with your jQuery</p>\n\n<pre><code>function mh_load_my_script() {\n wp_enqueue_script( 'jquery' );\n wp_enqueue_script( 'other-script' );\n wp_enqueue_script( 'other-script1' );\n}\n</code></pre>\n\n<p>Finally</p>\n\n<pre><code>if ( is_page( 1 ) ) {\n add_action( 'wp_enqueue_scripts', 'mh_load_my_script' );\n}\n</code></pre>\n" } ]
2016/04/04
[ "https://wordpress.stackexchange.com/questions/222608", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91744/" ]
I wrote my first Plugin and have one issue, the content of my Plugin is shown on every page. So if I want to open my gallery it shows my plugin content. **myplugin.php** ``` <?php /* * Plugin Name: Gw2 Event Timer * Plugin URI: http://localhost/wordpress * Description: T1Ein Guild Wars 2 Timer - beinhaltet alle Weltbosse und die neun HoT Gebiete * Version: 1.0 * Author: Niklas Grieger * Author URI: http://localhost/wordpress * License: No License */ $mm_plugin_basename = plugin_basename( __FILE__ ); function event_timer_head() { /** rtrim(get_settings('siteurl'), '/'): Gibt den Pfast .../wordpress zurück!!! **/ echo "<link href='". rtrim(get_settings('siteurl'), '/') ."/wp-content/plugins/gw2eventtimer/style.css' rel='stylesheet' type='text/css' /> <script type='text/javascript' src='". rtrim(get_settings('siteurl'), '/') ."/wp-content/plugins/gw2eventtimer/js/js.js'></script> <script type='text/javascript' src='http://www.moongate.pl/event-timers/moment.min.js'></script> "; } function event_timer_content($content) { $content="<div id='event-wrapper' class='event-wrapper'> <div class='event-limit'><span class='event-limit-text'>Nächste</span></div> <div class='event-pointer'><span class='event-pointer-time'>00:00 UTC</span></div> <div style='height:10px; width:100%;'></div> </div>"; return strtolower($content); } function event_timer_title($title) { $title = str_replace(' ', ' ', $title); return $title; } function mh_load_my_script() { wp_enqueue_script( 'jquery' ); } add_action( 'wp_enqueue_scripts', 'mh_load_my_script' ); add_action('wp_head', 'event_timer_head'); add_filter('the_content', 'event_timer_content'); add_filter('the_title', 'event_timer_title'); ?> ``` I want that `the_content` and `wp_head` only load if the page is active. If you need more information please tell me. Thanks.
It's a common mistake about the difference of WordPress' Actions and Filters. 1. Action is when you want something to happens besides the default. 2. Filter is when you want something to happens instead the default. Knowing that, when you use an action, your output will be inserted in that action content. But when you use a filter, your output will replace that filter content. In the filter `the_content` you are replacing all the content from a post with your plugin content. So, the right way to fix it would be appending your content to the output, like `$content .= "<div>...</div>";`
222,660
<p>all - </p> <p>I do not have the greatest CSS skills in the world, but I can normally figure things out. Right now I'm trying to implement a fairly simple media query in the child theme of my Wordpress site. I don't know if I typed something wrong or made another mistake, but the media query rules don't even show up when I inspect my page. Can anyone help?</p> <p>This is the page: <a href="http://www.thousandgirlsinitiative.org/" rel="nofollow">http://www.thousandgirlsinitiative.org/</a></p> <p>And these are the rules that I've tried to implement:</p> <pre><code>@media screen and (max-device-width: 479px) { .sow-slider-base ul.sow-slider-images li.sow-slider-image.sow-slider-image-cover { background-image:url ("http://www.thousandgirlsinitiative.org/wp-content/uploads/2016/04/Wendy-mobile.jpg") !important; } #why-sponsor-homepage { padding: 20px; } } </code></pre> <p>Basically I want to use a different hero image in the top row and decrease the padding on the "Why Sponsor?" row when the screen is narrower than 480px. </p> <p>I had written the query with "max-width" instead of "max-device-width" at first and it didn't work either, so that is not the problem.</p> <p>Any help would be very appreciated!</p>
[ { "answer_id": 222668, "author": "Emanuel Rocha Costa", "author_id": 75873, "author_profile": "https://wordpress.stackexchange.com/users/75873", "pm_score": 0, "selected": false, "text": "<p>The problem is due you having the styles associated to the element style property: </p>\n\n<pre><code>&lt;li class=\"sow-slider-image sow-slider-image-cover cycle-slide cycle-slide-active\" style=\"height: 700px; position: absolute; top: 0px; left: 0px; z-index: 99; opacity: 1; display: block; visibility: visible; background-image: url(&amp;quot;http://www.thousandgirlsinitiative.org/wp-content/uploads/2016/03/homepage-banner-1.jpg&amp;quot;); background-color: rgb(51, 51, 51);\"&gt;\n</code></pre>\n\n<p>Try move that style to a CSS class. Then you will be capable of switch the background image used.</p>\n" }, { "answer_id": 222695, "author": "Stephen", "author_id": 85776, "author_profile": "https://wordpress.stackexchange.com/users/85776", "pm_score": 2, "selected": true, "text": "<p>I think I may have the solution below :)</p>\n\n<p>Try adding this to your CSS file:</p>\n\n<pre><code>@media screen and (max-width: 479px) {\n .sow-slider-base ul.sow-slider-images li.sow-slider-image.sow-slider-image-cover {\n background-image: url('http://www.thousandgirlsinitiative.org/wp-content/uploads/2016/04/Wendy-mobile.jpg') !important;\n }\n #why-sponsor-homepage {\n padding: 20px;\n }\n}\n</code></pre>\n\n<p>All I have done here is removed the space between <code>url</code> and the link of the image and it seems to work like a charm when I added the CSS via Google Developer Tool.</p>\n" } ]
2016/04/04
[ "https://wordpress.stackexchange.com/questions/222660", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91768/" ]
all - I do not have the greatest CSS skills in the world, but I can normally figure things out. Right now I'm trying to implement a fairly simple media query in the child theme of my Wordpress site. I don't know if I typed something wrong or made another mistake, but the media query rules don't even show up when I inspect my page. Can anyone help? This is the page: <http://www.thousandgirlsinitiative.org/> And these are the rules that I've tried to implement: ``` @media screen and (max-device-width: 479px) { .sow-slider-base ul.sow-slider-images li.sow-slider-image.sow-slider-image-cover { background-image:url ("http://www.thousandgirlsinitiative.org/wp-content/uploads/2016/04/Wendy-mobile.jpg") !important; } #why-sponsor-homepage { padding: 20px; } } ``` Basically I want to use a different hero image in the top row and decrease the padding on the "Why Sponsor?" row when the screen is narrower than 480px. I had written the query with "max-width" instead of "max-device-width" at first and it didn't work either, so that is not the problem. Any help would be very appreciated!
I think I may have the solution below :) Try adding this to your CSS file: ``` @media screen and (max-width: 479px) { .sow-slider-base ul.sow-slider-images li.sow-slider-image.sow-slider-image-cover { background-image: url('http://www.thousandgirlsinitiative.org/wp-content/uploads/2016/04/Wendy-mobile.jpg') !important; } #why-sponsor-homepage { padding: 20px; } } ``` All I have done here is removed the space between `url` and the link of the image and it seems to work like a charm when I added the CSS via Google Developer Tool.
222,664
<p>I want to include the comments form on a page generated by my plugin. I got the post id I want to attach the comments to, but I can't get any of the Wordpress comments functions to work. </p> <p>Tried to create a Wordpress loop within my plugin page like this, but the comments form won´t show up: </p> <pre><code>$args = array ('post_type'=&gt; 'cpt', 'p' =&gt; $post_id ); $the_query = new WP_Query( $args ); if ( $the_query-&gt;have_posts() ) : while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); comment_form(); endwhile; endif; wp_reset_postdata(); </code></pre>
[ { "answer_id": 222690, "author": "Ray Flores", "author_id": 29355, "author_profile": "https://wordpress.stackexchange.com/users/29355", "pm_score": 2, "selected": true, "text": "<p>Just as @Jevuska mentioned, you can use the $post_id as an argument here, in fact, you can also use a ton of optional $args as well <code>&lt;?php comment_form( $args, $post_id ); ?&gt;</code></p>\n\n<p>You can find the information in the Codex here: <a href=\"https://codex.wordpress.org/Function_Reference/comment_form\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/comment_form</a></p>\n" }, { "answer_id": 222735, "author": "user33958", "author_id": 83020, "author_profile": "https://wordpress.stackexchange.com/users/83020", "pm_score": -1, "selected": false, "text": "<p>Thanks! Found the problem: \nI activated comments in settings, but there´s a checkbox for each post in the post edit screen. Without that activated, it won´t even throw an error. </p>\n" } ]
2016/04/04
[ "https://wordpress.stackexchange.com/questions/222664", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83020/" ]
I want to include the comments form on a page generated by my plugin. I got the post id I want to attach the comments to, but I can't get any of the Wordpress comments functions to work. Tried to create a Wordpress loop within my plugin page like this, but the comments form won´t show up: ``` $args = array ('post_type'=> 'cpt', 'p' => $post_id ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); comment_form(); endwhile; endif; wp_reset_postdata(); ```
Just as @Jevuska mentioned, you can use the $post\_id as an argument here, in fact, you can also use a ton of optional $args as well `<?php comment_form( $args, $post_id ); ?>` You can find the information in the Codex here: <https://codex.wordpress.org/Function_Reference/comment_form>
222,712
<p>My template works fine, however, its using my main header file, even though I have changed it to point to <code>sub-header.php</code> </p> <pre><code>&lt;?php /* Template Name: Sub Page */ get_header('sub-header'); ?&gt; </code></pre>
[ { "answer_id": 222713, "author": "Mehul Gohil", "author_id": 37768, "author_profile": "https://wordpress.stackexchange.com/users/37768", "pm_score": 1, "selected": true, "text": "<p>You are following a wrong format to call sub header file.</p>\n\n<p><strong>Here is how we have to call sub header files:</strong></p>\n\n<pre><code>&lt;?php get_header('subexample'); ?&gt;\n</code></pre>\n\n<p><strong>Here is how you have to name the sub header file:</strong></p>\n\n<p><code>header-subexample.php</code></p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 222714, "author": "Arunendra", "author_id": 80228, "author_profile": "https://wordpress.stackexchange.com/users/80228", "pm_score": 0, "selected": false, "text": "<p>You need to change you header file name</p>\n\n<p>From <code>sub-header.php</code> to <code>header-sub.php</code> and call it by using following code:</p>\n\n<pre><code>&lt;?php /* Template Name: Sub Page */ \nget_header('sub'); ?&gt;\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\">For more detail see here.</a></p>\n" }, { "answer_id": 222715, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 0, "selected": false, "text": "<p>When using the <code>get_header()</code> function, all you need to do is name the file as like</p>\n\n<p><code>header-sub-header.php</code> or <code>header-content.php</code>.</p>\n\n<p>When you are using the <code>get_header()</code> function you would call the your custom headers like this:</p>\n\n<pre><code>get_header( \"sub-header\" )\n//OR\nget_header ( \"content\" )\n</code></pre>\n" }, { "answer_id": 222716, "author": "claudios", "author_id": 91800, "author_profile": "https://wordpress.stackexchange.com/users/91800", "pm_score": 1, "selected": false, "text": "<p>You only need to pass the slug to get_header() function;\n for example, to call header-sample.php:</p>\n\n<pre><code>&lt;?php get_header( 'sample' ); ?&gt;\n</code></pre>\n" } ]
2016/04/05
[ "https://wordpress.stackexchange.com/questions/222712", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91799/" ]
My template works fine, however, its using my main header file, even though I have changed it to point to `sub-header.php` ``` <?php /* Template Name: Sub Page */ get_header('sub-header'); ?> ```
You are following a wrong format to call sub header file. **Here is how we have to call sub header files:** ``` <?php get_header('subexample'); ?> ``` **Here is how you have to name the sub header file:** `header-subexample.php` Hope this helps!
222,730
<p>I'm having an issue with the order WordPress is loading page templates and <code>functions.php</code>.</p> <p>I have <code>front-page.php</code> which has <code>$_POST['sort-by']</code> allowing users to sort posts using a drop-down menu.</p> <p>It's simple enough and works just fine. Now comes the part where I have the ability to "Load more posts" which uses <code>wp_ajax</code> and <code>wp_ajax_nopriv</code> and a function in <code>functions.php</code> to grab the additional posts with an offset of the number of posts shown by default. My AJAX query works just fine, but I'm unable to grab the <code>$_POST</code> data from the <code>front-page.php</code> template within' <code>functions.php</code> to properly sort the posts fetched by the AJAX.</p> <p>I thought it'd be as simple as just including my same <code>$_POST</code> values within' <code>functions.php</code> so it would use the proper sorting+meta_key, but no matter what I do including attempting to assign a separate variable to <code>$GLOBALS</code> containing the <code>$_POST</code>, I can not for the life of me get it to get the values set in <code>front-page.php</code> in <code>functions.php</code> so it will sort it properly when calling <code>wp_ajax</code> and <code>wp_ajax_nopriv</code>.</p> <p>I'm assuming this has to do with <code>functions.php</code> being loaded BEFORE <code>front-page.php</code> within' WordPress. I'm not sure if there's an <code>add_action();</code> of some kind that would allow me to fix my issue here or how I should go about getting it to work as intended. I know it has to be possible though.</p> <p>EDIT: Here is the function I'm trying to get <code>$_POST</code> data for from my page template <code>frontpage.php</code></p>
[ { "answer_id": 222713, "author": "Mehul Gohil", "author_id": 37768, "author_profile": "https://wordpress.stackexchange.com/users/37768", "pm_score": 1, "selected": true, "text": "<p>You are following a wrong format to call sub header file.</p>\n\n<p><strong>Here is how we have to call sub header files:</strong></p>\n\n<pre><code>&lt;?php get_header('subexample'); ?&gt;\n</code></pre>\n\n<p><strong>Here is how you have to name the sub header file:</strong></p>\n\n<p><code>header-subexample.php</code></p>\n\n<p>Hope this helps!</p>\n" }, { "answer_id": 222714, "author": "Arunendra", "author_id": 80228, "author_profile": "https://wordpress.stackexchange.com/users/80228", "pm_score": 0, "selected": false, "text": "<p>You need to change you header file name</p>\n\n<p>From <code>sub-header.php</code> to <code>header-sub.php</code> and call it by using following code:</p>\n\n<pre><code>&lt;?php /* Template Name: Sub Page */ \nget_header('sub'); ?&gt;\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_header\" rel=\"nofollow\">For more detail see here.</a></p>\n" }, { "answer_id": 222715, "author": "Aishan", "author_id": 89530, "author_profile": "https://wordpress.stackexchange.com/users/89530", "pm_score": 0, "selected": false, "text": "<p>When using the <code>get_header()</code> function, all you need to do is name the file as like</p>\n\n<p><code>header-sub-header.php</code> or <code>header-content.php</code>.</p>\n\n<p>When you are using the <code>get_header()</code> function you would call the your custom headers like this:</p>\n\n<pre><code>get_header( \"sub-header\" )\n//OR\nget_header ( \"content\" )\n</code></pre>\n" }, { "answer_id": 222716, "author": "claudios", "author_id": 91800, "author_profile": "https://wordpress.stackexchange.com/users/91800", "pm_score": 1, "selected": false, "text": "<p>You only need to pass the slug to get_header() function;\n for example, to call header-sample.php:</p>\n\n<pre><code>&lt;?php get_header( 'sample' ); ?&gt;\n</code></pre>\n" } ]
2016/04/05
[ "https://wordpress.stackexchange.com/questions/222730", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91806/" ]
I'm having an issue with the order WordPress is loading page templates and `functions.php`. I have `front-page.php` which has `$_POST['sort-by']` allowing users to sort posts using a drop-down menu. It's simple enough and works just fine. Now comes the part where I have the ability to "Load more posts" which uses `wp_ajax` and `wp_ajax_nopriv` and a function in `functions.php` to grab the additional posts with an offset of the number of posts shown by default. My AJAX query works just fine, but I'm unable to grab the `$_POST` data from the `front-page.php` template within' `functions.php` to properly sort the posts fetched by the AJAX. I thought it'd be as simple as just including my same `$_POST` values within' `functions.php` so it would use the proper sorting+meta\_key, but no matter what I do including attempting to assign a separate variable to `$GLOBALS` containing the `$_POST`, I can not for the life of me get it to get the values set in `front-page.php` in `functions.php` so it will sort it properly when calling `wp_ajax` and `wp_ajax_nopriv`. I'm assuming this has to do with `functions.php` being loaded BEFORE `front-page.php` within' WordPress. I'm not sure if there's an `add_action();` of some kind that would allow me to fix my issue here or how I should go about getting it to work as intended. I know it has to be possible though. EDIT: Here is the function I'm trying to get `$_POST` data for from my page template `frontpage.php`
You are following a wrong format to call sub header file. **Here is how we have to call sub header files:** ``` <?php get_header('subexample'); ?> ``` **Here is how you have to name the sub header file:** `header-subexample.php` Hope this helps!
222,742
<p>I am setting up an events page for my website. This page is using a loop to display a list of acts performing at different venues month-by-month. When a viewer comes to the page, they use a simple form to select the month, and when submitted this return the relevant data. At the moment the data fields I am displaying for each individual act in the loop are as follows:</p> <ol> <li>Event date (Advanced custom fields data picker)</li> <li>Venue (Advanced custom fields text field)</li> <li>Image of act (Advanced custom fields Image field)</li> <li>Act Name (Advanced custom fields text field)</li> <li>Description (Advanced custom fields text area field)</li> </ol> <p>You can view how this is working <a href="http://hru.websiteprime.co.uk/events/" rel="nofollow noreferrer">here</a></p> <p>I need to change the layout so that when the list of events are returned it looks like this:<a href="https://i.stack.imgur.com/NbdEg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NbdEg.jpg" alt="enter image description here"></a></p> <p>So essentially I need the loop to pump out rows for each day of the month and if there is an act at a venue on the date, to include it in the row. if there is no act on the date then i can just be left blank( as illustrated above)</p> <p>Thank you for your help in advance, and if you would like any further information, I will answer as best I can.</p>
[ { "answer_id": 222750, "author": "Charles Jaimet", "author_id": 43741, "author_profile": "https://wordpress.stackexchange.com/users/43741", "pm_score": 1, "selected": false, "text": "<p>Your best bet is not to run a bunch of queries but to loop through your data once to organize it then a second time to display it. Below is the logic you need. The exact code will depend on your data set.</p>\n\n<pre><code>$events = array();\n$posts = WP_Query( $args );\nforeach ( $posts as $post ) { \n $venue = $post-&gt;venue;\n $day_of_month = date( 'd', $post-&gt;date );\n $events[ $venue ][ $day_of_month ][] = $post;\n}\nfor ( $x = 1; $x &lt;= 31; $x ++ ) {\n foreach ( $events as $venue =&gt; $ev ) {\n if ( ! empty( $ev[ $x ] ) {\n echo '&lt;td&gt;';\n foreach ( $ev[ $x ] as $details ) {\n echo $details;\n }\n echo '&lt;/td&gt;';\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 222759, "author": "dg4220", "author_id": 91201, "author_profile": "https://wordpress.stackexchange.com/users/91201", "pm_score": 0, "selected": false, "text": "<p>I would try it this way. Use a meta query to get your events list and load everything into a <a href=\"https://datatables.net/\" rel=\"nofollow\">datatable</a>. This seems like a perfect time to let visitiors filter and sort.</p>\n\n<p>Here's a simple implementtation (which may need tweaking). Just print or return the '$disp_data' variable from function call or in a template. If you don't have datatable set up I can help you out. Otherwise you just update the html below and use the query</p>\n\n<pre><code> $disp_data = '&lt;div class=\"data-display\"&gt;&lt;script&gt;\n jQuery(document).ready(function() {\n jQuery(\"#my-events-table\").dataTable( {\n\n columnDefs: [ {\n targets: [ 0 ],\n orderData: [ 0, 1 ]\n }, {\n targets: [ 1 ],\n orderData: [ 1, 0 ]\n }, {\n targets: [ 3 ],\n orderData: [ 3, 0 ]\n } ]\n } );\n\n } );\n &lt;/SCRIPT&gt;\n &lt;TABLE id=\"my-events-table\" class=\"display\" cellspacing=\"0\" &gt;&lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt;Date&lt;/th&gt;\n &lt;th&gt;Venue&lt;/th&gt;\n &lt;th&gt;Venue&lt;/th&gt;\n &lt;th&gt;Venue&lt;/th&gt;\n\n\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;TBODY&gt;';\n\n\n $args = array(\n 'post_type' =&gt; 'my-event-type',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'meta_value',\n 'order' =&gt; 'ASC',\n 'meta_key' =&gt; 'acf-field',//custom field name holding event date\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; '_my-datetime-from',\n 'value' =&gt; array($start, $end),\n 'compare' =&gt; 'BETWEEN',\n 'type' =&gt; 'DATE'\n )\n )\n );\n $posts = new WP_Query( $args );\n\n\n foreach ( $posts as $post ) { \n\n /*get you acf values here and load in to a table row*/\n\n $disp_data .= '&lt;tr&gt;\n &lt;td&gt;' . $cur_property . '&lt;/td&gt;\n &lt;td&gt;' . $venue . '&lt;/td&gt;\n &lt;td&gt;' . $venue . '&lt;/td&gt;\n &lt;td&gt;' . $venue . '&lt;/td&gt;\n\n\n &lt;/tr&gt;';\n\n }\n wp_reset_postdata();\n $disp_data .= '&lt;/tbody&gt;&lt;/table&gt;&lt;/div&gt;';\n</code></pre>\n" } ]
2016/04/05
[ "https://wordpress.stackexchange.com/questions/222742", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91798/" ]
I am setting up an events page for my website. This page is using a loop to display a list of acts performing at different venues month-by-month. When a viewer comes to the page, they use a simple form to select the month, and when submitted this return the relevant data. At the moment the data fields I am displaying for each individual act in the loop are as follows: 1. Event date (Advanced custom fields data picker) 2. Venue (Advanced custom fields text field) 3. Image of act (Advanced custom fields Image field) 4. Act Name (Advanced custom fields text field) 5. Description (Advanced custom fields text area field) You can view how this is working [here](http://hru.websiteprime.co.uk/events/) I need to change the layout so that when the list of events are returned it looks like this:[![enter image description here](https://i.stack.imgur.com/NbdEg.jpg)](https://i.stack.imgur.com/NbdEg.jpg) So essentially I need the loop to pump out rows for each day of the month and if there is an act at a venue on the date, to include it in the row. if there is no act on the date then i can just be left blank( as illustrated above) Thank you for your help in advance, and if you would like any further information, I will answer as best I can.
Your best bet is not to run a bunch of queries but to loop through your data once to organize it then a second time to display it. Below is the logic you need. The exact code will depend on your data set. ``` $events = array(); $posts = WP_Query( $args ); foreach ( $posts as $post ) { $venue = $post->venue; $day_of_month = date( 'd', $post->date ); $events[ $venue ][ $day_of_month ][] = $post; } for ( $x = 1; $x <= 31; $x ++ ) { foreach ( $events as $venue => $ev ) { if ( ! empty( $ev[ $x ] ) { echo '<td>'; foreach ( $ev[ $x ] as $details ) { echo $details; } echo '</td>'; } } } ```
222,763
<p>Are there any disadvantages to using the following code to setup WP_HOME and WP_SITEURL in wp.config for both singlesite installs and multisite installs:</p> <pre><code>/** * Site Host URLs */ $hostname = $_SERVER['HTTP_HOST']; if(isset($_SERVER['HTTP_X_FORWARDED_HOST']) &amp;&amp; !empty($_SERVER['HTTP_X_FORWARDED_HOST'])) { $hostname = $_SERVER['HTTP_X_FORWARDED_HOST']; } $protocol = isset($_SERVER['HTTPS']) &amp;&amp; ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &amp;&amp; $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ? 'https://' : 'http://'; $siteUrl = $protocol . rtrim($hostname, '/'); define('WP_HOME', $siteUrl); define('WP_SITEURL', $siteUrl); </code></pre> <p>I know I do not have much of a reputation to offer as a bounty but your answer will get my 100% appreciation.</p>
[ { "answer_id": 222766, "author": "Marttin Notta", "author_id": 91525, "author_profile": "https://wordpress.stackexchange.com/users/91525", "pm_score": 0, "selected": false, "text": "<p>As far as i can see (2 years wordpress/woocommerce) i have always used WP_HOME and WP_SITEURL. Makes it very easy to move site from one domain to another, never had any issues with it even when moving ecommerce shops. You might want to go to admin panel and save permalinks there so they would be updated in DB, but usually it is not necessary. </p>\n\n<p><strong>NB!</strong> It won't update any kind links (a, img src etc) that have been saved to database. For ex if you have a blog on domain domainA.com where you have inserted images through WYSIWYG editor and now you move to domainB.com then all images in your blog content will still try to load from domainA.com. This is because WYSIWYG saves full length links even when they are from your own domain to database. If you have such content then you will have to perform search and replace against that database.</p>\n\n<p>Currently no more issues are coming to my head, but if i remember something i will update this post.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Like Mark already mentioned there is a security risk when trusting </p>\n\n<pre><code>$_SERVER['HTTP_X_FORWARDED_HOST']\n</code></pre>\n\n<p>because user can easily set that header himself.</p>\n" }, { "answer_id": 222768, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": true, "text": "<p>The obvious problem is that you are trusting user input (http headers) which makes your code suspicious from security POV.</p>\n\n<p>Other then that, no real problems with it, but my experience is that such hacks have a tendency to just move whatever problem you are trying to solve this way to another place.</p>\n" }, { "answer_id": 222775, "author": "incredimike", "author_id": 87334, "author_profile": "https://wordpress.stackexchange.com/users/87334", "pm_score": 2, "selected": false, "text": "<p>I've used a similar approach on many CMS projects throughout the years. It works really well for rapid development, but it does have issues.</p>\n\n<p>If you can trust that the web server (apache, nginx) are configured correctly, you could use <code>$_SERVER['SERVER_NAME']</code> to retrieve the hostname as configured by the webserver.\n(Reference: <a href=\"https://stackoverflow.com/questions/2297403/http-host-vs-server-name\">https://stackoverflow.com/questions/2297403/http-host-vs-server-name</a>)</p>\n\n<p>That said, HTTP_HOST is certainly more flexible!</p>\n\n<p>If I don't have control over server configs, I'll generally specify a set of \"allowed\" hosts that can be set, and a sensible default. For example:</p>\n\n<pre><code>/**\n* Site Host URLs\n*/\n\n$hostname = $_SERVER['HTTP_HOST'];\nif(!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {\n $hostname = $_SERVER['HTTP_X_FORWARDED_HOST'];\n}\n\n$hostname = rtrim($hostname, '/');\n\n$allowed = ['www.foo.com', 'dev.foo.com', 'staging.foo.com'];\n\nif (!in_array($hostname, $allowed)) {\n $hostname = 'www.foo.com';\n}\n\n$protocol = (!empty($_SERVER['HTTPS']) || !empty($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))\n ? 'https://'\n : 'http://';\n\n$siteUrl = $protocol . $hostname;\n\ndefine('WP_HOME', $siteUrl);\ndefine('WP_SITEURL', $siteUrl);\n</code></pre>\n" } ]
2016/04/05
[ "https://wordpress.stackexchange.com/questions/222763", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91822/" ]
Are there any disadvantages to using the following code to setup WP\_HOME and WP\_SITEURL in wp.config for both singlesite installs and multisite installs: ``` /** * Site Host URLs */ $hostname = $_SERVER['HTTP_HOST']; if(isset($_SERVER['HTTP_X_FORWARDED_HOST']) && !empty($_SERVER['HTTP_X_FORWARDED_HOST'])) { $hostname = $_SERVER['HTTP_X_FORWARDED_HOST']; } $protocol = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ? 'https://' : 'http://'; $siteUrl = $protocol . rtrim($hostname, '/'); define('WP_HOME', $siteUrl); define('WP_SITEURL', $siteUrl); ``` I know I do not have much of a reputation to offer as a bounty but your answer will get my 100% appreciation.
The obvious problem is that you are trusting user input (http headers) which makes your code suspicious from security POV. Other then that, no real problems with it, but my experience is that such hacks have a tendency to just move whatever problem you are trying to solve this way to another place.
222,797
<p>Good evening everyone.</p> <p>I have three Custom Post Types and i want to remove the parent slugs from them.</p> <pre><code>$args = array( 'rewrite' =&gt; array('slug' =&gt; '/','with_front' =&gt; true), ); </code></pre> <p><code>functions.php</code></p> <pre><code>function wpse_101072_flatten_hierarchies( $post_link, $post ) { if ( 'CPT1' != $post-&gt;post_type ) return $post_link; $uri = ''; foreach ( $post-&gt;ancestors as $parent ) { $uri = get_post( $parent )-&gt;post_name . "/" . $uri; } return str_replace( $uri, '', $post_link ); } add_filter( 'post_type_link', 'wpse_101072_flatten_hierarchies', 10, 2 ); </code></pre> <p>In this point i wonder how can use the function wpse_101072_flatten_hierarchies and add inside the cases of the other 2 CPT.</p>
[ { "answer_id": 222766, "author": "Marttin Notta", "author_id": 91525, "author_profile": "https://wordpress.stackexchange.com/users/91525", "pm_score": 0, "selected": false, "text": "<p>As far as i can see (2 years wordpress/woocommerce) i have always used WP_HOME and WP_SITEURL. Makes it very easy to move site from one domain to another, never had any issues with it even when moving ecommerce shops. You might want to go to admin panel and save permalinks there so they would be updated in DB, but usually it is not necessary. </p>\n\n<p><strong>NB!</strong> It won't update any kind links (a, img src etc) that have been saved to database. For ex if you have a blog on domain domainA.com where you have inserted images through WYSIWYG editor and now you move to domainB.com then all images in your blog content will still try to load from domainA.com. This is because WYSIWYG saves full length links even when they are from your own domain to database. If you have such content then you will have to perform search and replace against that database.</p>\n\n<p>Currently no more issues are coming to my head, but if i remember something i will update this post.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Like Mark already mentioned there is a security risk when trusting </p>\n\n<pre><code>$_SERVER['HTTP_X_FORWARDED_HOST']\n</code></pre>\n\n<p>because user can easily set that header himself.</p>\n" }, { "answer_id": 222768, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": true, "text": "<p>The obvious problem is that you are trusting user input (http headers) which makes your code suspicious from security POV.</p>\n\n<p>Other then that, no real problems with it, but my experience is that such hacks have a tendency to just move whatever problem you are trying to solve this way to another place.</p>\n" }, { "answer_id": 222775, "author": "incredimike", "author_id": 87334, "author_profile": "https://wordpress.stackexchange.com/users/87334", "pm_score": 2, "selected": false, "text": "<p>I've used a similar approach on many CMS projects throughout the years. It works really well for rapid development, but it does have issues.</p>\n\n<p>If you can trust that the web server (apache, nginx) are configured correctly, you could use <code>$_SERVER['SERVER_NAME']</code> to retrieve the hostname as configured by the webserver.\n(Reference: <a href=\"https://stackoverflow.com/questions/2297403/http-host-vs-server-name\">https://stackoverflow.com/questions/2297403/http-host-vs-server-name</a>)</p>\n\n<p>That said, HTTP_HOST is certainly more flexible!</p>\n\n<p>If I don't have control over server configs, I'll generally specify a set of \"allowed\" hosts that can be set, and a sensible default. For example:</p>\n\n<pre><code>/**\n* Site Host URLs\n*/\n\n$hostname = $_SERVER['HTTP_HOST'];\nif(!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {\n $hostname = $_SERVER['HTTP_X_FORWARDED_HOST'];\n}\n\n$hostname = rtrim($hostname, '/');\n\n$allowed = ['www.foo.com', 'dev.foo.com', 'staging.foo.com'];\n\nif (!in_array($hostname, $allowed)) {\n $hostname = 'www.foo.com';\n}\n\n$protocol = (!empty($_SERVER['HTTPS']) || !empty($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))\n ? 'https://'\n : 'http://';\n\n$siteUrl = $protocol . $hostname;\n\ndefine('WP_HOME', $siteUrl);\ndefine('WP_SITEURL', $siteUrl);\n</code></pre>\n" } ]
2016/04/05
[ "https://wordpress.stackexchange.com/questions/222797", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
Good evening everyone. I have three Custom Post Types and i want to remove the parent slugs from them. ``` $args = array( 'rewrite' => array('slug' => '/','with_front' => true), ); ``` `functions.php` ``` function wpse_101072_flatten_hierarchies( $post_link, $post ) { if ( 'CPT1' != $post->post_type ) return $post_link; $uri = ''; foreach ( $post->ancestors as $parent ) { $uri = get_post( $parent )->post_name . "/" . $uri; } return str_replace( $uri, '', $post_link ); } add_filter( 'post_type_link', 'wpse_101072_flatten_hierarchies', 10, 2 ); ``` In this point i wonder how can use the function wpse\_101072\_flatten\_hierarchies and add inside the cases of the other 2 CPT.
The obvious problem is that you are trusting user input (http headers) which makes your code suspicious from security POV. Other then that, no real problems with it, but my experience is that such hacks have a tendency to just move whatever problem you are trying to solve this way to another place.
222,799
<p>I have built a site using WooCommerce Bookings with an AJAX request that processes the payment, creates and order and lastly creates a booking with the order ID. However, when I send the newly created order ID via the WooCommerce Bookings create method the order doesn't appear in the Booking and I have to manually connect them.</p> <pre><code>$order = wc_create_order(); $product = wc_get_product($productId); $price = $product-&gt;get_price(); $order-&gt;add_product( $product, 1 ); $order-&gt;set_total( $price ); update_post_meta($order-&gt;id, '_customer_user', get_current_user_id() ); $order-&gt;update_status( 'completed' ); $new_booking_data = array( 'product_id' =&gt; $productId, 'start_date' =&gt; strtotime($startStr), 'end_date' =&gt; strtotime($endStr), 'user_id' =&gt; $user_ID, 'order_item_id' =&gt; $order-&gt;id, // Seems to be an issue here. 'persons' =&gt; $amountOfPeople, 'cost' =&gt; $orderTotal, 'all_day' =&gt; false, ); $returnVal = create_wc_booking( $productId, $new_booking_data, 'pending-confirmation', true ); </code></pre> <p>I know that the $order->id is valid because I'm able to use it in order to set the customer ID.</p> <p>Bookings Plugin Reference: (<a href="https://docs.woothemes.com/document/creating-bookings-programatically/" rel="nofollow">https://docs.woothemes.com/document/creating-bookings-programatically/</a>)</p>
[ { "answer_id": 222766, "author": "Marttin Notta", "author_id": 91525, "author_profile": "https://wordpress.stackexchange.com/users/91525", "pm_score": 0, "selected": false, "text": "<p>As far as i can see (2 years wordpress/woocommerce) i have always used WP_HOME and WP_SITEURL. Makes it very easy to move site from one domain to another, never had any issues with it even when moving ecommerce shops. You might want to go to admin panel and save permalinks there so they would be updated in DB, but usually it is not necessary. </p>\n\n<p><strong>NB!</strong> It won't update any kind links (a, img src etc) that have been saved to database. For ex if you have a blog on domain domainA.com where you have inserted images through WYSIWYG editor and now you move to domainB.com then all images in your blog content will still try to load from domainA.com. This is because WYSIWYG saves full length links even when they are from your own domain to database. If you have such content then you will have to perform search and replace against that database.</p>\n\n<p>Currently no more issues are coming to my head, but if i remember something i will update this post.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Like Mark already mentioned there is a security risk when trusting </p>\n\n<pre><code>$_SERVER['HTTP_X_FORWARDED_HOST']\n</code></pre>\n\n<p>because user can easily set that header himself.</p>\n" }, { "answer_id": 222768, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": true, "text": "<p>The obvious problem is that you are trusting user input (http headers) which makes your code suspicious from security POV.</p>\n\n<p>Other then that, no real problems with it, but my experience is that such hacks have a tendency to just move whatever problem you are trying to solve this way to another place.</p>\n" }, { "answer_id": 222775, "author": "incredimike", "author_id": 87334, "author_profile": "https://wordpress.stackexchange.com/users/87334", "pm_score": 2, "selected": false, "text": "<p>I've used a similar approach on many CMS projects throughout the years. It works really well for rapid development, but it does have issues.</p>\n\n<p>If you can trust that the web server (apache, nginx) are configured correctly, you could use <code>$_SERVER['SERVER_NAME']</code> to retrieve the hostname as configured by the webserver.\n(Reference: <a href=\"https://stackoverflow.com/questions/2297403/http-host-vs-server-name\">https://stackoverflow.com/questions/2297403/http-host-vs-server-name</a>)</p>\n\n<p>That said, HTTP_HOST is certainly more flexible!</p>\n\n<p>If I don't have control over server configs, I'll generally specify a set of \"allowed\" hosts that can be set, and a sensible default. For example:</p>\n\n<pre><code>/**\n* Site Host URLs\n*/\n\n$hostname = $_SERVER['HTTP_HOST'];\nif(!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {\n $hostname = $_SERVER['HTTP_X_FORWARDED_HOST'];\n}\n\n$hostname = rtrim($hostname, '/');\n\n$allowed = ['www.foo.com', 'dev.foo.com', 'staging.foo.com'];\n\nif (!in_array($hostname, $allowed)) {\n $hostname = 'www.foo.com';\n}\n\n$protocol = (!empty($_SERVER['HTTPS']) || !empty($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))\n ? 'https://'\n : 'http://';\n\n$siteUrl = $protocol . $hostname;\n\ndefine('WP_HOME', $siteUrl);\ndefine('WP_SITEURL', $siteUrl);\n</code></pre>\n" } ]
2016/04/05
[ "https://wordpress.stackexchange.com/questions/222799", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16020/" ]
I have built a site using WooCommerce Bookings with an AJAX request that processes the payment, creates and order and lastly creates a booking with the order ID. However, when I send the newly created order ID via the WooCommerce Bookings create method the order doesn't appear in the Booking and I have to manually connect them. ``` $order = wc_create_order(); $product = wc_get_product($productId); $price = $product->get_price(); $order->add_product( $product, 1 ); $order->set_total( $price ); update_post_meta($order->id, '_customer_user', get_current_user_id() ); $order->update_status( 'completed' ); $new_booking_data = array( 'product_id' => $productId, 'start_date' => strtotime($startStr), 'end_date' => strtotime($endStr), 'user_id' => $user_ID, 'order_item_id' => $order->id, // Seems to be an issue here. 'persons' => $amountOfPeople, 'cost' => $orderTotal, 'all_day' => false, ); $returnVal = create_wc_booking( $productId, $new_booking_data, 'pending-confirmation', true ); ``` I know that the $order->id is valid because I'm able to use it in order to set the customer ID. Bookings Plugin Reference: (<https://docs.woothemes.com/document/creating-bookings-programatically/>)
The obvious problem is that you are trusting user input (http headers) which makes your code suspicious from security POV. Other then that, no real problems with it, but my experience is that such hacks have a tendency to just move whatever problem you are trying to solve this way to another place.
222,857
<p>In a question that is related to, but not the same as, <a href="https://wordpress.stackexchange.com/questions/5144/how-to-link-to-images-in-my-plugin-regardless-of-the-plugin-folders-name/">How to link to images in my plugin regardless of the plugin folder&#39;s name</a></p> <ul> <li><code>plugin-folder/plugin-main-file.php</code></li> <li><code>plugin-folder/images/</code> containing all images</li> <li><code>plugin-folder/classes/</code> containing class definitions</li> <li><code>plugin-folder/classes/class1-files</code> containing additional files for class 1</li> <li><code>plugin-folder/classes/class2-files</code> containing additional files for class 2</li> <li>etc</li> </ul> <p>To access images, I can use relative addressing, such as <code>plugins_url( '../images/image.png', dirname( __FILE__ ) )</code> but this requires a knowledge of the file structure, and a level of hard-coding that leads to potential maintenance issues.</p> <p>Alternatively, I can define a global constant (eg) <code>define('PLUGIN_ROOT', basename(dirname(__FILE__)) . '/' . basename(__FILE__));</code> in my main-file.</p> <p>Ideally, there is a Wordpress function that would give me the plugin base name, from anywhere in my plugin (ie always return <code>/plugin-folder/</code>)... but I haven't found one. Is there such a beastie?</p> <p>-- EDIT TO ADD --</p> <p>I am also aware of <code>plugins_url()</code> with no parameters... but this returns <code>http://mydomain.ext/wp-content/plugins</code> - ie without my plugin name!</p>
[ { "answer_id": 222859, "author": "Elektra", "author_id": 91391, "author_profile": "https://wordpress.stackexchange.com/users/91391", "pm_score": 0, "selected": false, "text": "<p><strong>Edit</strong></p>\n\n<p>My bad, in that case I can think of this. </p>\n\n<pre><code>$x = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),\"\",plugin_basename(__FILE__));\n</code></pre>\n\n<p>It should return </p>\n\n<p><a href=\"http://[url-path-to-plugins]/[custom-plugin]/\" rel=\"nofollow\">http://[url-path-to-plugins]/[custom-plugin]/</a> </p>\n\n<p>But straight forward class I don't think wordpress has one </p>\n\n<hr>\n\n<p>Yes it is </p>\n\n<p>from <a href=\"https://codex.wordpress.org/Function_Reference/plugin_basename\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/plugin_basename</a></p>\n\n<pre><code>$x = plugin_basename( __FILE__ );\n</code></pre>\n" }, { "answer_id": 222860, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>I think you are looking for <a href=\"https://codex.wordpress.org/Function_Reference/plugin_dir_url\" rel=\"nofollow\">plugin_dir_url</a>:</p>\n\n<pre><code>$url = plugin_dir_url(__FILE__);\n\n$imageurl = $url.'images/someimage.png';\n</code></pre>\n\n<p><strong>EDIT</strong>: Sorry I misread the question... that is only an answer to the linked question. You could check the parent directory recursively until you find the right one:</p>\n\n<pre><code>function base_plugin_dir($dirpath) {\n if (substr(dirname($dir),-7) == 'plugins') {return $dirpath;}\n else {$dirpath = base_plugin_dir($dirpath);}\n return $dirpath;\n}\n\nfunction base_plugin_dir_url($filepath) {\n $baseplugindir = base_plugin_dir(dirname($filepath));\n $url = plugin_dir_url(trailingslashit($baseplugindir));\n return $url;\n}\n</code></pre>\n\n<p>Then you can get the URL using that function from whatever file:</p>\n\n<pre><code>$basepluginurl = base_plugin_dir_url(__FILE__);\n$imageurl = $basepluginurl.'/images/wordpress.png';\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<p>Better yet just set a constant from your main plugin file to use it later:</p>\n\n<pre><code>$url = plugin_dir_url(__FILE__);\ndefine('MY_UNIQUE_PLUGIN_URL',$url);\n</code></pre>\n\n<p>So as to use in say <code>/plugin/my-plugin/class/class1.php</code></p>\n\n<pre><code>$imageurl = MY_UNIQUE_PLUGIN_URL.'/images/wordpress.png';\n</code></pre>\n" }, { "answer_id": 222868, "author": "Kevinleary.net", "author_id": 1495, "author_profile": "https://wordpress.stackexchange.com/users/1495", "pm_score": 0, "selected": false, "text": "<p><code>plugin_basename</code> may be what you want. If your plugin file is located at <code>/wp-content/plugins/my-plugin/my-plugin.php</code> this would return:</p>\n\n<pre><code>$file = plugin_basename( __FILE__ ); // \"my-plugin/my-plugin.php\"\n</code></pre>\n\n<p>If you called the same thing from a sub-directory in your plugin, such as <code>/wp-content/plugins/my-plugin/inc/my-plugin-include.php</code> it would return:</p>\n\n<pre><code>my-plugin/inc/my-plugin-include.php\n</code></pre>\n\n<p>If you want the current root directory for a plugin, then this custom function should do the trick:</p>\n\n<pre><code>/**\n * Current Plugin Directory \n * \n * Returns the root directory for current plugin\n */\nfunction current_plugin_dir() {\n $basename = plugin_basename( __FILE__ );\n\n return str_replace( __FILE__, '', $basename );\n}\n</code></pre>\n" }, { "answer_id": 380652, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 1, "selected": false, "text": "<p>Sorry for the late answer, below is the function I use to retrieve the plugin directory name in the format requested by @Andrew (i.e. with a trailing slash as mentioned in the comment to Kevin)</p>\n<pre><code>/**\n * Retrieve the Plugin Directory \n * \n * Returns the root directory for current plugin with a trailing slash\n */\nfunction current_plugin_dir() {\n $base = plugin_basename( __FILE__ );\n $slash = strpos($base,'/');\n $plugin_dir = $loc? substr( $base, 0, $loc + 1): $base;\n return $plugin_dir;\n}\n</code></pre>\n<p>To remove the slash just leave out the '+ 1' in the $plugin_dir line.</p>\n" } ]
2016/04/06
[ "https://wordpress.stackexchange.com/questions/222857", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/19707/" ]
In a question that is related to, but not the same as, [How to link to images in my plugin regardless of the plugin folder's name](https://wordpress.stackexchange.com/questions/5144/how-to-link-to-images-in-my-plugin-regardless-of-the-plugin-folders-name/) * `plugin-folder/plugin-main-file.php` * `plugin-folder/images/` containing all images * `plugin-folder/classes/` containing class definitions * `plugin-folder/classes/class1-files` containing additional files for class 1 * `plugin-folder/classes/class2-files` containing additional files for class 2 * etc To access images, I can use relative addressing, such as `plugins_url( '../images/image.png', dirname( __FILE__ ) )` but this requires a knowledge of the file structure, and a level of hard-coding that leads to potential maintenance issues. Alternatively, I can define a global constant (eg) `define('PLUGIN_ROOT', basename(dirname(__FILE__)) . '/' . basename(__FILE__));` in my main-file. Ideally, there is a Wordpress function that would give me the plugin base name, from anywhere in my plugin (ie always return `/plugin-folder/`)... but I haven't found one. Is there such a beastie? -- EDIT TO ADD -- I am also aware of `plugins_url()` with no parameters... but this returns `http://mydomain.ext/wp-content/plugins` - ie without my plugin name!
I think you are looking for [plugin\_dir\_url](https://codex.wordpress.org/Function_Reference/plugin_dir_url): ``` $url = plugin_dir_url(__FILE__); $imageurl = $url.'images/someimage.png'; ``` **EDIT**: Sorry I misread the question... that is only an answer to the linked question. You could check the parent directory recursively until you find the right one: ``` function base_plugin_dir($dirpath) { if (substr(dirname($dir),-7) == 'plugins') {return $dirpath;} else {$dirpath = base_plugin_dir($dirpath);} return $dirpath; } function base_plugin_dir_url($filepath) { $baseplugindir = base_plugin_dir(dirname($filepath)); $url = plugin_dir_url(trailingslashit($baseplugindir)); return $url; } ``` Then you can get the URL using that function from whatever file: ``` $basepluginurl = base_plugin_dir_url(__FILE__); $imageurl = $basepluginurl.'/images/wordpress.png'; ``` **OR** Better yet just set a constant from your main plugin file to use it later: ``` $url = plugin_dir_url(__FILE__); define('MY_UNIQUE_PLUGIN_URL',$url); ``` So as to use in say `/plugin/my-plugin/class/class1.php` ``` $imageurl = MY_UNIQUE_PLUGIN_URL.'/images/wordpress.png'; ```
222,887
<p>Is there a way to get products in the order of the IDs in the shortcode parameter:</p> <p>e.g <code>[products ids="53,68,1"]</code></p> <p>Display block with 3 product, where 53 on first place, 68 on second...?</p> <p>Now I get products sorted by sku, name etc. Depending on order-by parameter, but I need specific order.</p>
[ { "answer_id": 222859, "author": "Elektra", "author_id": 91391, "author_profile": "https://wordpress.stackexchange.com/users/91391", "pm_score": 0, "selected": false, "text": "<p><strong>Edit</strong></p>\n\n<p>My bad, in that case I can think of this. </p>\n\n<pre><code>$x = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),\"\",plugin_basename(__FILE__));\n</code></pre>\n\n<p>It should return </p>\n\n<p><a href=\"http://[url-path-to-plugins]/[custom-plugin]/\" rel=\"nofollow\">http://[url-path-to-plugins]/[custom-plugin]/</a> </p>\n\n<p>But straight forward class I don't think wordpress has one </p>\n\n<hr>\n\n<p>Yes it is </p>\n\n<p>from <a href=\"https://codex.wordpress.org/Function_Reference/plugin_basename\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/plugin_basename</a></p>\n\n<pre><code>$x = plugin_basename( __FILE__ );\n</code></pre>\n" }, { "answer_id": 222860, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>I think you are looking for <a href=\"https://codex.wordpress.org/Function_Reference/plugin_dir_url\" rel=\"nofollow\">plugin_dir_url</a>:</p>\n\n<pre><code>$url = plugin_dir_url(__FILE__);\n\n$imageurl = $url.'images/someimage.png';\n</code></pre>\n\n<p><strong>EDIT</strong>: Sorry I misread the question... that is only an answer to the linked question. You could check the parent directory recursively until you find the right one:</p>\n\n<pre><code>function base_plugin_dir($dirpath) {\n if (substr(dirname($dir),-7) == 'plugins') {return $dirpath;}\n else {$dirpath = base_plugin_dir($dirpath);}\n return $dirpath;\n}\n\nfunction base_plugin_dir_url($filepath) {\n $baseplugindir = base_plugin_dir(dirname($filepath));\n $url = plugin_dir_url(trailingslashit($baseplugindir));\n return $url;\n}\n</code></pre>\n\n<p>Then you can get the URL using that function from whatever file:</p>\n\n<pre><code>$basepluginurl = base_plugin_dir_url(__FILE__);\n$imageurl = $basepluginurl.'/images/wordpress.png';\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<p>Better yet just set a constant from your main plugin file to use it later:</p>\n\n<pre><code>$url = plugin_dir_url(__FILE__);\ndefine('MY_UNIQUE_PLUGIN_URL',$url);\n</code></pre>\n\n<p>So as to use in say <code>/plugin/my-plugin/class/class1.php</code></p>\n\n<pre><code>$imageurl = MY_UNIQUE_PLUGIN_URL.'/images/wordpress.png';\n</code></pre>\n" }, { "answer_id": 222868, "author": "Kevinleary.net", "author_id": 1495, "author_profile": "https://wordpress.stackexchange.com/users/1495", "pm_score": 0, "selected": false, "text": "<p><code>plugin_basename</code> may be what you want. If your plugin file is located at <code>/wp-content/plugins/my-plugin/my-plugin.php</code> this would return:</p>\n\n<pre><code>$file = plugin_basename( __FILE__ ); // \"my-plugin/my-plugin.php\"\n</code></pre>\n\n<p>If you called the same thing from a sub-directory in your plugin, such as <code>/wp-content/plugins/my-plugin/inc/my-plugin-include.php</code> it would return:</p>\n\n<pre><code>my-plugin/inc/my-plugin-include.php\n</code></pre>\n\n<p>If you want the current root directory for a plugin, then this custom function should do the trick:</p>\n\n<pre><code>/**\n * Current Plugin Directory \n * \n * Returns the root directory for current plugin\n */\nfunction current_plugin_dir() {\n $basename = plugin_basename( __FILE__ );\n\n return str_replace( __FILE__, '', $basename );\n}\n</code></pre>\n" }, { "answer_id": 380652, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 1, "selected": false, "text": "<p>Sorry for the late answer, below is the function I use to retrieve the plugin directory name in the format requested by @Andrew (i.e. with a trailing slash as mentioned in the comment to Kevin)</p>\n<pre><code>/**\n * Retrieve the Plugin Directory \n * \n * Returns the root directory for current plugin with a trailing slash\n */\nfunction current_plugin_dir() {\n $base = plugin_basename( __FILE__ );\n $slash = strpos($base,'/');\n $plugin_dir = $loc? substr( $base, 0, $loc + 1): $base;\n return $plugin_dir;\n}\n</code></pre>\n<p>To remove the slash just leave out the '+ 1' in the $plugin_dir line.</p>\n" } ]
2016/04/06
[ "https://wordpress.stackexchange.com/questions/222887", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91898/" ]
Is there a way to get products in the order of the IDs in the shortcode parameter: e.g `[products ids="53,68,1"]` Display block with 3 product, where 53 on first place, 68 on second...? Now I get products sorted by sku, name etc. Depending on order-by parameter, but I need specific order.
I think you are looking for [plugin\_dir\_url](https://codex.wordpress.org/Function_Reference/plugin_dir_url): ``` $url = plugin_dir_url(__FILE__); $imageurl = $url.'images/someimage.png'; ``` **EDIT**: Sorry I misread the question... that is only an answer to the linked question. You could check the parent directory recursively until you find the right one: ``` function base_plugin_dir($dirpath) { if (substr(dirname($dir),-7) == 'plugins') {return $dirpath;} else {$dirpath = base_plugin_dir($dirpath);} return $dirpath; } function base_plugin_dir_url($filepath) { $baseplugindir = base_plugin_dir(dirname($filepath)); $url = plugin_dir_url(trailingslashit($baseplugindir)); return $url; } ``` Then you can get the URL using that function from whatever file: ``` $basepluginurl = base_plugin_dir_url(__FILE__); $imageurl = $basepluginurl.'/images/wordpress.png'; ``` **OR** Better yet just set a constant from your main plugin file to use it later: ``` $url = plugin_dir_url(__FILE__); define('MY_UNIQUE_PLUGIN_URL',$url); ``` So as to use in say `/plugin/my-plugin/class/class1.php` ``` $imageurl = MY_UNIQUE_PLUGIN_URL.'/images/wordpress.png'; ```
222,888
<p>I want to show a select box for user roles in the registration form. I am using this model:</p> <pre><code>/* ROLES IN LIST REGISTRATION */ // 1. Add a new form element... add_action( 'register_form', 'odin_register_form' ); function odin_register_form() { global $wp_roles; echo '&lt;select name="role" class="input"&gt;'; echo '&lt;option disabled selected value&gt; -- &lt;/option&gt;'; foreach ( $wp_roles-&gt;roles as $key=&gt;$value ): echo '&lt;option value="'.$key.'"&gt;'.$value['name'].'&lt;/option&gt;'; endforeach; echo '&lt;/select&gt;'; } // 2. Add validation. add_filter( 'registration_errors', 'odin_registration_errors', 10, 3 ); function odin_registration_errors( $errors, $sanitized_user_login, $user_email ) { if ( empty( $_POST['role'] ) || ! empty( $_POST['role'] ) &amp;&amp; trim( $_POST['role'] ) == '' || $_POST['role'] == 'administrator' || $_POST['role'] == 'editor' || $_POST['role'] == 'contributor' || $_POST['role'] == 'author' || $_POST['role'] == 'shop_manager' ) { $errors-&gt;add( 'role_error', __( '&lt;strong&gt;ERROR&lt;/strong&gt;: Select a valid option.', 'odin' ) ); } return $errors; } //3. Finally, save our extra registration user meta. add_action( 'user_register', 'odin_user_register' ); function odin_user_register( $user_id ) { if ( $_POST['role'] != 'administrator' || $_POST['role'] != 'editor' || $_POST['role'] != 'contributor' || $_POST['role'] != 'shop_manager' || $_POST['role'] != 'author' ) { $user_id = wp_update_user( array( 'ID' =&gt; $user_id, 'role' =&gt; $_POST['role'] ) ); } } </code></pre> <p>The point is that I have not seen the error happen when validation choose an empty option.</p> <p>So what I alncançar is as follows:</p> <p>1) Filter the types of users except the Administrator, Editor, Author, Contributor, and the Store Manager. I could just set the Subscriber and Customer functions, but the project must be free to create other roles without having to write the code again.</p> <p>2) I need to validate the record of the options in this field, because it already has achieved filter rendering of roles in the selection list, we have to ensure that there is the possibility of u stranger inject an option in html with the value 'administrator' for example. This may not happen for any of the papers with some editing capability.</p> <p>I need the hint of you how I can do this.</p>
[ { "answer_id": 222859, "author": "Elektra", "author_id": 91391, "author_profile": "https://wordpress.stackexchange.com/users/91391", "pm_score": 0, "selected": false, "text": "<p><strong>Edit</strong></p>\n\n<p>My bad, in that case I can think of this. </p>\n\n<pre><code>$x = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),\"\",plugin_basename(__FILE__));\n</code></pre>\n\n<p>It should return </p>\n\n<p><a href=\"http://[url-path-to-plugins]/[custom-plugin]/\" rel=\"nofollow\">http://[url-path-to-plugins]/[custom-plugin]/</a> </p>\n\n<p>But straight forward class I don't think wordpress has one </p>\n\n<hr>\n\n<p>Yes it is </p>\n\n<p>from <a href=\"https://codex.wordpress.org/Function_Reference/plugin_basename\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/plugin_basename</a></p>\n\n<pre><code>$x = plugin_basename( __FILE__ );\n</code></pre>\n" }, { "answer_id": 222860, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>I think you are looking for <a href=\"https://codex.wordpress.org/Function_Reference/plugin_dir_url\" rel=\"nofollow\">plugin_dir_url</a>:</p>\n\n<pre><code>$url = plugin_dir_url(__FILE__);\n\n$imageurl = $url.'images/someimage.png';\n</code></pre>\n\n<p><strong>EDIT</strong>: Sorry I misread the question... that is only an answer to the linked question. You could check the parent directory recursively until you find the right one:</p>\n\n<pre><code>function base_plugin_dir($dirpath) {\n if (substr(dirname($dir),-7) == 'plugins') {return $dirpath;}\n else {$dirpath = base_plugin_dir($dirpath);}\n return $dirpath;\n}\n\nfunction base_plugin_dir_url($filepath) {\n $baseplugindir = base_plugin_dir(dirname($filepath));\n $url = plugin_dir_url(trailingslashit($baseplugindir));\n return $url;\n}\n</code></pre>\n\n<p>Then you can get the URL using that function from whatever file:</p>\n\n<pre><code>$basepluginurl = base_plugin_dir_url(__FILE__);\n$imageurl = $basepluginurl.'/images/wordpress.png';\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<p>Better yet just set a constant from your main plugin file to use it later:</p>\n\n<pre><code>$url = plugin_dir_url(__FILE__);\ndefine('MY_UNIQUE_PLUGIN_URL',$url);\n</code></pre>\n\n<p>So as to use in say <code>/plugin/my-plugin/class/class1.php</code></p>\n\n<pre><code>$imageurl = MY_UNIQUE_PLUGIN_URL.'/images/wordpress.png';\n</code></pre>\n" }, { "answer_id": 222868, "author": "Kevinleary.net", "author_id": 1495, "author_profile": "https://wordpress.stackexchange.com/users/1495", "pm_score": 0, "selected": false, "text": "<p><code>plugin_basename</code> may be what you want. If your plugin file is located at <code>/wp-content/plugins/my-plugin/my-plugin.php</code> this would return:</p>\n\n<pre><code>$file = plugin_basename( __FILE__ ); // \"my-plugin/my-plugin.php\"\n</code></pre>\n\n<p>If you called the same thing from a sub-directory in your plugin, such as <code>/wp-content/plugins/my-plugin/inc/my-plugin-include.php</code> it would return:</p>\n\n<pre><code>my-plugin/inc/my-plugin-include.php\n</code></pre>\n\n<p>If you want the current root directory for a plugin, then this custom function should do the trick:</p>\n\n<pre><code>/**\n * Current Plugin Directory \n * \n * Returns the root directory for current plugin\n */\nfunction current_plugin_dir() {\n $basename = plugin_basename( __FILE__ );\n\n return str_replace( __FILE__, '', $basename );\n}\n</code></pre>\n" }, { "answer_id": 380652, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 1, "selected": false, "text": "<p>Sorry for the late answer, below is the function I use to retrieve the plugin directory name in the format requested by @Andrew (i.e. with a trailing slash as mentioned in the comment to Kevin)</p>\n<pre><code>/**\n * Retrieve the Plugin Directory \n * \n * Returns the root directory for current plugin with a trailing slash\n */\nfunction current_plugin_dir() {\n $base = plugin_basename( __FILE__ );\n $slash = strpos($base,'/');\n $plugin_dir = $loc? substr( $base, 0, $loc + 1): $base;\n return $plugin_dir;\n}\n</code></pre>\n<p>To remove the slash just leave out the '+ 1' in the $plugin_dir line.</p>\n" } ]
2016/04/06
[ "https://wordpress.stackexchange.com/questions/222888", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/71254/" ]
I want to show a select box for user roles in the registration form. I am using this model: ``` /* ROLES IN LIST REGISTRATION */ // 1. Add a new form element... add_action( 'register_form', 'odin_register_form' ); function odin_register_form() { global $wp_roles; echo '<select name="role" class="input">'; echo '<option disabled selected value> -- </option>'; foreach ( $wp_roles->roles as $key=>$value ): echo '<option value="'.$key.'">'.$value['name'].'</option>'; endforeach; echo '</select>'; } // 2. Add validation. add_filter( 'registration_errors', 'odin_registration_errors', 10, 3 ); function odin_registration_errors( $errors, $sanitized_user_login, $user_email ) { if ( empty( $_POST['role'] ) || ! empty( $_POST['role'] ) && trim( $_POST['role'] ) == '' || $_POST['role'] == 'administrator' || $_POST['role'] == 'editor' || $_POST['role'] == 'contributor' || $_POST['role'] == 'author' || $_POST['role'] == 'shop_manager' ) { $errors->add( 'role_error', __( '<strong>ERROR</strong>: Select a valid option.', 'odin' ) ); } return $errors; } //3. Finally, save our extra registration user meta. add_action( 'user_register', 'odin_user_register' ); function odin_user_register( $user_id ) { if ( $_POST['role'] != 'administrator' || $_POST['role'] != 'editor' || $_POST['role'] != 'contributor' || $_POST['role'] != 'shop_manager' || $_POST['role'] != 'author' ) { $user_id = wp_update_user( array( 'ID' => $user_id, 'role' => $_POST['role'] ) ); } } ``` The point is that I have not seen the error happen when validation choose an empty option. So what I alncançar is as follows: 1) Filter the types of users except the Administrator, Editor, Author, Contributor, and the Store Manager. I could just set the Subscriber and Customer functions, but the project must be free to create other roles without having to write the code again. 2) I need to validate the record of the options in this field, because it already has achieved filter rendering of roles in the selection list, we have to ensure that there is the possibility of u stranger inject an option in html with the value 'administrator' for example. This may not happen for any of the papers with some editing capability. I need the hint of you how I can do this.
I think you are looking for [plugin\_dir\_url](https://codex.wordpress.org/Function_Reference/plugin_dir_url): ``` $url = plugin_dir_url(__FILE__); $imageurl = $url.'images/someimage.png'; ``` **EDIT**: Sorry I misread the question... that is only an answer to the linked question. You could check the parent directory recursively until you find the right one: ``` function base_plugin_dir($dirpath) { if (substr(dirname($dir),-7) == 'plugins') {return $dirpath;} else {$dirpath = base_plugin_dir($dirpath);} return $dirpath; } function base_plugin_dir_url($filepath) { $baseplugindir = base_plugin_dir(dirname($filepath)); $url = plugin_dir_url(trailingslashit($baseplugindir)); return $url; } ``` Then you can get the URL using that function from whatever file: ``` $basepluginurl = base_plugin_dir_url(__FILE__); $imageurl = $basepluginurl.'/images/wordpress.png'; ``` **OR** Better yet just set a constant from your main plugin file to use it later: ``` $url = plugin_dir_url(__FILE__); define('MY_UNIQUE_PLUGIN_URL',$url); ``` So as to use in say `/plugin/my-plugin/class/class1.php` ``` $imageurl = MY_UNIQUE_PLUGIN_URL.'/images/wordpress.png'; ```
222,891
<p>I have to load multiple posts on a single page. The situation is different. The client ask to reorder the posts, that the current post of the category becomes first and all the rest are next. Then on scroll I load the next posts <em>(infinite scroll effect)</em>. So what I do is, I query the database, get the posts, find my current post in the returned collection, and create a new array with the already reordered posts and I load one post when the user reaches the end of the page, on scroll.</p> <p>So far so good...</p> <p>But my task is to show a corresponding comment form to each loaded post. So if I have 20 posts on my single page, I have 20 comment forms beneath each post. I can't find a way of doing this. The wordpress function <strong>comment_form()</strong>, <strong>comments_template()</strong>, they all <strong>render</strong> html and not <strong>return</strong>, which is the problem. I need to return the html of that form so I can insert it to my collection and render it along with the post on scroll.</p> <p>Not sure what code I have to provide there, because I don't have any. If you need me to provide something, please ask.</p> <p><strong>Cheers!</strong></p> <p>Tsvetan Dimitrov</p>
[ { "answer_id": 222893, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>You can use <em>output buffering</em> to achieve this effect:</p>\n\n<pre><code>function get_comments_form() {\n ob_start();\n comments_form();\n $commentsform = ob_get_contents();\n ob_end_clean();\n return $commentsform;\n}\n\n$commentsform = get_comments_form();\n</code></pre>\n" }, { "answer_id": 222976, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 0, "selected": false, "text": "<p>You can try the following code logic</p>\n\n<pre><code>function THEMENAME_comment($comment, $args, $depth) {\n $GLOBALS['comment'] = $comment;\n *your comment display code*\n}\n</code></pre>\n" } ]
2016/04/06
[ "https://wordpress.stackexchange.com/questions/222891", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81454/" ]
I have to load multiple posts on a single page. The situation is different. The client ask to reorder the posts, that the current post of the category becomes first and all the rest are next. Then on scroll I load the next posts *(infinite scroll effect)*. So what I do is, I query the database, get the posts, find my current post in the returned collection, and create a new array with the already reordered posts and I load one post when the user reaches the end of the page, on scroll. So far so good... But my task is to show a corresponding comment form to each loaded post. So if I have 20 posts on my single page, I have 20 comment forms beneath each post. I can't find a way of doing this. The wordpress function **comment\_form()**, **comments\_template()**, they all **render** html and not **return**, which is the problem. I need to return the html of that form so I can insert it to my collection and render it along with the post on scroll. Not sure what code I have to provide there, because I don't have any. If you need me to provide something, please ask. **Cheers!** Tsvetan Dimitrov
You can use *output buffering* to achieve this effect: ``` function get_comments_form() { ob_start(); comments_form(); $commentsform = ob_get_contents(); ob_end_clean(); return $commentsform; } $commentsform = get_comments_form(); ```
222,896
<p>Is there an image bug in WP 4.4.2? I have tried the forums but no-one replies there. </p> <p>When I upload an image, it is crunched according to my media settings. But when I go to 'Add media' and select 'Large' from the dropdown, it shows and inserts an image with width=640px, though it uses the crunched image that is 1140px wide - which incidently is my Large size. 640px I have not set anywhere. Does anyone know what is going on? I have deactivated all plugins before upload, and tried in 2015 and Underscores themes.</p> <p><a href="https://i.stack.imgur.com/43ZsF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/43ZsF.png" alt="enter image description here"></a></p>
[ { "answer_id": 222893, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>You can use <em>output buffering</em> to achieve this effect:</p>\n\n<pre><code>function get_comments_form() {\n ob_start();\n comments_form();\n $commentsform = ob_get_contents();\n ob_end_clean();\n return $commentsform;\n}\n\n$commentsform = get_comments_form();\n</code></pre>\n" }, { "answer_id": 222976, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 0, "selected": false, "text": "<p>You can try the following code logic</p>\n\n<pre><code>function THEMENAME_comment($comment, $args, $depth) {\n $GLOBALS['comment'] = $comment;\n *your comment display code*\n}\n</code></pre>\n" } ]
2016/04/06
[ "https://wordpress.stackexchange.com/questions/222896", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90448/" ]
Is there an image bug in WP 4.4.2? I have tried the forums but no-one replies there. When I upload an image, it is crunched according to my media settings. But when I go to 'Add media' and select 'Large' from the dropdown, it shows and inserts an image with width=640px, though it uses the crunched image that is 1140px wide - which incidently is my Large size. 640px I have not set anywhere. Does anyone know what is going on? I have deactivated all plugins before upload, and tried in 2015 and Underscores themes. [![enter image description here](https://i.stack.imgur.com/43ZsF.png)](https://i.stack.imgur.com/43ZsF.png)
You can use *output buffering* to achieve this effect: ``` function get_comments_form() { ob_start(); comments_form(); $commentsform = ob_get_contents(); ob_end_clean(); return $commentsform; } $commentsform = get_comments_form(); ```
222,899
<p>Here's the scenario - I want to select fontawesome icons from the dropdown list but it's not working. For some reason the class inside <code>span</code> is not adding up (I have tried <code>jQuery().append()</code>, CSS) but so far no luck. ANY help would be appreciated.</p> <p><strong>Code in <code>Page.php</code> file</strong></p> <pre><code>&lt;div class="features-block-one"&gt; &lt;div class="icon-one"&gt; &lt;span class="&lt;?php get_theme_mod('features_one_icon' ,'fa fa-bullseye');?&gt;"&gt; &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Code in Customizer file</strong> </p> <pre><code>//block one icon $wp_customize-&gt;add_setting( 'features_one_icon', array( 'default' =&gt; 'fa-fa box', 'transport' =&gt; 'postMessage', 'sanitize_callback' =&gt; 'sanitize_key', ) ); $wp_customize-&gt;add_control( 'features_one_icon_control', array( 'label' =&gt; __('Select Icon', 'text-domain'), 'section' =&gt; 'features_block', 'type' =&gt; 'select', 'settings' =&gt; 'features_one_icon', 'choices' =&gt; tar_icons() /*With function tar_icons() I'm pulling all the icons from the function */ ) ); </code></pre> <p><strong>Code in <code>customizer.js</code> file</strong></p> <pre><code>wp.customize( 'features_one_icon', function( value ) { value.bind( function( to ) { $( '.features-block-one .icon-one span' ).css( to ); } ); } ); </code></pre> <p><a href="https://i.stack.imgur.com/kbseT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kbseT.png" alt="enter image description here"></a></p>
[ { "answer_id": 222893, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>You can use <em>output buffering</em> to achieve this effect:</p>\n\n<pre><code>function get_comments_form() {\n ob_start();\n comments_form();\n $commentsform = ob_get_contents();\n ob_end_clean();\n return $commentsform;\n}\n\n$commentsform = get_comments_form();\n</code></pre>\n" }, { "answer_id": 222976, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 0, "selected": false, "text": "<p>You can try the following code logic</p>\n\n<pre><code>function THEMENAME_comment($comment, $args, $depth) {\n $GLOBALS['comment'] = $comment;\n *your comment display code*\n}\n</code></pre>\n" } ]
2016/04/06
[ "https://wordpress.stackexchange.com/questions/222899", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78505/" ]
Here's the scenario - I want to select fontawesome icons from the dropdown list but it's not working. For some reason the class inside `span` is not adding up (I have tried `jQuery().append()`, CSS) but so far no luck. ANY help would be appreciated. **Code in `Page.php` file** ``` <div class="features-block-one"> <div class="icon-one"> <span class="<?php get_theme_mod('features_one_icon' ,'fa fa-bullseye');?>"> </span> </div> </div> ``` **Code in Customizer file** ``` //block one icon $wp_customize->add_setting( 'features_one_icon', array( 'default' => 'fa-fa box', 'transport' => 'postMessage', 'sanitize_callback' => 'sanitize_key', ) ); $wp_customize->add_control( 'features_one_icon_control', array( 'label' => __('Select Icon', 'text-domain'), 'section' => 'features_block', 'type' => 'select', 'settings' => 'features_one_icon', 'choices' => tar_icons() /*With function tar_icons() I'm pulling all the icons from the function */ ) ); ``` **Code in `customizer.js` file** ``` wp.customize( 'features_one_icon', function( value ) { value.bind( function( to ) { $( '.features-block-one .icon-one span' ).css( to ); } ); } ); ``` [![enter image description here](https://i.stack.imgur.com/kbseT.png)](https://i.stack.imgur.com/kbseT.png)
You can use *output buffering* to achieve this effect: ``` function get_comments_form() { ob_start(); comments_form(); $commentsform = ob_get_contents(); ob_end_clean(); return $commentsform; } $commentsform = get_comments_form(); ```
222,921
<p>I have a php file located at:</p> <pre><code>.../wp-content/themes/kallyas-child/pagebuilder/elements/TH_TeamBox/TH_TeamBox.php </code></pre> <p>I'm trying to use the above file to overwrite the parent's <em>TH_TeamBox.php</em> file which is found here:</p> <pre><code>.../wp-content/themes/kallyas/pagebuilder/elements/TH_TeamBox/TH_TeamBox.php </code></pre> <p>My child theme is active and I have created the file path in my child theme to mimic my parent theme. I was under the impression that if I did that I would be able to edit PHP files to my liking in my child theme without losing my changes when I update my parent theme.</p> <p>I've been developing for a while, but as you can see I'm new(er) to Wordpress. Any insight on why my child's .php file isn't overwriting it's parent's .php file would be greatly appreciated. I'd be glad to give anymore info that you might need to assist me, thanks! : ) </p>
[ { "answer_id": 222923, "author": "Otto", "author_id": 2232, "author_profile": "https://wordpress.stackexchange.com/users/2232", "pm_score": 5, "selected": true, "text": "<p>Child themes are allowed to override <em>templates</em>, not simply arbitrary PHP files.</p>\n\n<p>In WordPress, a theme consists of a bunch of PHP files which are used as Templates. You can find a list of those files in the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"noreferrer\">Template Hierarchy</a>. </p>\n\n<p>Those specific template files can be overridden with new ones, but unless the parent theme has some special means for you to override other files, then files simply included by the parent as part of a support structure or as libraries for a pagebuilder piece of code cannot simply be overridden in that manner.</p>\n" }, { "answer_id": 222951, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>I have a workaround for you that may be better than just writing modifications in parent theme files which is of course not desirable for reasons Otto mentioned.</p>\n\n<p>If you add these two lines of PHP the top of any file you want to use a modified copy of in your in your child theme directory structure:</p>\n\n<pre><code>&lt;?php\n $filepath = str_replace(get_option('template'), get_option('stylesheet'), __FILE__);\n if (file_exists($filepath)) {include($filepath); return;}\n?&gt;\n</code></pre>\n\n<p>You would of course still need to do this again to each file you do this to after a theme upgrade, so recommendation would be to <em>take note of these files</em>, and probably no longer update the theme directly but instead download it, add these lines back in locally and upload the updated copy by FTP. </p>\n\n<p>It may seem to be not worth that hassle, but what it would do is allow you to keep your custom modified files together in your child theme structure and not be overwritten by any theme updates. Again, you'd just re-add those lines to the top of any parent file you want to keep overriding.</p>\n\n<p>It also means you could <em>remove</em> the modified child functions file copy without breaking your site (ie. to test against an updated theme file for example) - as this will fallback to the original file if a modified copy is not found.</p>\n\n<p>(CEM Typo Edit: replaced the first <code>get_options</code> call with <code>get_option</code>.)</p>\n" }, { "answer_id": 299524, "author": "Patriot", "author_id": 140935, "author_profile": "https://wordpress.stackexchange.com/users/140935", "pm_score": 3, "selected": false, "text": "<p>The solution is to move the required changes to your child theme <em>functions.php</em> file.</p>\n\n<p>If it is a function, usually there were will be an if statement that checks if it is already declared, in this case you can copy the function to functions.php with the same name and make the required changes, it will have priority over the rest of the theme files. In case the function was declared without an if statement, then you have to change its name in <em>functions.php</em>, find the template file the functions is called, copy it to your child theme and change the function call in it.</p>\n\n<p>If it is a widget, then copy the whole class declaration to <em>functions.php</em>, change its name and make the other changes. Make sure you also register the new widget and you will find it available in the widgets area with the new name and changes.</p>\n" } ]
2016/04/06
[ "https://wordpress.stackexchange.com/questions/222921", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91918/" ]
I have a php file located at: ``` .../wp-content/themes/kallyas-child/pagebuilder/elements/TH_TeamBox/TH_TeamBox.php ``` I'm trying to use the above file to overwrite the parent's *TH\_TeamBox.php* file which is found here: ``` .../wp-content/themes/kallyas/pagebuilder/elements/TH_TeamBox/TH_TeamBox.php ``` My child theme is active and I have created the file path in my child theme to mimic my parent theme. I was under the impression that if I did that I would be able to edit PHP files to my liking in my child theme without losing my changes when I update my parent theme. I've been developing for a while, but as you can see I'm new(er) to Wordpress. Any insight on why my child's .php file isn't overwriting it's parent's .php file would be greatly appreciated. I'd be glad to give anymore info that you might need to assist me, thanks! : )
Child themes are allowed to override *templates*, not simply arbitrary PHP files. In WordPress, a theme consists of a bunch of PHP files which are used as Templates. You can find a list of those files in the [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/). Those specific template files can be overridden with new ones, but unless the parent theme has some special means for you to override other files, then files simply included by the parent as part of a support structure or as libraries for a pagebuilder piece of code cannot simply be overridden in that manner.
222,960
<p>I want to make custom post types in my WordPress site. For that I used the <code>register_post_type</code> method in my <code>functions.php</code>, but why is only one custom post type showing in my admin page?</p> <p>The code is shown below:</p> <pre><code>function create_my_custom_posts() { register_post_type( 'career_post', array( 'labels' =&gt; array( 'name' =&gt; __( 'Careers' ), 'singular_name' =&gt; __( 'Career' ), 'add_new' =&gt; __( 'Add New' ), 'add_new_item' =&gt; __( 'Add New Career' ), 'new_item' =&gt; __( 'New Career' ), 'view_item' =&gt; __( 'View Career' ), 'search_items' =&gt; __( 'Search Careers' ), 'all_items' =&gt; __( 'All Careers' ), 'add_new_item' =&gt; __( 'Add New Career' ), 'not_found' =&gt; __( 'No Openings Yet' ) ), 'description' =&gt; 'job openings in uvionics tech', 'public' =&gt; true, 'has_archive' =&gt; true, 'menu_position' =&gt; 5 ) ); register_post_type( 'employees_comnts_post', array( 'labels' =&gt; array( 'name' =&gt; __( 'Emps Comnts' ), 'singular_name' =&gt; __( 'Emp Comnt' ), 'add_new' =&gt; __( 'Add New' ), 'add_new_item' =&gt; __( 'Add New Comnt' ), 'new_item' =&gt; __( 'New Comnt' ), 'view_item' =&gt; __( 'View Comnt' ), 'search_items' =&gt; __( 'Search Comnts' ), 'all_items' =&gt; __( 'All Comnts' ), 'add_new_item' =&gt; __( 'Add New Comnt' ), 'not_found' =&gt; __( 'No Comnts Yet' ) ), 'description' =&gt; 'Employees comments about life in company', 'public' =&gt; true, 'has_archive' =&gt; true, 'menu_position' =&gt; 5 ) ); flush_rewrite_rules( false ); } add_action( 'init', 'create_my_custom_posts' ); </code></pre>
[ { "answer_id": 222961, "author": "Marttin Notta", "author_id": 91525, "author_profile": "https://wordpress.stackexchange.com/users/91525", "pm_score": 3, "selected": true, "text": "<p>In the documentation it is written that post type must be max. 20 characters, cannot contain capital letters or spaces.</p>\n" }, { "answer_id": 222970, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 0, "selected": false, "text": "<p>Try the following code for the addition of multiple custom post type </p>\n\n<pre><code>function codex_custom_init() {\n\n register_post_type(\n 'testimonials', array(\n 'labels' =&gt; array('name' =&gt; __( 'Careers' ), 'singular_name' =&gt; __( 'Career' ) ),\n 'public' =&gt; true,\n 'has_archive' =&gt; true,\n 'supports' =&gt; array('title', 'editor', 'thumbnail')\n )\n );\n\n register_post_type(\n 'home-messages', array(\n 'labels' =&gt; array('name' =&gt; __( 'Emps Comnts' ), 'singular_name' =&gt; __( 'Emp Comnt' ) ),\n 'public' =&gt; true,\n 'has_archive' =&gt; true,\n 'supports' =&gt; array('title', 'editor', 'thumbnail')\n )\n );\n\n }\n add_action( 'init', 'codex_custom_init' );\n</code></pre>\n" }, { "answer_id": 337643, "author": "Mahad Ali", "author_id": 167792, "author_profile": "https://wordpress.stackexchange.com/users/167792", "pm_score": 1, "selected": false, "text": "<p>In my case problem was that I was registering twice with same name with different parameters into it. Just had to make post_type different.\nProblem in both cases was </p>\n\n<pre><code> register_post_type('custom', $arrgs); \n register_post_type('custom', $arrgs);\n</code></pre>\n\n<p>Solution was to name post_type differently.</p>\n\n<pre><code> register_post_type('custom', $arrgs);\n register_post_type('custom_2nd', $arrgs);\n</code></pre>\n" } ]
2016/04/07
[ "https://wordpress.stackexchange.com/questions/222960", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89018/" ]
I want to make custom post types in my WordPress site. For that I used the `register_post_type` method in my `functions.php`, but why is only one custom post type showing in my admin page? The code is shown below: ``` function create_my_custom_posts() { register_post_type( 'career_post', array( 'labels' => array( 'name' => __( 'Careers' ), 'singular_name' => __( 'Career' ), 'add_new' => __( 'Add New' ), 'add_new_item' => __( 'Add New Career' ), 'new_item' => __( 'New Career' ), 'view_item' => __( 'View Career' ), 'search_items' => __( 'Search Careers' ), 'all_items' => __( 'All Careers' ), 'add_new_item' => __( 'Add New Career' ), 'not_found' => __( 'No Openings Yet' ) ), 'description' => 'job openings in uvionics tech', 'public' => true, 'has_archive' => true, 'menu_position' => 5 ) ); register_post_type( 'employees_comnts_post', array( 'labels' => array( 'name' => __( 'Emps Comnts' ), 'singular_name' => __( 'Emp Comnt' ), 'add_new' => __( 'Add New' ), 'add_new_item' => __( 'Add New Comnt' ), 'new_item' => __( 'New Comnt' ), 'view_item' => __( 'View Comnt' ), 'search_items' => __( 'Search Comnts' ), 'all_items' => __( 'All Comnts' ), 'add_new_item' => __( 'Add New Comnt' ), 'not_found' => __( 'No Comnts Yet' ) ), 'description' => 'Employees comments about life in company', 'public' => true, 'has_archive' => true, 'menu_position' => 5 ) ); flush_rewrite_rules( false ); } add_action( 'init', 'create_my_custom_posts' ); ```
In the documentation it is written that post type must be max. 20 characters, cannot contain capital letters or spaces.
222,986
<p><a href="https://i.stack.imgur.com/F1yy5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F1yy5.jpg" alt="An image illustration on how a drop down for news archive should be after php is added"></a>Am trying to get wp posts between two specific calendar month. The problem is, it is a annual year. So month starts from May and ends in Next year April. So each year output should start from May of starting year to April of next year. (Eg: May 2015 - Apr 2016)</p> <p>I tried out myself with help of some plugins, but it will output only posts around a calendar year (jan-dec).</p> <p>After complete php is done, I need to show blog listing from May 2015 to April 2016 when selected from drop down...</p> <p>My code is below;</p> <pre><code>$args=array( 'orderby' =&gt; 'date', 'order' =&gt; 'ASC', 'posts_per_page' =&gt; 1, 'caller_get_posts'=&gt;1 ); $oldestpost = get_posts($args); $args=array( 'orderby' =&gt; 'date', 'order' =&gt; 'DESC', 'posts_per_page' =&gt; 1, 'caller_get_posts'=&gt;1 ); $newestpost = get_posts($args); if ( !empty($oldestpost) &amp;&amp; !empty($newestpost) ) { $oldest = mysql2date("Y", $oldestpost[0]-&gt;post_date); $newest = mysql2date("Y", $newestpost[0]-&gt;post_date); $years = $newest - $oldest; echo '&lt;select onchange="if (this.value) window.location.href=this.value"&gt;&lt;option value="" selected&gt;Select Year&lt;/option&gt;'; for ( $counter = 0; $counter &lt;= $years; $counter += 1) { $endDate = $oldest+1; $where = apply_filters( 'getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish' AND post_date BETWEEN '$oldest-05-01' AND '$endDate-04-30'" ); $join = apply_filters( 'getarchives_join', '' ); if ( $months = $wpdb-&gt;get_results( "SELECT YEAR(post_date) AS year, MONTH(post_date) AS numMonth, DATE_FORMAT(post_date, '%M') AS month, count(ID) as post_count FROM $wpdb-&gt;posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC" ) ) { foreach ( $months as $month ) { $currentYear = $month-&gt;year; if ( $prevYear !== $currentYear ) { echo '&lt;option value=' . esc_url( get_year_link( $month-&gt;year ) ) .'&gt;'. esc_html( ($currentYear).'-'.($currentYear+1) ) . '&lt;/option&gt;'; } $prevYear = $currentYear; if ( ( $currentYear !== $prevYear ) &amp;&amp; ( '' !== $prevYear ) ) { echo '&lt;/select&gt;'; } } } $oldest++; } ?&gt; &lt;?php echo '&lt;/select&gt;'; } **Elaborating this question with a list---Just an illustrative.** *if 2006 selected the archive page will list post like below. o May 2006 o June 2006 o July 2006 o August 2006 o September 2006 o October 2006 o November 2006 o December 2006 o January 2007 o February 2007 o March 2007 o April 2007 Like above all other year lists same... * 2005 * 2004 * 2003 * 2002 </code></pre>
[ { "answer_id": 222961, "author": "Marttin Notta", "author_id": 91525, "author_profile": "https://wordpress.stackexchange.com/users/91525", "pm_score": 3, "selected": true, "text": "<p>In the documentation it is written that post type must be max. 20 characters, cannot contain capital letters or spaces.</p>\n" }, { "answer_id": 222970, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 0, "selected": false, "text": "<p>Try the following code for the addition of multiple custom post type </p>\n\n<pre><code>function codex_custom_init() {\n\n register_post_type(\n 'testimonials', array(\n 'labels' =&gt; array('name' =&gt; __( 'Careers' ), 'singular_name' =&gt; __( 'Career' ) ),\n 'public' =&gt; true,\n 'has_archive' =&gt; true,\n 'supports' =&gt; array('title', 'editor', 'thumbnail')\n )\n );\n\n register_post_type(\n 'home-messages', array(\n 'labels' =&gt; array('name' =&gt; __( 'Emps Comnts' ), 'singular_name' =&gt; __( 'Emp Comnt' ) ),\n 'public' =&gt; true,\n 'has_archive' =&gt; true,\n 'supports' =&gt; array('title', 'editor', 'thumbnail')\n )\n );\n\n }\n add_action( 'init', 'codex_custom_init' );\n</code></pre>\n" }, { "answer_id": 337643, "author": "Mahad Ali", "author_id": 167792, "author_profile": "https://wordpress.stackexchange.com/users/167792", "pm_score": 1, "selected": false, "text": "<p>In my case problem was that I was registering twice with same name with different parameters into it. Just had to make post_type different.\nProblem in both cases was </p>\n\n<pre><code> register_post_type('custom', $arrgs); \n register_post_type('custom', $arrgs);\n</code></pre>\n\n<p>Solution was to name post_type differently.</p>\n\n<pre><code> register_post_type('custom', $arrgs);\n register_post_type('custom_2nd', $arrgs);\n</code></pre>\n" } ]
2016/04/07
[ "https://wordpress.stackexchange.com/questions/222986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91953/" ]
[![An image illustration on how a drop down for news archive should be after php is added](https://i.stack.imgur.com/F1yy5.jpg)](https://i.stack.imgur.com/F1yy5.jpg)Am trying to get wp posts between two specific calendar month. The problem is, it is a annual year. So month starts from May and ends in Next year April. So each year output should start from May of starting year to April of next year. (Eg: May 2015 - Apr 2016) I tried out myself with help of some plugins, but it will output only posts around a calendar year (jan-dec). After complete php is done, I need to show blog listing from May 2015 to April 2016 when selected from drop down... My code is below; ``` $args=array( 'orderby' => 'date', 'order' => 'ASC', 'posts_per_page' => 1, 'caller_get_posts'=>1 ); $oldestpost = get_posts($args); $args=array( 'orderby' => 'date', 'order' => 'DESC', 'posts_per_page' => 1, 'caller_get_posts'=>1 ); $newestpost = get_posts($args); if ( !empty($oldestpost) && !empty($newestpost) ) { $oldest = mysql2date("Y", $oldestpost[0]->post_date); $newest = mysql2date("Y", $newestpost[0]->post_date); $years = $newest - $oldest; echo '<select onchange="if (this.value) window.location.href=this.value"><option value="" selected>Select Year</option>'; for ( $counter = 0; $counter <= $years; $counter += 1) { $endDate = $oldest+1; $where = apply_filters( 'getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish' AND post_date BETWEEN '$oldest-05-01' AND '$endDate-04-30'" ); $join = apply_filters( 'getarchives_join', '' ); if ( $months = $wpdb->get_results( "SELECT YEAR(post_date) AS year, MONTH(post_date) AS numMonth, DATE_FORMAT(post_date, '%M') AS month, count(ID) as post_count FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC" ) ) { foreach ( $months as $month ) { $currentYear = $month->year; if ( $prevYear !== $currentYear ) { echo '<option value=' . esc_url( get_year_link( $month->year ) ) .'>'. esc_html( ($currentYear).'-'.($currentYear+1) ) . '</option>'; } $prevYear = $currentYear; if ( ( $currentYear !== $prevYear ) && ( '' !== $prevYear ) ) { echo '</select>'; } } } $oldest++; } ?> <?php echo '</select>'; } **Elaborating this question with a list---Just an illustrative.** *if 2006 selected the archive page will list post like below. o May 2006 o June 2006 o July 2006 o August 2006 o September 2006 o October 2006 o November 2006 o December 2006 o January 2007 o February 2007 o March 2007 o April 2007 Like above all other year lists same... * 2005 * 2004 * 2003 * 2002 ```
In the documentation it is written that post type must be max. 20 characters, cannot contain capital letters or spaces.
223,009
<p>I am trying to develop a plugin to extend WooCommerce and I would like to do something with the product id when I land on a single product page (e.g. store it in the database or store it in a session variable).</p> <p>However whatever hook I try to use, two results are given. So for example I might use the hook woocommerce_single_product_summary as follows:</p> <pre><code>add_action( 'woocommerce_single_product_summary', 'do_my_thing' ); function do_my_thing() { global $post; store_the_id( $post-&gt;ID ); //some function to do something with the id } </code></pre> <p>When a user lands on a product page, the hook is fired twice, the function store_my_id runs twice and with two different post ids. The first is the correct id for the product in questions, and the second is an id for some other product.</p> <p>This occurs whatever hook I use e.g. get_header. It wouldn't be a problem if I just wanted to echo something to the page because the echo only outputs when the hook fires for the first time.</p> <p>Can anyone explain to me what is happening here? Is this supposed to be happening? And if so is there some way I can differentiate between the two ids returned to know which is actually the id for the product I have just landed on?</p> <p>I have tried this on a completely fresh Wordpress install with just the WooCommerce plugin installed, the twentyfifteen theme and 2 products added so I don't think it's being caused by anything custom I am doing.</p> <p>Any help really appreciated...</p> <p><strong>EDIT</strong></p> <p>I wondered whether using get_queried_object would help (as per below) but the same thing happens</p> <pre><code>add_action( 'woocommerce_single_product_summary', 'do_my_thing' ); function do_my_thing() { $queried_object = get_queried_object(); if ( $queried_object-&gt;post_type == 'product' ) { store_the_id( $queried_object-&gt;ID ); //some function to do something with the id } } </code></pre>
[ { "answer_id": 223005, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 1, "selected": false, "text": "<p>Perhaps your question no so much clear regarding your issue.I give the solution which i have understand the above question.</p>\n\n<p><strong>1. Define a query variable that indicates the requested file</strong></p>\n\n<pre><code>function add_get_file_query_var( $vars ) {\n $vars[] = 'get_file';\n return $vars;\n}\nadd_filter( 'query_vars', 'add_get_file_query_var' );\n</code></pre>\n\n<p><strong>2. Update .htaccess to forward requests for restricted files to WordPress</strong></p>\n\n<p>This will capture requests to the files you want to restrict and send them back to WordPress using the custom query variable above. Insert the following rule before the RewriteCond lines.</p>\n\n<pre><code>RewriteRule ^wp-content/uploads/(.*\\.docx)$ /index.php?get_file=$1\n</code></pre>\n\n<p><strong>3. Capture the requested file name in custom query variable; and verify access to the file:</strong></p>\n\n<pre><code>function intercept_file_request( $wp ) {\n if( !isset( $wp-&gt;query_vars['get_file'] ) )\n return;\n\n global $wpdb, $current_user;\n\n // Find attachment entry for this file in the database:\n $query = $wpdb-&gt;prepare(\"SELECT ID FROM {$wpdb-&gt;posts} WHERE guid='%s'\", $_SERVER['REQUEST_URI'] );\n $attachment_id = $wpdb-&gt;get_var( $query );\n\n // No attachment found. 404 error. \n if( !$attachment_id ) {\n $wp-&gt;query_vars['error'] = '404';\n return;\n }\n\n // Get post from database \n $file_post = get_post( $attachment_id );\n $file_path = get_attached_file( $attachment_id );\n\n if( !$file_post || !$file_path || !file_exists( $file_path ) ) {\n $wp-&gt;query_vars['error'] = '404';\n return;\n }\n\n // Logic for validating current user's access to this file...\n // Option A: check for user capability\n if( !current_user_can( 'required_capability' ) ) {\n $wp-&gt;query_vars['error'] = '404';\n return;\n }\n\n // Option B: check against current user\n if( $current_user-&gt;user_login == \"authorized_user\" ) {\n $wp-&gt;query_vars['error'] = '404';\n return;\n }\n\n // Everything checks out, user can see this file. Simulate headers and go:\n header( 'Content-Type: ' . $file_post-&gt;post_mime_type );\n header( 'Content-Dispositon: attachment; filename=\"'. basename( $file_path ) .'\"' );\n header( 'Content-Length: ' . filesize( $file_path ) );\n\n echo file_get_contents( $file_path );\n die(0);\n}\nadd_action( 'wp', 'intercept_file_request' );\n</code></pre>\n\n<p>NB This solution works for single-site installs only! This is because WordPress MU already forwards uploaded file requests in sub-sites through wp-includes/ms-files.php. There is a solution for WordPress MU as well, but it's a bit more involved.</p>\n" }, { "answer_id": 223007, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 1, "selected": true, "text": "<p>If your attachment is handled via the WP media library, each one has unique ID, just like Posts. When your users download the attachment by clicking the button, store a reference to that attachment ID in a <code>user_meta</code> setting and then update the button accordingly.</p>\n\n<p>Another option: <a href=\"https://easydigitaldownloads.com/\" rel=\"nofollow\">https://easydigitaldownloads.com/</a></p>\n" } ]
2016/04/07
[ "https://wordpress.stackexchange.com/questions/223009", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91964/" ]
I am trying to develop a plugin to extend WooCommerce and I would like to do something with the product id when I land on a single product page (e.g. store it in the database or store it in a session variable). However whatever hook I try to use, two results are given. So for example I might use the hook woocommerce\_single\_product\_summary as follows: ``` add_action( 'woocommerce_single_product_summary', 'do_my_thing' ); function do_my_thing() { global $post; store_the_id( $post->ID ); //some function to do something with the id } ``` When a user lands on a product page, the hook is fired twice, the function store\_my\_id runs twice and with two different post ids. The first is the correct id for the product in questions, and the second is an id for some other product. This occurs whatever hook I use e.g. get\_header. It wouldn't be a problem if I just wanted to echo something to the page because the echo only outputs when the hook fires for the first time. Can anyone explain to me what is happening here? Is this supposed to be happening? And if so is there some way I can differentiate between the two ids returned to know which is actually the id for the product I have just landed on? I have tried this on a completely fresh Wordpress install with just the WooCommerce plugin installed, the twentyfifteen theme and 2 products added so I don't think it's being caused by anything custom I am doing. Any help really appreciated... **EDIT** I wondered whether using get\_queried\_object would help (as per below) but the same thing happens ``` add_action( 'woocommerce_single_product_summary', 'do_my_thing' ); function do_my_thing() { $queried_object = get_queried_object(); if ( $queried_object->post_type == 'product' ) { store_the_id( $queried_object->ID ); //some function to do something with the id } } ```
If your attachment is handled via the WP media library, each one has unique ID, just like Posts. When your users download the attachment by clicking the button, store a reference to that attachment ID in a `user_meta` setting and then update the button accordingly. Another option: <https://easydigitaldownloads.com/>
223,012
<p>Two post types blog and events. I want to list in the same query but order events by their event date and blogs by their published date:</p> <pre><code> $args = array( 'post_type' =&gt; array( 'post', 'event' ), 'posts_per_page' =&gt; '-1', 'meta_query' =&gt; array( array( 'key' =&gt; 'event_start_date', 'compare' =&gt; '&gt;' ) ), 'orderby' =&gt; 'event_start_date post_date', 'order' =&gt; 'ASC' ); query_posts($args); </code></pre> <p>The above doesn't display the blog posts. </p>
[ { "answer_id": 223005, "author": "Owais Alam", "author_id": 91939, "author_profile": "https://wordpress.stackexchange.com/users/91939", "pm_score": 1, "selected": false, "text": "<p>Perhaps your question no so much clear regarding your issue.I give the solution which i have understand the above question.</p>\n\n<p><strong>1. Define a query variable that indicates the requested file</strong></p>\n\n<pre><code>function add_get_file_query_var( $vars ) {\n $vars[] = 'get_file';\n return $vars;\n}\nadd_filter( 'query_vars', 'add_get_file_query_var' );\n</code></pre>\n\n<p><strong>2. Update .htaccess to forward requests for restricted files to WordPress</strong></p>\n\n<p>This will capture requests to the files you want to restrict and send them back to WordPress using the custom query variable above. Insert the following rule before the RewriteCond lines.</p>\n\n<pre><code>RewriteRule ^wp-content/uploads/(.*\\.docx)$ /index.php?get_file=$1\n</code></pre>\n\n<p><strong>3. Capture the requested file name in custom query variable; and verify access to the file:</strong></p>\n\n<pre><code>function intercept_file_request( $wp ) {\n if( !isset( $wp-&gt;query_vars['get_file'] ) )\n return;\n\n global $wpdb, $current_user;\n\n // Find attachment entry for this file in the database:\n $query = $wpdb-&gt;prepare(\"SELECT ID FROM {$wpdb-&gt;posts} WHERE guid='%s'\", $_SERVER['REQUEST_URI'] );\n $attachment_id = $wpdb-&gt;get_var( $query );\n\n // No attachment found. 404 error. \n if( !$attachment_id ) {\n $wp-&gt;query_vars['error'] = '404';\n return;\n }\n\n // Get post from database \n $file_post = get_post( $attachment_id );\n $file_path = get_attached_file( $attachment_id );\n\n if( !$file_post || !$file_path || !file_exists( $file_path ) ) {\n $wp-&gt;query_vars['error'] = '404';\n return;\n }\n\n // Logic for validating current user's access to this file...\n // Option A: check for user capability\n if( !current_user_can( 'required_capability' ) ) {\n $wp-&gt;query_vars['error'] = '404';\n return;\n }\n\n // Option B: check against current user\n if( $current_user-&gt;user_login == \"authorized_user\" ) {\n $wp-&gt;query_vars['error'] = '404';\n return;\n }\n\n // Everything checks out, user can see this file. Simulate headers and go:\n header( 'Content-Type: ' . $file_post-&gt;post_mime_type );\n header( 'Content-Dispositon: attachment; filename=\"'. basename( $file_path ) .'\"' );\n header( 'Content-Length: ' . filesize( $file_path ) );\n\n echo file_get_contents( $file_path );\n die(0);\n}\nadd_action( 'wp', 'intercept_file_request' );\n</code></pre>\n\n<p>NB This solution works for single-site installs only! This is because WordPress MU already forwards uploaded file requests in sub-sites through wp-includes/ms-files.php. There is a solution for WordPress MU as well, but it's a bit more involved.</p>\n" }, { "answer_id": 223007, "author": "darrinb", "author_id": 6304, "author_profile": "https://wordpress.stackexchange.com/users/6304", "pm_score": 1, "selected": true, "text": "<p>If your attachment is handled via the WP media library, each one has unique ID, just like Posts. When your users download the attachment by clicking the button, store a reference to that attachment ID in a <code>user_meta</code> setting and then update the button accordingly.</p>\n\n<p>Another option: <a href=\"https://easydigitaldownloads.com/\" rel=\"nofollow\">https://easydigitaldownloads.com/</a></p>\n" } ]
2016/04/07
[ "https://wordpress.stackexchange.com/questions/223012", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83064/" ]
Two post types blog and events. I want to list in the same query but order events by their event date and blogs by their published date: ``` $args = array( 'post_type' => array( 'post', 'event' ), 'posts_per_page' => '-1', 'meta_query' => array( array( 'key' => 'event_start_date', 'compare' => '>' ) ), 'orderby' => 'event_start_date post_date', 'order' => 'ASC' ); query_posts($args); ``` The above doesn't display the blog posts.
If your attachment is handled via the WP media library, each one has unique ID, just like Posts. When your users download the attachment by clicking the button, store a reference to that attachment ID in a `user_meta` setting and then update the button accordingly. Another option: <https://easydigitaldownloads.com/>
223,073
<p>How can I create a type of loop in WordPress where an image moves left or right for each post? I.e. first post image will be left, second post image will go right, third post image will go left, and so on...</p> <p><a href="https://i.stack.imgur.com/tohVE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tohVE.png" alt=""></a></p>
[ { "answer_id": 223074, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>The PHP modulus operator gives you the remainder from dividing 2 numbers. The remainder from the division of any number by two is either 0 or 1, so we can use that to provide an \"alternator\". We use the <code>current_post</code> var as a counter, which is available in any <code>WP_Query</code> object:</p>\n\n<pre><code>while( have_posts() ){\n the_post();\n\n if( $wp_query-&gt;current_post % 2 ){\n echo 'right';\n } else {\n echo 'left';\n }\n\n}\n</code></pre>\n" }, { "answer_id": 223194, "author": "Wordpress Student", "author_id": 91995, "author_profile": "https://wordpress.stackexchange.com/users/91995", "pm_score": 0, "selected": false, "text": "<p>Thank You very much. Problem solved. Here is my code.</p>\n\n<pre><code>&lt;section id=\"features\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;div class=\"row\"&gt;\n &lt;?php $args = array(\n 'post_type' =&gt; 'service',\n 'posts_per_page' =&gt; 4\n );\n $service = new WP_Query($args);\n while ( $service-&gt;have_posts() ) : $service-&gt;the_post(); \n ?&gt;\n &lt;?php if($service-&gt;current_post % 2) : ?&gt;\n &lt;div class=\"single-features\" id=\"post-&lt;?php the_ID(); ?&gt;\"&lt;?php post_class('my-class'); ?&gt;&gt;\n\n &lt;div class=\"col-sm-5 wow fadeInLeft imagePosition\" data-wow-duration=\"500ms\" data-wow-delay=\"300ms\"&gt;\n &lt;?php the_post_thumbnail(); ?&gt;\n &lt;/div&gt;\n &lt;div class=\"col-sm-6 wow fadeInRight textPosition\" data-wow-duration=\"500ms\" data-wow-delay=\"300ms\"&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;P&gt; &lt;?php the_content(); ?&gt;&lt;/P&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php else : ?&gt;\n\n &lt;div class=\"single-features\"&gt;\n &lt;div class=\"col-sm-6 col-sm-offset-1 align-right wow fadeInLeft\" data-wow-duration=\"500ms\" data-wow-delay=\"300ms\"&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;P&gt;&lt;?php the_content(); ?&gt;&lt;/P&gt;\n &lt;/div&gt;\n &lt;div class=\"col-sm-5 wow fadeInRight\" data-wow-duration=\"500ms\" data-wow-delay=\"300ms\"&gt;\n &lt;?php the_post_thumbnail(); ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php endif; ?&gt;\n &lt;?php endwhile; ?&gt;\n &lt;!-- Do other stuff... --&gt;\n\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/section&gt;\n &lt;!--/#features--&gt;\n</code></pre>\n" } ]
2016/04/08
[ "https://wordpress.stackexchange.com/questions/223073", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91995/" ]
How can I create a type of loop in WordPress where an image moves left or right for each post? I.e. first post image will be left, second post image will go right, third post image will go left, and so on... [![](https://i.stack.imgur.com/tohVE.png)](https://i.stack.imgur.com/tohVE.png)
The PHP modulus operator gives you the remainder from dividing 2 numbers. The remainder from the division of any number by two is either 0 or 1, so we can use that to provide an "alternator". We use the `current_post` var as a counter, which is available in any `WP_Query` object: ``` while( have_posts() ){ the_post(); if( $wp_query->current_post % 2 ){ echo 'right'; } else { echo 'left'; } } ```
223,117
<p>I currently have simple pagination set up showing the text older and newer. If one of the text isn't needed it display an 'inactive' version of it so that the text doesn't disappear.</p> <pre><code>&lt;?php if( get_next_posts_link() ) :?&gt; &lt;div id="next-post-link" class="post-pag flL"&gt;&lt;?php next_posts_link( '&lt;i class="icon-left-open-big"&gt;&lt;/i&gt;&lt;span&gt;Older&lt;/span&gt;' );?&gt;&lt;/div&gt; &lt;?php else: ?&gt; &lt;div id="next-post-link" class="post-pag inactive flL"&gt;&lt;i class="icon-left-open-big"&gt;&lt;/i&gt;&lt;span&gt;Older&lt;/span&gt;&lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php if( get_previous_posts_link() ) :?&gt; &lt;div id="prev-post-link" class="post-pag flR"&gt;&lt;?php previous_posts_link( '&lt;span&gt;Newer&lt;/span&gt;&lt;i class="icon-right-open-big"&gt;&lt;/i&gt;' );?&gt;&lt;/div&gt; &lt;?php else: ?&gt; &lt;div id="prev-post-link" class="post-pag inactive flR"&gt;&lt;span&gt;Newer&lt;/span&gt;&lt;i class="icon-right-open-big"&gt;&lt;/i&gt;&lt;/div&gt; &lt;?php endif; ?&gt; </code></pre> <p>This is working fine however I'm struggling to achieve a page counter. I've looked at several questions about numbered pagination but it seems over the top for what I want. I'm looking to print the current page that I'm on and print the total amount of pages all the time.</p> <p>This image should show what I mean better: <a href="https://i.stack.imgur.com/Rty4T.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rty4T.jpg" alt="enter image description here"></a></p> <p>This is my Query so far:</p> <pre><code>$current_page = get_query_var( 'paged' ); $pages = $wp_query-&gt;max_num_pages; $args = array( 'paged'=&gt; $paged, 'posts_per_page' =&gt; '2' ); $wp_query = new WP_Query($args); if ($wp_query-&gt;have_posts()) : </code></pre>
[ { "answer_id": 223119, "author": "Greg McMullen", "author_id": 36028, "author_profile": "https://wordpress.stackexchange.com/users/36028", "pm_score": 1, "selected": true, "text": "<p>You can find more information in the <a href=\"https://codex.wordpress.org/Widgets_API\" rel=\"nofollow\">Widgets API</a></p>\n" }, { "answer_id": 223121, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>You can add a Shortcode using the built-in text widget. To get the widget to process Shortcodes, add the following filter in your theme's <code>functions.php</code>:</p>\n\n<pre><code>add_filter( 'widget_text', 'do_shortcode' );\n</code></pre>\n\n<p>This will result in widget text being passed thru <code>do_shortcode</code>, which will render any Shortcodes embedded in the text. Just note that this may not work for all Shortcodes, depending on what it actually does and if it needs a specific context to work properly.</p>\n" } ]
2016/04/08
[ "https://wordpress.stackexchange.com/questions/223117", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51147/" ]
I currently have simple pagination set up showing the text older and newer. If one of the text isn't needed it display an 'inactive' version of it so that the text doesn't disappear. ``` <?php if( get_next_posts_link() ) :?> <div id="next-post-link" class="post-pag flL"><?php next_posts_link( '<i class="icon-left-open-big"></i><span>Older</span>' );?></div> <?php else: ?> <div id="next-post-link" class="post-pag inactive flL"><i class="icon-left-open-big"></i><span>Older</span></div> <?php endif; ?> <?php if( get_previous_posts_link() ) :?> <div id="prev-post-link" class="post-pag flR"><?php previous_posts_link( '<span>Newer</span><i class="icon-right-open-big"></i>' );?></div> <?php else: ?> <div id="prev-post-link" class="post-pag inactive flR"><span>Newer</span><i class="icon-right-open-big"></i></div> <?php endif; ?> ``` This is working fine however I'm struggling to achieve a page counter. I've looked at several questions about numbered pagination but it seems over the top for what I want. I'm looking to print the current page that I'm on and print the total amount of pages all the time. This image should show what I mean better: [![enter image description here](https://i.stack.imgur.com/Rty4T.jpg)](https://i.stack.imgur.com/Rty4T.jpg) This is my Query so far: ``` $current_page = get_query_var( 'paged' ); $pages = $wp_query->max_num_pages; $args = array( 'paged'=> $paged, 'posts_per_page' => '2' ); $wp_query = new WP_Query($args); if ($wp_query->have_posts()) : ```
You can find more information in the [Widgets API](https://codex.wordpress.org/Widgets_API)
223,135
<p>I'm implementing a Kiosk webapp based off WordPress and I have some conditionals which are key, they work based on whether user is logged in or not.</p> <p>I'm aware that after user clicks "remember me" it will keep them logged in for 14 days.</p> <p>However, I want to keep users logged in for as long as possible once they log in through the kiosk.</p> <p>I was maybe thinking 1 month.</p> <p>Is there any limit to how long I can set? Can I set for 2 months? 3 months? 4 months? I know an actual cookie can be set to more than 10 years, but not sure if WP has it's own limitations on that.</p> <p>I also found a snippet of code to help me set this but I'm not sure how to know if it works, the article I found it from is 2 years old...</p> <pre><code>// keep users logged in for longer in wordpress function wcs_users_logged_in_longer( $expirein ) { // 1 month in seconds return 2628000; } add_filter( 'auth_cookie_expiration', 'wcs_users_logged_in_longer' ); </code></pre> <p>Thank you.</p>
[ { "answer_id": 223136, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>What you found is actually perfectly accurate. With WP's commitment to backwards compatibility it's not that common for thing to stop working.</p>\n\n<p>This filter is used in <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_auth_cookie\" rel=\"nofollow\"><code>wp_set_auth_cookie()</code></a> to calculate the duration. Resulting value is used in PHP's <a href=\"http://php.net/manual/en/function.setcookie.php\" rel=\"nofollow\"><code>setcookie()</code></a>.</p>\n\n<p>There is no mention of specifics limits in documentation, so in practice the value is limited by integer range for Unix timestamp (practically at the moment — year 2038 give or take).</p>\n\n<p>So you are pretty set on WP side, but I'd also look into how browsers handle it. I don't think I heard about extra long expiration times used in practice outside of development. So it's not well covered topic.</p>\n" }, { "answer_id": 299093, "author": "lukeseager", "author_id": 140592, "author_profile": "https://wordpress.stackexchange.com/users/140592", "pm_score": -1, "selected": false, "text": "<p>I know this question is old, but incase anyone stumbles across it (like I did). </p>\n\n<p>I've recently had the same problem of wanting to keep users logged into WP, so I've created a plugin to do just that. </p>\n\n<p>Take a look, I hope it helps: <a href=\"https://wordpress.org/plugins/wp-persistent-login/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-persistent-login/</a></p>\n" } ]
2016/04/08
[ "https://wordpress.stackexchange.com/questions/223135", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76433/" ]
I'm implementing a Kiosk webapp based off WordPress and I have some conditionals which are key, they work based on whether user is logged in or not. I'm aware that after user clicks "remember me" it will keep them logged in for 14 days. However, I want to keep users logged in for as long as possible once they log in through the kiosk. I was maybe thinking 1 month. Is there any limit to how long I can set? Can I set for 2 months? 3 months? 4 months? I know an actual cookie can be set to more than 10 years, but not sure if WP has it's own limitations on that. I also found a snippet of code to help me set this but I'm not sure how to know if it works, the article I found it from is 2 years old... ``` // keep users logged in for longer in wordpress function wcs_users_logged_in_longer( $expirein ) { // 1 month in seconds return 2628000; } add_filter( 'auth_cookie_expiration', 'wcs_users_logged_in_longer' ); ``` Thank you.
What you found is actually perfectly accurate. With WP's commitment to backwards compatibility it's not that common for thing to stop working. This filter is used in [`wp_set_auth_cookie()`](https://codex.wordpress.org/Function_Reference/wp_set_auth_cookie) to calculate the duration. Resulting value is used in PHP's [`setcookie()`](http://php.net/manual/en/function.setcookie.php). There is no mention of specifics limits in documentation, so in practice the value is limited by integer range for Unix timestamp (practically at the moment — year 2038 give or take). So you are pretty set on WP side, but I'd also look into how browsers handle it. I don't think I heard about extra long expiration times used in practice outside of development. So it's not well covered topic.
223,141
<p>I am working with wp-rest api and i have this json structure to work with:</p> <pre><code>[ { "id": 11, "title": { "rendered": "Test-Font" }, "acf": { "schrift": [ { "zeichen": "A", "anzahl": "23" }, { "zeichen": "B", "anzahl": "46" }, { "zeichen": "C", "anzahl": "42" }, { "zeichen": "D", "anzahl": "49" }, { "zeichen": "E", "anzahl": "31" }, … { "id": 12, "title": { "rendered": "Test-Font2" }, "acf": { "schrift": [ { "zeichen": "A", "anzahl": "20" }, { "zeichen": "B", "anzahl": "12" }, … </code></pre> <p>i want to load this like this:</p> <pre><code>jQuery(function ($) { $.ajax({ url: 'http://localhost/wordpress-dev/mi/wp-json/wp/v2/schriften/', type: "GET", dataType: "json", success: function (data) { data.forEach(function (element) { } }); }); </code></pre> <p>I want to achieve this structure, like an associative array:</p> <pre><code>[11] [A]:23 [B]:46 [C]:42 … [12] [A]:20 </code></pre> <p>how could this be done? can somebody push me in the right direction? Thanks alot!</p>
[ { "answer_id": 223136, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>What you found is actually perfectly accurate. With WP's commitment to backwards compatibility it's not that common for thing to stop working.</p>\n\n<p>This filter is used in <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_auth_cookie\" rel=\"nofollow\"><code>wp_set_auth_cookie()</code></a> to calculate the duration. Resulting value is used in PHP's <a href=\"http://php.net/manual/en/function.setcookie.php\" rel=\"nofollow\"><code>setcookie()</code></a>.</p>\n\n<p>There is no mention of specifics limits in documentation, so in practice the value is limited by integer range for Unix timestamp (practically at the moment — year 2038 give or take).</p>\n\n<p>So you are pretty set on WP side, but I'd also look into how browsers handle it. I don't think I heard about extra long expiration times used in practice outside of development. So it's not well covered topic.</p>\n" }, { "answer_id": 299093, "author": "lukeseager", "author_id": 140592, "author_profile": "https://wordpress.stackexchange.com/users/140592", "pm_score": -1, "selected": false, "text": "<p>I know this question is old, but incase anyone stumbles across it (like I did). </p>\n\n<p>I've recently had the same problem of wanting to keep users logged into WP, so I've created a plugin to do just that. </p>\n\n<p>Take a look, I hope it helps: <a href=\"https://wordpress.org/plugins/wp-persistent-login/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-persistent-login/</a></p>\n" } ]
2016/04/08
[ "https://wordpress.stackexchange.com/questions/223141", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86584/" ]
I am working with wp-rest api and i have this json structure to work with: ``` [ { "id": 11, "title": { "rendered": "Test-Font" }, "acf": { "schrift": [ { "zeichen": "A", "anzahl": "23" }, { "zeichen": "B", "anzahl": "46" }, { "zeichen": "C", "anzahl": "42" }, { "zeichen": "D", "anzahl": "49" }, { "zeichen": "E", "anzahl": "31" }, … { "id": 12, "title": { "rendered": "Test-Font2" }, "acf": { "schrift": [ { "zeichen": "A", "anzahl": "20" }, { "zeichen": "B", "anzahl": "12" }, … ``` i want to load this like this: ``` jQuery(function ($) { $.ajax({ url: 'http://localhost/wordpress-dev/mi/wp-json/wp/v2/schriften/', type: "GET", dataType: "json", success: function (data) { data.forEach(function (element) { } }); }); ``` I want to achieve this structure, like an associative array: ``` [11] [A]:23 [B]:46 [C]:42 … [12] [A]:20 ``` how could this be done? can somebody push me in the right direction? Thanks alot!
What you found is actually perfectly accurate. With WP's commitment to backwards compatibility it's not that common for thing to stop working. This filter is used in [`wp_set_auth_cookie()`](https://codex.wordpress.org/Function_Reference/wp_set_auth_cookie) to calculate the duration. Resulting value is used in PHP's [`setcookie()`](http://php.net/manual/en/function.setcookie.php). There is no mention of specifics limits in documentation, so in practice the value is limited by integer range for Unix timestamp (practically at the moment — year 2038 give or take). So you are pretty set on WP side, but I'd also look into how browsers handle it. I don't think I heard about extra long expiration times used in practice outside of development. So it's not well covered topic.
223,153
<p>I have a WP site with multiple post types. Posts, products w/taxonomies.</p> <p>I have my WP Default posts_per_page setting at 10 in the admin. I want to keep this setting as the blog would be best at 10 per page.</p> <p>However on a page/template like taxonomyNAme-archive.php I want to get many more than 10. But I don't need a custom query, since WP knows what posts to get me. Can I hijack the posts_per_page without writing a custom query?</p> <p>thanks</p>
[ { "answer_id": 223156, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>Use the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow\"><code>pre_get_posts</code></a> action to modify query parameters before the queries are run. You can use many of the <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow\">Conditional Tags</a> to target specific types of pages.</p>\n\n<pre><code>function wpd_alter_posts_per_page( $query ) {\n // don't alter admin or custom queries\n if ( is_admin() || ! $query-&gt;is_main_query() )\n return;\n\n // if this is your-custom-tax archive\n if ( is_tax( 'your-custom-tax' ) ) {\n $query-&gt;set( 'posts_per_page', 20 );\n return;\n }\n}\nadd_action( 'pre_get_posts', 'wpd_alter_posts_per_page' );\n</code></pre>\n" }, { "answer_id": 223158, "author": "Jevuska", "author_id": 18731, "author_profile": "https://wordpress.stackexchange.com/users/18731", "pm_score": 0, "selected": false, "text": "<p><em>@TJ Sherrill</em>, as alternative of <a href=\"https://wordpress.stackexchange.com/a/223156\"><em>@Milo answer</em></a>, WordPress say, <em>\"If you want to alter the value of an option during the rendering of a page without changing it permanently in the database you can use</em> <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/pre_option_%28option_name%29\" rel=\"nofollow noreferrer\"><code>pre_option_(option name)</code></a>.</p>\n\n<p>Here the sample code related to your issue, using <a href=\"https://codex.wordpress.org/Function_Reference/is_tax\" rel=\"nofollow noreferrer\"><code>is_tax</code></a> as conditional taxonomy:</p>\n\n<pre><code>add_filter( 'pre_option_posts_per_page', 'limit_posts_per_page' );\nfunction limit_posts_per_page( $posts_per_page )\n{\n /* taxonomy \"genre\" with term \"romantic\" */\n if ( is_tax( 'genre', 'romantic' ) ) \n return 11;\n return $posts_per_page;\n}\n</code></pre>\n\n<p>Just tweak the condition tag that suit with your need.</p>\n" } ]
2016/04/08
[ "https://wordpress.stackexchange.com/questions/223153", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5181/" ]
I have a WP site with multiple post types. Posts, products w/taxonomies. I have my WP Default posts\_per\_page setting at 10 in the admin. I want to keep this setting as the blog would be best at 10 per page. However on a page/template like taxonomyNAme-archive.php I want to get many more than 10. But I don't need a custom query, since WP knows what posts to get me. Can I hijack the posts\_per\_page without writing a custom query? thanks
Use the [`pre_get_posts`](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) action to modify query parameters before the queries are run. You can use many of the [Conditional Tags](https://codex.wordpress.org/Conditional_Tags) to target specific types of pages. ``` function wpd_alter_posts_per_page( $query ) { // don't alter admin or custom queries if ( is_admin() || ! $query->is_main_query() ) return; // if this is your-custom-tax archive if ( is_tax( 'your-custom-tax' ) ) { $query->set( 'posts_per_page', 20 ); return; } } add_action( 'pre_get_posts', 'wpd_alter_posts_per_page' ); ```
223,169
<p>It seems that some of the css on the table that shows the list of all the pages adversely reacts with one of my plugins, which adds a bunch of columns to the table. I'm pretty sure this is edit.php. At least, that's what's in the URL.</p> <p>Using the developer tools in Chrome I noticed that the table contains a class called <code>fixed</code>, which adds <code>table-layout:fixed</code> to the table styles. Removing it clears up the problem.</p> <p>The question is, how do I edit the styles for this table?</p> <p>Here's the relevant code:</p> <pre><code>&lt;form id="posts-filter" method="get"&gt; ... &lt;h2 class='screen-reader-text'&gt;Pages list&lt;/h2&gt; &lt;table class="wp-list-table widefat fixed striped pages"&gt; </code></pre> <p>The form element is the closet parent with an ID. The table with class <code>wp-list-table</code> is what needs to be targeted. Removing the <code>fixed</code> class fixes the problem, at least in the developer tools. How do I remove it?</p>
[ { "answer_id": 223172, "author": "ashraf", "author_id": 30937, "author_profile": "https://wordpress.stackexchange.com/users/30937", "pm_score": 1, "selected": false, "text": "<p>I guess you are in edit.php so you can add style only for this admin page. </p>\n\n<pre><code>function enqueue_my_scripts($hook) {\nif ( 'edit.php' != $hook ) {\n return;\n }\n //our script to remove fixed table class\n echo '&lt;script&gt;';\n echo '$( \".wp-list-table\" ).removeClass( \"fixed\" )';\n echo '&lt;/script&gt;';\n\n}\nadd_action( 'admin_enqueue_scripts', 'enqueue_my_scripts' );\n</code></pre>\n\n<p>The explanation is basic first we check if we are in edit page then execute the remove class. </p>\n" }, { "answer_id": 242604, "author": "user38365", "author_id": 38365, "author_profile": "https://wordpress.stackexchange.com/users/38365", "pm_score": 1, "selected": true, "text": "<p>A bit of a hack fix, I installed Tampermonkey for Chrome (a userscript manager) and created the following userscript:</p>\n\n<pre><code>// ==UserScript==\n// @name Fix edit.php!\n// @author You\n// @match http://www.example.com/wp-admin/edit.php*\n// @grant none\n// ==/UserScript==\n\n(function() {\n 'use strict';\n\n // Your code here...\n\n function addGlobalStyle(css) {\n var head, style;\n head = document.getElementsByTagName('head')[0];\n if (!head) { return; }\n style = document.createElement('style');\n style.type = 'text/css';\n style.innerHTML = css;\n head.appendChild(style);\n }\n addGlobalStyle('.fixed { table-layout:auto !important; }');\n\n})();\n</code></pre>\n\n<p>It's light, so it doesn't slow down the page at all. As far as I can tell, the problem doesn't exist anymore since a WP update, but I still have the userscript just in case.</p>\n" } ]
2016/04/09
[ "https://wordpress.stackexchange.com/questions/223169", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38365/" ]
It seems that some of the css on the table that shows the list of all the pages adversely reacts with one of my plugins, which adds a bunch of columns to the table. I'm pretty sure this is edit.php. At least, that's what's in the URL. Using the developer tools in Chrome I noticed that the table contains a class called `fixed`, which adds `table-layout:fixed` to the table styles. Removing it clears up the problem. The question is, how do I edit the styles for this table? Here's the relevant code: ``` <form id="posts-filter" method="get"> ... <h2 class='screen-reader-text'>Pages list</h2> <table class="wp-list-table widefat fixed striped pages"> ``` The form element is the closet parent with an ID. The table with class `wp-list-table` is what needs to be targeted. Removing the `fixed` class fixes the problem, at least in the developer tools. How do I remove it?
A bit of a hack fix, I installed Tampermonkey for Chrome (a userscript manager) and created the following userscript: ``` // ==UserScript== // @name Fix edit.php! // @author You // @match http://www.example.com/wp-admin/edit.php* // @grant none // ==/UserScript== (function() { 'use strict'; // Your code here... function addGlobalStyle(css) { var head, style; head = document.getElementsByTagName('head')[0]; if (!head) { return; } style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = css; head.appendChild(style); } addGlobalStyle('.fixed { table-layout:auto !important; }'); })(); ``` It's light, so it doesn't slow down the page at all. As far as I can tell, the problem doesn't exist anymore since a WP update, but I still have the userscript just in case.
223,216
<p>The situation is this: I have created a custom post type which works perfectly, now I want to create a specific archive page template for the taxonomies of this post type.</p> <p>I duplicated the <code>archive.php</code> page of my theme (schema by MTS) but it doesn't work in this case. </p> <p>Here the code: </p> <pre><code>&lt;?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ), get_query_var( 'count' ) ); echo $term-&gt;name; echo ' has nr elements: '; echo $term-&gt;count; ?&gt; &lt;div id="page"&gt; &lt;div class="&lt;?php mts_article_class(); ?&gt;"&gt; &lt;div id="content_box"&gt; &lt;h1 class="postsby"&gt; &lt;span&gt;&lt;?php echo the_archive_title(); ?&gt;&lt;/span&gt; &lt;/h1&gt; &lt;?php $j = 0; if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;article class="latestPost excerpt &lt;?php echo (++$j % 3 == 0) ? 'last' : ''; ?&gt;"&gt; &lt;?php mts_archive_post(); ?&gt; &lt;/article&gt;&lt;!--.post excerpt--&gt; &lt;?php endwhile; else: echo 'nothing'; endif; ?&gt; &lt;?php if ( $j !== 0 ) { // No pagination if there is no posts ?&gt; &lt;?php mts_pagination(); ?&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php get_sidebar(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>The strange aspect is that the code print "nothing" because the function <code>have_posts()</code> return false but the <code>$term-&gt;count</code> is <code>3</code>.</p> <p>Can you help me please? Thank you very much in advance!</p>
[ { "answer_id": 223237, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>What is wrong here is your assumptions that the values should be the same. I don't know of the top of my head what exactly the term count represent, and it is not apparent from the docs, but it is most likely a raw number of posts associated with the term. OTOH <code>wp_query</code> (which is used for the main loop) takes into account user permissions on top of that raw number, simplest example - by default the result will not include posts which are not published, more complex things can happen if you have some plugins which manipulate the query.</p>\n" }, { "answer_id": 281694, "author": "Ilya Sviridenko", "author_id": 128852, "author_profile": "https://wordpress.stackexchange.com/users/128852", "pm_score": 1, "selected": false, "text": "<p>I had same problem.</p>\n\n<p>According to <a href=\"https://developer.wordpress.org/themes/template-files-section/taxonomy-templates/\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<pre><code>The hierarchy for a custom taxonomy is listed below:\n\ntaxonomy-{taxonomy}-{term}.php\ntaxonomy-{taxonomy}.php\ntaxonomy.php\narchive.php\nindex.php\n</code></pre>\n\n<p>So, it doesn't matter witch template file you are using, all of them will generate same issue.</p>\n\n<p>When I put in the beginning of template file code <code>var_dump($wp_query);</code>, i found this:</p>\n\n<pre><code>public 'request' =&gt; string 'SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( \n wp_term_relationships.term_taxonomy_id IN (20)\n) AND wp_posts.post_type IN ('post', 'page', 'attachment') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10' (length=433)\n public 'posts' =&gt;\n</code></pre>\n\n<p>Important part in this query is <code>wp_posts.post_type IN ('post', 'page', 'attachment')</code>.</p>\n\n<p>Problem occur because there is no your custom <code>post_type</code> in this array <code>('post', 'page', 'attachment')</code>. </p>\n\n<p>I don't know why it's happen, but it's possible to fix it using <code>pre_get_posts</code> hook:</p>\n\n<pre><code>add_filter('pre_get_posts', 'add_custom_post_type_to_query');\nfunction add_custom_post_type_to_query($query) {\n // We do not want unintended consequences.\n if ( is_admin() || ! $query-&gt;is_main_query() ) {\n return; \n }\n\n // Check if custom taxonomy is being viewed\n if( is_tax() &amp;&amp; empty( $query-&gt;query_vars['suppress_filters'] ) ) \n {\n $query-&gt;set( 'post_type', array( \n 'post',\n 'page',\n 'my_custom_post_type'\n ) );\n }\n}\n</code></pre>\n" }, { "answer_id": 355924, "author": "Phil Birnie", "author_id": 60439, "author_profile": "https://wordpress.stackexchange.com/users/60439", "pm_score": 0, "selected": false, "text": "<p>Same issue as the OP. As @sviriden noted in his answer, the problem is that the main query is not including your custom post type in the <code>wp_posts.post_type IN</code> clause. I tracked down the issue in <code>class-wp-query.php</code> to these lines: </p>\n\n<pre><code> if ( 'any' == $post_type ) {\n $in_search_post_types = get_post_types( array( 'exclude_from_search' =&gt; false ) );\n if ( empty( $in_search_post_types ) ) {\n $where .= ' AND 1=0 ';\n } else {\n $where .= \" AND {$wpdb-&gt;posts}.post_type IN ('\" . join( \"', '\", array_map( 'esc_sql', $in_search_post_types ) ) . \"')\";\n }\n } elseif ( ! empty( $post_type ) &amp;&amp; is_array( $post_type ) ) {\n $where .= \" AND {$wpdb-&gt;posts}.post_type IN ('\" . join( \"', '\", esc_sql( $post_type ) ) . \"')\";\n } elseif ( ! empty( $post_type ) ) {\n $where .= $wpdb-&gt;prepare( \" AND {$wpdb-&gt;posts}.post_type = %s\", $post_type );\n $post_type_object = get_post_type_object( $post_type );\n } elseif ( $this-&gt;is_attachment ) {\n $where .= \" AND {$wpdb-&gt;posts}.post_type = 'attachment'\";\n $post_type_object = get_post_type_object( 'attachment' );\n } elseif ( $this-&gt;is_page ) {\n $where .= \" AND {$wpdb-&gt;posts}.post_type = 'page'\";\n $post_type_object = get_post_type_object( 'page' );\n } else {\n $where .= \" AND {$wpdb-&gt;posts}.post_type = 'post'\";\n $post_type_object = get_post_type_object( 'post' );\n }\n</code></pre>\n\n<p>The key is the <code>$in_search_post_types</code> which only includes Custom Post Types that have <code>exclude_from_search</code> as false. In my case I had <code>exclude_from_search</code> as <code>true</code> when registering the custom post type. Changing this value to <code>false</code> resolved the issue. </p>\n" } ]
2016/04/09
[ "https://wordpress.stackexchange.com/questions/223216", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/92109/" ]
The situation is this: I have created a custom post type which works perfectly, now I want to create a specific archive page template for the taxonomies of this post type. I duplicated the `archive.php` page of my theme (schema by MTS) but it doesn't work in this case. Here the code: ``` <?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ), get_query_var( 'count' ) ); echo $term->name; echo ' has nr elements: '; echo $term->count; ?> <div id="page"> <div class="<?php mts_article_class(); ?>"> <div id="content_box"> <h1 class="postsby"> <span><?php echo the_archive_title(); ?></span> </h1> <?php $j = 0; if (have_posts()) : while (have_posts()) : the_post(); ?> <article class="latestPost excerpt <?php echo (++$j % 3 == 0) ? 'last' : ''; ?>"> <?php mts_archive_post(); ?> </article><!--.post excerpt--> <?php endwhile; else: echo 'nothing'; endif; ?> <?php if ( $j !== 0 ) { // No pagination if there is no posts ?> <?php mts_pagination(); ?> <?php } ?> </div> </div> <?php get_sidebar(); ?> <?php get_footer(); ?> ``` The strange aspect is that the code print "nothing" because the function `have_posts()` return false but the `$term->count` is `3`. Can you help me please? Thank you very much in advance!
I had same problem. According to [documentation](https://developer.wordpress.org/themes/template-files-section/taxonomy-templates/): ``` The hierarchy for a custom taxonomy is listed below: taxonomy-{taxonomy}-{term}.php taxonomy-{taxonomy}.php taxonomy.php archive.php index.php ``` So, it doesn't matter witch template file you are using, all of them will generate same issue. When I put in the beginning of template file code `var_dump($wp_query);`, i found this: ``` public 'request' => string 'SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (20) ) AND wp_posts.post_type IN ('post', 'page', 'attachment') AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10' (length=433) public 'posts' => ``` Important part in this query is `wp_posts.post_type IN ('post', 'page', 'attachment')`. Problem occur because there is no your custom `post_type` in this array `('post', 'page', 'attachment')`. I don't know why it's happen, but it's possible to fix it using `pre_get_posts` hook: ``` add_filter('pre_get_posts', 'add_custom_post_type_to_query'); function add_custom_post_type_to_query($query) { // We do not want unintended consequences. if ( is_admin() || ! $query->is_main_query() ) { return; } // Check if custom taxonomy is being viewed if( is_tax() && empty( $query->query_vars['suppress_filters'] ) ) { $query->set( 'post_type', array( 'post', 'page', 'my_custom_post_type' ) ); } } ```