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
219,357
<p>For a redirect in CF7, on_sent_ok: "location.replace('<a href="https://www.mywebsite.com/pageid" rel="nofollow">https://www.mywebsite.com/pageid</a>')" works well in the additional settings but I need to make my website more portable. I would like to use a function to call base_url() or home_url(). Instead of writing out <a href="http://www.mywebsite.com/pageid" rel="nofollow">http://www.mywebsite.com/pageid</a>, I would rather use on_sent_ok: "function('pageid')."</p> <p>I have tried adding a JS to the page template:</p> <pre><code>&lt;script type="text/javascript"&gt; function PgRedirect($pageid) { var url='' url= "&lt;?php echo home_url($pageid)?&gt;"; window.location = url; &lt;/script&gt; </code></pre> <p>This does not work. I have tried adding a function to functions.php:</p> <pre><code>function wpcf7_pg_redirect($pageid){ wp_redirect(home_url($pageid)); exit(); } add_action('wpcf7_mail_sent', 'wpcf7_pg_redirect'); </code></pre> <p>This does not work either. I am not sure what I am missing here. Any tips would be appreciated.</p>
[ { "answer_id": 219359, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 0, "selected": false, "text": "<p>If you need to get the URL of any type of post, including pages, you should use <a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"nofollow\"><code>get_permalink()</code></a> function, which returns the canonical URL of the post/page taken care of WordPress permalink configuration.</p>\n\n<p>Using <code>home_url()</code> or <code>base_url()</code> to get a page permalink is bad idea because you can not be sure if you are getting the caninical URL of the page. Also, <code>home_url($pageid)</code> is wrong, <code>home_url()</code> accepts a path to be appended to the home url bu a page ID is not a path.</p>\n\n<p>So, use <code>get_permalink()</code>:</p>\n\n<pre><code>echo get_permalink( $pageid );\n</code></pre>\n\n<p>If you are going to print it within inline JavaScript, you should use also <a href=\"https://codex.wordpress.org/Function_Reference/esc_js\" rel=\"nofollow\"><code>esc_js()</code></a> to escape the string. Or, if you are going to use it for a redirection, <a href=\"https://codex.wordpress.org/Function_Reference/esc_url_raw\" rel=\"nofollow\">esc_url_raw()</a>:</p>\n\n<pre><code>function wpcf7_pg_redirect($pageid){\n wp_redirect( esc_url_raw( get_permalink( $pageid ) ) );\n exit();\n}\nadd_action('wpcf7_mail_sent', 'wpcf7_pg_redirect');\n</code></pre>\n\n<p>Or, if you want it to work with the ajax request (filter suggested by @userauser):</p>\n\n<pre><code>add_filter('wpcf7_ajax_json_echo', 'cf7_custom_redirect_uri', 10, 2);\nfunction cf7_custom_redirect_uri($items, $result) {\n\n if ( $some_condition_is_true ) {\n\n $redirect_to = get_permalink( $pageid );\n\n $items['onSentOk'] = \"location.replace('{\" . esc_js( $redirect_to ) . \"}')\";\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 219361, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 0, "selected": false, "text": "<p>Instead of enqueing your own JS function in the DOM hoping to marry it with CF7's <code>on_sent_ok</code> functionality in an unorthodox manner, let's take a step back and filter the resulting JS that CF7 will pass through <strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval\" rel=\"nofollow noreferrer\"><code>eval()</code></a></strong> represented as a string.</p>\n<p>For example:</p>\n<pre><code>function cf7_custom_redirect_uri($items, $result) {\n\n if ( $some_condition_is_true ) {\n\n //build the url in which you wish to redirect to...\n $redirect_to = home_url('?p=123');\n\n $items['onSentOk'] = &quot;location.replace('{$redirect_to}')&quot;;\n \n }\n\n}\n\nadd_filter('wpcf7_ajax_json_echo', 'cf7_custom_redirect_uri', 10, 2);\n</code></pre>\n<p>In your (OP) example above, you are hooking onto <code>wpcf7_mail_sent</code> to issue your redirect, which in all cases is the way I would issue the redirect instead of worrying about the <code>eval()</code> nonsense that CF7 does. If you don't need to render anything else in the DOM before redirecting the latter is better in my opinion.</p>\n<p>Example:</p>\n<pre><code>function wpcf7_pg_redirect(){\n\n if ( $some_condition_is_true ) {\n\n //build the url in which you wish to redirect to...\n $redirect_to = home_url('?p=123');\n\n wp_redirect(home_url($redirect_to));\n exit();\n\n }\n\n\n}\n\nadd_action('wpcf7_mail_sent', 'wpcf7_pg_redirect');\n</code></pre>\n<p>Note: in my examples <code> $redirect_to = home_url('?p=123');</code> can be built anyway you want, programmatically, you do not need to hardcode <code>?p=123</code>.</p>\n<p>So if you know the URL in which you wish to go to based upon some scheme or available variable or condition you would build the URL in accordance with that specification.</p>\n<p>If you are having trouble building the destination URL, tell us exactly how you want to determine which URL you should redirect to...</p>\n<ul>\n<li>are you redirecting to the same page (like a refresh)?</li>\n<li>or are you redirecting to another page and if so what conditions need to be met that determine which page you redirect too?</li>\n</ul>\n" }, { "answer_id": 219727, "author": "Craig Tucker", "author_id": 82889, "author_profile": "https://wordpress.stackexchange.com/users/82889", "pm_score": -1, "selected": false, "text": "<p>Thanks for your tips. I did try them. I found I was over complicating things in the process. This ended up being my solution:</p>\n\n<p>on_sent_ok: \"location.replace(window.location.href.substring(0, (window.location.href.lastIndexOf(\"/\")) + 1) + '[postid]');\"</p>\n\n<p>This gives me the home url and makes it possible to adjust to changes in that url when I try to port the site on other servers.</p>\n" }, { "answer_id": 219786, "author": "Craig Tucker", "author_id": 82889, "author_profile": "https://wordpress.stackexchange.com/users/82889", "pm_score": -1, "selected": false, "text": "<p>This is an even better solution based upon a shourtcode method found here:\n<a href=\"https://wordpress.org/support/topic/linking-to-pages-within-site?replies=12\" rel=\"nofollow\">https://wordpress.org/support/topic/linking-to-pages-within-site?replies=12</a></p>\n\n<p>In functions.php add this:</p>\n\n<pre><code>// create shortcode for website's home page address: [url]\n\nfunction myUrl($atts, $content = null) {\n extract(shortcode_atts(array(\n \"href\" =&gt; home_url()\n ), $atts));\n return $href;\n}\nadd_shortcode(\"url\", \"myUrl\");\n</code></pre>\n\n<p>With this [url] works in this form:</p>\n\n<p>on_sent_ok: \"location.replace('[url]/pageid/');\"</p>\n\n<p>It also works on pages and posts. Very useful.</p>\n" } ]
2016/03/01
[ "https://wordpress.stackexchange.com/questions/219357", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82889/" ]
For a redirect in CF7, on\_sent\_ok: "location.replace('<https://www.mywebsite.com/pageid>')" works well in the additional settings but I need to make my website more portable. I would like to use a function to call base\_url() or home\_url(). Instead of writing out <http://www.mywebsite.com/pageid>, I would rather use on\_sent\_ok: "function('pageid')." I have tried adding a JS to the page template: ``` <script type="text/javascript"> function PgRedirect($pageid) { var url='' url= "<?php echo home_url($pageid)?>"; window.location = url; </script> ``` This does not work. I have tried adding a function to functions.php: ``` function wpcf7_pg_redirect($pageid){ wp_redirect(home_url($pageid)); exit(); } add_action('wpcf7_mail_sent', 'wpcf7_pg_redirect'); ``` This does not work either. I am not sure what I am missing here. Any tips would be appreciated.
If you need to get the URL of any type of post, including pages, you should use [`get_permalink()`](https://developer.wordpress.org/reference/functions/get_permalink/) function, which returns the canonical URL of the post/page taken care of WordPress permalink configuration. Using `home_url()` or `base_url()` to get a page permalink is bad idea because you can not be sure if you are getting the caninical URL of the page. Also, `home_url($pageid)` is wrong, `home_url()` accepts a path to be appended to the home url bu a page ID is not a path. So, use `get_permalink()`: ``` echo get_permalink( $pageid ); ``` If you are going to print it within inline JavaScript, you should use also [`esc_js()`](https://codex.wordpress.org/Function_Reference/esc_js) to escape the string. Or, if you are going to use it for a redirection, [esc\_url\_raw()](https://codex.wordpress.org/Function_Reference/esc_url_raw): ``` function wpcf7_pg_redirect($pageid){ wp_redirect( esc_url_raw( get_permalink( $pageid ) ) ); exit(); } add_action('wpcf7_mail_sent', 'wpcf7_pg_redirect'); ``` Or, if you want it to work with the ajax request (filter suggested by @userauser): ``` add_filter('wpcf7_ajax_json_echo', 'cf7_custom_redirect_uri', 10, 2); function cf7_custom_redirect_uri($items, $result) { if ( $some_condition_is_true ) { $redirect_to = get_permalink( $pageid ); $items['onSentOk'] = "location.replace('{" . esc_js( $redirect_to ) . "}')"; } } ```
219,365
<p>I bought a wordpress theme and I am not able to display the category link and name.</p> <pre><code>&lt;div class="item-info"&gt;'; if($show_aut!='0'){ $author = get_author_posts_url( get_the_author_meta( 'ID' ) ); $html .='&lt;span class="item-author"&gt;&lt;a href="'.$author.'"title="'.get_the_author().'"&gt;'.get_the_author().'&lt;/a&gt;&lt;/span&gt;';} //DISPLAY CATEGORY LINK AND NAME if($show_sub_aut!='0'){ $subaut = get_the_category(); $html .= '&lt;span class="item-sub-aut"&gt;&lt;a href="'.$subaut.'" title="'.get_category_link().'"&gt;'.get_category_link().'&lt;/a&gt;&lt;/span&gt;';} if($show_date!='0'){ $html .= '&lt;span class="item-date"&gt;'.get_the_time(get_option('date_format')).'&lt;/span&gt;';} $html .= '&lt;/div&gt; &lt;/div&gt;'; </code></pre>
[ { "answer_id": 219359, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 0, "selected": false, "text": "<p>If you need to get the URL of any type of post, including pages, you should use <a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"nofollow\"><code>get_permalink()</code></a> function, which returns the canonical URL of the post/page taken care of WordPress permalink configuration.</p>\n\n<p>Using <code>home_url()</code> or <code>base_url()</code> to get a page permalink is bad idea because you can not be sure if you are getting the caninical URL of the page. Also, <code>home_url($pageid)</code> is wrong, <code>home_url()</code> accepts a path to be appended to the home url bu a page ID is not a path.</p>\n\n<p>So, use <code>get_permalink()</code>:</p>\n\n<pre><code>echo get_permalink( $pageid );\n</code></pre>\n\n<p>If you are going to print it within inline JavaScript, you should use also <a href=\"https://codex.wordpress.org/Function_Reference/esc_js\" rel=\"nofollow\"><code>esc_js()</code></a> to escape the string. Or, if you are going to use it for a redirection, <a href=\"https://codex.wordpress.org/Function_Reference/esc_url_raw\" rel=\"nofollow\">esc_url_raw()</a>:</p>\n\n<pre><code>function wpcf7_pg_redirect($pageid){\n wp_redirect( esc_url_raw( get_permalink( $pageid ) ) );\n exit();\n}\nadd_action('wpcf7_mail_sent', 'wpcf7_pg_redirect');\n</code></pre>\n\n<p>Or, if you want it to work with the ajax request (filter suggested by @userauser):</p>\n\n<pre><code>add_filter('wpcf7_ajax_json_echo', 'cf7_custom_redirect_uri', 10, 2);\nfunction cf7_custom_redirect_uri($items, $result) {\n\n if ( $some_condition_is_true ) {\n\n $redirect_to = get_permalink( $pageid );\n\n $items['onSentOk'] = \"location.replace('{\" . esc_js( $redirect_to ) . \"}')\";\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 219361, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 0, "selected": false, "text": "<p>Instead of enqueing your own JS function in the DOM hoping to marry it with CF7's <code>on_sent_ok</code> functionality in an unorthodox manner, let's take a step back and filter the resulting JS that CF7 will pass through <strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval\" rel=\"nofollow noreferrer\"><code>eval()</code></a></strong> represented as a string.</p>\n<p>For example:</p>\n<pre><code>function cf7_custom_redirect_uri($items, $result) {\n\n if ( $some_condition_is_true ) {\n\n //build the url in which you wish to redirect to...\n $redirect_to = home_url('?p=123');\n\n $items['onSentOk'] = &quot;location.replace('{$redirect_to}')&quot;;\n \n }\n\n}\n\nadd_filter('wpcf7_ajax_json_echo', 'cf7_custom_redirect_uri', 10, 2);\n</code></pre>\n<p>In your (OP) example above, you are hooking onto <code>wpcf7_mail_sent</code> to issue your redirect, which in all cases is the way I would issue the redirect instead of worrying about the <code>eval()</code> nonsense that CF7 does. If you don't need to render anything else in the DOM before redirecting the latter is better in my opinion.</p>\n<p>Example:</p>\n<pre><code>function wpcf7_pg_redirect(){\n\n if ( $some_condition_is_true ) {\n\n //build the url in which you wish to redirect to...\n $redirect_to = home_url('?p=123');\n\n wp_redirect(home_url($redirect_to));\n exit();\n\n }\n\n\n}\n\nadd_action('wpcf7_mail_sent', 'wpcf7_pg_redirect');\n</code></pre>\n<p>Note: in my examples <code> $redirect_to = home_url('?p=123');</code> can be built anyway you want, programmatically, you do not need to hardcode <code>?p=123</code>.</p>\n<p>So if you know the URL in which you wish to go to based upon some scheme or available variable or condition you would build the URL in accordance with that specification.</p>\n<p>If you are having trouble building the destination URL, tell us exactly how you want to determine which URL you should redirect to...</p>\n<ul>\n<li>are you redirecting to the same page (like a refresh)?</li>\n<li>or are you redirecting to another page and if so what conditions need to be met that determine which page you redirect too?</li>\n</ul>\n" }, { "answer_id": 219727, "author": "Craig Tucker", "author_id": 82889, "author_profile": "https://wordpress.stackexchange.com/users/82889", "pm_score": -1, "selected": false, "text": "<p>Thanks for your tips. I did try them. I found I was over complicating things in the process. This ended up being my solution:</p>\n\n<p>on_sent_ok: \"location.replace(window.location.href.substring(0, (window.location.href.lastIndexOf(\"/\")) + 1) + '[postid]');\"</p>\n\n<p>This gives me the home url and makes it possible to adjust to changes in that url when I try to port the site on other servers.</p>\n" }, { "answer_id": 219786, "author": "Craig Tucker", "author_id": 82889, "author_profile": "https://wordpress.stackexchange.com/users/82889", "pm_score": -1, "selected": false, "text": "<p>This is an even better solution based upon a shourtcode method found here:\n<a href=\"https://wordpress.org/support/topic/linking-to-pages-within-site?replies=12\" rel=\"nofollow\">https://wordpress.org/support/topic/linking-to-pages-within-site?replies=12</a></p>\n\n<p>In functions.php add this:</p>\n\n<pre><code>// create shortcode for website's home page address: [url]\n\nfunction myUrl($atts, $content = null) {\n extract(shortcode_atts(array(\n \"href\" =&gt; home_url()\n ), $atts));\n return $href;\n}\nadd_shortcode(\"url\", \"myUrl\");\n</code></pre>\n\n<p>With this [url] works in this form:</p>\n\n<p>on_sent_ok: \"location.replace('[url]/pageid/');\"</p>\n\n<p>It also works on pages and posts. Very useful.</p>\n" } ]
2016/03/01
[ "https://wordpress.stackexchange.com/questions/219365", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89777/" ]
I bought a wordpress theme and I am not able to display the category link and name. ``` <div class="item-info">'; if($show_aut!='0'){ $author = get_author_posts_url( get_the_author_meta( 'ID' ) ); $html .='<span class="item-author"><a href="'.$author.'"title="'.get_the_author().'">'.get_the_author().'</a></span>';} //DISPLAY CATEGORY LINK AND NAME if($show_sub_aut!='0'){ $subaut = get_the_category(); $html .= '<span class="item-sub-aut"><a href="'.$subaut.'" title="'.get_category_link().'">'.get_category_link().'</a></span>';} if($show_date!='0'){ $html .= '<span class="item-date">'.get_the_time(get_option('date_format')).'</span>';} $html .= '</div> </div>'; ```
If you need to get the URL of any type of post, including pages, you should use [`get_permalink()`](https://developer.wordpress.org/reference/functions/get_permalink/) function, which returns the canonical URL of the post/page taken care of WordPress permalink configuration. Using `home_url()` or `base_url()` to get a page permalink is bad idea because you can not be sure if you are getting the caninical URL of the page. Also, `home_url($pageid)` is wrong, `home_url()` accepts a path to be appended to the home url bu a page ID is not a path. So, use `get_permalink()`: ``` echo get_permalink( $pageid ); ``` If you are going to print it within inline JavaScript, you should use also [`esc_js()`](https://codex.wordpress.org/Function_Reference/esc_js) to escape the string. Or, if you are going to use it for a redirection, [esc\_url\_raw()](https://codex.wordpress.org/Function_Reference/esc_url_raw): ``` function wpcf7_pg_redirect($pageid){ wp_redirect( esc_url_raw( get_permalink( $pageid ) ) ); exit(); } add_action('wpcf7_mail_sent', 'wpcf7_pg_redirect'); ``` Or, if you want it to work with the ajax request (filter suggested by @userauser): ``` add_filter('wpcf7_ajax_json_echo', 'cf7_custom_redirect_uri', 10, 2); function cf7_custom_redirect_uri($items, $result) { if ( $some_condition_is_true ) { $redirect_to = get_permalink( $pageid ); $items['onSentOk'] = "location.replace('{" . esc_js( $redirect_to ) . "}')"; } } ```
219,381
<p>I'm working on a WordPress site and I use the following code to show posts in two columns on archive and category pages:</p> <pre><code>&lt;div id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class( 0 === ++$GLOBALS['wpdb']-&gt;current_post % 2 ? 'grid col-340 fit' : 'grid col-340' ); ?&gt;&gt; </code></pre> <p>With debug set to "true" I got the following notice:</p> <blockquote> <p>Notice: Undefined property: wpdb::$current_post in D:\beta\www.beta.dev\wp-includes\wp-db.php on line 684</p> </blockquote> <p>What can be wrong with this code? I noticed that this notice appeared with WordPress version 4+</p> <p>Any help will be greatly appreciated. Thanks.</p>
[ { "answer_id": 219383, "author": "user3114253", "author_id": 76325, "author_profile": "https://wordpress.stackexchange.com/users/76325", "pm_score": -1, "selected": false, "text": "<p>use <code>get_the_ID()</code> to get the current post id </p>\n\n<pre><code>&lt;?php echo get_the_ID(); ?&gt;\n</code></pre>\n\n<p>and this is how you call Global variable in wp <code>global $wpdb;</code>;</p>\n" }, { "answer_id": 219386, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 4, "selected": true, "text": "<p>There are problems with this part:</p>\n\n<pre><code> ++$GLOBALS['wpdb']-&gt;current_post\n</code></pre>\n\n<p>There's no <code>current_post</code> property of the <code>wpdb</code> class, here you're most likely confusing the <code>wpdb</code> class with the <code>WP_Query</code> class. </p>\n\n<p>Also we wouldn't want in general to modify the <code>current_post</code> property of the global <code>WP_Query</code>, it could surely \"bite us\" if we mess with the globals ;-)</p>\n\n<p>Note that the <code>current_post</code> property of <code>WP_Query</code> is already doing the counting for us with <code>$this-&gt;current_post++</code>; inside <code>next_post()</code>, that's called within <code>the_post()</code>. See <a href=\"https://github.com/WordPress/WordPress/blob/5a7a3bb9245ca84467d36c7a1a96129c0dbd10af/wp-includes/query.php#L3846\" rel=\"nofollow noreferrer\">here</a>. So there's no need to increase it manually (++) within the loop. </p>\n\n<p>Here's an example using the <code>post_class</code> filter, with the help of a <em>static</em> variable:</p>\n\n<pre><code>add_filter( 'post_class', function( $classes ) \n{\n static $instance = 0;\n\n if( in_the_loop() )\n $classes[] = ( 0 === $instance++ % 2 ) ? 'even' : 'odd'; \n\n return $classes;\n} );\n</code></pre>\n\n<p>where we target post classes in the main query loop. Just remember to modify the even/odd classes and other restrictions to your needs. </p>\n\n<p>Using the <code>post_class</code> filter could mean better re-usability for our template parts.</p>\n\n<h2>Update</h2>\n\n<p>It looks like you're using the first version of @toscho's one-liner <a href=\"https://wordpress.stackexchange.com/a/44976/26350\">answer</a>, creating a custom <code>current_post</code> property (for counting) of the global <code>wpdb</code> object. He suggested then to use the prefixed custom property, like <code>wpse_post_counter</code>. But it looks like it needs an initialization to avoid the PHP notice.</p>\n\n<p>@kaiser did post a great answer <a href=\"https://wordpress.stackexchange.com/a/44908/26350\">here</a> that uses the <code>current_post</code> property of the global <code>$wp_query</code> (probably not the global <code>$wpdb</code>).</p>\n\n<p>Since I gave a <a href=\"https://wordpress.stackexchange.com/questions/218474/display-different-smiley-when-entering/218496#comment319921_218496\">promise here</a>, regarding <em>anonymous</em> functions and <em>global</em> variables, I should rewrite it to: See my <a href=\"https://wordpress.stackexchange.com/a/44908/26350\">edit here</a>\n- where we use the <code>use</code> keyword to pass on the global <code>$wp_query</code> object.</p>\n" } ]
2016/03/01
[ "https://wordpress.stackexchange.com/questions/219381", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/33903/" ]
I'm working on a WordPress site and I use the following code to show posts in two columns on archive and category pages: ``` <div id="post-<?php the_ID(); ?>" <?php post_class( 0 === ++$GLOBALS['wpdb']->current_post % 2 ? 'grid col-340 fit' : 'grid col-340' ); ?>> ``` With debug set to "true" I got the following notice: > > Notice: Undefined property: wpdb::$current\_post in D:\beta\www.beta.dev\wp-includes\wp-db.php on line 684 > > > What can be wrong with this code? I noticed that this notice appeared with WordPress version 4+ Any help will be greatly appreciated. Thanks.
There are problems with this part: ``` ++$GLOBALS['wpdb']->current_post ``` There's no `current_post` property of the `wpdb` class, here you're most likely confusing the `wpdb` class with the `WP_Query` class. Also we wouldn't want in general to modify the `current_post` property of the global `WP_Query`, it could surely "bite us" if we mess with the globals ;-) Note that the `current_post` property of `WP_Query` is already doing the counting for us with `$this->current_post++`; inside `next_post()`, that's called within `the_post()`. See [here](https://github.com/WordPress/WordPress/blob/5a7a3bb9245ca84467d36c7a1a96129c0dbd10af/wp-includes/query.php#L3846). So there's no need to increase it manually (++) within the loop. Here's an example using the `post_class` filter, with the help of a *static* variable: ``` add_filter( 'post_class', function( $classes ) { static $instance = 0; if( in_the_loop() ) $classes[] = ( 0 === $instance++ % 2 ) ? 'even' : 'odd'; return $classes; } ); ``` where we target post classes in the main query loop. Just remember to modify the even/odd classes and other restrictions to your needs. Using the `post_class` filter could mean better re-usability for our template parts. Update ------ It looks like you're using the first version of @toscho's one-liner [answer](https://wordpress.stackexchange.com/a/44976/26350), creating a custom `current_post` property (for counting) of the global `wpdb` object. He suggested then to use the prefixed custom property, like `wpse_post_counter`. But it looks like it needs an initialization to avoid the PHP notice. @kaiser did post a great answer [here](https://wordpress.stackexchange.com/a/44908/26350) that uses the `current_post` property of the global `$wp_query` (probably not the global `$wpdb`). Since I gave a [promise here](https://wordpress.stackexchange.com/questions/218474/display-different-smiley-when-entering/218496#comment319921_218496), regarding *anonymous* functions and *global* variables, I should rewrite it to: See my [edit here](https://wordpress.stackexchange.com/a/44908/26350) - where we use the `use` keyword to pass on the global `$wp_query` object.
219,391
<p>I wish that my 'custom post type archive page' would point to Page.</p> <p>The situations is as follows:</p> <p>I have <code>Page</code> in Wordpress with permalink <code>http://myurl.com/galleries</code>. This page shows list of posts with custom post type = <code>vmgallery</code>. I have custom logic for this page that is working fine. </p> <p>From another view, this page works like "custom post type archive page", because it displays all posts for given custom post type vmgallery. Currently, if user goes to <a href="http://myurl.com/vmgallery/" rel="nofollow">http://myurl.com/vmgallery/</a> wordpress is loading archive page (archive.php), instead, I wish <code>http://myurl.com/galleries</code> page is loaded. </p> <p>How to achieve this?</p>
[ { "answer_id": 219392, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 5, "selected": true, "text": "<p>You have multiple options here.</p>\n\n<p><strong>1. Define post type archive slug on post type registration</strong></p>\n\n<p>By setting <code>'has_archive' =&gt; 'galleries'</code> you can define custom post type archive slug.\nCheck <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#has_archive\" rel=\"noreferrer\">documentation</a>.\nThen you can delete your page \"galleries\" then add &amp; customize the <code>archive-post_type.php</code></p>\n\n<p><strong>2. Disable default archive for post type</strong></p>\n\n<p>Disable the archive by setting <code>'has_archive' =&gt; false</code> then keep the page for the post type archive.</p>\n\n<p><strong>3. Redirect archive requests to your page</strong></p>\n\n<p>You can permanent redirect default archive request to your page.</p>\n\n<pre><code>function archive_to_custom_archive() {\n if( is_post_type_archive( 'post_slug' ) ) {\n wp_redirect( home_url( '/galleries/' ), 301 );\n exit();\n }\n}\nadd_action( 'template_redirect', 'archive_to_custom_archive' );\n</code></pre>\n\n<blockquote>\n <p>I will say the first method is good!</p>\n</blockquote>\n" }, { "answer_id": 326102, "author": "Gauravbhai Daxini", "author_id": 137687, "author_profile": "https://wordpress.stackexchange.com/users/137687", "pm_score": 0, "selected": false, "text": "<p>Here is below code to remove archive page link with not affecting in single post url.and you can create page with archive slug.</p>\n\n<pre><code>function dg_custom_post_type_args( $args, $post_type ) {\nif ( $post_type === \"custom post type\" ) {\n $args['rewrite'] = array(\n 'with_front' =&gt; false,\n 'slug' =&gt; 'slug here'\n );\n}\n\nreturn $args;\n}\nadd_filter( 'register_post_type_args', 'dg_custom_post_type_args', 20, 2 );\n</code></pre>\n" } ]
2016/03/01
[ "https://wordpress.stackexchange.com/questions/219391", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35268/" ]
I wish that my 'custom post type archive page' would point to Page. The situations is as follows: I have `Page` in Wordpress with permalink `http://myurl.com/galleries`. This page shows list of posts with custom post type = `vmgallery`. I have custom logic for this page that is working fine. From another view, this page works like "custom post type archive page", because it displays all posts for given custom post type vmgallery. Currently, if user goes to <http://myurl.com/vmgallery/> wordpress is loading archive page (archive.php), instead, I wish `http://myurl.com/galleries` page is loaded. How to achieve this?
You have multiple options here. **1. Define post type archive slug on post type registration** By setting `'has_archive' => 'galleries'` you can define custom post type archive slug. Check [documentation](https://codex.wordpress.org/Function_Reference/register_post_type#has_archive). Then you can delete your page "galleries" then add & customize the `archive-post_type.php` **2. Disable default archive for post type** Disable the archive by setting `'has_archive' => false` then keep the page for the post type archive. **3. Redirect archive requests to your page** You can permanent redirect default archive request to your page. ``` function archive_to_custom_archive() { if( is_post_type_archive( 'post_slug' ) ) { wp_redirect( home_url( '/galleries/' ), 301 ); exit(); } } add_action( 'template_redirect', 'archive_to_custom_archive' ); ``` > > I will say the first method is good! > > >
219,410
<p>I'm making a website and it seems that product sku is hidden from product page. I have found how to add it to the catalog (shop) page but I need it to show inside the product page.</p> <p>So far, by altering the single-product.php, I managed to add it at the end of the page (something we do not want) or before the title on the top left of the page (something we also do not want).</p> <p>I found no way to add it before the price and below the title of the product.</p> <p>The code of the themes' single-product.php: </p> <pre><code> &lt;?php /** * Single Product title * * This template can be overridden by copying it to yourtheme/woocommerce/single-product/title.php. * * HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer). * will need to copy the new files to your theme to maintain compatibility. We try to do this. * as little as possible, but it does happen. When this occurs the version of the template file will. * be bumped and the readme will list any important changes. * * @see http://docs.woothemes.com/document/template-structure/ * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } ?&gt; &lt;?php echo '&lt;div class="sku"&gt;' . $product-&gt;sku . '&lt;/div&gt;'; ?&gt; </code></pre> <p>I added the last line.</p> <p>However, on the theme/woocommerce/single-product/meta.php I can see that sku should be displayed, which is not:</p> <pre><code>&lt;?php /** * Single Product Meta * * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $post, $product; ?&gt; &lt;div class="product_meta"&gt; &lt;?php if ( $product-&gt;is_type( array( 'simple', 'variable' ) ) &amp;&amp; get_option('woocommerce_enable_sku') == 'yes' &amp;&amp; $product-&gt;get_sku() ) : ?&gt; &lt;span itemprop="productID" class="sku"&gt;&lt;?php _e('SKU:','qns' ); ?&gt; &lt;?php echo $product-&gt;get_sku(); ?&gt;.&lt;/span&gt; &lt;?php endif; ?&gt; &lt;?php echo $product-&gt;get_categories( ', ', ' &lt;span class="posted_in"&gt;'.__('Category:','qns' ).' ', '.&lt;/span&gt;'); ?&gt; &lt;?php echo $product-&gt;get_tags( ', ', ' &lt;span class="tagged_as"&gt;'.__('Tags:','qns' ).' ', '.&lt;/span&gt;'); ?&gt; &lt;/div&gt; </code></pre> <p>Any ideas of how I can show the product SKU number inside the product page?</p> <p>Thanks in advance.</p>
[ { "answer_id": 219427, "author": "Joe Dooley", "author_id": 81789, "author_profile": "https://wordpress.stackexchange.com/users/81789", "pm_score": 4, "selected": true, "text": "<p>Add this to your functions.php</p>\n\n<pre><code>add_action( 'woocommerce_single_product_summary', 'dev_designs_show_sku', 5 );\nfunction dev_designs_show_sku(){\n global $product;\n echo 'SKU: ' . $product-&gt;get_sku();\n}\n</code></pre>\n\n<p>This will output the product SKU below the product title. See image below. The product SKU is VERTEX-SLVR.</p>\n\n<p><a href=\"https://i.stack.imgur.com/kG2GJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/kG2GJ.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 237026, "author": "Zoe", "author_id": 101601, "author_profile": "https://wordpress.stackexchange.com/users/101601", "pm_score": 0, "selected": false, "text": "<p>Add the following code in your (child) theme's <code>functions.php</code>:</p>\n\n<pre><code>function visupporti_get_product_quantity( $atts ) {\n\nglobal $product;\n\n$atts = shortcode_atts( array(\n'id' =&gt; ”,\n), $atts );\n\n// If no id, we’re probably on a product page already\nif ( empty( $atts['id'] ) ) {\n\n$sku = $product-&gt;get_stock_quantity( );\n\n} else {\n\n//get which product from ID we should display a SKU for\n$product = wc_get_product( $atts['id'] );\n$sku = $product-&gt;get_stock_quantity( );\n\n}\n\nob_start();\n\n// Only echo if there is a SKU\nif ( !empty( $sku ) ) {\necho $sku;\n}\n\nreturn ob_get_clean();\n\n}\nadd_shortcode( 'wc_sku', 'visupporti_get_product_quantity' );\n</code></pre>\n\n<p>See more details on <a href=\"http://visupporti.com/woocommerce-how-to-show-sku-via-shortcode/\" rel=\"nofollow noreferrer\">how to display SKU on the site</a>.</p>\n" }, { "answer_id": 379139, "author": "John Fotios", "author_id": 197784, "author_profile": "https://wordpress.stackexchange.com/users/197784", "pm_score": 0, "selected": false, "text": "<p>Add to functions.php, only shows if product has an SKU</p>\n<pre><code> add_action( 'woocommerce_single_product_summary', 'dev_designs_show_sku', 5 );\n function dev_designs_show_sku(){\n global $product;\n $sku = $product-&gt;get_sku();\n if ($sku != null) {\n echo 'SKU: ' . $product-&gt;get_sku();\n }\n }\n</code></pre>\n" } ]
2016/03/01
[ "https://wordpress.stackexchange.com/questions/219410", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89804/" ]
I'm making a website and it seems that product sku is hidden from product page. I have found how to add it to the catalog (shop) page but I need it to show inside the product page. So far, by altering the single-product.php, I managed to add it at the end of the page (something we do not want) or before the title on the top left of the page (something we also do not want). I found no way to add it before the price and below the title of the product. The code of the themes' single-product.php: ``` <?php /** * Single Product title * * This template can be overridden by copying it to yourtheme/woocommerce/single-product/title.php. * * HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer). * will need to copy the new files to your theme to maintain compatibility. We try to do this. * as little as possible, but it does happen. When this occurs the version of the template file will. * be bumped and the readme will list any important changes. * * @see http://docs.woothemes.com/document/template-structure/ * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } ?> <?php echo '<div class="sku">' . $product->sku . '</div>'; ?> ``` I added the last line. However, on the theme/woocommerce/single-product/meta.php I can see that sku should be displayed, which is not: ``` <?php /** * Single Product Meta * * @author WooThemes * @package WooCommerce/Templates * @version 1.6.4 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $post, $product; ?> <div class="product_meta"> <?php if ( $product->is_type( array( 'simple', 'variable' ) ) && get_option('woocommerce_enable_sku') == 'yes' && $product->get_sku() ) : ?> <span itemprop="productID" class="sku"><?php _e('SKU:','qns' ); ?> <?php echo $product->get_sku(); ?>.</span> <?php endif; ?> <?php echo $product->get_categories( ', ', ' <span class="posted_in">'.__('Category:','qns' ).' ', '.</span>'); ?> <?php echo $product->get_tags( ', ', ' <span class="tagged_as">'.__('Tags:','qns' ).' ', '.</span>'); ?> </div> ``` Any ideas of how I can show the product SKU number inside the product page? Thanks in advance.
Add this to your functions.php ``` add_action( 'woocommerce_single_product_summary', 'dev_designs_show_sku', 5 ); function dev_designs_show_sku(){ global $product; echo 'SKU: ' . $product->get_sku(); } ``` This will output the product SKU below the product title. See image below. The product SKU is VERTEX-SLVR. [![enter image description here](https://i.stack.imgur.com/kG2GJ.png)](https://i.stack.imgur.com/kG2GJ.png)
219,454
<p>I'm using a dynamic CSS file with PHP extention.</p> <pre><code>wp_enqueue_style('css', get_template_directory_uri().'/inc/css.php'); </code></pre> <p>The output:</p> <pre><code>&lt;link rel='stylesheet' id='dynamic-css' href='PATH/inc/css.php?ver=4.4.2' type='text/css' media='all' /&gt; </code></pre> <p>I'm also using a cache plugin (WP Super Cache).</p> <p>My question is, is this CSS file cached as PHP or CSS?</p>
[ { "answer_id": 220596, "author": "iantsch", "author_id": 90220, "author_profile": "https://wordpress.stackexchange.com/users/90220", "pm_score": 0, "selected": false, "text": "<p>I don't know what you do in your <code>css.php</code> to handle your php cache, but i guess not much. If you want your <code>css.php</code> to be cached as CSS you can use this adapted <a href=\"http://www.catswhocode.com/blog/how-to-create-a-simple-and-efficient-php-cache\" rel=\"nofollow\">snippet</a> I found.</p>\n\n<h2>HOW TO CREATE A SIMPLE AND EFFICIENT PHP CACHE</h2>\n\n<p><strong>Edit 2:</strong></p>\n\n<p>As stated in @TomJNowell 's answer this is not a safe approach:</p>\n\n<blockquote>\n <p>If your file bootstraps WordPress, then it will work even when the\n plugin or theme is disabled, acting as a potential security hole. This\n is even more true of AJAX endpoints and form handlers. WordPress is a\n CMS, and all requests should be routed through it. An AJAX API is\n provided already, and there are rewrite rules and query variables that\n you can add and detect to output CSS and other things.</p>\n</blockquote>\n\n<p><strong>css.php:</strong></p>\n\n<pre><code>$url = $_SERVER[\"SCRIPT_NAME\"];\n$break = Explode('/', $url);\n$file = $break[count($break) - 1];\n$cachefile = 'cached-'.substr_replace($file ,\"\",-4).'.css';\n$cachetime = 18000;\n\n// Serve from the cache if it is younger than $cachetime\nif (file_exists($cachefile) &amp;&amp; time() - $cachetime &lt; filemtime($cachefile)) {\n echo \"/* Cached copy, generated \".date('H:i', filemtime($cachefile)).\" */\\n\";\n include($cachefile);\n exit;\n}\nob_start(); \n\n//Add your former css.php here\n\n$cached = fopen($cachefile, 'w');\nfwrite($cached, ob_get_contents());\nfclose($cached);\nob_end_flush();\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>Your Plugin caches all template output (posts, pages, archives, …) as HTML but no linked data, like JS or CSS.</p>\n" }, { "answer_id": 220600, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>A great deal of this will depend on your server configuration, but:</p>\n\n<h2>Will WP Super Cache cache the css.php output?</h2>\n\n<p>Extremely unlikely. If your file simply generates CSS from a few variables, then no.</p>\n\n<p>If however it bootstraps and loads WordPress, then it 'might' cache some things, but I doubt it will work as you expect, or that it will do a full page cache. Here the word 'might' is a stretch at best</p>\n\n<h2>Will Other Caching Plugins Cache it?</h2>\n\n<p>Switching to another caching plugin will not change things</p>\n\n<h2>Will the Server cache it? Or the Browser?</h2>\n\n<p>That depends on the headers sent, and at this point we've moved beyond the scope of WordPress and this stack exchange. The answer is entirely dependent on your setup, and is impossible to answer without making this question useless to other people, or having intimate knowledge of your system</p>\n\n<h2>Is What I'm Doing Safe?</h2>\n\n<p>No.</p>\n\n<p>If your file bootstraps WordPress, then it will work even when the plugin or theme is disabled, acting as a potential security hole. This is even more true of AJAX endpoints and form handlers. WordPress is a CMS, and all requests should be routed through it. An AJAX API is provided already, and there are rewrite rules and query variables that you can add and detect to output CSS and other things.</p>\n\n<p>If however your <code>css.php</code> outputs PHP after doing a small amount of math etc, then you should eliminate it, and simply use a build process to generate a css file. You can use less or sass or some other system to generate the CSS, but it doesn't need distributing to your server</p>\n" } ]
2016/03/02
[ "https://wordpress.stackexchange.com/questions/219454", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62214/" ]
I'm using a dynamic CSS file with PHP extention. ``` wp_enqueue_style('css', get_template_directory_uri().'/inc/css.php'); ``` The output: ``` <link rel='stylesheet' id='dynamic-css' href='PATH/inc/css.php?ver=4.4.2' type='text/css' media='all' /> ``` I'm also using a cache plugin (WP Super Cache). My question is, is this CSS file cached as PHP or CSS?
A great deal of this will depend on your server configuration, but: Will WP Super Cache cache the css.php output? --------------------------------------------- Extremely unlikely. If your file simply generates CSS from a few variables, then no. If however it bootstraps and loads WordPress, then it 'might' cache some things, but I doubt it will work as you expect, or that it will do a full page cache. Here the word 'might' is a stretch at best Will Other Caching Plugins Cache it? ------------------------------------ Switching to another caching plugin will not change things Will the Server cache it? Or the Browser? ----------------------------------------- That depends on the headers sent, and at this point we've moved beyond the scope of WordPress and this stack exchange. The answer is entirely dependent on your setup, and is impossible to answer without making this question useless to other people, or having intimate knowledge of your system Is What I'm Doing Safe? ----------------------- No. If your file bootstraps WordPress, then it will work even when the plugin or theme is disabled, acting as a potential security hole. This is even more true of AJAX endpoints and form handlers. WordPress is a CMS, and all requests should be routed through it. An AJAX API is provided already, and there are rewrite rules and query variables that you can add and detect to output CSS and other things. If however your `css.php` outputs PHP after doing a small amount of math etc, then you should eliminate it, and simply use a build process to generate a css file. You can use less or sass or some other system to generate the CSS, but it doesn't need distributing to your server
219,471
<p>I have a little problem.</p> <p>This is my page structure:</p> <pre><code>Ancestor Parent Child 1 Child 2 Child 3 Child 4 </code></pre> <p>What i try to do is when i'm on Child 4 i want to show Child 2. </p> <p>And when i'm on Child 2 i want to show Parent. </p> <p>But i can't figure out how to do this. The code that i use is this:</p> <pre><code>function wpb_list_child_pages_popup() { global $post; if ( is_page() &amp;&amp; $post-&gt;post_parent ) $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;post_parent . '&amp;echo=0' ); else $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;ID . '&amp;echo=0' ); if ( $childpages ) { $string = '&lt;ul id="child-menu"&gt;' . $childpages . '&lt;/ul&gt;'; } return $string; } add_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup'); </code></pre>
[ { "answer_id": 219482, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": true, "text": "<p>You need to look at <code>get_ancestors()</code> to get the top level parent of a page. Just a note, for reliability, use <code>get_queried_object()</code> (<em>or even better <code>$GLOBALS['wp_the_query']-&gt;get_queried_object()</code></em>) to get the current post/page object on singular pages, <code>$post</code> can be quite unreliable</p>\n\n<p>You can try the following in your shortcode:</p>\n\n<pre><code>$post = $GLOBALS['wp_the_query']-&gt;get_queried_object();\n// Make sure the current page is not top level\nif ( 0 === (int) $post-&gt;post_parent ) {\n $parent = $post-&gt;ID;\n} else {\n $ancestors = get_ancestors( $post-&gt;ID, $post-&gt;post_type );\n $parent = end( $ancestors );\n}\n</code></pre>\n\n<p><code>$parent</code> will now always hold the top level parent of any given page</p>\n\n<h2>EDIT - from comments</h2>\n\n<p>If you need to get the page two levels higher than the current one, you can still use the same approach, but insted of using the last ID from `get_ancestors (<em>which is the top level parent</em>), we need to adjust this to get the second entry</p>\n\n<p>Lets modify the code above slightly</p>\n\n<pre><code>$post = $GLOBALS['wp_the_query']-&gt;get_queried_object();\n// Make sure the current page is not top level\nif ( 0 === (int) $post-&gt;post_parent ) {\n $parent = $post-&gt;ID;\n} else {\n $ancestors = get_ancestors( $post-&gt;ID, $post-&gt;post_type );\n // Check if $ancestors have at least two key/value pairs\n if ( 1 == count( $ancestors ) ) {\n $parent = $post-&gt;post_parent;\n } esle {\n $parent = $ancestors[1]; // Gets the parent two levels higher\n }\n}\n</code></pre>\n\n<h2>LAST EDIT - full code</h2>\n\n<pre><code>function wpb_list_child_pages_popup() \n{\n // Define our $string variable\n $string = '';\n\n // Make sure this is a page\n if ( !is_page() )\n return $string;\n\n $post = $GLOBALS['wp_the_query']-&gt;get_queried_object();\n // Make sure the current page is not top level\n if ( 0 === (int) $post-&gt;post_parent ) {\n $parent = $post-&gt;ID;\n } else {\n $ancestors = get_ancestors( $post-&gt;ID, $post-&gt;post_type );\n // Check if $ancestors have at least two key/value pairs\n if ( 1 == count( $ancestors ) ) {\n $parent = $post-&gt;post_parent;\n } else {\n $parent = $ancestors[1]; // Gets the parent two levels higher\n }\n } \n\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $parent . '&amp;echo=0' );\n\n $string .= '&lt;ul id=\"child-menu\"&gt;' . $childpages . '&lt;/ul&gt;';\n\n return $string;\n\n}\n\nadd_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');\n</code></pre>\n" }, { "answer_id": 219485, "author": "Jebble", "author_id": 81939, "author_profile": "https://wordpress.stackexchange.com/users/81939", "pm_score": 1, "selected": false, "text": "<p>I don't completely understand what your question is, mainly because you're talking about parents and childs but this will never show the parent of a page let alone the grandparent.</p>\n\n<p>I've commented your code down here to show you what exactly what is happenign in the code.</p>\n\n<pre><code>function wpb_list_child_pages_popup() { \n\n // Get the current WP Post object\n global $post;\n\n /**\n * If post_type of current WP Post object is 'page'\n * and the post_parent in the WP Post object is set\n */\n if ( is_page() &amp;&amp; $post-&gt;post_parent )\n /**\n * Get all wordpress pages that are a child of this pages parent.\n * In other words get THIS page and all it's siblings\n */\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;post_parent . '&amp;echo=0' );\n /**\n * If this page doesn't have a parent\n */\n else\n /**\n * Get all wordpress pages that are a child of this page\n */\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;ID . '&amp;echo=0' );\n\n if ( $childpages ) {\n\n $string = '&lt;ul id=\"child-menu\"&gt;' . $childpages . '&lt;/ul&gt;';\n }\n\n return $string;\n\n}\n\nadd_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');\n</code></pre>\n\n<p>What I'm guessing is that you simply want a list with alle pages that are \"connected\" by being a (grand)parent, (grand)child, or sibling.\nThis function returns a string that contains all of that no matter which of the siblings you're on.</p>\n\n<pre><code>function wpb_list_child_pages_popup() {\n\n // Get the current WP Post object\n global $post;\n\n if ( is_page() ) {\n\n /**\n * Get 'first' parent, the highest ranking post parent which is the ancestor of all.\n * @var array\n */\n $ancestor = array_reverse( get_post_ancestors( $post-&gt;ID ) );\n // If there is no ancestor, set ancestor to this page.\n if ( empty( $ancestor ) ) {\n $ancestor_id = $post-&gt;ID;\n }\n else {\n $ancestor_id = $ancestor[0];\n }\n\n // Get childpages from ancestor\n $pages = wp_list_pages( array(\n 'child_of' =&gt; $ancestor_id,\n 'title_li' =&gt; '',\n 'echo' =&gt; 0\n ) );\n\n $string = '&lt;ul id=\"child-menu\"&gt;';\n // Ancestor is not included in the $pages so add this manually\n $string .= '&lt;li class=\"ancestor\"&gt;&lt;a href=\"' . get_the_permalink( $ancestor_id ) . '\"&gt;' . get_the_title( $ancestor_id ) . '&lt;/a&gt;&lt;/li&gt;';\n $string .= '&lt;ul class=\"children\"&gt;';\n $string .= $pages;\n $string .= '&lt;/ul&gt;';\n $string .= '&lt;/ul&gt;';\n\n return $string;\n }\n}\nadd_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');\n</code></pre>\n" } ]
2016/03/02
[ "https://wordpress.stackexchange.com/questions/219471", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44597/" ]
I have a little problem. This is my page structure: ``` Ancestor Parent Child 1 Child 2 Child 3 Child 4 ``` What i try to do is when i'm on Child 4 i want to show Child 2. And when i'm on Child 2 i want to show Parent. But i can't figure out how to do this. The code that i use is this: ``` function wpb_list_child_pages_popup() { global $post; if ( is_page() && $post->post_parent ) $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' ); else $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' ); if ( $childpages ) { $string = '<ul id="child-menu">' . $childpages . '</ul>'; } return $string; } add_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup'); ```
You need to look at `get_ancestors()` to get the top level parent of a page. Just a note, for reliability, use `get_queried_object()` (*or even better `$GLOBALS['wp_the_query']->get_queried_object()`*) to get the current post/page object on singular pages, `$post` can be quite unreliable You can try the following in your shortcode: ``` $post = $GLOBALS['wp_the_query']->get_queried_object(); // Make sure the current page is not top level if ( 0 === (int) $post->post_parent ) { $parent = $post->ID; } else { $ancestors = get_ancestors( $post->ID, $post->post_type ); $parent = end( $ancestors ); } ``` `$parent` will now always hold the top level parent of any given page EDIT - from comments -------------------- If you need to get the page two levels higher than the current one, you can still use the same approach, but insted of using the last ID from `get\_ancestors (*which is the top level parent*), we need to adjust this to get the second entry Lets modify the code above slightly ``` $post = $GLOBALS['wp_the_query']->get_queried_object(); // Make sure the current page is not top level if ( 0 === (int) $post->post_parent ) { $parent = $post->ID; } else { $ancestors = get_ancestors( $post->ID, $post->post_type ); // Check if $ancestors have at least two key/value pairs if ( 1 == count( $ancestors ) ) { $parent = $post->post_parent; } esle { $parent = $ancestors[1]; // Gets the parent two levels higher } } ``` LAST EDIT - full code --------------------- ``` function wpb_list_child_pages_popup() { // Define our $string variable $string = ''; // Make sure this is a page if ( !is_page() ) return $string; $post = $GLOBALS['wp_the_query']->get_queried_object(); // Make sure the current page is not top level if ( 0 === (int) $post->post_parent ) { $parent = $post->ID; } else { $ancestors = get_ancestors( $post->ID, $post->post_type ); // Check if $ancestors have at least two key/value pairs if ( 1 == count( $ancestors ) ) { $parent = $post->post_parent; } else { $parent = $ancestors[1]; // Gets the parent two levels higher } } $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $parent . '&echo=0' ); $string .= '<ul id="child-menu">' . $childpages . '</ul>'; return $string; } add_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup'); ```
219,483
<p>I am adding a <code>#section</code> as a custom link to my menu, because I want to scroll to that section when I click on that link. When I'm on the home page, this works fine (the section is on the home page), but when I'm not, and I click on it nothing happens, because it treats the link as just <code>#section</code>.</p> <p>That is, when I'm on second page:</p> <pre><code>http://127.0.0.1/second-page </code></pre> <p>and I click on the <code>#section</code> link in the menu, it tries to do</p> <pre><code>http://127.0.0.1/second-page/#section </code></pre> <p>instead of </p> <pre><code>http://127.0.0.1/#section </code></pre> <p>Now, the site is still in development, so it's set via IP address. But that shouldn't matter. The issue is that I've tried to set the custom link in the wordpress backend as</p> <pre><code>http://127.0.0.1/#section </code></pre> <p>and while in the backend this looks like that, on my menu on the front end I only see</p> <pre><code>&lt;a href="#section"&gt;Section&lt;/a&gt; </code></pre> <p>The menu walker that controls the menu output looks like this:</p> <pre><code>&lt;?php // Allow HTML descriptions in WordPress Menu remove_filter( 'nav_menu_description', 'strip_tags' ); function my_plugin_wp_setup_nav_menu_item( $menu_item ) { if ( isset( $menu_item-&gt;post_type ) ) { if ( 'nav_menu_item' == $menu_item-&gt;post_type ) { $menu_item-&gt;description = apply_filters( 'nav_menu_description', $menu_item-&gt;post_content ); } } return $menu_item; } add_filter( 'wp_setup_nav_menu_item', 'my_plugin_wp_setup_nav_menu_item' ); // Menu without icons class my_walker_nav_menu extends Walker_Nav_Menu { public function display_element($el, &amp;$children, $max_depth, $depth = 0, $args, &amp;$output){ $id = $this-&gt;db_fields['id']; if(isset($children[$el-&gt;$id])){ $el-&gt;classes[] = 'has_children'; } parent::display_element($el, $children, $max_depth, $depth, $args, $output); } // add classes to ul sub-menus function start_lvl( &amp;$output, $depth = 0, $args = array() ) { // depth dependent classes $indent = ( $depth &gt; 0 ? str_repeat( "\t", $depth ) : '' ); // code indent $display_depth = ( $depth + 1); // because it counts the first submenu as 0 $classes = array( 'navi', ( $display_depth ==1 ? 'first' : '' ), ( $display_depth &gt;=2 ? 'navi' : '' ), 'menu-depth-' . $display_depth ); $class_names = implode( ' ', $classes ); // build html $output .= "\n" . $indent . '&lt;ul class="' . esc_attr($class_names) . '"&gt;' . "\n"; } // add main/sub classes to li's and links function start_el( &amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth &gt; 0 ? str_repeat( "\t", $depth ) : '' ); // code indent static $is_first; $is_first++; // depth dependent classes $depth_classes = array( ( $depth == 0 ? 'main-menu-item' : '' ), ( $depth &gt;=2 ? 'navi' : '' ), ( $is_first ==1 ? 'menu-first' : '' ), 'menu-item-depth-' . $depth ); $depth_class_names = esc_attr( implode( ' ', $depth_classes ) ); // passed classes $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false; $use_desc = (strpos($class_names,'use_desc') !== false) ? true : false; $no_title = (strpos($class_names,'no_title') !== false) ? true : false; if(!$is_mega_menu){ $class_names .= ' normal_menu_item'; } // build html $output .= $indent . '&lt;li id="nav-menu-item-'. esc_attr($item-&gt;ID) . '" class="' . esc_attr($depth_class_names) . ' ' . esc_attr($class_names) . '"&gt;'; // link attributes $attributes = ! empty( $item-&gt;attr_title ) ? ' title="' . esc_attr( $item-&gt;attr_title ) .'"' : ''; $attributes .= ! empty( $item-&gt;target ) ? ' target="' . esc_attr( $item-&gt;target ) .'"' : ''; $attributes .= ! empty( $item-&gt;xfn ) ? ' rel="' . esc_attr( $item-&gt;xfn ) .'"' : ''; $attributes .= ! empty( $item-&gt;url ) ? ' href="' . (($item-&gt;url[0] == "#" &amp;&amp; !is_front_page()) ? home_url('/') : '') . esc_attr($item-&gt;url) .'"' : ''; $attributes .= ' class="menu-link '.((strpos($item-&gt;url,'#') === false) ? '' : 'scroll').' ' . ( $depth &gt; 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"'; $html_output = ($use_desc) ? '&lt;div class="description_menu_item"&gt;'.$item-&gt;description.'&lt;/div&gt;' : ''; $item_output = (!$no_title) ? '&lt;a ' . $attributes . '&gt;&lt;span&gt;' . apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ) . '&lt;/span&gt;&lt;/a&gt;'.$html_output : $html_output; // build html $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ).(($is_mega_menu)?'&lt;div class="sf-mega"&gt;&lt;div class="sf-mega-inner clearfix"&gt;':''); } function end_el( &amp;$output, $item, $depth = 0, $args = array() ) { $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false; $output .= (($is_mega_menu)?'&lt;/div&gt;&lt;/div&gt;':'') . "&lt;/li&gt;\n"; } } </code></pre> <p>The anchor is controlled with this line:</p> <pre><code>$attributes .= ! empty( $item-&gt;url ) ? ' href="' . (($item-&gt;url[0] == "#" &amp;&amp; !is_front_page()) ? home_url('/') : '') . esc_attr($item-&gt;url) .'"' : ''; </code></pre> <p>It even says that if the url has <code>#</code> in it, and if it's not front page, that it should add a <code>home_url()</code> to it.</p> <p>Without this I cannot scroll to the section on the first page from other pages. </p> <p>Why is it doing this? Because the address is IP instead of www?</p> <p><strong>ANSWER</strong></p> <p>Apparently I didn't call the walker instance in my <code>wp_nav_menu()</code>. <em>feels dumb</em></p> <p>It works now. Sorry for not checking this sooner.</p>
[ { "answer_id": 219482, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": true, "text": "<p>You need to look at <code>get_ancestors()</code> to get the top level parent of a page. Just a note, for reliability, use <code>get_queried_object()</code> (<em>or even better <code>$GLOBALS['wp_the_query']-&gt;get_queried_object()</code></em>) to get the current post/page object on singular pages, <code>$post</code> can be quite unreliable</p>\n\n<p>You can try the following in your shortcode:</p>\n\n<pre><code>$post = $GLOBALS['wp_the_query']-&gt;get_queried_object();\n// Make sure the current page is not top level\nif ( 0 === (int) $post-&gt;post_parent ) {\n $parent = $post-&gt;ID;\n} else {\n $ancestors = get_ancestors( $post-&gt;ID, $post-&gt;post_type );\n $parent = end( $ancestors );\n}\n</code></pre>\n\n<p><code>$parent</code> will now always hold the top level parent of any given page</p>\n\n<h2>EDIT - from comments</h2>\n\n<p>If you need to get the page two levels higher than the current one, you can still use the same approach, but insted of using the last ID from `get_ancestors (<em>which is the top level parent</em>), we need to adjust this to get the second entry</p>\n\n<p>Lets modify the code above slightly</p>\n\n<pre><code>$post = $GLOBALS['wp_the_query']-&gt;get_queried_object();\n// Make sure the current page is not top level\nif ( 0 === (int) $post-&gt;post_parent ) {\n $parent = $post-&gt;ID;\n} else {\n $ancestors = get_ancestors( $post-&gt;ID, $post-&gt;post_type );\n // Check if $ancestors have at least two key/value pairs\n if ( 1 == count( $ancestors ) ) {\n $parent = $post-&gt;post_parent;\n } esle {\n $parent = $ancestors[1]; // Gets the parent two levels higher\n }\n}\n</code></pre>\n\n<h2>LAST EDIT - full code</h2>\n\n<pre><code>function wpb_list_child_pages_popup() \n{\n // Define our $string variable\n $string = '';\n\n // Make sure this is a page\n if ( !is_page() )\n return $string;\n\n $post = $GLOBALS['wp_the_query']-&gt;get_queried_object();\n // Make sure the current page is not top level\n if ( 0 === (int) $post-&gt;post_parent ) {\n $parent = $post-&gt;ID;\n } else {\n $ancestors = get_ancestors( $post-&gt;ID, $post-&gt;post_type );\n // Check if $ancestors have at least two key/value pairs\n if ( 1 == count( $ancestors ) ) {\n $parent = $post-&gt;post_parent;\n } else {\n $parent = $ancestors[1]; // Gets the parent two levels higher\n }\n } \n\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $parent . '&amp;echo=0' );\n\n $string .= '&lt;ul id=\"child-menu\"&gt;' . $childpages . '&lt;/ul&gt;';\n\n return $string;\n\n}\n\nadd_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');\n</code></pre>\n" }, { "answer_id": 219485, "author": "Jebble", "author_id": 81939, "author_profile": "https://wordpress.stackexchange.com/users/81939", "pm_score": 1, "selected": false, "text": "<p>I don't completely understand what your question is, mainly because you're talking about parents and childs but this will never show the parent of a page let alone the grandparent.</p>\n\n<p>I've commented your code down here to show you what exactly what is happenign in the code.</p>\n\n<pre><code>function wpb_list_child_pages_popup() { \n\n // Get the current WP Post object\n global $post;\n\n /**\n * If post_type of current WP Post object is 'page'\n * and the post_parent in the WP Post object is set\n */\n if ( is_page() &amp;&amp; $post-&gt;post_parent )\n /**\n * Get all wordpress pages that are a child of this pages parent.\n * In other words get THIS page and all it's siblings\n */\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;post_parent . '&amp;echo=0' );\n /**\n * If this page doesn't have a parent\n */\n else\n /**\n * Get all wordpress pages that are a child of this page\n */\n $childpages = wp_list_pages( 'sort_column=menu_order&amp;title_li=&amp;child_of=' . $post-&gt;ID . '&amp;echo=0' );\n\n if ( $childpages ) {\n\n $string = '&lt;ul id=\"child-menu\"&gt;' . $childpages . '&lt;/ul&gt;';\n }\n\n return $string;\n\n}\n\nadd_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');\n</code></pre>\n\n<p>What I'm guessing is that you simply want a list with alle pages that are \"connected\" by being a (grand)parent, (grand)child, or sibling.\nThis function returns a string that contains all of that no matter which of the siblings you're on.</p>\n\n<pre><code>function wpb_list_child_pages_popup() {\n\n // Get the current WP Post object\n global $post;\n\n if ( is_page() ) {\n\n /**\n * Get 'first' parent, the highest ranking post parent which is the ancestor of all.\n * @var array\n */\n $ancestor = array_reverse( get_post_ancestors( $post-&gt;ID ) );\n // If there is no ancestor, set ancestor to this page.\n if ( empty( $ancestor ) ) {\n $ancestor_id = $post-&gt;ID;\n }\n else {\n $ancestor_id = $ancestor[0];\n }\n\n // Get childpages from ancestor\n $pages = wp_list_pages( array(\n 'child_of' =&gt; $ancestor_id,\n 'title_li' =&gt; '',\n 'echo' =&gt; 0\n ) );\n\n $string = '&lt;ul id=\"child-menu\"&gt;';\n // Ancestor is not included in the $pages so add this manually\n $string .= '&lt;li class=\"ancestor\"&gt;&lt;a href=\"' . get_the_permalink( $ancestor_id ) . '\"&gt;' . get_the_title( $ancestor_id ) . '&lt;/a&gt;&lt;/li&gt;';\n $string .= '&lt;ul class=\"children\"&gt;';\n $string .= $pages;\n $string .= '&lt;/ul&gt;';\n $string .= '&lt;/ul&gt;';\n\n return $string;\n }\n}\nadd_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup');\n</code></pre>\n" } ]
2016/03/02
[ "https://wordpress.stackexchange.com/questions/219483", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58895/" ]
I am adding a `#section` as a custom link to my menu, because I want to scroll to that section when I click on that link. When I'm on the home page, this works fine (the section is on the home page), but when I'm not, and I click on it nothing happens, because it treats the link as just `#section`. That is, when I'm on second page: ``` http://127.0.0.1/second-page ``` and I click on the `#section` link in the menu, it tries to do ``` http://127.0.0.1/second-page/#section ``` instead of ``` http://127.0.0.1/#section ``` Now, the site is still in development, so it's set via IP address. But that shouldn't matter. The issue is that I've tried to set the custom link in the wordpress backend as ``` http://127.0.0.1/#section ``` and while in the backend this looks like that, on my menu on the front end I only see ``` <a href="#section">Section</a> ``` The menu walker that controls the menu output looks like this: ``` <?php // Allow HTML descriptions in WordPress Menu remove_filter( 'nav_menu_description', 'strip_tags' ); function my_plugin_wp_setup_nav_menu_item( $menu_item ) { if ( isset( $menu_item->post_type ) ) { if ( 'nav_menu_item' == $menu_item->post_type ) { $menu_item->description = apply_filters( 'nav_menu_description', $menu_item->post_content ); } } return $menu_item; } add_filter( 'wp_setup_nav_menu_item', 'my_plugin_wp_setup_nav_menu_item' ); // Menu without icons class my_walker_nav_menu extends Walker_Nav_Menu { public function display_element($el, &$children, $max_depth, $depth = 0, $args, &$output){ $id = $this->db_fields['id']; if(isset($children[$el->$id])){ $el->classes[] = 'has_children'; } parent::display_element($el, $children, $max_depth, $depth, $args, $output); } // add classes to ul sub-menus function start_lvl( &$output, $depth = 0, $args = array() ) { // depth dependent classes $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent $display_depth = ( $depth + 1); // because it counts the first submenu as 0 $classes = array( 'navi', ( $display_depth ==1 ? 'first' : '' ), ( $display_depth >=2 ? 'navi' : '' ), 'menu-depth-' . $display_depth ); $class_names = implode( ' ', $classes ); // build html $output .= "\n" . $indent . '<ul class="' . esc_attr($class_names) . '">' . "\n"; } // add main/sub classes to li's and links function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { global $wp_query; $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent static $is_first; $is_first++; // depth dependent classes $depth_classes = array( ( $depth == 0 ? 'main-menu-item' : '' ), ( $depth >=2 ? 'navi' : '' ), ( $is_first ==1 ? 'menu-first' : '' ), 'menu-item-depth-' . $depth ); $depth_class_names = esc_attr( implode( ' ', $depth_classes ) ); // passed classes $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false; $use_desc = (strpos($class_names,'use_desc') !== false) ? true : false; $no_title = (strpos($class_names,'no_title') !== false) ? true : false; if(!$is_mega_menu){ $class_names .= ' normal_menu_item'; } // build html $output .= $indent . '<li id="nav-menu-item-'. esc_attr($item->ID) . '" class="' . esc_attr($depth_class_names) . ' ' . esc_attr($class_names) . '">'; // link attributes $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . (($item->url[0] == "#" && !is_front_page()) ? home_url('/') : '') . esc_attr($item->url) .'"' : ''; $attributes .= ' class="menu-link '.((strpos($item->url,'#') === false) ? '' : 'scroll').' ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"'; $html_output = ($use_desc) ? '<div class="description_menu_item">'.$item->description.'</div>' : ''; $item_output = (!$no_title) ? '<a ' . $attributes . '><span>' . apply_filters( 'the_title', $item->title, $item->ID ) . '</span></a>'.$html_output : $html_output; // build html $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ).(($is_mega_menu)?'<div class="sf-mega"><div class="sf-mega-inner clearfix">':''); } function end_el( &$output, $item, $depth = 0, $args = array() ) { $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); $is_mega_menu = (strpos($class_names,'mega') !== false) ? true : false; $output .= (($is_mega_menu)?'</div></div>':'') . "</li>\n"; } } ``` The anchor is controlled with this line: ``` $attributes .= ! empty( $item->url ) ? ' href="' . (($item->url[0] == "#" && !is_front_page()) ? home_url('/') : '') . esc_attr($item->url) .'"' : ''; ``` It even says that if the url has `#` in it, and if it's not front page, that it should add a `home_url()` to it. Without this I cannot scroll to the section on the first page from other pages. Why is it doing this? Because the address is IP instead of www? **ANSWER** Apparently I didn't call the walker instance in my `wp_nav_menu()`. *feels dumb* It works now. Sorry for not checking this sooner.
You need to look at `get_ancestors()` to get the top level parent of a page. Just a note, for reliability, use `get_queried_object()` (*or even better `$GLOBALS['wp_the_query']->get_queried_object()`*) to get the current post/page object on singular pages, `$post` can be quite unreliable You can try the following in your shortcode: ``` $post = $GLOBALS['wp_the_query']->get_queried_object(); // Make sure the current page is not top level if ( 0 === (int) $post->post_parent ) { $parent = $post->ID; } else { $ancestors = get_ancestors( $post->ID, $post->post_type ); $parent = end( $ancestors ); } ``` `$parent` will now always hold the top level parent of any given page EDIT - from comments -------------------- If you need to get the page two levels higher than the current one, you can still use the same approach, but insted of using the last ID from `get\_ancestors (*which is the top level parent*), we need to adjust this to get the second entry Lets modify the code above slightly ``` $post = $GLOBALS['wp_the_query']->get_queried_object(); // Make sure the current page is not top level if ( 0 === (int) $post->post_parent ) { $parent = $post->ID; } else { $ancestors = get_ancestors( $post->ID, $post->post_type ); // Check if $ancestors have at least two key/value pairs if ( 1 == count( $ancestors ) ) { $parent = $post->post_parent; } esle { $parent = $ancestors[1]; // Gets the parent two levels higher } } ``` LAST EDIT - full code --------------------- ``` function wpb_list_child_pages_popup() { // Define our $string variable $string = ''; // Make sure this is a page if ( !is_page() ) return $string; $post = $GLOBALS['wp_the_query']->get_queried_object(); // Make sure the current page is not top level if ( 0 === (int) $post->post_parent ) { $parent = $post->ID; } else { $ancestors = get_ancestors( $post->ID, $post->post_type ); // Check if $ancestors have at least two key/value pairs if ( 1 == count( $ancestors ) ) { $parent = $post->post_parent; } else { $parent = $ancestors[1]; // Gets the parent two levels higher } } $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $parent . '&echo=0' ); $string .= '<ul id="child-menu">' . $childpages . '</ul>'; return $string; } add_shortcode('wpb_childpages_popup', 'wpb_list_child_pages_popup'); ```
219,531
<p>Hi I have created two custom fields - both of them should be required, but when I fill out username and correct email, the error messages are skipped and user gets registered. If there is an error in username or email, it writes the messages correctly. Could anybody give me a helping hand?</p> <pre><code>//1. Add a new form element... add_action( 'register_form', 'myplugin_register_form' ); function myplugin_register_form() { $first_name = ( ! empty( $_POST['first_name'] ) ) ? trim( $_POST['first_name'] ) : ''; ?&gt; &lt;p&gt; &lt;label for="first_name"&gt;&lt;?php _e( 'Jméno a příjmení', 'faveaplus' ) ?&gt;&lt;br /&gt; &lt;input type="text" name="first_name" id="first_name" class="input" value="&lt;?php echo esc_attr( wp_unslash( $first_name ) ); ?&gt;" size="25" /&gt;&lt;/label&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="subscribe"&gt; &lt;input type="checkbox" name="subscribe" value="1" /&gt; Prohlašuji, že jsem pracovník ve zdravotnictví s oprávněním předepisovat nebo vydávat humánní léčivé přípravky (lékař nebo farmaceut). &lt;/label&gt; &lt;/p&gt; &lt;?php } //2. Add validation. In this case, we make sure first_name is required. add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 ); function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) { if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) &amp;&amp; trim( $_POST['first_name'] ) == '' ) { $errors-&gt;add( 'first_name_error', __( '&lt;strong&gt;CHYBA&lt;/strong&gt;: Musíte uvést své jméno a příjmení.', 'faveaplus' ) ); } if ($_POST['subscribe'] != "checked") { $errors-&gt;add( 'subscribe_error', __( '&lt;strong&gt;CHYBA&lt;/strong&gt;: Musíte prohlásit, že jste pracovník ve zdravotnictví', 'faveaplus' ) ); } return $errors; } </code></pre>
[ { "answer_id": 219535, "author": "locomo", "author_id": 42754, "author_profile": "https://wordpress.stackexchange.com/users/42754", "pm_score": 1, "selected": false, "text": "<p>the value of the checkbox wouldn't be \"checked\" - it should equal whatever you put in the \"value\" attribute .. and i think you need an extra set of parentheses in the if statement for first_name</p>\n\n<p>to make sure your filter is firing you could try explicitly adding an error (with no validation checks) to see if you can force registration to fail</p>\n\n<pre><code>//2. Add validation. In this case, we make sure first_name is required.\nadd_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );\nfunction myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {\n\n if ( empty( $_POST['first_name'] ) || ( ! empty( $_POST['first_name'] ) &amp;&amp; trim( $_POST['first_name'] ) == '' ) ) {\n $errors-&gt;add( 'first_name_error', __( '&lt;strong&gt;CHYBA&lt;/strong&gt;: Musíte uvést své jméno a příjmení.', 'faveaplus' ) );\n }\n if ( empty($_POST['subscribe']) ) {\n $errors-&gt;add( 'subscribe_error', __( '&lt;strong&gt;CHYBA&lt;/strong&gt;: Musíte prohlásit, že jste pracovník ve zdravotnictví', 'faveaplus' ) );\n }\n\n return $errors;\n}\n</code></pre>\n" }, { "answer_id": 219660, "author": "Karolína Vyskočilová", "author_id": 64771, "author_profile": "https://wordpress.stackexchange.com/users/64771", "pm_score": 1, "selected": true, "text": "<p>I've found my answer - unfortunatelly I've forgotten to mention that I'm using <strong>at same time the plugin New User Approve</strong> and that's what has been causing the problem of accepting before firing errors. Finally, thanks to @locomo I have google the right thing.</p>\n\n<p>Answer found here: <a href=\"https://wordpress.org/support/topic/registration_errors-filter-problem\" rel=\"nofollow\">https://wordpress.org/support/topic/registration_errors-filter-problem</a></p>\n\n<blockquote>\n <p>The new user is created in send_approval_email(). This function is\n called using the register_post action hook. Unfortunately,\n register_post fires before registration_errors so there is no way to\n validate data.</p>\n</blockquote>\n\n<p><strong>The solution:</strong></p>\n\n<p>replace this code (adding the validation):</p>\n\n<pre><code>add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );\n</code></pre>\n\n<p>with following</p>\n\n<pre><code>add_filter( 'register_post', 'myplugin_registration_errors', 9, 3 );\n</code></pre>\n\n<p>two changes have been made: <code>registration_errors</code> become <code>register_post</code> and <code>10</code> has been changed to <code>9</code> to have it fired at the right time.</p>\n" }, { "answer_id": 372765, "author": "Sven Möller", "author_id": 182093, "author_profile": "https://wordpress.stackexchange.com/users/182093", "pm_score": 0, "selected": false, "text": "<p>@kybernaut.cz is right but there is an additional third change to be made.</p>\n<pre><code>function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email )\n</code></pre>\n<p>Replace with</p>\n<pre><code>function myplugin_registration_errors( $sanitized_user_login, $user_email, $errors )\n</code></pre>\n<p>Then you would have no problem at all.\nRemember to change <code>$errors</code> variable position.</p>\n" } ]
2016/03/02
[ "https://wordpress.stackexchange.com/questions/219531", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64771/" ]
Hi I have created two custom fields - both of them should be required, but when I fill out username and correct email, the error messages are skipped and user gets registered. If there is an error in username or email, it writes the messages correctly. Could anybody give me a helping hand? ``` //1. Add a new form element... add_action( 'register_form', 'myplugin_register_form' ); function myplugin_register_form() { $first_name = ( ! empty( $_POST['first_name'] ) ) ? trim( $_POST['first_name'] ) : ''; ?> <p> <label for="first_name"><?php _e( 'Jméno a příjmení', 'faveaplus' ) ?><br /> <input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr( wp_unslash( $first_name ) ); ?>" size="25" /></label> </p> <p> <label for="subscribe"> <input type="checkbox" name="subscribe" value="1" /> Prohlašuji, že jsem pracovník ve zdravotnictví s oprávněním předepisovat nebo vydávat humánní léčivé přípravky (lékař nebo farmaceut). </label> </p> <?php } //2. Add validation. In this case, we make sure first_name is required. add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 ); function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) { if ( empty( $_POST['first_name'] ) || ! empty( $_POST['first_name'] ) && trim( $_POST['first_name'] ) == '' ) { $errors->add( 'first_name_error', __( '<strong>CHYBA</strong>: Musíte uvést své jméno a příjmení.', 'faveaplus' ) ); } if ($_POST['subscribe'] != "checked") { $errors->add( 'subscribe_error', __( '<strong>CHYBA</strong>: Musíte prohlásit, že jste pracovník ve zdravotnictví', 'faveaplus' ) ); } return $errors; } ```
I've found my answer - unfortunatelly I've forgotten to mention that I'm using **at same time the plugin New User Approve** and that's what has been causing the problem of accepting before firing errors. Finally, thanks to @locomo I have google the right thing. Answer found here: <https://wordpress.org/support/topic/registration_errors-filter-problem> > > The new user is created in send\_approval\_email(). This function is > called using the register\_post action hook. Unfortunately, > register\_post fires before registration\_errors so there is no way to > validate data. > > > **The solution:** replace this code (adding the validation): ``` add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 ); ``` with following ``` add_filter( 'register_post', 'myplugin_registration_errors', 9, 3 ); ``` two changes have been made: `registration_errors` become `register_post` and `10` has been changed to `9` to have it fired at the right time.
219,567
<p>I am try to hide the metabox fields with empty value like</p> <pre> $Product_Brennwert = get_post_meta(get_the_ID(), 'Product_Brennwert', true); if ( ! empty ( $Product_Brennwert ) ) { echo 'Brennwert '. $Product_power . ' '; } </pre> <p>now i am try to add this in my php file but no idea how to add this in table can some on help me to do this?</p> <p>part of my php file <a href="http://pastebin.com/etJHPb0u" rel="nofollow">Single.PHP </a></p>
[ { "answer_id": 219536, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>The two overarching advantages are:</p>\n\n<ol>\n<li>You can (eventually) do all admin tasks without the admin interface.</li>\n<li>You can get all data for display and eliminate the front end (and writing PHP) completely.</li>\n</ol>\n\n<p>Regarding your example specifically-</p>\n\n<p>Replace steps 3 &amp; 4 with the REST API, and replace steps 1, 2, and 5 with Backbone.js. BOOM, dynamic web application. Or maybe you're more comfortable doing the complex routing necessary for your site with Python instead.</p>\n" }, { "answer_id": 219547, "author": "Nick F", "author_id": 59505, "author_profile": "https://wordpress.stackexchange.com/users/59505", "pm_score": 0, "selected": false, "text": "<p>In addition to the 2 great points @Milo mentioned, I specifically use the REST API to expose my data to non-WordPress applications. We have a Chrome extension that pulls information from our WordPress database, and this is accomplished by hitting REST API endpoints with POST requests.</p>\n" }, { "answer_id": 219555, "author": "Colton McCormack", "author_id": 89876, "author_profile": "https://wordpress.stackexchange.com/users/89876", "pm_score": 2, "selected": false, "text": "<p>Well, a few things actually. </p>\n\n<ol>\n<li><p>It lets you run specific functions as needed, rather than requiring all of the computation of an entire page load. So, you could update the comments periodically with fairly low overhead without needing a page refresh by just calling that API endpoint and updating the data on your page. This concept will eventually be extrapolated into SPAs (single page applications) which load the \"client\" site quickly once, and emulates all page \"changes\" without needing to re-pull the page's HTML each time. This is already very popular with the advent of frameworks such as Angular, Ember, and React. Sites may respond with blazing speed, while both offloading some computational power to the end-user (render cycle, non-business logic) and reducing the overall number of calls to the server significantly (only pull the data that you need, rather than reloading everything each time).</p></li>\n<li><p>It separates the business logic and the renderer. Yes, you can use the API with another PHP site spitting out the results, or handle it with Javascript like you mentioned, but you can also consume it with a native mobile application, desktop application, etc. Not only that, but you could have one of each all talking to the same API, which consistently performs the same business logic, which in turn creates consistency and reliability across the various clients consuming the API.</p></li>\n</ol>\n\n<p>APIs are good because they separate the concerns of logic and display.</p>\n" }, { "answer_id": 219561, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 4, "selected": true, "text": "<p>At its current state, it is a badly engineered feature that do not have any real advantage for a competent developer.</p>\n\n<p>The basic idea, as it stands at the time this answer is written, is to expose WordPress core functionality as JSON REST API. This will enable decoupling of the WordPress \"business\" logic from the UI and enable creating different full or partial UIs to manage and extract information from wordpress. This by itself is not a revolution, but an evolution. just a replacement of the XML-RPC API which by itself kinda streamlines the HTTP based for submission API.</p>\n\n<p>As with any evolution, at each step you might ask yourself, what advantage do you get from the former state, and the answer is probably \"not much\", but hopefully the steps do accumulate to a big difference.</p>\n\n<p>So why the negative preface to this answer? Because my experience as software developer is that it is rarely possible to design a generic API that is actually useful without having concrete use cases to answer to. A concrete use case here can be replacing the XML-RPC API for automated wordpress management, but any front end related has to be site specific and since there is a huge performance penalty for every request sent from the client to the server you can not just aggregate use of different API to get the result you want in a way in which the users will remain happy. This means that for front end, for non trivial usage, there will still be very little difference in development effort between using the AJAX route and the REST-API route.</p>\n" }, { "answer_id": 238027, "author": "Jeremy Ross", "author_id": 102007, "author_profile": "https://wordpress.stackexchange.com/users/102007", "pm_score": 2, "selected": false, "text": "<p>The WordPress REST API is the new hotness. With single page js driven applications, and WordPresses desire to become an app platform this makes a lot of sense. The plan is to replace XML-RPC with the REST API (which is a good thing for security reasons alone!)</p>\n\n<p><a href=\"https://make.wordpress.org/core/2015/09/21/wp-rest-api-merge-proposal/\" rel=\"nofollow\">https://make.wordpress.org/core/2015/09/21/wp-rest-api-merge-proposal/</a></p>\n\n<ul>\n<li>The New York times new site is built on it, <a href=\"https://www.godaddy.com/garage/webpro/wordpress/3-practical-use-cases-wp-rest-api/\" rel=\"nofollow\">apparently</a>.</li>\n<li>It allows mobile apps and other external services to access wp content (like <a href=\"http://wp-cli.org/restful/\" rel=\"nofollow\">wp-cli</a>)</li>\n<li>It allows developers to build a single-page app front end with their\nfavorite JSON consuming framework of the week, and have all of the\ncool interactions at their fingertips.</li>\n<li>It allows for separation of concerns (as mentioned above) and greater independence between the back-end and front-end teams.</li>\n</ul>\n\n<p>It's another set of tools to take WordPress forward. And, although it's been a meandering journey to get to where we are, I think it's worth taking the time to explore and understand it.</p>\n" }, { "answer_id": 276679, "author": "Divyanshu Jimmy", "author_id": 92345, "author_profile": "https://wordpress.stackexchange.com/users/92345", "pm_score": 1, "selected": false, "text": "<p><strong>First things first - REST is lightweight</strong> </p>\n\n<p>In one line -\nWhen we use REST APIs we do all data rendering at client side (loops , conditions and server side calls etc. ) saving bandwidth and at the same time our application becomes ready for any mobile platform , 3rd party integrations and modularized (sepration of concern between frontend and server side ). </p>\n\n<p>Dont you want this ? </p>\n" }, { "answer_id": 287957, "author": "Armstrongest", "author_id": 37479, "author_profile": "https://wordpress.stackexchange.com/users/37479", "pm_score": 0, "selected": false, "text": "<h3>CONSISTENT Infrastructure</h3>\n<p>The REST API is consistent and human-readable. It's self-documenting.</p>\n<p><code>GET wp-json/wp/v2/posts</code> is pretty clear what it does. It <code>GET</code>s some posts.</p>\n<p>You have a namespace: <code>wp</code>, a version: <code>v2</code> and an object collection <code>posts</code></p>\n<p>Can you guess what: <code>GET wp-json/wp/v2/posts/5</code> does?\nHow about : <code>GET wp-json/wp/v2/posts/5/comments</code>\nHow about: <code>GET wp-json/shop/v2/orders/345/lines/11/price</code></p>\n<p>A developer can easily guess by looking at that, it's going to get the price of line <code>11</code> on order <code>345</code> even without reading the documentation. The dev can even easily tell that it's coming from the <code>shop</code> Plugin as it is namespaced.</p>\n<p>How about <code>POST /wp-json/v2/posts title=New Blog Post</code>\nHow about <code>PUT /wp-json/v2/posts title=New Title</code></p>\n<p>That's pretty clear as well. It makes a new post. By the way, it returns the ID of the new post. It's not about AJAX OR the REST API. AJAX is simply a technology that <strong>accesses</strong> the REST API. Whereas, before, you would have to come up with a bunch of abstract ajax function names like:\n<code>get_price_for_lineitem( $order, $line )</code>. Is that going to return just a number, or a JSON object? I'm not sure, where's the documentation. Oh... was the ajax call <code>get_order_line_price</code> or <code>get_lineitem_price</code>.</p>\n<p>The developer doesn't have to make these decisions, because the existing <code>wp-json</code> api provides a good <strong>base model</strong> to follow when creating your own endpoints. Sure, a plugin or api developer can break these rules, but in general it's easier to follow a standard that's already been set and most developers would much rather follow a pattern already set ( see how pervasive jQuery patterns are now ).</p>\n<h3>ABSTRACTION without distraction</h3>\n<p>Do I care about how <code>POST /wp-json/mysite/v1/widgets title=Foobar</code> works? Nope. I just want to create a new <code>Widget</code> and I want the ID in return. I wanna do it from a form on my front end without refreshing the page. If I make a request to a URL, I don't care if it's PHP,C#, ASP.NET or any other technology. I just want to create a new Widget.</p>\n<p>The REST API decouples the backend from the front. Technically, if your API is good enough, you could change your entire backend stack. As long as you maintained the same REST API structure, anything that depended on the API would not be affected.</p>\n<p>If your REST API is simple and consistent enough, using a noun like <code>Widgets</code> as a collection of objects and noun/identifier like <code>Widget/2</code> to indicate a single entity, it's really straightforward to write that API in a vastly different technology as it's more or less basic database plumbing code.</p>\n<h3>Uses Standard HTTP Request verbs.</h3>\n<p>REST APIs leverage the core of how the web works and the VERBs ( read: action ) that you use map to standard data CRUD functions.</p>\n<pre><code>CREATE : POST\nREAD : GET\nUPDATE : PUT/PATCH\nDELETE : DELETE\n</code></pre>\n<p>There are more HTTP verbs, but those are the basics. Every single request over the internet uses these verbs. A REST API sits right on top of the model the web is built upon requests. No need for any communication layer or abstraction model in between. It's just a standard http request to a URL and it returns a response. You can not get much simpler than that.</p>\n<p>Essentially, it makes a developer more aware of the nuts and bolts of how the web actually works and when you get closer to understanding how the underlying protocols work, you end up making a more efficient better product.</p>\n" } ]
2016/03/03
[ "https://wordpress.stackexchange.com/questions/219567", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24876/" ]
I am try to hide the metabox fields with empty value like ``` $Product_Brennwert = get_post_meta(get_the_ID(), 'Product_Brennwert', true); if ( ! empty ( $Product_Brennwert ) ) { echo 'Brennwert '. $Product_power . ' '; } ``` now i am try to add this in my php file but no idea how to add this in table can some on help me to do this? part of my php file [Single.PHP](http://pastebin.com/etJHPb0u)
At its current state, it is a badly engineered feature that do not have any real advantage for a competent developer. The basic idea, as it stands at the time this answer is written, is to expose WordPress core functionality as JSON REST API. This will enable decoupling of the WordPress "business" logic from the UI and enable creating different full or partial UIs to manage and extract information from wordpress. This by itself is not a revolution, but an evolution. just a replacement of the XML-RPC API which by itself kinda streamlines the HTTP based for submission API. As with any evolution, at each step you might ask yourself, what advantage do you get from the former state, and the answer is probably "not much", but hopefully the steps do accumulate to a big difference. So why the negative preface to this answer? Because my experience as software developer is that it is rarely possible to design a generic API that is actually useful without having concrete use cases to answer to. A concrete use case here can be replacing the XML-RPC API for automated wordpress management, but any front end related has to be site specific and since there is a huge performance penalty for every request sent from the client to the server you can not just aggregate use of different API to get the result you want in a way in which the users will remain happy. This means that for front end, for non trivial usage, there will still be very little difference in development effort between using the AJAX route and the REST-API route.
219,568
<p>I would like to have 0 to 5, and "n/a" as possible values, however this code will output "n/a" when I want it to output a zero. How can I get it to output "0"?</p> <p>("n/a" is the placeholder if no value is set.)</p> <pre><code>Difficulty: &lt;?php if(get_field('difficulty')) { echo the_field('difficulty');} else { echo "n/a"; } ?&gt; </code></pre>
[ { "answer_id": 219570, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": -1, "selected": true, "text": "<p>In PHP, <code>0 == false == [] == '' == null</code>. A simple check to check if a variable or condition has a value will return <code>false</code> if the value is equal to 0. </p>\n\n<p>For <code>0</code> to return true as a valid value, you would need to make use of strict comparison by using the identical (<em><code>===</code></em>) operator. Just remember, if you use <code>===</code>, not only the value must match, but the type as well, otherwise the condition will return false. If your values are a string, you should use <code>'0'</code>, if they are integer values (<em>which I doubt as custom field values are strings as single values</em>), you should use <code>0</code>. </p>\n\n<p>You can do the following check</p>\n\n<pre><code>$difficulty = get_field( 'difficulty' );\nif ( $difficulty // Check if we have a valid value\n || '0' === $difficulty // This assumes '0' to be string, if integer, change to 0\n) {\n $value = $difficulty;\n} else {\n $value = 'n/a';\n}\necho 'Difficulty: ' . $value;\n</code></pre>\n" }, { "answer_id": 219572, "author": "Nik", "author_id": 89023, "author_profile": "https://wordpress.stackexchange.com/users/89023", "pm_score": -1, "selected": false, "text": "<pre><code>&lt;?php \n$some = get_field('difficulty')\nif($some != '') { echo $some;} else { echo \"n/a\"; } \n?&gt;\n</code></pre>\n\n<p><code>the_field</code> function is its self echo.</p>\n" } ]
2016/03/03
[ "https://wordpress.stackexchange.com/questions/219568", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87385/" ]
I would like to have 0 to 5, and "n/a" as possible values, however this code will output "n/a" when I want it to output a zero. How can I get it to output "0"? ("n/a" is the placeholder if no value is set.) ``` Difficulty: <?php if(get_field('difficulty')) { echo the_field('difficulty');} else { echo "n/a"; } ?> ```
In PHP, `0 == false == [] == '' == null`. A simple check to check if a variable or condition has a value will return `false` if the value is equal to 0. For `0` to return true as a valid value, you would need to make use of strict comparison by using the identical (*`===`*) operator. Just remember, if you use `===`, not only the value must match, but the type as well, otherwise the condition will return false. If your values are a string, you should use `'0'`, if they are integer values (*which I doubt as custom field values are strings as single values*), you should use `0`. You can do the following check ``` $difficulty = get_field( 'difficulty' ); if ( $difficulty // Check if we have a valid value || '0' === $difficulty // This assumes '0' to be string, if integer, change to 0 ) { $value = $difficulty; } else { $value = 'n/a'; } echo 'Difficulty: ' . $value; ```
219,583
<p>I have a custom form that allows users to make posts and also upload images with it. The images are saved in <code>wp_posts</code> as post_type = <code>attachment</code> with a <code>guid</code> to show the image.</p> <p>Now I have created a grid created with php which shows all main pictures of my posts. However, since I call the guid's of the images it loads very slow when the pictures are large.</p> <p>I know that there is some smaller thumbnail that should get saved with each image upload, but I cannot find these files in the database.</p> <p>I tried showing them with all of the following ways:</p> <pre><code>//test with ID of the post: get_the_post_thumbnail('17547'); get_the_post_thumbnail(17547, 'thumbnail'); get_the_post_thumbnail(17547, 'medium'); //test with ID of the attachment: wp_get_attachment_image(17548, 'medium' ); wp_get_attachment_image_src(17548, 'medium' ); </code></pre> <p>The two different numbers are because i tried the post ID and the attachement ID. But all of the above functions don't show me anything in the DOM...</p> <p><strong>I think that maybe the way I save the pictures doesn't allows me to use this function.</strong> But I don't know what I'm doing wrong! Does anyone know where I can look or how I can show these thumbnails?</p> <p>This is how my photo grid is made:<br> <strong>①</strong> First I get a list of ID's based on what the user searches:</p> <pre><code>$allluca01 = $wpdb-&gt;get_results(" SELECT wpp.ID, post_title FROM wp_posts AS wpp WHERE post_type = 'post' ".$plus_other_search_conditions." GROUP BY wpp.ID "); </code></pre> <p><strong>②</strong> Then I get the guid of the image. I have the attachment id saved as metavalue to a metakey called image01 (linked to post_id).</p> <pre><code>foreach($sqlsearchquery as $results){ $resultid = $results-&gt;ID; $getpicture = $wpdb-&gt;get_results(" SELECT guid AS pic FROM wp_posts LEFT JOIN wp_postmeta ON ID = meta_value WHERE post_id = '$resultid' AND meta_key = 'item_image01' "); &lt;div class="grid_item_img" style="background-image:url('&lt;? echo $getpicture[0]-&gt;pic; ?&gt;')"&gt; </code></pre> <p>As you can see I attain the <strong>guid</strong> and then I use it in my grid. <strong>I just want to obtain a guid of a smaller size of my media</strong> so I can have the grid load faster. Does anyone know how to do that?</p>
[ { "answer_id": 219587, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 0, "selected": false, "text": "<p>I am not sure how you have implemented the image upload in custom form. If you have followed standard way then you shall be able to get thumbnails using either of following:</p>\n\n<p><code>get_the_post_thumbnail( $post_id, 'thumbnail' );\n get_the_post_thumbnail( $post_id, 'medium' );</code></p>\n\n<p>If above does not work then you can give specific image size, through second argument. Simply pass size as below, and WordPress will return the image with specified size on the fly:</p>\n\n<p><code>get_the_post_thumbnail( $post_id, array(300, 300))</code></p>\n\n<p>Let me know how it goes :-)</p>\n" }, { "answer_id": 219589, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": true, "text": "<p>You can use several functions to get the URL of a image of any of the intermediate sizes created by WordPress (thumbnail, medium, large, full, or any other <a href=\"https://developer.wordpress.org/reference/functions/add_image_size/\" rel=\"nofollow\">custom size</a>).</p>\n\n<p>You can use <code>get_the_post_thumbnail()</code>/<code>the_post_thumbnail()</code>: use this function if you want <strong>to get a <code>&lt;img&gt;</code> element of the featured image of a post (aka \"post thumbnail\")</strong>. For example, to get the featured image, medium szie, of the post with ID 78:</p>\n\n<pre><code>$featured_image = get_the_post_thumbanil( 78, 'medium' );\necho $featured_image;\n</code></pre>\n\n<p>If you are within the loop, you can display the post thumbnail, medium size, of the current post as follow:</p>\n\n<pre><code>// Don't need echo\nthe_post_thumbnail( 'medium' );\n</code></pre>\n\n<p>If no image size is set, <code>get_the_post_thumbanil()</code>/<code>the_post_thumbnail()</code> use <code>post-thumbnail</code>, which is <a href=\"https://codex.wordpress.org/Function_Reference/set_post_thumbnail_size\" rel=\"nofollow\">the size registered for the post thumbanil</a> (featured image).</p>\n\n<p>If you want <strong>to get a <code>&lt;img&gt;</code> element of any image</strong>, not the post thumbnail (featured image), use <code>wp_get_attachment_image()</code>. For example, if the attachement has ID of 7898 and you want to get medium size <code>&lt;img&gt;</code>:</p>\n\n<pre><code>echo wp_get_attachment_image( 7898, 'medium' );\n</code></pre>\n\n<p>You can also use <code>wp_get_attachment_image_src()</code> if you only want to get the URL of any image (but not a <code>&lt;img&gt;</code> element):</p>\n\n<pre><code>$image_url = wp_get_attachment_image_src( $id_of_the_attachment, $size );\n</code></pre>\n\n<p>For example, if the attachement has ID of 7898 and you want to get medium size URL:</p>\n\n<pre><code>$image_url = wp_get_attachment_image_src( 7898, 'medium' );\n</code></pre>\n\n<p>In you custom query, you could select the attachment ID instead of the <code>guid</code> and use this attachment ID with <code>wp_get_attachment_image()</code> and <code>wp_get_attachment_image_src()</code>.</p>\n\n<p>Anyway, <strong>you should avoid that custom SQL queries</strong>. You are missing important WordPress hooks and several functions, template tags, filters on content, embeds, etc, won't wrok. If you want to work with WordPress posts within WordPress, the best choice is to use <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\"><code>get_posts()</code></a> o or a new instance of <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\"><code>WP_Query</code></a>.</p>\n\n<p>Now, <strong>to directly answer your question</strong>: the attachment files, including the intermediate sizes of images, are stored in <code>wp-content/uploads</code> folder. The database keeps information of the attachement post type, but the files are not in database.</p>\n" }, { "answer_id": 219591, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 0, "selected": false, "text": "<p>I wonder if you aren't looking for something different than I have originally answered. After rereading your post trying to make proper sense, I think your images are actually attachments and not thumbnails, if I read this correctly. If, so, these attachments are still not saved in db, only the info about the attachment as you correctly pointed out</p>\n\n<p>In this case, loading attachment can be very expensive if not done correctly. It is quite frustrating that WordPress does not allow you to directly query attachments without passing a post parent ID. </p>\n\n<p>To get attached images for your posts, you can try the following, it will be a bit faster doing it this way</p>\n\n<pre><code>/**\n * Because we really just need post ID's and nothing more like\n * custom fields, postdata, and post terms, we will not be updating\n * the post cache. This saves a lot of time and resources. If you are \n * going to need custom fields or post data or terms, then you should remove\n * cache_results because this will cause huge increase in db queries when you\n * try to get post terms or custom fields\n *\n * Also, we will only get post ID's as we do not need anything else\n */\n$args = [\n 'fields' =&gt; 'ids', // Get only post ID's\n 'cache_results' =&gt; false, // Do not update post caches\n // Add any extra arguments\n];\n$q = get_posts( $args );\n\nif ( $q ) {\n foreach ( $q as $id ) {\n /**\n * Get all attached images\n * \n * We will be doing what get_attached_media does, but because we only\n * have post ID's and have not updated the post cache, we will not be \n * using get_attached_media() as it will lead to a large number of db hits\n * because get_attached_media() will use get_post() to get the complete post object\n */\n $image_args = [\n 'post_parent' =&gt; $id,\n 'post_type' =&gt; 'attachment',\n 'post_mime_type' =&gt; 'image',\n 'posts_per_page' =&gt; -1,\n 'orderby' =&gt; 'menu_order',\n 'order' =&gt; 'ASC',\n ];\n $images = get_children( $image_args );\n\n if ( !$images )\n continue;\n\n // Loop throught the images\n foreach ( $images as $image ) {\n // Output the images as needed\n\n // For debugging, see the var_dump for values\n var_dump( $image );\n\n }\n }\n}\n</code></pre>\n\n<h2>ORIGINAL ANSWER</h2>\n\n<p>Post thumbnails aren't explicitely saved in the db, only the ID of that particular thumbnail is saved as post meta in the <code>wp_postmeta</code> table. The particular meta key is <code>_thumbnail_id</code>. </p>\n\n<p>You can specifiy which thumbnail size to return for each post via the second parameter of the <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow\"><code>get_the_post_thumbnail()</code></a> function. You can alternatively set a string or an array of custom attributes as third parameter</p>\n\n<p>It should be noted, <code>get_the_post_thumbnail()</code> does not display the thumbnail, but simply returns it. Inside the loop, you would want to use <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"nofollow\"><code>the_post_thumbnail()</code></a> to display the thumbnail, in which case the parameters as discussed above will be the first and second parameters respectively.</p>\n\n<p>Loading thumbnails in a custom loop is expensive as thumbnails aren't cached for custom queries. Only the main query is covered. You need to explicitely set caching for thumbnails in a custom loop.</p>\n\n<p>You can try the following as a probable solution: (<strong><em>NOTE:</strong> Everything is untested and might be buggy</em>)</p>\n\n<p>(<em>Lets say you want to use the <code>medium</code> size thumbnail and only want to display thumbnails, nothing else, if need any other post properties, remove the filter</em>)</p>\n\n<p>Lets first look at the filter which should go into <code>functions.php</code></p>\n\n<pre><code>/**\n * Custom filter to retrieve only post ID's.\n *\n * We cannot set the fields arguments to ID in our query because\n * we need to update the thumbnail cache, and if you look at \n * update_post_thumbnail_cache(), we need the post as an object\n * so we can use $post-&gt;ID, if we set the fields parameter, we only\n * get an array of ID's, not post objects with only ID's\n */\nadd_filter( 'posts_fields', function ( $fields, \\WP_Query $q ) use ( &amp;$wpdb )\n{\n remove_filter( current_filter(), __FUNCTION__ );\n\n // Only target a query where the new wpse_fields parameter is set with a value of ID\n if ( 'ID' === $q-&gt;get( 'wpse_fields' ) ) {\n // Only get the post ID field to reduce server load\n $fields = \"$wpdb-&gt;posts.ID\";\n }\n\n return $fields;\n}, 10, 2);\n</code></pre>\n\n<p>This filter will reduce server load by a big margin as we only get post ID's, but still maintain the post object.</p>\n\n<p>Your custom query can look something like the following:</p>\n\n<pre><code>/** \n * Because we only need to display the post thumbnails, we will not be\n * updating the term cache. If you need post term info, remove the \n * update_post_term_cache argument. This will increase performance if you\n * do not need post term info\n */\n$args = [\n 'meta_key' =&gt; '_thumbnail_id', // Only get posts with thumbnails\n 'wpse_fields' =&gt; 'ID', // Our custom argument to get only post ID's\n 'update_post_term_cache' =&gt; false, // Do not update the post caches to make the query faster\n // Any other arguments\n];\n$q = new WP_Query( $args );\n\nif ( $q-&gt;have_posts() ) {\n\n // Update the post thumbnail cache\n update_post_thumbnail_cache( $q );\n\n while ( $q-&gt;have_posts() ) {\n $q-&gt;the_post();\n\n // Display the post thumbnail, medium size\n if ( has_post_thumbnail() ) // Not really necessary in current context\n the_post_thumbnail( 'medium' ); // Get medium size post thumbnail\n\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p><strong>VERY IMPORTANT NOTE</strong></p>\n\n<p>The use of short PHP tags are highly discouraged, it is actually not allowed in WordPress. It is really bad coding practice. You should make a habit of it to use proper PHP tags (*<code>&lt;?php</code> and <code>?&gt;</code></p>\n" }, { "answer_id": 219674, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>By default the thumbnail (attachment) ID is stored in the post's <code>meta_key</code> of <code>_thumbnail_id</code>, so if that is not set (eg. by adding the image to the post via the post writing screen) then <code>get_the_post_thumbnail</code> and <code>the_post_thumbnail</code> will not do anything, as you pass them the <code>$post_id</code> they will check and find that <code>_thumbnail_id</code> is not set for that <code>$post_id</code> and return nothing.</p>\n\n<p><code>wp_get_attachment</code> and <code>wp_get_attachment_src</code> <em>will</em> do something however, but only if you pass the <code>Attachment ID</code> and <em>not</em> the <code>Post ID</code>. You say you have saved the attachment ID to meta_key of <code>item_image01</code> (or <code>image01</code>?) but in your current SQL query you are not actually retrieving this value, just checking it has been set. So you should be able to just do this instead:</p>\n\n<pre><code>foreach ($sqlsearchquery as $results) {\n $post_id = $results-&gt;ID;\n $attachment_id = get_post_meta($post_id,'item_image01',true);\n $source_url = wp_get_attachment_src($attachment_id,'medium');\n ?&gt;\n\n &lt;div class=\"grid_item_img\" style=\"background-image:url('&lt;? echo $source_url; ?&gt;')\"&gt;\n</code></pre>\n\n<p>So it also seems you are using some other method to set the attachment ID to this meta_key, again, if you did want to simply use <code>get_the_post_thumbnail</code> you would set the attachment ID to the post's <code>_thumbnail_id</code> meta_key instead.</p>\n" }, { "answer_id": 219680, "author": "mesqueeb", "author_id": 87968, "author_profile": "https://wordpress.stackexchange.com/users/87968", "pm_score": -1, "selected": false, "text": "<p>The answer is simple:</p>\n\n<p>Don't forget to write <code>echo</code> in front of all of these functions.</p>\n\n<pre><code>echo wp_get_attachment_image($attachment_id, 'medium' );\necho wp_get_attachment_image_src($attachment_id, 'medium' );\n\necho get_the_post_thumbnail($post_id, 'thumbnail');\necho get_the_post_thumbnail($post_id, 'medium');\n//note this only works if you have _thumbnail_id set to the postmeta of the post.\n</code></pre>\n\n<p>This all works fine and the problem is solved.</p>\n" } ]
2016/03/03
[ "https://wordpress.stackexchange.com/questions/219583", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87968/" ]
I have a custom form that allows users to make posts and also upload images with it. The images are saved in `wp_posts` as post\_type = `attachment` with a `guid` to show the image. Now I have created a grid created with php which shows all main pictures of my posts. However, since I call the guid's of the images it loads very slow when the pictures are large. I know that there is some smaller thumbnail that should get saved with each image upload, but I cannot find these files in the database. I tried showing them with all of the following ways: ``` //test with ID of the post: get_the_post_thumbnail('17547'); get_the_post_thumbnail(17547, 'thumbnail'); get_the_post_thumbnail(17547, 'medium'); //test with ID of the attachment: wp_get_attachment_image(17548, 'medium' ); wp_get_attachment_image_src(17548, 'medium' ); ``` The two different numbers are because i tried the post ID and the attachement ID. But all of the above functions don't show me anything in the DOM... **I think that maybe the way I save the pictures doesn't allows me to use this function.** But I don't know what I'm doing wrong! Does anyone know where I can look or how I can show these thumbnails? This is how my photo grid is made: **①** First I get a list of ID's based on what the user searches: ``` $allluca01 = $wpdb->get_results(" SELECT wpp.ID, post_title FROM wp_posts AS wpp WHERE post_type = 'post' ".$plus_other_search_conditions." GROUP BY wpp.ID "); ``` **②** Then I get the guid of the image. I have the attachment id saved as metavalue to a metakey called image01 (linked to post\_id). ``` foreach($sqlsearchquery as $results){ $resultid = $results->ID; $getpicture = $wpdb->get_results(" SELECT guid AS pic FROM wp_posts LEFT JOIN wp_postmeta ON ID = meta_value WHERE post_id = '$resultid' AND meta_key = 'item_image01' "); <div class="grid_item_img" style="background-image:url('<? echo $getpicture[0]->pic; ?>')"> ``` As you can see I attain the **guid** and then I use it in my grid. **I just want to obtain a guid of a smaller size of my media** so I can have the grid load faster. Does anyone know how to do that?
You can use several functions to get the URL of a image of any of the intermediate sizes created by WordPress (thumbnail, medium, large, full, or any other [custom size](https://developer.wordpress.org/reference/functions/add_image_size/)). You can use `get_the_post_thumbnail()`/`the_post_thumbnail()`: use this function if you want **to get a `<img>` element of the featured image of a post (aka "post thumbnail")**. For example, to get the featured image, medium szie, of the post with ID 78: ``` $featured_image = get_the_post_thumbanil( 78, 'medium' ); echo $featured_image; ``` If you are within the loop, you can display the post thumbnail, medium size, of the current post as follow: ``` // Don't need echo the_post_thumbnail( 'medium' ); ``` If no image size is set, `get_the_post_thumbanil()`/`the_post_thumbnail()` use `post-thumbnail`, which is [the size registered for the post thumbanil](https://codex.wordpress.org/Function_Reference/set_post_thumbnail_size) (featured image). If you want **to get a `<img>` element of any image**, not the post thumbnail (featured image), use `wp_get_attachment_image()`. For example, if the attachement has ID of 7898 and you want to get medium size `<img>`: ``` echo wp_get_attachment_image( 7898, 'medium' ); ``` You can also use `wp_get_attachment_image_src()` if you only want to get the URL of any image (but not a `<img>` element): ``` $image_url = wp_get_attachment_image_src( $id_of_the_attachment, $size ); ``` For example, if the attachement has ID of 7898 and you want to get medium size URL: ``` $image_url = wp_get_attachment_image_src( 7898, 'medium' ); ``` In you custom query, you could select the attachment ID instead of the `guid` and use this attachment ID with `wp_get_attachment_image()` and `wp_get_attachment_image_src()`. Anyway, **you should avoid that custom SQL queries**. You are missing important WordPress hooks and several functions, template tags, filters on content, embeds, etc, won't wrok. If you want to work with WordPress posts within WordPress, the best choice is to use [`get_posts()`](https://codex.wordpress.org/Class_Reference/WP_Query) o or a new instance of [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query). Now, **to directly answer your question**: the attachment files, including the intermediate sizes of images, are stored in `wp-content/uploads` folder. The database keeps information of the attachement post type, but the files are not in database.
219,613
<p>I'm making a page for settings API using Codestar Framework, and loading fields using their <a href="http://codestarframework.com/documentation/#configuration" rel="nofollow">filterable configure</a> - <strong>question is not related to Codestar</strong>. In one of such dropdown field, I need to load all the posts from a custom post type that are added within 30 days. To make the things nice and clean I made a custom function:</p> <pre><code>&lt;?php /** * Get posts of last 30 days only. * * @return array Array of posts. * -------------------------------------------------------------------------- */ function pre_get_active_posts_of_30_days() { //admin-only function if( !is_admin() ) return; global $project_prefix; //set a project prefix (i.e. pre_) $latest_posts = new WP_Query( array( 'post_type' =&gt; 'cpt', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'date_query' =&gt; array( array( 'after' =&gt; '30 days ago', 'inclusive' =&gt; true, ), ) ) ); $posts_this_month = array(); if( $latest_posts-&gt;have_posts() ) : while( $latest_posts-&gt;have_posts() ) : $latest_posts-&gt;the_post(); $validity_type = get_post_meta( get_the_ID(), "{$project_prefix}validity_type", true ); if( $validity_type &amp;&amp; 'validity date' === $validity_type ) { $validity = get_post_meta( get_the_ID(), "{$project_prefix}validity", true ); $tag = days_until( $validity ) .' days left'; //custom function } else if( $validity_type &amp;&amp; 'validity stock' === $validity_type ) { $tag = 'Stock'; } else { $tag = '...'; } $posts_this_month[get_the_ID()] = get_the_title() .' ['. $tag .']'; endwhile; endif; wp_reset_postdata(); return $posts_this_month; } </code></pre> <p>Question is not even with the function.</p> <p>I want to do the query <strong>only on that particular top_level_custom-settings-api page</strong>. The function is loading on every page load of admin. I tried using <code>get_current_screen()</code> but this function's giving me not found fatal error.</p> <h3>Edit</h3> <p>No @bonger, I remembered that. I tried your code in this way:</p> <pre><code>add_action('current_screen', 'current_screen_callback'); function current_screen_callback($screen) { if( is_object($screen) &amp;&amp; $screen-&gt;id == 'top_level_custom-settings-api' ) { add_action( 'admin_init', 'pre_get_active_posts_of_30_days' ); } } </code></pre> <p>The code does work well, but it doesn't control my function loading only on that particular page. I checked the query on other pages, the query is there too. And I tried changing the conditional to something wrong, like <code>$screen-&gt;id == 'top_level_-api'</code>, it still works that way. :(</p> <p>I'm afraid, I know I have a serious lack in behind-the-scene action and filter things. Would love to have a good read for that too.</p>
[ { "answer_id": 220258, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 2, "selected": false, "text": "<p>It's worthwhile pointing out that using <code>admin_init</code> within the <code>current_screen</code> filter is too late because <code>admin_init</code> has already fired.</p>\n\n<p>Instead do: </p>\n\n<pre><code>add_action('current_screen', 'current_screen_callback');\n\nfunction current_screen_callback($screen) {\n if( is_object($screen) &amp;&amp; $screen-&gt;id === 'top_level_custom-settings-api' ) {\n add_filter('top_level_screen', '__return_true');\n }\n}\n</code></pre>\n\n<p>Elsewhere in your <code>top_level_page_callback</code> callback responsible for executing the query:</p>\n\n<pre><code>function top_level_page_callback() {\n\n $active_posts = null;\n\n if ( ($is_top_level = apply_filters('top_level_screen', false)) ) {\n\n $active_posts = pre_get_active_posts_of_30_days();\n\n }\n\n //etc...\n\n}\n</code></pre>\n\n<p>That's one way to do it...</p>\n\n<p>Or you could use, <code>add_action('load-top_level_custom-settings-api', 'callback');</code></p>\n\n<p>Other than the <code>current_screen</code> hook, where else were you trying to call <code>pre_get_active_posts_of_30_days()</code> from? Because you had to have been calling it in a global scope of some sort for it to be running on all pages and not just the target page.</p>\n" }, { "answer_id": 289438, "author": "mohamdio", "author_id": 78247, "author_profile": "https://wordpress.stackexchange.com/users/78247", "pm_score": 1, "selected": false, "text": "<p>Just do that</p>\n\n<pre><code>/**\n * Make sure to do WP_Query (or whatever) only on specific admin page.\n */\n\n// save current page slug\n$current_page_slug = '';\n\n// get current page slug\nglobal $pagenow;\nif ($pagenow === 'admin.php' &amp;&amp; isset($_GET['page'])) {\n $current_page_slug = $_GET['page'];\n}\n\n// we are not inside our 'specific_page_slug' page? go back\nif ($current_page_slug !== 'specific_page_slug') {\n return; // or do whatever\n}\n\n// here we are inside our 'specific_page_slug' page\n// so now you can do wp_query or whatever\n</code></pre>\n" } ]
2016/03/03
[ "https://wordpress.stackexchange.com/questions/219613", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
I'm making a page for settings API using Codestar Framework, and loading fields using their [filterable configure](http://codestarframework.com/documentation/#configuration) - **question is not related to Codestar**. In one of such dropdown field, I need to load all the posts from a custom post type that are added within 30 days. To make the things nice and clean I made a custom function: ``` <?php /** * Get posts of last 30 days only. * * @return array Array of posts. * -------------------------------------------------------------------------- */ function pre_get_active_posts_of_30_days() { //admin-only function if( !is_admin() ) return; global $project_prefix; //set a project prefix (i.e. pre_) $latest_posts = new WP_Query( array( 'post_type' => 'cpt', 'post_status' => 'publish', 'posts_per_page' => -1, 'date_query' => array( array( 'after' => '30 days ago', 'inclusive' => true, ), ) ) ); $posts_this_month = array(); if( $latest_posts->have_posts() ) : while( $latest_posts->have_posts() ) : $latest_posts->the_post(); $validity_type = get_post_meta( get_the_ID(), "{$project_prefix}validity_type", true ); if( $validity_type && 'validity date' === $validity_type ) { $validity = get_post_meta( get_the_ID(), "{$project_prefix}validity", true ); $tag = days_until( $validity ) .' days left'; //custom function } else if( $validity_type && 'validity stock' === $validity_type ) { $tag = 'Stock'; } else { $tag = '...'; } $posts_this_month[get_the_ID()] = get_the_title() .' ['. $tag .']'; endwhile; endif; wp_reset_postdata(); return $posts_this_month; } ``` Question is not even with the function. I want to do the query **only on that particular top\_level\_custom-settings-api page**. The function is loading on every page load of admin. I tried using `get_current_screen()` but this function's giving me not found fatal error. ### Edit No @bonger, I remembered that. I tried your code in this way: ``` add_action('current_screen', 'current_screen_callback'); function current_screen_callback($screen) { if( is_object($screen) && $screen->id == 'top_level_custom-settings-api' ) { add_action( 'admin_init', 'pre_get_active_posts_of_30_days' ); } } ``` The code does work well, but it doesn't control my function loading only on that particular page. I checked the query on other pages, the query is there too. And I tried changing the conditional to something wrong, like `$screen->id == 'top_level_-api'`, it still works that way. :( I'm afraid, I know I have a serious lack in behind-the-scene action and filter things. Would love to have a good read for that too.
It's worthwhile pointing out that using `admin_init` within the `current_screen` filter is too late because `admin_init` has already fired. Instead do: ``` add_action('current_screen', 'current_screen_callback'); function current_screen_callback($screen) { if( is_object($screen) && $screen->id === 'top_level_custom-settings-api' ) { add_filter('top_level_screen', '__return_true'); } } ``` Elsewhere in your `top_level_page_callback` callback responsible for executing the query: ``` function top_level_page_callback() { $active_posts = null; if ( ($is_top_level = apply_filters('top_level_screen', false)) ) { $active_posts = pre_get_active_posts_of_30_days(); } //etc... } ``` That's one way to do it... Or you could use, `add_action('load-top_level_custom-settings-api', 'callback');` Other than the `current_screen` hook, where else were you trying to call `pre_get_active_posts_of_30_days()` from? Because you had to have been calling it in a global scope of some sort for it to be running on all pages and not just the target page.
219,629
<p>I'm writing a web/db application. My clients would like authentication based on whether the user is logged into WordPress.</p> <p>Assuming this application is hosted from within <code>/wordpress</code> I would like to be able to:</p> <ol> <li><p>Determine who, if anyone, is logged into WordPress</p> <p>Seems as if it should be possible via <code>wp_get_current_user()</code> but I can't find any documentation detailing which include files need to be included to make that work. Including <code>/wp-includes/plugin.php</code> and <code>pluggable.php</code> results in a <code>class WP_User not found</code> error from <code>wp_get_current_user()</code>. I presume some required include files are not included, but which?</p></li> <li><p>Read WordPress cookies</p> <p>Seems to require knowledge of the hash that was used when they were created - how is this gettable?</p></li> </ol> <p><strong>Additional Information:</strong> The clients are a group of over 300 artists who want </p> <ul> <li>a website managed in WordPress and </li> <li>a system to manage exhibition submissions, </li> <li>a member database, </li> <li>rotas,</li> <li>user roles</li> <li>catalogue production</li> <li>detailed business rules/validation, permissions etc</li> </ul> <p>It boils down to various m:n relationships. So a separate system providing 'club admin' alongside WordPress for the public-facing website, seemed a better fit than WordPress with endless plugins with uncertain futures. The group, understandably, desires SSO. OAuth or similar is not an option since we're restricted to a single shared hosting (cPanel) account.</p> <p><strong>UPDATE - simple solution found - see my answer below</strong></p>
[ { "answer_id": 220258, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 2, "selected": false, "text": "<p>It's worthwhile pointing out that using <code>admin_init</code> within the <code>current_screen</code> filter is too late because <code>admin_init</code> has already fired.</p>\n\n<p>Instead do: </p>\n\n<pre><code>add_action('current_screen', 'current_screen_callback');\n\nfunction current_screen_callback($screen) {\n if( is_object($screen) &amp;&amp; $screen-&gt;id === 'top_level_custom-settings-api' ) {\n add_filter('top_level_screen', '__return_true');\n }\n}\n</code></pre>\n\n<p>Elsewhere in your <code>top_level_page_callback</code> callback responsible for executing the query:</p>\n\n<pre><code>function top_level_page_callback() {\n\n $active_posts = null;\n\n if ( ($is_top_level = apply_filters('top_level_screen', false)) ) {\n\n $active_posts = pre_get_active_posts_of_30_days();\n\n }\n\n //etc...\n\n}\n</code></pre>\n\n<p>That's one way to do it...</p>\n\n<p>Or you could use, <code>add_action('load-top_level_custom-settings-api', 'callback');</code></p>\n\n<p>Other than the <code>current_screen</code> hook, where else were you trying to call <code>pre_get_active_posts_of_30_days()</code> from? Because you had to have been calling it in a global scope of some sort for it to be running on all pages and not just the target page.</p>\n" }, { "answer_id": 289438, "author": "mohamdio", "author_id": 78247, "author_profile": "https://wordpress.stackexchange.com/users/78247", "pm_score": 1, "selected": false, "text": "<p>Just do that</p>\n\n<pre><code>/**\n * Make sure to do WP_Query (or whatever) only on specific admin page.\n */\n\n// save current page slug\n$current_page_slug = '';\n\n// get current page slug\nglobal $pagenow;\nif ($pagenow === 'admin.php' &amp;&amp; isset($_GET['page'])) {\n $current_page_slug = $_GET['page'];\n}\n\n// we are not inside our 'specific_page_slug' page? go back\nif ($current_page_slug !== 'specific_page_slug') {\n return; // or do whatever\n}\n\n// here we are inside our 'specific_page_slug' page\n// so now you can do wp_query or whatever\n</code></pre>\n" } ]
2016/03/03
[ "https://wordpress.stackexchange.com/questions/219629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89934/" ]
I'm writing a web/db application. My clients would like authentication based on whether the user is logged into WordPress. Assuming this application is hosted from within `/wordpress` I would like to be able to: 1. Determine who, if anyone, is logged into WordPress Seems as if it should be possible via `wp_get_current_user()` but I can't find any documentation detailing which include files need to be included to make that work. Including `/wp-includes/plugin.php` and `pluggable.php` results in a `class WP_User not found` error from `wp_get_current_user()`. I presume some required include files are not included, but which? 2. Read WordPress cookies Seems to require knowledge of the hash that was used when they were created - how is this gettable? **Additional Information:** The clients are a group of over 300 artists who want * a website managed in WordPress and * a system to manage exhibition submissions, * a member database, * rotas, * user roles * catalogue production * detailed business rules/validation, permissions etc It boils down to various m:n relationships. So a separate system providing 'club admin' alongside WordPress for the public-facing website, seemed a better fit than WordPress with endless plugins with uncertain futures. The group, understandably, desires SSO. OAuth or similar is not an option since we're restricted to a single shared hosting (cPanel) account. **UPDATE - simple solution found - see my answer below**
It's worthwhile pointing out that using `admin_init` within the `current_screen` filter is too late because `admin_init` has already fired. Instead do: ``` add_action('current_screen', 'current_screen_callback'); function current_screen_callback($screen) { if( is_object($screen) && $screen->id === 'top_level_custom-settings-api' ) { add_filter('top_level_screen', '__return_true'); } } ``` Elsewhere in your `top_level_page_callback` callback responsible for executing the query: ``` function top_level_page_callback() { $active_posts = null; if ( ($is_top_level = apply_filters('top_level_screen', false)) ) { $active_posts = pre_get_active_posts_of_30_days(); } //etc... } ``` That's one way to do it... Or you could use, `add_action('load-top_level_custom-settings-api', 'callback');` Other than the `current_screen` hook, where else were you trying to call `pre_get_active_posts_of_30_days()` from? Because you had to have been calling it in a global scope of some sort for it to be running on all pages and not just the target page.
219,643
<p>What is a best way to eliminate xmlrpc.php file from WordPress when you don't need it?</p>
[ { "answer_id": 219646, "author": "Jorin van Vilsteren", "author_id": 68062, "author_profile": "https://wordpress.stackexchange.com/users/68062", "pm_score": 3, "selected": false, "text": "<p>We are using the htaccess file to protect it from hackers.</p>\n\n<pre><code># BEGIN protect xmlrpc.php\n&lt;files xmlrpc.php&gt;\norder allow,deny\ndeny from all\n&lt;/files&gt;\n# END protect xmlrpc.php\n</code></pre>\n" }, { "answer_id": 219647, "author": "markratledge", "author_id": 268, "author_profile": "https://wordpress.stackexchange.com/users/268", "pm_score": 3, "selected": false, "text": "<p>The best thing to do is disable <code>xmlrpc.php</code> functions with a plugin rather than delete or disable the file itself. The file itself will be replaced on WordPress core updates, while a plugin will keep it disabled after core updates and if you change themes.</p>\n\n<p>See <a href=\"https://wordpress.org/plugins/search.php?q=disable+xml-rpc\" rel=\"nofollow\">https://wordpress.org/plugins/search.php?q=disable+xml-rpc</a> for different plugins. They all have minor differences.</p>\n\n<p>These plugins do the same thing as a function added to the theme's <code>functions.php</code> file or adding an <code>order,allow deny</code> rule to .htaccess (as outlined in other answers), with the difference being a plugin or function disables calls to <code>xmlrpc.php</code> via PHP, and the rule in .htaccess works by leveraging mod_rewrite in the webserver (i.e., Apache or Nginx). There is no appreciable performance difference between using PHP and mod_rewrite on a modern server.</p>\n" }, { "answer_id": 219666, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 6, "selected": true, "text": "<p>Since WordPress 3.5 this option (<em><code>XML-RPC</code></em>) is enabled by default, and the ability to turn it off from WordPress <code>dashboard</code> is gone.</p>\n\n<p>Add this code snippet for use in <code>functions.php</code>: </p>\n\n<pre><code>// Disable use XML-RPC\nadd_filter( 'xmlrpc_enabled', '__return_false' );\n\n// Disable X-Pingback to header\nadd_filter( 'wp_headers', 'disable_x_pingback' );\nfunction disable_x_pingback( $headers ) {\n unset( $headers['X-Pingback'] );\n\nreturn $headers;\n}\n</code></pre>\n\n<p>Although it does what it says, it can get intensive when a site is under attack by hitting it.<br />\nYou may better off using following code snippet in your <code>.htaccess</code> file.</p>\n\n<pre><code># Block WordPress xmlrpc.php requests\n&lt;Files xmlrpc.php&gt;\norder allow,deny\ndeny from all\n&lt;/Files&gt;\n</code></pre>\n\n<p>Or use this to disable access to the <code>xmlrpc.php</code> file from NGINX server block.</p>\n\n<pre><code># nginx block xmlrpc.php requests\nlocation /xmlrpc.php {\n deny all;\n}\n</code></pre>\n\n<blockquote>\n <p>Be aware that disabling also can have impact on logins through mobile. If I am correct WordPress mobile app does need this.<br />\n See <a href=\"https://codex.wordpress.org/XML-RPC_WordPress_API\" rel=\"noreferrer\">Codex</a> for more information about the use of <code>XML-RPC</code>.<br /></p>\n \n <ul>\n <li><em>Please make always a backup of the file(s) before edit/add.</em></li>\n </ul>\n</blockquote>\n\n<p><hr>\n<strong>Edit/Update</strong><br /></p>\n\n<p>@Prosti, -You are absolutely correct- about the options which <code>RESTful API</code> will offer for WordPress!<br /></p>\n\n<p>I forgot to mention this. It should already have been integrated into core (<em>WordPress version 4.1</em>) which was not possible at that time. But as it seems, will be core in WordPress 4.5 .<br /></p>\n\n<p>The alternative for the moment is this plugin: <a href=\"https://wordpress.org/plugins/rest-api/\" rel=\"noreferrer\">WordPress REST API (Version 2)</a> <br />\nYou can use it till <code>Restful API</code> is also core for WordPress.<br />\n<strong>Target date for release of WordPress 4.5. (April 12, 2016 (+3w))</strong></p>\n\n<blockquote>\n <p>For those who are interested in <code>RESTful</code>, on <a href=\"https://stackoverflow.com/a/671132/1370973\">Stackoverflow</a> is a very nice community wiki.</p>\n</blockquote>\n" }, { "answer_id": 239956, "author": "BRass", "author_id": 103235, "author_profile": "https://wordpress.stackexchange.com/users/103235", "pm_score": 2, "selected": false, "text": "<p>For the extreme minority that are hosting WordPress in IIS, you could use the IIS URL Rewrite module to do similar htaccess-like restrictions. The example below assumes the true client IP is coming in the X-Forwarded-For header, the known whitelist IP is 55.55.555.555, and that you want to respond with an HTTP 404 to non-whitelist IPs.</p>\n\n<pre><code>&lt;rule name=\"wordpress-restrictions\" enabled=\"true\" stopProcessing=\"true\"&gt;\n &lt;match url=\"(^xmlrpc.php)|(^wp-admin)|(^wp-login.php)\" /&gt;\n &lt;conditions logicalGrouping=\"MatchAll\" trackAllCaptures=\"false\"&gt;\n &lt;add input=\"{HTTP_X_FORWARDED_FOR}\" pattern=\"(^55\\.55\\.555\\.555$)\" negate=\"true\" /&gt;\n &lt;/conditions&gt;\n &lt;action type=\"CustomResponse\" statusCode=\"404\" subStatusCode=\"44\" statusReason=\"File or directory not found\" statusDescription=\"The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.\" /&gt;\n&lt;/rule&gt;\n</code></pre>\n" }, { "answer_id": 273492, "author": "Steve", "author_id": 88236, "author_profile": "https://wordpress.stackexchange.com/users/88236", "pm_score": 0, "selected": false, "text": "<p>I have recently installed Wordfence which, as of version 6.3.12 has the ability to block direct access to any location. Putting /xmlrpc.php onto the Options page in the list of banned access IPs <em>\"Immediately block IPs that access these URLs\"</em> is now showing one attempt being blocked about every 15 minutes.</p>\n\n<p>This also has the advantage of being able to block a URL to escape from those pesky bots that come back with a different IP address time and again.</p>\n\n<p>I do not know if it allows the use of xmlrpc.php by Apps for valid operations.</p>\n\n<p>I had some issues with it producing 504 Timeout and 502 Bad Gateway errors on the server at first but it seems to have settled down. </p>\n\n<p>Very impressed with the result so far and it produced a valuable cleanup profile after the site had been hacked before installing Wordfence and despite always having the latest version of WordPress and plugins.</p>\n\n<p><a href=\"https://www.wordfence.com/\" rel=\"nofollow noreferrer\">Wordfence</a> <a href=\"https://www.wordfence.com/\" rel=\"nofollow noreferrer\">https://www.wordfence.com/</a></p>\n" }, { "answer_id": 300198, "author": "tweber", "author_id": 141403, "author_profile": "https://wordpress.stackexchange.com/users/141403", "pm_score": 3, "selected": false, "text": "<p>When you have the ability to block it via your web server's configuration, @Charles' suggestions are good.</p>\n<p>If you can only disable it using php, the <code>xmlrpc_enabled</code> filter is not the right way.\nLike documented here:\n<a href=\"https://developer.wordpress.org/reference/hooks/xmlrpc_enabled/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/xmlrpc_enabled/</a>\nit only disables xml rpc methods that require authentication.</p>\n<p>Instead use the <code>xmlrpc_methods</code> filter to disable all methods:</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n// Disable all xml-rpc endpoints\nadd_filter('xmlrpc_methods', function () {\n return [];\n}, PHP_INT_MAX);\n</code></pre>\n<p>You can test if it's working by sending a POST request to xmlrpc.php with the following content:</p>\n<pre><code>&lt;methodCall&gt;\n &lt;methodName&gt;system.listMethods&lt;/methodName&gt;\n&lt;/methodCall&gt;\n</code></pre>\n<p>If the filter is working, there should only be 3 methods left:</p>\n<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;\n&lt;methodResponse&gt;\n &lt;params&gt;\n &lt;param&gt;\n &lt;value&gt;\n &lt;array&gt;\n &lt;data&gt;\n &lt;value&gt;\n &lt;string&gt;system.multicall&lt;/string&gt;\n &lt;/value&gt;\n &lt;value&gt;\n &lt;string&gt;system.listMethods&lt;/string&gt;\n &lt;/value&gt;\n &lt;value&gt;\n &lt;string&gt;system.getCapabilities&lt;/string&gt;\n &lt;/value&gt;\n &lt;/data&gt;\n &lt;/array&gt;\n &lt;/value&gt;\n &lt;/param&gt;\n &lt;/params&gt;\n&lt;/methodResponse&gt;\n</code></pre>\n<p>you can quickly test it with curl:</p>\n<pre><code>curl -X POST \\\n -H 'Cache-Control: no-cache' \\\n -H 'Content-Type: application/xml' \\\n -d '&lt;methodCall&gt;&lt;methodName&gt;system.listMethods&lt;/methodName&gt;&lt;/methodCall&gt;' \\\n https://your-wordpress-site.com/xmlrpc.php\n</code></pre>\n" }, { "answer_id": 320224, "author": "Manuel K", "author_id": 154725, "author_profile": "https://wordpress.stackexchange.com/users/154725", "pm_score": 0, "selected": false, "text": "<p>i use for nginx this small Code and this works 100%</p>\n\n<pre><code>location ~* (/wp-content/.*\\.php|/wp-includes/.*\\.php|/xmlrpc\\.php$|/(?:uploads|files)/.*\\.php$) {\ndeny all;\naccess_log off;\nlog_not_found off;\nreturn 444;\n}\n</code></pre>\n" }, { "answer_id": 381878, "author": "Amin Nazemi", "author_id": 200685, "author_profile": "https://wordpress.stackexchange.com/users/200685", "pm_score": 1, "selected": false, "text": "<p>The best way is to use .htaccess file to block all requests by adding</p>\n<pre><code># Block WordPress xmlrpc.php requests\n&lt;Files xmlrpc.php&gt;\norder deny,allow\ndeny from all\nallow from 1.1.1.1\n&lt;/Files&gt;\n</code></pre>\n<p>to the end of the file\n<strong>but</strong> if you want the <strong>easiest</strong> way using <a href=\"https://wordpress.org/plugins/disable-xml-rpc-api/\" rel=\"nofollow noreferrer\">Disable XML-RPC-API</a> plugin will do the job.</p>\n" } ]
2016/03/03
[ "https://wordpress.stackexchange.com/questions/219643", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88606/" ]
What is a best way to eliminate xmlrpc.php file from WordPress when you don't need it?
Since WordPress 3.5 this option (*`XML-RPC`*) is enabled by default, and the ability to turn it off from WordPress `dashboard` is gone. Add this code snippet for use in `functions.php`: ``` // Disable use XML-RPC add_filter( 'xmlrpc_enabled', '__return_false' ); // Disable X-Pingback to header add_filter( 'wp_headers', 'disable_x_pingback' ); function disable_x_pingback( $headers ) { unset( $headers['X-Pingback'] ); return $headers; } ``` Although it does what it says, it can get intensive when a site is under attack by hitting it. You may better off using following code snippet in your `.htaccess` file. ``` # Block WordPress xmlrpc.php requests <Files xmlrpc.php> order allow,deny deny from all </Files> ``` Or use this to disable access to the `xmlrpc.php` file from NGINX server block. ``` # nginx block xmlrpc.php requests location /xmlrpc.php { deny all; } ``` > > Be aware that disabling also can have impact on logins through mobile. If I am correct WordPress mobile app does need this. > > See [Codex](https://codex.wordpress.org/XML-RPC_WordPress_API) for more information about the use of `XML-RPC`. > > > > * *Please make always a backup of the file(s) before edit/add.* > > > --- **Edit/Update** @Prosti, -You are absolutely correct- about the options which `RESTful API` will offer for WordPress! I forgot to mention this. It should already have been integrated into core (*WordPress version 4.1*) which was not possible at that time. But as it seems, will be core in WordPress 4.5 . The alternative for the moment is this plugin: [WordPress REST API (Version 2)](https://wordpress.org/plugins/rest-api/) You can use it till `Restful API` is also core for WordPress. **Target date for release of WordPress 4.5. (April 12, 2016 (+3w))** > > For those who are interested in `RESTful`, on [Stackoverflow](https://stackoverflow.com/a/671132/1370973) is a very nice community wiki. > > >
219,658
<p>I made 2 plugins (Plugin A and plugin B/custom post type.) which some of the the module on Plugin A need to call taxonomy from PLUGIN B. Everything works fine when both plugin active, but when the Plugin B deactivate, I got this notice:</p> <blockquote> <p>Notice: Trying to get property of non-object in D:\MYWEB\InstantWP_4.3.1\iwpserver\htdocs\wordpress\wp-content\plugins\NYPLUGIN\myplugin.php on line 50</p> </blockquote> <p>Line 50 looks like this:</p> <pre><code>$option_value_event[] .= $cat-&gt;name; </code></pre> <p>Here the code:</p> <pre><code> //Get all EVENT categories $args = array( 'type' =&gt; 'post', 'child_of' =&gt; 0, 'parent' =&gt; '', 'orderby' =&gt; 'date', 'order' =&gt; 'ASC', 'hide_empty' =&gt; 1, 'hierarchical' =&gt; 1, 'exclude' =&gt; '', 'include' =&gt; '', 'number' =&gt; '', 'taxonomy' =&gt; 'catevent', 'pad_counts' =&gt; false ); $categories_event = get_categories($args); $option_value_event = array(); //Extract all EVENT categories foreach ( $categories_event as $cat ){ $option_value_event[] .= $cat-&gt;name; } </code></pre> <p>Sometime my user dont want to use Plugin B. Is there any way to deactivate PLUGIN B without break PLUGIN A?</p> <p>Is there a quick fix to resolve these error?</p> <p>Really appreciate for any help</p> <p>Thank you</p>
[ { "answer_id": 219661, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 0, "selected": false, "text": "<p>Well, a simple solution is to check if whatever is returned is empty. Always throw in these conditionals to ensure you have what you need before doing any kind of concatenation or evaluation. A simple PHP function such as <a href=\"http://php.net/manual/en/function.empty.php\" rel=\"nofollow\"><code>is_empty()</code></a> should suffice:</p>\n\n<pre><code>//Get all EVENT categories\n$args = array(\n 'type' =&gt; 'post', \n 'child_of' =&gt; 0, \n 'parent' =&gt; '', \n 'orderby' =&gt; 'date', \n 'order' =&gt; 'ASC', \n 'hide_empty' =&gt; 1, \n 'hierarchical' =&gt; 1, \n 'exclude' =&gt; '', \n 'include' =&gt; '', \n 'number' =&gt; '', \n 'taxonomy' =&gt; 'catevent', \n 'pad_counts' =&gt; false \n); \n$categories_event = get_categories( $args );\n$option_value_event = array();\n\n//Extract all EVENT categories\nif( ! empty( $categories_event ) ) {\n foreach( $categories_event as $cat ) { \n $option_value_event[] .= $cat-&gt;name;\n }\n}\n</code></pre>\n" }, { "answer_id": 219691, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>You will either need to do two things</p>\n\n<ul>\n<li><p>Check for an empty array <strong>AND</strong> a <code>WP_Error</code> object</p></li>\n<li><p>Check if the taxonomy exists (<em>which <code>get_categories()</code> and <code>get_terms()</code> already does</em>) before your execute your code and still check for an empty array</p></li>\n</ul>\n\n<h2>FEW NOTES TO CONSIDER</h2>\n\n<ul>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/get_categories/\" rel=\"nofollow\"><code>get_categories()</code></a> uses <code>get_terms()</code>, you you could use <a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow\"><code>get_terms()</code></a></p></li>\n<li><p>You do not need to set arguments if you use it's default values</p></li>\n<li><p><code>date</code> is not a valid value for <code>orderby</code> in <code>get_terms()</code>. Valid values are <code>name</code>, <code>slug</code>, <code>term_group</code>, <code>term_id</code>, <code>id</code>, <code>description</code> and <code>count</code></p></li>\n<li><p>The <code>type</code> parameter in <code>get_categories()</code> does not relate to the post type, but to the taxonomy type. This parameter used to accept <code>link</code> as value and where used before the introduction of custom taxonomies in WordPress 3.0. Before WordPress 3.0, you could set <code>type</code> to <code>link</code> to return terms from the <code>link_category</code> taxonomy. This parameter was depreciated in WordPress 3.0 in favor of the <code>taxonomy</code> parameter</p></li>\n</ul>\n\n<h2>SOLUTION</h2>\n\n<pre><code>//Get all EVENT categories\n$categories_event = get_terms( 'catevent' );\n\n$option_value_event = array(); \n\n// Check for empty array and WP_Error\nif ( $categories_event\n &amp;&amp; !is_wp_error( $categories_event )\n) {\n //Extract all EVENT categories\n foreach ( $categories_event as $cat ){ \n $option_value_event[] = $cat-&gt;name;\n }\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>I cannot see why the above code would not work. You can try the following as a test</p>\n\n<pre><code>if ( taxonomy_exists( 'catevent' ) ) {\n //Get all EVENT categories\n $categories_event = get_terms( 'catevent' );\n\n $option_value_event = array(); \n\n // Check for empty array and WP_Error\n if ( $categories_event\n &amp;&amp; !is_wp_error( $categories_event )\n ) {\n //Extract all EVENT categories\n foreach ( $categories_event as $cat ){ \n $option_value_event[] = $cat-&gt;name;\n }\n }\n}\n</code></pre>\n\n<p>That should work, if not, then you have a serious error somewhere in one of your plugins</p>\n" } ]
2016/03/03
[ "https://wordpress.stackexchange.com/questions/219658", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89109/" ]
I made 2 plugins (Plugin A and plugin B/custom post type.) which some of the the module on Plugin A need to call taxonomy from PLUGIN B. Everything works fine when both plugin active, but when the Plugin B deactivate, I got this notice: > > Notice: Trying to get property of non-object in D:\MYWEB\InstantWP\_4.3.1\iwpserver\htdocs\wordpress\wp-content\plugins\NYPLUGIN\myplugin.php on line 50 > > > Line 50 looks like this: ``` $option_value_event[] .= $cat->name; ``` Here the code: ``` //Get all EVENT categories $args = array( 'type' => 'post', 'child_of' => 0, 'parent' => '', 'orderby' => 'date', 'order' => 'ASC', 'hide_empty' => 1, 'hierarchical' => 1, 'exclude' => '', 'include' => '', 'number' => '', 'taxonomy' => 'catevent', 'pad_counts' => false ); $categories_event = get_categories($args); $option_value_event = array(); //Extract all EVENT categories foreach ( $categories_event as $cat ){ $option_value_event[] .= $cat->name; } ``` Sometime my user dont want to use Plugin B. Is there any way to deactivate PLUGIN B without break PLUGIN A? Is there a quick fix to resolve these error? Really appreciate for any help Thank you
You will either need to do two things * Check for an empty array **AND** a `WP_Error` object * Check if the taxonomy exists (*which `get_categories()` and `get_terms()` already does*) before your execute your code and still check for an empty array FEW NOTES TO CONSIDER --------------------- * [`get_categories()`](https://developer.wordpress.org/reference/functions/get_categories/) uses `get_terms()`, you you could use [`get_terms()`](https://developer.wordpress.org/reference/functions/get_terms/) * You do not need to set arguments if you use it's default values * `date` is not a valid value for `orderby` in `get_terms()`. Valid values are `name`, `slug`, `term_group`, `term_id`, `id`, `description` and `count` * The `type` parameter in `get_categories()` does not relate to the post type, but to the taxonomy type. This parameter used to accept `link` as value and where used before the introduction of custom taxonomies in WordPress 3.0. Before WordPress 3.0, you could set `type` to `link` to return terms from the `link_category` taxonomy. This parameter was depreciated in WordPress 3.0 in favor of the `taxonomy` parameter SOLUTION -------- ``` //Get all EVENT categories $categories_event = get_terms( 'catevent' ); $option_value_event = array(); // Check for empty array and WP_Error if ( $categories_event && !is_wp_error( $categories_event ) ) { //Extract all EVENT categories foreach ( $categories_event as $cat ){ $option_value_event[] = $cat->name; } } ``` EDIT ---- I cannot see why the above code would not work. You can try the following as a test ``` if ( taxonomy_exists( 'catevent' ) ) { //Get all EVENT categories $categories_event = get_terms( 'catevent' ); $option_value_event = array(); // Check for empty array and WP_Error if ( $categories_event && !is_wp_error( $categories_event ) ) { //Extract all EVENT categories foreach ( $categories_event as $cat ){ $option_value_event[] = $cat->name; } } } ``` That should work, if not, then you have a serious error somewhere in one of your plugins
219,686
<p>How can I get a list of all users that are in WordPress by their role or capabilities?</p> <p>For example: </p> <ul> <li>Display <code>all subscribers list</code> in WordPress.</li> <li>Display <code>all authors list</code> in WordPress.</li> <li>Display <code>all editors list</code> in WordPress.</li> </ul>
[ { "answer_id": 219687, "author": "Raja Usman Mehmood", "author_id": 75825, "author_profile": "https://wordpress.stackexchange.com/users/75825", "pm_score": 6, "selected": true, "text": "<p>There may be some different way to do that, but most proper way to do that is following.</p>\n\n<pre><code>&lt;?php\n\n$args = array(\n 'role' =&gt; 'Your desired role goes here.',\n 'orderby' =&gt; 'user_nicename',\n 'order' =&gt; 'ASC'\n);\n$users = get_users( $args );\n\necho '&lt;ul&gt;';\nforeach ( $users as $user ) {\n echo '&lt;li&gt;' . esc_html( $user-&gt;display_name ) . '[' . esc_html( $user-&gt;user_email ) . ']&lt;/li&gt;';\n}\necho '&lt;/ul&gt;';\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 219715, "author": "Jevuska", "author_id": 18731, "author_profile": "https://wordpress.stackexchange.com/users/18731", "pm_score": 2, "selected": false, "text": "<p>Here the simple approach to grouping roles.</p>\n\n<pre><code>$wp_roles = wp_roles();\n$result = count_users();\n\nforeach ( $result['avail_roles'] as $role =&gt; $count )\n{\n if ( 0 == $count )\n continue; //pass role none\n\n $args = array(\n 'role' =&gt; $role\n );\n\n $users = get_users( $args );\n $user = array();\n for ( $i = 0; $i &lt; $count ; $i++ )\n $user[] = esc_html( $users[ $i ]-&gt;display_name ); //show display name\n\n //output\n echo wp_sprintf( '&lt;h2&gt;%1$s&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;%2$s&lt;/li&gt;&lt;/ul&gt;',\n esc_html( $wp_roles-&gt;role_names[ $role ] ),\n implode( '&lt;/li&gt;&lt;li&gt;', $user )\n );\n}\n</code></pre>\n" }, { "answer_id": 342482, "author": "Wikus", "author_id": 84136, "author_profile": "https://wordpress.stackexchange.com/users/84136", "pm_score": 0, "selected": false, "text": "<p>Expanding on Raja's answer you could also write a helper function that handles this for you:</p>\n\n<pre><code>&lt;?php\n# This goes in functions.php\nfunction get_users_by_role($role, $orderby, $order) {\n $args = array(\n 'role' =&gt; $role,\n 'orderby' =&gt; $orderby,\n 'order' =&gt; $order\n );\n\n $users = get_users( $args );\n\n return $users;\n}\n?&gt;\n</code></pre>\n\n<p>Then to get users by a specific role you can simply do:</p>\n\n<pre><code>&lt;?php $users = get_users_by_role('Your role', 'user_nicename', 'ASC'); ?&gt;\n</code></pre>\n" }, { "answer_id": 359745, "author": "CristianR", "author_id": 167341, "author_profile": "https://wordpress.stackexchange.com/users/167341", "pm_score": 2, "selected": false, "text": "<p>When you find users with Ultimate Member Plugin Roles, You have to add \"um_\" to your role value.\nFor example, you created the role name \"Client\" in Ultimate Membership Plugin, then $args would be</p>\n\n<pre><code>$args = array(\n 'role' =&gt; 'um_client',\n 'orderby' =&gt; 'user_nicename',\n 'order' =&gt; 'ASC'\n);\n</code></pre>\n" } ]
2016/03/04
[ "https://wordpress.stackexchange.com/questions/219686", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75825/" ]
How can I get a list of all users that are in WordPress by their role or capabilities? For example: * Display `all subscribers list` in WordPress. * Display `all authors list` in WordPress. * Display `all editors list` in WordPress.
There may be some different way to do that, but most proper way to do that is following. ``` <?php $args = array( 'role' => 'Your desired role goes here.', 'orderby' => 'user_nicename', 'order' => 'ASC' ); $users = get_users( $args ); echo '<ul>'; foreach ( $users as $user ) { echo '<li>' . esc_html( $user->display_name ) . '[' . esc_html( $user->user_email ) . ']</li>'; } echo '</ul>'; ?> ```
219,745
<p>I've got the following error messages on the themecheck plugin in my WordPress theme. </p> <blockquote> <p>REQUIRED: The theme uses the register_taxonomy() function, which is plugin-territory functionality. <br> REQUIRED: The theme uses the register_post_type() function, which is plugin-territory functionality. <br> WARNING: The theme uses the add_shortcode() function. Custom post-content shortcodes are plugin-territory functionality.</p> </blockquote> <p>I declared the <code>register_taxonomy()</code> and <code>register_post_type()</code> function in <code>after_setup_theme</code> hook. <br> My <code>register_taxonomy()</code> function is:</p> <pre><code>register_taxonomy('project_cat', 'project', array( 'public' =&gt; true, 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name' =&gt; 'Categories', ) )); </code></pre> <p>And one of my <code>register_post_type()</code> function is:</p> <pre><code>register_post_type('service', array( 'public' =&gt; true, 'supports' =&gt; array('title', 'thumbnail', 'editor'), 'labels' =&gt; array( 'name' =&gt; esc_html__('Services', 'textdomain'), 'add_new_item' =&gt; esc_html__('Add Service', 'textdomain'), 'add_new' =&gt; esc_html__('Add Service', 'textdomain') ) )); </code></pre> <p>How can I fix those issues?</p>
[ { "answer_id": 219687, "author": "Raja Usman Mehmood", "author_id": 75825, "author_profile": "https://wordpress.stackexchange.com/users/75825", "pm_score": 6, "selected": true, "text": "<p>There may be some different way to do that, but most proper way to do that is following.</p>\n\n<pre><code>&lt;?php\n\n$args = array(\n 'role' =&gt; 'Your desired role goes here.',\n 'orderby' =&gt; 'user_nicename',\n 'order' =&gt; 'ASC'\n);\n$users = get_users( $args );\n\necho '&lt;ul&gt;';\nforeach ( $users as $user ) {\n echo '&lt;li&gt;' . esc_html( $user-&gt;display_name ) . '[' . esc_html( $user-&gt;user_email ) . ']&lt;/li&gt;';\n}\necho '&lt;/ul&gt;';\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 219715, "author": "Jevuska", "author_id": 18731, "author_profile": "https://wordpress.stackexchange.com/users/18731", "pm_score": 2, "selected": false, "text": "<p>Here the simple approach to grouping roles.</p>\n\n<pre><code>$wp_roles = wp_roles();\n$result = count_users();\n\nforeach ( $result['avail_roles'] as $role =&gt; $count )\n{\n if ( 0 == $count )\n continue; //pass role none\n\n $args = array(\n 'role' =&gt; $role\n );\n\n $users = get_users( $args );\n $user = array();\n for ( $i = 0; $i &lt; $count ; $i++ )\n $user[] = esc_html( $users[ $i ]-&gt;display_name ); //show display name\n\n //output\n echo wp_sprintf( '&lt;h2&gt;%1$s&lt;/h2&gt;&lt;ul&gt;&lt;li&gt;%2$s&lt;/li&gt;&lt;/ul&gt;',\n esc_html( $wp_roles-&gt;role_names[ $role ] ),\n implode( '&lt;/li&gt;&lt;li&gt;', $user )\n );\n}\n</code></pre>\n" }, { "answer_id": 342482, "author": "Wikus", "author_id": 84136, "author_profile": "https://wordpress.stackexchange.com/users/84136", "pm_score": 0, "selected": false, "text": "<p>Expanding on Raja's answer you could also write a helper function that handles this for you:</p>\n\n<pre><code>&lt;?php\n# This goes in functions.php\nfunction get_users_by_role($role, $orderby, $order) {\n $args = array(\n 'role' =&gt; $role,\n 'orderby' =&gt; $orderby,\n 'order' =&gt; $order\n );\n\n $users = get_users( $args );\n\n return $users;\n}\n?&gt;\n</code></pre>\n\n<p>Then to get users by a specific role you can simply do:</p>\n\n<pre><code>&lt;?php $users = get_users_by_role('Your role', 'user_nicename', 'ASC'); ?&gt;\n</code></pre>\n" }, { "answer_id": 359745, "author": "CristianR", "author_id": 167341, "author_profile": "https://wordpress.stackexchange.com/users/167341", "pm_score": 2, "selected": false, "text": "<p>When you find users with Ultimate Member Plugin Roles, You have to add \"um_\" to your role value.\nFor example, you created the role name \"Client\" in Ultimate Membership Plugin, then $args would be</p>\n\n<pre><code>$args = array(\n 'role' =&gt; 'um_client',\n 'orderby' =&gt; 'user_nicename',\n 'order' =&gt; 'ASC'\n);\n</code></pre>\n" } ]
2016/03/04
[ "https://wordpress.stackexchange.com/questions/219745", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81042/" ]
I've got the following error messages on the themecheck plugin in my WordPress theme. > > REQUIRED: The theme uses the register\_taxonomy() function, which is plugin-territory functionality. > > REQUIRED: The theme uses the register\_post\_type() function, which is plugin-territory functionality. > > WARNING: The theme uses the add\_shortcode() function. Custom post-content shortcodes are plugin-territory functionality. > > > I declared the `register_taxonomy()` and `register_post_type()` function in `after_setup_theme` hook. My `register_taxonomy()` function is: ``` register_taxonomy('project_cat', 'project', array( 'public' => true, 'hierarchical' => true, 'labels' => array( 'name' => 'Categories', ) )); ``` And one of my `register_post_type()` function is: ``` register_post_type('service', array( 'public' => true, 'supports' => array('title', 'thumbnail', 'editor'), 'labels' => array( 'name' => esc_html__('Services', 'textdomain'), 'add_new_item' => esc_html__('Add Service', 'textdomain'), 'add_new' => esc_html__('Add Service', 'textdomain') ) )); ``` How can I fix those issues?
There may be some different way to do that, but most proper way to do that is following. ``` <?php $args = array( 'role' => 'Your desired role goes here.', 'orderby' => 'user_nicename', 'order' => 'ASC' ); $users = get_users( $args ); echo '<ul>'; foreach ( $users as $user ) { echo '<li>' . esc_html( $user->display_name ) . '[' . esc_html( $user->user_email ) . ']</li>'; } echo '</ul>'; ?> ```
219,810
<p>I've internationalised my plugin and am now looking at how best to load the plugin's translated strings. I'm including myplugin/languages/myplugin.pot with my plugin but am not planning to distribute .po or .mo files.</p> <p><strong>My question:</strong></p> <p>Is it my job as a plugin author to use a function such as <code>load_plugin_textdomain()</code> to load translated strings or is this the job of my plugin's end user?</p> <p><strong>The reason why I'm asking:</strong></p> <p>If I were to use <code>load_plugin_textdomain()</code>, passing a third argument like in the example below will load myplugin{$locale}.mo from myplugin/languages. However, the plugin end-user will need to supply this myplugin{$locale}.mo file but, of course, when I issue a plugin update, that myplugin{$locale}.mo file will be overwritten.</p> <pre><code>function myplugin_load_textdomain() { load_plugin_textdomain( 'myplugin', false, plugin_basename( dirname( __FILE__ ) ) . '/languages' ); } add_action( 'plugins_loaded', 'myplugin_load_textdomain' ); </code></pre> <p>Ref: <a href="https://codex.wordpress.org/Function_Reference/load_plugin_textdomain" rel="nofollow">https://codex.wordpress.org/Function_Reference/load_plugin_textdomain</a></p>
[ { "answer_id": 219812, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>You need to:</p>\n\n<ul>\n<li>Call to <code>load_plugin_textdomain()</code>. (<a href=\"https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/\" rel=\"nofollow noreferrer\">See How to translate your plugin</a>).</li>\n<li>Supply the language catalogue myplugin.pot and all the localized translation mo files you want to distribute</li>\n<li>If the user want to override some translation file, he/she should use any of the available filters to do it, for example <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext\" rel=\"nofollow noreferrer\"><code>gettext</code> filter</a>, the user should not to modify the translation file directly.</li>\n<li>But really, you are required only to <a href=\"https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/\" rel=\"nofollow noreferrer\">set any string into a <code>gettext</code> function with a textdomain matching the slug of the plugin</a>. <strong>You are not required to include any language file</strong>, specially if you submit the plugin to the plugin directory because it will be imported into GlotPress in translate.wordpress.org where anyone can translate your plugin to any language and the system will generate a language pack that WordPress will download if necessary while the plugin installation. When a language pack is upadated, the admin will be noticed about the update, just like updates for plugins and themes work but separated from the plugin update.</li>\n<li><strong>Do not load languages files from <code>WP_LANG_DIR</code> directly in your plugin</strong> as overriden system like it is suggested in other answers. It can break the load of <a href=\"https://translate.wordpress.org/\" rel=\"nofollow noreferrer\">language packs from translate.wordpress.org</a> if the mo files share the same folder under <code>WP_LANG_DIR</code>. Additionally, <a href=\"https://wordpress.stackexchange.com/questions/97591/localized-wordpress-is-much-slower\">loading multiple mo files, one overriden another, can slow down your site</a>.</li>\n</ul>\n" }, { "answer_id": 219813, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": true, "text": "<p><strong>EDIT - apparently this is all wrong so please disregard.</strong></p>\n\n<p>You can use the <code>WP_LANG_DIR</code> constant to load translations from the update-safe languages directory first, and fall back to your plugin languages directory for any plugin-supplied translations. The default location is <code>wp-content/languages</code>, and users can set <code>WP_LANG_DIR</code> themselves in <code>wp-config.php</code>. When you load translations from multiple sources, the first found instance will be used, so user translations will always override any plugin-supplied translations, and allow users to do partial translations without translating all strings.</p>\n\n<pre><code>function your_plugin_load_plugin_textdomain(){\n\n $domain = 'your-plugin';\n $locale = apply_filters( 'plugin_locale', get_locale(), $domain );\n\n // wp-content/languages/your-plugin/your-plugin-de_DE.mo\n load_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain . '/' . $domain . '-' . $locale . '.mo' );\n\n // wp-content/plugins/your-plugin/languages/your-plugin-de_DE.mo\n load_plugin_textdomain( $domain, FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );\n\n}\nadd_action( 'init', 'your_plugin_load_plugin_textdomain' );\n</code></pre>\n" } ]
2016/03/05
[ "https://wordpress.stackexchange.com/questions/219810", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22599/" ]
I've internationalised my plugin and am now looking at how best to load the plugin's translated strings. I'm including myplugin/languages/myplugin.pot with my plugin but am not planning to distribute .po or .mo files. **My question:** Is it my job as a plugin author to use a function such as `load_plugin_textdomain()` to load translated strings or is this the job of my plugin's end user? **The reason why I'm asking:** If I were to use `load_plugin_textdomain()`, passing a third argument like in the example below will load myplugin{$locale}.mo from myplugin/languages. However, the plugin end-user will need to supply this myplugin{$locale}.mo file but, of course, when I issue a plugin update, that myplugin{$locale}.mo file will be overwritten. ``` function myplugin_load_textdomain() { load_plugin_textdomain( 'myplugin', false, plugin_basename( dirname( __FILE__ ) ) . '/languages' ); } add_action( 'plugins_loaded', 'myplugin_load_textdomain' ); ``` Ref: <https://codex.wordpress.org/Function_Reference/load_plugin_textdomain>
**EDIT - apparently this is all wrong so please disregard.** You can use the `WP_LANG_DIR` constant to load translations from the update-safe languages directory first, and fall back to your plugin languages directory for any plugin-supplied translations. The default location is `wp-content/languages`, and users can set `WP_LANG_DIR` themselves in `wp-config.php`. When you load translations from multiple sources, the first found instance will be used, so user translations will always override any plugin-supplied translations, and allow users to do partial translations without translating all strings. ``` function your_plugin_load_plugin_textdomain(){ $domain = 'your-plugin'; $locale = apply_filters( 'plugin_locale', get_locale(), $domain ); // wp-content/languages/your-plugin/your-plugin-de_DE.mo load_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain . '/' . $domain . '-' . $locale . '.mo' ); // wp-content/plugins/your-plugin/languages/your-plugin-de_DE.mo load_plugin_textdomain( $domain, FALSE, basename( dirname( __FILE__ ) ) . '/languages/' ); } add_action( 'init', 'your_plugin_load_plugin_textdomain' ); ```
219,828
<p>Is it possible to communicate with a plugin from an outside source?</p> <p>I have an apache web server set up with wordpress running, and I would like to have automated input from a script trigger an action in a plugin.</p> <p>I thought at first I might just be able to make a plugin that listens on a socket for input and uses hooks to call the right functions from other plugins. This just caused the website to never load completely.</p> <p>Is it possible? Am I just missing something?</p> <p>Edit: If anyone needs clarification let me know and I will do my best to explain differently. I realized that it might not be clear where the outside input would be coming from. It would be completely seperate from what is happening on the website, more like a bash script run locally on the server.</p> <p>Edit2: My question might be a duplicate of <a href="https://wordpress.stackexchange.com/questions/130169/setting-up-an-api-listening-page">Setting up an API &quot;listening&quot; page</a>, but I'm not restricted to just an HTTP post.</p> <p>Edit3: I also realized the plugin I was using might help:(plugin.php)</p> <pre><code>$address = 'localhost'; $port = 8888; if(( $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false ) { error_log("socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"); } if(socket_bind($sock, $address, $port) === false ){ error_log("socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"); } if(socket_listen($sock, 5) === false){ error_log("socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"); } socket_set_nonblock($sock); do{ if(($msgsock = socket_accept($sock)) === false ){ error_log("socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"); } else{ do{ if( false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))){ error_log("socket_read() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"); } //Do things with buf socket_close($msg_socket); } while(true); } break; } while(true); socket_close($sock); </code></pre> <p>Right now it doesn't do anything except for wait for a connection and read 2048 bytes, but when it goes to socket_accept it gets an error "Success".</p>
[ { "answer_id": 219812, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>You need to:</p>\n\n<ul>\n<li>Call to <code>load_plugin_textdomain()</code>. (<a href=\"https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/\" rel=\"nofollow noreferrer\">See How to translate your plugin</a>).</li>\n<li>Supply the language catalogue myplugin.pot and all the localized translation mo files you want to distribute</li>\n<li>If the user want to override some translation file, he/she should use any of the available filters to do it, for example <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext\" rel=\"nofollow noreferrer\"><code>gettext</code> filter</a>, the user should not to modify the translation file directly.</li>\n<li>But really, you are required only to <a href=\"https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/\" rel=\"nofollow noreferrer\">set any string into a <code>gettext</code> function with a textdomain matching the slug of the plugin</a>. <strong>You are not required to include any language file</strong>, specially if you submit the plugin to the plugin directory because it will be imported into GlotPress in translate.wordpress.org where anyone can translate your plugin to any language and the system will generate a language pack that WordPress will download if necessary while the plugin installation. When a language pack is upadated, the admin will be noticed about the update, just like updates for plugins and themes work but separated from the plugin update.</li>\n<li><strong>Do not load languages files from <code>WP_LANG_DIR</code> directly in your plugin</strong> as overriden system like it is suggested in other answers. It can break the load of <a href=\"https://translate.wordpress.org/\" rel=\"nofollow noreferrer\">language packs from translate.wordpress.org</a> if the mo files share the same folder under <code>WP_LANG_DIR</code>. Additionally, <a href=\"https://wordpress.stackexchange.com/questions/97591/localized-wordpress-is-much-slower\">loading multiple mo files, one overriden another, can slow down your site</a>.</li>\n</ul>\n" }, { "answer_id": 219813, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": true, "text": "<p><strong>EDIT - apparently this is all wrong so please disregard.</strong></p>\n\n<p>You can use the <code>WP_LANG_DIR</code> constant to load translations from the update-safe languages directory first, and fall back to your plugin languages directory for any plugin-supplied translations. The default location is <code>wp-content/languages</code>, and users can set <code>WP_LANG_DIR</code> themselves in <code>wp-config.php</code>. When you load translations from multiple sources, the first found instance will be used, so user translations will always override any plugin-supplied translations, and allow users to do partial translations without translating all strings.</p>\n\n<pre><code>function your_plugin_load_plugin_textdomain(){\n\n $domain = 'your-plugin';\n $locale = apply_filters( 'plugin_locale', get_locale(), $domain );\n\n // wp-content/languages/your-plugin/your-plugin-de_DE.mo\n load_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain . '/' . $domain . '-' . $locale . '.mo' );\n\n // wp-content/plugins/your-plugin/languages/your-plugin-de_DE.mo\n load_plugin_textdomain( $domain, FALSE, basename( dirname( __FILE__ ) ) . '/languages/' );\n\n}\nadd_action( 'init', 'your_plugin_load_plugin_textdomain' );\n</code></pre>\n" } ]
2016/03/05
[ "https://wordpress.stackexchange.com/questions/219828", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90060/" ]
Is it possible to communicate with a plugin from an outside source? I have an apache web server set up with wordpress running, and I would like to have automated input from a script trigger an action in a plugin. I thought at first I might just be able to make a plugin that listens on a socket for input and uses hooks to call the right functions from other plugins. This just caused the website to never load completely. Is it possible? Am I just missing something? Edit: If anyone needs clarification let me know and I will do my best to explain differently. I realized that it might not be clear where the outside input would be coming from. It would be completely seperate from what is happening on the website, more like a bash script run locally on the server. Edit2: My question might be a duplicate of [Setting up an API "listening" page](https://wordpress.stackexchange.com/questions/130169/setting-up-an-api-listening-page), but I'm not restricted to just an HTTP post. Edit3: I also realized the plugin I was using might help:(plugin.php) ``` $address = 'localhost'; $port = 8888; if(( $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false ) { error_log("socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"); } if(socket_bind($sock, $address, $port) === false ){ error_log("socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"); } if(socket_listen($sock, 5) === false){ error_log("socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"); } socket_set_nonblock($sock); do{ if(($msgsock = socket_accept($sock)) === false ){ error_log("socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"); } else{ do{ if( false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))){ error_log("socket_read() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"); } //Do things with buf socket_close($msg_socket); } while(true); } break; } while(true); socket_close($sock); ``` Right now it doesn't do anything except for wait for a connection and read 2048 bytes, but when it goes to socket\_accept it gets an error "Success".
**EDIT - apparently this is all wrong so please disregard.** You can use the `WP_LANG_DIR` constant to load translations from the update-safe languages directory first, and fall back to your plugin languages directory for any plugin-supplied translations. The default location is `wp-content/languages`, and users can set `WP_LANG_DIR` themselves in `wp-config.php`. When you load translations from multiple sources, the first found instance will be used, so user translations will always override any plugin-supplied translations, and allow users to do partial translations without translating all strings. ``` function your_plugin_load_plugin_textdomain(){ $domain = 'your-plugin'; $locale = apply_filters( 'plugin_locale', get_locale(), $domain ); // wp-content/languages/your-plugin/your-plugin-de_DE.mo load_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain . '/' . $domain . '-' . $locale . '.mo' ); // wp-content/plugins/your-plugin/languages/your-plugin-de_DE.mo load_plugin_textdomain( $domain, FALSE, basename( dirname( __FILE__ ) ) . '/languages/' ); } add_action( 'init', 'your_plugin_load_plugin_textdomain' ); ```
219,845
<p>To display all the categories name with checkbox from custom taxonomy called <code>ct_category</code> I have the following code: </p> <pre><code>$terms = get_terms('ct_category'); foreach ( $terms as $term ) { echo '&lt;li class='.$term-&gt;term_id.'&gt;&lt;label &gt; &lt;input class="taxonomy_category" type="checkbox" name="taxonomy_category['.$term-&gt;term_id.']" value ="'.$term-&gt;term_id.'" /&gt;'.$term-&gt;name.'&lt;/label &gt;&lt;/li&gt;'; } </code></pre> <p>I would like to display content only from checked categories. I tried following that didn't work:</p> <pre><code>$args = array( 'post_type' =&gt; 'cpt', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; $ct_category, 'field' =&gt; 'term_id', 'terms' =&gt; $_POST['taxonomy_category'] ) ) ); $loop = new WP_Query( $args ); </code></pre> <p>I can guess that the issue is in <code>'terms' =&gt; $_POST['taxonomy_category']</code>. If name attribute <code>taxonomy_category['.$term-&gt;term_id.']</code> can be displayed as array in <code>'terms' =&gt;</code>, the issue would be fixed. Spent plenty of times searching google but couldn't find any solution. </p> <p>Here is the full code</p> <pre><code>&lt;?php function add_meta_box() { add_meta_box( 'ct_metabox', 'CT', 'meta_box_content_output', 'cpt', 'normal' ); } add_action( 'add_meta_boxes', 'add_meta_box' ); function meta_box_content_output ( $post ) { wp_nonce_field( 'save_meta_box_data', 'meta_box_nonce' ); $taxonomy_category = get_post_meta( $post-&gt;ID, 'taxonomy_category', true ); function categories_checkbox(){ $terms = get_terms('ct_category'); foreach ( $terms as $term ) { echo '&lt;li class='.$term-&gt;term_id.'&gt;&lt;label &gt; &lt;input class="taxonomy_category" type="checkbox" name="taxonomy_category['.$term-&gt;term_id.']" value ="'.$term-&gt;term_id.'" /&gt;'.$term-&gt;name.'&lt;/label &gt;&lt;/li&gt;'; } } &lt;? &lt;ul&gt; &lt;li&gt; &lt;?php categories_checkbox() ?&gt; &lt;li&gt; &lt;/ul&gt; &lt;?php } function save_meta_box_data( $post_id ) { // Check if our nonce is set. if ( ! isset( $_POST['meta_box_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['meta_box_nonce'], 'save_meta_box_data' ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) &amp;&amp; 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } $taxonomy_category_value = ""; if(isset($_POST["logo_taxonomy_category"])) { $taxonomy_category_value = sanitize_text_field( $_POST["logo_taxonomy_category"] ); } update_post_meta($post_id, "logo_taxonomy_category", $taxonomy_category_value); } add_action( 'save_post', 'save_meta_box_data' ); ?&gt; &lt;?php $args = array( 'post_type' =&gt; 'cpt', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; $ct_category, 'field' =&gt; 'term_id', 'terms' =&gt; $taxonomy_category ) ) ); $loop = new WP_Query( $args ); ?&gt; </code></pre>
[ { "answer_id": 219848, "author": "willrich33", "author_id": 90020, "author_profile": "https://wordpress.stackexchange.com/users/90020", "pm_score": 0, "selected": false, "text": "<p>It is an advanced question that would take me time to debug. However I believe the 'id' value for 'field' is not right. From the documentation,</p>\n\n<blockquote>\n <p>field (string) - Select taxonomy term by. Possible values are 'term_id', 'name', 'slug' or 'term_taxonomy_id'. Default value is 'term_id'.</p>\n</blockquote>\n\n<p>I think you want term_id...</p>\n\n<p>Try 2:</p>\n\n<p>Click into your custom taxonomy called 'ct_category' and get the slug for your taxonomy. You do this in the backend probably a submenu of a custom post type.</p>\n\n<p>set up your tax_query</p>\n\n<pre><code>$tax_args = array(\n array('taxonomy' =&gt; 'ct_category', \n 'field' =&gt; 'slug', \n 'terms' =&gt; 'term_slug', \n 'operator' =&gt; 'IN')\n); \n</code></pre>\n\n<p>Set up your args</p>\n\n<pre><code>$args = array('post_type' =&gt; 'cpt',\n 'post_status' =&gt; 'publish', \n 'posts_per_page'=&gt;-1, \n 'tax_query'=&gt;$tax_args); \n\n$query = new WP_Query($args);\n</code></pre>\n\n<p>See if you can get that working...then work on getting it to work with term_id. </p>\n" }, { "answer_id": 219851, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>If <code>$taxonomy_category</code> is already an array, then:</p>\n\n<pre><code>'terms' =&gt; array($taxonomy_category)\n</code></pre>\n\n<p>should just be:</p>\n\n<pre><code>'terms' =&gt; $taxonomy_category\n</code></pre>\n\n<p>where <code>$taxonomy_category</code> is equal to whatever was submitted from your form as <code>$_POST['taxonomy_category']</code> or <code>$_GET['taxonomy_category']</code></p>\n" } ]
2016/03/06
[ "https://wordpress.stackexchange.com/questions/219845", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48090/" ]
To display all the categories name with checkbox from custom taxonomy called `ct_category` I have the following code: ``` $terms = get_terms('ct_category'); foreach ( $terms as $term ) { echo '<li class='.$term->term_id.'><label > <input class="taxonomy_category" type="checkbox" name="taxonomy_category['.$term->term_id.']" value ="'.$term->term_id.'" />'.$term->name.'</label ></li>'; } ``` I would like to display content only from checked categories. I tried following that didn't work: ``` $args = array( 'post_type' => 'cpt', 'tax_query' => array( array( 'taxonomy' => $ct_category, 'field' => 'term_id', 'terms' => $_POST['taxonomy_category'] ) ) ); $loop = new WP_Query( $args ); ``` I can guess that the issue is in `'terms' => $_POST['taxonomy_category']`. If name attribute `taxonomy_category['.$term->term_id.']` can be displayed as array in `'terms' =>`, the issue would be fixed. Spent plenty of times searching google but couldn't find any solution. Here is the full code ``` <?php function add_meta_box() { add_meta_box( 'ct_metabox', 'CT', 'meta_box_content_output', 'cpt', 'normal' ); } add_action( 'add_meta_boxes', 'add_meta_box' ); function meta_box_content_output ( $post ) { wp_nonce_field( 'save_meta_box_data', 'meta_box_nonce' ); $taxonomy_category = get_post_meta( $post->ID, 'taxonomy_category', true ); function categories_checkbox(){ $terms = get_terms('ct_category'); foreach ( $terms as $term ) { echo '<li class='.$term->term_id.'><label > <input class="taxonomy_category" type="checkbox" name="taxonomy_category['.$term->term_id.']" value ="'.$term->term_id.'" />'.$term->name.'</label ></li>'; } } <? <ul> <li> <?php categories_checkbox() ?> <li> </ul> <?php } function save_meta_box_data( $post_id ) { // Check if our nonce is set. if ( ! isset( $_POST['meta_box_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['meta_box_nonce'], 'save_meta_box_data' ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } $taxonomy_category_value = ""; if(isset($_POST["logo_taxonomy_category"])) { $taxonomy_category_value = sanitize_text_field( $_POST["logo_taxonomy_category"] ); } update_post_meta($post_id, "logo_taxonomy_category", $taxonomy_category_value); } add_action( 'save_post', 'save_meta_box_data' ); ?> <?php $args = array( 'post_type' => 'cpt', 'tax_query' => array( array( 'taxonomy' => $ct_category, 'field' => 'term_id', 'terms' => $taxonomy_category ) ) ); $loop = new WP_Query( $args ); ?> ```
If `$taxonomy_category` is already an array, then: ``` 'terms' => array($taxonomy_category) ``` should just be: ``` 'terms' => $taxonomy_category ``` where `$taxonomy_category` is equal to whatever was submitted from your form as `$_POST['taxonomy_category']` or `$_GET['taxonomy_category']`
219,867
<p>I have a setup, where I want to achieve that I have a big Picture of a product (Post-image), and then below a list of other thumbnails, which can be opened in a Lightbox. I made this, by querying the post-image in the appropriate large size, and then querying the attachment images through a WP_Query post-type. But, the problem is, that the Query get also the post-thumbnail, and not only the images attached to the post. This is the code</p> <pre><code>&lt;div class="product-img"&gt; &lt;?php if ( has_post_thumbnail()) : // Check if Thumbnail exists ?&gt; &lt;?php // get fullimage $thumb_id = get_post_thumbnail_id( $post-&gt;ID ); $image = wp_get_attachment_image_src( $thumb_id,'full' ); ?&gt; &lt;a href="&lt;?php echo $image[0]; ?&gt;" title="&lt;?php the_title(); ?&gt;" rel="lightbox"&gt; &lt;?php the_post_thumbnail( 'large' ); // large image for the single post ?&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;div class="other-images"&gt; &lt;?php /* QUery attached images */ $images_query_args = array( 'post_type' =&gt; 'attachment', 'post_status' =&gt; 'inherit', 'post_mime_type' =&gt; 'image', 'post_parent' =&gt; $post-&gt;ID ); $images_query = new WP_Query( $images_query_args ); if ( $images_query-&gt;have_posts() ) : while ( $images_query-&gt;have_posts() ) : $images_query-&gt;the_post(); ?&gt; &lt;a href="&lt;?php echo wp_get_attachment_image_url( get_the_ID(), 'large' ); ?&gt;" title="&lt;?php the_title(); ?&gt;" rel="lightbox"&gt; &lt;?php // Output the attachment image echo wp_get_attachment_image( get_the_ID(), 'thumbnail' ); ?&gt; &lt;/a&gt; &lt;?php endwhile; endif; wp_reset_postdata(); ?&gt; &lt;/div&gt; </code></pre> <p>How can I make the image_query not to display the post-image, but only the others? Or, if there exists a plugin which handles the attached galleries better (eg. custom sorting-order, better visualizing which image is attached) than the native WP, I'm also interested in reworking the code if necessary. It would be important for the editors that these galleries are per-post, and not separate, through shortcodes like eg. the NextCellent</p>
[ { "answer_id": 219848, "author": "willrich33", "author_id": 90020, "author_profile": "https://wordpress.stackexchange.com/users/90020", "pm_score": 0, "selected": false, "text": "<p>It is an advanced question that would take me time to debug. However I believe the 'id' value for 'field' is not right. From the documentation,</p>\n\n<blockquote>\n <p>field (string) - Select taxonomy term by. Possible values are 'term_id', 'name', 'slug' or 'term_taxonomy_id'. Default value is 'term_id'.</p>\n</blockquote>\n\n<p>I think you want term_id...</p>\n\n<p>Try 2:</p>\n\n<p>Click into your custom taxonomy called 'ct_category' and get the slug for your taxonomy. You do this in the backend probably a submenu of a custom post type.</p>\n\n<p>set up your tax_query</p>\n\n<pre><code>$tax_args = array(\n array('taxonomy' =&gt; 'ct_category', \n 'field' =&gt; 'slug', \n 'terms' =&gt; 'term_slug', \n 'operator' =&gt; 'IN')\n); \n</code></pre>\n\n<p>Set up your args</p>\n\n<pre><code>$args = array('post_type' =&gt; 'cpt',\n 'post_status' =&gt; 'publish', \n 'posts_per_page'=&gt;-1, \n 'tax_query'=&gt;$tax_args); \n\n$query = new WP_Query($args);\n</code></pre>\n\n<p>See if you can get that working...then work on getting it to work with term_id. </p>\n" }, { "answer_id": 219851, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>If <code>$taxonomy_category</code> is already an array, then:</p>\n\n<pre><code>'terms' =&gt; array($taxonomy_category)\n</code></pre>\n\n<p>should just be:</p>\n\n<pre><code>'terms' =&gt; $taxonomy_category\n</code></pre>\n\n<p>where <code>$taxonomy_category</code> is equal to whatever was submitted from your form as <code>$_POST['taxonomy_category']</code> or <code>$_GET['taxonomy_category']</code></p>\n" } ]
2016/03/06
[ "https://wordpress.stackexchange.com/questions/219867", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80726/" ]
I have a setup, where I want to achieve that I have a big Picture of a product (Post-image), and then below a list of other thumbnails, which can be opened in a Lightbox. I made this, by querying the post-image in the appropriate large size, and then querying the attachment images through a WP\_Query post-type. But, the problem is, that the Query get also the post-thumbnail, and not only the images attached to the post. This is the code ``` <div class="product-img"> <?php if ( has_post_thumbnail()) : // Check if Thumbnail exists ?> <?php // get fullimage $thumb_id = get_post_thumbnail_id( $post->ID ); $image = wp_get_attachment_image_src( $thumb_id,'full' ); ?> <a href="<?php echo $image[0]; ?>" title="<?php the_title(); ?>" rel="lightbox"> <?php the_post_thumbnail( 'large' ); // large image for the single post ?> </a> <?php endif; ?> <div class="other-images"> <?php /* QUery attached images */ $images_query_args = array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 'post_parent' => $post->ID ); $images_query = new WP_Query( $images_query_args ); if ( $images_query->have_posts() ) : while ( $images_query->have_posts() ) : $images_query->the_post(); ?> <a href="<?php echo wp_get_attachment_image_url( get_the_ID(), 'large' ); ?>" title="<?php the_title(); ?>" rel="lightbox"> <?php // Output the attachment image echo wp_get_attachment_image( get_the_ID(), 'thumbnail' ); ?> </a> <?php endwhile; endif; wp_reset_postdata(); ?> </div> ``` How can I make the image\_query not to display the post-image, but only the others? Or, if there exists a plugin which handles the attached galleries better (eg. custom sorting-order, better visualizing which image is attached) than the native WP, I'm also interested in reworking the code if necessary. It would be important for the editors that these galleries are per-post, and not separate, through shortcodes like eg. the NextCellent
If `$taxonomy_category` is already an array, then: ``` 'terms' => array($taxonomy_category) ``` should just be: ``` 'terms' => $taxonomy_category ``` where `$taxonomy_category` is equal to whatever was submitted from your form as `$_POST['taxonomy_category']` or `$_GET['taxonomy_category']`
219,870
<p>I am working on the data validation side of my WordPress theme. I have an option where user can input JS in the backend, and same is outputted in the front end between the script tags.</p> <p>The problem I am facing is, I am not able to find a WordPress function that allows only JavaScript to pass through. What if user types some junk, CSS/HTML in it?</p> <p>Is there any function in WordPress core/PHP that I can use? Or will I have to just echo it straightaway?</p>
[ { "answer_id": 219881, "author": "thebigtine", "author_id": 76059, "author_profile": "https://wordpress.stackexchange.com/users/76059", "pm_score": 1, "selected": false, "text": "<p>From this answer: <a href=\"https://wordpress.stackexchange.com/a/107558/76059\">https://wordpress.stackexchange.com/a/107558/76059</a></p>\n\n<p>If you want to allow the user to be able to input their own Javascript code, but you don't want to allow them to enter any HTML, you could use something like this:</p>\n\n<pre><code>preg_match( '/\\A&lt;script((?!&lt;[a-zA-Z])[\\s\\S])*&lt;/script&gt;\\Z/', trim($input) );\n</code></pre>\n\n<p>The trim function removes whitespace from the beginning and end, and the regex pattern will only match the string if it begins with <code>'&lt;script'</code>, ends with <code>'&lt;/script&gt;'</code>, and doesn't have any <code>'&lt;'</code> characters immediately followed by a letter. That should effectively keep any stray HTML out, while allowing the user to put some Javascript code using a less than operator, if they need to for some reason.</p>\n\n<p>The other thing I would do is make sure that only an administrator can set this option, and if he or she sneaks some HTML into there and breaks their own website, it's their own fault. Of course, if this is going into the database, make sure it is sanitized for SQL.</p>\n" }, { "answer_id": 219887, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>You should not let users enter JS code. Users are not developers and should not write code. Once a user writes code the responsibility of anything bad that might happen is on him, and there is very little you might or should do cause after all it is his site and if he wants to write code then who are you to tell him \"no\".</p>\n\n<p>Now, it is a very bad UX to force a user to enter JS code, so the question should be is there a better way to let user input the info without resorting to writing code (and unfortunately, not always there is one).</p>\n" }, { "answer_id": 219888, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>What you're asking for is impossible, there is no such thing as a safe javascript entry box.</p>\n\n<p>Even if we strip out extra script and style tags, it's pointless, as the javascript code itself is inherently dangerous, and can create any elements it wants using DOM construction, e.g.:</p>\n\n<pre><code>var s = jQuery( 'script', { 'src': 'example.com/dangerous.js' } );\njQuery('body').append( s );\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>var s = jQuery( 'link', {\n 'rel': 'stylesheet',\n 'type': 'text/css',\n 'href': 'example.com/broken.css'\n} );\njQuery('body').append( s );\n</code></pre>\n\n<p>Nevermind something that steals your login cookies, etc. Javascript is inherently dangerous, and what you're trying to implement is an attack vector. This isn't because people might break out of javascript, but because the javascript itself is potentially dangerous</p>\n" } ]
2016/03/06
[ "https://wordpress.stackexchange.com/questions/219870", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63853/" ]
I am working on the data validation side of my WordPress theme. I have an option where user can input JS in the backend, and same is outputted in the front end between the script tags. The problem I am facing is, I am not able to find a WordPress function that allows only JavaScript to pass through. What if user types some junk, CSS/HTML in it? Is there any function in WordPress core/PHP that I can use? Or will I have to just echo it straightaway?
What you're asking for is impossible, there is no such thing as a safe javascript entry box. Even if we strip out extra script and style tags, it's pointless, as the javascript code itself is inherently dangerous, and can create any elements it wants using DOM construction, e.g.: ``` var s = jQuery( 'script', { 'src': 'example.com/dangerous.js' } ); jQuery('body').append( s ); ``` Or ``` var s = jQuery( 'link', { 'rel': 'stylesheet', 'type': 'text/css', 'href': 'example.com/broken.css' } ); jQuery('body').append( s ); ``` Nevermind something that steals your login cookies, etc. Javascript is inherently dangerous, and what you're trying to implement is an attack vector. This isn't because people might break out of javascript, but because the javascript itself is potentially dangerous
219,874
<p>My WordPress plugin uses Chosen Select and is supposed to use the css file at <code>my-plugin/assets/resources/chosen.min.css</code>.</p> <p>Unfortunately, when another plugin also uses Chosen Select, my plugin has a tendency to grab styles from the other css file instead. </p> <p>For example, it's currently getting styles from <code>yith-woocommerce-ajax-search/plugin-fw/assets/css/chosen/chosen.css</code> which messes up all my custom styling. </p> <p>What's the best way to make sure an installation of Chosen Select (or other common things that have their own syling) doesn't get styles from other css files?</p> <p>Here's how I register the stylesheet. </p> <pre><code>function lsmi_load_admin_script() { wp_register_style( 'chosencss', plugins_url( 'assets/resources/chosen.min.css', __FILE__ ), true, '', 'all' ); wp_enqueue_style( 'chosencss' ); } </code></pre>
[ { "answer_id": 219880, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>There really is no foolproof method to detect a style sheet from other plugins or from a theme and then \"switching them off\". You can only guess that other plugins and themes will be using the same handle as you to register the style sheet with. It is however much easier if your plugin is for personal use only, then you can manually go through a plugin, get the handle of the conflicting style sheet and deregister it yourself</p>\n\n<p>You can also give your <code>wp_enqueue_scripts</code> action a very low priority (<em>very high number</em>) in order to load your style sheet as late as possible </p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'lsmi_load_admin_script', PHP_INT_MAX );\nfunction lsmi_load_admin_script() \n{\n // Deregister and dequeue other conflicting stylesheets\n wp_dequeue_style( 'chosencss' );\n wp_deregister_style( 'chosencss' );\n\n // Add your own stylesheet\n wp_register_style( 'chosencss', plugins_url( 'assets/resources/chosen.min.css', __FILE__ ), true, '', 'all' );\n wp_enqueue_style( 'chosencss' );\n}\n</code></pre>\n" }, { "answer_id": 219902, "author": "StevenV", "author_id": 90099, "author_profile": "https://wordpress.stackexchange.com/users/90099", "pm_score": 1, "selected": false, "text": "<p>The best way to avoid CSS/JS conflict between plugins is to enqueue in the right place.</p>\n\n<p>I mean, enqueue the style/script right when the script is needed and not in the registration of the styles/scripts.</p>\n\n<pre><code>function lsmi_load_admin_script() {\n wp_register_style( 'chosencss', plugins_url( 'assets/resources/chosen.min.css', __FILE__ ), true, '', 'all' );\n}\n\nadd_action( 'wp_enqueue_scripts' , 'lsmi_load_admin_script' );\n\n/* When you really need the style/script - use it */\nfunction use_my_style () {\n wp_enqueue_style('chosencss');\n}\n</code></pre>\n\n<p>This way, if you don't need a style in a certain page, you can do an if/else, according to the page/post that is going to display the style/script</p>\n" } ]
2016/03/06
[ "https://wordpress.stackexchange.com/questions/219874", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81557/" ]
My WordPress plugin uses Chosen Select and is supposed to use the css file at `my-plugin/assets/resources/chosen.min.css`. Unfortunately, when another plugin also uses Chosen Select, my plugin has a tendency to grab styles from the other css file instead. For example, it's currently getting styles from `yith-woocommerce-ajax-search/plugin-fw/assets/css/chosen/chosen.css` which messes up all my custom styling. What's the best way to make sure an installation of Chosen Select (or other common things that have their own syling) doesn't get styles from other css files? Here's how I register the stylesheet. ``` function lsmi_load_admin_script() { wp_register_style( 'chosencss', plugins_url( 'assets/resources/chosen.min.css', __FILE__ ), true, '', 'all' ); wp_enqueue_style( 'chosencss' ); } ```
There really is no foolproof method to detect a style sheet from other plugins or from a theme and then "switching them off". You can only guess that other plugins and themes will be using the same handle as you to register the style sheet with. It is however much easier if your plugin is for personal use only, then you can manually go through a plugin, get the handle of the conflicting style sheet and deregister it yourself You can also give your `wp_enqueue_scripts` action a very low priority (*very high number*) in order to load your style sheet as late as possible ``` add_action( 'wp_enqueue_scripts', 'lsmi_load_admin_script', PHP_INT_MAX ); function lsmi_load_admin_script() { // Deregister and dequeue other conflicting stylesheets wp_dequeue_style( 'chosencss' ); wp_deregister_style( 'chosencss' ); // Add your own stylesheet wp_register_style( 'chosencss', plugins_url( 'assets/resources/chosen.min.css', __FILE__ ), true, '', 'all' ); wp_enqueue_style( 'chosencss' ); } ```
219,911
<p>I'm developing my first plugin and wp_enqueue_style doesn't work. I'm in localhost (apache2) installation, ubuntu 14.04.</p> <p>In my main file I have</p> <pre><code>define( 'EASYDM_CSS_DIR', plugin_dir_path( __FILE__ ).'css/' ); add_action( 'wp_enqueue_style', 'easydm_add_link_tag_to_head' ); </code></pre> <p>And in my php functions file I have:</p> <pre><code>function easydm_add_link_tag_to_head() { wp_enqueue_style( 'style.css', EASYDM_CSS_DIR ); } </code></pre> <p>I want to style an option page, in the admin panel.</p>
[ { "answer_id": 219914, "author": "Tim Malone", "author_id": 46066, "author_profile": "https://wordpress.stackexchange.com/users/46066", "pm_score": 1, "selected": false, "text": "<p>You've given <code>wp_enqueue_style</code> a directory, but no file name. Have a look at <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/wp_enqueue_style/</a>:</p>\n\n<ul>\n<li>The first parameter of <code>wp_enqueue_style</code> is the name, or handle, of the stylesheet as referred to internally by Wordpress (this should be a unique name for each stylesheet you enqueue)</li>\n<li>The second parameter is the src to the stylesheet - so this is where you need to add both your directory and your stylesheet name</li>\n</ul>\n\n<p>So, if you change your second parameter to <code>EASYDM_CSS_DIR . \"style.css\"</code> - and just use something like <code>'my-stylesheet'</code> as the first parameter, providing everything is in the right place you should find it works. :)</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Just noticed something I didn't pick up earlier in your code: there's actually no <code>wp_enqueue_style</code> action. You need to use the <code>wp_enqueue_scripts</code> action to add both styles and scripts. This is a bit confusing, because the <em>function</em> <code>wp_enqueue_style</code> you've used <em>is</em> correct, but it's never being called because of the incorrect action.</p>\n\n<p>Change this:</p>\n\n<p><code>add_action( 'wp_enqueue_style', 'easydm_add_link_tag_to_head' );</code></p>\n\n<p>to this:</p>\n\n<p><code>add_action( 'wp_enqueue_scripts', 'easydm_add_link_tag_to_head' );</code></p>\n\n<p>and then your function <code>easydm_add_link_tag_to_head</code> should be called correctly.</p>\n\n<p>If it's still not working, it's probably down to either the path not being correct, or something else I didn't notice in the code! This is where we need to start debugging to find the issue. The simplest, crudest, easiest way to do this is just to put <code>echo 1;</code>, <code>echo 2;</code>, <code>echo 3;</code> etc. in different parts of your code - and then viewing the source of your page - to determine what is working and what isn't. Of course, it's also worth checking if the <code>&lt;link&gt;</code> tag is making it through to the source of your page, because if it is, the clue might be in the path not being correct!</p>\n" }, { "answer_id": 220037, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 0, "selected": false, "text": "<p>You need to hook into <code>admin_enqueue_scripts</code> because you want to <strong>style an option page, in the admin panel</strong>.</p>\n\n<p>Add this code and change <code>css/style.css</code> with appropriate file path if needed. Hope this works.</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', 'easydm_add_link_tag_to_head' );\nfunction easydm_add_link_tag_to_head(){\n wp_enqueue_style( 'enrique_custom', plugin_dir_url( __FILE__ ). 'css/style.css' );\n}\n</code></pre>\n" }, { "answer_id": 220038, "author": "Enrique René", "author_id": 89766, "author_profile": "https://wordpress.stackexchange.com/users/89766", "pm_score": 1, "selected": false, "text": "<p>SOLVED!!!</p>\n\n<p>The documentation for <code>wp_enqueue_style</code> function is clear to say that the second argument nedd to be relative path to the root installation WordPress. But as I viewed many examples in tutorials using full path I ignored it. Now, defining this constant and all previous steps everything runs ok.</p>\n\n<p><code>define( 'EASYDM_CSS_PATH' , str_replace( site_url().'/', '', plugin_dir_url( __FILE__ ) ).'css/' );</code></p>\n\n<p>and in function:</p>\n\n<p><code>wp_enqueue_style( 'easydm-style', '/'.EASYDM_CSS_PATH.'style.css', array(), null, 'all' );</code></p>\n\n<p>So, if someone is tired out to looking for and don't wanna read this all discussion, the final code is:</p>\n\n<pre><code>define( 'EASYDM_CSS_PATH' , str_replace( site_url().'/', '', plugin_dir_url( __FILE__ ) ).'css/' );\nadd_action( 'admin_enqueue_scripts', 'easydm_add_link_tag_to_head' );\n</code></pre>\n\n<p>functions file:</p>\n\n<pre><code>function easydm_add_link_tag_to_head() {\n wp_enqueue_style( 'easydm-style', '/'.EASYDM_CSS_PATH.'style.css', array(), null, 'all' );\n wp_enqueue_style( 'easydm-manager', '/'.EASYDM_CSS_PATH.'manager.css', array(), null, 'all' );\n}\n</code></pre>\n\n<p>Where I add two styles. I really hope this help someone. Thank you everyone!</p>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/219911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89766/" ]
I'm developing my first plugin and wp\_enqueue\_style doesn't work. I'm in localhost (apache2) installation, ubuntu 14.04. In my main file I have ``` define( 'EASYDM_CSS_DIR', plugin_dir_path( __FILE__ ).'css/' ); add_action( 'wp_enqueue_style', 'easydm_add_link_tag_to_head' ); ``` And in my php functions file I have: ``` function easydm_add_link_tag_to_head() { wp_enqueue_style( 'style.css', EASYDM_CSS_DIR ); } ``` I want to style an option page, in the admin panel.
You've given `wp_enqueue_style` a directory, but no file name. Have a look at <https://developer.wordpress.org/reference/functions/wp_enqueue_style/>: * The first parameter of `wp_enqueue_style` is the name, or handle, of the stylesheet as referred to internally by Wordpress (this should be a unique name for each stylesheet you enqueue) * The second parameter is the src to the stylesheet - so this is where you need to add both your directory and your stylesheet name So, if you change your second parameter to `EASYDM_CSS_DIR . "style.css"` - and just use something like `'my-stylesheet'` as the first parameter, providing everything is in the right place you should find it works. :) **EDIT** Just noticed something I didn't pick up earlier in your code: there's actually no `wp_enqueue_style` action. You need to use the `wp_enqueue_scripts` action to add both styles and scripts. This is a bit confusing, because the *function* `wp_enqueue_style` you've used *is* correct, but it's never being called because of the incorrect action. Change this: `add_action( 'wp_enqueue_style', 'easydm_add_link_tag_to_head' );` to this: `add_action( 'wp_enqueue_scripts', 'easydm_add_link_tag_to_head' );` and then your function `easydm_add_link_tag_to_head` should be called correctly. If it's still not working, it's probably down to either the path not being correct, or something else I didn't notice in the code! This is where we need to start debugging to find the issue. The simplest, crudest, easiest way to do this is just to put `echo 1;`, `echo 2;`, `echo 3;` etc. in different parts of your code - and then viewing the source of your page - to determine what is working and what isn't. Of course, it's also worth checking if the `<link>` tag is making it through to the source of your page, because if it is, the clue might be in the path not being correct!
219,931
<p>I am using the Wordpress theme Twenty Twelve (a child of it to be precise). </p> <p>I want to know how to insert some HTML just after body opening, in just functions.php and not using header.php. </p> <p>Is that possible?</p>
[ { "answer_id": 219938, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 6, "selected": true, "text": "<p>Twenty Twelve does not have any hooks that fire immediately after the opening <code>&lt;body&gt;</code> tag.</p>\n<p>Therefore you in your child theme which extends the parent Twenty Twelve theme, copy the <code>header.php</code> across to your child theme directory.</p>\n<p>Open the <code>header.php</code> file in your child theme and just after the opening body tag add an action hook which you can then hook onto via your <code>functions.php</code> file.</p>\n<p>For example in your <code>twenty-twelve-child/header.php</code> file:</p>\n<pre><code>&lt;body &lt;?php body_class(); ?&gt;&gt;\n\n&lt;?php do_action('after_body_open_tag'); ?&gt;\n</code></pre>\n<p>Then in your <code>twenty-twelve-child/functions.php</code> file:</p>\n<pre><code>function custom_content_after_body_open_tag() {\n\n ?&gt;\n\n &lt;div&gt;My Custom Content&lt;/div&gt;\n\n &lt;?php\n\n}\n\nadd_action('after_body_open_tag', 'custom_content_after_body_open_tag');\n</code></pre>\n<p>This will then render in your HTML as:</p>\n<pre><code>&lt;body&gt;\n&lt;div&gt;My Custom Content&lt;/div&gt;\n</code></pre>\n<p>Recommended reading:</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/do_action/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/do_action/</a></p>\n<h2>UPDATE: JULY, 2019</h2>\n<p>As commented by <a href=\"https://wordpress.stackexchange.com/questions/219931/insert-html-just-after-body-tag/219938?noredirect=1#comment504459_219938\">Junaid Bhura</a> from WordPress 5.2 a new theme helper function <a href=\"https://developer.wordpress.org/reference/functions/wp_body_open/\" rel=\"noreferrer\"><code>wp_body_open</code></a> has been introduced that is intended for use as per the likes of other helper functions <code>wp_head</code> and <code>wp_footer</code>.</p>\n<p>For example:</p>\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n\n &lt;?php wp_head(); ?&gt;\n \n &lt;/head&gt;\n &lt;body &lt;?php body_class(); ?&gt;&gt;\n \n &lt;?php wp_body_open(); ?&gt;\n\n &lt;!-- BODY CONTENT HERE --&gt;\n \n &lt;?php wp_footer(); ?&gt;\n \n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n<p>In your theme functions.php file (or suitably elsewhere)</p>\n<pre><code>function custom_content_after_body_open_tag() {\n\n ?&gt;\n\n &lt;div&gt;My Custom Content&lt;/div&gt;\n\n &lt;?php\n\n}\n\nadd_action('wp_body_open', 'custom_content_after_body_open_tag');\n</code></pre>\n<h3>IMPORTANT</h3>\n<blockquote>\n<p>You should ensure that the hook exists within the theme that you are wanting to inject-into as this may not be widely adopted by the community, yet.</p>\n<p>If <strong>NOT</strong>, you will still <strong>need to follow the principle of extending the theme with a child theme</strong> with the exception that <strong>YOU</strong> would use:</p>\n<p><code>&lt;?php wp_body_open(); ?&gt;</code></p>\n<p>...instead of OR in addition to:</p>\n<p><code>&lt;?php do_action('after_body_open_tag'); ?&gt;</code></p>\n</blockquote>\n<p>Recommended reading:</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_body_open/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/wp_body_open/</a></p>\n" }, { "answer_id": 231954, "author": "Jatinder Kaur", "author_id": 76687, "author_profile": "https://wordpress.stackexchange.com/users/76687", "pm_score": -1, "selected": false, "text": "<p>Add this code in functions.php</p>\n\n<pre><code>function my_function() {\n echo'&lt;div id=\"from_my_function\"&gt;&lt;/div&gt;';\n\n}\nadd_action('wp_head', 'my_function');\n</code></pre>\n" }, { "answer_id": 274139, "author": "Martin from WP-Stars.com", "author_id": 85008, "author_profile": "https://wordpress.stackexchange.com/users/85008", "pm_score": 2, "selected": false, "text": "<p>A very, very, very dirty solution would be:</p>\n\n<pre><code>/* Insert tracking code or other stuff directly after BODY opens */\nadd_filter('body_class', 'wps_add_tracking_body', PHP_INT_MAX); // make sure, that's the last filter in the queue\nfunction wps_add_tracking_body($classes) {\n\n // close &lt;body&gt; tag, insert stuff, open some other tag with senseless variable \n $classes[] = '\"&gt;&lt;script&gt; /* do whatever */ &lt;/script&gt;&lt;noscript&gt;&lt;/noscript novar=\"';\n\n return $classes;\n}\n</code></pre>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/219931", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87509/" ]
I am using the Wordpress theme Twenty Twelve (a child of it to be precise). I want to know how to insert some HTML just after body opening, in just functions.php and not using header.php. Is that possible?
Twenty Twelve does not have any hooks that fire immediately after the opening `<body>` tag. Therefore you in your child theme which extends the parent Twenty Twelve theme, copy the `header.php` across to your child theme directory. Open the `header.php` file in your child theme and just after the opening body tag add an action hook which you can then hook onto via your `functions.php` file. For example in your `twenty-twelve-child/header.php` file: ``` <body <?php body_class(); ?>> <?php do_action('after_body_open_tag'); ?> ``` Then in your `twenty-twelve-child/functions.php` file: ``` function custom_content_after_body_open_tag() { ?> <div>My Custom Content</div> <?php } add_action('after_body_open_tag', 'custom_content_after_body_open_tag'); ``` This will then render in your HTML as: ``` <body> <div>My Custom Content</div> ``` Recommended reading: <https://developer.wordpress.org/reference/functions/do_action/> UPDATE: JULY, 2019 ------------------ As commented by [Junaid Bhura](https://wordpress.stackexchange.com/questions/219931/insert-html-just-after-body-tag/219938?noredirect=1#comment504459_219938) from WordPress 5.2 a new theme helper function [`wp_body_open`](https://developer.wordpress.org/reference/functions/wp_body_open/) has been introduced that is intended for use as per the likes of other helper functions `wp_head` and `wp_footer`. For example: ``` <html> <head> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <?php wp_body_open(); ?> <!-- BODY CONTENT HERE --> <?php wp_footer(); ?> </body> </html> ``` In your theme functions.php file (or suitably elsewhere) ``` function custom_content_after_body_open_tag() { ?> <div>My Custom Content</div> <?php } add_action('wp_body_open', 'custom_content_after_body_open_tag'); ``` ### IMPORTANT > > You should ensure that the hook exists within the theme that you are wanting to inject-into as this may not be widely adopted by the community, yet. > > > If **NOT**, you will still **need to follow the principle of extending the theme with a child theme** with the exception that **YOU** would use: > > > `<?php wp_body_open(); ?>` > > > ...instead of OR in addition to: > > > `<?php do_action('after_body_open_tag'); ?>` > > > Recommended reading: <https://developer.wordpress.org/reference/functions/wp_body_open/>
219,954
<p>My loop below shows the latest 4 posts from the same category as the post currently being viewed. Its located within single.php. </p> <p>I'm trying to get the URL of that same category so I can link back to category.php to view all posts from that same category. I thought grabbing the category slug would work but my code below doesn't output anything:</p> <pre><code>&lt;?php global $post; $categories = get_the_category(); foreach ($categories as $category) : $exclude = get_the_ID(); $posts = get_posts('posts_per_page=4&amp;category='. $category-&gt;term_id); foreach($posts as $post) : if( $exclude != get_the_ID() ) { ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title(); ?&gt;" class="post c-1"&gt; Link to actual post&lt;/a&gt; &lt;?php } endforeach; ?&gt; &lt;a href="&lt;?php bloginfo('url'); ?&gt;/categories/&lt;?php echo $childcat-&gt;cat_slug; ?&gt;" title="View all" class="btn border"&gt;&lt;i class="i-right-double-arrow"&gt;&lt;/i&gt; View all &lt;?php echo $childcat-&gt;cat_slug; ?&gt;&lt;/a&gt; &lt;?php endforeach; wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 219955, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 4, "selected": true, "text": "<p>Use:</p>\n\n<pre><code>get_category_link( $category_id );\n</code></pre>\n\n<p>See: </p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_category_link\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/get_category_link</a></p>\n\n<p>In your specific case:</p>\n\n<pre><code>&lt;?php\nglobal $post;\n$categories = get_the_category();\n\n foreach ($categories as $category) :\n\n $exclude = get_the_ID();\n $posts = get_posts('posts_per_page=4&amp;category='. $category-&gt;term_id);\n\n foreach($posts as $post) :\n if( $exclude != get_the_ID() ) { ?&gt;\n\n &lt;a href=\"&lt;?php the_permalink(); ?&gt;\" title=\"&lt;?php the_title(); ?&gt;\" class=\"post c-1\"&gt; Link to actual post&lt;/a&gt;\n\n &lt;?php } endforeach; ?&gt;\n\n&lt;a href=\"&lt;?php echo esc_url( get_category_link( $category-&gt;term_id ) ); ?&gt;\" title=\"View all\" class=\"btn border\"&gt;&lt;i class=\"i-right-double-arrow\"&gt;&lt;/i&gt; View all &lt;?php echo $category-&gt;name; ?&gt;&lt;/a&gt;\n&lt;?php endforeach; wp_reset_postdata(); ?&gt;\n</code></pre>\n" }, { "answer_id": 378848, "author": "Mrbiizy", "author_id": 198125, "author_profile": "https://wordpress.stackexchange.com/users/198125", "pm_score": 0, "selected": false, "text": "<p><strong>A STRAIGHT FORWARD AND CLEAN CODE</strong></p>\n<p>I'm a newbie :)</p>\n<p>I modified the codes given by Adam and removed the unnecessary parts not needed to answer the initial question.</p>\n<p><em><strong>It worked for me 100%.</strong></em></p>\n<p>Give it a try.</p>\n<p>Please let me know if it worked for you too :)</p>\n<pre><code>&lt;?php $categories = get_the_category();\nforeach ($categories as $category) :\nendforeach; ?&gt;\n\n&lt;a href=&quot;&lt;?php echo esc_url( get_category_link( $category-&gt;term_id ) ); ?&gt;&quot;&gt;\n LINK TO CURRENT POST CATEGORY &gt;&gt;\n&lt;/a&gt;\n</code></pre>\n<p>OR</p>\n<pre><code>&lt;?php $categories = get_the_category();\nforeach ($categories as $category) : ?&gt;\n\nThe category is:\n&lt;a href=&quot;&lt;?php echo esc_url( get_category_link( $category-&gt;term_id ) ); ?&gt;&quot;&gt;\n &lt;?php echo $category-&gt;name; ?&gt;\n&lt;/a&gt;\n\n&lt;?php endforeach; ?&gt;\n</code></pre>\n<p>COMBINE SOME OTHER ELEMENTS AS YOU LIKE. PLAY AROUND BUDDY.</p>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/219954", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/14149/" ]
My loop below shows the latest 4 posts from the same category as the post currently being viewed. Its located within single.php. I'm trying to get the URL of that same category so I can link back to category.php to view all posts from that same category. I thought grabbing the category slug would work but my code below doesn't output anything: ``` <?php global $post; $categories = get_the_category(); foreach ($categories as $category) : $exclude = get_the_ID(); $posts = get_posts('posts_per_page=4&category='. $category->term_id); foreach($posts as $post) : if( $exclude != get_the_ID() ) { ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post c-1"> Link to actual post</a> <?php } endforeach; ?> <a href="<?php bloginfo('url'); ?>/categories/<?php echo $childcat->cat_slug; ?>" title="View all" class="btn border"><i class="i-right-double-arrow"></i> View all <?php echo $childcat->cat_slug; ?></a> <?php endforeach; wp_reset_postdata(); ?> ```
Use: ``` get_category_link( $category_id ); ``` See: <https://codex.wordpress.org/Function_Reference/get_category_link> In your specific case: ``` <?php global $post; $categories = get_the_category(); foreach ($categories as $category) : $exclude = get_the_ID(); $posts = get_posts('posts_per_page=4&category='. $category->term_id); foreach($posts as $post) : if( $exclude != get_the_ID() ) { ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post c-1"> Link to actual post</a> <?php } endforeach; ?> <a href="<?php echo esc_url( get_category_link( $category->term_id ) ); ?>" title="View all" class="btn border"><i class="i-right-double-arrow"></i> View all <?php echo $category->name; ?></a> <?php endforeach; wp_reset_postdata(); ?> ```
219,959
<p>I want to restrict pending posts to only certain users in the admin section, so I want to remove it from the post status options when viewing all posts (the bit highlighted in red in the image below):</p> <p><a href="https://i.stack.imgur.com/XHX9j.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XHX9j.png" alt="WordPress post statuses submenu"></a></p> <p>However, I can't find which hook I need to edit this. Can anyone shunt me in the right direction? I've scanned the filter reference but didn't see anything appropriate.</p>
[ { "answer_id": 219961, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 2, "selected": false, "text": "<p>The filter you are looking for is <code>views_{$this-&gt;screen-&gt;id}</code> which is located in the <code>WP_List_Table::views()</code> method.</p>\n\n<p>Where <code>$this-&gt;screen-&gt;id</code> is that of the context you are in, e.g. <code>posts</code>, <code>users</code>, etc...</p>\n\n<p>File <code>wp-admin/class-wp-list-table.php</code></p>\n\n<p>Example usage:</p>\n\n<pre><code>function filter_posts_listable_views($views) {\n //do your thing...\n\n return $views;\n}\n\nadd_filter( 'views_posts', 'filter_posts_list_table_views', 100);\n</code></pre>\n" }, { "answer_id": 219962, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>You can use the filter <code>views_edit-post</code> (or <code>views_edit-{custom-post-type}</code>) to modify the available \"views\":</p>\n\n<pre><code>add_filter('views_edit-post', 'cyb_remove_pending_filter' );\nfunction cyb_remove_pending_filter( $views ) {\n if( isset( $views['pending'] ) ) {\n unset( $views['pending'] );\n }\n return $views;\n}\n</code></pre>\n\n<p>In the above filter you need inlude the user rules you want to apply. For exmple, if you want to remove the \"Pending\" view only for users who can not edit others posts:</p>\n\n<pre><code>add_filter('views_edit-post', 'cyb_remove_pending_filter' );\nfunction cyb_remove_pending_filter( $views ) {\n if( isset( $views['pending'] ) &amp;&amp; ! current_user_can('edit_others_posts') ) {\n unset( $views['pending'] );\n }\n return $views;\n}\n</code></pre>\n\n<p>Also, if you exclude the pending view, you need to update the \"All\" post count:</p>\n\n<pre><code>add_filter('views_edit-post', 'cyb_remove_pending_filter' );\nfunction cyb_remove_pending_filter( $views ) {\n\n if( isset( $views['pending'] ) &amp;&amp; ! current_user_can('edit_others_posts') ) {\n unset( $views['pending'] );\n\n $args = [\n // Post params here\n // Include only the desired post statues for \"All\"\n 'post_status' =&gt; [ 'publish', 'draft', 'future', 'trash' ],\n 'all_posts' =&gt; 1,\n ];\n $result = new WP_Query($args);\n\n if($result-&gt;found_posts &gt; 0) {\n\n $views['all'] = sprintf( \n '&lt;a href=\"%s\"&gt;'.__('All').' &lt;span class=\"count\"&gt;(%d)&lt;/span&gt;&lt;/a&gt;',\n admin_url('edit.php?all_posts=1&amp;post_type='.get_query_var('post_type')),\n $result-&gt;found_posts\n );\n\n }\n }\n\n return $views;\n}\n</code></pre>\n\n<p>This code only remove the filter in the screen but it doesn't block the access to the post with pending status. To block the access you need to use <code>pre_get_posts</code> action. For example:</p>\n\n<pre><code>add_action( 'pre_get_posts', 'cyb_exclude_pending_posts' );\nfunction cyb_exclude_pending_posts( $query ) {\n\n // only in admin, main query and if user can not edit others posts\n if( is_admin() &amp;&amp; ! current_user_can('edit_others_posts') &amp;&amp; $query-&gt;is_main_query() ) {\n // Include only the desired post statues\n $post_status_arg = [ 'publish', 'draft', 'future', 'trash' ];\n $query-&gt;set( 'post_status', $post_status_arg );\n }\n\n}\n</code></pre>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/219959", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63673/" ]
I want to restrict pending posts to only certain users in the admin section, so I want to remove it from the post status options when viewing all posts (the bit highlighted in red in the image below): [![WordPress post statuses submenu](https://i.stack.imgur.com/XHX9j.png)](https://i.stack.imgur.com/XHX9j.png) However, I can't find which hook I need to edit this. Can anyone shunt me in the right direction? I've scanned the filter reference but didn't see anything appropriate.
The filter you are looking for is `views_{$this->screen->id}` which is located in the `WP_List_Table::views()` method. Where `$this->screen->id` is that of the context you are in, e.g. `posts`, `users`, etc... File `wp-admin/class-wp-list-table.php` Example usage: ``` function filter_posts_listable_views($views) { //do your thing... return $views; } add_filter( 'views_posts', 'filter_posts_list_table_views', 100); ```
219,974
<p>I have declared post type as below:</p> <pre><code> $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'agences'), 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'menu_position' =&gt; 5, 'taxonomies' =&gt; array('brands', 'country'), 'supports' =&gt; array('title', 'editor', 'author', 'thumbnail', 'custom-fields') ); register_post_type('destinations', $args); </code></pre> <p>Initially I was able to access single page of this post type using <code>single-agences.php</code> but now it is redirecting to 404.</p> <p>I have checked other answers and found that its a common mistake but other answers were not able to resolve this. Any help will be wonderful.</p>
[ { "answer_id": 219980, "author": "Mayeenul Islam", "author_id": 22728, "author_profile": "https://wordpress.stackexchange.com/users/22728", "pm_score": 4, "selected": false, "text": "<p>Newly registered CPT shows 404 because, the <code>register_post_type()</code> doesn't flush the rewrite rules. So it's up to you, whether you want to do it manually or automatically.</p>\n\n<h1>Manually:</h1>\n\n<p>Get to <code>/wp-admin/</code>, then Settings &raquo; Permalinks, and then just hit the <kbd>Save Changes</kbd> button to flush the rewrite rules.</p>\n\n<h1>Automatically:</h1>\n\n<p>You can flush the rewrite rules using <a href=\"https://codex.wordpress.org/Function_Reference/flush_rewrite_rules\" rel=\"nofollow noreferrer\"><code>flush_rewrite_rules()</code></a> function. But as <code>register_post_type()</code> is called in <code>init</code> hook, it will fire every time when the <code>init</code> hook will fire. The same thing the codex is saying also:</p>\n\n<blockquote>\n <p><em>This function is useful when used with custom post types as it allows for automatic flushing of the WordPress rewrite rules (usually needs to be done manually for new custom post types). However, <strong>this is an expensive operation</strong> so it should only be used when absolutely necessary.</em></p>\n</blockquote>\n\n<p>That's why it's better to hook the thing to something that fire once, and that flush rules when necessary only. As <a href=\"https://wordpress.stackexchange.com/q/219395/22728\">@cybmeta already showed that</a> to you. But you can follow @bainternet's approach as well:</p>\n\n<pre><code>/**\n * To activate CPT Single page\n * @author Bainternet\n * @link http://en.bainternet.info/2011/custom-post-type-getting-404-on-permalinks\n * ---\n */\n$set = get_option( 'post_type_rules_flased_mycpt' );\nif ( $set !== true ){\n flush_rewrite_rules( false );\n update_option( 'post_type_rules_flased_mycpt', true );\n}\n</code></pre>\n\n<p>He is saving a value to <code>options</code> table only for your post type. And if the value is not there, he's flushing rewrite rules. If it's there, he's not doing it.</p>\n\n<p>But please note, it's actually making a db call every time (if not cached). So, I'd prefer hooking the code <a href=\"https://developer.wordpress.org/reference/hooks/after_setup_theme/\" rel=\"nofollow noreferrer\"><code>after_setup_theme</code></a> for theme, or <a href=\"https://developer.wordpress.org/reference/functions/register_activation_hook/\" rel=\"nofollow noreferrer\"><code>register_activation_hook</code></a> for plugin.</p>\n\n<h1>Bonus</h1>\n\n<p>While debugging rewrite rules, plugin like these could be very helpful:</p>\n\n<ul>\n<li><a href=\"https://wordpress.org/plugins/rewrite-rules-inspector/\" rel=\"nofollow noreferrer\"><strong>Rewrite Rules Inspector</strong> <em>by Automattic</em></a></li>\n<li><a href=\"https://wordpress.org/plugins/rewrite-testing/\" rel=\"nofollow noreferrer\"><strong>Rewrite Rule Testing</strong> <em>by Matthew Boynes</em></a></li>\n<li><a href=\"https://wordpress.org/plugins/fg-debug-bar-rewrite-rules/\" rel=\"nofollow noreferrer\"><strong>Debug Bar Rewrite Rules</strong> <em>by Frédéric GILLES</em></a></li>\n</ul>\n" }, { "answer_id": 272444, "author": "Deepak jha", "author_id": 66318, "author_profile": "https://wordpress.stackexchange.com/users/66318", "pm_score": 1, "selected": true, "text": "<p>It was due to a plugin \"Remove taxonomy base slug\". It was conflicting with base slug of CPT \"destinations\". I had to use <code>add_rewrite_rule</code> to check for slug and manually redirect it to proper location</p>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/219974", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66318/" ]
I have declared post type as below: ``` $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array('slug' => 'agences'), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 5, 'taxonomies' => array('brands', 'country'), 'supports' => array('title', 'editor', 'author', 'thumbnail', 'custom-fields') ); register_post_type('destinations', $args); ``` Initially I was able to access single page of this post type using `single-agences.php` but now it is redirecting to 404. I have checked other answers and found that its a common mistake but other answers were not able to resolve this. Any help will be wonderful.
It was due to a plugin "Remove taxonomy base slug". It was conflicting with base slug of CPT "destinations". I had to use `add_rewrite_rule` to check for slug and manually redirect it to proper location
219,975
<p>I have a WordPress database with over 2 million posts. Whenever I insert a new post I have to call <code>wp_set_object_terms</code> which takes over two seconds to execute. I came across <a href="http://www.kellbot.com/wordpress-post-inserts-are-super-slow/" rel="nofollow">this post</a> that recommends calling <code>wp_defer_term_counting</code> to skip the term counting.</p> <p>Are there serious consequences to the functioning of WordPress if I use this approach?</p> <p>Here's the code from the post just in case the link goes dead:</p> <pre><code>function insert_many_posts(){ wp_defer_term_counting(true); $tasks = get_default_tasks(); for ($tasks as $task){ $post = array( 'post_title' =&gt; $task[content], 'post_author' =&gt; $current_user-&gt;ID, 'post_content' =&gt; '', 'post_type' =&gt; 'bpc_default_task', 'post_status' =&gt; 'publish' ); $task_id = wp_insert_post( $post ); if ( $task[category] ) //Make sure we're passing an int as the term so it isn't mistaken for a slug wp_set_object_terms( $task_id, array( intval( $category ) ), 'bpc_category' ); } } </code></pre>
[ { "answer_id": 219977, "author": "phatskat", "author_id": 20143, "author_profile": "https://wordpress.stackexchange.com/users/20143", "pm_score": 0, "selected": false, "text": "<p>This should be relatively safe as an operation. This is deferring the counting of terms that appears on the Edit Taxonomy page. So, it doesn't appear that there would be any serious consequences.</p>\n" }, { "answer_id": 220072, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 4, "selected": true, "text": "<p><strong>Here are some thoughts on the issue, but please note that this is by no means a conclusive answer as there may be some things I have overlooked however this should give you an insight to the potential gotchas.</strong></p>\n\n<hr>\n\n<p>Yes, technically there could be consequences.</p>\n\n<p>Where calling <code>wp_defer_term_counting(true)</code> becomes truly beneficial is when for instance you are performing a mass insertion to the database of posts and assigned terms to each object as part of the process.</p>\n\n<p>In such a case you would do the following:</p>\n\n<pre><code>wp_defer_term_counting(true); //defer counting terms\n\n//mass insertion or posts and assignment of terms here\n\nwp_defer_term_counting(false); //count terms after completing business logic\n</code></pre>\n\n<p>Now in your case, if you are only inserting one post at a time, then deferring term counting will still benefit you however by not call <code>wp_defer_term_counting(false)</code> after your operation could leave you and or other parties involved with the request in a bind if you rely upon the term count for any other logic/processing, conditional or otherwise.</p>\n\n<p>To explain further, let's say you do the following:</p>\n\n<p>Assume we have 3 terms within a taxonomy called <code>product_cat</code>, the IDs for those terms are 1 (term name A), 2 (term name B) and 3 (term name C) respectively.</p>\n\n<p>Each of the above terms already has a term count of <strong><code>5</code></strong> (just for the example).</p>\n\n<p>Then this happens...</p>\n\n<pre><code>wp_defer_term_counting(true); //defer counting terms\n\n$post_id = wp_insert_post($data);\n\nwp_set_object_terms($post_id, array(1, 2, 3), 'product_cat');\n</code></pre>\n\n<p>Then later in your logic you decide to fetch the term because you want to assess the amount of objects associated with that term and perform some other action based on the result.</p>\n\n<p>So you do this...</p>\n\n<pre><code>$terms = get_the_terms($post_id, 'product_cat');\n\n//let's just grab the first term object off the array of returned results\n//for the sake of this example $terms[0] relates to term_id 1 (A)\necho $terms[0]-&gt;count; //result 5\n\n//dump output of $terms above\narray (\n 0 =&gt; \n WP_Term::__set_state(array(\n 'term_id' =&gt; 1,\n 'name' =&gt; 'A',\n 'slug' =&gt; 'a',\n 'term_group' =&gt; 0,\n 'term_taxonomy_id' =&gt; 1,\n 'taxonomy' =&gt; 'product_cat',\n 'description' =&gt; '',\n 'parent' =&gt; 0,\n 'count' =&gt; 5, //notice term count still equal to 5 instead of 6\n 'filter' =&gt; 'raw',\n )),\n)\n</code></pre>\n\n<p>In the case of our example, we said that term name A (term_id 1) already has 5 objects associated with it, in otherwords already has a term count of 5.</p>\n\n<p>So we would expect the <code>count</code> parameter on the returned object above to be 6 but because you did not call <code>wp_defer_term_counting(false)</code> after your operation, the term counts were not updated for the terms applicable (term A, B or C).</p>\n\n<p>Therefore that is the <strong>consequence</strong> of calling <code>wp_defer_term_counting(true)</code> without calling <code>wp_defer_term_counting(false)</code> after your operation.</p>\n\n<p>Now the question is of course, does this effect you? What if you have no need to call <code>get_the_terms</code> or perform some action that retrieves the term where by you use the <code>count</code> value to perform some other operation? Well in that case <strong>great, no problem for you</strong>.</p>\n\n<p>But... what if someone else is hooked onto <code>set_object_terms</code> action in the <code>wp_set_object_terms()</code> function and they are relying upon the term count being correct? Now you see where the consequences could arise.</p>\n\n<p>Or what if after the request has terminated, another request is performed that retrieves a taxonomy term and makes use of the <code>count</code> property in their business logic? That could be a problem.</p>\n\n<p>While it may sound far fetched that <code>count</code> values could be of much harm, we cannot assume the way such data will be used based on our own philosophy.</p>\n\n<p>Also as mentioned in the alternate answer, the count as seen on the taxonomy list table will not be updated either.</p>\n\n<p>In fact the only way to update term counts after you defer term counting and your request has ended is to manually call <code>wp_update_term_count($terms, $taxonomy)</code> or wait until someone adds a term for the given taxonomy either via the taxonomy UI or programmatically.</p>\n\n<p>Food for thought.</p>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/219975", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/657/" ]
I have a WordPress database with over 2 million posts. Whenever I insert a new post I have to call `wp_set_object_terms` which takes over two seconds to execute. I came across [this post](http://www.kellbot.com/wordpress-post-inserts-are-super-slow/) that recommends calling `wp_defer_term_counting` to skip the term counting. Are there serious consequences to the functioning of WordPress if I use this approach? Here's the code from the post just in case the link goes dead: ``` function insert_many_posts(){ wp_defer_term_counting(true); $tasks = get_default_tasks(); for ($tasks as $task){ $post = array( 'post_title' => $task[content], 'post_author' => $current_user->ID, 'post_content' => '', 'post_type' => 'bpc_default_task', 'post_status' => 'publish' ); $task_id = wp_insert_post( $post ); if ( $task[category] ) //Make sure we're passing an int as the term so it isn't mistaken for a slug wp_set_object_terms( $task_id, array( intval( $category ) ), 'bpc_category' ); } } ```
**Here are some thoughts on the issue, but please note that this is by no means a conclusive answer as there may be some things I have overlooked however this should give you an insight to the potential gotchas.** --- Yes, technically there could be consequences. Where calling `wp_defer_term_counting(true)` becomes truly beneficial is when for instance you are performing a mass insertion to the database of posts and assigned terms to each object as part of the process. In such a case you would do the following: ``` wp_defer_term_counting(true); //defer counting terms //mass insertion or posts and assignment of terms here wp_defer_term_counting(false); //count terms after completing business logic ``` Now in your case, if you are only inserting one post at a time, then deferring term counting will still benefit you however by not call `wp_defer_term_counting(false)` after your operation could leave you and or other parties involved with the request in a bind if you rely upon the term count for any other logic/processing, conditional or otherwise. To explain further, let's say you do the following: Assume we have 3 terms within a taxonomy called `product_cat`, the IDs for those terms are 1 (term name A), 2 (term name B) and 3 (term name C) respectively. Each of the above terms already has a term count of **`5`** (just for the example). Then this happens... ``` wp_defer_term_counting(true); //defer counting terms $post_id = wp_insert_post($data); wp_set_object_terms($post_id, array(1, 2, 3), 'product_cat'); ``` Then later in your logic you decide to fetch the term because you want to assess the amount of objects associated with that term and perform some other action based on the result. So you do this... ``` $terms = get_the_terms($post_id, 'product_cat'); //let's just grab the first term object off the array of returned results //for the sake of this example $terms[0] relates to term_id 1 (A) echo $terms[0]->count; //result 5 //dump output of $terms above array ( 0 => WP_Term::__set_state(array( 'term_id' => 1, 'name' => 'A', 'slug' => 'a', 'term_group' => 0, 'term_taxonomy_id' => 1, 'taxonomy' => 'product_cat', 'description' => '', 'parent' => 0, 'count' => 5, //notice term count still equal to 5 instead of 6 'filter' => 'raw', )), ) ``` In the case of our example, we said that term name A (term\_id 1) already has 5 objects associated with it, in otherwords already has a term count of 5. So we would expect the `count` parameter on the returned object above to be 6 but because you did not call `wp_defer_term_counting(false)` after your operation, the term counts were not updated for the terms applicable (term A, B or C). Therefore that is the **consequence** of calling `wp_defer_term_counting(true)` without calling `wp_defer_term_counting(false)` after your operation. Now the question is of course, does this effect you? What if you have no need to call `get_the_terms` or perform some action that retrieves the term where by you use the `count` value to perform some other operation? Well in that case **great, no problem for you**. But... what if someone else is hooked onto `set_object_terms` action in the `wp_set_object_terms()` function and they are relying upon the term count being correct? Now you see where the consequences could arise. Or what if after the request has terminated, another request is performed that retrieves a taxonomy term and makes use of the `count` property in their business logic? That could be a problem. While it may sound far fetched that `count` values could be of much harm, we cannot assume the way such data will be used based on our own philosophy. Also as mentioned in the alternate answer, the count as seen on the taxonomy list table will not be updated either. In fact the only way to update term counts after you defer term counting and your request has ended is to manually call `wp_update_term_count($terms, $taxonomy)` or wait until someone adds a term for the given taxonomy either via the taxonomy UI or programmatically. Food for thought.
219,983
<p>I need help. Thanks in advance. I need a function that update post title and slug with some default title + current date when post status is updated from draft to published.</p> <p>I use this one to update the post date on status change but I need to add a functionality the title also to be updated (with a default one) plus current date also to be shown in the updated title.</p> <pre><code>//auto change post date on every status change add_filter('wp_insert_post_data','reset_post_date',99,2); function reset_post_date($data,$postarr) { $data['post_date'] = $data['post_modified']; $data['post_date_gmt'] = $data['post_modified_gmt']; return $data; } </code></pre> <p>Example:</p> <p>J. Doe register to my site and publish a new post.</p> <p>He gives the post some crazy name.</p> <p>J. Doe's post go to drafts.</p> <p>After 2 weeks Draft scheduler Plugin takes J. Doe's post from drafts and publish it by changing its status to published.</p> <p>At this point the desired function has to be able to update the post date with the current date, rename J. Doe's crazy title with a default one, add the current date into the title and update the slug.</p>
[ { "answer_id": 219992, "author": "Grandeto", "author_id": 90139, "author_profile": "https://wordpress.stackexchange.com/users/90139", "pm_score": 1, "selected": false, "text": "<p>I think I found the solution:</p>\n\n<pre><code> add_filter('wp_insert_post_data','reset_post_date',99,2);\n\n function reset_post_date($data,$postarr) {\n\n //update post time on status change\n $data['post_date'] = $data['post_modified'];\n $data['post_date_gmt'] = $data['post_modified_gmt'];\n\n //also update title and add the current date to title\n $data['post_title'] = 'Your Default Title - '. current_time ( 'm-d-Y' );\n\n //also update the slug of the post for the URL\n $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'] ), $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent'] );\n\n return $data; \n }\n</code></pre>\n" }, { "answer_id": 220262, "author": "Mohamed Rihan", "author_id": 85768, "author_profile": "https://wordpress.stackexchange.com/users/85768", "pm_score": 0, "selected": false, "text": "<p>maybe try this.</p>\n\n<pre><code>add_filter('wp_insert_post_data','reset_post_date',99,2);\n\n function reset_post_date($data,$postarr) {\n\n //update post time on status change\n $data['post_date'] = $data['post_modified'];\n $data['post_date_gmt'] = $data['post_modified_gmt'];\n\n //also update title and add the current date to title\n if( is_tax() ) {\n\n global $wp_query;\n $term = $wp_query-&gt;get_queried_object();\n $cat_name = $term-&gt;name;\n\n $data['post_title'] = $cat_name .' '. current_time ( 'm-d-Y' );\n }else{ \n $data['post_title'] = 'name'. current_time ( 'm-d-Y' );\n }\n //also update the slug of the post for the URL\n $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'] ), $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent'] );\n\n return $data; \n }\n</code></pre>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/219983", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90139/" ]
I need help. Thanks in advance. I need a function that update post title and slug with some default title + current date when post status is updated from draft to published. I use this one to update the post date on status change but I need to add a functionality the title also to be updated (with a default one) plus current date also to be shown in the updated title. ``` //auto change post date on every status change add_filter('wp_insert_post_data','reset_post_date',99,2); function reset_post_date($data,$postarr) { $data['post_date'] = $data['post_modified']; $data['post_date_gmt'] = $data['post_modified_gmt']; return $data; } ``` Example: J. Doe register to my site and publish a new post. He gives the post some crazy name. J. Doe's post go to drafts. After 2 weeks Draft scheduler Plugin takes J. Doe's post from drafts and publish it by changing its status to published. At this point the desired function has to be able to update the post date with the current date, rename J. Doe's crazy title with a default one, add the current date into the title and update the slug.
I think I found the solution: ``` add_filter('wp_insert_post_data','reset_post_date',99,2); function reset_post_date($data,$postarr) { //update post time on status change $data['post_date'] = $data['post_modified']; $data['post_date_gmt'] = $data['post_modified_gmt']; //also update title and add the current date to title $data['post_title'] = 'Your Default Title - '. current_time ( 'm-d-Y' ); //also update the slug of the post for the URL $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'] ), $postarr['ID'], $data['post_status'], $data['post_type'], $data['post_parent'] ); return $data; } ```
219,998
<p>I have a script I'd like to include with Wordpress. This script relies on another (prettyPhoto) to run, as well as on JQuery being loaded. I'd like my script to be the very last script to be included on the page.</p> <p>After reading about using wp_enqueue_scipt in this answer: <a href="https://stackoverflow.com/a/19914138/1745715">https://stackoverflow.com/a/19914138/1745715</a></p> <p>And after fostertime was nice enough to walk me through a little debugging down in the comments below, I've found that I can't enqueue my script, as the last script to load (themify.gallery.js, I was mistaken in the comments below when I thought it was carousel.js) is done so asyncronously in a function inside a Themify javascript file called main.js <em>(themes/themify-ultra/themify/js/main.js)</em></p> <p>Here's where it's loaded:</p> <pre><code> InitGallery: function ($el, $args) { var lightboxConditions = ((themifyScript.lightbox.lightboxContentImages &amp;&amp; $(themifyScript.lightbox.contentImagesAreas).length &amp;&amp; themifyScript.lightbox.lightboxGalleryOn) || themifyScript.lightbox.lightboxGalleryOn) ? true : false; if ($('.module.module-gallery').length &gt; 0 || $('.module.module-image').length &gt; 0 || $('.lightbox').length || lightboxConditions) { if ($('.module.module-gallery').length &gt; 0) this.showcaseGallery(); this.LoadAsync(themify_vars.url + '/js/themify.gallery.js', function () { Themify.GalleryCallBack($el, $args); }, null, null, function () { return ('undefined' !== typeof ThemifyGallery); }); } }, </code></pre> <p>It would stand to reason that I could simply add my javascript include right here within this function after the line that loads themify.gallery.js. However, I want to ensure that I can upgrade my themify theme without causing the change to be lost. To solve this problem I'm using a child theme. As this main.js is located within the themes folder, is it possible to overwrite it the same way I would a normal template file, and make my change? Even if it is, is it really safe to overwrite the entire main.js file when I'm concerned about my ability to upgrade Themify later down the road? Or Is there a less destructive way to inject my include code into this function from elsewhere? Open to suggestions on the best solution.</p>
[ { "answer_id": 220001, "author": "fostertime", "author_id": 90145, "author_profile": "https://wordpress.stackexchange.com/users/90145", "pm_score": 0, "selected": false, "text": "<p>I would have simply commented on your post first, but I don't have enough reputation... :/</p>\n\n<p>Are all the other scripts loaded via <code>wp_enqueue_script</code>?</p>\n\n<p>If you <code>var_dump( $GLOBALS['wp_scripts']-&gt;registered );</code> you can see all registered/enqueued scripts (via <a href=\"https://wordpress.stackexchange.com/questions/114473/wp-enqueue-script-how-to-change-loading-order-of-scripts\">wp_enqueue_script : how to change loading order of scripts?</a>)</p>\n\n<p>You should be able to change the dependency ( <code>array('jquery')</code> ) handle in your <code>wp_register_script</code> to <code>array('handle-of-last-enqueued-script')</code> this will make sure your script isn't loaded until that one is.</p>\n" }, { "answer_id": 220047, "author": "carbide20", "author_id": 90152, "author_profile": "https://wordpress.stackexchange.com/users/90152", "pm_score": 1, "selected": false, "text": "<p>After doing some reading, I found that it is not possible to overwrite one function in a JS file in that way. The solution was to overwrite the entire main.js file in order to make the change. I then enqueued my new main.js script with the exact same name that it was registered to in the original:</p>\n\n<pre><code>// Enqueue main js that will load others needed js\nwp_register_script('themify-main-script', '/wp-includes/js/main.js', array('jquery'), THEMIFY_VERSION, true);\nwp_enqueue_script('themify-main-script');\n</code></pre>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/219998", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90152/" ]
I have a script I'd like to include with Wordpress. This script relies on another (prettyPhoto) to run, as well as on JQuery being loaded. I'd like my script to be the very last script to be included on the page. After reading about using wp\_enqueue\_scipt in this answer: <https://stackoverflow.com/a/19914138/1745715> And after fostertime was nice enough to walk me through a little debugging down in the comments below, I've found that I can't enqueue my script, as the last script to load (themify.gallery.js, I was mistaken in the comments below when I thought it was carousel.js) is done so asyncronously in a function inside a Themify javascript file called main.js *(themes/themify-ultra/themify/js/main.js)* Here's where it's loaded: ``` InitGallery: function ($el, $args) { var lightboxConditions = ((themifyScript.lightbox.lightboxContentImages && $(themifyScript.lightbox.contentImagesAreas).length && themifyScript.lightbox.lightboxGalleryOn) || themifyScript.lightbox.lightboxGalleryOn) ? true : false; if ($('.module.module-gallery').length > 0 || $('.module.module-image').length > 0 || $('.lightbox').length || lightboxConditions) { if ($('.module.module-gallery').length > 0) this.showcaseGallery(); this.LoadAsync(themify_vars.url + '/js/themify.gallery.js', function () { Themify.GalleryCallBack($el, $args); }, null, null, function () { return ('undefined' !== typeof ThemifyGallery); }); } }, ``` It would stand to reason that I could simply add my javascript include right here within this function after the line that loads themify.gallery.js. However, I want to ensure that I can upgrade my themify theme without causing the change to be lost. To solve this problem I'm using a child theme. As this main.js is located within the themes folder, is it possible to overwrite it the same way I would a normal template file, and make my change? Even if it is, is it really safe to overwrite the entire main.js file when I'm concerned about my ability to upgrade Themify later down the road? Or Is there a less destructive way to inject my include code into this function from elsewhere? Open to suggestions on the best solution.
After doing some reading, I found that it is not possible to overwrite one function in a JS file in that way. The solution was to overwrite the entire main.js file in order to make the change. I then enqueued my new main.js script with the exact same name that it was registered to in the original: ``` // Enqueue main js that will load others needed js wp_register_script('themify-main-script', '/wp-includes/js/main.js', array('jquery'), THEMIFY_VERSION, true); wp_enqueue_script('themify-main-script'); ```
220,003
<p>I'm running a website that uses EasyAdmin (for user content generation).</p> <p>I created two taxonomies (via functions.php) for my own needs, but now my users can see them when they are adding their content to the website.</p> <pre><code>add_action( 'init', 'create_item_nominations' ); function create_item_nominations() { register_taxonomy( 'nominations', 'ait-dir-item', array( 'label' =&gt; __( 'Nominations' ), 'rewrite' =&gt; array( 'slug' =&gt; 'nominations' ), 'hierarchical' =&gt; true, ) ); } </code></pre> <p>I can hide them with CSS but that's not a really nice solution, more like a workaround for a while. </p> <p>Thank you</p>
[ { "answer_id": 220022, "author": "Tim Malone", "author_id": 46066, "author_profile": "https://wordpress.stackexchange.com/users/46066", "pm_score": 1, "selected": false, "text": "<p>Sounds like just setting <code>show_ui</code> to <code>false</code> will do what you're after - it will hide the taxonomy in the admin menu, and it won't create a metabox on the post edit page.</p>\n\n<p>After this:</p>\n\n<p><code>'hierarchical' =&gt; true,</code></p>\n\n<p>Add this:</p>\n\n<p><code>'show_ui' =&gt; false,</code></p>\n\n<p>You'll find a full reference of all the available arguments over at the Wordpress codex: <a href=\"https://codex.wordpress.org/Function_Reference/register_taxonomy\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/register_taxonomy</a></p>\n\n<p><strong>EDIT:</strong> (thanks to Howdy_McGee in the comments)</p>\n\n<p>This will hide from all backend users including admins. If you want the taxonomy to be visible just for admins but not lower level users, instead use:</p>\n\n<p><code>'show_ui' =&gt; current_user_can( 'administrator' ),</code></p>\n\n<p>Instead of 'administrator' here, you can also use any role at <a href=\"https://codex.wordpress.org/Roles_and_Capabilities\" rel=\"nofollow\">https://codex.wordpress.org/Roles_and_Capabilities</a> if you want more fine-grained control.</p>\n" }, { "answer_id": 220035, "author": "juz", "author_id": 68207, "author_profile": "https://wordpress.stackexchange.com/users/68207", "pm_score": 0, "selected": false, "text": "<p>I don't think you can do that via EasyAdmin (unless you change the code in the plugin). 'show_ui' is for the actual wordpress admin, it might work there but it would also remove it from the actual wordpress admin that you use.</p>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/220003", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90155/" ]
I'm running a website that uses EasyAdmin (for user content generation). I created two taxonomies (via functions.php) for my own needs, but now my users can see them when they are adding their content to the website. ``` add_action( 'init', 'create_item_nominations' ); function create_item_nominations() { register_taxonomy( 'nominations', 'ait-dir-item', array( 'label' => __( 'Nominations' ), 'rewrite' => array( 'slug' => 'nominations' ), 'hierarchical' => true, ) ); } ``` I can hide them with CSS but that's not a really nice solution, more like a workaround for a while. Thank you
Sounds like just setting `show_ui` to `false` will do what you're after - it will hide the taxonomy in the admin menu, and it won't create a metabox on the post edit page. After this: `'hierarchical' => true,` Add this: `'show_ui' => false,` You'll find a full reference of all the available arguments over at the Wordpress codex: <https://codex.wordpress.org/Function_Reference/register_taxonomy> **EDIT:** (thanks to Howdy\_McGee in the comments) This will hide from all backend users including admins. If you want the taxonomy to be visible just for admins but not lower level users, instead use: `'show_ui' => current_user_can( 'administrator' ),` Instead of 'administrator' here, you can also use any role at <https://codex.wordpress.org/Roles_and_Capabilities> if you want more fine-grained control.
220,004
<p>Basically what I am trying to achieve is to have title changed of posts which are in category number 30.</p> <p>My code is:</p> <pre><code>function adddd($title) { if(has_category('30',$post-&gt;ID)){ $title = 'Prefix '.$title; } return $title; } add_action('the_title','adddd'); </code></pre> <p>The code works, but has one issue. When I am inside the post which has that category, title is being changed for all other pages (which are called through the_title) too.</p> <p>How can I change the title only to post titles which has that category, no matter what page I am on?</p>
[ { "answer_id": 220005, "author": "nicogaldo", "author_id": 87880, "author_profile": "https://wordpress.stackexchange.com/users/87880", "pm_score": 0, "selected": false, "text": "<p>Why not use javascript/jquery?</p>\n<p>if your use <code>&lt;?php post_class(); ?&gt;</code> you can find a different class for each category.</p>\n<pre><code> $('.post.category-one').find('h2.item-title').prepend('Prefix ');\n</code></pre>\n<p>Use <code>.find()</code> to the selector title</p>\n<h2>Edit</h2>\n<p>With php try this</p>\n<pre><code>function adddd($title) {\n global $post;\n\n if(has_category('30',$post-&gt;ID)) {\n $title = 'Prefix '.$post-&gt;post_title;\n }\n\n return $title;\n}\nadd_action('the_title','adddd');\n</code></pre>\n" }, { "answer_id": 220043, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p><code>$post</code> is undefined in your filter. You need to explicitely invoke the <code>$post</code> global inside your filter function to have it available. You must remember that variables (<em>even global variables</em>) outside a function will not be available inside a function, that is how PHP works.</p>\n\n<p>You actually do not need to use the <code>$post</code> global, the post ID is passed by reference as second parameter to the <code>the_title</code> filter.</p>\n\n<p>You can use the following:</p>\n\n<pre><code>add_action( 'the_title', 'adddd', 10, 2 );\nfunction adddd( $title, $post_id ) \n{\n if( has_category( 30, $post_id ) ) {\n $title = 'Prefix ' . $title;\n }\n\n return $title;\n}\n</code></pre>\n\n<p>If you need to target only the titles of posts in the main query/loop, you can wrap your contional in an extra <code>in_the_loop()</code> condition</p>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/220004", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66106/" ]
Basically what I am trying to achieve is to have title changed of posts which are in category number 30. My code is: ``` function adddd($title) { if(has_category('30',$post->ID)){ $title = 'Prefix '.$title; } return $title; } add_action('the_title','adddd'); ``` The code works, but has one issue. When I am inside the post which has that category, title is being changed for all other pages (which are called through the\_title) too. How can I change the title only to post titles which has that category, no matter what page I am on?
`$post` is undefined in your filter. You need to explicitely invoke the `$post` global inside your filter function to have it available. You must remember that variables (*even global variables*) outside a function will not be available inside a function, that is how PHP works. You actually do not need to use the `$post` global, the post ID is passed by reference as second parameter to the `the_title` filter. You can use the following: ``` add_action( 'the_title', 'adddd', 10, 2 ); function adddd( $title, $post_id ) { if( has_category( 30, $post_id ) ) { $title = 'Prefix ' . $title; } return $title; } ``` If you need to target only the titles of posts in the main query/loop, you can wrap your contional in an extra `in_the_loop()` condition
220,014
<p>My <code>WP_Query</code> request looks like:</p> <pre><code>$query_args = array('posts_per_page' =&gt; $products, 'no_found_rows' =&gt; 1, 'post_status' =&gt; 'publish', 'post_type' =&gt; 'product' ); $query_args['meta_query'] = $woocommerce-&gt;query-&gt;get_meta_query(); $query_args['meta_query'][] = array( 'key' =&gt; '_featured', 'value' =&gt; 'yes' ); $r = new WP_Query($query_args); </code></pre> <p>What argument I need to add to return a query ordered by IDs in a particular row (ex. I need to return products IDs 161,165,131,202 in that order).</p> <p>Edit: I have added a <code>post__in</code> and <code>orderby</code> arguments which pulls only those particular products by IDs but not in the order specified in the array but it looks like based on when product was added to the back end.</p> <pre><code>$query_args = array('posts_per_page' =&gt; $products, 'no_found_rows' =&gt; 1, 'post_status' =&gt; 'publish', 'post_type' =&gt; 'product', 'post__in' =&gt; array(161,165,131,202), 'orderby' =&gt; 'post__in', 'order' =&gt; 'ASC' ); </code></pre> <p>WP Query for that looks like:</p> <pre><code>SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1 AND wp_posts.ID IN (161,165,131,202) AND wp_posts.post_type = 'product' AND ((wp_posts.post_status = 'publish')) AND ( ( wp_postmeta.meta_key = '_visibility' AND CAST(wp_postmeta.meta_value AS CHAR) IN ('visible','catalog') ) AND (mt1.meta_key = '_featured' AND CAST(mt1.meta_value AS CHAR) = 'yes' )) GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order, FIELD( wp_posts.ID, 161,165,131,202 ) LIMIT 0, 5 </code></pre> <p>no clue why <code>ORDER BY</code> is set to be <code>menu_order</code> not <code>post__in</code></p>
[ { "answer_id": 220023, "author": "Tim Malone", "author_id": 46066, "author_profile": "https://wordpress.stackexchange.com/users/46066", "pm_score": 0, "selected": false, "text": "<p>You can order in ascending or descending order, but you can't specify a custom order - in the query parameters at least.</p>\n\n<p>The easiest way to do what you're wanting to do - display featured products in a particular order - would be to rearrange the results after the query has occured. That is, if it's feasible for you to come back and change this code whenever you want to change the order (or add new products). If you want a more robust solution, I'd be looking at adding a custom field to the products, such as 'featured_order', and then ordering your query by that field. I can run through that if you wish.</p>\n\n<p>That said, assuming you're after the easiest solution here, you'll want to add something like this to the end of the code snippet you've posted:</p>\n\n<pre><code>$my_posts = array();\n$id_order = array(161, 165, 131, 202);\n\nforeach($r-&gt;posts as $key =&gt; $the_post){\n $my_posts[$the_post-&gt;ID] = $key; // store the order of the returned posts by post ID\n}\n\nforeach($id_order as $id){ // go through custom list of post IDs\n $post = $r-&gt;posts[$my_posts[$id]]; // grab the query result for the post ID we want\n setup_postdata($post);\n // the_title(); the_content(); ........\n}\n</code></pre>\n\n<p>It's important to note that if the post ID is not present in the <code>$id_order</code> array, it will NOT be shown by this code - even if it was returned by the query.</p>\n\n<p><strong>EDIT</strong>: If you want to make sure the other posts NOT in the array do still return, see the answer posted by juz.</p>\n" }, { "answer_id": 220031, "author": "juz", "author_id": 68207, "author_profile": "https://wordpress.stackexchange.com/users/68207", "pm_score": 1, "selected": false, "text": "<p>To include the other posts not in the array, you can try the following which creates an array with keys that combine the post id with an indicator so you can do a key sort (ksort) and return all the posts with the array first </p>\n\n<pre><code>$query_args = array('posts_per_page' =&gt; $products, 'no_found_rows' =&gt; 1, 'post_status' =&gt; 'publish', 'post_type' =&gt; 'product' );\n\n$r = new WP_Query($query_args);\n\n$my_posts = array();\n$id_order = array(161, 165, 131, 202);\n\nforeach($r-&gt;posts as $key =&gt; $the_post){\n if (in_array($the_post-&gt;ID, $id_order)) {\n $index = array_search($the_post-&gt;ID, $id_order);\n $my_posts[\"a\" . $index . '_' . $the_post-&gt;ID] = $the_post; // store the order of the returned posts by post ID\n } else {\n $my_posts[\"b0_\" . $the_post-&gt;ID] = $the_post; // store the order of the returned posts by post ID\n }\n}\n\nksort($my_posts);\n\nforeach($my_posts as $post){ // go through custom list of post IDs\n setup_postdata($post);\n\n // do your content here\n ?&gt;&lt;article&gt;&lt;h2&gt;&lt;?php the_title();?&gt;&lt;/h2&gt;&lt;?php\n the_content();\n ?&gt;&lt;/article&gt;&lt;?php\n}\n</code></pre>\n" }, { "answer_id": 220089, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 5, "selected": true, "text": "<p>To keep the same post order as it was passed to the <code>post__in</code> parameter, you need to pass <code>post__in</code> as value to <code>orderby</code> argument and <code>ASC</code> to the <code>order</code> argument</p>\n\n<pre><code>$query_args = [\n 'posts_per_page' =&gt; $products, \n 'no_found_rows' =&gt; true, \n 'post_type' =&gt; 'product', \n 'post__in' =&gt; [161,165,131,202],\n 'orderby' =&gt; 'post__in',\n 'order' =&gt; 'ASC'\n];\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>Looking at your edit, you have a bad filter somewhere, most probably a bad <code>pre_get_posts</code> action or a <code>posts_orderby</code> filter. Do the two following tests</p>\n\n<ul>\n<li><p>Add <code>'suppress_filters' =&gt; true,</code> to your query arguments, if that helps, you have a bad filter</p></li>\n<li><p>Add <code>remove_all_actions( 'pre_get_posts' );</code> before you do your query, if that helps, you have a bad <code>pre_get_posts</code> filter</p></li>\n<li><p>A third, but most probable useless check would be to add <code>wp_reset_query()</code> before the custom query, if that helps, you have a bad query somewhere, most probably one using <code>query_posts</code></p></li>\n</ul>\n" } ]
2016/03/07
[ "https://wordpress.stackexchange.com/questions/220014", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28491/" ]
My `WP_Query` request looks like: ``` $query_args = array('posts_per_page' => $products, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'product' ); $query_args['meta_query'] = $woocommerce->query->get_meta_query(); $query_args['meta_query'][] = array( 'key' => '_featured', 'value' => 'yes' ); $r = new WP_Query($query_args); ``` What argument I need to add to return a query ordered by IDs in a particular row (ex. I need to return products IDs 161,165,131,202 in that order). Edit: I have added a `post__in` and `orderby` arguments which pulls only those particular products by IDs but not in the order specified in the array but it looks like based on when product was added to the back end. ``` $query_args = array('posts_per_page' => $products, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'product', 'post__in' => array(161,165,131,202), 'orderby' => 'post__in', 'order' => 'ASC' ); ``` WP Query for that looks like: ``` SELECT wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1 AND wp_posts.ID IN (161,165,131,202) AND wp_posts.post_type = 'product' AND ((wp_posts.post_status = 'publish')) AND ( ( wp_postmeta.meta_key = '_visibility' AND CAST(wp_postmeta.meta_value AS CHAR) IN ('visible','catalog') ) AND (mt1.meta_key = '_featured' AND CAST(mt1.meta_value AS CHAR) = 'yes' )) GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order, FIELD( wp_posts.ID, 161,165,131,202 ) LIMIT 0, 5 ``` no clue why `ORDER BY` is set to be `menu_order` not `post__in`
To keep the same post order as it was passed to the `post__in` parameter, you need to pass `post__in` as value to `orderby` argument and `ASC` to the `order` argument ``` $query_args = [ 'posts_per_page' => $products, 'no_found_rows' => true, 'post_type' => 'product', 'post__in' => [161,165,131,202], 'orderby' => 'post__in', 'order' => 'ASC' ]; ``` EDIT ---- Looking at your edit, you have a bad filter somewhere, most probably a bad `pre_get_posts` action or a `posts_orderby` filter. Do the two following tests * Add `'suppress_filters' => true,` to your query arguments, if that helps, you have a bad filter * Add `remove_all_actions( 'pre_get_posts' );` before you do your query, if that helps, you have a bad `pre_get_posts` filter * A third, but most probable useless check would be to add `wp_reset_query()` before the custom query, if that helps, you have a bad query somewhere, most probably one using `query_posts`
220,021
<p>It took me great time today to convert one site from <a href="https://example.com" rel="nofollow">https://example.com</a> to <a href="https://sub.example2.com" rel="nofollow">https://sub.example2.com</a> from WordPress multiste installation to normal WordPress installation (read: singlesite). </p> <p>Since I started using wp-cli recently I thought it will be possible to do it only with wp-cli.</p> <p>I used wp-cli to export a database. Since my instance was prefixed as: <code>wp_9_</code></p> <p>I used the code like this:</p> <pre><code>wp db export --tables="wp_users, wp_usermeta, wp_9_posts, wp_9_comments, wp_9_links, wp_9_options, wp_9_postmeta, wp_9_terms, wp_9_term_taxonomy, wp_9_term_relationships, wp_9_termmeta, wp_9_commentmeta" </code></pre> <p>While I later found I should use something like this:</p> <pre><code>wp db export --tables=wp_users,wp_usermeta, $(wp db tables --all-tables-with-prefix 'wp_9' --format=csv --allow-root) --allow-root </code></pre> <p>For those not using the #</p> <pre><code>wp db export --tables=wp_users,wp_usermeta, $(wp db tables --all-tables-with-prefix 'wp_9' --format=csv) </code></pre> <p>Then I set:</p> <pre><code>define('WP_HOME','https://sub.example2.com'); define('WP_SITEURL','https://sub.example2.com'); </code></pre> <p>But I faced the problem: posts, guids, and meta not updated... Usually I never do the next step since it just works in numerous instances. </p> <p>But I was forced to do the following:</p> <pre><code>UPDATE wp_posts SET post_content = replace(post_content, 'https://example.com', 'https://sub.example2.com'); UPDATE wp_posts SET guid = replace(guid, 'https://example.com', 'https://sub.example2.com'); UPDATE wp_postmeta SET meta_value = replace(meta_value,'https://example.com', 'https://sub.example2.com'); </code></pre> <p>Even further, I needed to update the uploads path, in the post content and even in the post_meta, since on mulitsite the uploads path was <code>/uploads/sites/9/</code> while on a single site only <code>/uploads/</code>.</p> <p>This should also reflect in the posts and post meta like this:</p> <pre><code>UPDATE wp_posts SET post_content = replace(post_content, '/uploads/sites/9/', '/uploads/'); UPDATE wp_postmeta SET meta_value = replace(meta_value,'/uploads/sites/9/', '/uploads/'); </code></pre> <p>After this step, I manually copied files from /uploads/sites/9/ folder to the /uploads/ folder of the new WordPress instance on the same server using the <code>cp</code> command. Sadly, I haven't even considered wp-cli for that.</p> <p>I am asking is it possible to automate this processes entirely using wp-cli? It would be a great helper next time.</p>
[ { "answer_id": 225620, "author": "AntonChanning", "author_id": 5077, "author_profile": "https://wordpress.stackexchange.com/users/5077", "pm_score": 1, "selected": false, "text": "<p>If your multi-site install only has a small number of subsites, you might find it easier to just use the export and import tools from the administration area.</p>\n\n<p>For each site in the multi site install, you can download an export file that contains blog posts, pages, users, comments etc. Then you can import all these into the same single site. Might be easier than fiddling with the database...</p>\n" }, { "answer_id": 225640, "author": "Daniel Bachhuber", "author_id": 82349, "author_profile": "https://wordpress.stackexchange.com/users/82349", "pm_score": 3, "selected": true, "text": "<p>Try using the <code>10up/MU-Migration</code> command: <a href=\"https://github.com/10up/MU-Migration\" rel=\"nofollow\">https://github.com/10up/MU-Migration</a></p>\n" }, { "answer_id": 256364, "author": "Anthony", "author_id": 113266, "author_profile": "https://wordpress.stackexchange.com/users/113266", "pm_score": 0, "selected": false, "text": "<p>Instead of doing those MySQL <code>UPDATE</code> commands you can use WP-CLI's <code>wp search-replace</code> command.</p>\n\n<p>Example: <code>wp search-replace 'https://example.com' 'https://sub.example2.com'</code></p>\n\n<p>This is a serialisation-safe search and replace, so your meta won't get borked.</p>\n\n<p>More info at <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow noreferrer\">http://wp-cli.org/commands/search-replace/</a> </p>\n" } ]
2016/03/08
[ "https://wordpress.stackexchange.com/questions/220021", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88606/" ]
It took me great time today to convert one site from <https://example.com> to <https://sub.example2.com> from WordPress multiste installation to normal WordPress installation (read: singlesite). Since I started using wp-cli recently I thought it will be possible to do it only with wp-cli. I used wp-cli to export a database. Since my instance was prefixed as: `wp_9_` I used the code like this: ``` wp db export --tables="wp_users, wp_usermeta, wp_9_posts, wp_9_comments, wp_9_links, wp_9_options, wp_9_postmeta, wp_9_terms, wp_9_term_taxonomy, wp_9_term_relationships, wp_9_termmeta, wp_9_commentmeta" ``` While I later found I should use something like this: ``` wp db export --tables=wp_users,wp_usermeta, $(wp db tables --all-tables-with-prefix 'wp_9' --format=csv --allow-root) --allow-root ``` For those not using the # ``` wp db export --tables=wp_users,wp_usermeta, $(wp db tables --all-tables-with-prefix 'wp_9' --format=csv) ``` Then I set: ``` define('WP_HOME','https://sub.example2.com'); define('WP_SITEURL','https://sub.example2.com'); ``` But I faced the problem: posts, guids, and meta not updated... Usually I never do the next step since it just works in numerous instances. But I was forced to do the following: ``` UPDATE wp_posts SET post_content = replace(post_content, 'https://example.com', 'https://sub.example2.com'); UPDATE wp_posts SET guid = replace(guid, 'https://example.com', 'https://sub.example2.com'); UPDATE wp_postmeta SET meta_value = replace(meta_value,'https://example.com', 'https://sub.example2.com'); ``` Even further, I needed to update the uploads path, in the post content and even in the post\_meta, since on mulitsite the uploads path was `/uploads/sites/9/` while on a single site only `/uploads/`. This should also reflect in the posts and post meta like this: ``` UPDATE wp_posts SET post_content = replace(post_content, '/uploads/sites/9/', '/uploads/'); UPDATE wp_postmeta SET meta_value = replace(meta_value,'/uploads/sites/9/', '/uploads/'); ``` After this step, I manually copied files from /uploads/sites/9/ folder to the /uploads/ folder of the new WordPress instance on the same server using the `cp` command. Sadly, I haven't even considered wp-cli for that. I am asking is it possible to automate this processes entirely using wp-cli? It would be a great helper next time.
Try using the `10up/MU-Migration` command: <https://github.com/10up/MU-Migration>
220,029
<p>I want to display a product with a product image and when visitor hovers over that image, it will change to the first image from the product gallery. I am using this code to display the image gallery, but it displays all the images from product gallery. I just want the 1 image.</p> <pre><code> &lt;?php do_action( 'woocommerce_product_thumbnails' ); ?&gt; </code></pre> <p>Anybody know how to resolve this problem? Really appreciate any ideas.</p> <p>Regards</p>
[ { "answer_id": 220036, "author": "Isaac Lubow", "author_id": 2150, "author_profile": "https://wordpress.stackexchange.com/users/2150", "pm_score": 3, "selected": true, "text": "<p>Along with the product thumbnail (I'm assuming you have this), what you need is a list (array) of the product images - WooCommerce has such methods, eg <code>$product-&gt;get_gallery_attachment_ids()</code>.</p>\n\n<p>You can grab the first ID in the array and use it to fetch the single image using <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_image/\" rel=\"nofollow\"><code>wp_get_attachment_image()</code></a>, or <a href=\"https://codex.wordpress.org/Function_Reference/wp_get_attachment_url\" rel=\"nofollow\"><code>wp_get_attachment_url()</code></a>, etc., then use that as an alternate source for the main (thumbnail) image.</p>\n\n<p>Incidentally, the <code>woocommerce_product_thumbnails</code> call is outputting markup that you probably don't want to use. You'll need to either discard this or unhook functions from it to get the output you want.</p>\n" }, { "answer_id": 323325, "author": "Samyer", "author_id": 112788, "author_profile": "https://wordpress.stackexchange.com/users/112788", "pm_score": 1, "selected": false, "text": "<p><strong>2018 Update:</strong> Need to use <code>get_gallery_image_ids();</code> instead. Then use <code>wp_get_attachment_url()</code> with the first ID in the array returned.</p>\n\n<pre><code>$product-&gt;get_gallery_image_ids();\n</code></pre>\n" } ]
2016/03/08
[ "https://wordpress.stackexchange.com/questions/220029", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89109/" ]
I want to display a product with a product image and when visitor hovers over that image, it will change to the first image from the product gallery. I am using this code to display the image gallery, but it displays all the images from product gallery. I just want the 1 image. ``` <?php do_action( 'woocommerce_product_thumbnails' ); ?> ``` Anybody know how to resolve this problem? Really appreciate any ideas. Regards
Along with the product thumbnail (I'm assuming you have this), what you need is a list (array) of the product images - WooCommerce has such methods, eg `$product->get_gallery_attachment_ids()`. You can grab the first ID in the array and use it to fetch the single image using [`wp_get_attachment_image()`](https://developer.wordpress.org/reference/functions/wp_get_attachment_image/), or [`wp_get_attachment_url()`](https://codex.wordpress.org/Function_Reference/wp_get_attachment_url), etc., then use that as an alternate source for the main (thumbnail) image. Incidentally, the `woocommerce_product_thumbnails` call is outputting markup that you probably don't want to use. You'll need to either discard this or unhook functions from it to get the output you want.
220,059
<p>A WordPress website is created and MySQL is the database for it. When tried to import the database to an empty database via Linux Command Shell we encountered below errors:</p> <blockquote> <p>ERROR 1146 (42S02): Table 'xx-xxx-xxx-xxx' doesn't exist</p> <p>ERROR 1273 (HY000): Unknown collation: 'utf8mb4_unicode_ci'</p> <p>ERROR 1115 (42000): Unknown character set: 'utf8mb4'</p> </blockquote> <p>What could be the possible cause for these errors? Or should we try an alternative step to restore my WordPress website?</p> <p>The source database version is mysqlnd 5.0.12 and the destination database is mySQL 5.1.66.</p>
[ { "answer_id": 220061, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>When exporting from original database you should choose to create the tables if they dosn't exist (First error). If you didn't choose that option (in phpMyAdmin that option exists, not sure in other database tools), the import file can not create the tables for your and you need to create then prior to start importing it.</p>\n\n<p>For second and third error, you should upgrade your database version to MySQL 5.5.3 or later. Although WordPress can run on MySQL 5.0+, <a href=\"https://wordpress.org/about/requirements/\" rel=\"nofollow\">the recommended MySQL version is 5.6 or greater</a>. The problem is that WordPress updates the database to use utf8mb4 if database version is 5.5.3 or later, so probably the source database version was greater than 5.5.3 and the destination database version is lesser than 5.5.3.</p>\n\n<p>If you can not upgrade the destination databser version, edit the import file to change the collation utf8_general_ci and character set to utf8.</p>\n\n<p>Lood for lines similar to:</p>\n\n<pre><code>SET character_set_client = utf8mb4 ;\nSET character_set_results = utf8mb4 ;\nSET collation_connection = utf8mb4_unicode_ci;\n</code></pre>\n\n<p>and change them.</p>\n" }, { "answer_id": 243705, "author": "user105529", "author_id": 105529, "author_profile": "https://wordpress.stackexchange.com/users/105529", "pm_score": 1, "selected": false, "text": "<p>change all of utf8mb4_unicode_520_ci to utf8mb4_general_ci</p>\n" }, { "answer_id": 249692, "author": "Trilok Mohnani", "author_id": 109214, "author_profile": "https://wordpress.stackexchange.com/users/109214", "pm_score": 0, "selected": false, "text": "<p>Instead Connect the server with mysql workbench application.</p>\n\n<p>Create the new database with all the permissions in place.</p>\n\n<p>Change the collation on created DB by selecting the gear icon on DB to utf8</p>\n\n<p>and then import.</p>\n" } ]
2016/03/08
[ "https://wordpress.stackexchange.com/questions/220059", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75992/" ]
A WordPress website is created and MySQL is the database for it. When tried to import the database to an empty database via Linux Command Shell we encountered below errors: > > ERROR 1146 (42S02): Table 'xx-xxx-xxx-xxx' doesn't exist > > > ERROR 1273 (HY000): Unknown collation: 'utf8mb4\_unicode\_ci' > > > ERROR 1115 (42000): Unknown character set: 'utf8mb4' > > > What could be the possible cause for these errors? Or should we try an alternative step to restore my WordPress website? The source database version is mysqlnd 5.0.12 and the destination database is mySQL 5.1.66.
When exporting from original database you should choose to create the tables if they dosn't exist (First error). If you didn't choose that option (in phpMyAdmin that option exists, not sure in other database tools), the import file can not create the tables for your and you need to create then prior to start importing it. For second and third error, you should upgrade your database version to MySQL 5.5.3 or later. Although WordPress can run on MySQL 5.0+, [the recommended MySQL version is 5.6 or greater](https://wordpress.org/about/requirements/). The problem is that WordPress updates the database to use utf8mb4 if database version is 5.5.3 or later, so probably the source database version was greater than 5.5.3 and the destination database version is lesser than 5.5.3. If you can not upgrade the destination databser version, edit the import file to change the collation utf8\_general\_ci and character set to utf8. Lood for lines similar to: ``` SET character_set_client = utf8mb4 ; SET character_set_results = utf8mb4 ; SET collation_connection = utf8mb4_unicode_ci; ``` and change them.
220,073
<p>While looking for proper form submission handling in plugins for users (frontend) I've stumbled upon this article <a href="http://www.sitepoint.com/handling-post-requests-the-wordpress-way/">Handling POST Requests the WordPress Way</a>, which encourages to use <code>admin-post.php</code> for this purpose. Taking a look into header we can find some kind of confirmation:</p> <pre><code> /** * WordPress Generic Request (POST/GET) Handler * * Intended for form submission handling in themes and plugins. * * @package WordPress * @subpackage Administration */ </code></pre> <p>My main concern is that this method comes from admin part of WP code and its use in non-admin tasks makes some ambiguity.</p> <p>Can anyone (especially WP authors) confirm that this approach intention is really holistic or admin only as I think?</p>
[ { "answer_id": 220074, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 2, "selected": false, "text": "<p>Seems fairly clear from the use of the <code>nopriv</code> handling (for non logged in users) in <code>admin-post.php</code> that this is indeed useable for both frontend and backend form handling, very similar to how <code>admin-ajax.php</code> can be used. </p>\n" }, { "answer_id": 220075, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 4, "selected": false, "text": "<p><code>admin-post.php</code> is like a poor mans controller for handling requests.</p>\n\n<p>It's useful in the sense that you don't need to process your request on an alternative hook such as <code>init</code> and check to see whether or not special keys exists on the superglobals, like:</p>\n\n<pre><code>function handle_request() {\n\n if ( !empty($_POST['action']) &amp;&amp; $_POST['action'] === 'xyz' ) {\n //do business logic\n }\n\n}\n\nadd_action('init', 'handle_request');\n</code></pre>\n\n<p>Instead using admin-post.php affords you the ability to specify a callback function that will always be called on any request that supplies an action value that matches the suffix supplied to the action.</p>\n\n<pre><code>function handle_request() {\n\n //do business logic here...\n\n}\n\nadd_action( 'admin_post_handle_request', 'handle_request' );\nadd_action( 'admin_post_nopriv_handle_request', 'handle_request' );\n</code></pre>\n\n<p>In the above example, we can forgoe the need to check for <code>!empty($_POST['action']) &amp;&amp; $_POST['action'] === 'xyz'</code> because at this point that processing has been taken care of for us.</p>\n\n<p>That is the result of the specifying the action parameter and value and posting said value to the <code>admin-post.php</code> URL.</p>\n\n<p>Additionally what is beneficial is that <code>admin-post.php</code> handles both <code>$_POST</code> and <code>$_GET</code> so it's not neccessary to check what kind of method the request is of course unless you want to for more complex processing.</p>\n\n<p>Bottom line:</p>\n\n<p>It is safe to use, it's just the name that throws you off.</p>\n\n<p>By the way you should also remember to <code>wp_redirect()</code> the user back to an acceptable location as requesting <code>admin-post.php</code> will return nothing but a white screen as its response.</p>\n" } ]
2016/03/08
[ "https://wordpress.stackexchange.com/questions/220073", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89088/" ]
While looking for proper form submission handling in plugins for users (frontend) I've stumbled upon this article [Handling POST Requests the WordPress Way](http://www.sitepoint.com/handling-post-requests-the-wordpress-way/), which encourages to use `admin-post.php` for this purpose. Taking a look into header we can find some kind of confirmation: ``` /** * WordPress Generic Request (POST/GET) Handler * * Intended for form submission handling in themes and plugins. * * @package WordPress * @subpackage Administration */ ``` My main concern is that this method comes from admin part of WP code and its use in non-admin tasks makes some ambiguity. Can anyone (especially WP authors) confirm that this approach intention is really holistic or admin only as I think?
`admin-post.php` is like a poor mans controller for handling requests. It's useful in the sense that you don't need to process your request on an alternative hook such as `init` and check to see whether or not special keys exists on the superglobals, like: ``` function handle_request() { if ( !empty($_POST['action']) && $_POST['action'] === 'xyz' ) { //do business logic } } add_action('init', 'handle_request'); ``` Instead using admin-post.php affords you the ability to specify a callback function that will always be called on any request that supplies an action value that matches the suffix supplied to the action. ``` function handle_request() { //do business logic here... } add_action( 'admin_post_handle_request', 'handle_request' ); add_action( 'admin_post_nopriv_handle_request', 'handle_request' ); ``` In the above example, we can forgoe the need to check for `!empty($_POST['action']) && $_POST['action'] === 'xyz'` because at this point that processing has been taken care of for us. That is the result of the specifying the action parameter and value and posting said value to the `admin-post.php` URL. Additionally what is beneficial is that `admin-post.php` handles both `$_POST` and `$_GET` so it's not neccessary to check what kind of method the request is of course unless you want to for more complex processing. Bottom line: It is safe to use, it's just the name that throws you off. By the way you should also remember to `wp_redirect()` the user back to an acceptable location as requesting `admin-post.php` will return nothing but a white screen as its response.
220,079
<p>I use this function to insert at the beginning of the loop two post at my convenience (with meta key and value) </p> <pre><code>add_filter( 'posts_results', 'insert_post_wpse_96347', 10, 2 ); function insert_post_wpse_96347( $posts, \WP_Query $q ) { remove_filter( current_filter(), __FUNCTION__ ); if ( $q-&gt;is_main_query() &amp;&amp; $q-&gt;is_home() &amp;&amp; 0 == get_query_var( 'paged' ) ) { $args = [ 'meta_key' =&gt; 'caja', 'meta_value' =&gt; ['uno','dos'], 'post__not_in' =&gt; get_option( "sticky_posts" ), 'posts_per_page' =&gt; '2', 'suppress_filters' =&gt; true ]; $p2insert = new WP_Query($args); $insert_at = 0; if ( !empty( $p2insert-&gt;posts ) ) { array_splice( $posts, $insert_at, 0, $p2insert-&gt;posts ); } } return $posts; } </code></pre> <p>But these posts still appear in the loop, they would have to hide to not look twice.</p> <p>How can I do this?</p>
[ { "answer_id": 220094, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 0, "selected": false, "text": "<p>Try this instead:</p>\n\n<p><strong>NOTE: make sure to add any extra conditional logic you need for your usecase, such as a check for <code>is_home()</code> and the value for <code>get_query_var( 'paged' )</code>. I have intentionally left those out just for brevity.</strong> </p>\n\n<pre><code>function custom_pre_get_posts_meta_query( $query ) {\n\n if ( is_admin() || ! $query-&gt;is_main_query() )\n return;\n\n\n $meta_key = 'caja'; //meta_key to query\n\n $query-&gt;set( \n 'orderby', \n array(\n 'meta_value' =&gt; 'DESC',\n 'date' =&gt; 'DESC'\n ) \n );\n\n $query-&gt;set( \n 'meta_query', \n array(\n array(\n 'key' =&gt; $meta_key,\n 'value' =&gt; 'IGNORE THIS VALUE', //this just needs to be something random\n 'compare' =&gt; 'NOT EXISTS'\n )\n )\n );\n\n add_filter( 'posts_where', 'custom_where_meta_query' );\n\n} \n\nadd_action( 'pre_get_posts', 'custom_pre_get_posts_meta_query', 1 );\n\n\nfunction custom_where_meta_query( $where = '' ){\n\n global $wpdb;\n\n $meta_key = 'caja'; //meta_key\n $meta_values = array('uno', 'dos'); //meta_values\n\n $sql = \"'\" . implode( \"', '\", array_map( 'esc_sql', $meta_values ) ) . \"'\";\n\n $where .= $wpdb-&gt;prepare( \n \" OR (( {$wpdb-&gt;postmeta}.meta_key = %s AND {$wpdb-&gt;postmeta}.meta_value IN ( {$sql} ) ))\", \n $meta_key\n );\n\n remove_filter( 'posts_where', 'custom_where_meta_query' );\n\n return $where;\n\n}\n</code></pre>\n\n<p>The first callback function on <code>pre_get_posts</code> will initiate <code>WP_Meta_Query</code> which builds the neccessary SQL that we then filter in the second callback function.</p>\n\n<p>The results are first ordered by <code>meta_value DESC</code> then by <code>date DESC</code>. This will group the two matched posts for the meta key <code>caja</code> at the top and the remaining posts will be sorted by date thereafter.</p>\n\n<p>This avoids you having to re-query the database for two specific posts you want, then splice the result set and finally purge the result set of the duplicates.</p>\n" }, { "answer_id": 220108, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": true, "text": "<p>We can try the following alternative way:</p>\n\n<ul>\n<li><p>Remove the two posts we select via our custom query from the main query via the <code>pre_get_posts</code> action</p></li>\n<li><p>Return the two posts on top of page one via the <code>the_posts</code> filter</p></li>\n</ul>\n\n<p>Lets look at possible code:</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n remove_filter( current_filter(), __FUNCTION__ );\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 // Set our query args and run our query to get the required post ID's\n $args = [\n 'meta_key' =&gt; 'caja', \n 'meta_value' =&gt; ['uno','dos'], \n 'posts_per_page' =&gt; '2',\n 'fields' =&gt; 'ids', // Get only post ID's\n ]; \n $ids = get_posts( $args );\n\n // Make sure we have ID's, if not, bail\n if ( !$ids )\n return;\n\n // We have id's, lets remove them from the main query\n $q-&gt;set( 'post__not_in', $ids );\n\n // Lets add the two posts in front on page one\n if ( $q-&gt;is_paged() )\n return;\n\n add_filter( 'the_posts', function ( $posts, $q ) use ( $args )\n {\n if ( !$q-&gt;is_main_query() )\n return $posts;\n\n // Lets run our query to get the posts to add\n $args['fields'] = 'all';\n $posts_to_add = get_posts( $args );\n\n $stickies = get_option( 'sticky_posts' );\n if ( $stickies ) {\n $sticky_count = count( $stickies );\n array_splice( $posts, $sticky_count, 0, $posts_to_add );\n\n return $posts;\n }\n\n // Add these two posts in front\n $posts = array_merge( $posts_to_add, $posts );\n\n return $posts;\n }, 10, 2 );\n }\n}); \n</code></pre>\n\n<p>This should replace the current code that you have posted in your question</p>\n" } ]
2016/03/08
[ "https://wordpress.stackexchange.com/questions/220079", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87880/" ]
I use this function to insert at the beginning of the loop two post at my convenience (with meta key and value) ``` add_filter( 'posts_results', 'insert_post_wpse_96347', 10, 2 ); function insert_post_wpse_96347( $posts, \WP_Query $q ) { remove_filter( current_filter(), __FUNCTION__ ); if ( $q->is_main_query() && $q->is_home() && 0 == get_query_var( 'paged' ) ) { $args = [ 'meta_key' => 'caja', 'meta_value' => ['uno','dos'], 'post__not_in' => get_option( "sticky_posts" ), 'posts_per_page' => '2', 'suppress_filters' => true ]; $p2insert = new WP_Query($args); $insert_at = 0; if ( !empty( $p2insert->posts ) ) { array_splice( $posts, $insert_at, 0, $p2insert->posts ); } } return $posts; } ``` But these posts still appear in the loop, they would have to hide to not look twice. How can I do this?
We can try the following alternative way: * Remove the two posts we select via our custom query from the main query via the `pre_get_posts` action * Return the two posts on top of page one via the `the_posts` filter Lets look at possible code: ``` add_action( 'pre_get_posts', function ( $q ) { remove_filter( current_filter(), __FUNCTION__ ); if ( $q->is_home() // Only target the home page && $q->is_main_query() // Only target the main query ) { // Set our query args and run our query to get the required post ID's $args = [ 'meta_key' => 'caja', 'meta_value' => ['uno','dos'], 'posts_per_page' => '2', 'fields' => 'ids', // Get only post ID's ]; $ids = get_posts( $args ); // Make sure we have ID's, if not, bail if ( !$ids ) return; // We have id's, lets remove them from the main query $q->set( 'post__not_in', $ids ); // Lets add the two posts in front on page one if ( $q->is_paged() ) return; add_filter( 'the_posts', function ( $posts, $q ) use ( $args ) { if ( !$q->is_main_query() ) return $posts; // Lets run our query to get the posts to add $args['fields'] = 'all'; $posts_to_add = get_posts( $args ); $stickies = get_option( 'sticky_posts' ); if ( $stickies ) { $sticky_count = count( $stickies ); array_splice( $posts, $sticky_count, 0, $posts_to_add ); return $posts; } // Add these two posts in front $posts = array_merge( $posts_to_add, $posts ); return $posts; }, 10, 2 ); } }); ``` This should replace the current code that you have posted in your question
220,082
<p>For each post, I use the custom excerpt field to write a custom excerpt (180 characters max) for each of my posts, which I use as the meta description of my post for SEO.</p> <p>When I show a list of my posts (archive pages, categories etc.) this excerpt is displayed as "teaser text" for each of my posts. The problem is that this text is too short, as it is written for meta description purposes.</p> <p>Would it be possible to have a longer excerpt showing in category and index pages, yet keep my custom excerpt as a meta description of each post?</p> <p>Btw, most of my posts have a specifically placed "read more" tag, which now is ignored as I have a custom excerpt.</p>
[ { "answer_id": 220098, "author": "thebigtine", "author_id": 76059, "author_profile": "https://wordpress.stackexchange.com/users/76059", "pm_score": 1, "selected": false, "text": "<p>This is a function that I use all the time to create a custom excerpt:</p>\n\n<pre><code>function custom_excerpt( $limit, $post_id=NULL ) \n{\n if ( $post_id == NULL ) { \n $the_excerpt = get_the_excerpt(); \n } else { \n $the_excerpt = get_the_excerpt($post_id); \n }\n\n $excerpt = explode( ' ', $the_excerpt, $limit ); \n\n if ( count( $excerpt ) &gt;= $limit ) {\n array_pop($excerpt);\n $excerpt = implode( \" \",$excerpt ) . '...';\n } else {\n $excerpt = implode( \" \",$excerpt );\n } \n $excerpt = preg_replace( '`\\[[^\\]]*\\]`', '', $excerpt );\n\nreturn $excerpt;\n} \n</code></pre>\n\n<p>Then you would use it like so in your theme templates where you want to use your custom excerpt length </p>\n\n<pre><code>echo custom_excerpt(50,1);\n</code></pre>\n\n<p>or without defining the post id</p>\n\n<pre><code>echo custom_excerpt(50,NULL);\n</code></pre>\n\n<p>Where the first number (50) is the length of the excerpt and the second number (1) is the post id. </p>\n" }, { "answer_id": 220103, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>We can try to filter the excerpt through the <a href=\"https://developer.wordpress.org/reference/hooks/get_the_excerpt/\" rel=\"nofollow\"><code>get_the_excerpt</code></a> filter. By default, if we have a manual excerpt, the manual excerpt will be used and not the automatically created excerpt which is created by the <a href=\"https://developer.wordpress.org/reference/functions/wp_trim_excerpt/\" rel=\"nofollow\"><code>wp_trim_excerpt()</code></a> function.</p>\n\n<p>We can alter this behavior. What we will do is, when we are inside the main query (<em><code>in_the_loop()</code></em>), we will return the output from the <code>wp_trim_excerpt()</code> function. This way, we keep all filters as per default. Whenever we are outside the main query, we can return the manually created excerpt, if it exists, otherwise the normal excerpt</p>\n\n<pre><code>add_filter( 'get_the_excerpt', function( $text )\n{\n if ( in_the_loop() ) \n return wp_trim_excerpt();\n\n return $text;\n});\n</code></pre>\n" } ]
2016/03/08
[ "https://wordpress.stackexchange.com/questions/220082", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80031/" ]
For each post, I use the custom excerpt field to write a custom excerpt (180 characters max) for each of my posts, which I use as the meta description of my post for SEO. When I show a list of my posts (archive pages, categories etc.) this excerpt is displayed as "teaser text" for each of my posts. The problem is that this text is too short, as it is written for meta description purposes. Would it be possible to have a longer excerpt showing in category and index pages, yet keep my custom excerpt as a meta description of each post? Btw, most of my posts have a specifically placed "read more" tag, which now is ignored as I have a custom excerpt.
We can try to filter the excerpt through the [`get_the_excerpt`](https://developer.wordpress.org/reference/hooks/get_the_excerpt/) filter. By default, if we have a manual excerpt, the manual excerpt will be used and not the automatically created excerpt which is created by the [`wp_trim_excerpt()`](https://developer.wordpress.org/reference/functions/wp_trim_excerpt/) function. We can alter this behavior. What we will do is, when we are inside the main query (*`in_the_loop()`*), we will return the output from the `wp_trim_excerpt()` function. This way, we keep all filters as per default. Whenever we are outside the main query, we can return the manually created excerpt, if it exists, otherwise the normal excerpt ``` add_filter( 'get_the_excerpt', function( $text ) { if ( in_the_loop() ) return wp_trim_excerpt(); return $text; }); ```
220,111
<p>I want to pass a variable from my child theme function to a filter which resides in my parent theme. Please let me know whether below code will work or not ? Is it the right way ?</p> <p><strong>Code in Parent Theme's functions.php</strong></p> <pre><code>add_filter( 'post_thumbnail_html', "map_thumbnail" ); function map_thumbnail($html,$color) { $my_post = get_post($post-&gt;ID); $my_color = $color; if($my_post-&gt;post_name == "contact") { $html = '&lt;img src="http://maps.googleapis.com/maps/api/staticmap?color:$my_color"&gt;'; } return $html; } </code></pre> <p><strong>Code in Child Theme's functions.php</strong></p> <pre><code>&lt;?php map_thumbnail('#0099dd'); ?&gt; </code></pre> <p>Please tell me, will above code work? Can I pass the variable <code>$color</code> from my child theme to parent theme like this ?</p>
[ { "answer_id": 220113, "author": "Brent", "author_id": 10972, "author_profile": "https://wordpress.stackexchange.com/users/10972", "pm_score": 1, "selected": false, "text": "<p>I'm not exactly sure what you're trying to accomplish but this won't work because your trying to use or call the function that is declared in the parent theme instead of replacing it with a new function. I'm not sure if replacing a function in the child theme would work either. Maybe someone else can help answer that. </p>\n\n<p>The function <code>map_thumbnail()</code> that you're trying to call in the child theme, is actually being used by the <code>add_filter()</code> function right above it to modify the existing function <code>post_thumbnail_html()</code>. </p>\n\n<p>Additionally, even if it would work, you only passed one paramater ('#0099dd') in your attempt to call the function, and it appears to be out of order. </p>\n" }, { "answer_id": 220115, "author": "Apeiron", "author_id": 88938, "author_profile": "https://wordpress.stackexchange.com/users/88938", "pm_score": 0, "selected": false, "text": "<p><code>apply_filter('post_thumbnail_html', $color)</code>. I guess you need this one no?</p>\n\n<p><strong>Call the functions added to a filter hook.</strong></p>\n\n<p>The callback functions attached to filter hook $tag are invoked by calling this function. This function can be used to create a new filter hook by simply calling this function with the name of the new hook specified using the $tag parameter.</p>\n\n<p>The function allows for additional arguments to be added and passed to hooks.</p>\n\n<p>Here is the doc <a href=\"https://developer.wordpress.org/reference/functions/apply_filters/\" rel=\"nofollow\">apply_filters</a></p>\n" }, { "answer_id": 244917, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 0, "selected": false, "text": "<p>Before we get to a solution, let's take a look at how functions work.</p>\n\n<p>Yes, you can call functions in the parent theme from the child theme (though in your example you'll get an error because you pass one variable where two are expected). So, you can add it as a filter in one place and call it independently elsewhere.</p>\n\n<p>When WordPress is loaded it is making an inventory of all available functions. It <a href=\"https://codex.wordpress.org/Child_Themes#Using_functions.php\" rel=\"nofollow noreferrer\">first loads the child theme's <code>functions.php</code></a>, then the parent theme's. A function that is redefined in the child, is skipped in the parent. Execution of code only starts after the inventory has been made. Then you can call parent theme functions from the child. You can call plugin functions from your theme, or the other way around. It simply doesn't matter where the function is defined, as long as it is <a href=\"https://stackoverflow.com/questions/4361553/php-public-private-protected\">available</a>.</p>\n\n<p>What your function call from the child theme won't do is change the behaviour of the function when it is called as a filter <code>post_thumbnail_html</code> from the <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow noreferrer\"><code>get_the_post_thumbnail</code></a> function. That's two separate calls that are unaware of eachother. So if you want the color from the child function to be applied in the filter, that won't work. To do that, you would have to turn it around. In the parent function call a function from the child (if it exists) and in the child define a function that passes the color.</p>\n\n<pre><code>// parent\nif (function_exists (wpse220111_get_child_color))\n $my_color = wpse220111_get_child_color;\nelse\n $my_color = \"#000000\";\n\n// child\nfunction wpse220111_get_child_color () {return \"#0099dd\";}\n</code></pre>\n" } ]
2016/03/08
[ "https://wordpress.stackexchange.com/questions/220111", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81686/" ]
I want to pass a variable from my child theme function to a filter which resides in my parent theme. Please let me know whether below code will work or not ? Is it the right way ? **Code in Parent Theme's functions.php** ``` add_filter( 'post_thumbnail_html', "map_thumbnail" ); function map_thumbnail($html,$color) { $my_post = get_post($post->ID); $my_color = $color; if($my_post->post_name == "contact") { $html = '<img src="http://maps.googleapis.com/maps/api/staticmap?color:$my_color">'; } return $html; } ``` **Code in Child Theme's functions.php** ``` <?php map_thumbnail('#0099dd'); ?> ``` Please tell me, will above code work? Can I pass the variable `$color` from my child theme to parent theme like this ?
I'm not exactly sure what you're trying to accomplish but this won't work because your trying to use or call the function that is declared in the parent theme instead of replacing it with a new function. I'm not sure if replacing a function in the child theme would work either. Maybe someone else can help answer that. The function `map_thumbnail()` that you're trying to call in the child theme, is actually being used by the `add_filter()` function right above it to modify the existing function `post_thumbnail_html()`. Additionally, even if it would work, you only passed one paramater ('#0099dd') in your attempt to call the function, and it appears to be out of order.
220,122
<p>I have just had to deal with a few of my WordPress websites being hacked. First time put an index.html file in the cpanel of each site and replenished my admin user. Once I felt I cleaned this up, it's happened once again but it changed my title tag to "Hacked by Bala Sniper" and the widgets from the footer of each website were removed.</p> <p>My WHM account isn't WP only websites so I know it can't be a hacker accessing from there.</p> <p>I've Googled this many times and rectified a few issues such as not making the id=1 to be admin, captcha plugin amongst a few others.</p> <p>I feel this is going to happen once again. I'm on here to ask if anyone has had this problem today or yesterday or if you've ever had this hacked by bala sniper title tag change etc. and if you cleaned up the problem and tightened your security, to hopefully help me out amongst anyone else who reads this.</p> <p>What is concerning me the most is that it's been every single wordpress site on my WHM was compromised and I've not found anything where every single site has something similar to them all.</p> <p>Thanks for anyone to helps, I have googled this and rectified as much issues I've neglected, just need to know why all of my WP accounts were effected.</p> <p>Dev</p>
[ { "answer_id": 224778, "author": "dExIT", "author_id": 92983, "author_profile": "https://wordpress.stackexchange.com/users/92983", "pm_score": 1, "selected": false, "text": "<p>I wanted to state, this happened to me a few times in the early WP 3.x days.\nAm using GoDaddy shared hsoting etc.</p>\n\n<p>My solution, i compiled my own HTaccess file(if ur using Apache) against RFI / LFI / SQL injects etc, just very basic ones, disabling the use of base64, bogus image hacks, finger printing and so on.\nThen you need to check your CHMOD aka Permissions, you can also do that through FTP or filemanager, or better HTACCESS, the one of the last things, is actualy hardening your WP, and this is not a easy task, stop relying on Revolution Slider(just for example), and keep a whatch out on epxloit-db or vulndb for things concerning plugins that you use.</p>\n\n<p>All </p>\n\n<p>Check this out, and edit the .htaccess file at the start ull see YOURDOMAIN.COM and change them -> lines 21 and 22 </p>\n\n<p><a href=\"https://github.com/dexit/wp-ht-access-se\" rel=\"nofollow\">https://github.com/dexit/wp-ht-access-se</a></p>\n" }, { "answer_id": 264465, "author": "Developer.Sumit", "author_id": 118194, "author_profile": "https://wordpress.stackexchange.com/users/118194", "pm_score": 2, "selected": false, "text": "<p><em>wordpress configuration file is located in the root</em>.In the event that PHP stops functioning on webserver for any reason.we run the risk of this file being displayed in plaintext,which will give our password and database information to visitor.\n you can safely move <strong>wp-config</strong> directory up out of root directory.this will stop if from accidentally served. Wordpress has built-in functionality that automatic check parent directory if it cannot find a configuration file. </p>\n\n<p>In this situations on certain hosts, is not option. An alternative on Apache web servers is to set your <strong>.htaccess</strong> to not serve up the <strong>wp-config</strong> file.\nAdd the following line to ur <strong>.htaccess</strong> file in the root directory.</p>\n\n<pre><code>&lt;FilesMatch ^wp-config.php$&gt;deny from all&lt;/FilesMatch&gt;\n</code></pre>\n" } ]
2016/03/08
[ "https://wordpress.stackexchange.com/questions/220122", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86831/" ]
I have just had to deal with a few of my WordPress websites being hacked. First time put an index.html file in the cpanel of each site and replenished my admin user. Once I felt I cleaned this up, it's happened once again but it changed my title tag to "Hacked by Bala Sniper" and the widgets from the footer of each website were removed. My WHM account isn't WP only websites so I know it can't be a hacker accessing from there. I've Googled this many times and rectified a few issues such as not making the id=1 to be admin, captcha plugin amongst a few others. I feel this is going to happen once again. I'm on here to ask if anyone has had this problem today or yesterday or if you've ever had this hacked by bala sniper title tag change etc. and if you cleaned up the problem and tightened your security, to hopefully help me out amongst anyone else who reads this. What is concerning me the most is that it's been every single wordpress site on my WHM was compromised and I've not found anything where every single site has something similar to them all. Thanks for anyone to helps, I have googled this and rectified as much issues I've neglected, just need to know why all of my WP accounts were effected. Dev
*wordpress configuration file is located in the root*.In the event that PHP stops functioning on webserver for any reason.we run the risk of this file being displayed in plaintext,which will give our password and database information to visitor. you can safely move **wp-config** directory up out of root directory.this will stop if from accidentally served. Wordpress has built-in functionality that automatic check parent directory if it cannot find a configuration file. In this situations on certain hosts, is not option. An alternative on Apache web servers is to set your **.htaccess** to not serve up the **wp-config** file. Add the following line to ur **.htaccess** file in the root directory. ``` <FilesMatch ^wp-config.php$>deny from all</FilesMatch> ```
220,163
<p>I need to cross reference two taxonomies, <code>product_categories</code> and <code>brands</code>. the only way I can think to do this is to get all the posts in one taxonomy, then get all the posts that exist in another taxonomy:</p> <pre><code>&lt;?php $category = /* Taxonomy object selected from list */; // Get all the posts in this query $args = array( 'post_type' =&gt; 'product', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; $category-&gt;taxonomy, 'field' =&gt; 'slug', 'terms' =&gt; $category-&gt;slug ) ) ); $product_items = get_posts( $args ); // create a blank array ready for the IDs $product_items_ids = []; // For every post found, populate the array foreach ($product_items as $product_item) { // Create array from all post IDs in category $product_items_ids[] = $product_item-&gt;ID; } // Get all terms in Brand taxonomy that are in the array above $brand_items = wp_get_object_terms( $product_items_ids, 'brand' ); // Output the information needed foreach ($brand_items as $brand_item) { ?&gt; &lt;li&gt;&lt;a href="&lt;?php echo get_term_link( $brand_item-&gt;slug, $brand_item-&gt;taxonomy ); ?&gt;"&gt; &lt;?php echo $brand_item-&gt;name; ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php } ?&gt; </code></pre> <p>I'm calling this in 5-10 times, and if the product listings become vast, this means i'm calling in every post on the site 10 times to load the menu etc.</p> <p>Is there a more efficient way of doing this type of query?</p> <hr> <p>Addition things to note:</p> <p>The first query pulls in the posts assigned the taxonomy of <code>$category-&gt;taxonomy</code>.</p> <p><code>$category</code> is a taxonomy object selected in the admin by Advanced Custom Fields. For this example, say <strong>accessories</strong> is a term, and <code>product_cat</code> is the taxonomy @PieterGoosen</p> <p>I need to return all the terms in brands that are also posts with the accessories term.</p>
[ { "answer_id": 220213, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 0, "selected": false, "text": "<p>I am not so good with SQL. But this query does the job for me, I just combined two queries into one!</p>\n\n<pre><code>$brands = $wpdb-&gt;get_results(\"SELECT DISTINCT term_id \"\n . \"FROM {$wpdb-&gt;prefix}term_taxonomy \"\n . \"LEFT JOIN {$wpdb-&gt;prefix}term_relationships my_tr ON {$wpdb-&gt;prefix}term_taxonomy.term_taxonomy_id = my_tr.term_taxonomy_id \"\n . \"WHERE object_id IN (SELECT object_id FROM {$wpdb-&gt;prefix}term_relationships WHERE term_taxonomy_id = {$category-&gt;term_taxonomy_id}) \"\n . \"AND taxonomy = 'your_brand_taxonomy'\");\n</code></pre>\n\n<p>However, I will recommend you to change the data structure with parent and child term instead of two different taxonomies. </p>\n" }, { "answer_id": 220228, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 5, "selected": true, "text": "<p>We can do quite a lot to improve performance of your code. Lets set some benchmarks first</p>\n\n<h2>BENCH MARKS</h2>\n\n<ul>\n<li><p>I'm testing this with a </p>\n\n<ul>\n<li><p><code>category</code> taxonomy term which has 9 posts and </p></li>\n<li><p>the <code>post_tag</code> taxonomy with 61 matching tags. </p></li>\n</ul></li>\n</ul>\n\n<p>With your current code, I get the following results</p>\n\n<ul>\n<li><strong><em>69 queries in =/- 0.4s</em></strong></li>\n</ul>\n\n<p>That is pretty expensive and a huge amount of queries on such a small database and test subject</p>\n\n<h2>OPTIMIZATIONS</h2>\n\n<p>The first thing we will do, is to query only the post ID's from the posts because of the following reasons</p>\n\n<ul>\n<li><p>We do not need any post data</p></li>\n<li><p>We do not need post cache and post meta cache updated, we do not need that</p></li>\n<li><p>Obviously, only querying post ID's will increase performance drastically</p></li>\n</ul>\n\n<p>Only querying the ID's have the drawback in that we also loose the term cache. Because we do not update the term cache, this will lead to a huge increase in db queries. In order to solve that, we will manually update the term cache with <code>update_object_term_cache</code>.</p>\n\n<p>By this time, just on your query alone, you have gained 1db call and 0.02s, which is not that much, but it makes a huge difference on a huge database. The real gain will come in the next section</p>\n\n<p>The really big gain is by passing the term object to <code>get_term_link()</code>, and not the term ID. If there is no terms in the term cache, and you pass the term ID to <code>get_term_link()</code>, instead of getting the term object from the cache, <code>get_term_link()</code> will query the db to get the term object. Just on test, this amounts to an extra 61 db calls, one per tag. Think about a few hundred tags. </p>\n\n<p>We already have the term object, so we can simply pass the complete term object. You should always do that. Even if the term object is in cache, it is still very marginally slower to pass the term ID as we must still get the term object from the cache</p>\n\n<p>I have cleaned up your code a bit. Note, I have used short array syntax which do need PHP 5.4+. Here is how your code could look like</p>\n\n<pre><code>$category = get_category( 13 ); // JUST FOR TESTING&lt; ADJUST TO YOUR NEEDS\n\n$args = [\n 'post_type' =&gt; 'product',\n 'fields' =&gt; 'ids', // Only query the post ID's, not complete post objects\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; $category-&gt;taxonomy,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $category-&gt;slug\n ]\n ]\n];\n$ids = get_posts( $args );\n\n$links = [];\n// Make sure we have ID'saves\nif ( $ids ) {\n /**\n * Because we only query post ID's, the post caches are not updated which is\n * good and bad\n *\n * GOOD -&gt; It saves on resources because we do not need post data or post meta data\n * BAD -&gt; We loose the vital term cache, which will result in even more db calls\n *\n * To solve that, we manually update the term cache with update_object_term_cache\n */\n update_object_term_cache( $ids, 'product' );\n\n $term_names = [];\n\n foreach ( $ids as $id ) {\n $terms = get_object_term_cache( $id, 'post_tag' );\n foreach ( $terms as $term ) {\n if ( in_array( $term-&gt;name, $term_names ) )\n continue;\n\n $term_names[] = $term-&gt;name;\n\n $links[$term-&gt;name] = '&lt;li&gt;&lt;a href=\"' . get_term_link( $term ) . '\"&gt;' . $term-&gt;name . '&lt;/a&gt;&lt;/li&gt;';\n }\n }\n}\n\nif ( $links ) {\n ksort( $links );\n $link_string = implode( \"\\n\\t\" , $links );\n} else {\n $link_string = '';\n}\n\necho $link_string;\n</code></pre>\n\n<p>As it now stand, we have reduced the numbers down to <strong><em>6 db queries in 0.04s</em></strong> which is a huge improvement.</p>\n\n<p>We can even go further and store the results in a transient</p>\n\n<pre><code>$category = get_category( 13 ); // JUST FOR TESTING&lt; ADJUST TO YOUR NEEDS\n\n$link_string = '';\n$transient_name = 'query_' . md5( $category-&gt;slug . $category-&gt;taxonomy );\nif ( false === ( $link_string = get_transient( $transient_name ) ) ) {\n $args = [\n 'post_type' =&gt; 'product',\n 'fields' =&gt; 'ids', // Only query the post ID's, not complete post objects\n 'tax_query' =&gt; [\n [\n 'taxonomy' =&gt; $category-&gt;taxonomy,\n 'field' =&gt; 'slug',\n 'terms' =&gt; $category-&gt;slug\n ]\n ]\n ];\n $ids = get_posts( $args );\n\n $links = [];\n // Make sure we have ID'saves\n if ( $ids ) {\n /**\n * Because we only query post ID's, the post caches are not updated which is\n * good and bad\n *\n * GOOD -&gt; It saves on resources because we do not need post data or post meta data\n * BAD -&gt; We loose the vital term cache, which will result in even more db calls\n *\n * To solve that, we manually update the term cache with update_object_term_cache\n */\n update_object_term_cache( $ids, 'product' );\n\n $term_names = [];\n\n foreach ( $ids as $id ) {\n $terms = get_object_term_cache( $id, 'post_tag' );\n foreach ( $terms as $term ) {\n if ( in_array( $term-&gt;name, $term_names ) )\n continue;\n\n $term_names[] = $term-&gt;name;\n\n $links[$term-&gt;name] = '&lt;li&gt;&lt;a href=\"' . get_term_link( $term ) . '\"&gt;' . $term-&gt;name . '&lt;/a&gt;&lt;/li&gt;';\n }\n }\n }\n\n\n if ( $links ) {\n ksort( $links );\n $link_string = implode( \"\\n\\t\" , $links );\n } else {\n $link_string = '';\n }\n\n set_transient( $transient_name, $link_string, 7 * DAY_IN_SECONDS );\n} \n\necho $link_string;\n</code></pre>\n\n<p>This will reduce everything to <strong><em>2 queries in 0.002s</em></strong>. With the transient in place, we will just to flush the transient when we publish, update, delete or undelete posts. We will use the <code>transition_post_status</code> hook here</p>\n\n<pre><code>add_action( 'transition_post_status', function ()\n{\n global $wpdb;\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient%_query_%')\" );\n $wpdb-&gt;query( \"DELETE FROM $wpdb-&gt;options WHERE `option_name` LIKE ('_transient_timeout%_query_%')\" );\n});\n</code></pre>\n" } ]
2016/03/09
[ "https://wordpress.stackexchange.com/questions/220163", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27504/" ]
I need to cross reference two taxonomies, `product_categories` and `brands`. the only way I can think to do this is to get all the posts in one taxonomy, then get all the posts that exist in another taxonomy: ``` <?php $category = /* Taxonomy object selected from list */; // Get all the posts in this query $args = array( 'post_type' => 'product', 'tax_query' => array( array( 'taxonomy' => $category->taxonomy, 'field' => 'slug', 'terms' => $category->slug ) ) ); $product_items = get_posts( $args ); // create a blank array ready for the IDs $product_items_ids = []; // For every post found, populate the array foreach ($product_items as $product_item) { // Create array from all post IDs in category $product_items_ids[] = $product_item->ID; } // Get all terms in Brand taxonomy that are in the array above $brand_items = wp_get_object_terms( $product_items_ids, 'brand' ); // Output the information needed foreach ($brand_items as $brand_item) { ?> <li><a href="<?php echo get_term_link( $brand_item->slug, $brand_item->taxonomy ); ?>"> <?php echo $brand_item->name; ?></a></li> <?php } ?> ``` I'm calling this in 5-10 times, and if the product listings become vast, this means i'm calling in every post on the site 10 times to load the menu etc. Is there a more efficient way of doing this type of query? --- Addition things to note: The first query pulls in the posts assigned the taxonomy of `$category->taxonomy`. `$category` is a taxonomy object selected in the admin by Advanced Custom Fields. For this example, say **accessories** is a term, and `product_cat` is the taxonomy @PieterGoosen I need to return all the terms in brands that are also posts with the accessories term.
We can do quite a lot to improve performance of your code. Lets set some benchmarks first BENCH MARKS ----------- * I'm testing this with a + `category` taxonomy term which has 9 posts and + the `post_tag` taxonomy with 61 matching tags. With your current code, I get the following results * ***69 queries in =/- 0.4s*** That is pretty expensive and a huge amount of queries on such a small database and test subject OPTIMIZATIONS ------------- The first thing we will do, is to query only the post ID's from the posts because of the following reasons * We do not need any post data * We do not need post cache and post meta cache updated, we do not need that * Obviously, only querying post ID's will increase performance drastically Only querying the ID's have the drawback in that we also loose the term cache. Because we do not update the term cache, this will lead to a huge increase in db queries. In order to solve that, we will manually update the term cache with `update_object_term_cache`. By this time, just on your query alone, you have gained 1db call and 0.02s, which is not that much, but it makes a huge difference on a huge database. The real gain will come in the next section The really big gain is by passing the term object to `get_term_link()`, and not the term ID. If there is no terms in the term cache, and you pass the term ID to `get_term_link()`, instead of getting the term object from the cache, `get_term_link()` will query the db to get the term object. Just on test, this amounts to an extra 61 db calls, one per tag. Think about a few hundred tags. We already have the term object, so we can simply pass the complete term object. You should always do that. Even if the term object is in cache, it is still very marginally slower to pass the term ID as we must still get the term object from the cache I have cleaned up your code a bit. Note, I have used short array syntax which do need PHP 5.4+. Here is how your code could look like ``` $category = get_category( 13 ); // JUST FOR TESTING< ADJUST TO YOUR NEEDS $args = [ 'post_type' => 'product', 'fields' => 'ids', // Only query the post ID's, not complete post objects 'tax_query' => [ [ 'taxonomy' => $category->taxonomy, 'field' => 'slug', 'terms' => $category->slug ] ] ]; $ids = get_posts( $args ); $links = []; // Make sure we have ID'saves if ( $ids ) { /** * Because we only query post ID's, the post caches are not updated which is * good and bad * * GOOD -> It saves on resources because we do not need post data or post meta data * BAD -> We loose the vital term cache, which will result in even more db calls * * To solve that, we manually update the term cache with update_object_term_cache */ update_object_term_cache( $ids, 'product' ); $term_names = []; foreach ( $ids as $id ) { $terms = get_object_term_cache( $id, 'post_tag' ); foreach ( $terms as $term ) { if ( in_array( $term->name, $term_names ) ) continue; $term_names[] = $term->name; $links[$term->name] = '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>'; } } } if ( $links ) { ksort( $links ); $link_string = implode( "\n\t" , $links ); } else { $link_string = ''; } echo $link_string; ``` As it now stand, we have reduced the numbers down to ***6 db queries in 0.04s*** which is a huge improvement. We can even go further and store the results in a transient ``` $category = get_category( 13 ); // JUST FOR TESTING< ADJUST TO YOUR NEEDS $link_string = ''; $transient_name = 'query_' . md5( $category->slug . $category->taxonomy ); if ( false === ( $link_string = get_transient( $transient_name ) ) ) { $args = [ 'post_type' => 'product', 'fields' => 'ids', // Only query the post ID's, not complete post objects 'tax_query' => [ [ 'taxonomy' => $category->taxonomy, 'field' => 'slug', 'terms' => $category->slug ] ] ]; $ids = get_posts( $args ); $links = []; // Make sure we have ID'saves if ( $ids ) { /** * Because we only query post ID's, the post caches are not updated which is * good and bad * * GOOD -> It saves on resources because we do not need post data or post meta data * BAD -> We loose the vital term cache, which will result in even more db calls * * To solve that, we manually update the term cache with update_object_term_cache */ update_object_term_cache( $ids, 'product' ); $term_names = []; foreach ( $ids as $id ) { $terms = get_object_term_cache( $id, 'post_tag' ); foreach ( $terms as $term ) { if ( in_array( $term->name, $term_names ) ) continue; $term_names[] = $term->name; $links[$term->name] = '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>'; } } } if ( $links ) { ksort( $links ); $link_string = implode( "\n\t" , $links ); } else { $link_string = ''; } set_transient( $transient_name, $link_string, 7 * DAY_IN_SECONDS ); } echo $link_string; ``` This will reduce everything to ***2 queries in 0.002s***. With the transient in place, we will just to flush the transient when we publish, update, delete or undelete posts. We will use the `transition_post_status` hook here ``` add_action( 'transition_post_status', function () { global $wpdb; $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient%_query_%')" ); $wpdb->query( "DELETE FROM $wpdb->options WHERE `option_name` LIKE ('_transient_timeout%_query_%')" ); }); ```
220,181
<p>I want to pass my google map custom colors from my child theme to my parent theme. </p> <p><strong>So in my Parent Theme's functions.php I have</strong></p> <pre><code>add_filter( 'post_thumbnail_html', "map_thumbnail" ); function map_thumbnail($html, $color1, $color2) { $my_post = get_post($post-&gt;ID); $water_color=$color1; $tree_color=$color2; if($my_post-&gt;post_name == "contact") { $html = '&lt;img height="100%" width="100%" src="http://maps.googleapis.com/maps/api/staticmap?watercolor='.$water_color.'treecolor='.$tree_color.'"&gt;'; } return $html; } </code></pre> <p><strong>I just want to pass two colors from my child theme's functions.php like so,</strong></p> <pre><code>$color1 = '#fb0000'; $color2 = '#c0e8e8'; apply_filters('post_thumbnail_html', $color1, $color2); </code></pre> <p>But unfortunately this is not working. Can anyone help me out here ? I have 3 child themes and all of them have the same map, just the tree color and water color are different. I want to keep the main map_thumbnail function in the parent theme and pass only the individual colors from my child themes. Please help me out if possible.</p>
[ { "answer_id": 220183, "author": "tillinberlin", "author_id": 26059, "author_profile": "https://wordpress.stackexchange.com/users/26059", "pm_score": 0, "selected": false, "text": "<p>Without having tried it myself I would suggest you write a small function for your child theme and then call the parent's theme funstion like this: </p>\n\n<pre><code>add_filter( 'post_thumbnail_html', \"child_map_thumbnail\", 11 );\n\nfunction child_map_thumbnail($html) {\n\n $color1 = '#fb0000';\n $color2 = '#c0e8e8';\n\n map_thumbnail($html, $color1, $color2);\n\n return $html;\n\n}\n</code></pre>\n\n<p>As I said: I haven't tried this myself – but I suppose the function of your parent theme should be available – so basically my suggestion would be to call that function instead of passing variables… </p>\n" }, { "answer_id": 220184, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 3, "selected": true, "text": "<p>Stick to filtering one value at a time to keep it simple, and add filters for the colors to be used by the child theme:</p>\n\n<pre><code>add_filter( 'post_thumbnail_html', 'map_thumbnail');\nfunction map_thumbnail($html) {\n $my_post = get_post($post-&gt;ID);\n $defaultcolor1 = \"#??????\"; // parent theme default\n $defaultcolor2 = \"#??????\"; // parent theme default\n $water_color = apply_filters('water_color',$defaultcolor1);\n $tree_color = apply_filters('tree_color',$defaultcolor2);\n if($my_post-&gt;post_name == \"contact\") {\n $html = '&lt;img height=\"100%\" width=\"100%\" src=\"http://maps.googleapis.com/maps/api/staticmap?watercolor='.$water_color.'treecolor='.$tree_color.'\"&gt;'; \n }\n return $html;\n}\n</code></pre>\n\n<p>So in the child theme you can use:</p>\n\n<pre><code>add_filter('water_color','custom_water_color');\nadd_filter('tree_color','custom_tree_color');\n\nfunction custom_water_color() {return '#fb0000';}\nfunction custom_tree_color() {return '#c0e8e8';}\n</code></pre>\n" } ]
2016/03/09
[ "https://wordpress.stackexchange.com/questions/220181", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81686/" ]
I want to pass my google map custom colors from my child theme to my parent theme. **So in my Parent Theme's functions.php I have** ``` add_filter( 'post_thumbnail_html', "map_thumbnail" ); function map_thumbnail($html, $color1, $color2) { $my_post = get_post($post->ID); $water_color=$color1; $tree_color=$color2; if($my_post->post_name == "contact") { $html = '<img height="100%" width="100%" src="http://maps.googleapis.com/maps/api/staticmap?watercolor='.$water_color.'treecolor='.$tree_color.'">'; } return $html; } ``` **I just want to pass two colors from my child theme's functions.php like so,** ``` $color1 = '#fb0000'; $color2 = '#c0e8e8'; apply_filters('post_thumbnail_html', $color1, $color2); ``` But unfortunately this is not working. Can anyone help me out here ? I have 3 child themes and all of them have the same map, just the tree color and water color are different. I want to keep the main map\_thumbnail function in the parent theme and pass only the individual colors from my child themes. Please help me out if possible.
Stick to filtering one value at a time to keep it simple, and add filters for the colors to be used by the child theme: ``` add_filter( 'post_thumbnail_html', 'map_thumbnail'); function map_thumbnail($html) { $my_post = get_post($post->ID); $defaultcolor1 = "#??????"; // parent theme default $defaultcolor2 = "#??????"; // parent theme default $water_color = apply_filters('water_color',$defaultcolor1); $tree_color = apply_filters('tree_color',$defaultcolor2); if($my_post->post_name == "contact") { $html = '<img height="100%" width="100%" src="http://maps.googleapis.com/maps/api/staticmap?watercolor='.$water_color.'treecolor='.$tree_color.'">'; } return $html; } ``` So in the child theme you can use: ``` add_filter('water_color','custom_water_color'); add_filter('tree_color','custom_tree_color'); function custom_water_color() {return '#fb0000';} function custom_tree_color() {return '#c0e8e8';} ```
220,208
<p>I've applied the following code to enable the comment section in the page template.</p> <pre><code>&lt;div class="col-md-12"&gt; &lt;?php while ( have_posts() ) : the_post(); ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;div class="sec-text wow fadeInUp" data-wow-delay="300ms" data-wow-duration="1000ms"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;/article&gt; &lt;div class="col-md-8"&gt; &lt;?php if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?&gt; &lt;/div&gt; &lt;?php endwhile; wp_reset_query();?&gt; &lt;/div&gt; </code></pre> <p>The comment form is showing directly by this code. User can not able to disable or re-enable the comment form in editor for specific page.</p>
[ { "answer_id": 220210, "author": "Chandan Kumar Thakur", "author_id": 88637, "author_profile": "https://wordpress.stackexchange.com/users/88637", "pm_score": 0, "selected": false, "text": "<p>yes you can do that for specific pages like with a page of page id 9</p>\n\n<pre><code> //for single page\n if(is_page(9)){ \n //execute comment template\n comments_template( '', true );\n\n }\n\n//for single post\nif(is_single(9)){\n comments_template( '', true );\n\n} \n</code></pre>\n" }, { "answer_id": 220276, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>I think it <em>could</em> be a problem with <code>get_comments_number</code> which returns numeric, though theoretically it should test this way too... you could try instead:</p>\n<pre><code>if ( comments_open() || have_comments() ) :\n comments_template();\nendif;\n</code></pre>\n<p>OR</p>\n<pre><code>if ( comments_open() || (get_comments_number() &gt; 0) ) :\n comments_template();\nendif;\n</code></pre>\n" } ]
2016/03/09
[ "https://wordpress.stackexchange.com/questions/220208", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81042/" ]
I've applied the following code to enable the comment section in the page template. ``` <div class="col-md-12"> <?php while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="sec-text wow fadeInUp" data-wow-delay="300ms" data-wow-duration="1000ms"> <?php the_content(); ?> </div> </article> <div class="col-md-8"> <?php if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> </div> <?php endwhile; wp_reset_query();?> </div> ``` The comment form is showing directly by this code. User can not able to disable or re-enable the comment form in editor for specific page.
I think it *could* be a problem with `get_comments_number` which returns numeric, though theoretically it should test this way too... you could try instead: ``` if ( comments_open() || have_comments() ) : comments_template(); endif; ``` OR ``` if ( comments_open() || (get_comments_number() > 0) ) : comments_template(); endif; ```
220,214
<p>I'm a newbie for coding, I would like to learn how to add css style conditionally in functions.php My header controlled by <code>.header-outer</code> class. What would it be the best way to add css depending on category? I was able to determine category slug (not standard wordpress category) and wrote some if conditions. It's working but could not understand adding css. With <code>wp_enqueue_style</code> should I call external predefined css files or is it possible to write directly in functions.php.</p> <pre><code>wp_enqueue_style( '***', get_template_directory_uri() . '/mycss/category1.css', array(), '1.1', 'all'); </code></pre> <p>Here I could not understand the first *** part ? I would like to embed all style not a class.</p> <p>Thank you, Best Regards.</p>
[ { "answer_id": 220210, "author": "Chandan Kumar Thakur", "author_id": 88637, "author_profile": "https://wordpress.stackexchange.com/users/88637", "pm_score": 0, "selected": false, "text": "<p>yes you can do that for specific pages like with a page of page id 9</p>\n\n<pre><code> //for single page\n if(is_page(9)){ \n //execute comment template\n comments_template( '', true );\n\n }\n\n//for single post\nif(is_single(9)){\n comments_template( '', true );\n\n} \n</code></pre>\n" }, { "answer_id": 220276, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>I think it <em>could</em> be a problem with <code>get_comments_number</code> which returns numeric, though theoretically it should test this way too... you could try instead:</p>\n<pre><code>if ( comments_open() || have_comments() ) :\n comments_template();\nendif;\n</code></pre>\n<p>OR</p>\n<pre><code>if ( comments_open() || (get_comments_number() &gt; 0) ) :\n comments_template();\nendif;\n</code></pre>\n" } ]
2016/03/09
[ "https://wordpress.stackexchange.com/questions/220214", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/32315/" ]
I'm a newbie for coding, I would like to learn how to add css style conditionally in functions.php My header controlled by `.header-outer` class. What would it be the best way to add css depending on category? I was able to determine category slug (not standard wordpress category) and wrote some if conditions. It's working but could not understand adding css. With `wp_enqueue_style` should I call external predefined css files or is it possible to write directly in functions.php. ``` wp_enqueue_style( '***', get_template_directory_uri() . '/mycss/category1.css', array(), '1.1', 'all'); ``` Here I could not understand the first \*\*\* part ? I would like to embed all style not a class. Thank you, Best Regards.
I think it *could* be a problem with `get_comments_number` which returns numeric, though theoretically it should test this way too... you could try instead: ``` if ( comments_open() || have_comments() ) : comments_template(); endif; ``` OR ``` if ( comments_open() || (get_comments_number() > 0) ) : comments_template(); endif; ```
220,225
<p>I'm using Postman to test my project and the wp-api. More specifically POST requests where a user must be authenticated to do something. Here's what I'm working with to create a user:</p> <pre><code>{{url}}/projectname/wp-json/wp/v2/users/?username=anewname&amp;[email protected]&amp;password=passwordhere </code></pre> <p>However when testing something <a href="http://v2.wp-api.org/guide/authentication/" rel="nofollow">requiring authentication</a>, such as creating a user, I get a 401'ed:</p> <pre><code>{ "code": "rest_cannot_create_user", "message": "Sorry, you are not allowed to create resource.", "data": { "status": 401 } } </code></pre> <p><strong>Authenticating via Nonce:</strong> If you see the link above, the documentation explains setting the header and sending along the nonce. I could set the header to <code>X-WP-Nonce</code> but then how would I get the nonce to send along in Postman?</p> <p><strong>Authenticating via cookies:</strong> I've installed Postman's <a href="https://chrome.google.com/webstore/detail/postman-interceptor/aicmkgpgakddgnaphhhpliifpcfhicfo" rel="nofollow">interceptor</a> to grab cookies and am seeing 5 of them but still get 401'ed with the method above.</p> <p>Any ideas or guidance would be really useful to the community.</p>
[ { "answer_id": 226822, "author": "MTT", "author_id": 1057, "author_profile": "https://wordpress.stackexchange.com/users/1057", "pm_score": -1, "selected": false, "text": "<p>Postman doesn't need a nonce to create content with v2 beta 12... just use the WP-API Basic Auth plugin. The one header is the authentication header.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ucSMX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ucSMX.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 248177, "author": "Gnanasekaran Loganathan", "author_id": 82760, "author_profile": "https://wordpress.stackexchange.com/users/82760", "pm_score": 1, "selected": false, "text": "<p>Postman shares cookies with Chrome. If you are logged into your site you may see unexpected results.</p>\n\n<p>REF : <a href=\"https://wordpress.org/support/topic/wp-api-cant-create-a-post/\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/wp-api-cant-create-a-post/</a></p>\n" } ]
2016/03/09
[ "https://wordpress.stackexchange.com/questions/220225", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18726/" ]
I'm using Postman to test my project and the wp-api. More specifically POST requests where a user must be authenticated to do something. Here's what I'm working with to create a user: ``` {{url}}/projectname/wp-json/wp/v2/users/?username=anewname&[email protected]&password=passwordhere ``` However when testing something [requiring authentication](http://v2.wp-api.org/guide/authentication/), such as creating a user, I get a 401'ed: ``` { "code": "rest_cannot_create_user", "message": "Sorry, you are not allowed to create resource.", "data": { "status": 401 } } ``` **Authenticating via Nonce:** If you see the link above, the documentation explains setting the header and sending along the nonce. I could set the header to `X-WP-Nonce` but then how would I get the nonce to send along in Postman? **Authenticating via cookies:** I've installed Postman's [interceptor](https://chrome.google.com/webstore/detail/postman-interceptor/aicmkgpgakddgnaphhhpliifpcfhicfo) to grab cookies and am seeing 5 of them but still get 401'ed with the method above. Any ideas or guidance would be really useful to the community.
Postman shares cookies with Chrome. If you are logged into your site you may see unexpected results. REF : <https://wordpress.org/support/topic/wp-api-cant-create-a-post/>
220,245
<p>Whats the most simple way to change my wp-menu generated output from <code>&lt;li&gt;&lt;a href=""&gt;nav link&lt;/a&gt;&lt;/li&gt;</code> to <code>&lt;a href=""&gt;&lt;li&gt;&lt;li/&gt;&lt;/a&gt;</code>? Do I create an array in my <code>functions.php</code>?</p> <p>This is what I have in my <code>functions.php</code> </p> <pre><code>function register_my_menus() { register_nav_menus( array( 'primary' =&gt; __( 'Main Menu' ), 'mobile-menu' =&gt; __( 'Mobile Menu' ), ) ); } add_action( 'init', 'register_my_menus' ); </code></pre>
[ { "answer_id": 220253, "author": "Madan Karki", "author_id": 83958, "author_profile": "https://wordpress.stackexchange.com/users/83958", "pm_score": -1, "selected": false, "text": "<p>use <a href=\"https://gist.github.com/toscho/1053467\" rel=\"nofollow\">\"T5_Nav_Menu_Walker_Simple\"</a> custom walker to modify markup of <code>Wp_nav_menu</code>:</p>\n\n<pre><code>&lt;?php # -*- coding: utf-8 -*-\n/**\n * Create a nav menu with very basic markup.\n *\n * @author Thomas Scholz http://toscho.de\n * @version 1.0\n */\nclass T5_Nav_Menu_Walker_Simple extends Walker_Nav_Menu\n{\n /**\n * Start the element output.\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param object $item Menu item data object.\n * @param int $depth Depth of menu item. May be used for padding.\n * @param array $args Additional strings.\n * @return void\n */\n public function start_el( &amp;$output, $item, $depth, $args )\n {\n $output .= '&lt;li&gt;';\n $attributes = '';\n ! empty ( $item-&gt;attr_title )\n // Avoid redundant titles\n and $item-&gt;attr_title !== $item-&gt;title\n and $attributes .= ' title=\"' . esc_attr( $item-&gt;attr_title ) .'\"';\n ! empty ( $item-&gt;url )\n and $attributes .= ' href=\"' . esc_attr( $item-&gt;url ) .'\"';\n $attributes = trim( $attributes );\n $title = apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID );\n $item_output = \"$args-&gt;before&lt;a $attributes&gt;$args-&gt;link_before$title&lt;/a&gt;\"\n . \"$args-&gt;link_after$args-&gt;after\";\n // Since $output is called by reference we don't need to return anything.\n $output .= apply_filters(\n 'walker_nav_menu_start_el'\n , $item_output\n , $item\n , $depth\n , $args\n );\n }\n /**\n * @see Walker::start_lvl()\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @return void\n */\n public function start_lvl( &amp;$output )\n {\n $output .= '&lt;ul class=\"sub-menu\"&gt;';\n }\n /**\n * @see Walker::end_lvl()\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @return void\n */\n public function end_lvl( &amp;$output )\n {\n $output .= '&lt;/ul&gt;';\n }\n /**\n * @see Walker::end_el()\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @return void\n */\n function end_el( &amp;$output )\n {\n $output .= '&lt;/li&gt;';\n }\n}\n</code></pre>\n" }, { "answer_id": 220351, "author": "RLM", "author_id": 60779, "author_profile": "https://wordpress.stackexchange.com/users/60779", "pm_score": 0, "selected": false, "text": "<p>I really just wanted to make the WHOLE <code>&lt;li&gt;</code> linkable and I achieved that ( simply ) by getting rid of padding on <code>menu li</code> and adding it and <code>display:block</code> to <code>menu li a</code></p>\n" }, { "answer_id": 220356, "author": "Peter Thomas Simmons", "author_id": 83121, "author_profile": "https://wordpress.stackexchange.com/users/83121", "pm_score": 1, "selected": false, "text": "<p>I don't recommend having anything in-between a ul and li. </p>\n\n<p>If you make the anchor tag display:block that fills the list, the whole list tag will be clickable. So dont put any height, width, or padding on the list and manage it all instead with the anchor. </p>\n\n<pre><code>a {\n display: block;\n width: 100%;\n}\n</code></pre>\n" } ]
2016/03/10
[ "https://wordpress.stackexchange.com/questions/220245", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60779/" ]
Whats the most simple way to change my wp-menu generated output from `<li><a href="">nav link</a></li>` to `<a href=""><li><li/></a>`? Do I create an array in my `functions.php`? This is what I have in my `functions.php` ``` function register_my_menus() { register_nav_menus( array( 'primary' => __( 'Main Menu' ), 'mobile-menu' => __( 'Mobile Menu' ), ) ); } add_action( 'init', 'register_my_menus' ); ```
I don't recommend having anything in-between a ul and li. If you make the anchor tag display:block that fills the list, the whole list tag will be clickable. So dont put any height, width, or padding on the list and manage it all instead with the anchor. ``` a { display: block; width: 100%; } ```
220,270
<p>What I'm trying to do is show the current logged in user's comment at the top of the list in the comments section in Wordpress on any given post. I don't care if it is just duplicated at the top and still shows in the regular order below as well, I just need it to show at the top of the list so the user can find it easily. I figured out how to single out their comment so I can style it with CSS, but changing where it appears in the list is eluding me. Any help would be incredibly appreciated, thanks in advance guys.</p> <pre><code>add_filter( 'comment_class', 'comment_class_logged_in_user' ); function comment_class_logged_in_user( $classes ) { global $comment; if ( $comment-&gt;user_id &gt; 0 &amp;&amp; is_user_logged_in() ) { global $current_user; get_currentuserinfo(); $logged_in_user = $current_user-&gt;ID; if( $comment-&gt;user_id == $logged_in_user ) $classes[] = 'comment-author-logged-in'; } return $classes; } </code></pre> <p>This is what I tried for my wp_comment_query, but it doesn't work.</p> <pre><code>&lt;?php global $current_user; get_currentuserinfo(); $logged_in_user = $current_user-&gt;ID; $args = array( 'user_id' =&gt; '$logged_in_user', ); // The Query $comments_query = new WP_Comment_Query; $comments = $comments_query-&gt;query( $args ); // Comment Loop if ( $comments ) { foreach ( $comments as $comment ) { echo '&lt;p&gt;' . $comment-&gt;comment_content . '&lt;/p&gt;'; } } else { echo 'No comments found.'; } ?&gt; </code></pre>
[ { "answer_id": 220253, "author": "Madan Karki", "author_id": 83958, "author_profile": "https://wordpress.stackexchange.com/users/83958", "pm_score": -1, "selected": false, "text": "<p>use <a href=\"https://gist.github.com/toscho/1053467\" rel=\"nofollow\">\"T5_Nav_Menu_Walker_Simple\"</a> custom walker to modify markup of <code>Wp_nav_menu</code>:</p>\n\n<pre><code>&lt;?php # -*- coding: utf-8 -*-\n/**\n * Create a nav menu with very basic markup.\n *\n * @author Thomas Scholz http://toscho.de\n * @version 1.0\n */\nclass T5_Nav_Menu_Walker_Simple extends Walker_Nav_Menu\n{\n /**\n * Start the element output.\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @param object $item Menu item data object.\n * @param int $depth Depth of menu item. May be used for padding.\n * @param array $args Additional strings.\n * @return void\n */\n public function start_el( &amp;$output, $item, $depth, $args )\n {\n $output .= '&lt;li&gt;';\n $attributes = '';\n ! empty ( $item-&gt;attr_title )\n // Avoid redundant titles\n and $item-&gt;attr_title !== $item-&gt;title\n and $attributes .= ' title=\"' . esc_attr( $item-&gt;attr_title ) .'\"';\n ! empty ( $item-&gt;url )\n and $attributes .= ' href=\"' . esc_attr( $item-&gt;url ) .'\"';\n $attributes = trim( $attributes );\n $title = apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID );\n $item_output = \"$args-&gt;before&lt;a $attributes&gt;$args-&gt;link_before$title&lt;/a&gt;\"\n . \"$args-&gt;link_after$args-&gt;after\";\n // Since $output is called by reference we don't need to return anything.\n $output .= apply_filters(\n 'walker_nav_menu_start_el'\n , $item_output\n , $item\n , $depth\n , $args\n );\n }\n /**\n * @see Walker::start_lvl()\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @return void\n */\n public function start_lvl( &amp;$output )\n {\n $output .= '&lt;ul class=\"sub-menu\"&gt;';\n }\n /**\n * @see Walker::end_lvl()\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @return void\n */\n public function end_lvl( &amp;$output )\n {\n $output .= '&lt;/ul&gt;';\n }\n /**\n * @see Walker::end_el()\n *\n * @param string $output Passed by reference. Used to append additional content.\n * @return void\n */\n function end_el( &amp;$output )\n {\n $output .= '&lt;/li&gt;';\n }\n}\n</code></pre>\n" }, { "answer_id": 220351, "author": "RLM", "author_id": 60779, "author_profile": "https://wordpress.stackexchange.com/users/60779", "pm_score": 0, "selected": false, "text": "<p>I really just wanted to make the WHOLE <code>&lt;li&gt;</code> linkable and I achieved that ( simply ) by getting rid of padding on <code>menu li</code> and adding it and <code>display:block</code> to <code>menu li a</code></p>\n" }, { "answer_id": 220356, "author": "Peter Thomas Simmons", "author_id": 83121, "author_profile": "https://wordpress.stackexchange.com/users/83121", "pm_score": 1, "selected": false, "text": "<p>I don't recommend having anything in-between a ul and li. </p>\n\n<p>If you make the anchor tag display:block that fills the list, the whole list tag will be clickable. So dont put any height, width, or padding on the list and manage it all instead with the anchor. </p>\n\n<pre><code>a {\n display: block;\n width: 100%;\n}\n</code></pre>\n" } ]
2016/03/10
[ "https://wordpress.stackexchange.com/questions/220270", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90312/" ]
What I'm trying to do is show the current logged in user's comment at the top of the list in the comments section in Wordpress on any given post. I don't care if it is just duplicated at the top and still shows in the regular order below as well, I just need it to show at the top of the list so the user can find it easily. I figured out how to single out their comment so I can style it with CSS, but changing where it appears in the list is eluding me. Any help would be incredibly appreciated, thanks in advance guys. ``` add_filter( 'comment_class', 'comment_class_logged_in_user' ); function comment_class_logged_in_user( $classes ) { global $comment; if ( $comment->user_id > 0 && is_user_logged_in() ) { global $current_user; get_currentuserinfo(); $logged_in_user = $current_user->ID; if( $comment->user_id == $logged_in_user ) $classes[] = 'comment-author-logged-in'; } return $classes; } ``` This is what I tried for my wp\_comment\_query, but it doesn't work. ``` <?php global $current_user; get_currentuserinfo(); $logged_in_user = $current_user->ID; $args = array( 'user_id' => '$logged_in_user', ); // The Query $comments_query = new WP_Comment_Query; $comments = $comments_query->query( $args ); // Comment Loop if ( $comments ) { foreach ( $comments as $comment ) { echo '<p>' . $comment->comment_content . '</p>'; } } else { echo 'No comments found.'; } ?> ```
I don't recommend having anything in-between a ul and li. If you make the anchor tag display:block that fills the list, the whole list tag will be clickable. So dont put any height, width, or padding on the list and manage it all instead with the anchor. ``` a { display: block; width: 100%; } ```
220,275
<p>I'm using PHPUnit to Unit Test my WP plugin on top of the WP testing suite. Everything works fine except that when I try to create a table via the setUp method, the table doesn't get created. </p> <p>Here's my code:</p> <pre><code>class Test_Db extends PAO_UnitTestCase { function setUp() { parent::setUp(); global $wpdb; $sql = "CREATE TABLE {$wpdb-&gt;prefix}mytest ( id bigint(20) NOT NULL AUTO_INCREMENT, column_1 varchar(255) NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $this-&gt;el(dbDelta($sql)); } function tearDown() { parent::tearDown(); } function test_db_stuff(){ global $wpdb; $sql = "SHOW TABLES LIKE '%'"; $results = $wpdb-&gt;get_results($sql); foreach($results as $index =&gt; $value) { foreach($value as $tableName) { $this-&gt;el($tableName); } } } } </code></pre> <p>The class PAO_UnitTestCase is simply an extension of the WP_UnitTestCase class which contains one method - the el method - which simply logs whatever into a file of my choosing.</p> <p>As you can see, I used the el method to</p> <ol> <li>Write the response of dbDelta into the log</li> <li>Write the names of all existing tables into the log</li> </ol> <p>According to the log, dbDelta was able to create the table but it's not being listed down as part of the existing tables.</p> <p>So my questions are:</p> <ol> <li>Is it possible to create tables during unit testing via PHPUnit?</li> <li>If so, what am I doing wrong?</li> </ol> <p>Hope someone can help me.</p> <p>Thanks!</p> <p><strong>Update:</strong> As seen in the discussion and accepted answer below, the tables do get created but as TEMPORARY tables. You won't be able to see the tables via SHOW TABLES though but you check its existence by inserting a row and then trying to retrieve the row.</p>
[ { "answer_id": 220308, "author": "J.D.", "author_id": 27757, "author_profile": "https://wordpress.stackexchange.com/users/27757", "pm_score": 5, "selected": true, "text": "<p>You've just discovered an important feature of the core test suite: it forces any tables created during the test to be temporary tables.</p>\n\n<p>If you look in the <code>WP_UnitTestCase::setUp()</code> method you'll see that <a href=\"https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L120\" rel=\"noreferrer\">it calls a method called <code>start_transaction()</code></a>. That <a href=\"https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L260\" rel=\"noreferrer\"><code>start_transaction()</code> method</a> starts a <a href=\"https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-transactions.html\" rel=\"noreferrer\">MySQL database transaction</a>:</p>\n\n<pre><code> function start_transaction() {\n global $wpdb;\n $wpdb-&gt;query( 'SET autocommit = 0;' );\n $wpdb-&gt;query( 'START TRANSACTION;' );\n add_filter( 'query', array( $this, '_create_temporary_tables' ) );\n add_filter( 'query', array( $this, '_drop_temporary_tables' ) );\n }\n</code></pre>\n\n<p>It does this so that any changes that your test makes in the database can just be <a href=\"https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L141\" rel=\"noreferrer\">rolled back afterward in the <code>tearDown()</code> method</a>. This means that each test starts with a clean WordPress database, untainted by the prior tests.</p>\n\n<p>However, you'll note that <code>start_transaction()</code> also hooks two methods to the <a href=\"https://developer.wordpress.org/reference/hooks/query/\" rel=\"noreferrer\"><code>'query'</code> filter</a>: <code>_create_temporary_tables</code> and <code>_drop_temporary_tables</code>. If you look at <a href=\"https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L278\" rel=\"noreferrer\">the source of these methods</a>, you'll see that they cause any <code>CREATE</code> or <code>DROP</code> table queries to be for temporary tables instead:</p>\n\n<pre><code> function _create_temporary_tables( $query ) {\n if ( 'CREATE TABLE' === substr( trim( $query ), 0, 12 ) )\n return substr_replace( trim( $query ), 'CREATE TEMPORARY TABLE', 0, 12 );\n return $query;\n }\n\n function _drop_temporary_tables( $query ) {\n if ( 'DROP TABLE' === substr( trim( $query ), 0, 10 ) )\n return substr_replace( trim( $query ), 'DROP TEMPORARY TABLE', 0, 10 );\n return $query;\n }\n</code></pre>\n\n<p>The <code>'query'</code> filter is applied to all database queries passed through <code>$wpdb-&gt;query()</code>, <a href=\"https://developer.wordpress.org/reference/functions/dbdelta/#source-code\" rel=\"noreferrer\">which <code>dbDelta()</code> uses</a>. So that means when your tables are created, they are created as <em>temporary</em> tables.</p>\n\n<p>So in order to list those tables, <del>I think you'd have to show temporary tables instead: <code>$sql = \"SHOW TEMPORARY TABLES LIKE '%'\";</code></del></p>\n\n<p><strong>Update:</strong> MySQL doesn't allow you to list the temporary tables like you can with the regular tables. You will have to use another method of checking if the table exists, like attempting to insert a row.</p>\n\n<p>But why does the unit test case require temporary tables to be created in the first place? Remember that we are using MySQL transactions so that the database stays clean. We don't want to ever commit the transactions though, we want to always roll them back at the end of the test. But there are <a href=\"https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html\" rel=\"noreferrer\">some MySQL statements that will cause an <em>implicit</em> commit</a>. Among these are, you guessed it, <code>CREATE TABLE</code> and <code>DROP TABLE</code>. However, per the MySQL docs:</p>\n\n<blockquote>\n <p><code>CREATE TABLE</code> and <code>DROP TABLE</code> statements do not commit a transaction if the <code>TEMPORARY</code> keyword is used.</p>\n</blockquote>\n\n<p>So to avoid an implicit commit, the test case forces any tables created or dropped to be temporary tables.</p>\n\n<p>This is not a well documented feature, but once you understand what is going on it should be pretty easy to work with.</p>\n" }, { "answer_id": 405036, "author": "Enrique", "author_id": 221494, "author_profile": "https://wordpress.stackexchange.com/users/221494", "pm_score": 1, "selected": false, "text": "<p>Do not extend WP_UnitTestCase. Extend PHPUnit\\Framework\\TestCase instead. Changes made to tables structures won't be persisted (see <a href=\"https://make.wordpress.org/core/handbook/testing/automated-testing/writing-phpunit-tests/#database\" rel=\"nofollow noreferrer\">here</a>). But you will have to manually remove all the tables that were created during the test. You can look at this <a href=\"https://github.com/madasha/beerlog/blob/master/tests/test-beerlog_install.php\" rel=\"nofollow noreferrer\">example</a>. The repository is old but the code still works.</p>\n" } ]
2016/03/10
[ "https://wordpress.stackexchange.com/questions/220275", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38261/" ]
I'm using PHPUnit to Unit Test my WP plugin on top of the WP testing suite. Everything works fine except that when I try to create a table via the setUp method, the table doesn't get created. Here's my code: ``` class Test_Db extends PAO_UnitTestCase { function setUp() { parent::setUp(); global $wpdb; $sql = "CREATE TABLE {$wpdb->prefix}mytest ( id bigint(20) NOT NULL AUTO_INCREMENT, column_1 varchar(255) NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $this->el(dbDelta($sql)); } function tearDown() { parent::tearDown(); } function test_db_stuff(){ global $wpdb; $sql = "SHOW TABLES LIKE '%'"; $results = $wpdb->get_results($sql); foreach($results as $index => $value) { foreach($value as $tableName) { $this->el($tableName); } } } } ``` The class PAO\_UnitTestCase is simply an extension of the WP\_UnitTestCase class which contains one method - the el method - which simply logs whatever into a file of my choosing. As you can see, I used the el method to 1. Write the response of dbDelta into the log 2. Write the names of all existing tables into the log According to the log, dbDelta was able to create the table but it's not being listed down as part of the existing tables. So my questions are: 1. Is it possible to create tables during unit testing via PHPUnit? 2. If so, what am I doing wrong? Hope someone can help me. Thanks! **Update:** As seen in the discussion and accepted answer below, the tables do get created but as TEMPORARY tables. You won't be able to see the tables via SHOW TABLES though but you check its existence by inserting a row and then trying to retrieve the row.
You've just discovered an important feature of the core test suite: it forces any tables created during the test to be temporary tables. If you look in the `WP_UnitTestCase::setUp()` method you'll see that [it calls a method called `start_transaction()`](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L120). That [`start_transaction()` method](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L260) starts a [MySQL database transaction](https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-transactions.html): ``` function start_transaction() { global $wpdb; $wpdb->query( 'SET autocommit = 0;' ); $wpdb->query( 'START TRANSACTION;' ); add_filter( 'query', array( $this, '_create_temporary_tables' ) ); add_filter( 'query', array( $this, '_drop_temporary_tables' ) ); } ``` It does this so that any changes that your test makes in the database can just be [rolled back afterward in the `tearDown()` method](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L141). This means that each test starts with a clean WordPress database, untainted by the prior tests. However, you'll note that `start_transaction()` also hooks two methods to the [`'query'` filter](https://developer.wordpress.org/reference/hooks/query/): `_create_temporary_tables` and `_drop_temporary_tables`. If you look at [the source of these methods](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/includes/testcase.php#L278), you'll see that they cause any `CREATE` or `DROP` table queries to be for temporary tables instead: ``` function _create_temporary_tables( $query ) { if ( 'CREATE TABLE' === substr( trim( $query ), 0, 12 ) ) return substr_replace( trim( $query ), 'CREATE TEMPORARY TABLE', 0, 12 ); return $query; } function _drop_temporary_tables( $query ) { if ( 'DROP TABLE' === substr( trim( $query ), 0, 10 ) ) return substr_replace( trim( $query ), 'DROP TEMPORARY TABLE', 0, 10 ); return $query; } ``` The `'query'` filter is applied to all database queries passed through `$wpdb->query()`, [which `dbDelta()` uses](https://developer.wordpress.org/reference/functions/dbdelta/#source-code). So that means when your tables are created, they are created as *temporary* tables. So in order to list those tables, ~~I think you'd have to show temporary tables instead: `$sql = "SHOW TEMPORARY TABLES LIKE '%'";`~~ **Update:** MySQL doesn't allow you to list the temporary tables like you can with the regular tables. You will have to use another method of checking if the table exists, like attempting to insert a row. But why does the unit test case require temporary tables to be created in the first place? Remember that we are using MySQL transactions so that the database stays clean. We don't want to ever commit the transactions though, we want to always roll them back at the end of the test. But there are [some MySQL statements that will cause an *implicit* commit](https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html). Among these are, you guessed it, `CREATE TABLE` and `DROP TABLE`. However, per the MySQL docs: > > `CREATE TABLE` and `DROP TABLE` statements do not commit a transaction if the `TEMPORARY` keyword is used. > > > So to avoid an implicit commit, the test case forces any tables created or dropped to be temporary tables. This is not a well documented feature, but once you understand what is going on it should be pretty easy to work with.
220,278
<p>I am using CMB2 and following code to select date &amp; time:</p> <pre><code>$cmb-&gt;add_field( array( 'name' =&gt; __( 'Test Date/Time Picker Combo (UNIX timestamp)', 'cmb2' ), 'desc' =&gt; __( 'field description (optional)', 'cmb2' ), 'id' =&gt; $prefix . 'datetime_timestamp', 'type' =&gt; 'text_datetime_timestamp', ) ); </code></pre> <p>That code give me this in admin panel:</p> <p><a href="https://i.stack.imgur.com/tSJbN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tSJbN.png" alt="date and time admin"></a></p> <p>To retrieve this meta data I am using following code:</p> <pre><code>$text = get_post_meta( get_the_ID(), '_cmb2_event_date_prefix_datetime_timestamp', true ) echo esc_html( $text ); </code></pre> <p>But this gives me a number as follow not the date and time I selected in admin panel.</p> <pre><code>1457368800 </code></pre> <p>Why is this ? How can I get the date and time I selected in that meta box.</p>
[ { "answer_id": 220280, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 3, "selected": false, "text": "<p>You're almost there. The number you see is a called <a href=\"https://en.m.wikipedia.org/wiki/Unix_time\" rel=\"nofollow\">Unix Timestamp</a>.</p>\n\n<p>You can easily convert it using <a href=\"https://codex.wordpress.org/Function_Reference/date_i18n\" rel=\"nofollow\">date_i18n</a> like this:</p>\n\n<pre><code>&lt;?php echo date_i18n(get_option( 'date_format' ), $text); ?&gt;\n</code></pre>\n" }, { "answer_id": 220281, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 2, "selected": false, "text": "<p>It seems that CMB2 is sabving dates in unix timestamp format, which IMHO, is a really good thing. This makes sorting and searching a breeze when you need to sort or search data according to dates.</p>\n\n<p>It is really easy to convert unix timestamps into any needed format. As from PHP 5.3, you can use the <a href=\"http://uk.php.net/datetime\" rel=\"nofollow\"><code>DateTime</code> class</a> for these type of convertions</p>\n\n<pre><code>$text = get_post_meta( get_the_ID(), '_cmb2_event_date_prefix_datetime_timestamp', true );\n$date = DateTime::createFromFormat( 'U', $text );\necho $date-&gt;format( 'd/m/Y H:i');\n</code></pre>\n\n<p>Just make sure about the output format, we in South Africa reads <code>03/07/2016</code> as the <em>3rd of July 2016</em>, I know some countries read it as the <em>March the 7th 2016</em>. If the latter, then change your format to <code>m/d/Y H:i</code></p>\n" }, { "answer_id": 220282, "author": "Adam", "author_id": 13418, "author_profile": "https://wordpress.stackexchange.com/users/13418", "pm_score": 4, "selected": true, "text": "<p>The date/time related field types for CMB2 store all their values as Unix timestamps in the database with the exception of <code>text_datetime_timestamp_timezone</code> which stores it's value as a serialized DateTime object.</p>\n\n<ul>\n<li><strong>text_date_timestamp</strong> Date Picker (UNIX timestamp)</li>\n<li><strong>text_datetime_timestamp</strong> Text Date/Time Picker Combo (UNIX timestamp)</li>\n<li><strong>text_datetime_timestamp_timezone</strong> Text Date/Time Picker/Time zone Combo (serialized DateTime object)</li>\n</ul>\n\n<p>See: <a href=\"https://github.com/WebDevStudios/CMB2/wiki/Field-Types\" rel=\"noreferrer\">https://github.com/WebDevStudios/CMB2/wiki/Field-Types</a></p>\n\n<p>What you see in the metabox is a conversion from the Unix timestamp to a human readable format which I believe you can adjust to your liking using the <code>date_format</code> key when calling <code>$cmb-&gt;add_field()</code>.</p>\n\n<p>In your case, all you need to do is pass your timestamp through PHP's <code>date()</code> function to format the result as you desire.</p>\n\n<p>Example:</p>\n\n<pre><code>$text = get_post_meta( get_the_ID(), '_cmb2_event_date_prefix_datetime_timestamp', true )\necho date('Y-m-d H:i:s A', $text ); // results in 2016-03-07 08:40:00 AM\n</code></pre>\n\n<p>See the documentation on PHP's <code>date()</code> function for formatting instructions:</p>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/function.date.php\" rel=\"noreferrer\">http://php.net/manual/en/function.date.php</a></li>\n</ul>\n" } ]
2016/03/10
[ "https://wordpress.stackexchange.com/questions/220278", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/69828/" ]
I am using CMB2 and following code to select date & time: ``` $cmb->add_field( array( 'name' => __( 'Test Date/Time Picker Combo (UNIX timestamp)', 'cmb2' ), 'desc' => __( 'field description (optional)', 'cmb2' ), 'id' => $prefix . 'datetime_timestamp', 'type' => 'text_datetime_timestamp', ) ); ``` That code give me this in admin panel: [![date and time admin](https://i.stack.imgur.com/tSJbN.png)](https://i.stack.imgur.com/tSJbN.png) To retrieve this meta data I am using following code: ``` $text = get_post_meta( get_the_ID(), '_cmb2_event_date_prefix_datetime_timestamp', true ) echo esc_html( $text ); ``` But this gives me a number as follow not the date and time I selected in admin panel. ``` 1457368800 ``` Why is this ? How can I get the date and time I selected in that meta box.
The date/time related field types for CMB2 store all their values as Unix timestamps in the database with the exception of `text_datetime_timestamp_timezone` which stores it's value as a serialized DateTime object. * **text\_date\_timestamp** Date Picker (UNIX timestamp) * **text\_datetime\_timestamp** Text Date/Time Picker Combo (UNIX timestamp) * **text\_datetime\_timestamp\_timezone** Text Date/Time Picker/Time zone Combo (serialized DateTime object) See: <https://github.com/WebDevStudios/CMB2/wiki/Field-Types> What you see in the metabox is a conversion from the Unix timestamp to a human readable format which I believe you can adjust to your liking using the `date_format` key when calling `$cmb->add_field()`. In your case, all you need to do is pass your timestamp through PHP's `date()` function to format the result as you desire. Example: ``` $text = get_post_meta( get_the_ID(), '_cmb2_event_date_prefix_datetime_timestamp', true ) echo date('Y-m-d H:i:s A', $text ); // results in 2016-03-07 08:40:00 AM ``` See the documentation on PHP's `date()` function for formatting instructions: * <http://php.net/manual/en/function.date.php>
220,293
<p>When I call the_content(), I want to show only text and don't want to show images. Notable that, I don't want to remove text style. The text style should be display as well. How can I do this?</p>
[ { "answer_id": 220298, "author": "Kishan Chauhan", "author_id": 63564, "author_profile": "https://wordpress.stackexchange.com/users/63564", "pm_score": 3, "selected": true, "text": "<p>This answer already here <a href=\"https://wordpress.stackexchange.com/questions/162162/how-to-remove-images-from-showing-in-a-post-with-the-content#162165\">How to remove images from showing in a post with the_content()?</a></p>\n\n<pre><code>&lt;?php \n$content = get_the_content();\n$content = preg_replace(\"/&lt;img[^&gt;]+\\&gt;/i\", \" \", $content); \n$content = apply_filters('the_content', $content);\n$content = str_replace(']]&gt;', ']]&gt;', $content);\necho $content;\n?&gt;\n</code></pre>\n" }, { "answer_id": 220299, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 1, "selected": false, "text": "<p>Add this code to your <code>functions.php</code></p>\n<pre><code>function mdc_remove_img($content) {\n $content = preg_replace(&quot;/&lt;img[^&gt;]+\\&gt;/i&quot;, &quot;&quot;, $content); \n return $content;\n}\n\nadd_filter( 'the_content', 'mdc_remove_img' );\n</code></pre>\n" } ]
2016/03/10
[ "https://wordpress.stackexchange.com/questions/220293", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81042/" ]
When I call the\_content(), I want to show only text and don't want to show images. Notable that, I don't want to remove text style. The text style should be display as well. How can I do this?
This answer already here [How to remove images from showing in a post with the\_content()?](https://wordpress.stackexchange.com/questions/162162/how-to-remove-images-from-showing-in-a-post-with-the-content#162165) ``` <?php $content = get_the_content(); $content = preg_replace("/<img[^>]+\>/i", " ", $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content; ?> ```
220,326
<p>I'm hoping someone will be able to help me with this issue. I noticed today that when I search certain serch terms in my Wordpress site's search box the link is messed up (shown in the image below outlined by the yellow boxes) and when clicked, the link takes the user to a blank page.</p> <p><a href="https://i.stack.imgur.com/1J3I8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1J3I8.png" alt="Issue example"></a></p> <p>When I searched other terms, either there was the issue on all of the search results for that term or there was no issue at all.</p> <p>Any ideas what may be causing this and how to fix it? Thanks in advance!</p>
[ { "answer_id": 220298, "author": "Kishan Chauhan", "author_id": 63564, "author_profile": "https://wordpress.stackexchange.com/users/63564", "pm_score": 3, "selected": true, "text": "<p>This answer already here <a href=\"https://wordpress.stackexchange.com/questions/162162/how-to-remove-images-from-showing-in-a-post-with-the-content#162165\">How to remove images from showing in a post with the_content()?</a></p>\n\n<pre><code>&lt;?php \n$content = get_the_content();\n$content = preg_replace(\"/&lt;img[^&gt;]+\\&gt;/i\", \" \", $content); \n$content = apply_filters('the_content', $content);\n$content = str_replace(']]&gt;', ']]&gt;', $content);\necho $content;\n?&gt;\n</code></pre>\n" }, { "answer_id": 220299, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 1, "selected": false, "text": "<p>Add this code to your <code>functions.php</code></p>\n<pre><code>function mdc_remove_img($content) {\n $content = preg_replace(&quot;/&lt;img[^&gt;]+\\&gt;/i&quot;, &quot;&quot;, $content); \n return $content;\n}\n\nadd_filter( 'the_content', 'mdc_remove_img' );\n</code></pre>\n" } ]
2016/03/10
[ "https://wordpress.stackexchange.com/questions/220326", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90354/" ]
I'm hoping someone will be able to help me with this issue. I noticed today that when I search certain serch terms in my Wordpress site's search box the link is messed up (shown in the image below outlined by the yellow boxes) and when clicked, the link takes the user to a blank page. [![Issue example](https://i.stack.imgur.com/1J3I8.png)](https://i.stack.imgur.com/1J3I8.png) When I searched other terms, either there was the issue on all of the search results for that term or there was no issue at all. Any ideas what may be causing this and how to fix it? Thanks in advance!
This answer already here [How to remove images from showing in a post with the\_content()?](https://wordpress.stackexchange.com/questions/162162/how-to-remove-images-from-showing-in-a-post-with-the-content#162165) ``` <?php $content = get_the_content(); $content = preg_replace("/<img[^>]+\>/i", " ", $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content; ?> ```
220,330
<p>This is my code. Where I'm wrong? </p> <pre><code>&lt;?php $connection = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD); mysql_select_db($DB_NAME); $img = mysql_query("SELECT * FROM wp_bwg_image"); while($res = mysql_fetch_array($img)){ echo $res; } ?&gt; </code></pre> <p>From this table I want to take any pictures.</p> <p><a href="https://i.stack.imgur.com/2DaDY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2DaDY.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 220385, "author": "brianlmerritt", "author_id": 78419, "author_profile": "https://wordpress.stackexchange.com/users/78419", "pm_score": 1, "selected": false, "text": "<p>Use the global $wpdb for example <code>$myrows = $wpdb-&gt;get_results( “insert sql here\");</code></p>\n" }, { "answer_id": 220397, "author": "Venelin Vasilev", "author_id": 90385, "author_profile": "https://wordpress.stackexchange.com/users/90385", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>&lt;?php\n $connection = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD); \n mysql_select_db($DB_NAME);\n $img = mysql_query(\"SELECT * FROM wp_bwg_image\");\n\n while($res = mysql_fetch_array($img)){\n $Image = $res['image_url'];\n echo $Image;\n }\n?&gt;\n</code></pre>\n\n<p>You are not declaring the row name from which you want to get data.</p>\n" } ]
2016/03/10
[ "https://wordpress.stackexchange.com/questions/220330", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90333/" ]
This is my code. Where I'm wrong? ``` <?php $connection = mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD); mysql_select_db($DB_NAME); $img = mysql_query("SELECT * FROM wp_bwg_image"); while($res = mysql_fetch_array($img)){ echo $res; } ?> ``` From this table I want to take any pictures. [![enter image description here](https://i.stack.imgur.com/2DaDY.jpg)](https://i.stack.imgur.com/2DaDY.jpg)
Use the global $wpdb for example `$myrows = $wpdb->get_results( “insert sql here");`
220,339
<p>I have a little problem, I created a wordpress theme with documentation created with the site helpscout, to reduce the number of support ticket, I would like to do the same thing EDD: <a href="https://easydigitaldownloads.com/support/" rel="nofollow">https://easydigitaldownloads.com/support/</a>, if you click on "Submit Support Request", an input appears and if you enter a word, for example, "google", links to helpscout documentation are available, then you can create a request. I copied the code of this site, I created a multi-part form with gravity form, everything works well, except looking towards the doc, here is the code I entered my functions.php file:</p> <pre><code>function support_form() { if ( ! wp_script_is( 'gform_gravityforms' ) ) { return; } ?&gt; &lt;script type="text/javascript"&gt; jQuery(document).ready(function($) { var wrap = $('.gform_body .gfield.helpscout-docs'); var paging = $('.gform_body .gform_page_footer'); var hidden = $('.gform_body .gfield.helpscout-docs').next().find('input'); var field = wrap.find('input[type="text"]'); var searching = false, allowed = false; paging.hide(); wrap.append( '&lt;div class="docs-search-wrap"&gt;&lt;/div&gt;' ); field.attr( 'autocomplete', 'off' ); paging.find('input[type="submit"]').on('click', function(e) { if( ! allowed ) { return false; } }); field.keyup(function(e) { query = $(this).val(); if( query.length &lt; 4 ) { return; } var html = '&lt;ul class="docs-search-results"&gt;'; if( ! searching ) { var count = 0; // Getting Started $.ajax({ url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d89d519033600eafd436e4&amp;query=' + query, headers: { 'Authorization': 'Basic &lt;?php echo base64_encode( 'username:password' ); ?&gt;' }, xhrFields: { withCredentials: false }, beforeSend: function() { searching = true; }, success: function(results) { count += results.articles.items.length; $.each( results.articles.items, function( key, article ) { html = html + '&lt;li class="article"&gt;&lt;a href="' + article.url + '" title="' + article.preview + '" target="_blank"&gt;' + article.name + '&lt;/a&gt;&lt;li&gt;'; }); } }).done(function() { // FAQs $.ajax({ url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d8b3c9c6979159b4453cf6&amp;query=' + query, headers: { 'Authorization': 'Basic &lt;?php echo base64_encode( 'username:password' ); ?&gt;' }, xhrFields: { withCredentials: false }, beforeSend: function() { searching = true; }, success: function(results) { count += results.articles.items.length; $.each( results.articles.items, function( key, article ) { html = html + '&lt;li class="article"&gt;&lt;a href="' + article.url + '" title="' + article.preview + '" target="_blank"&gt;' + article.name + '&lt;/a&gt;&lt;li&gt;'; }); } }).done(function() { // Extensions $.ajax({ url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d8b96fc6979159b4453d22&amp;query=' + query, headers: { 'Authorization': 'Basic &lt;?php echo base64_encode( 'username:password' ); ?&gt;' }, xhrFields: { withCredentials: false }, beforeSend: function() { searching = true; }, success: function(results) { count += results.articles.items.length; $.each( results.articles.items, function( key, article ) { html = html + '&lt;li class="article"&gt;&lt;a href="' + article.url + '" title="' + article.preview + '" target="_blank"&gt;' + article.name + '&lt;/a&gt;&lt;li&gt;'; }); } }).done(function() { html = html + '&lt;/ul&gt;' html = '&lt;span class="results-found"&gt;' + count + ' results found . . . &lt;/span&gt;' + html; wrap.find('.docs-search-wrap').html( html ); paging.show(); searching = false; }); }); }); } }); }); &lt;/script&gt; &lt;?php } add_action( 'send_headers', 'add_header_acao' ); function add_header_acao() { header( 'Access-Control-Allow-Origin: *' ); } </code></pre> <p>But when I enter a word in the input I receive an error message in the console: "No 'Access-Control-Allow-Origin' header is present on the requested resource."</p> <p>I have not inserted the " 'Access-Control-Allow-Origin" correctly? Is it because of the "username:password", I set the username and password from my dashboard help scout, maybe it is not that I need to insert.</p> <p>Can you help me?</p> <p>Thank you a lot :)</p>
[ { "answer_id": 220366, "author": "kingkool68", "author_id": 2744, "author_profile": "https://wordpress.stackexchange.com/users/2744", "pm_score": 0, "selected": false, "text": "<p>You're trying to make an AJAX request to another domain which is prohibited by JavaScript for security/privacy reasons.If docsapi.helpscout.net returned a certain HTTP header in their response then it would work. The answer on this Stackoverflow question provides a good explanation about how CORS works <a href=\"https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work\">https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work</a></p>\n\n<p>One workaround would be to make an AJAX request to your own server passing the URL you want to query and then let your server make the request and return the response back to your page. This gets around the cross-site origin issue but it is a little more complicated.</p>\n" }, { "answer_id": 220386, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>Have you tried adding the header that it is mentioning. Even though it is a CORS request as @kingkool68 is pointing out, it seems like you are only going to get the needed response if you send the needed header with the request. Try adding it this way:</p>\n\n<pre><code>headers: {\n 'Access-Control-Allow-Origin': '&lt;?php echo home_url(); ?&gt;',\n 'Authorization': 'Basic &lt;?php echo base64_encode( 'username:password' ); ?&gt;'\n},\n</code></pre>\n" }, { "answer_id": 220453, "author": "Nick", "author_id": 45874, "author_profile": "https://wordpress.stackexchange.com/users/45874", "pm_score": 1, "selected": false, "text": "<p>I found !!!\nIt had nothing to do with \"Access-Control-Allow-Origin\" was because of the API key, I entered the username and password from my dashboard help scout, I had to enter the api key for my documentation :)</p>\n\n<p>Thanks a lot for your help :)</p>\n" } ]
2016/03/10
[ "https://wordpress.stackexchange.com/questions/220339", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45874/" ]
I have a little problem, I created a wordpress theme with documentation created with the site helpscout, to reduce the number of support ticket, I would like to do the same thing EDD: <https://easydigitaldownloads.com/support/>, if you click on "Submit Support Request", an input appears and if you enter a word, for example, "google", links to helpscout documentation are available, then you can create a request. I copied the code of this site, I created a multi-part form with gravity form, everything works well, except looking towards the doc, here is the code I entered my functions.php file: ``` function support_form() { if ( ! wp_script_is( 'gform_gravityforms' ) ) { return; } ?> <script type="text/javascript"> jQuery(document).ready(function($) { var wrap = $('.gform_body .gfield.helpscout-docs'); var paging = $('.gform_body .gform_page_footer'); var hidden = $('.gform_body .gfield.helpscout-docs').next().find('input'); var field = wrap.find('input[type="text"]'); var searching = false, allowed = false; paging.hide(); wrap.append( '<div class="docs-search-wrap"></div>' ); field.attr( 'autocomplete', 'off' ); paging.find('input[type="submit"]').on('click', function(e) { if( ! allowed ) { return false; } }); field.keyup(function(e) { query = $(this).val(); if( query.length < 4 ) { return; } var html = '<ul class="docs-search-results">'; if( ! searching ) { var count = 0; // Getting Started $.ajax({ url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d89d519033600eafd436e4&query=' + query, headers: { 'Authorization': 'Basic <?php echo base64_encode( 'username:password' ); ?>' }, xhrFields: { withCredentials: false }, beforeSend: function() { searching = true; }, success: function(results) { count += results.articles.items.length; $.each( results.articles.items, function( key, article ) { html = html + '<li class="article"><a href="' + article.url + '" title="' + article.preview + '" target="_blank">' + article.name + '</a><li>'; }); } }).done(function() { // FAQs $.ajax({ url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d8b3c9c6979159b4453cf6&query=' + query, headers: { 'Authorization': 'Basic <?php echo base64_encode( 'username:password' ); ?>' }, xhrFields: { withCredentials: false }, beforeSend: function() { searching = true; }, success: function(results) { count += results.articles.items.length; $.each( results.articles.items, function( key, article ) { html = html + '<li class="article"><a href="' + article.url + '" title="' + article.preview + '" target="_blank">' + article.name + '</a><li>'; }); } }).done(function() { // Extensions $.ajax({ url: 'https://docsapi.helpscout.net/v1/search/articles?collectionId=56d8b96fc6979159b4453d22&query=' + query, headers: { 'Authorization': 'Basic <?php echo base64_encode( 'username:password' ); ?>' }, xhrFields: { withCredentials: false }, beforeSend: function() { searching = true; }, success: function(results) { count += results.articles.items.length; $.each( results.articles.items, function( key, article ) { html = html + '<li class="article"><a href="' + article.url + '" title="' + article.preview + '" target="_blank">' + article.name + '</a><li>'; }); } }).done(function() { html = html + '</ul>' html = '<span class="results-found">' + count + ' results found . . . </span>' + html; wrap.find('.docs-search-wrap').html( html ); paging.show(); searching = false; }); }); }); } }); }); </script> <?php } add_action( 'send_headers', 'add_header_acao' ); function add_header_acao() { header( 'Access-Control-Allow-Origin: *' ); } ``` But when I enter a word in the input I receive an error message in the console: "No 'Access-Control-Allow-Origin' header is present on the requested resource." I have not inserted the " 'Access-Control-Allow-Origin" correctly? Is it because of the "username:password", I set the username and password from my dashboard help scout, maybe it is not that I need to insert. Can you help me? Thank you a lot :)
I found !!! It had nothing to do with "Access-Control-Allow-Origin" was because of the API key, I entered the username and password from my dashboard help scout, I had to enter the api key for my documentation :) Thanks a lot for your help :)
220,347
<p>I have created a metabox to upload images. Whenever I click on the "Select Image" button the Image Uploader Box successfully pops up but when I select an image and click the "Insert" button the image URL doesn't get inserted in the text field. Please tell me what to do so that whenever I insert an image the image URL gets inserted into the correct field.</p> <pre><code>var image_field; jQuery( function( $ ) { $( document ).on( 'click', 'input.select-img', function( evt ) { image_field = $( this ).siblings( '.img' ); check_flag = 1; tb_show( '', 'media-upload.php?type=image&amp;amp;TB_iframe=true' ); window.send_to_editor = function( html ) { imgurl = $( 'img', html ).attr( 'src' ); image_field.val( imgurl ); tb_remove(); } return false; } ); } ); </code></pre>
[ { "answer_id": 220366, "author": "kingkool68", "author_id": 2744, "author_profile": "https://wordpress.stackexchange.com/users/2744", "pm_score": 0, "selected": false, "text": "<p>You're trying to make an AJAX request to another domain which is prohibited by JavaScript for security/privacy reasons.If docsapi.helpscout.net returned a certain HTTP header in their response then it would work. The answer on this Stackoverflow question provides a good explanation about how CORS works <a href=\"https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work\">https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work</a></p>\n\n<p>One workaround would be to make an AJAX request to your own server passing the URL you want to query and then let your server make the request and return the response back to your page. This gets around the cross-site origin issue but it is a little more complicated.</p>\n" }, { "answer_id": 220386, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>Have you tried adding the header that it is mentioning. Even though it is a CORS request as @kingkool68 is pointing out, it seems like you are only going to get the needed response if you send the needed header with the request. Try adding it this way:</p>\n\n<pre><code>headers: {\n 'Access-Control-Allow-Origin': '&lt;?php echo home_url(); ?&gt;',\n 'Authorization': 'Basic &lt;?php echo base64_encode( 'username:password' ); ?&gt;'\n},\n</code></pre>\n" }, { "answer_id": 220453, "author": "Nick", "author_id": 45874, "author_profile": "https://wordpress.stackexchange.com/users/45874", "pm_score": 1, "selected": false, "text": "<p>I found !!!\nIt had nothing to do with \"Access-Control-Allow-Origin\" was because of the API key, I entered the username and password from my dashboard help scout, I had to enter the api key for my documentation :)</p>\n\n<p>Thanks a lot for your help :)</p>\n" } ]
2016/03/10
[ "https://wordpress.stackexchange.com/questions/220347", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90367/" ]
I have created a metabox to upload images. Whenever I click on the "Select Image" button the Image Uploader Box successfully pops up but when I select an image and click the "Insert" button the image URL doesn't get inserted in the text field. Please tell me what to do so that whenever I insert an image the image URL gets inserted into the correct field. ``` var image_field; jQuery( function( $ ) { $( document ).on( 'click', 'input.select-img', function( evt ) { image_field = $( this ).siblings( '.img' ); check_flag = 1; tb_show( '', 'media-upload.php?type=image&amp;TB_iframe=true' ); window.send_to_editor = function( html ) { imgurl = $( 'img', html ).attr( 'src' ); image_field.val( imgurl ); tb_remove(); } return false; } ); } ); ```
I found !!! It had nothing to do with "Access-Control-Allow-Origin" was because of the API key, I entered the username and password from my dashboard help scout, I had to enter the api key for my documentation :) Thanks a lot for your help :)
220,349
<p>I have a plugin that is syncing data from a third party service into a custom post type. The idea is that the post type acts as a slave to the third party service, so any changes there overwrite any on the wordpress site. However there will be a few extra custom fields that will be made to add information from the wordpress side to the data from the third party service.</p> <p>What I am looking for is a way to more or less disable the fields that will be overwritten (title, body, 50-60 custom fields) Leaving only the ones that will not be overwritten to be editable.</p> <p>I know how to hide title/body (although unsure if it completely removes them), however I feel it would be beneficial to keep them visible, just grayed out / disabled. </p> <p>This is how I am disabling title/body:</p> <pre><code>function remove_edit_fields(){ remove_post_type_support( 'property_listings', 'title' ); remove_post_type_support( 'property_listings', 'editor' ); } add_action( 'admin_init', 'remove_edit_fields' ); </code></pre> <p>Is there any way to do this while keeping them visible and do the same for custom fields?</p>
[ { "answer_id": 220371, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>To begin with, adding an <code>_</code> to the start of the custom field key will make it a hidden field not available for editing from the post writing screen. </p>\n\n<p>ie. using <code>_address</code> instead of just <code>address</code>. </p>\n\n<p>I think this is what you are looking for..?</p>\n\n<p>If you then want to display these hidden field values (read-only) on the post writing screen then you can probably add a metabox that will output the display.</p>\n" }, { "answer_id": 220668, "author": "Jordan Ramstad", "author_id": 63445, "author_profile": "https://wordpress.stackexchange.com/users/63445", "pm_score": 1, "selected": true, "text": "<p>In order to do this I had to hide the fields in the default ACF output. There is no way to do this in the core, underscores can work to disable the output everywhere else but the edit area is an exception.</p>\n\n<p>I had used the following code to create a hidden field type, it outputs no input and hides its own label. It is based off of <a href=\"https://github.com/gerbenvandijk/acf-hidden-field\" rel=\"nofollow\">https://github.com/gerbenvandijk/acf-hidden-field</a></p>\n\n<pre><code>&lt;?php\nclass acf_field_hidden_field extends acf_field\n{\n // vars\n var $settings, // will hold info such as dir / path\n $defaults; // will hold default field options\n /*\n * __construct\n *\n * Set name / label needed for actions / filters\n *\n * @since 3.6\n * @date 23/01/13\n */\n function __construct()\n {\n // vars\n $this-&gt;name = 'hidden_field';\n $this-&gt;label = __('Hidden field');\n $this-&gt;category = __(\"Basic\",'acf'); // Basic, Content, Choice, etc\n $this-&gt;defaults = array(\n // add default here to merge into your field.\n // This makes life easy when creating the field options as you don't need to use any if( isset('') ) logic. eg:\n //'preview_size' =&gt; 'thumbnail'\n );\n // do not delete!\n parent::__construct();\n // settings\n $this-&gt;settings = array(\n 'path' =&gt; apply_filters('acf/helpers/get_path', __FILE__),\n 'dir' =&gt; apply_filters('acf/helpers/get_dir', __FILE__),\n 'version' =&gt; '1.0.0'\n );\n }\n /*\n * create_field()\n *\n * Create the HTML interface for your field\n *\n * @param $field - an array holding all the field's data\n *\n * @type action\n * @since 3.6\n * @date 23/01/13\n */\n function render_field( $field )\n {\n // defaults?\n /*\n $field = array_merge($this-&gt;defaults, $field);\n */\n // perhaps use $field['preview_size'] to alter the markup?\n // create Field HTML\n ?&gt;\n &lt;style&gt;div[data-key=\"&lt;?php echo $field['key'];?&gt;\"]{ display: none;}&lt;/style&gt;\n &lt;?php\n }\n}\n// create field\nnew acf_field_hidden_field();\n?&gt;\n</code></pre>\n\n<p>I also used my own custom meta box to bring the data in, my way. I had \"labeled\" the fields by naming them in such a way as to know they were technically hidden fields (like <code>hide_title</code> and <code>hide_desc</code>). By using a custom one it does not affect the regular front end display.</p>\n" } ]
2016/03/10
[ "https://wordpress.stackexchange.com/questions/220349", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63445/" ]
I have a plugin that is syncing data from a third party service into a custom post type. The idea is that the post type acts as a slave to the third party service, so any changes there overwrite any on the wordpress site. However there will be a few extra custom fields that will be made to add information from the wordpress side to the data from the third party service. What I am looking for is a way to more or less disable the fields that will be overwritten (title, body, 50-60 custom fields) Leaving only the ones that will not be overwritten to be editable. I know how to hide title/body (although unsure if it completely removes them), however I feel it would be beneficial to keep them visible, just grayed out / disabled. This is how I am disabling title/body: ``` function remove_edit_fields(){ remove_post_type_support( 'property_listings', 'title' ); remove_post_type_support( 'property_listings', 'editor' ); } add_action( 'admin_init', 'remove_edit_fields' ); ``` Is there any way to do this while keeping them visible and do the same for custom fields?
In order to do this I had to hide the fields in the default ACF output. There is no way to do this in the core, underscores can work to disable the output everywhere else but the edit area is an exception. I had used the following code to create a hidden field type, it outputs no input and hides its own label. It is based off of <https://github.com/gerbenvandijk/acf-hidden-field> ``` <?php class acf_field_hidden_field extends acf_field { // vars var $settings, // will hold info such as dir / path $defaults; // will hold default field options /* * __construct * * Set name / label needed for actions / filters * * @since 3.6 * @date 23/01/13 */ function __construct() { // vars $this->name = 'hidden_field'; $this->label = __('Hidden field'); $this->category = __("Basic",'acf'); // Basic, Content, Choice, etc $this->defaults = array( // add default here to merge into your field. // This makes life easy when creating the field options as you don't need to use any if( isset('') ) logic. eg: //'preview_size' => 'thumbnail' ); // do not delete! parent::__construct(); // settings $this->settings = array( 'path' => apply_filters('acf/helpers/get_path', __FILE__), 'dir' => apply_filters('acf/helpers/get_dir', __FILE__), 'version' => '1.0.0' ); } /* * create_field() * * Create the HTML interface for your field * * @param $field - an array holding all the field's data * * @type action * @since 3.6 * @date 23/01/13 */ function render_field( $field ) { // defaults? /* $field = array_merge($this->defaults, $field); */ // perhaps use $field['preview_size'] to alter the markup? // create Field HTML ?> <style>div[data-key="<?php echo $field['key'];?>"]{ display: none;}</style> <?php } } // create field new acf_field_hidden_field(); ?> ``` I also used my own custom meta box to bring the data in, my way. I had "labeled" the fields by naming them in such a way as to know they were technically hidden fields (like `hide_title` and `hide_desc`). By using a custom one it does not affect the regular front end display.
220,376
<p>In the home page, I have a custom loop for displaying different post type content. I have this loop on my index.php</p> <pre><code>$loop = new WP_Query( array( 'post_type' =&gt; array('photo', 'video', 'web'), 'paged' =&gt; get_query_var('paged') ? get_query_var('paged') : 1, 'posts_per_page' =&gt; -1 ) ); </code></pre> <p>Now it displays correctly but I want to include the title from what post type it belongs so that I can link to right page.</p> <p>for example if I have these items in my home page (as a result of the above loop):</p> <ol> <li>Item 1 - <a href="http://page-video" rel="nofollow">video</a></li> <li>Item 2 - <a href="http://page-photo" rel="nofollow">photo</a></li> <li>Item 3 - <a href="http://page-web" rel="nofollow">web</a></li> </ol> <p>Where the links are the page I created that displays those custom post type and the title is the title of the post type (ie video. photo, web).</p> <p>I have tried this to put inside my loop but it doesn't work.</p> <pre><code>&lt;?php while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;?php if ( is_singular( 'photo' ) ) : echo "&lt;a href='/photo'&gt;photo&lt;/a&gt;"; elseif ( is_singular( 'video' ) ) : echo "&lt;a href='/video'&gt;video&lt;/a&gt;"; elseif ( is_singular( 'web' ) ) : echo "&lt;a href='/web'&gt;web&lt;/a&gt;"; endif; ?&gt; &lt;?php get_template_part( 'content', 'grid'); ?&gt; &lt;?php endwhile; ?&gt; </code></pre>
[ { "answer_id": 220382, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>You are doing it wrong on many levels here:</p>\n\n<ul>\n<li><p>You should not be using a custom query in place of the main query. Rather use <code>pre_get_posts</code> to alter the main query accordingly. Go back to the main loop and add the following in your functions file or in a custom plugin</p>\n\n<pre><code>add_action( 'pre_get_posts', function ( $q )\n{\n if ( $q-&gt;is_home()\n &amp;&amp; $q-&gt;is_main_query()\n ) {\n $q-&gt;set( 'post_type', ['photo', 'video', 'web'] );\n $q-&gt;set( 'posts_per_page', -1 );\n }\n});\n</code></pre></li>\n<li><p><code>is_singular()</code> is the wrong check here. <code>is_singular()</code> checks if you are on a singular post page, so it will always return false on any page that is not a singular post page. </p>\n\n<p>What you need is <code>get_post_type()</code> to get the post type the post belongs to and test against that</p>\n\n<pre><code>if ( 'photo' === get_post_type() ) :\n echo \"&lt;a href='/photo'&gt;photo&lt;/a&gt;\";\n\nelseif ( 'video' === get_post_type() ) :\n echo \"&lt;a href='/video'&gt;video&lt;/a&gt;\";\n\nelseif ( 'web' === get_post_type() ) :\n echo \"&lt;a href='/web'&gt;web&lt;/a&gt;\";\n endif;\n</code></pre></li>\n<li><p>Lastly, if you want to link to the archive pages of those post types, you should be using <a href=\"https://codex.wordpress.org/Function_Reference/get_post_type_archive_link\" rel=\"nofollow noreferrer\"><code>get_post_type_archive()</code></a>. Something like the following would work</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo get_post_type_archive_link( 'Photo' ); ?&gt;\"&gt;Photo&lt;/a&gt;\n</code></pre>\n\n<p>instead of <code>echo \"&lt;a href='/photo'&gt;photo&lt;/a&gt;\"</code></p></li>\n</ul>\n\n<h2>EDIT</h2>\n\n<p>From comments, I have done an extensive answer on why not to use custom queries in place of the main query. Feel free to check it out <a href=\"https://wordpress.stackexchange.com/a/155976/31545\">here</a>. It should answer quite a few questions for you</p>\n" }, { "answer_id": 220391, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 0, "selected": false, "text": "<p>Calling <code>the_post()</code> populates the <code>$post</code> object variable, so you can use this to make things easier by getting information directly from the <code>$post</code> object (and also the post type object):</p>\n\n<pre><code>&lt;?php $post_object = array();\n\nwhile ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); \n\nglobal $post; $post_type = $post-&gt;post_type; // just for clarity\n\n// link to post permalink with post title anchor\necho \"&lt;a href='\".get_permalink($post-&gt;ID).\"'&gt;\".$post-&gt;post_title.\"&lt;/a&gt;\";\n\n// to be efficient, only get the post type object if we have not already\nif (!isset($post_object[$post_type])) {$post_object[$post_type] = get_post_type_object($post_type);}\n\n// link to post type archive, with post type name as anchor (plural)\necho \" (&lt;a href='\".get_post_type_archive_link($post_type).\"'&gt;\".$post_object[$post_type]-&gt;labels-&gt;name.\"&lt;/a&gt;)\";\n\nget_template_part( 'content', 'grid');\n\nendwhile; ?&gt;\n</code></pre>\n\n<p>This should cover all post types now rather than having to add conditions if you ever add more.</p>\n" } ]
2016/03/11
[ "https://wordpress.stackexchange.com/questions/220376", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/55160/" ]
In the home page, I have a custom loop for displaying different post type content. I have this loop on my index.php ``` $loop = new WP_Query( array( 'post_type' => array('photo', 'video', 'web'), 'paged' => get_query_var('paged') ? get_query_var('paged') : 1, 'posts_per_page' => -1 ) ); ``` Now it displays correctly but I want to include the title from what post type it belongs so that I can link to right page. for example if I have these items in my home page (as a result of the above loop): 1. Item 1 - [video](http://page-video) 2. Item 2 - [photo](http://page-photo) 3. Item 3 - [web](http://page-web) Where the links are the page I created that displays those custom post type and the title is the title of the post type (ie video. photo, web). I have tried this to put inside my loop but it doesn't work. ``` <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php if ( is_singular( 'photo' ) ) : echo "<a href='/photo'>photo</a>"; elseif ( is_singular( 'video' ) ) : echo "<a href='/video'>video</a>"; elseif ( is_singular( 'web' ) ) : echo "<a href='/web'>web</a>"; endif; ?> <?php get_template_part( 'content', 'grid'); ?> <?php endwhile; ?> ```
You are doing it wrong on many levels here: * You should not be using a custom query in place of the main query. Rather use `pre_get_posts` to alter the main query accordingly. Go back to the main loop and add the following in your functions file or in a custom plugin ``` add_action( 'pre_get_posts', function ( $q ) { if ( $q->is_home() && $q->is_main_query() ) { $q->set( 'post_type', ['photo', 'video', 'web'] ); $q->set( 'posts_per_page', -1 ); } }); ``` * `is_singular()` is the wrong check here. `is_singular()` checks if you are on a singular post page, so it will always return false on any page that is not a singular post page. What you need is `get_post_type()` to get the post type the post belongs to and test against that ``` if ( 'photo' === get_post_type() ) : echo "<a href='/photo'>photo</a>"; elseif ( 'video' === get_post_type() ) : echo "<a href='/video'>video</a>"; elseif ( 'web' === get_post_type() ) : echo "<a href='/web'>web</a>"; endif; ``` * Lastly, if you want to link to the archive pages of those post types, you should be using [`get_post_type_archive()`](https://codex.wordpress.org/Function_Reference/get_post_type_archive_link). Something like the following would work ``` <a href="<?php echo get_post_type_archive_link( 'Photo' ); ?>">Photo</a> ``` instead of `echo "<a href='/photo'>photo</a>"` EDIT ---- From comments, I have done an extensive answer on why not to use custom queries in place of the main query. Feel free to check it out [here](https://wordpress.stackexchange.com/a/155976/31545). It should answer quite a few questions for you
220,396
<p>I am using the 'standard' trick for category removal in wordpress. In my permalinks I set the permalinks structure to </p> <pre><code>/%category%/%postname%/ </code></pre> <p>And my category base to </p> <pre><code>. </code></pre> <p>Which worked fine, until the client said he wants parent categories to appear in the header of the article, and the child categories to show in the footer of the articles on the home/index pages...</p> <p>I've set it up, but the problem is that my child categories links are now:</p> <pre><code>http://www.example.com/./parent_category/child_category </code></pre> <p>And when I click the child category, I get sent to the latest article.</p> <p>I've tried to add in my <code>.htaccess</code></p> <pre><code>RewriteRule ^category/(.+)$ http://www.example.com/$1 [R=301,L] </code></pre> <p>But this did nothing. </p> <p>Now all this works, when I remove the dot, but then my links look like:</p> <pre><code>http://www.example.com/category/parent_category/child_category </code></pre> <p>And client explicitly doesn't want <code>category/</code> in the link...</p> <p>Other than installing a plugin, what can I do? How to sort this? Can I have </p> <pre><code>http://www.example.com/parent_category/child_category </code></pre> <p>As my permalink, and if so how to achieve this?</p>
[ { "answer_id": 220790, "author": "CK MacLeod", "author_id": 35923, "author_profile": "https://wordpress.stackexchange.com/users/35923", "pm_score": 2, "selected": false, "text": "<p>The \".\" method was always an unlikely kludge. </p>\n\n<p>The <a href=\"https://wordpress.org/plugins/remove-category-url/\" rel=\"nofollow\">\"Remove Category URL\" plug-in</a> works fine and, in my experience, as advertised. I'm not sure about the basis of the aversion to installing a plug-in for this purpose is, but, if you don't want to do so for some reason, you could always just examine it, and copy and pare down the technique employed by the plug-in developers, though the code, which relies on mastery of built-in rules, is not actually very complicated. The entirety of the main file is only 128 lines, and the core functionality resides in around 100 of them, covering four actions and four filters. </p>\n\n<p>If you don't want to install it as a plugin, I suppose you could just strip out the plug-in convenience and installation functions/files, and add the core functions to your theme functions file. I suspect that whatever method anyone else drafts here is likely just to re-invent the same wheel.</p>\n\n<pre><code>/**\n * Plugin Name: Remove Category URL\n * Plugin URI: http://valeriosouza.com.br/portfolio/remove-category-url/\n * Description: This plugin removes '/category' from your category permalinks. (e.g. `/category/my-category/` to `/my-category/`)\n * Version: 1.1\n * Author: Valerio Souza, WordLab Academy\n * Author URI: http://valeriosouza.com.br/\n */\n\n/* hooks */\nregister_activation_hook( __FILE__, 'remove_category_url_refresh_rules' );\nregister_deactivation_hook( __FILE__, 'remove_category_url_deactivate' );\n\n/* actions */\nadd_action( 'created_category', 'remove_category_url_refresh_rules' );\nadd_action( 'delete_category', 'remove_category_url_refresh_rules' );\nadd_action( 'edited_category', 'remove_category_url_refresh_rules' );\nadd_action( 'init', 'remove_category_url_permastruct' );\n\n/* filters */\nadd_filter( 'category_rewrite_rules', 'remove_category_url_rewrite_rules' );\nadd_filter( 'query_vars', 'remove_category_url_query_vars' ); // Adds 'category_redirect' query variable\nadd_filter( 'request', 'remove_category_url_request' ); // Redirects if 'category_redirect' is set\nadd_filter( 'plugin_row_meta', 'remove_category_url_plugin_row_meta', 10, 4 );\n\nfunction remove_category_url_refresh_rules() {\n global $wp_rewrite;\n $wp_rewrite-&gt;flush_rules();\n}\n\nfunction remove_category_url_deactivate() {\n remove_filter( 'category_rewrite_rules', 'remove_category_url_rewrite_rules' ); // We don't want to insert our custom rules again\n remove_category_url_refresh_rules();\n}\n\n/**\n * Removes category base.\n *\n * @return void\n */\nfunction remove_category_url_permastruct() {\n global $wp_rewrite, $wp_version;\n\n if ( 3.4 &lt;= $wp_version ) {\n $wp_rewrite-&gt;extra_permastructs['category']['struct'] = '%category%';\n } else {\n $wp_rewrite-&gt;extra_permastructs['category'][0] = '%category%';\n }\n}\n\n/**\n * Adds our custom category rewrite rules.\n *\n * @param array $category_rewrite Category rewrite rules.\n *\n * @return array\n */\nfunction remove_category_url_rewrite_rules( $category_rewrite ) {\n global $wp_rewrite;\n\n $category_rewrite = array();\n\n /* WPML is present: temporary disable terms_clauses filter to get all categories for rewrite */\n if ( class_exists( 'Sitepress' ) ) {\n global $sitepress;\n\n remove_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) );\n $categories = get_categories( array( 'hide_empty' =&gt; false, '_icl_show_all_langs' =&gt; true ) );\n add_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) );\n } else {\n $categories = get_categories( array( 'hide_empty' =&gt; false ) );\n }\n\n foreach ( $categories as $category ) {\n $category_nicename = $category-&gt;slug;\n if ( $category-&gt;parent == $category-&gt;cat_ID ) {\n $category-&gt;parent = 0;\n } elseif ( 0 != $category-&gt;parent ) {\n $category_nicename = get_category_parents( $category-&gt;parent, false, '/', true ) . $category_nicename;\n }\n $category_rewrite[ '(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$' ] = 'index.php?category_name=$matches[1]&amp;feed=$matches[2]';\n $category_rewrite[ '(' . $category_nicename . ')/page/?([0-9]{1,})/?$' ] = 'index.php?category_name=$matches[1]&amp;paged=$matches[2]';\n $category_rewrite[ '(' . $category_nicename . ')/?$' ] = 'index.php?category_name=$matches[1]';\n }\n\n // Redirect support from Old Category Base\n $old_category_base = get_option( 'category_base' ) ? get_option( 'category_base' ) : 'category';\n $old_category_base = trim( $old_category_base, '/' );\n $category_rewrite[ $old_category_base . '/(.*)$' ] = 'index.php?category_redirect=$matches[1]';\n\n return $category_rewrite;\n}\n\nfunction remove_category_url_query_vars( $public_query_vars ) {\n $public_query_vars[] = 'category_redirect';\n\n return $public_query_vars;\n}\n\n/**\n * Handles category redirects.\n *\n * @param $query_vars Current query vars.\n *\n * @return array $query_vars, or void if category_redirect is present.\n */\nfunction remove_category_url_request( $query_vars ) {\n if ( isset( $query_vars['category_redirect'] ) ) {\n $catlink = trailingslashit( get_option( 'home' ) ) . user_trailingslashit( $query_vars['category_redirect'], 'category' );\n status_header( 301 );\n header( \"Location: $catlink\" );\n exit;\n }\n\n return $query_vars;\n}\n\nfunction remove_category_url_plugin_row_meta( $links, $file ) {\n if( plugin_basename( __FILE__ ) === $file ) {\n $links[] = sprintf(\n '&lt;a target=\"_blank\" href=\"%s\"&gt;%s&lt;/a&gt;',\n esc_url('http://wordlab.com.br/donate/'),\n __( 'Donate', 'remove_category_url' )\n );\n }\n return $links;\n }\n</code></pre>\n" }, { "answer_id": 258943, "author": "YooWoo", "author_id": 114199, "author_profile": "https://wordpress.stackexchange.com/users/114199", "pm_score": 0, "selected": false, "text": "<p>Place this code within your functions.php and you're good to go (even with WordPress 4.7.2)</p>\n\n<pre><code>/* hooks */\nregister_activation_hook(__FILE__, 'yw_no_category_slug_refresh_rules');\nregister_deactivation_hook(__FILE__, 'yw_no_category_slug_deactivate');\n\n/* actions */\nadd_action('created_category', 'yw_no_category_slug_refresh_rules');\nadd_action('delete_category', 'yw_no_category_slug_refresh_rules');\nadd_action('edited_category', 'yw_no_category_slug_refresh_rules');\nadd_action('init', 'yw_no_category_slug_permastruct');\n\n/* filters */\nadd_filter('category_rewrite_rules', 'yw_no_category_slug_rewrite_rules');\nadd_filter('query_vars', 'yw_no_category_slug_query_vars'); // Adds 'category_redirect' query variable\nadd_filter('request', 'yw_no_category_slug_request'); // Redirects if 'category_redirect' is set\n\nfunction yw_no_category_slug_refresh_rules() {\n global $wp_rewrite;\n $wp_rewrite-&gt;flush_rules();\n}\n\nfunction yw_no_category_slug_deactivate() {\n remove_filter( 'category_rewrite_rules', 'yw_no_category_slug_rewrite_rules' ); // We don't want to insert our custom rules again\n yw_no_category_slug_refresh_rules();\n}\n\n/**\n * Removes category base.\n *\n * @return void\n */\nfunction yw_no_category_slug_permastruct()\n{\n global $wp_rewrite;\n global $wp_version;\n\n if ( $wp_version &gt;= 3.4 ) {\n $wp_rewrite-&gt;extra_permastructs['category']['struct'] = '%category%';\n } else {\n $wp_rewrite-&gt;extra_permastructs['category'][0] = '%category%';\n }\n}\n\n/**\n * Adds our custom category rewrite rules.\n *\n * @param array $category_rewrite Category rewrite rules.\n *\n * @return array\n */\nfunction yw_no_category_slug_rewrite_rules($category_rewrite) {\n global $wp_rewrite;\n $category_rewrite=array();\n\n /* WPML is present: temporary disable terms_clauses filter to get all categories for rewrite */\n if ( class_exists( 'Sitepress' ) ) {\n global $sitepress;\n\n remove_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) );\n $categories = get_categories( array( 'hide_empty' =&gt; false ) );\n //Fix provided by Albin here https://wordpress.org/support/topic/bug-with-wpml-2/#post-8362218\n //add_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) );\n add_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ), 10, 4 );\n } else {\n $categories = get_categories( array( 'hide_empty' =&gt; false ) );\n }\n\n foreach( $categories as $category ) {\n $category_nicename = $category-&gt;slug;\n\n if ( $category-&gt;parent == $category-&gt;cat_ID ) {\n $category-&gt;parent = 0;\n } elseif ( $category-&gt;parent != 0 ) {\n $category_nicename = get_category_parents( $category-&gt;parent, false, '/', true ) . $category_nicename;\n }\n\n $category_rewrite['('.$category_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&amp;feed=$matches[2]';\n $category_rewrite[\"({$category_nicename})/{$wp_rewrite-&gt;pagination_base}/?([0-9]{1,})/?$\"] = 'index.php?category_name=$matches[1]&amp;paged=$matches[2]';\n $category_rewrite['('.$category_nicename.')/?$'] = 'index.php?category_name=$matches[1]';\n }\n\n // Redirect support from Old Category Base\n $old_category_base = get_option( 'category_base' ) ? get_option( 'category_base' ) : 'category';\n $old_category_base = trim( $old_category_base, '/' );\n $category_rewrite[$old_category_base.'/(.*)$'] = 'index.php?category_redirect=$matches[1]';\n\n return $category_rewrite;\n}\n\nfunction yw_no_category_slug_query_vars($public_query_vars) {\n $public_query_vars[] = 'category_redirect';\n return $public_query_vars;\n}\n\n/**\n * Handles category redirects.\n *\n * @param $query_vars Current query vars.\n *\n * @return array $query_vars, or void if category_redirect is present.\n */\nfunction yw_no_category_slug_request($query_vars) {\n if( isset( $query_vars['category_redirect'] ) ) {\n $catlink = trailingslashit( get_option( 'home' ) ) . user_trailingslashit( $query_vars['category_redirect'], 'category' );\n status_header( 301 );\n header( \"Location: $catlink\" );\n exit();\n }\n\n return $query_vars;\n}\n</code></pre>\n" } ]
2016/03/11
[ "https://wordpress.stackexchange.com/questions/220396", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58895/" ]
I am using the 'standard' trick for category removal in wordpress. In my permalinks I set the permalinks structure to ``` /%category%/%postname%/ ``` And my category base to ``` . ``` Which worked fine, until the client said he wants parent categories to appear in the header of the article, and the child categories to show in the footer of the articles on the home/index pages... I've set it up, but the problem is that my child categories links are now: ``` http://www.example.com/./parent_category/child_category ``` And when I click the child category, I get sent to the latest article. I've tried to add in my `.htaccess` ``` RewriteRule ^category/(.+)$ http://www.example.com/$1 [R=301,L] ``` But this did nothing. Now all this works, when I remove the dot, but then my links look like: ``` http://www.example.com/category/parent_category/child_category ``` And client explicitly doesn't want `category/` in the link... Other than installing a plugin, what can I do? How to sort this? Can I have ``` http://www.example.com/parent_category/child_category ``` As my permalink, and if so how to achieve this?
The "." method was always an unlikely kludge. The ["Remove Category URL" plug-in](https://wordpress.org/plugins/remove-category-url/) works fine and, in my experience, as advertised. I'm not sure about the basis of the aversion to installing a plug-in for this purpose is, but, if you don't want to do so for some reason, you could always just examine it, and copy and pare down the technique employed by the plug-in developers, though the code, which relies on mastery of built-in rules, is not actually very complicated. The entirety of the main file is only 128 lines, and the core functionality resides in around 100 of them, covering four actions and four filters. If you don't want to install it as a plugin, I suppose you could just strip out the plug-in convenience and installation functions/files, and add the core functions to your theme functions file. I suspect that whatever method anyone else drafts here is likely just to re-invent the same wheel. ``` /** * Plugin Name: Remove Category URL * Plugin URI: http://valeriosouza.com.br/portfolio/remove-category-url/ * Description: This plugin removes '/category' from your category permalinks. (e.g. `/category/my-category/` to `/my-category/`) * Version: 1.1 * Author: Valerio Souza, WordLab Academy * Author URI: http://valeriosouza.com.br/ */ /* hooks */ register_activation_hook( __FILE__, 'remove_category_url_refresh_rules' ); register_deactivation_hook( __FILE__, 'remove_category_url_deactivate' ); /* actions */ add_action( 'created_category', 'remove_category_url_refresh_rules' ); add_action( 'delete_category', 'remove_category_url_refresh_rules' ); add_action( 'edited_category', 'remove_category_url_refresh_rules' ); add_action( 'init', 'remove_category_url_permastruct' ); /* filters */ add_filter( 'category_rewrite_rules', 'remove_category_url_rewrite_rules' ); add_filter( 'query_vars', 'remove_category_url_query_vars' ); // Adds 'category_redirect' query variable add_filter( 'request', 'remove_category_url_request' ); // Redirects if 'category_redirect' is set add_filter( 'plugin_row_meta', 'remove_category_url_plugin_row_meta', 10, 4 ); function remove_category_url_refresh_rules() { global $wp_rewrite; $wp_rewrite->flush_rules(); } function remove_category_url_deactivate() { remove_filter( 'category_rewrite_rules', 'remove_category_url_rewrite_rules' ); // We don't want to insert our custom rules again remove_category_url_refresh_rules(); } /** * Removes category base. * * @return void */ function remove_category_url_permastruct() { global $wp_rewrite, $wp_version; if ( 3.4 <= $wp_version ) { $wp_rewrite->extra_permastructs['category']['struct'] = '%category%'; } else { $wp_rewrite->extra_permastructs['category'][0] = '%category%'; } } /** * Adds our custom category rewrite rules. * * @param array $category_rewrite Category rewrite rules. * * @return array */ function remove_category_url_rewrite_rules( $category_rewrite ) { global $wp_rewrite; $category_rewrite = array(); /* WPML is present: temporary disable terms_clauses filter to get all categories for rewrite */ if ( class_exists( 'Sitepress' ) ) { global $sitepress; remove_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) ); $categories = get_categories( array( 'hide_empty' => false, '_icl_show_all_langs' => true ) ); add_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) ); } else { $categories = get_categories( array( 'hide_empty' => false ) ); } foreach ( $categories as $category ) { $category_nicename = $category->slug; if ( $category->parent == $category->cat_ID ) { $category->parent = 0; } elseif ( 0 != $category->parent ) { $category_nicename = get_category_parents( $category->parent, false, '/', true ) . $category_nicename; } $category_rewrite[ '(' . $category_nicename . ')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$' ] = 'index.php?category_name=$matches[1]&feed=$matches[2]'; $category_rewrite[ '(' . $category_nicename . ')/page/?([0-9]{1,})/?$' ] = 'index.php?category_name=$matches[1]&paged=$matches[2]'; $category_rewrite[ '(' . $category_nicename . ')/?$' ] = 'index.php?category_name=$matches[1]'; } // Redirect support from Old Category Base $old_category_base = get_option( 'category_base' ) ? get_option( 'category_base' ) : 'category'; $old_category_base = trim( $old_category_base, '/' ); $category_rewrite[ $old_category_base . '/(.*)$' ] = 'index.php?category_redirect=$matches[1]'; return $category_rewrite; } function remove_category_url_query_vars( $public_query_vars ) { $public_query_vars[] = 'category_redirect'; return $public_query_vars; } /** * Handles category redirects. * * @param $query_vars Current query vars. * * @return array $query_vars, or void if category_redirect is present. */ function remove_category_url_request( $query_vars ) { if ( isset( $query_vars['category_redirect'] ) ) { $catlink = trailingslashit( get_option( 'home' ) ) . user_trailingslashit( $query_vars['category_redirect'], 'category' ); status_header( 301 ); header( "Location: $catlink" ); exit; } return $query_vars; } function remove_category_url_plugin_row_meta( $links, $file ) { if( plugin_basename( __FILE__ ) === $file ) { $links[] = sprintf( '<a target="_blank" href="%s">%s</a>', esc_url('http://wordlab.com.br/donate/'), __( 'Donate', 'remove_category_url' ) ); } return $links; } ```
220,421
<p>I was wondering if it's possible to set up user roles in a way that means that users in certain groups can ONLY edit posts that have a specific taxonomy assigned to them e.g:</p> <pre><code>Properties (Post Type) Taxonomy One Taxonomy Two Taxonomy Three User Roles Group One - Can only edit properties with 'Taxonomy One' assigned. Group Two - Can only edit properties with 'Taxonomy Two' assigned. Group Three - Can only edit properties with 'Taxonomy Three' assigned. </code></pre> <p>I'm using the <a href="https://wordpress.org/plugins/members/" rel="nofollow">Members plugin</a> for role management at the moment, and I'm using custom post types/taxonomies.</p> <p>From what I've seen so far it doesn't look as though you can restrict access to POSTS based on TAXONOMIES.</p> <p><strong>UPDATE</strong></p> <p>I've now got permissions working for post types using the following code:</p> <pre><code>register_post_type( 'properties', array( 'labels' =&gt; array( 'name' =&gt; __( 'Properties' ), 'singular_name' =&gt; __( 'Property' ) ), 'public' =&gt; true, 'capability_type' =&gt; 'property', 'map_meta_cap' =&gt; true, 'capabilities' =&gt; array( 'publish_posts' =&gt; 'publish_properties', // This allows a user to publish a property. 'edit_posts' =&gt; 'edit_properties', // Allows editing of the user’s own properties but does not grant publishing permission. 'edit_others_posts' =&gt; 'edit_others_properties', // Allows the user to edit everyone else’s properties but not publish. 'delete_posts' =&gt; 'delete_properties', // Grants the ability to delete properties written by that user but not others’ properties. 'delete_others_posts' =&gt; 'delete_others_properties', // Capability to edit properties written by other users. 'read_private_posts' =&gt; 'read_private_properties', // Allows users to read private properties. 'edit_post' =&gt; 'edit_property', // Meta capability assigned by WordPress. Do not give to any role. 'delete_post' =&gt; 'delete_property', // Meta capability assigned by WordPress. Do not give to any role. 'read_post' =&gt; 'read_property', // Meta capability assigned by WordPress. Do not give to any role. ) ) ); </code></pre> <p>A 'Properties' section has now appeared when editing roles in the 'Members' plugin which lets me restrict/allow access. Just need to figure out if this is do-able for each taxonomy now :)</p>
[ { "answer_id": 220424, "author": "Jarod Thornton", "author_id": 44017, "author_profile": "https://wordpress.stackexchange.com/users/44017", "pm_score": 0, "selected": false, "text": "<p>I actually dug up that plugin developers blog and this is what he offers as insight.</p>\n\n<blockquote>\n <p>Meta capabilities are capabilities a user is granted on a per-post basis. The three we’re dealing with here are:</p>\n</blockquote>\n\n<p><code>edit_post\ndelete_post\nread_post</code></p>\n\n<blockquote>\n <p>For regular blog posts, WordPress “maps” these to specific\n capabilities granted to user roles. For example, a user might be given\n the edit_post capability for post 100 if they are the post author or\n have the edit_others_posts capability.</p>\n \n <p>When using custom post types, this mapping doesn’t happen\n automatically if you’re setting up custom capabilities. We have to\n come up with our own solution.</p>\n \n <p>In this tutorial...</p>\n</blockquote>\n\n<p><a href=\"http://justintadlock.com/archives/2010/07/10/meta-capabilities-for-custom-post-types\" rel=\"nofollow\">http://justintadlock.com/archives/2010/07/10/meta-capabilities-for-custom-post-types</a></p>\n\n<p>*I can't comment yet so I posted as an answer.</p>\n" }, { "answer_id": 220437, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 1, "selected": false, "text": "<p>You might be able to use the filter <code>user_has_cap</code> which is used when checking for a particular capability (found in <code>/wp-includes/class-wp-user.php</code> in <code>has_cap</code>):</p>\n\n<pre><code> /**\n * Dynamically filter a user's capabilities.\n *\n * @since 2.0.0\n * @since 3.7.0 Added the user object.\n *\n * @param array $allcaps An array of all the user's capabilities.\n * @param array $caps Actual capabilities for meta capability.\n * @param array $args Optional parameters passed to has_cap(), typically object ID.\n * @param WP_User $user The user object.\n */\n $capabilities = apply_filters( 'user_has_cap', $this-&gt;allcaps, $caps, $args, $this );\n</code></pre>\n\n<p>So it would be something like:</p>\n\n<pre><code>add_filter('user_has_cap','check_post_taxonomy',10,4);\nfunction check_post_taxonomy($allcaps,$caps,$args,$user) {\n global $post; if (!isset($post)) {return $allcaps;}\n\n $group = get_user_meta($user-&gt;ID,'special_edit_group',true);\n $taxonomy = 'taxonomy_'.$group; // maybe set to a, b or c?\n $terms = get_the_terms($post-&gt;ID,$taxonomy);\n\n // if there are no terms, remove the user capability(s) for this check\n // you may have to experiment to remove all the ones you want to\n if (!$terms) {\n unset($allcaps['edit_properties']);\n }\n\n return $allcaps;\n}\n</code></pre>\n\n<p>I have done it this way because I realized the logic of the question is not quite right. If a post type has taxonomy A, B and C assigned to it, even if you set these capability filters for the role groups as you say, all three role groups would be able to edit anything in this post type anyway. In other words, there is no case where taxonomy A, B or C is \"not\" actually assigned.</p>\n\n<p>Instead, I think you are really meaning \"check whether this particular post has any terms assigned to it in taxonomy A\"... and if so along group A to edit it, and so on. (Note: I have no idea if the above code will actually work for this case, it might need some more work. For example, currently this is checking for a user meta key for the group rather than an actual role/group.)</p>\n" } ]
2016/03/11
[ "https://wordpress.stackexchange.com/questions/220421", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78497/" ]
I was wondering if it's possible to set up user roles in a way that means that users in certain groups can ONLY edit posts that have a specific taxonomy assigned to them e.g: ``` Properties (Post Type) Taxonomy One Taxonomy Two Taxonomy Three User Roles Group One - Can only edit properties with 'Taxonomy One' assigned. Group Two - Can only edit properties with 'Taxonomy Two' assigned. Group Three - Can only edit properties with 'Taxonomy Three' assigned. ``` I'm using the [Members plugin](https://wordpress.org/plugins/members/) for role management at the moment, and I'm using custom post types/taxonomies. From what I've seen so far it doesn't look as though you can restrict access to POSTS based on TAXONOMIES. **UPDATE** I've now got permissions working for post types using the following code: ``` register_post_type( 'properties', array( 'labels' => array( 'name' => __( 'Properties' ), 'singular_name' => __( 'Property' ) ), 'public' => true, 'capability_type' => 'property', 'map_meta_cap' => true, 'capabilities' => array( 'publish_posts' => 'publish_properties', // This allows a user to publish a property. 'edit_posts' => 'edit_properties', // Allows editing of the user’s own properties but does not grant publishing permission. 'edit_others_posts' => 'edit_others_properties', // Allows the user to edit everyone else’s properties but not publish. 'delete_posts' => 'delete_properties', // Grants the ability to delete properties written by that user but not others’ properties. 'delete_others_posts' => 'delete_others_properties', // Capability to edit properties written by other users. 'read_private_posts' => 'read_private_properties', // Allows users to read private properties. 'edit_post' => 'edit_property', // Meta capability assigned by WordPress. Do not give to any role. 'delete_post' => 'delete_property', // Meta capability assigned by WordPress. Do not give to any role. 'read_post' => 'read_property', // Meta capability assigned by WordPress. Do not give to any role. ) ) ); ``` A 'Properties' section has now appeared when editing roles in the 'Members' plugin which lets me restrict/allow access. Just need to figure out if this is do-able for each taxonomy now :)
You might be able to use the filter `user_has_cap` which is used when checking for a particular capability (found in `/wp-includes/class-wp-user.php` in `has_cap`): ``` /** * Dynamically filter a user's capabilities. * * @since 2.0.0 * @since 3.7.0 Added the user object. * * @param array $allcaps An array of all the user's capabilities. * @param array $caps Actual capabilities for meta capability. * @param array $args Optional parameters passed to has_cap(), typically object ID. * @param WP_User $user The user object. */ $capabilities = apply_filters( 'user_has_cap', $this->allcaps, $caps, $args, $this ); ``` So it would be something like: ``` add_filter('user_has_cap','check_post_taxonomy',10,4); function check_post_taxonomy($allcaps,$caps,$args,$user) { global $post; if (!isset($post)) {return $allcaps;} $group = get_user_meta($user->ID,'special_edit_group',true); $taxonomy = 'taxonomy_'.$group; // maybe set to a, b or c? $terms = get_the_terms($post->ID,$taxonomy); // if there are no terms, remove the user capability(s) for this check // you may have to experiment to remove all the ones you want to if (!$terms) { unset($allcaps['edit_properties']); } return $allcaps; } ``` I have done it this way because I realized the logic of the question is not quite right. If a post type has taxonomy A, B and C assigned to it, even if you set these capability filters for the role groups as you say, all three role groups would be able to edit anything in this post type anyway. In other words, there is no case where taxonomy A, B or C is "not" actually assigned. Instead, I think you are really meaning "check whether this particular post has any terms assigned to it in taxonomy A"... and if so along group A to edit it, and so on. (Note: I have no idea if the above code will actually work for this case, it might need some more work. For example, currently this is checking for a user meta key for the group rather than an actual role/group.)
220,435
<p>How can I add the words "Posted on" before the post data in a Twentyfourteen theme's post? The default is only to show the date and clock icon.</p> <p>I'm not sure if this is a basic modification or if it's going to be a fix unique to Twentyfourteen.</p> <p>I found <a href="https://premium.wpmudev.org/blog/remove-date-from-wordpress-posts/" rel="nofollow">this web page</a> talking about <em>removing</em> the "posted on" text in the Twentyeleven theme (I hoped the themes would be similar). It said to look in the functions.php file for <code>function twentyeleven_posted_on()</code> but I was unable to find anything like that in the Twentyfourteen parent theme's functions.php file. There didn't seem to be anything directly relating to a post's date in the Twentyfourteen functions.php file.</p> <p>I am using a child theme, so I assume I'm probably going to be putting an altered function in my child theme's functions.php file, but I can't find the original function in Twentfourteen.</p> <p>The reason I ask is because Twentyfourteen default of only having the date has confused some of my readers; when the post is talking about an event they think the post date is the date of the event.</p> <h2>Solution (Thanks to Tom Woodward and Dave Clements)</h2> <p>Both Tom's and Dave's functions worked, but neither of them did at first because I was placing the new function below the <code>?&gt;</code> which is the ending tag for PHP and no code would work below it.</p> <p>This was my existing child theme's functions.php file (just basically copied from the <a href="https://codex.wordpress.org/Child_Themes" rel="nofollow">Wordpress support guide on setting up a child theme</a>)</p> <pre><code>&lt;?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } ?&gt; </code></pre> <p>I needed to add the new function in between the last <code>}</code> and the bottom <code>?&gt;</code></p> <pre><code>&lt;?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } function add_publish_dates( $the_date, $d, $post ) { if ( is_int( $post) ) { $post_id = $post; } else { $post_id = $post-&gt;ID; } return 'Posted on '. date( 'Y-d-m - h:j:s', strtotime( $the_date ) ); } add_action( 'get_the_date', 'add_publish_dates', 10, 3 ); ?&gt; </code></pre> <p>I eventually ended up using Tom Woodward's code because it placed the little clock icon before the "Posted on" whereas Dave Clement's put it after "Posted on" in between it and the date, which looked odd.</p> <p>Then I changed the date formatting for the date after <code>return 'Posted on '. date</code> from <code>'Y-d-m - h:j:s'</code> (which displayed the date as 2016-16-03 - 12:00:00 [which oddly ALWAYS said it was posted at 12am, when the posts were not]) to <code>'F j, Y'</code> (Which displays the default "March 16, 2016")</p> <pre><code>&lt;?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } function add_publish_dates( $the_date, $d, $post ) { if ( is_int( $post) ) { $post_id = $post; } else { $post_id = $post-&gt;ID; } return 'Posted on '. date( 'F j, Y', strtotime( $the_date ) ); } add_action( 'get_the_date', 'add_publish_dates', 10, 3 ); ?&gt; </code></pre> <p>As I said, I ended up using Tom Woodward's code as a base, but Dave Clements code did exactly what I had asked (just not exactly what I wanted) and he solved the <code>?&gt;</code> problem for me, so I give Dave the point. But thank you so much to both Tom and Dave!</p>
[ { "answer_id": 220454, "author": "Tom Woodward", "author_id": 82797, "author_profile": "https://wordpress.stackexchange.com/users/82797", "pm_score": 0, "selected": false, "text": "<p>I took a look at the documentation <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/get_the_date\" rel=\"nofollow\">here</a> and this filter seems to work for 2014.</p>\n\n<pre><code>function add_publish_dates( $the_date, $d, $post ) {\nif ( is_int( $post) ) {\n $post_id = $post;\n} else {\n $post_id = $post-&gt;ID;\n}\n\nreturn 'Posted on '. date( 'Y-d-m - h:j:s', strtotime( $the_date ) );\n}\nadd_action( 'get_the_date', 'add_publish_dates', 10, 3 );\n</code></pre>\n" }, { "answer_id": 220457, "author": "Dave Clements", "author_id": 35918, "author_profile": "https://wordpress.stackexchange.com/users/35918", "pm_score": 2, "selected": true, "text": "<p>The post date is added by <code>twentyfourteen_posted_on</code> as shown in <a href=\"https://themes.trac.wordpress.org/browser/twentyfourteen/1.6/content.php#L34\" rel=\"nofollow\">content.php</a>. This function is in <a href=\"https://themes.trac.wordpress.org/browser/twentyfourteen/1.6/inc/template-tags.php#L101\" rel=\"nofollow\">/inc/template-tags.php</a> and is correctly wrapped in an <code>if ( ! function_exists( 'twentyfourteen_posted_on' ) )</code> conditional so you can declare the same function in your child theme and modify it to your heart's content.</p>\n\n<p>As such you could add a function like this to your theme's functions.php file and that should do the trick (note the addition of \"Posted on \" in the <code>printf</code> function:</p>\n\n<pre><code>function twentyfourteen_posted_on() {\n if ( is_sticky() &amp;&amp; is_home() &amp;&amp; ! is_paged() ) {\n echo '&lt;span class=\"featured-post\"&gt;' . __( 'Sticky', 'twentyfourteen' ) . '&lt;/span&gt;';\n }\n\n // Set up and print post meta information.\n printf( 'Posted on &lt;span class=\"entry-date\"&gt;&lt;a href=\"%1$s\" rel=\"bookmark\"&gt;&lt;time class=\"entry-date\" datetime=\"%2$s\"&gt;%3$s&lt;/time&gt;&lt;/a&gt;&lt;/span&gt; &lt;span class=\"byline\"&gt;&lt;span class=\"author vcard\"&gt;&lt;a class=\"url fn n\" href=\"%4$s\" rel=\"author\"&gt;%5$s&lt;/a&gt;&lt;/span&gt;&lt;/span&gt;',\n esc_url( get_permalink() ),\n esc_attr( get_the_date( 'c' ) ),\n esc_html( get_the_date() ),\n esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),\n get_the_author()\n );\n}\n</code></pre>\n" } ]
2016/03/11
[ "https://wordpress.stackexchange.com/questions/220435", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90408/" ]
How can I add the words "Posted on" before the post data in a Twentyfourteen theme's post? The default is only to show the date and clock icon. I'm not sure if this is a basic modification or if it's going to be a fix unique to Twentyfourteen. I found [this web page](https://premium.wpmudev.org/blog/remove-date-from-wordpress-posts/) talking about *removing* the "posted on" text in the Twentyeleven theme (I hoped the themes would be similar). It said to look in the functions.php file for `function twentyeleven_posted_on()` but I was unable to find anything like that in the Twentyfourteen parent theme's functions.php file. There didn't seem to be anything directly relating to a post's date in the Twentyfourteen functions.php file. I am using a child theme, so I assume I'm probably going to be putting an altered function in my child theme's functions.php file, but I can't find the original function in Twentfourteen. The reason I ask is because Twentyfourteen default of only having the date has confused some of my readers; when the post is talking about an event they think the post date is the date of the event. Solution (Thanks to Tom Woodward and Dave Clements) --------------------------------------------------- Both Tom's and Dave's functions worked, but neither of them did at first because I was placing the new function below the `?>` which is the ending tag for PHP and no code would work below it. This was my existing child theme's functions.php file (just basically copied from the [Wordpress support guide on setting up a child theme](https://codex.wordpress.org/Child_Themes)) ``` <?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } ?> ``` I needed to add the new function in between the last `}` and the bottom `?>` ``` <?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } function add_publish_dates( $the_date, $d, $post ) { if ( is_int( $post) ) { $post_id = $post; } else { $post_id = $post->ID; } return 'Posted on '. date( 'Y-d-m - h:j:s', strtotime( $the_date ) ); } add_action( 'get_the_date', 'add_publish_dates', 10, 3 ); ?> ``` I eventually ended up using Tom Woodward's code because it placed the little clock icon before the "Posted on" whereas Dave Clement's put it after "Posted on" in between it and the date, which looked odd. Then I changed the date formatting for the date after `return 'Posted on '. date` from `'Y-d-m - h:j:s'` (which displayed the date as 2016-16-03 - 12:00:00 [which oddly ALWAYS said it was posted at 12am, when the posts were not]) to `'F j, Y'` (Which displays the default "March 16, 2016") ``` <?php add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } function add_publish_dates( $the_date, $d, $post ) { if ( is_int( $post) ) { $post_id = $post; } else { $post_id = $post->ID; } return 'Posted on '. date( 'F j, Y', strtotime( $the_date ) ); } add_action( 'get_the_date', 'add_publish_dates', 10, 3 ); ?> ``` As I said, I ended up using Tom Woodward's code as a base, but Dave Clements code did exactly what I had asked (just not exactly what I wanted) and he solved the `?>` problem for me, so I give Dave the point. But thank you so much to both Tom and Dave!
The post date is added by `twentyfourteen_posted_on` as shown in [content.php](https://themes.trac.wordpress.org/browser/twentyfourteen/1.6/content.php#L34). This function is in [/inc/template-tags.php](https://themes.trac.wordpress.org/browser/twentyfourteen/1.6/inc/template-tags.php#L101) and is correctly wrapped in an `if ( ! function_exists( 'twentyfourteen_posted_on' ) )` conditional so you can declare the same function in your child theme and modify it to your heart's content. As such you could add a function like this to your theme's functions.php file and that should do the trick (note the addition of "Posted on " in the `printf` function: ``` function twentyfourteen_posted_on() { if ( is_sticky() && is_home() && ! is_paged() ) { echo '<span class="featured-post">' . __( 'Sticky', 'twentyfourteen' ) . '</span>'; } // Set up and print post meta information. printf( 'Posted on <span class="entry-date"><a href="%1$s" rel="bookmark"><time class="entry-date" datetime="%2$s">%3$s</time></a></span> <span class="byline"><span class="author vcard"><a class="url fn n" href="%4$s" rel="author">%5$s</a></span></span>', esc_url( get_permalink() ), esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ), esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ), get_the_author() ); } ```
220,471
<p>I'm working on getting the editor to look more like the front end by adding extra CSS to the TinyMCE rich text editor.</p> <p>WordPress adds <code>/wp-includes/js/tinymce/skins/lightgray/content.min.css</code> and <code>/wp-includes/js/tinymce/skins/wordpress/wp-content.css</code> by default.</p> <p>Is there an easy way to remove this?</p>
[ { "answer_id": 220472, "author": "Tim Malone", "author_id": 46066, "author_profile": "https://wordpress.stackexchange.com/users/46066", "pm_score": 2, "selected": false, "text": "<p>You should be able to remove these by hooking into the <code>mce_css</code> filter in your <code>functions.php</code> file:</p>\n\n<pre><code>add_filter(\"mce_css\", \"my_remove_mce_css\");\n\nfunction my_remove_mce_css($stylesheets){\n return \"\";\n}\n</code></pre>\n\n<p>I haven't tested this but it should work. You might want to <code>echo</code> out the value of <code>$stylesheets</code> before you return nothing just to see what else is coming through - it might be that you want to retain some of the stylesheets, in which case you could remove the ones you don't want with <code>str_replace</code>.</p>\n\n<p>You can read more about this filter at <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/mce_css\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Filter_Reference/mce_css</a></p>\n" }, { "answer_id": 220515, "author": "squarecandy", "author_id": 41488, "author_profile": "https://wordpress.stackexchange.com/users/41488", "pm_score": 3, "selected": true, "text": "<p>This is what I arrived at. This will remove just the custom wordpress css <code>/wp-includes/js/tinymce/skins/wordpress/wp-content.css</code>.</p>\n\n<pre><code>function squarecandy_tinymce_remove_mce_css($stylesheets)\n{\n $stylesheets = explode(',',$stylesheets);\n foreach ($stylesheets as $key =&gt; $sheet) {\n if (preg_match('/wp\\-includes/',$sheet)) {\n unset($stylesheets[$key]);\n }\n }\n $stylesheets = implode(',',$stylesheets);\n return $stylesheets;\n}\nadd_filter(\"mce_css\", \"squarecandy_tinymce_remove_mce_css\");\n</code></pre>\n\n<p>The other file loaded by default (<code>/wp-includes/js/tinymce/skins/lightgray/content.min.css</code>) is not part of the mce_css filter. There does not appear to be any way to remove this without breaking TinyMCE. But of the two css files, this one adds less default things that need to be overridden.</p>\n" }, { "answer_id": 286047, "author": "Takahashi Ei", "author_id": 59346, "author_profile": "https://wordpress.stackexchange.com/users/59346", "pm_score": 0, "selected": false, "text": "<p>To remove <code>/wp-includes/js/tinymce/skins/lightgray/content.min.css</code>, try this code in your <code>functions.php</code>.</p>\n\n<pre>\nadd_filter('tiny_mce_before_init', function($init){\n $init['init_instance_callback'] = 'function(){'\n . 'jQuery(\"#content_ifr\").contents().find(\"link[href*=\\'content.min.css\\']\").remove();'\n . '}';\n return $init;\n});\n</pre>\n\n<p>I don't know it's right way, but works well.</p>\n" } ]
2016/03/12
[ "https://wordpress.stackexchange.com/questions/220471", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/41488/" ]
I'm working on getting the editor to look more like the front end by adding extra CSS to the TinyMCE rich text editor. WordPress adds `/wp-includes/js/tinymce/skins/lightgray/content.min.css` and `/wp-includes/js/tinymce/skins/wordpress/wp-content.css` by default. Is there an easy way to remove this?
This is what I arrived at. This will remove just the custom wordpress css `/wp-includes/js/tinymce/skins/wordpress/wp-content.css`. ``` function squarecandy_tinymce_remove_mce_css($stylesheets) { $stylesheets = explode(',',$stylesheets); foreach ($stylesheets as $key => $sheet) { if (preg_match('/wp\-includes/',$sheet)) { unset($stylesheets[$key]); } } $stylesheets = implode(',',$stylesheets); return $stylesheets; } add_filter("mce_css", "squarecandy_tinymce_remove_mce_css"); ``` The other file loaded by default (`/wp-includes/js/tinymce/skins/lightgray/content.min.css`) is not part of the mce\_css filter. There does not appear to be any way to remove this without breaking TinyMCE. But of the two css files, this one adds less default things that need to be overridden.
220,473
<p>I need a way to change the themes "Live Preview" url within the Appearance->Themes page? I want the themes thumbnails to link to a demo site showcasing the theme and not open the customizer. I looked into the code some but I am not seeing much for a solution, but was wondering if someone else has a trick for this. Thanks</p>
[ { "answer_id": 220476, "author": "Tim Malone", "author_id": 46066, "author_profile": "https://wordpress.stackexchange.com/users/46066", "pm_score": 0, "selected": false, "text": "<p>Wordpress seems to call <code>wp_customize_url</code> to get the theme preview URL, and there's not much there in the way of filters that you can hook into (<a href=\"https://developer.wordpress.org/reference/functions/wp_customize_url/\" rel=\"nofollow\">https://developer.wordpress.org/reference/functions/wp_customize_url/</a>). You could potentially hook into the <code>admin_url</code> filter to make changes - but returning a different URL when <code>customize.php</code> is sent through will obviously affect every instance of the customizer, not just the Live Preview function. If this doesn't concern you, then this could be what you need:</p>\n\n<pre><code>add_filter(\"admin_url\", \"my_live_preview\", 10, 3);\nfunction my_live_preview($url, $path, $blog_id){\n if($path == \"customize.php\"){ $url = \"http://offsitethemepreviewurl.com\"; }\n return $url;\n}\n</code></pre>\n\n<p>This <code>$url</code> will then be appended by <code>?theme=name-of-theme</code> which would allow you to determine at that page what theme is being requested.</p>\n\n<p>This may or may not suit.</p>\n\n<p>If it doesn't, I think you're left with some front-end JavaScript to change the URL. You'll need to enqueue a JavaScript file in the admin using <code>admin_enqueue_scripts</code> (see <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"nofollow\">https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts</a> for help), then reference the Live Preview link:</p>\n\n<pre><code>jQuery(\".theme-browser .theme[aria-describedby*='twentysixteen'] .button.load-customize\")\n .attr(\"href\", \"http://offsitethemepreviewurl.com/\");\n</code></pre>\n\n<p>This should change the Load Preview link for the twentysixteen theme to <a href=\"http://offsitethemepreviewurl.com\" rel=\"nofollow\">http://offsitethemepreviewurl.com</a>.</p>\n\n<p>I haven't tested either of these solutions... but I think they'll work :)</p>\n" }, { "answer_id": 220497, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 1, "selected": false, "text": "<h2>External <em>Live Previews</em> For Themes</h2>\n\n<p>The <kbd>Live Preview</kbd> buttons, on the <code>/wp-admin/themes.php</code> page, are generated from the <em>tmpl-theme</em> micro template:</p>\n\n<pre><code>&lt;script id=\"tmpl-wpse\" type=\"text/template\"&gt;\n\n ...cut...\n\n &lt;div class=\"theme-actions\"&gt;\n\n &lt;# if ( data.active ) { #&gt;\n &lt;# if ( data.actions.customize ) { #&gt;\n &lt;a class=\"button button-primary customize load-customize hide-if-no-customize\" href=\"{{{ data.actions.customize }}}\"&gt;&lt;?php _e( 'Customize' ); ?&gt;&lt;/a&gt;\n &lt;# } #&gt;\n &lt;# } else { #&gt;\n &lt;a class=\"button button-secondary activate\" href=\"{{{ data.actions.activate }}}\"&gt;&lt;?php _e( 'Activate' ); ?&gt;&lt;/a&gt;\n &lt;a class=\"button button-primary load-customize hide-if-no-customize\" href=\"{{{ data.actions.customize }}}\"&gt;&lt;?php _e( 'Live Preview' ); ?&gt;&lt;/a&gt;\n &lt;# } #&gt;\n &lt;/div&gt;\n\n ...cut...\n\n &lt;/script&gt;\n</code></pre>\n\n<p>We can modify the <em>template data</em> via the <code>wp_prepare_themes_for_js</code> filter.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>/**\n * External Live Previews\n */\nadd_filter( 'wp_prepare_themes_for_js', function( $prepared_themes )\n{\n //--------------------------\n // Edit this to your needs:\n\n $externals = [ \n 'twentysixteen' =&gt; 'http://foo.tld/demo/twentysixteen/', \n 'twentyfifteen' =&gt; 'http://bar.tld/demo/twentyfifteen/' \n ];\n //--------------------------\n\n foreach( $externals as $slug =&gt; $url )\n {\n if( isset( $prepared_themes[$slug]['actions']['customize'] ) )\n $prepared_themes[$slug]['actions']['customize'] = $url;\n } \n\n return $prepared_themes;\n} );\n</code></pre>\n\n<p>But this will not work as expected, because of the <code>load-customize</code> class, that will trigger a click event and open up an <em>iframe</em> overlay with: </p>\n\n<pre><code>$('#wpbody').on( 'click', '.load-customize', function( event ) {\n event.preventDefault();\n\n // Store a reference to the link that opened the Customizer.\n Loader.link = $(this);\n // Load the theme.\n Loader.open( Loader.link.attr('href') );\n});\n</code></pre>\n\n<p>When we click on the <kbd>Live Preview</kbd> button, with an external url, it will trigger an error like:</p>\n\n<blockquote>\n <p>Uncaught SecurityError: Failed to execute '<code>pushState</code>' on 'History': A\n history state object with URL '<code>http://foo.tld/demo/twentysixteen/</code>'\n cannot be created in a document with origin '<code>http://example.tld</code>' and\n URL '<code>http://example.tld/wp-admin/themes.php</code>'.</p>\n</blockquote>\n\n<p>We could prevent this, by double clicking (not really a reliable option) or by removing the <code>load-customize</code> class for the external preview links. Here's one such hack:</p>\n\n<pre><code>/**\n * Remove the .load-customize class from buttons with external links\n */\nadd_action( 'admin_print_styles-themes.php', function()\n{ ?&gt;\n &lt;script&gt;\n jQuery(document).ready( function($) {\n $('.load-customize').each( function( index ){\n if( this.host !== window.location.host )\n $( this ).removeClass( 'load-customize' );\n } );\n });\n &lt;/script&gt; &lt;?php\n} );\n</code></pre>\n\n<p>where I got the <code>this.host</code> idea from @daved <a href=\"https://stackoverflow.com/a/18660968/2078474\">here</a>.</p>\n\n<p>Another more drastic approach would be to override the <code>tmpl-theme</code> template.</p>\n" }, { "answer_id": 232791, "author": "mj_azani", "author_id": 98670, "author_profile": "https://wordpress.stackexchange.com/users/98670", "pm_score": 0, "selected": false, "text": "<p>If you are in wp customizer, here is how you can change the current preview URL via Javascript:</p>\n\n<p>Try this one when you plan to change the current URL from controls panel: \n<code>wp.customize.previewer.previewUrl( url )</code></p>\n\n<p>or try this one while you intend to change the URL from preview frame:\n<code>wp.customize.preview.send( \"url\", url )</code></p>\n\n<hr>\n\n<p>Moreover, here is how to get the current preview URL from the controls panel:\n<code>wp.customize.previewer.previewUrl()</code></p>\n" } ]
2016/03/12
[ "https://wordpress.stackexchange.com/questions/220473", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/38434/" ]
I need a way to change the themes "Live Preview" url within the Appearance->Themes page? I want the themes thumbnails to link to a demo site showcasing the theme and not open the customizer. I looked into the code some but I am not seeing much for a solution, but was wondering if someone else has a trick for this. Thanks
External *Live Previews* For Themes ----------------------------------- The `Live Preview` buttons, on the `/wp-admin/themes.php` page, are generated from the *tmpl-theme* micro template: ``` <script id="tmpl-wpse" type="text/template"> ...cut... <div class="theme-actions"> <# if ( data.active ) { #> <# if ( data.actions.customize ) { #> <a class="button button-primary customize load-customize hide-if-no-customize" href="{{{ data.actions.customize }}}"><?php _e( 'Customize' ); ?></a> <# } #> <# } else { #> <a class="button button-secondary activate" href="{{{ data.actions.activate }}}"><?php _e( 'Activate' ); ?></a> <a class="button button-primary load-customize hide-if-no-customize" href="{{{ data.actions.customize }}}"><?php _e( 'Live Preview' ); ?></a> <# } #> </div> ...cut... </script> ``` We can modify the *template data* via the `wp_prepare_themes_for_js` filter. Here's an example: ``` /** * External Live Previews */ add_filter( 'wp_prepare_themes_for_js', function( $prepared_themes ) { //-------------------------- // Edit this to your needs: $externals = [ 'twentysixteen' => 'http://foo.tld/demo/twentysixteen/', 'twentyfifteen' => 'http://bar.tld/demo/twentyfifteen/' ]; //-------------------------- foreach( $externals as $slug => $url ) { if( isset( $prepared_themes[$slug]['actions']['customize'] ) ) $prepared_themes[$slug]['actions']['customize'] = $url; } return $prepared_themes; } ); ``` But this will not work as expected, because of the `load-customize` class, that will trigger a click event and open up an *iframe* overlay with: ``` $('#wpbody').on( 'click', '.load-customize', function( event ) { event.preventDefault(); // Store a reference to the link that opened the Customizer. Loader.link = $(this); // Load the theme. Loader.open( Loader.link.attr('href') ); }); ``` When we click on the `Live Preview` button, with an external url, it will trigger an error like: > > Uncaught SecurityError: Failed to execute '`pushState`' on 'History': A > history state object with URL '`http://foo.tld/demo/twentysixteen/`' > cannot be created in a document with origin '`http://example.tld`' and > URL '`http://example.tld/wp-admin/themes.php`'. > > > We could prevent this, by double clicking (not really a reliable option) or by removing the `load-customize` class for the external preview links. Here's one such hack: ``` /** * Remove the .load-customize class from buttons with external links */ add_action( 'admin_print_styles-themes.php', function() { ?> <script> jQuery(document).ready( function($) { $('.load-customize').each( function( index ){ if( this.host !== window.location.host ) $( this ).removeClass( 'load-customize' ); } ); }); </script> <?php } ); ``` where I got the `this.host` idea from @daved [here](https://stackoverflow.com/a/18660968/2078474). Another more drastic approach would be to override the `tmpl-theme` template.
220,479
<p>Permalinks are (finally) working for individual posts of the custom <code>yoga-event</code> type I've created.</p> <p>And archive works without URL rewriting: </p> <p><code>http://website.localhost/?post_type=yoga-event</code></p> <p>However <code>get_post_type_archive_link( 'yoga-event' )</code> returns false.</p> <p>This is the array I'm sending to <code>register_post_type</code>:</p> <pre><code>Array ( [labels] =&gt; Array ( [name] =&gt; Yoga Events [singular_name] =&gt; Yoga Event [menu_name] =&gt; Yoga Events [all_items] =&gt; Yoga Events [add_new] =&gt; Add New [add_new_item] =&gt; Add New Yoga Event [edit_item] =&gt; Edit Yoga Event [new_item] =&gt; New Yoga Event [view_item] =&gt; View Yoga Event [search_items] =&gt; Search Yoga Events [not_found] =&gt; No Yoga Events found [not_found_in_trash] =&gt; No Yoga Events found in Trash [parent_item_colon] =&gt; Parent Yoga Event: ) [public] =&gt; 1 [rewrite] =&gt; Array ( [slug] =&gt; yoga-event ) [has_arhchive] =&gt; 1 [menu_icon] =&gt; dashicons-book-alt ) </code></pre> <p>I can sort of make my own "archive" like this:</p> <pre><code>$type = 'yoga-event'; $args=array( 'post_type' =&gt; $type, 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'ignore_sticky_posts'=&gt; 1); $my_query = null; $my_query = new WP_Query($args); if( $my_query-&gt;have_posts() ) { while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; &lt;p&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt; &lt;/a&gt;&lt;/p&gt; &lt;?php endwhile; } // list of yoga-event items </code></pre> <p>But I'm guessing that the array that <code>register_post_type</code> is getting has some kind of misconfiguration.</p> <p>Any insights?</p> <p>PS:</p> <pre><code>//List Post Types foreach ( get_post_types( '', 'names' ) as $post_type ) { echo '&lt;p&gt;' . $post_type . '&lt;/p&gt;'; } </code></pre> <p>Returns <code>yoga-event</code> (among others).</p>
[ { "answer_id": 220502, "author": "frogg3862", "author_id": 83367, "author_profile": "https://wordpress.stackexchange.com/users/83367", "pm_score": 2, "selected": true, "text": "<p>Can I see your <code>register_post_type</code> line? Those are usually like: <code>register_post_type( 'some-post-type', $args );</code>.</p>\n\n<p>In this example, <code>some-post-type</code> would be the ID that you use in <code>get_post_type_archive_link( 'some-post-type' )</code>, not the rewrite slug <code>yoga-event</code>.</p>\n" }, { "answer_id": 220536, "author": "MikeiLL", "author_id": 48604, "author_profile": "https://wordpress.stackexchange.com/users/48604", "pm_score": 0, "selected": false, "text": "<p>There was a typo in the code above, which one of the community pointed out, but I'll add here that that final piece of the puzzle for me was this little bit of code (<a href=\"https://wordpress.stackexchange.com/questions/54357/has-archive-false-on-the-default-post-type\">also SO-based</a>) by which we can examine a CPT as WP understands (outputs) it:</p>\n\n<pre><code>$type = 'yoga-event';\n//let's look at our CPT: \n$type_obj = get_post_type_object($type);\nmz_pr($type_obj);\n\nfunction mz_pr($message) {\n echo \"&lt;pre&gt;\";\n print_r($message);\n echo \"&lt;/pre&gt;\";\n</code></pre>\n\n<p>Also this wonderful <a href=\"https://github.com/jjgrainger/wp-custom-post-type-class\" rel=\"nofollow noreferrer\">CPT Class</a> is being a great way to generate the CPT. (Note, though that I am currently adding <code>'has_archive' =&gt; True`` to the</code>register_post_types` array manually, as the method for adding it via an \"instance method\" didn't seem to be working.)</p>\n" } ]
2016/03/12
[ "https://wordpress.stackexchange.com/questions/220479", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48604/" ]
Permalinks are (finally) working for individual posts of the custom `yoga-event` type I've created. And archive works without URL rewriting: `http://website.localhost/?post_type=yoga-event` However `get_post_type_archive_link( 'yoga-event' )` returns false. This is the array I'm sending to `register_post_type`: ``` Array ( [labels] => Array ( [name] => Yoga Events [singular_name] => Yoga Event [menu_name] => Yoga Events [all_items] => Yoga Events [add_new] => Add New [add_new_item] => Add New Yoga Event [edit_item] => Edit Yoga Event [new_item] => New Yoga Event [view_item] => View Yoga Event [search_items] => Search Yoga Events [not_found] => No Yoga Events found [not_found_in_trash] => No Yoga Events found in Trash [parent_item_colon] => Parent Yoga Event: ) [public] => 1 [rewrite] => Array ( [slug] => yoga-event ) [has_arhchive] => 1 [menu_icon] => dashicons-book-alt ) ``` I can sort of make my own "archive" like this: ``` $type = 'yoga-event'; $args=array( 'post_type' => $type, 'post_status' => 'publish', 'posts_per_page' => -1, 'ignore_sticky_posts'=> 1); $my_query = null; $my_query = new WP_Query($args); if( $my_query->have_posts() ) { while ($my_query->have_posts()) : $my_query->the_post(); ?> <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?> </a></p> <?php endwhile; } // list of yoga-event items ``` But I'm guessing that the array that `register_post_type` is getting has some kind of misconfiguration. Any insights? PS: ``` //List Post Types foreach ( get_post_types( '', 'names' ) as $post_type ) { echo '<p>' . $post_type . '</p>'; } ``` Returns `yoga-event` (among others).
Can I see your `register_post_type` line? Those are usually like: `register_post_type( 'some-post-type', $args );`. In this example, `some-post-type` would be the ID that you use in `get_post_type_archive_link( 'some-post-type' )`, not the rewrite slug `yoga-event`.
220,483
<p>So, I have a few form fields like so:</p> <pre><code>&lt;input name='mainStageSatOrder[theband][theid]' type='hidden' class='band-id' value='' /&gt;"; &lt;input name='mainStageSatOrder[theband][theorder]' type='hidden' class='band-order' value='' /&gt;"; </code></pre> <p>As you can see, these form fields (of which there are more, these are just examples of both types) create a multi-dimensional array like so (I hope, please correct me if I'm wrong):</p> <pre><code>Array ( [mainStageSatOrder] =&gt; Array ( [theband] =&gt; Array ( [theid] =&gt; 1 [theorder] =&gt; 5 ) [theband] =&gt; Array ( [theid] =&gt; 2 [theorder] =&gt; 8 ) ) ) </code></pre> <p>I want these values to use the update_post_meta function to update the relevant fields when the page update is submitted. I know I can hook into the submit action post_submitbox_start action which I understand just fine. </p> <p>What I'm not sure on, is what the PHP might be once the submit button is clicked. What I want to happen is that when the submit button is clicked, the multidimensional array is looped through using a foreach loop and for each 'theband' sub-array, the two values are used in the update_post_meta function.</p> <pre><code>foreach(???) { update_post_meta( 1, 'theorder', '5' ); //where 1 and 5 are values passed from the MD array } </code></pre> <p>So, the process goes:</p> <p>1) User clicks publish/update button 2) All values from all fields are passed into the multidimensional array 3) The MD array is looped through and, using update_post_meta, the relavent data is updated 4) Confirm yes/no</p> <p>Thanks.</p>
[ { "answer_id": 220552, "author": "iantsch", "author_id": 90220, "author_profile": "https://wordpress.stackexchange.com/users/90220", "pm_score": 1, "selected": false, "text": "<p>You got a litte thinking problem with your MD array, it should look like that, otherwise you will overwrite data within your form:</p>\n\n<pre><code>[\"mainStageSatOrder\"]=&gt; array(2) {\n [0]=&gt; array(1) {\n [\"theband\"]=&gt; array(2) {\n [\"theid\"]=&gt; int(1)\n [\"theorder\"]=&gt; int(5)\n }\n }\n [1]=&gt; array(1) {\n [\"theband\"]=&gt; array(2) {\n [\"theid\"]=&gt; int(2)\n [\"theorder\"]=&gt; int(8)\n }\n }\n}\n</code></pre>\n\n<p>Now you got two options (I'd recommend option B, because you might not need the single meta data without the context)</p>\n\n<p><strong>Option A:</strong> Save your data in single meta fields. You will need the parent_key (<code>$key</code> or <code>'mainStageSatOrder'</code>), <code>$row_id</code> and field_id (<code>$sub_key</code> or <code>$key</code>) to get your data.</p>\n\n<pre><code>function save($post_id) {\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE )\n return;\n if ( !current_user_can( 'edit_post', $post_id ) || !array_key_exists('mainStageSatOrder', $_POST) )\n return;\n foreach ($_POST['mainStageSatOrder'] as $row_id =&gt; $rows) {\n foreach ($rows as $key =&gt; $value) {\n if (is_array($value)) {\n foreach ($value as $sub_key =&gt; $sub_value) {\n $meta_key = '_'.$key.'_'.$row_id.'_'.$sub_key;\n update_post_meta($post_id, $meta_key, $sub_value);\n }\n } else {\n $meta_key = \"_mainStageSatOrder_\".$row_id.\"_\".$key;\n update_post_meta($post_id, $meta_key, $value);\n }\n }\n }\n update_post_meta($post_id, '_mainStageSatOrder', array_keys($_POST['mainStageSatOrder']));\n}\n</code></pre>\n\n<p><strong>Option B:</strong> Save your data in a serialized array (WordPress handles the serialization). To access and do stuff with the array again, just <code>unserialize()</code> the meta_value.</p>\n\n<pre><code>function save_array($post_id) {\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE )\n return;\n if ( !current_user_can( 'edit_post', $post_id ) || !array_key_exists('mainStageSatOrder', $_POST) )\n return;\n update_post_meta($post_id, '_mainStageSatOrder', $_POST['mainStageSatOrder']);\n}\n</code></pre>\n\n<p>Somewhere in your PHP code:</p>\n\n<pre><code>$mainStageSatOrder = unserialize(\n get_post_meta(\n get_the_ID(), \n '_mainStageSatOrder', \n true\n )\n);\n</code></pre>\n" }, { "answer_id": 268279, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 2, "selected": false, "text": "<p>First off, there's a problem with your array. Arrays can not have duplicate keys. So, only the first key will be saved. You need to change your form to something like this. </p>\n\n<pre><code>&lt;input name='mainStageSatOrder[theband0][theid]' type='hidden' class='band-id' value='' /&gt;\";\n&lt;input name='mainStageSatOrder[theband0][theorder]' type='hidden' class='band-order' value='' /&gt;\";\n&lt;input name='mainStageSatOrder[theband1][theid]' type='hidden' class='band-id' value='' /&gt;\";\n&lt;input name='mainStageSatOrder[theband1][theorder]' type='hidden' class='band-order' value='' /&gt;\";\n</code></pre>\n\n<p>The array will look like this </p>\n\n<pre><code>$array = array(\n 'mainStageSatOrder' =&gt; array(\n 'theband0' =&gt; array(\n 'theid' =&gt; 1,\n 'theorder' =&gt; 5\n ),\n 'theband1' =&gt; array(\n 'theid' =&gt; 2,\n 'theorder' =&gt; 8\n )\n )\n);\n</code></pre>\n\n<p>You don't need a foreach loop while saving the meta data. You can instead save it as an array. WordPress will automatically serialize it for you.</p>\n\n<pre><code>$array = $_POST['mainStageSatOrder'];\nupdate_post_meta( $postid, 'mainStageSatOrder', $array ); \n</code></pre>\n\n<p>And, while retriving the values.. </p>\n\n<pre><code>$data = get_post_meta($post-&gt;ID, 'mainStageSatOrder', true); \n</code></pre>\n\n<p>The returned <code>$data</code> will be an array.</p>\n" } ]
2016/03/12
[ "https://wordpress.stackexchange.com/questions/220483", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35299/" ]
So, I have a few form fields like so: ``` <input name='mainStageSatOrder[theband][theid]' type='hidden' class='band-id' value='' />"; <input name='mainStageSatOrder[theband][theorder]' type='hidden' class='band-order' value='' />"; ``` As you can see, these form fields (of which there are more, these are just examples of both types) create a multi-dimensional array like so (I hope, please correct me if I'm wrong): ``` Array ( [mainStageSatOrder] => Array ( [theband] => Array ( [theid] => 1 [theorder] => 5 ) [theband] => Array ( [theid] => 2 [theorder] => 8 ) ) ) ``` I want these values to use the update\_post\_meta function to update the relevant fields when the page update is submitted. I know I can hook into the submit action post\_submitbox\_start action which I understand just fine. What I'm not sure on, is what the PHP might be once the submit button is clicked. What I want to happen is that when the submit button is clicked, the multidimensional array is looped through using a foreach loop and for each 'theband' sub-array, the two values are used in the update\_post\_meta function. ``` foreach(???) { update_post_meta( 1, 'theorder', '5' ); //where 1 and 5 are values passed from the MD array } ``` So, the process goes: 1) User clicks publish/update button 2) All values from all fields are passed into the multidimensional array 3) The MD array is looped through and, using update\_post\_meta, the relavent data is updated 4) Confirm yes/no Thanks.
First off, there's a problem with your array. Arrays can not have duplicate keys. So, only the first key will be saved. You need to change your form to something like this. ``` <input name='mainStageSatOrder[theband0][theid]' type='hidden' class='band-id' value='' />"; <input name='mainStageSatOrder[theband0][theorder]' type='hidden' class='band-order' value='' />"; <input name='mainStageSatOrder[theband1][theid]' type='hidden' class='band-id' value='' />"; <input name='mainStageSatOrder[theband1][theorder]' type='hidden' class='band-order' value='' />"; ``` The array will look like this ``` $array = array( 'mainStageSatOrder' => array( 'theband0' => array( 'theid' => 1, 'theorder' => 5 ), 'theband1' => array( 'theid' => 2, 'theorder' => 8 ) ) ); ``` You don't need a foreach loop while saving the meta data. You can instead save it as an array. WordPress will automatically serialize it for you. ``` $array = $_POST['mainStageSatOrder']; update_post_meta( $postid, 'mainStageSatOrder', $array ); ``` And, while retriving the values.. ``` $data = get_post_meta($post->ID, 'mainStageSatOrder', true); ``` The returned `$data` will be an array.
220,508
<p>This is My Category List :</p> <p>1- Years 2- Genere</p> <p>And I use This Code For show in posts :</p> <pre><code>&lt;?php the_category(' , ') ?&gt; </code></pre> <p>How Can Hide "Year or Genere" in up code?</p> <p>Please Help Me.i want Show Only One Category.</p>
[ { "answer_id": 220552, "author": "iantsch", "author_id": 90220, "author_profile": "https://wordpress.stackexchange.com/users/90220", "pm_score": 1, "selected": false, "text": "<p>You got a litte thinking problem with your MD array, it should look like that, otherwise you will overwrite data within your form:</p>\n\n<pre><code>[\"mainStageSatOrder\"]=&gt; array(2) {\n [0]=&gt; array(1) {\n [\"theband\"]=&gt; array(2) {\n [\"theid\"]=&gt; int(1)\n [\"theorder\"]=&gt; int(5)\n }\n }\n [1]=&gt; array(1) {\n [\"theband\"]=&gt; array(2) {\n [\"theid\"]=&gt; int(2)\n [\"theorder\"]=&gt; int(8)\n }\n }\n}\n</code></pre>\n\n<p>Now you got two options (I'd recommend option B, because you might not need the single meta data without the context)</p>\n\n<p><strong>Option A:</strong> Save your data in single meta fields. You will need the parent_key (<code>$key</code> or <code>'mainStageSatOrder'</code>), <code>$row_id</code> and field_id (<code>$sub_key</code> or <code>$key</code>) to get your data.</p>\n\n<pre><code>function save($post_id) {\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE )\n return;\n if ( !current_user_can( 'edit_post', $post_id ) || !array_key_exists('mainStageSatOrder', $_POST) )\n return;\n foreach ($_POST['mainStageSatOrder'] as $row_id =&gt; $rows) {\n foreach ($rows as $key =&gt; $value) {\n if (is_array($value)) {\n foreach ($value as $sub_key =&gt; $sub_value) {\n $meta_key = '_'.$key.'_'.$row_id.'_'.$sub_key;\n update_post_meta($post_id, $meta_key, $sub_value);\n }\n } else {\n $meta_key = \"_mainStageSatOrder_\".$row_id.\"_\".$key;\n update_post_meta($post_id, $meta_key, $value);\n }\n }\n }\n update_post_meta($post_id, '_mainStageSatOrder', array_keys($_POST['mainStageSatOrder']));\n}\n</code></pre>\n\n<p><strong>Option B:</strong> Save your data in a serialized array (WordPress handles the serialization). To access and do stuff with the array again, just <code>unserialize()</code> the meta_value.</p>\n\n<pre><code>function save_array($post_id) {\n if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE )\n return;\n if ( !current_user_can( 'edit_post', $post_id ) || !array_key_exists('mainStageSatOrder', $_POST) )\n return;\n update_post_meta($post_id, '_mainStageSatOrder', $_POST['mainStageSatOrder']);\n}\n</code></pre>\n\n<p>Somewhere in your PHP code:</p>\n\n<pre><code>$mainStageSatOrder = unserialize(\n get_post_meta(\n get_the_ID(), \n '_mainStageSatOrder', \n true\n )\n);\n</code></pre>\n" }, { "answer_id": 268279, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 2, "selected": false, "text": "<p>First off, there's a problem with your array. Arrays can not have duplicate keys. So, only the first key will be saved. You need to change your form to something like this. </p>\n\n<pre><code>&lt;input name='mainStageSatOrder[theband0][theid]' type='hidden' class='band-id' value='' /&gt;\";\n&lt;input name='mainStageSatOrder[theband0][theorder]' type='hidden' class='band-order' value='' /&gt;\";\n&lt;input name='mainStageSatOrder[theband1][theid]' type='hidden' class='band-id' value='' /&gt;\";\n&lt;input name='mainStageSatOrder[theband1][theorder]' type='hidden' class='band-order' value='' /&gt;\";\n</code></pre>\n\n<p>The array will look like this </p>\n\n<pre><code>$array = array(\n 'mainStageSatOrder' =&gt; array(\n 'theband0' =&gt; array(\n 'theid' =&gt; 1,\n 'theorder' =&gt; 5\n ),\n 'theband1' =&gt; array(\n 'theid' =&gt; 2,\n 'theorder' =&gt; 8\n )\n )\n);\n</code></pre>\n\n<p>You don't need a foreach loop while saving the meta data. You can instead save it as an array. WordPress will automatically serialize it for you.</p>\n\n<pre><code>$array = $_POST['mainStageSatOrder'];\nupdate_post_meta( $postid, 'mainStageSatOrder', $array ); \n</code></pre>\n\n<p>And, while retriving the values.. </p>\n\n<pre><code>$data = get_post_meta($post-&gt;ID, 'mainStageSatOrder', true); \n</code></pre>\n\n<p>The returned <code>$data</code> will be an array.</p>\n" } ]
2016/03/12
[ "https://wordpress.stackexchange.com/questions/220508", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90454/" ]
This is My Category List : 1- Years 2- Genere And I use This Code For show in posts : ``` <?php the_category(' , ') ?> ``` How Can Hide "Year or Genere" in up code? Please Help Me.i want Show Only One Category.
First off, there's a problem with your array. Arrays can not have duplicate keys. So, only the first key will be saved. You need to change your form to something like this. ``` <input name='mainStageSatOrder[theband0][theid]' type='hidden' class='band-id' value='' />"; <input name='mainStageSatOrder[theband0][theorder]' type='hidden' class='band-order' value='' />"; <input name='mainStageSatOrder[theband1][theid]' type='hidden' class='band-id' value='' />"; <input name='mainStageSatOrder[theband1][theorder]' type='hidden' class='band-order' value='' />"; ``` The array will look like this ``` $array = array( 'mainStageSatOrder' => array( 'theband0' => array( 'theid' => 1, 'theorder' => 5 ), 'theband1' => array( 'theid' => 2, 'theorder' => 8 ) ) ); ``` You don't need a foreach loop while saving the meta data. You can instead save it as an array. WordPress will automatically serialize it for you. ``` $array = $_POST['mainStageSatOrder']; update_post_meta( $postid, 'mainStageSatOrder', $array ); ``` And, while retriving the values.. ``` $data = get_post_meta($post->ID, 'mainStageSatOrder', true); ``` The returned `$data` will be an array.
220,511
<p>I need to print all terms associated to a custom post type post. In the post template I wrote that code:</p> <pre><code>&lt;?php foreach (get_the_terms(the_ID(), 'taxonomy') as $cat) : ?&gt; &lt;?php echo $cat-&gt;name; ?&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>The loop works correctly, but before the list also the id was printed. Like:</p> <pre><code>37 taxonomy01 taxonomy02 taxonomy03 </code></pre> <p>What is wrong?</p>
[ { "answer_id": 220512, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 5, "selected": true, "text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/the_ID\" rel=\"noreferrer\"><code>the_ID()</code></a> print the post ID. You need to use the <a href=\"https://developer.wordpress.org/reference/functions/get_the_ID/\" rel=\"noreferrer\"><code>get_the_ID()</code></a> which return the post ID.</p>\n\n<p>Example:</p>\n\n<pre><code>foreach (get_the_terms(get_the_ID(), 'taxonomy') as $cat) {\n echo $cat-&gt;name;\n}\n</code></pre>\n\n<p>Always remember the naming convention of WordPress for template tags. <code>the</code> which mean to print <code>get</code> which mean to return in most of the cases.</p>\n" }, { "answer_id": 376573, "author": "Arif Rahman", "author_id": 150838, "author_profile": "https://wordpress.stackexchange.com/users/150838", "pm_score": 0, "selected": false, "text": "<p>Also you can declare a variable.</p>\n<pre><code>$taxonomy = get_the_terms( get_the_ID(), 'taxonomy' );\n\nforeach ( $taxonomy as $tax ) {\n echo esc_html( $tax-&gt;name ); \n}\n</code></pre>\n" } ]
2016/03/12
[ "https://wordpress.stackexchange.com/questions/220511", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90362/" ]
I need to print all terms associated to a custom post type post. In the post template I wrote that code: ``` <?php foreach (get_the_terms(the_ID(), 'taxonomy') as $cat) : ?> <?php echo $cat->name; ?> <?php endforeach; ?> ``` The loop works correctly, but before the list also the id was printed. Like: ``` 37 taxonomy01 taxonomy02 taxonomy03 ``` What is wrong?
[`the_ID()`](https://codex.wordpress.org/Function_Reference/the_ID) print the post ID. You need to use the [`get_the_ID()`](https://developer.wordpress.org/reference/functions/get_the_ID/) which return the post ID. Example: ``` foreach (get_the_terms(get_the_ID(), 'taxonomy') as $cat) { echo $cat->name; } ``` Always remember the naming convention of WordPress for template tags. `the` which mean to print `get` which mean to return in most of the cases.
220,549
<p>I want to add an inline word(s) after comments of post author's name. Suppose, my name is Tiger and i am the post author, so <strong>Post author</strong> will be printed after my name every time when i add a comment on the post.</p> <p><a href="https://i.stack.imgur.com/Ca7iP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ca7iP.png" alt="Like this picture"></a></p> <p>I don't want to edit comment.php file. I want custom functions for functions.php</p>
[ { "answer_id": 220553, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 0, "selected": false, "text": "<p>If I'm not getting it wrong, you are going to add some text to commenter's name if he is the post author, right?</p>\n\n<p>You need to hook into <code>get_comment_author</code>. Check either the post author is the commenter. If yes, then return your custom text, otherwise return original text.</p>\n\n<p>Use this code-</p>\n\n<pre><code>add_filter( 'get_comment_author', 'add_text_to_comment_author' );\nfunction add_text_to_comment_author( $author ){\n global $post;\n if( get_comment( get_comment_ID() )-&gt;user_id == $post-&gt;post_author ){\n return \"custom text here \" . $author;\n }\n return $author;\n}\n</code></pre>\n" }, { "answer_id": 220556, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>You can make use of the <a href=\"https://developer.wordpress.org/reference/hooks/get_comment_author/\" rel=\"nofollow\"><code>get_comment_author</code></a> filter to adjust the text displayed as comment author name according to your needs. All you need to do is to check who the post author is and then check that against the comment author. </p>\n\n<p>The complete comment object is passed by reference as third parameter to the filter, we can access that object to get the comment author which we can compare to the <code>post_author</code> of the post object</p>\n\n<pre><code>add_filter( 'get_comment_author', function ( $author, $comment_ID, $comment )\n{\n // Get the current post object\n $post = get_post();\n\n // Check if the comment author is the post author, if not, bail\n if ( $post-&gt;post_author !== $comment-&gt;user_id )\n return $author;\n\n // The user ids are the same, lets append our extra text\n $author = $author . ' Post author';\n\n return $author;\n}, 10, 3 );\n</code></pre>\n\n<p>You can adjust and add styling as needed</p>\n\n<h2>EDIT - from comments</h2>\n\n<p>As pointed out by @birgire, the <a href=\"https://developer.wordpress.org/reference/functions/get_comment_class/\" rel=\"nofollow\"><code>get_comment_class()</code></a> sets the <code>.bypostauthor</code> class for the post author comments. </p>\n\n<pre><code>// For comment authors who are the author of the post\nif ( $post = get_post($post_id) ) {\n if ( $comment-&gt;user_id === $post-&gt;post_author ) {\n $classes[] = 'bypostauthor';\n }\n}\n</code></pre>\n\n<p>We can also use this to check for comments by the post author. Just a not, it may not be very reliable as it can be overriden by themes or plugins</p>\n\n<pre><code>add_filter( 'get_comment_author', function ( $author )\n{\n if( !in_array( 'bypostauthor', get_comment_class() ) )\n return $author;\n\n // The user ids are the same, lets append our extra text\n $author = $author . ' Post author';\n\n return $author;\n});\n</code></pre>\n" }, { "answer_id": 220564, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Just wanted to mention some alternatives:</p>\n\n<h2>Alternative #1</h2>\n\n<p>You say you don't want to edit the <code>comments.php</code> file in the current theme directory. If we need to change how the <code>wp_list_comments()</code> works, we can always modify it through the <code>wp_list_comments_args</code> filter. For example to add our own callback:</p>\n\n<pre><code>add_filter( 'wp_list_comments_args', function( $r )\n{\n if( function_exists( 'wpse_comment_callback' ) )\n $r['callback'] = 'wpse_comment_callback';\n return $r;\n} );\n</code></pre>\n\n<p>where the <code>wpse_comment_callback()</code> callback contains the customization of your comment's layout. </p>\n\n<h2>Alternative #2</h2>\n\n<p>If we take a look at e.g. the <em>Twenty Sixteen</em> theme, we will see how the <code>.bypostauthor</code> class is used to mark the <em>post comment author</em> from the stylesheet:</p>\n\n<pre><code>.bypostauthor &gt; article .fn:after {\n content: \"\\f304\";\n left: 3px;\n position: relative;\n top: 5px;\n}\n</code></pre>\n\n<p>where you could adjust the content attribute to your needs. This might not be the workaround for you, if you need to style it or use words with translations.</p>\n" } ]
2016/03/13
[ "https://wordpress.stackexchange.com/questions/220549", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/75682/" ]
I want to add an inline word(s) after comments of post author's name. Suppose, my name is Tiger and i am the post author, so **Post author** will be printed after my name every time when i add a comment on the post. [![Like this picture](https://i.stack.imgur.com/Ca7iP.png)](https://i.stack.imgur.com/Ca7iP.png) I don't want to edit comment.php file. I want custom functions for functions.php
Just wanted to mention some alternatives: Alternative #1 -------------- You say you don't want to edit the `comments.php` file in the current theme directory. If we need to change how the `wp_list_comments()` works, we can always modify it through the `wp_list_comments_args` filter. For example to add our own callback: ``` add_filter( 'wp_list_comments_args', function( $r ) { if( function_exists( 'wpse_comment_callback' ) ) $r['callback'] = 'wpse_comment_callback'; return $r; } ); ``` where the `wpse_comment_callback()` callback contains the customization of your comment's layout. Alternative #2 -------------- If we take a look at e.g. the *Twenty Sixteen* theme, we will see how the `.bypostauthor` class is used to mark the *post comment author* from the stylesheet: ``` .bypostauthor > article .fn:after { content: "\f304"; left: 3px; position: relative; top: 5px; } ``` where you could adjust the content attribute to your needs. This might not be the workaround for you, if you need to style it or use words with translations.
220,572
<p>Using WordPress 4.4.2 (latest version as of writing this)</p> <p>I'm trying to use the [video] shortcode to show a video on my site. If I provide a url ending with the <code>filename.mp4</code> it works fine:</p> <p><code>[video src="http://example.com/filename.mp4"]</code></p> <p>but when I add a querystring parameter to the end of the URL, it refuses to show the video player. Instead, it just shows me a link to the URL:</p> <p><code>[video src="http://example.com/filename.mp4?type=0"]</code></p> <p>I've tried using the <code>mp4</code> attribute, and it produces the same result.</p> <p>How do I get the [video] shortcode to allow querystring parameters in the <code>src</code> or <code>mp4</code> attributes?</p>
[ { "answer_id": 220553, "author": "mukto90", "author_id": 57944, "author_profile": "https://wordpress.stackexchange.com/users/57944", "pm_score": 0, "selected": false, "text": "<p>If I'm not getting it wrong, you are going to add some text to commenter's name if he is the post author, right?</p>\n\n<p>You need to hook into <code>get_comment_author</code>. Check either the post author is the commenter. If yes, then return your custom text, otherwise return original text.</p>\n\n<p>Use this code-</p>\n\n<pre><code>add_filter( 'get_comment_author', 'add_text_to_comment_author' );\nfunction add_text_to_comment_author( $author ){\n global $post;\n if( get_comment( get_comment_ID() )-&gt;user_id == $post-&gt;post_author ){\n return \"custom text here \" . $author;\n }\n return $author;\n}\n</code></pre>\n" }, { "answer_id": 220556, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>You can make use of the <a href=\"https://developer.wordpress.org/reference/hooks/get_comment_author/\" rel=\"nofollow\"><code>get_comment_author</code></a> filter to adjust the text displayed as comment author name according to your needs. All you need to do is to check who the post author is and then check that against the comment author. </p>\n\n<p>The complete comment object is passed by reference as third parameter to the filter, we can access that object to get the comment author which we can compare to the <code>post_author</code> of the post object</p>\n\n<pre><code>add_filter( 'get_comment_author', function ( $author, $comment_ID, $comment )\n{\n // Get the current post object\n $post = get_post();\n\n // Check if the comment author is the post author, if not, bail\n if ( $post-&gt;post_author !== $comment-&gt;user_id )\n return $author;\n\n // The user ids are the same, lets append our extra text\n $author = $author . ' Post author';\n\n return $author;\n}, 10, 3 );\n</code></pre>\n\n<p>You can adjust and add styling as needed</p>\n\n<h2>EDIT - from comments</h2>\n\n<p>As pointed out by @birgire, the <a href=\"https://developer.wordpress.org/reference/functions/get_comment_class/\" rel=\"nofollow\"><code>get_comment_class()</code></a> sets the <code>.bypostauthor</code> class for the post author comments. </p>\n\n<pre><code>// For comment authors who are the author of the post\nif ( $post = get_post($post_id) ) {\n if ( $comment-&gt;user_id === $post-&gt;post_author ) {\n $classes[] = 'bypostauthor';\n }\n}\n</code></pre>\n\n<p>We can also use this to check for comments by the post author. Just a not, it may not be very reliable as it can be overriden by themes or plugins</p>\n\n<pre><code>add_filter( 'get_comment_author', function ( $author )\n{\n if( !in_array( 'bypostauthor', get_comment_class() ) )\n return $author;\n\n // The user ids are the same, lets append our extra text\n $author = $author . ' Post author';\n\n return $author;\n});\n</code></pre>\n" }, { "answer_id": 220564, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 3, "selected": true, "text": "<p>Just wanted to mention some alternatives:</p>\n\n<h2>Alternative #1</h2>\n\n<p>You say you don't want to edit the <code>comments.php</code> file in the current theme directory. If we need to change how the <code>wp_list_comments()</code> works, we can always modify it through the <code>wp_list_comments_args</code> filter. For example to add our own callback:</p>\n\n<pre><code>add_filter( 'wp_list_comments_args', function( $r )\n{\n if( function_exists( 'wpse_comment_callback' ) )\n $r['callback'] = 'wpse_comment_callback';\n return $r;\n} );\n</code></pre>\n\n<p>where the <code>wpse_comment_callback()</code> callback contains the customization of your comment's layout. </p>\n\n<h2>Alternative #2</h2>\n\n<p>If we take a look at e.g. the <em>Twenty Sixteen</em> theme, we will see how the <code>.bypostauthor</code> class is used to mark the <em>post comment author</em> from the stylesheet:</p>\n\n<pre><code>.bypostauthor &gt; article .fn:after {\n content: \"\\f304\";\n left: 3px;\n position: relative;\n top: 5px;\n}\n</code></pre>\n\n<p>where you could adjust the content attribute to your needs. This might not be the workaround for you, if you need to style it or use words with translations.</p>\n" } ]
2016/03/13
[ "https://wordpress.stackexchange.com/questions/220572", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44758/" ]
Using WordPress 4.4.2 (latest version as of writing this) I'm trying to use the [video] shortcode to show a video on my site. If I provide a url ending with the `filename.mp4` it works fine: `[video src="http://example.com/filename.mp4"]` but when I add a querystring parameter to the end of the URL, it refuses to show the video player. Instead, it just shows me a link to the URL: `[video src="http://example.com/filename.mp4?type=0"]` I've tried using the `mp4` attribute, and it produces the same result. How do I get the [video] shortcode to allow querystring parameters in the `src` or `mp4` attributes?
Just wanted to mention some alternatives: Alternative #1 -------------- You say you don't want to edit the `comments.php` file in the current theme directory. If we need to change how the `wp_list_comments()` works, we can always modify it through the `wp_list_comments_args` filter. For example to add our own callback: ``` add_filter( 'wp_list_comments_args', function( $r ) { if( function_exists( 'wpse_comment_callback' ) ) $r['callback'] = 'wpse_comment_callback'; return $r; } ); ``` where the `wpse_comment_callback()` callback contains the customization of your comment's layout. Alternative #2 -------------- If we take a look at e.g. the *Twenty Sixteen* theme, we will see how the `.bypostauthor` class is used to mark the *post comment author* from the stylesheet: ``` .bypostauthor > article .fn:after { content: "\f304"; left: 3px; position: relative; top: 5px; } ``` where you could adjust the content attribute to your needs. This might not be the workaround for you, if you need to style it or use words with translations.
220,581
<p>I have a main page and beyond that it has children. I successfully rewrite the children like so:</p> <pre><code>add_rewrite_rule('my-url/?([^/]*)', 'index.php?my-var=$matches[1]', 'top'); </code></pre> <p>This works great. But when I try to rewrite the base:</p> <pre><code>add_rewrite_rule('my-url/?', 'index.php?my-var=main', 'top'); </code></pre> <p>... it doesn't work. I know, it's getting rewritten by the first rule, so I switched them around, but then the children were all getting redirected to the main page.</p> <p>Is there a way to make the second rule strict so that it will only be effective if there is NOTHING after the "my-url/" ? This way I should be able to move it first, and all should work.</p> <p>I have searched the net and found no solution. Maybe it's my terms, but I'm racking myself on this one. I hate regex! Shoot me if it's simple!</p>
[ { "answer_id": 220583, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>This should work for both, slight adjustments to each regex pattern-</p>\n\n<pre><code>add_rewrite_rule('my-url/([^/]+)/?$', 'index.php?my-var=$matches[1]', 'top');\nadd_rewrite_rule('my-url/?$', 'index.php?my-var=main', 'top');\n</code></pre>\n" }, { "answer_id": 220584, "author": "iantsch", "author_id": 90220, "author_profile": "https://wordpress.stackexchange.com/users/90220", "pm_score": 1, "selected": true, "text": "<p>Change your rewrite rules and the order to the following:</p>\n\n<pre><code>add_rewrite_rule('my-url/([^/]*)/?$', 'index.php?my-var=$matches[1]', 'top');\nadd_rewrite_rule('my-url/?$', 'index.php?my-var=main', 'top');\n</code></pre>\n\n<p><strong>Why the order?</strong>\nIf the order would be the other way around, the first rule will always apply, so the ruleset would never reach your <em>main page</em></p>\n\n<p><strong>Why the changed syntax?</strong>\nTo allow an additional query string to be properly processed. E.g. <a href=\"http://foo.bar/my-url/?my-var=foo\" rel=\"nofollow\">http://foo.bar/my-url/?my-var=foo</a> and <a href=\"http://foo.bar/my-url/foo/?bar=1\" rel=\"nofollow\">http://foo.bar/my-url/foo/?bar=1</a> should be fetched to.</p>\n\n<p><strong>Additionally:</strong> A template redirect, if you want to apply your rewrite rules to query string requests like <a href=\"http://foo.bar/my-url/?my-var=foo\" rel=\"nofollow\">http://foo.bar/my-url/?my-var=foo</a>:</p>\n\n<pre><code>function custom_template_redirect(){\n preg_match('/(\\?|&amp;)my-var=/', $_SERVER['REQUEST_URI'], $matches);\n if (\n get_query_var( 'my-var', false ) !== false &amp;&amp;\n !empty($matches) &amp;&amp;\n !is_admin()\n ) {\n wp_redirect(\n home_url(\n '/my-url/'.(get_query_var( 'my-var' )?get_query_var( 'my-var' ).'/':'')\n )\n );\n exit();\n }\n}\n\nadd_action( 'template_redirect', 'custom_template_redirect' );\n</code></pre>\n" } ]
2016/03/13
[ "https://wordpress.stackexchange.com/questions/220581", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85669/" ]
I have a main page and beyond that it has children. I successfully rewrite the children like so: ``` add_rewrite_rule('my-url/?([^/]*)', 'index.php?my-var=$matches[1]', 'top'); ``` This works great. But when I try to rewrite the base: ``` add_rewrite_rule('my-url/?', 'index.php?my-var=main', 'top'); ``` ... it doesn't work. I know, it's getting rewritten by the first rule, so I switched them around, but then the children were all getting redirected to the main page. Is there a way to make the second rule strict so that it will only be effective if there is NOTHING after the "my-url/" ? This way I should be able to move it first, and all should work. I have searched the net and found no solution. Maybe it's my terms, but I'm racking myself on this one. I hate regex! Shoot me if it's simple!
Change your rewrite rules and the order to the following: ``` add_rewrite_rule('my-url/([^/]*)/?$', 'index.php?my-var=$matches[1]', 'top'); add_rewrite_rule('my-url/?$', 'index.php?my-var=main', 'top'); ``` **Why the order?** If the order would be the other way around, the first rule will always apply, so the ruleset would never reach your *main page* **Why the changed syntax?** To allow an additional query string to be properly processed. E.g. <http://foo.bar/my-url/?my-var=foo> and <http://foo.bar/my-url/foo/?bar=1> should be fetched to. **Additionally:** A template redirect, if you want to apply your rewrite rules to query string requests like <http://foo.bar/my-url/?my-var=foo>: ``` function custom_template_redirect(){ preg_match('/(\?|&)my-var=/', $_SERVER['REQUEST_URI'], $matches); if ( get_query_var( 'my-var', false ) !== false && !empty($matches) && !is_admin() ) { wp_redirect( home_url( '/my-url/'.(get_query_var( 'my-var' )?get_query_var( 'my-var' ).'/':'') ) ); exit(); } } add_action( 'template_redirect', 'custom_template_redirect' ); ```
220,587
<p>I am really clueless. I want to do an insertion in my WordPress plugin the problem is it doesn't return any errors nor it insert the stuff!</p> <p>I don't know how to fix this and really need your help. In the following code i used example names, but i used the character <code>-</code> for these in case of that my real table has also names with <code>-</code> in it as well as the table itself.</p> <p>Usually there is no problem, just use some back ticks `` and the stuff works well, but now welcome to WordPress. Is there a problem with the insertion function in WordPress or is there any other possible error?</p> <p>I really tried to fix this by myself but i failed.</p> <pre><code>$insertion = $wpdb-&gt;insert($wpdb-&gt;prefix.'table-name-of-plugin', array( 'column-name' =&gt; $stringValueForC1, 'second-column-name' =&gt; $stringValueForC2 ), array('%s, %s')); </code></pre> <p>If i use <code>var_dump()</code> for the insertion variable i get: <code>int(0)</code>. string <code>0</code> for <code>wpdb-&gt;last_error</code> and <code>bool(false)</code> for <code>wpdb-&gt;last_query</code>.</p> <p>I also double checked my table name and it is 100% correct! What can be the error?</p>
[ { "answer_id": 220615, "author": "Sumit", "author_id": 32475, "author_profile": "https://wordpress.stackexchange.com/users/32475", "pm_score": 0, "selected": false, "text": "<p>Issue exist in the data type format. You've passed <code>array('%s, %s')</code> take a closer look, instead of two values you've passed them as a single value, which leads to incorrect data type format.</p>\n\n<p>It should be <code>array('%s', '%s')</code></p>\n\n<p>So the final correct statement will look like this</p>\n\n<pre><code>$insertion = $wpdb-&gt;insert($wpdb-&gt;prefix . 'table-name-of-plugin', array(\n 'column-name' =&gt; $stringValueForC1,\n 'second-column-name' =&gt; $stringValueForC2\n ), array('%s', '%s')\n);\n</code></pre>\n" }, { "answer_id": 220626, "author": "donMhi.co", "author_id": 90541, "author_profile": "https://wordpress.stackexchange.com/users/90541", "pm_score": 2, "selected": true, "text": "<p>Your format is wrong.</p>\n\n<p>On your code is should be</p>\n\n<pre><code>$insertion = $wpdb-&gt;insert($wpdb-&gt;prefix . 'table-name-of-plugin', array(\n'column-name' =&gt; $stringValueForC1,\n'second-column-name' =&gt; $stringValueForC2\n ), array('%s', '%s') );\n</code></pre>\n\n<p>Notice the change from</p>\n\n<pre><code>array('%s, %s')\n</code></pre>\n\n<p>to</p>\n\n<pre><code>array('%s', '%s')\n</code></pre>\n\n<p>Also, since you are setting the format for both of the value as string. I recommend that you just use</p>\n\n<pre><code>'%s'\n</code></pre>\n\n<p>The format parameter accepts either array or string. If it's string, the string will be used as the format for all the values. Source - <a href=\"https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row\" rel=\"nofollow\">https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row</a></p>\n" } ]
2016/03/13
[ "https://wordpress.stackexchange.com/questions/220587", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90515/" ]
I am really clueless. I want to do an insertion in my WordPress plugin the problem is it doesn't return any errors nor it insert the stuff! I don't know how to fix this and really need your help. In the following code i used example names, but i used the character `-` for these in case of that my real table has also names with `-` in it as well as the table itself. Usually there is no problem, just use some back ticks `` and the stuff works well, but now welcome to WordPress. Is there a problem with the insertion function in WordPress or is there any other possible error? I really tried to fix this by myself but i failed. ``` $insertion = $wpdb->insert($wpdb->prefix.'table-name-of-plugin', array( 'column-name' => $stringValueForC1, 'second-column-name' => $stringValueForC2 ), array('%s, %s')); ``` If i use `var_dump()` for the insertion variable i get: `int(0)`. string `0` for `wpdb->last_error` and `bool(false)` for `wpdb->last_query`. I also double checked my table name and it is 100% correct! What can be the error?
Your format is wrong. On your code is should be ``` $insertion = $wpdb->insert($wpdb->prefix . 'table-name-of-plugin', array( 'column-name' => $stringValueForC1, 'second-column-name' => $stringValueForC2 ), array('%s', '%s') ); ``` Notice the change from ``` array('%s, %s') ``` to ``` array('%s', '%s') ``` Also, since you are setting the format for both of the value as string. I recommend that you just use ``` '%s' ``` The format parameter accepts either array or string. If it's string, the string will be used as the format for all the values. Source - <https://codex.wordpress.org/Class_Reference/wpdb#INSERT_row>
220,595
<p>I know that the style.css file needs to be copied to the child theme before being edited for changes. Is that also true for template.php files? If so, do I need to just copy the specific template file only, or should I copy all?</p> <p><strong>UPDATE:</strong></p> <p><em>includes/breadcrumbs.php:</em></p> <pre><code>&lt;?php if ( is_front_page() ) return; if ( class_exists( 'woocommerce' ) &amp;&amp; is_woocommerce() ) { woocommerce_breadcrumb(); return; } ?&gt; &lt;div id="breadcrumbs"&lt;?php if ( function_exists( 'bcn_display') ) echo ' class="bcn_breadcrumbs"'; ?&gt;&gt; &lt;?php if(function_exists('bcn_display')) { bcn_display(); } else { $et_breadcrumbs_content_open = true; ?&gt; &lt;span class="et_breadcrumbs_content"&gt; &lt;a href="&lt;?php echo esc_url( home_url() ); ?&gt;" class="breadcrumbs_home"&gt;&lt;?php esc_html_e('Home','Nexus' ... </code></pre>
[ { "answer_id": 220597, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": false, "text": "<p>You should only copy the files you intend to change, otherwise when the parent theme is updated, it will load the out of date files in the child theme that you didn't edit</p>\n\n<p>Think of it this way, any templates in the child theme override the parent theme. <code>style.css</code>, <code>functions.php</code> etc are not templates, and don't work this way</p>\n" }, { "answer_id": 220607, "author": "Ameen Khan", "author_id": 31179, "author_profile": "https://wordpress.stackexchange.com/users/31179", "pm_score": 1, "selected": false, "text": "<p>You have to copy that file in which you are willing to append and for example if a file resides in themes\\abc\\xyz\\thefile.php so you should have to create same path as in the parent theme. For example child-themes\\abc\\xyz\\thefile.php</p>\n\n<p>hope that answers the question.</p>\n" }, { "answer_id": 220611, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 3, "selected": true, "text": "<p>Generally, you do not need to copy the complete parent stylesheet to your child theme, you can just copy the particular code in question to your child theme's stylesheet and modify that. </p>\n\n<p>As for <code>functions.php</code> and any other functions related files, you cannot copy that to your child theme as this will lead to a cannot redeclare fatal error. There are a few write-ups on this, so be sure to use the site search for this.</p>\n\n<p>Templates files should always be modified in a child theme (<em>if you are not the parent theme's author</em>) as templates are theme territory. You only need to copy the affected templates. It should be noted, for page templates, you need to keep the same file structure as the parent theme. </p>\n\n<p>The real question is if whether or not you should copy a template and modify it. With the large amount of native filters and actions available to filter template tags, template parts, the loop itself, the posts array, nav menus, headers and footer, etc etc, it has became increasingly easy to change something via a custom plugin without having to directly alter template files itself. Changing these specifics via their respective filters and actions via a plugin have the added benefit of making these changes available across any theme used at any given time. It would be beneficial to sit down and decide what you would need to change and whether that change would be needed when you change themes before jumping in and copying a template file to a child theme to modify it. </p>\n\n<p>Some of the big commercial themes have added theme specific filters which you can use to filter certain things within a template. In most cases you can alter a template through just these filters, in which case you would use these filters in your child theme's functions file to alter the parent template's output accordingly. </p>\n\n<p>If your changes cannot be done through filters and actions, then yes, the correct way would be to copy that particular template to your child theme and modifying it there. The only drawback will then be that you would need to manually keep those templates updated</p>\n" } ]
2016/03/14
[ "https://wordpress.stackexchange.com/questions/220595", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89458/" ]
I know that the style.css file needs to be copied to the child theme before being edited for changes. Is that also true for template.php files? If so, do I need to just copy the specific template file only, or should I copy all? **UPDATE:** *includes/breadcrumbs.php:* ``` <?php if ( is_front_page() ) return; if ( class_exists( 'woocommerce' ) && is_woocommerce() ) { woocommerce_breadcrumb(); return; } ?> <div id="breadcrumbs"<?php if ( function_exists( 'bcn_display') ) echo ' class="bcn_breadcrumbs"'; ?>> <?php if(function_exists('bcn_display')) { bcn_display(); } else { $et_breadcrumbs_content_open = true; ?> <span class="et_breadcrumbs_content"> <a href="<?php echo esc_url( home_url() ); ?>" class="breadcrumbs_home"><?php esc_html_e('Home','Nexus' ... ```
Generally, you do not need to copy the complete parent stylesheet to your child theme, you can just copy the particular code in question to your child theme's stylesheet and modify that. As for `functions.php` and any other functions related files, you cannot copy that to your child theme as this will lead to a cannot redeclare fatal error. There are a few write-ups on this, so be sure to use the site search for this. Templates files should always be modified in a child theme (*if you are not the parent theme's author*) as templates are theme territory. You only need to copy the affected templates. It should be noted, for page templates, you need to keep the same file structure as the parent theme. The real question is if whether or not you should copy a template and modify it. With the large amount of native filters and actions available to filter template tags, template parts, the loop itself, the posts array, nav menus, headers and footer, etc etc, it has became increasingly easy to change something via a custom plugin without having to directly alter template files itself. Changing these specifics via their respective filters and actions via a plugin have the added benefit of making these changes available across any theme used at any given time. It would be beneficial to sit down and decide what you would need to change and whether that change would be needed when you change themes before jumping in and copying a template file to a child theme to modify it. Some of the big commercial themes have added theme specific filters which you can use to filter certain things within a template. In most cases you can alter a template through just these filters, in which case you would use these filters in your child theme's functions file to alter the parent template's output accordingly. If your changes cannot be done through filters and actions, then yes, the correct way would be to copy that particular template to your child theme and modifying it there. The only drawback will then be that you would need to manually keep those templates updated
220,619
<p>What is the difference between <code>$GLOBALS['wp_the_query']</code> and <code>global $wp_query</code>?</p> <p>Why prefer one over the other?</p>
[ { "answer_id": 220620, "author": "Jebble", "author_id": 81939, "author_profile": "https://wordpress.stackexchange.com/users/81939", "pm_score": 2, "selected": false, "text": "<p>The global keyword imports the variable into the local scope, while $GLOBALS just grants you access to the variable.</p>\n\n<p>To elaborate, if you use <code>global $wp_the_query;</code>\nyou can use <code>$wp_the_query</code> inside the local scope without using the word global again. So basically <code>global $wp_the_query</code> can be compared to <code>$wp_the_query = $GLOBALS['wp_the_query']</code></p>\n\n<p><strong>EDIT</strong></p>\n\n<p>I misread wp_query for wp_the_query so my answer isn't a complete answer to the question but still provides general information about the difference between <code>global $variable</code> and <code>$GLOBALS['variable']</code></p>\n" }, { "answer_id": 220621, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 2, "selected": false, "text": "<p>Basically one is copy of the other.</p>\n" }, { "answer_id": 220624, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 6, "selected": true, "text": "<p>You have missed one, <code>$GLOBALS['wp_query']</code>. For all purposes, <code>$GLOBALS['wp_query'] === $wp_query</code>. <code>$GLOBALS['wp_query']</code> is however better for readability and should be used instead of <code>$wp_query</code>, BUT, that remains personal preference</p>\n\n<p>Now, in a perfect world where unicorns rule the world, <code>$GLOBALS['wp_the_query'] === $GLOBALS['wp_query'] === $wp_query</code>. By default, this should be true. If we look at where these globals are set (<em><a href=\"https://github.com/WordPress/WordPress/blob/5.3.2/wp-settings.php#L407-L422\" rel=\"noreferrer\"><code>wp-settings.php</code></a></em>), you will see the main query object is stored in <code>$GLOBALS['wp_the_query']</code> and <code>$GLOBALS['wp_query']</code> is just a duplicate copy of <code>$GLOBALS['wp_the_query']</code></p>\n\n<pre><code>/**\n * WordPress Query object\n * @global WP_Query $wp_the_query\n * @since 2.0.0\n */\n$GLOBALS['wp_the_query'] = new WP_Query();\n/**\n * Holds the reference to @see $wp_the_query\n * Use this global for WordPress queries\n * @global WP_Query $wp_query\n * @since 1.5.0\n */\n$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];\n</code></pre>\n\n<p>The reason for doing it this way, is because WordPress saw the arrival of <a href=\"https://developer.wordpress.org/reference/functions/query_posts/\" rel=\"noreferrer\"><code>query_posts</code></a> in version 1.5.</p>\n\n<pre><code>function query_posts($query) {\n $GLOBALS['wp_query'] = new WP_Query();\n return $GLOBALS['wp_query']-&gt;query($query);\n}\n</code></pre>\n\n<p>As you can see, <code>query_posts</code> sets the main query object to the current custom query beign run. This breaks the integrity of the main query object, which gives you incorrect data, so anything that relies on the main query object is broken due to wrong data.</p>\n\n<p>A way to counter this was to create another global to store the main query object, <code>$GLOBALS['wp_the_query']</code> which was introduced in version 2.0.0. This new global hold the main query object and <code>$GLOBALS['wp_query']</code> just a copy. Through <code>wp_reset_query()</code>, we could now reset <code>$GLOBALS['wp_query']</code> back to the original main query object to restore its integrity.</p>\n\n<p>But this is not a perfect world, and <code>query_posts</code> are the devil himself. Although thousands of warnings, people still use <code>query_posts</code>. Apart from breaking the main query, it reruns the main query, making it much slower as a normal custom query with <code>WP_Query</code>. Many people also do not reset the <code>query_posts</code> query with <code>wp_reset_query()</code> when done, which makes <code>query_posts</code> even more evil. </p>\n\n<p>Because we cannot do anything about that, and cannot stop plugins and themes from using <code>query_posts</code> and we can never know if a <code>query_posts</code> query was reset with <code>wp_reset_query()</code>, we need a more reliable copy of the main query object which we know will give us 99.99999% reliable, correct data. That is where <code>$GLOBALS['wp_the_query']</code> is useful as no WordPress related code can change it's value (<em>except through the filters and actions inside <code>WP_Query</code> itself</em>). </p>\n\n<p>Quick proof, run the following</p>\n\n<pre><code>var_dump( $GLOBALS['wp_the_query'] );\nvar_dump( $GLOBALS['wp_query'] );\n\nquery_posts( 's=crap' );\n\n\nvar_dump( $GLOBALS['wp_the_query'] );\nvar_dump( $GLOBALS['wp_query'] );\n</code></pre>\n\n<p>and check the results. <code>$GLOBALS['wp_the_query']</code> did not change, and <code>$GLOBALS['wp_query']</code> has. So which is more reliable?</p>\n\n<p>Final note, <code>$GLOBALS['wp_the_query']</code> is <strong>NOT</strong> a replacement for <code>wp_reset_query()</code>. <code>wp_reset_query()</code> should <strong>always</strong> be used with <code>query_posts</code>, and <code>query_posts</code> should <strong>never</strong> be used. </p>\n\n<h2>TO CONCLUDE</h2>\n\n<p>If you need reliable code which will almost always never fail, use <code>$GLOBALS['wp_the_query']</code>, if you trust and believe plugins and theme code and believe no one uses <code>query_posts</code> or is using it correctly, use <code>$GLOBALS['wp_query']</code> or <code>$wp_query</code></p>\n\n<h2>IMPORTANT EDIT</h2>\n\n<p>Being answering questions on this site now for a couple of years, I saw many users using <code>$wp_query</code> as a local variable, which in turn also breaks the main query object. This further increases the vulnerabilty of the <code>$wp_query</code>.</p>\n\n<p>As example, some people to this</p>\n\n<pre><code>$wp_query = new WP_Query( $args );\n</code></pre>\n\n<p>which is in essence the exactly the same as what <code>query_posts</code> are doing</p>\n" } ]
2016/03/14
[ "https://wordpress.stackexchange.com/questions/220619", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/27196/" ]
What is the difference between `$GLOBALS['wp_the_query']` and `global $wp_query`? Why prefer one over the other?
You have missed one, `$GLOBALS['wp_query']`. For all purposes, `$GLOBALS['wp_query'] === $wp_query`. `$GLOBALS['wp_query']` is however better for readability and should be used instead of `$wp_query`, BUT, that remains personal preference Now, in a perfect world where unicorns rule the world, `$GLOBALS['wp_the_query'] === $GLOBALS['wp_query'] === $wp_query`. By default, this should be true. If we look at where these globals are set (*[`wp-settings.php`](https://github.com/WordPress/WordPress/blob/5.3.2/wp-settings.php#L407-L422)*), you will see the main query object is stored in `$GLOBALS['wp_the_query']` and `$GLOBALS['wp_query']` is just a duplicate copy of `$GLOBALS['wp_the_query']` ``` /** * WordPress Query object * @global WP_Query $wp_the_query * @since 2.0.0 */ $GLOBALS['wp_the_query'] = new WP_Query(); /** * Holds the reference to @see $wp_the_query * Use this global for WordPress queries * @global WP_Query $wp_query * @since 1.5.0 */ $GLOBALS['wp_query'] = $GLOBALS['wp_the_query']; ``` The reason for doing it this way, is because WordPress saw the arrival of [`query_posts`](https://developer.wordpress.org/reference/functions/query_posts/) in version 1.5. ``` function query_posts($query) { $GLOBALS['wp_query'] = new WP_Query(); return $GLOBALS['wp_query']->query($query); } ``` As you can see, `query_posts` sets the main query object to the current custom query beign run. This breaks the integrity of the main query object, which gives you incorrect data, so anything that relies on the main query object is broken due to wrong data. A way to counter this was to create another global to store the main query object, `$GLOBALS['wp_the_query']` which was introduced in version 2.0.0. This new global hold the main query object and `$GLOBALS['wp_query']` just a copy. Through `wp_reset_query()`, we could now reset `$GLOBALS['wp_query']` back to the original main query object to restore its integrity. But this is not a perfect world, and `query_posts` are the devil himself. Although thousands of warnings, people still use `query_posts`. Apart from breaking the main query, it reruns the main query, making it much slower as a normal custom query with `WP_Query`. Many people also do not reset the `query_posts` query with `wp_reset_query()` when done, which makes `query_posts` even more evil. Because we cannot do anything about that, and cannot stop plugins and themes from using `query_posts` and we can never know if a `query_posts` query was reset with `wp_reset_query()`, we need a more reliable copy of the main query object which we know will give us 99.99999% reliable, correct data. That is where `$GLOBALS['wp_the_query']` is useful as no WordPress related code can change it's value (*except through the filters and actions inside `WP_Query` itself*). Quick proof, run the following ``` var_dump( $GLOBALS['wp_the_query'] ); var_dump( $GLOBALS['wp_query'] ); query_posts( 's=crap' ); var_dump( $GLOBALS['wp_the_query'] ); var_dump( $GLOBALS['wp_query'] ); ``` and check the results. `$GLOBALS['wp_the_query']` did not change, and `$GLOBALS['wp_query']` has. So which is more reliable? Final note, `$GLOBALS['wp_the_query']` is **NOT** a replacement for `wp_reset_query()`. `wp_reset_query()` should **always** be used with `query_posts`, and `query_posts` should **never** be used. TO CONCLUDE ----------- If you need reliable code which will almost always never fail, use `$GLOBALS['wp_the_query']`, if you trust and believe plugins and theme code and believe no one uses `query_posts` or is using it correctly, use `$GLOBALS['wp_query']` or `$wp_query` IMPORTANT EDIT -------------- Being answering questions on this site now for a couple of years, I saw many users using `$wp_query` as a local variable, which in turn also breaks the main query object. This further increases the vulnerabilty of the `$wp_query`. As example, some people to this ``` $wp_query = new WP_Query( $args ); ``` which is in essence the exactly the same as what `query_posts` are doing
220,639
<p>When I switched to using a blank theme, the WordPress dashboard disappeared. </p> <p>To re-activate the previous theme I was using (which did have dashboard support), I reset the values of <em>template, stylesheet</em> and <em>current_theme</em> fields in the <em>wp_options</em> table to the previous theme (by manually entering the theme name). However, this failed to restore the dashboard. I did restart both the MySQL database and the Apache web server. I am using the Bitnami WAMP stack.</p> <p>How can I manually activate my previous theme without browser access to dashboard?</p>
[ { "answer_id": 220841, "author": "Monkey Puzzle", "author_id": 48568, "author_profile": "https://wordpress.stackexchange.com/users/48568", "pm_score": 0, "selected": false, "text": "<p>At the server, can you delete (or download and delete) the current non-working theme? The other one (if it's the only other one) should be activated as the next option. </p>\n\n<p>Otherwise download and delete all themes but use some theme (any theme!) that gives you dashboard access. </p>\n\n<p>Then upload a zipped version of your good downloaded theme as a new theme, and activate it. </p>\n" }, { "answer_id": 220843, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 1, "selected": false, "text": "<p>Are you sure that you've entered the correct name? For <code>template</code> you need to usually use the folder name (template name).</p>\n\n<pre><code>UPDATE wp_options SET option_value = 'twentysixteen' WHERE option_name = 'template';\nUPDATE wp_options SET option_value = 'twentysixteen' WHERE option_name = 'stylesheet';\nUPDATE wp_options SET option_value = 'twentysixteen' WHERE option_name = 'current_theme';\n</code></pre>\n" }, { "answer_id": 220849, "author": "Swopnil Dangol", "author_id": 90685, "author_profile": "https://wordpress.stackexchange.com/users/90685", "pm_score": 2, "selected": false, "text": "<p>In your current theme, you can use switch_theme('stylesheet') in the index.php of your theme folder.No need to make changes in the database :)</p>\n\n<pre><code>&lt;?php\n switch_theme('twentyfifteen');//Specify the name of stylesheet of intended theme\n exit;\n //Rest of the code\n?&gt;\n</code></pre>\n\n<p>You can remove the code after use</p>\n" } ]
2016/03/14
[ "https://wordpress.stackexchange.com/questions/220639", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89458/" ]
When I switched to using a blank theme, the WordPress dashboard disappeared. To re-activate the previous theme I was using (which did have dashboard support), I reset the values of *template, stylesheet* and *current\_theme* fields in the *wp\_options* table to the previous theme (by manually entering the theme name). However, this failed to restore the dashboard. I did restart both the MySQL database and the Apache web server. I am using the Bitnami WAMP stack. How can I manually activate my previous theme without browser access to dashboard?
In your current theme, you can use switch\_theme('stylesheet') in the index.php of your theme folder.No need to make changes in the database :) ``` <?php switch_theme('twentyfifteen');//Specify the name of stylesheet of intended theme exit; //Rest of the code ?> ``` You can remove the code after use
220,650
<p>I am adding an admin notice via the conventional <code>admin_notice</code> hook in my plugin:</p> <pre><code>function my_admin_notice() { ?&gt; &lt;div class="notice notice-info is-dismissible"&gt; &lt;p&gt;&lt;?php _e( 'some message', 'my-text-domain' ); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } if ( my_plugin_show_admin_notice() ) add_action( 'admin_notices', 'my_admin_notice' ); </code></pre> <p>How can I control where wordpress places the admin notice, in the html on the current screen, without using Javascript?</p>
[ { "answer_id": 220652, "author": "iantsch", "author_id": 90220, "author_profile": "https://wordpress.stackexchange.com/users/90220", "pm_score": 2, "selected": false, "text": "<p>According to the Codex <code>admin_notice</code> does the following:</p>\n\n<blockquote>\n <p>Notices displayed near the top of admin pages. The hook function\n should echo a message to be displayed.</p>\n</blockquote>\n\n<p>That means you cannot place them at the bottom or middle of your screen, if you use the hook. Furthermore if you place a div with the class notice anywhere in your admin pages, WP admin JS scripts will put them just where all the other notices would be; and they will behave like notices too.</p>\n\n<p>FYI: I tested this already with a fresh install. ;)</p>\n\n<h2>But</h2>\n\n<p>If you want to show a <code>admin_notice</code> at a particular page, you can add the action within a <code>current_screen</code> action:</p>\n\n<pre><code>function my_admin_notice() { ?&gt;\n &lt;div class=\"notice notice-info is-dismissible\"&gt;\n &lt;p&gt;&lt;?php _e( 'some message', 'my_textdomain' ); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n}\n\nfunction my_current_screen_example( $current_screen ) {\n // All your conditions go here, e.g. show notice @ post (not page) edit/new\n if ( 'post' == $current_screen-&gt;post_type &amp;&amp; 'post' == $current_screen-&gt;base ) {\n add_action( 'admin_notices', 'my_admin_notice' );\n }\n}\n\nadd_action( 'current_screen', 'my_current_screen_example' );\n</code></pre>\n\n<h2>More Information:</h2>\n\n<ul>\n<li>Action Hook: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_notices\" rel=\"nofollow\">admin_notices</a></li>\n<li>Action Hook: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/current_screen\" rel=\"nofollow\">current_screen</a></li>\n</ul>\n" }, { "answer_id": 220733, "author": "Rutwick Gangurde", "author_id": 4740, "author_profile": "https://wordpress.stackexchange.com/users/4740", "pm_score": 0, "selected": false, "text": "<p>The action <code>admin_notices</code> is called or applied <strong>only once</strong> in the file, <code>admin-header.php</code> on line number 238, just at the beginning of the <code>wpbody-content</code> div, which makes up the body of a dashboard page. Hence, there is no way you can change the position of the admin notice, without using JavaScript. However, you can definitely make your own <code>notice</code> divs at the positions or locations you want, and manipulate their visibility.</p>\n\n<p>Just create the mark up for the notice as:</p>\n\n<pre><code>&lt;div class=\"notice notice-info is-dismissible\"&gt;\n &lt;p&gt;This is a notice.&lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You can now control it's visibility using PHP. Meaning when you redirect a user to this page, or submit a form on this page, just set the message in the div, and using a simple if else, echo the div.</p>\n" }, { "answer_id": 220735, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 4, "selected": true, "text": "<p>I found out by accident recently that all the notices will be moved to after the first <code>&lt;h2&gt;</code> tag on the page inside a <code>&lt;div class=\"wrap\"&gt;</code>. This gives you some <em>slight</em> control in that, for example, on a plugin settings page you can put an empty <code>&lt;h2&gt;&lt;/h2&gt;</code> at the very top if you want to use <code>&lt;h2&gt;Plugin Title&lt;/h2&gt;</code> without it messing up the display formatting there.</p>\n" }, { "answer_id": 342200, "author": "NJENGAH", "author_id": 67761, "author_profile": "https://wordpress.stackexchange.com/users/67761", "pm_score": 1, "selected": false, "text": "<p>I had the same problem and I resolved it by ensuring all the heading tags above where I want to place the notice there is no <code>&lt;h2&gt;</code>.</p>\n\n<p>In this case, I wanted to display an error log notice below the input field as shown below : \n<a href=\"https://i.stack.imgur.com/7gizl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7gizl.png\" alt=\"enter image description here\"></a></p>\n\n<p>I solved it by introducing an empty <code>&lt;h2&gt;</code> tag just below the email input field and also change the tabs tag to <code>&lt;h3&gt;</code> instead of <code>&lt;h2&gt;</code> </p>\n" }, { "answer_id": 395849, "author": "Spartieee", "author_id": 212634, "author_profile": "https://wordpress.stackexchange.com/users/212634", "pm_score": 1, "selected": false, "text": "<p>I recently came across this issue and tried using the empty <code>&lt;h2&gt;&lt;/h2&gt;</code> method and it didn't work for me. Eventually I discovered that using <code>&lt;hr class=&quot;wp-header-end&quot;&gt;</code> seems to work and the admin notice will always appear directly below it.</p>\n<p>Hopefully it helps someone!</p>\n" }, { "answer_id": 411500, "author": "Jefferson", "author_id": 190088, "author_profile": "https://wordpress.stackexchange.com/users/190088", "pm_score": 0, "selected": false, "text": "<p>It appears that <code>settings_errors()</code> will display all notices that I've tested with a settings form so far. Despite the name it also outputs success messages. Place it anwhere in your template and that's where the notices will appear.</p>\n<p>I found the <code>&lt;h2&gt;</code> solution mentioned to not do anything.</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/settings_errors/\" rel=\"nofollow noreferrer\">WordPress Reference settings_errors()</a></p>\n" } ]
2016/03/14
[ "https://wordpress.stackexchange.com/questions/220650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/15010/" ]
I am adding an admin notice via the conventional `admin_notice` hook in my plugin: ``` function my_admin_notice() { ?> <div class="notice notice-info is-dismissible"> <p><?php _e( 'some message', 'my-text-domain' ); ?></p> </div> <?php } if ( my_plugin_show_admin_notice() ) add_action( 'admin_notices', 'my_admin_notice' ); ``` How can I control where wordpress places the admin notice, in the html on the current screen, without using Javascript?
I found out by accident recently that all the notices will be moved to after the first `<h2>` tag on the page inside a `<div class="wrap">`. This gives you some *slight* control in that, for example, on a plugin settings page you can put an empty `<h2></h2>` at the very top if you want to use `<h2>Plugin Title</h2>` without it messing up the display formatting there.
220,661
<p><strong>What I'm trying to do:</strong><br> Make an ajax-powered search button that gets the text from an input and give a list of post id's that match that search.</p> <p>Note: I must probably sound very stupid to 90% of you, but I'm rather new to ajax and wordpress, so if I'm doing it all wrong, it would be great if someone could point me out what I'm doing wrong or if he knows a better guide than the ones I used. (The problems I think I'm having with the script are written all the way down below.)</p> <p>To start I thought of just making <strong>a button that uses ajax to get the title of a post-id.</strong><Br> I read these pages:</p> <ul> <li><a href="https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/" rel="nofollow">https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/</a></li> <li><a href="https://developer.wordpress.org/plugins/javascript/summary/" rel="nofollow">https://developer.wordpress.org/plugins/javascript/summary/</a></li> </ul> <p>I've tried out all this code on both these pages, however, I'm always stuck because I need to create a plugin. <strong>I'm not trying to create a plugin</strong> so I was wondering if I could just write all the code on my search page.</p> <p>I'm sad however that it doesn't work, and I cannot find out why... (i get redirected to the homepage)</p> <p>I'm just curious if I have to research how to create plugins etc. or is there a much simpler way that just allows me to get e.g. the post title of a certain ID through an AJAX call without using a plugin?</p> <p>This is the code I tried:</p> <p><strong>The Ajax call:</strong></p> <pre><code>&lt;script&gt; jQuery(document).ready(function($) { //wrapper $("body").on("click",".ajax",function() { //event var s_str = this.value; console.log(s_str); console.log(admin_ajax_url.ajax_url); var this2 = this; //use in callback $.post(admin_ajax_url.ajaxurl, { //POST request _ajax_nonce: get_title_nonce.nonce, //nonce action: "get_title", //action id: s_str, //data success: function(response) { if(response.type == "success") { alert("success") } else { alert("failed") } } }, function(data) { //callback $("#tt").html(data); //insert server response }); }); }); &lt;/script&gt; </code></pre> <p><strong>The search form:</strong></p> <pre><code>$the_title = ''; $s_str = 18694; $nonce = wp_create_nonce("get_title_nonce"); $link = admin_url('http://jtc.ae/pre/wp/wp-admin/admin-ajax.php?action=get_title&amp;post_id='.$s_str.'&amp;nonce='.$nonce); echo '&lt;a class="ajax" data-nonce="' . $nonce . '" data-post_id="' . $s_str . '" href="' . $link . '"&gt;'.$s_str.'&lt;/a&gt; Title: &lt;span id="tt"&gt;'.$the_title."&lt;/span&gt;"; </code></pre> <p><strong>The rest of the code I added as written in the guides:</strong><br></p> <pre><code>&lt;?php add_action( 'init', 'my_script_enqueuer' ); function my_script_enqueuer() { wp_register_script('ajax_search',TEMPLATEPATH.'/new/js/ajax_search.js', array('jquery')); wp_localize_script('ajax_search', 'admin_ajax_url', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'ajax_search' ); } add_action("wp_ajax_get_title", "get_title"); add_action("wp_ajax_nopriv_get_title", "get_title_must_login"); function get_title() { if ( !wp_verify_nonce( $_REQUEST['nonce'], "get_title")) { exit("No naughty business please"); } $the_title = get_the_title($_REQUEST["post_id"]); if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &amp;&amp; strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $result = json_encode($result); echo $result; } else { header("Location: ".$_SERVER["HTTP_REFERER"]); } die(); } function get_title_must_login() { echo "You must log in to get title"; die(); } ?&gt; </code></pre> <p><strong>Probably the problems lie here:</strong><br> I'm not sure about these <code>add_action</code> parts... I don't think I need it if I add the link to admin-ajax.php directly like I did just here above: <code>http://jtc.ae/pre/wp/wp-admin/admin-ajax.php?</code> So could I just scrap this first <code>add_action</code>?</p> <p>Also I think that the bottom <code>add_action</code>s are probably not properly excecuted on my search_page.php. But this is just the thing: I'm not planning on creating any plugins, so I don't know where to put them...</p>
[ { "answer_id": 220652, "author": "iantsch", "author_id": 90220, "author_profile": "https://wordpress.stackexchange.com/users/90220", "pm_score": 2, "selected": false, "text": "<p>According to the Codex <code>admin_notice</code> does the following:</p>\n\n<blockquote>\n <p>Notices displayed near the top of admin pages. The hook function\n should echo a message to be displayed.</p>\n</blockquote>\n\n<p>That means you cannot place them at the bottom or middle of your screen, if you use the hook. Furthermore if you place a div with the class notice anywhere in your admin pages, WP admin JS scripts will put them just where all the other notices would be; and they will behave like notices too.</p>\n\n<p>FYI: I tested this already with a fresh install. ;)</p>\n\n<h2>But</h2>\n\n<p>If you want to show a <code>admin_notice</code> at a particular page, you can add the action within a <code>current_screen</code> action:</p>\n\n<pre><code>function my_admin_notice() { ?&gt;\n &lt;div class=\"notice notice-info is-dismissible\"&gt;\n &lt;p&gt;&lt;?php _e( 'some message', 'my_textdomain' ); ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php\n}\n\nfunction my_current_screen_example( $current_screen ) {\n // All your conditions go here, e.g. show notice @ post (not page) edit/new\n if ( 'post' == $current_screen-&gt;post_type &amp;&amp; 'post' == $current_screen-&gt;base ) {\n add_action( 'admin_notices', 'my_admin_notice' );\n }\n}\n\nadd_action( 'current_screen', 'my_current_screen_example' );\n</code></pre>\n\n<h2>More Information:</h2>\n\n<ul>\n<li>Action Hook: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_notices\" rel=\"nofollow\">admin_notices</a></li>\n<li>Action Hook: <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/current_screen\" rel=\"nofollow\">current_screen</a></li>\n</ul>\n" }, { "answer_id": 220733, "author": "Rutwick Gangurde", "author_id": 4740, "author_profile": "https://wordpress.stackexchange.com/users/4740", "pm_score": 0, "selected": false, "text": "<p>The action <code>admin_notices</code> is called or applied <strong>only once</strong> in the file, <code>admin-header.php</code> on line number 238, just at the beginning of the <code>wpbody-content</code> div, which makes up the body of a dashboard page. Hence, there is no way you can change the position of the admin notice, without using JavaScript. However, you can definitely make your own <code>notice</code> divs at the positions or locations you want, and manipulate their visibility.</p>\n\n<p>Just create the mark up for the notice as:</p>\n\n<pre><code>&lt;div class=\"notice notice-info is-dismissible\"&gt;\n &lt;p&gt;This is a notice.&lt;/p&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You can now control it's visibility using PHP. Meaning when you redirect a user to this page, or submit a form on this page, just set the message in the div, and using a simple if else, echo the div.</p>\n" }, { "answer_id": 220735, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 4, "selected": true, "text": "<p>I found out by accident recently that all the notices will be moved to after the first <code>&lt;h2&gt;</code> tag on the page inside a <code>&lt;div class=\"wrap\"&gt;</code>. This gives you some <em>slight</em> control in that, for example, on a plugin settings page you can put an empty <code>&lt;h2&gt;&lt;/h2&gt;</code> at the very top if you want to use <code>&lt;h2&gt;Plugin Title&lt;/h2&gt;</code> without it messing up the display formatting there.</p>\n" }, { "answer_id": 342200, "author": "NJENGAH", "author_id": 67761, "author_profile": "https://wordpress.stackexchange.com/users/67761", "pm_score": 1, "selected": false, "text": "<p>I had the same problem and I resolved it by ensuring all the heading tags above where I want to place the notice there is no <code>&lt;h2&gt;</code>.</p>\n\n<p>In this case, I wanted to display an error log notice below the input field as shown below : \n<a href=\"https://i.stack.imgur.com/7gizl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7gizl.png\" alt=\"enter image description here\"></a></p>\n\n<p>I solved it by introducing an empty <code>&lt;h2&gt;</code> tag just below the email input field and also change the tabs tag to <code>&lt;h3&gt;</code> instead of <code>&lt;h2&gt;</code> </p>\n" }, { "answer_id": 395849, "author": "Spartieee", "author_id": 212634, "author_profile": "https://wordpress.stackexchange.com/users/212634", "pm_score": 1, "selected": false, "text": "<p>I recently came across this issue and tried using the empty <code>&lt;h2&gt;&lt;/h2&gt;</code> method and it didn't work for me. Eventually I discovered that using <code>&lt;hr class=&quot;wp-header-end&quot;&gt;</code> seems to work and the admin notice will always appear directly below it.</p>\n<p>Hopefully it helps someone!</p>\n" }, { "answer_id": 411500, "author": "Jefferson", "author_id": 190088, "author_profile": "https://wordpress.stackexchange.com/users/190088", "pm_score": 0, "selected": false, "text": "<p>It appears that <code>settings_errors()</code> will display all notices that I've tested with a settings form so far. Despite the name it also outputs success messages. Place it anwhere in your template and that's where the notices will appear.</p>\n<p>I found the <code>&lt;h2&gt;</code> solution mentioned to not do anything.</p>\n<p><a href=\"https://developer.wordpress.org/reference/functions/settings_errors/\" rel=\"nofollow noreferrer\">WordPress Reference settings_errors()</a></p>\n" } ]
2016/03/14
[ "https://wordpress.stackexchange.com/questions/220661", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87968/" ]
**What I'm trying to do:** Make an ajax-powered search button that gets the text from an input and give a list of post id's that match that search. Note: I must probably sound very stupid to 90% of you, but I'm rather new to ajax and wordpress, so if I'm doing it all wrong, it would be great if someone could point me out what I'm doing wrong or if he knows a better guide than the ones I used. (The problems I think I'm having with the script are written all the way down below.) To start I thought of just making **a button that uses ajax to get the title of a post-id.** I read these pages: * <https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/> * <https://developer.wordpress.org/plugins/javascript/summary/> I've tried out all this code on both these pages, however, I'm always stuck because I need to create a plugin. **I'm not trying to create a plugin** so I was wondering if I could just write all the code on my search page. I'm sad however that it doesn't work, and I cannot find out why... (i get redirected to the homepage) I'm just curious if I have to research how to create plugins etc. or is there a much simpler way that just allows me to get e.g. the post title of a certain ID through an AJAX call without using a plugin? This is the code I tried: **The Ajax call:** ``` <script> jQuery(document).ready(function($) { //wrapper $("body").on("click",".ajax",function() { //event var s_str = this.value; console.log(s_str); console.log(admin_ajax_url.ajax_url); var this2 = this; //use in callback $.post(admin_ajax_url.ajaxurl, { //POST request _ajax_nonce: get_title_nonce.nonce, //nonce action: "get_title", //action id: s_str, //data success: function(response) { if(response.type == "success") { alert("success") } else { alert("failed") } } }, function(data) { //callback $("#tt").html(data); //insert server response }); }); }); </script> ``` **The search form:** ``` $the_title = ''; $s_str = 18694; $nonce = wp_create_nonce("get_title_nonce"); $link = admin_url('http://jtc.ae/pre/wp/wp-admin/admin-ajax.php?action=get_title&post_id='.$s_str.'&nonce='.$nonce); echo '<a class="ajax" data-nonce="' . $nonce . '" data-post_id="' . $s_str . '" href="' . $link . '">'.$s_str.'</a> Title: <span id="tt">'.$the_title."</span>"; ``` **The rest of the code I added as written in the guides:** ``` <?php add_action( 'init', 'my_script_enqueuer' ); function my_script_enqueuer() { wp_register_script('ajax_search',TEMPLATEPATH.'/new/js/ajax_search.js', array('jquery')); wp_localize_script('ajax_search', 'admin_ajax_url', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'ajax_search' ); } add_action("wp_ajax_get_title", "get_title"); add_action("wp_ajax_nopriv_get_title", "get_title_must_login"); function get_title() { if ( !wp_verify_nonce( $_REQUEST['nonce'], "get_title")) { exit("No naughty business please"); } $the_title = get_the_title($_REQUEST["post_id"]); if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $result = json_encode($result); echo $result; } else { header("Location: ".$_SERVER["HTTP_REFERER"]); } die(); } function get_title_must_login() { echo "You must log in to get title"; die(); } ?> ``` **Probably the problems lie here:** I'm not sure about these `add_action` parts... I don't think I need it if I add the link to admin-ajax.php directly like I did just here above: `http://jtc.ae/pre/wp/wp-admin/admin-ajax.php?` So could I just scrap this first `add_action`? Also I think that the bottom `add_action`s are probably not properly excecuted on my search\_page.php. But this is just the thing: I'm not planning on creating any plugins, so I don't know where to put them...
I found out by accident recently that all the notices will be moved to after the first `<h2>` tag on the page inside a `<div class="wrap">`. This gives you some *slight* control in that, for example, on a plugin settings page you can put an empty `<h2></h2>` at the very top if you want to use `<h2>Plugin Title</h2>` without it messing up the display formatting there.
220,680
<p>i had to resize a lot of existing images in my upload folder (around 1k). After reuploading them, Wordpress of course, doesn't recognize the new dimensions. My approach was to just change the size in the _post_meta table. But this looks like this:</p> <pre><code>a:6{s:5:"width";s:3:"330";s:6:"height";s:4:"1067";s:14:"hwstring_small";s:22:"height='96' width='29'";s:4:"file";s:22:"2012/03/2-IMG_1540.png";s:5:"sizes";a:3:{s:9:"thumbnail";a:3:{s:4:"file";s:21:"2-IMG_1540-56x183.png"; ... </code></pre> <p>All I need to change is the "width" value of the first entry from "330" to sth. else. Although it looks like a dictionary to me I do not find a way to get access to that value in SQL. </p> <p>The wp_update_attachment_metadata reference states that all data must be given as existing data will be wiped. That's the reason why I thought it would be easier to do it in SQL.</p>
[ { "answer_id": 220684, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>What you are looking at is PHP <a href=\"http://php.net/manual/en/function.serialize.php\" rel=\"nofollow\">serialized</a> data saved as string in MySQL database. SQL simply won't have any clue on what to do with it.</p>\n\n<p>The most important thing to remember about serialized data is that isn't trivial to edit. It embeds the length of values in the format and if the edits mismatch the length the whole data gets corrupted.</p>\n\n<p>So typically the preferred method to manipulate such data is with PHP code itself.</p>\n\n<p>Notably there are multiple solutions out there to rebuild the image data (plugins, WP CLI command) but it's usually for additional sizes, not original image. I am not sure if they would handle your case, but you might try. Just test first so that it's not making it worse.</p>\n" }, { "answer_id": 221254, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": 2, "selected": true, "text": "<p>You could do this via PHP instead of SQL, just get the existing metadata and change what you need to, it will handle the serializing for you:</p>\n<pre><code>$newwidth = '250'; // or whatever it is\n$attachments = get_posts(array('post_type'=&gt;'attachment'));\nforeach ($attachments as $attachment) {\n $id = $attachment-&gt;ID;\n $metadata = wp_get_attachment_metadata($id);\n $metadata['width'] = $newwidth;\n wp_update_attachment_metadata($id,$metadata);\n}\n</code></pre>\n<p>But really, you may do better using the <a href=\"http://wordpres.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">Regenerate Thumbnails Plugin</a> which may fix this and regenerate the different thumbnail sizes at the same time.</p>\n" }, { "answer_id": 286607, "author": "Hatem Badawi", "author_id": 131902, "author_profile": "https://wordpress.stackexchange.com/users/131902", "pm_score": 0, "selected": false, "text": "<p>you need to unserialize this string then you will get an array that you can edit.\nThen serialize this array again.</p>\n\n<pre><code>$attachment_data_array=unserialize('a:6{s:5:\"width\"; ...');\n//change array values as you need \n//for example\n$attachment_data_array['sizes']['thumbnail']['file']='newlink.jpg';\n//then serialize again\n$data=serialize($attachment_data_array);\n</code></pre>\n" }, { "answer_id": 315736, "author": "WowPress.host", "author_id": 135591, "author_profile": "https://wordpress.stackexchange.com/users/135591", "pm_score": 0, "selected": false, "text": "<p>There is \"Fix Media Library\" plugin doing that, it updates _wp_attachment_metadata field as a part of thumbs regeneration.</p>\n\n<p><a href=\"https://wordpress.org/plugins/wow-media-library-fix/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wow-media-library-fix/</a></p>\n" } ]
2016/03/14
[ "https://wordpress.stackexchange.com/questions/220680", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90571/" ]
i had to resize a lot of existing images in my upload folder (around 1k). After reuploading them, Wordpress of course, doesn't recognize the new dimensions. My approach was to just change the size in the \_post\_meta table. But this looks like this: ``` a:6{s:5:"width";s:3:"330";s:6:"height";s:4:"1067";s:14:"hwstring_small";s:22:"height='96' width='29'";s:4:"file";s:22:"2012/03/2-IMG_1540.png";s:5:"sizes";a:3:{s:9:"thumbnail";a:3:{s:4:"file";s:21:"2-IMG_1540-56x183.png"; ... ``` All I need to change is the "width" value of the first entry from "330" to sth. else. Although it looks like a dictionary to me I do not find a way to get access to that value in SQL. The wp\_update\_attachment\_metadata reference states that all data must be given as existing data will be wiped. That's the reason why I thought it would be easier to do it in SQL.
You could do this via PHP instead of SQL, just get the existing metadata and change what you need to, it will handle the serializing for you: ``` $newwidth = '250'; // or whatever it is $attachments = get_posts(array('post_type'=>'attachment')); foreach ($attachments as $attachment) { $id = $attachment->ID; $metadata = wp_get_attachment_metadata($id); $metadata['width'] = $newwidth; wp_update_attachment_metadata($id,$metadata); } ``` But really, you may do better using the [Regenerate Thumbnails Plugin](http://wordpres.org/plugins/regenerate-thumbnails/) which may fix this and regenerate the different thumbnail sizes at the same time.
220,716
<p>Currently I've tried this process with two browsers: Google Chrome and Mozilla Firefox. Whenever I want to run a JavaScript code on them they show me the raw code instead of executing it. Exactly what I wrote in my Editor will be shown in the browser screen.</p> <p>Hope someone can help.</p> <h2>Edit</h2> <blockquote> <p>Hey, am not using wordpress. </p> </blockquote> <p>Sorry that I didn't put the code here. Here is the code in my text Editor:</p> <pre><code>&lt;Script&gt; Document.write("hello world") &lt;/script&gt; </code></pre> <p>This is what it output .... </p> <pre><code>&lt;Script&gt; Document.write("hello world") &lt;/script&gt; </code></pre> <p>The same thing.</p>
[ { "answer_id": 220683, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 4, "selected": false, "text": "<p>The best reason I can find it to separate Logic from Structure or Control from Markup. The handbook on the <a href=\"https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#brace-style\">PHP Coding Standard for WordPress</a> says:</p>\n\n\n\n<blockquote>\n <p>Braces should always be used, even when they are not required:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>if ( condition ) {\n action0();\n}\n\nif ( condition ) {\n action1();\n} elseif ( condition2 ) {\n action2a();\n action2b();\n}\n\nforeach ( $items as $item ) {\n process_item( $item );\n}\n</code></pre>\n \n <p>Note that requiring the use of braces just means that single-statement\n inline control structures are prohibited. You are free to use the\n <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\">alternative syntax for control structures</a> (e.g. if/endif,\n while/endwhile) — <strong>especially in your templates where PHP code is\n embedded within HTML</strong>, for instance:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php if ( have_posts() ) : ?&gt;\n\n &lt;div class=\"hfeed\"&gt;\n\n &lt;?php while ( have_posts() ) : the_post(); ?&gt;\n\n &lt;article id=\"post-&lt;?php the_ID() ?&gt;\" class=\"&lt;?php post_class() ?&gt;\"&gt;\n &lt;!-- ... --&gt;\n &lt;/article&gt;\n\n &lt;?php endwhile; ?&gt;\n\n &lt;/div&gt;\n\n&lt;?php endif; ?&gt;\n</code></pre>\n</blockquote>\n\n<p>Some could argue that braces are better because of syntax highlighting ( i.e. click opening bracket and it highlights closing bracket ) but it comes down to preference. The alternative syntax isn't required or necessary but offered as an <em>alternative</em> so you're free to use whichever is the cleanest to read.</p>\n\n<hr>\n\n<p>Personally, I use the alt syntax in templates ( or any time I plan on mixing HTML and PHP ) with appropriate spacing and indentation as I find it easier to read overall. </p>\n" }, { "answer_id": 220710, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 4, "selected": true, "text": "<p>As in many things wordpress, inertia has a lot to do with why things are done in specific way. Early core themes were written using those constructs and later developers copied them because they either did not know better or thought there was some non obvious reason to prefer them.</p>\n\n<p>As @Howdy_McGee said, it is just a style preference but I would avoid the <code>endif</code>, <code>endwhile</code> as curly braces are standard block delimiters across many languages and therefor are in general easier to read even if we will ignore the benefit of syntax highlighting and block collapsing in general editors.</p>\n" } ]
2016/03/15
[ "https://wordpress.stackexchange.com/questions/220716", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83327/" ]
Currently I've tried this process with two browsers: Google Chrome and Mozilla Firefox. Whenever I want to run a JavaScript code on them they show me the raw code instead of executing it. Exactly what I wrote in my Editor will be shown in the browser screen. Hope someone can help. Edit ---- > > Hey, am not using wordpress. > > > Sorry that I didn't put the code here. Here is the code in my text Editor: ``` <Script> Document.write("hello world") </script> ``` This is what it output .... ``` <Script> Document.write("hello world") </script> ``` The same thing.
As in many things wordpress, inertia has a lot to do with why things are done in specific way. Early core themes were written using those constructs and later developers copied them because they either did not know better or thought there was some non obvious reason to prefer them. As @Howdy\_McGee said, it is just a style preference but I would avoid the `endif`, `endwhile` as curly braces are standard block delimiters across many languages and therefor are in general easier to read even if we will ignore the benefit of syntax highlighting and block collapsing in general editors.
220,726
<p>I want to add a support page to my plugin wordpress. My plugin is already developed. Now I want to allow users to contact me for any question. I want the support button to be next to the activate and Update buttons in the plugin add page.</p>
[ { "answer_id": 220728, "author": "denis.stoyanov", "author_id": 76287, "author_profile": "https://wordpress.stackexchange.com/users/76287", "pm_score": 3, "selected": true, "text": "<p>You can use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)\" rel=\"nofollow\"><code>plugin_action_links_</code></a> filter for that task:</p>\n\n<pre><code>add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'add_support_link_wpse_220726' );\n\nfunction add_support_link_wpse_220726( $links ) {\n $links[] = '&lt;a href=\"http://example.com/support/\" target=\"_blank\"&gt;Support&lt;/a&gt;';\n return $links;\n} \n</code></pre>\n\n<p>Note that you must also pass the plugin name (<code>plugin_basename(__FILE__)</code>) for it to work. That's why take into consideration from where you will call it.</p>\n" }, { "answer_id": 220729, "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...</p>\n\n<pre><code>add_filter('plugin_action_links', 'mycustom_plugin_action_links', 10, 2);\nfunction mycustom_plugin_action_links($links, $file) {\n $thisplugin = plugin_basename(__FILE__);\n if ($file == $thisplugin) {\n $supportlink = \"&lt;a href='\".admin_url('admin.php').\"?page=mycustom-support'&gt;Support&lt;/a&gt;\";\n array_unshift($links, $supportlink);\n }\n return $links;\n}\n</code></pre>\n\n<p>Sounds like you might be needing <code>add_menu_page</code> also, so my answer assumes your link is to an admin page.</p>\n" } ]
2016/03/15
[ "https://wordpress.stackexchange.com/questions/220726", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90607/" ]
I want to add a support page to my plugin wordpress. My plugin is already developed. Now I want to allow users to contact me for any question. I want the support button to be next to the activate and Update buttons in the plugin add page.
You can use the [`plugin_action_links_`](https://codex.wordpress.org/Plugin_API/Filter_Reference/plugin_action_links_(plugin_file_name)) filter for that task: ``` add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'add_support_link_wpse_220726' ); function add_support_link_wpse_220726( $links ) { $links[] = '<a href="http://example.com/support/" target="_blank">Support</a>'; return $links; } ``` Note that you must also pass the plugin name (`plugin_basename(__FILE__)`) for it to work. That's why take into consideration from where you will call it.
220,789
<p>Im experimenting with random theme and "new technology" and Im trying to convert whole front-end to pure JS single page application <em>(no page refreshes - like Facebook, Twitter etc)</em> using <a href="http://wp-api.org/" rel="nofollow">WP REST API</a>, <a href="http://redux.js.org/" rel="nofollow">Redux.js</a> and <a href="https://facebook.github.io/react/" rel="nofollow">React.js</a> and few other helpers.</p> <p><strong>How to handle logged-in users?</strong> How do I keep track of that? I know that this information is normally handled with cookies. How would one check it <em>via</em> JS?</p> <p>I could just make an ajax call every time route/url changes and use <code>is_user_logged_in()</code> in server-side but it seems primative. Could I access directly to cookie <em>via</em> JS and check it in browser?</p> <hr> <ul> <li>I gave it a long thought if that's off-topic here but it really seems like a very WP specific question</li> <li>Im just experimenting and trying to push it to a new level, please no <em>"this is a bad idea"</em> comments</li> </ul>
[ { "answer_id": 220792, "author": "Bruno Cantuaria", "author_id": 65717, "author_profile": "https://wordpress.stackexchange.com/users/65717", "pm_score": 0, "selected": false, "text": "<p>You will need to check cookies than (and probably DB) or call a function somehow (maybe ajax or something like that) to check if user is logged in and what user is it. Try looking at the function wp_validate_auth_cookie() at wp-includes/pluggable.php</p>\n" }, { "answer_id": 220793, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 0, "selected": false, "text": "<p>We can localize data whenever we enqueue the scripts:</p>\n\n<pre><code>function localize_vars() {\n\n // Register your script so we may reference it.\n wp_register_script( 'some_handle', 'path/to/myscript.js' );\n\n $js_arr = array( 'logged_in' =&gt; is_user_logged_in() );\n\n // Localize our data\n wp_localize_script( 'some_handle', 'object_name', $js_arr );\n\n // Enqueue Your Script!\n wp_enqueue_script( 'some_handle' );\n}\nadd_action( 'wp_enqueue_scripts', 'localize_vars' );\n</code></pre>\n\n<p>We register our script, create an associative array so it can convert it to object properties, localize it, and finally enqueue it as normal. In your JS file you can then check if a user is logged in by referencing the <code>object_name</code> and associative array index:</p>\n\n<pre><code>jQuery( function( $ ) {\n if( object_name.logged_in ) { // True or False \n /* ... */\n }\n} );\n</code></pre>\n" }, { "answer_id": 220798, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": 2, "selected": true, "text": "<p>As you are going to send ajax request from theme (frontend) you need to specify the ajaxurl otherwise it will throw an error \"undefined ajaurl\"</p>\n\n<pre><code>/**\n * frontend ajax requests.\n */\nwp_enqueue_script( 'frontend-ajax', JS_DIR_URI . 'frontend-ajax.js', array('jquery'), null, true );\nwp_localize_script( 'frontend-ajax', 'frontend_ajax_object',\n array( \n 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' )\n )\n);\n</code></pre>\n\n<p>then in your frontend-ajax.js you can can send ajax request like this</p>\n\n<pre><code>$.ajax({\n url: frontend_ajax_object.ajaxurl,\n type: 'GET',\n data: {\n action: 'register_action_hook',\n },\n success: function( response ) {\n console.log( response );\n },\n});\n</code></pre>\n\n<p>then in your functions.php you can hook your function to the register_action_hook.</p>\n\n<pre><code>add_action( 'wp_ajax_register_action_hook', 'prefix_do_something' );\nfunction prefix_do_something() {\n if ( is_user_logged_in ) {\n // do something\n } else {\n // do something else\n }\n}\n</code></pre>\n\n<p>you can also use the @Howdy_McGee method to localize the is_logged_in variable using</p>\n\n<pre><code>wp_localize_script( 'handler', 'js_object', $array_of_variables );\n</code></pre>\n\n<p>and accessing it in your js with js_object.variable_name see the @Howdy_McGee answer for reference.</p>\n" } ]
2016/03/15
[ "https://wordpress.stackexchange.com/questions/220789", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/80903/" ]
Im experimenting with random theme and "new technology" and Im trying to convert whole front-end to pure JS single page application *(no page refreshes - like Facebook, Twitter etc)* using [WP REST API](http://wp-api.org/), [Redux.js](http://redux.js.org/) and [React.js](https://facebook.github.io/react/) and few other helpers. **How to handle logged-in users?** How do I keep track of that? I know that this information is normally handled with cookies. How would one check it *via* JS? I could just make an ajax call every time route/url changes and use `is_user_logged_in()` in server-side but it seems primative. Could I access directly to cookie *via* JS and check it in browser? --- * I gave it a long thought if that's off-topic here but it really seems like a very WP specific question * Im just experimenting and trying to push it to a new level, please no *"this is a bad idea"* comments
As you are going to send ajax request from theme (frontend) you need to specify the ajaxurl otherwise it will throw an error "undefined ajaurl" ``` /** * frontend ajax requests. */ wp_enqueue_script( 'frontend-ajax', JS_DIR_URI . 'frontend-ajax.js', array('jquery'), null, true ); wp_localize_script( 'frontend-ajax', 'frontend_ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); ``` then in your frontend-ajax.js you can can send ajax request like this ``` $.ajax({ url: frontend_ajax_object.ajaxurl, type: 'GET', data: { action: 'register_action_hook', }, success: function( response ) { console.log( response ); }, }); ``` then in your functions.php you can hook your function to the register\_action\_hook. ``` add_action( 'wp_ajax_register_action_hook', 'prefix_do_something' ); function prefix_do_something() { if ( is_user_logged_in ) { // do something } else { // do something else } } ``` you can also use the @Howdy\_McGee method to localize the is\_logged\_in variable using ``` wp_localize_script( 'handler', 'js_object', $array_of_variables ); ``` and accessing it in your js with js\_object.variable\_name see the @Howdy\_McGee answer for reference.
220,802
<p>I've found several other threads asking this same question, but for some reason I can't seem to make a solution work for me. For clarification, I want to have a custom field that is applied to a post but contains no value so that I can setup a template post (portfolio item in this case) and simply duplicate it around but leave out values where the field does not apply, and of course if there is no value I do not want the related html to show. So, here is what I have:</p> <pre><code>&lt;?php $fbb_CurrentMetaSet = get_post_meta($post-&gt;ID, 'fbb_ProjectData_Process', false); if (!empty($fbb_CurrentMetaSet)){?&gt; &lt;div id="fbb_ProjectData_Process" class="fbb_ProjectDataSetSection"&gt; &lt;div class="fbb_Title"&gt;&lt;h5&gt;Process:&lt;/h5&gt;&lt;/div&gt; &lt;div&gt; &lt;?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){ echo '&lt;div&gt;'.$fbb_MetaDataSingle.'&lt;/div&gt;'; }?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>This code works if I simply check whether the custom field exists ( if ($fbb_CurrentMetaSet) ), but for some reason the !empty() method isn't working. Can anyone explain why? FYI I'm using the latest wordpress and the x-theme.</p> <p>It may be that the larger context yields an explanation so below I've pasted the entire set of related code. My test code can be found in the last section. Once I've got it working I intend to duplicate it to the similar sections above it:</p> <pre><code>&lt;div id="fbb_ProjectDataWrap"&gt; &lt;div id="fbb_ProjectData_Client" class="fbb_ProjectDataSetSection"&gt; &lt;div class="fbb_Title"&gt;&lt;h5&gt;Client:&lt;/h5&gt;&lt;/div&gt; &lt;ul&gt; &lt;?php $fbb_CurrentMetaSet = get_post_meta($post-&gt;ID, 'fbb_ProjectData_Client', false);?&gt; &lt;?phpforeach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){ echo '&lt;li&gt;'.$fbb_MetaDataSingle.'&lt;/li&gt;'; } }?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="fbb_ProjectData_Tools" class="fbb_ProjectDataSetSection"&gt; &lt;div class="fbb_Title"&gt;&lt;h5&gt;Tools:&lt;/h5&gt;&lt;/div&gt; &lt;ul&gt; &lt;?php $fbb_CurrentMetaSet = get_post_meta($post-&gt;ID, 'fbb_ProjectData_Tools', false); ?&gt; &lt;?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){ echo '&lt;li&gt;'.$fbb_MetaDataSingle.'&lt;/li&gt;'; } ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="fbb_ProjectData_About" class="fbb_ProjectDataSetSection"&gt; &lt;div class="fbb_Title"&gt;&lt;h5&gt;About:&lt;/h5&gt;&lt;/div&gt; &lt;div&gt; &lt;?php $fbb_CurrentMetaSet = get_post_meta($post-&gt;ID, 'fbb_ProjectData_AboutTheProject', false); ?&gt; &lt;?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){ echo '&lt;div&gt;'.$fbb_MetaDataSingle.'&lt;/div&gt;'; } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $fbb_CurrentMetaSet = get_post_meta($post-&gt;ID, 'fbb_ProjectData_Process', false); if (!empty($fbb_CurrentMetaSet)){?&gt; &lt;div id="fbb_ProjectData_Process" class="fbb_ProjectDataSetSection"&gt; &lt;div class="fbb_Title"&gt;&lt;h5&gt;Process:&lt;/h5&gt;&lt;/div&gt; &lt;div&gt; &lt;?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){ echo '&lt;div&gt;'.$fbb_MetaDataSingle.'&lt;/div&gt;'; }?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 220803, "author": "vancoder", "author_id": 26778, "author_profile": "https://wordpress.stackexchange.com/users/26778", "pm_score": 3, "selected": true, "text": "<p>Your third parameter of <code>get_post_meta()</code> is set to <code>false</code>. This means it will return an array. Even though you didn't set a value for this custom field, it will still record an array element in the DB - so <code>empty()</code> will return false.</p>\n\n<p>Try switching to <code>true</code> for your third param. That should return an empty string.</p>\n" }, { "answer_id": 220821, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>I think we can do this in a bit better and safer. We can get all the post meta in one go (<em>This is just DRY'ing up your code a bit, see <a href=\"https://wordpress.stackexchange.com/a/167151/31545\">this post on custom field performance</a></em>).</p>\n\n<p>We can try the following: (<em>Code is commented as we go along, and note, all code is untested</em>)</p>\n\n<h2>OPTION 1 - Calling <code>get_post_meta()</code> once</h2>\n\n<pre><code>$meta = get_post_meta( get_the_ID() );\n\n// First make sure we have data before continuing\nif ( $meta ) :\n // Get your field values and set defaults\n $fields = [];\n $field_names = ['Client', 'Tools', 'About', 'Process'];\n foreach ( $field_names as $field_name ) {\n if ( 'About' === $field_name ) {\n $name = 'AboutTheProject';\n } else {\n $name = $field_name;\n }\n $fields[$field_name] = ( isset( $meta['fbb_ProjectData_' . $name] ) )\n ? filter_var( $meta['fbb_ProjectData_' . $name][0], FILTER_SANITIZE_STRING ) \n : '';\n }\n\n // Lets make sure we have at least one key/value pair with avalue\n if ( array_filter( $fields ) ) : ?&gt;\n &lt;div id=\"fbb_ProjectDataWrap\"&gt;\n &lt;?php // Lets loop through $fields and display them\n foreach ( $fields as $key=&gt;$field ) : \n // Make sure $field is not empty, if so, continue\n if ( !$field )\n continue;\n\n // We have values, lets display them\n ?&gt;\n\n &lt;div id=\"fbb_ProjectData_&lt;?php echo $key; ?&gt;\" class=\"fbb_ProjectDataSetSection\"&gt;\n &lt;div class=\"fbb_Title\"&gt;\n &lt;h5&gt;&lt;?php echo $key; ?&gt;:&lt;/h5&gt;\n &lt;/div&gt;\n &lt;ul&gt;\n &lt;li&gt;\n &lt;div&gt;\n &lt;?php echo $field; ?&gt;\n &lt;/div&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;?php endforeach; ?&gt; \n &lt;/div&gt;\n &lt;?php\n endi\n</code></pre>\n\n<p>f;\nendif;</p>\n\n<h2>OPTION 2 - Calling <code>get_post_meta()</code> for each key</h2>\n\n<p>Because custom fields are cached and do not decrease performance if we call multiple instances of <code>get_post_meta()</code> (<em>see the linked post</em>), we can call <code>get_post_meta()</code> for each key. Just remember to set <code>$single</code> to <code>true</code></p>\n\n<pre><code>// Get your field values and set defaults\n$fields = [];\n$field_names = ['Client', 'Tools', 'About', 'Process'];\nforeach ( $field_names as $field_name ) {\n if ( 'About' === $field_name ) {\n $name = 'AboutTheProject';\n } else {\n $name = $field_name;\n }\n $fields[$field_name] = filter_var( \n get_post_meta( get_the_ID(), 'fbb_ProjectData_' . $name, true ), \n FILTER_SANITIZE_STRING \n );\n}\n\n// Lets make sure we have at least one key/value pair with avalue\nif ( array_filter( $fields ) ) : ?&gt;\n &lt;div id=\"fbb_ProjectDataWrap\"&gt;\n &lt;?php // Lets loop through $fields and display them\n foreach ( $fields as $key=&gt;$field ) : \n // Make sure $field is not empty, if so, continue\n if ( !$field )\n continue;\n\n // We have values, lets display them\n ?&gt;\n\n &lt;div id=\"fbb_ProjectData_&lt;?php echo $key; ?&gt;\" class=\"fbb_ProjectDataSetSection\"&gt;\n &lt;div class=\"fbb_Title\"&gt;\n &lt;h5&gt;&lt;?php echo $key; ?&gt;:&lt;/h5&gt;\n &lt;/div&gt;\n &lt;ul&gt;\n &lt;li&gt;\n &lt;div&gt;\n &lt;?php echo $field; ?&gt;\n &lt;/div&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;?php endforeach; ?&gt; \n &lt;/div&gt;\n&lt;?php\nendif;\n</code></pre>\n" } ]
2016/03/15
[ "https://wordpress.stackexchange.com/questions/220802", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90658/" ]
I've found several other threads asking this same question, but for some reason I can't seem to make a solution work for me. For clarification, I want to have a custom field that is applied to a post but contains no value so that I can setup a template post (portfolio item in this case) and simply duplicate it around but leave out values where the field does not apply, and of course if there is no value I do not want the related html to show. So, here is what I have: ``` <?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Process', false); if (!empty($fbb_CurrentMetaSet)){?> <div id="fbb_ProjectData_Process" class="fbb_ProjectDataSetSection"> <div class="fbb_Title"><h5>Process:</h5></div> <div> <?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){ echo '<div>'.$fbb_MetaDataSingle.'</div>'; }?> </div> </div> <?php } ?> ``` This code works if I simply check whether the custom field exists ( if ($fbb\_CurrentMetaSet) ), but for some reason the !empty() method isn't working. Can anyone explain why? FYI I'm using the latest wordpress and the x-theme. It may be that the larger context yields an explanation so below I've pasted the entire set of related code. My test code can be found in the last section. Once I've got it working I intend to duplicate it to the similar sections above it: ``` <div id="fbb_ProjectDataWrap"> <div id="fbb_ProjectData_Client" class="fbb_ProjectDataSetSection"> <div class="fbb_Title"><h5>Client:</h5></div> <ul> <?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Client', false);?> <?phpforeach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){ echo '<li>'.$fbb_MetaDataSingle.'</li>'; } }?> </ul> </div> <div id="fbb_ProjectData_Tools" class="fbb_ProjectDataSetSection"> <div class="fbb_Title"><h5>Tools:</h5></div> <ul> <?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Tools', false); ?> <?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){ echo '<li>'.$fbb_MetaDataSingle.'</li>'; } ?> </ul> </div> <div id="fbb_ProjectData_About" class="fbb_ProjectDataSetSection"> <div class="fbb_Title"><h5>About:</h5></div> <div> <?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_AboutTheProject', false); ?> <?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){ echo '<div>'.$fbb_MetaDataSingle.'</div>'; } ?> </div> </div> <?php $fbb_CurrentMetaSet = get_post_meta($post->ID, 'fbb_ProjectData_Process', false); if (!empty($fbb_CurrentMetaSet)){?> <div id="fbb_ProjectData_Process" class="fbb_ProjectDataSetSection"> <div class="fbb_Title"><h5>Process:</h5></div> <div> <?php foreach($fbb_CurrentMetaSet as $fbb_MetaDataSingle){ echo '<div>'.$fbb_MetaDataSingle.'</div>'; }?> </div> </div> <?php } ?> </div> ```
Your third parameter of `get_post_meta()` is set to `false`. This means it will return an array. Even though you didn't set a value for this custom field, it will still record an array element in the DB - so `empty()` will return false. Try switching to `true` for your third param. That should return an empty string.
220,822
<p>I am trying to create two additional <strong>add_meta_box</strong> <em>context</em> locations ('after_title' and 'after_editor') within posts.</p> <p>This doesn't appear to do what I think it should. The meta box does appear on the page just within the normal <em>context</em>, not in the new defined <em>context</em> locations. Does anyone have any insight on this? </p> <p>Thank you in advance for your time and consideration,</p> <p>Tim</p> <p><strong>REFERENCES:</strong></p> <p><a href="http://adambrown.info/p/wp_hooks/hook/edit_form_after_editor?version=4.4&amp;file=wp-admin/edit-form-advanced.php" rel="nofollow">http://adambrown.info/p/wp_hooks/hook/edit_form_after_editor?version=4.4&amp;file=wp-admin/edit-form-advanced.php</a></p> <p><a href="http://adambrown.info/p/wp_hooks/hook/edit_form_after_title?version=4.4&amp;file=wp-admin/edit-form-advanced.php" rel="nofollow">http://adambrown.info/p/wp_hooks/hook/edit_form_after_title?version=4.4&amp;file=wp-admin/edit-form-advanced.php</a></p> <p><strong>ACTION HOOKS:</strong></p> <pre><code> public function initialize_hooks() { add_action( 'edit_form_after_editor', array( $this, 'add_after_editor_meta_boxes' ) ); add_action( 'edit_form_after_title', array( $this, 'add_after_title_meta_boxes' ) ) ; } /** * Register meta box context location: after_editor * * @return null **/ public function add_after_editor_meta_boxes() { global $post, $wp_meta_boxes; # Output the `after_editor` meta boxes: do_meta_boxes( get_current_screen(), 'after_editor', $post ); } /** * Register meta box context location: after_title * * @return null **/ public function add_after_title_meta_boxes() { global $post, $wp_meta_boxes; # Output the `after_title` meta boxes: do_meta_boxes( get_current_screen(), 'after_title', $post ); } </code></pre> <p><strong>ADD META BOX:</strong></p> <pre><code> /** * The function responsible for creating the actual meta box. * * @since 0.2.0 **/ public function add_meta_box() { add_meta_box( 'new-meta-box', "New Meta Box", array( $this, 'display_meta_box' ), 'after_editor', 'high', 'default' ); </code></pre>
[ { "answer_id": 220825, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 0, "selected": false, "text": "<p>these metaboxes appears as <em>normal</em> because <code>add_meta_box()</code> adds them in the loop of the others metaboxes.<br>\nand to use a real metaboxe fully functional (in order to hide / show it and move it arround the page) you have to put the metabox in the loop.</p>\n\n<p>so the last time I had to put a meta box before the editor, I choose to hide the default editor (in the properties of the post type) and to add another metaboxe with a new editor in it with <code>wp_editor()</code> <a href=\"http://codex.wordpress.org/Function_Reference/wp_editor\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/wp_editor</a>.</p>\n" }, { "answer_id": 220855, "author": "STEAMworks Learning Center", "author_id": 90671, "author_profile": "https://wordpress.stackexchange.com/users/90671", "pm_score": 1, "selected": false, "text": "<p>Here is a fully working dummy plugin to show how to add the new meta box contexts. </p>\n\n<p><strong>STEPS:</strong></p>\n\n<ol>\n<li><p>Create the plugin structure below and copy the code into <em>plugin-shell.php</em>.</p></li>\n<li><p>Leave the style sheets empty.</p></li>\n<li><p>Install and activate the plugin. </p></li>\n<li><p>Navigate to the plugin from the admin menu item 'Plugin Shell | Add New'. </p></li>\n<li><p>Directions on use are in the meta box.</p></li>\n</ol>\n\n<p>I hope this is easy to follow. If you have any questions ask them in the comments.</p>\n\n<p>Best,</p>\n\n<p>Tim</p>\n\n<p><strong>PLUGIN DIRECTORY STRUCTURE:</strong></p>\n\n<pre><code>plugin-shell &gt; plugin-shell.php\nplugin-shell &gt; assets &gt; css &gt; admin &gt; style.css\nplugin-shell &gt; assets &gt; css &gt; frontend &gt; style.css\n</code></pre>\n\n<p><strong>PLUGIN CODE:</strong></p>\n\n<pre><code>&lt;?php\n\n/*\n Plugin Name: PluginShell\n Plugin URI: http://www.pluginshell.com/\n Description: Aenean Vestibulum Risus Commodo Ullamcorper\n Author: PluginShell\n Author URI: http://www.pluginshell.com/\n Version: 0.0.0\n*/\n\nmb_internal_encoding(\"UTF-8\");\nclass Plugin_Shell {\n /**\n *\n * CONSTRUCTOR\n * Adds all actions and filters to the class\n *\n * @since 0.0.0\n *\n **/ \n function __construct() {\n //Actions\n add_action( 'init', array( &amp;$this, 'plugin_shell_register_post_type' ) );\n add_action( 'admin_init', array( &amp;$this, 'plugin_shell_register_and_build_fields') );\n add_action( 'wp_enqueue_scripts', array( &amp;$this, 'plugin_shell_enqueue_style' ) );\n add_action( 'admin_enqueue_scripts', array( &amp;$this, 'plugin_shell_enqueue_options_style' ) );\n add_action( 'admin_menu', array( &amp;$this, 'plugin_shell_add_meta_boxes' ) );\n add_action( 'admin_menu', array( &amp;$this, 'plugin_shell_options_page' ) );\n add_action( 'add_meta_boxes', array( &amp;$this, 'plugin_shell_add_contextable_meta_box' ) );\n add_action( 'save_post', array( &amp;$this, 'plugin_shell_meta_box_save' ), 1, 2 );\n add_action( 'edit_form_after_editor',array( &amp;$this, 'add_after_editor_meta_boxes' ) );\n add_action( 'edit_form_after_title', array( &amp;$this, 'add_after_title_meta_boxes' ) );\n\n }\n\n /**\n *\n * PHP4 CONSTRUCTOR\n * Calls __construct to create class\n *\n * @since 0.0.0\n *\n **/ \n function plugin_shell() {\n $this-&gt;__construct();\n }\n\n /**\n *\n * LOAD CSS INTO THE WEBSITE'S FRONT END\n *\n * @since 0.0.0\n *\n **/ \n function plugin_shell_enqueue_style() {\n wp_register_style( 'plugin-shell-style', plugin_dir_url( __FILE__ ) . 'assets/css/frontend/style.css' );\n wp_enqueue_style( 'plugin-shell-style' ); \n }\n\n /**\n *\n * LOAD CSS INTO THE ADMIN PAGE\n *\n * @since 0.0.0\n *\n **/ \n function plugin_shell_enqueue_options_style() {\n wp_register_style( 'plugin-shell-options-style', plugin_dir_url( __FILE__ ) . 'assets/css/admin/style.css' );\n wp_enqueue_style( 'plugin-shell-options-style' ); \n }\n\n /**\n * Register meta box context location: after_editor\n *\n * @return null\n **/\n function add_after_editor_meta_boxes() {\n global $post, $wp_meta_boxes;\n # Output the `after_editor` meta boxes:\n do_meta_boxes( get_current_screen(), 'after_editor', $post );\n }\n\n /**\n * Register meta box context location: after_title\n *\n * @return null\n **/\n function add_after_title_meta_boxes() {\n global $post, $wp_meta_boxes;\n # Output the `after_title` meta boxes:\n do_meta_boxes( get_current_screen(), 'after_title', $post );\n }\n\n /**\n *\n * REGISTER CUSTOM POST TYPE: plugin_shell\n *\n * @since 0.0.0\n *\n **/\n function plugin_shell_register_post_type() {\n $options = get_option('plugin_shell_options');\n\n register_post_type( 'plugin_shell',\n array(\n 'labels' =&gt; array(\n 'name' =&gt; __( 'Plugin Shell' ),\n 'singular_name' =&gt; __( 'term' ),\n 'add_new' =&gt; __( 'Add New' ),\n 'add_new_item' =&gt; __( 'Add New Term' ),\n 'edit' =&gt; __( 'Edit' ),\n 'edit_item' =&gt; __( 'Edit Term' ),\n 'new_item' =&gt; __( 'New Term' ),\n 'view' =&gt; __( 'View Term' ),\n 'view_item' =&gt; __( 'View Term' ),\n 'search_items' =&gt; __( 'Search Term' ),\n 'not_found' =&gt; __( 'No Terms found' ),\n 'not_found_in_trash' =&gt; __( 'No Terms found in Trash' )\n ),\n 'public' =&gt; true,\n 'query_var' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'show_ui' =&gt; true,\n 'menu_icon' =&gt; 'dashicons-book-alt',\n 'supports' =&gt; array( 'title', 'editor' ),\n 'rewrite' =&gt; array( 'slug' =&gt; $options['plugin_shell_slug_url_setting'] ? get_post($options['plugin_shell_slug_url_setting'])-&gt;post_name : 'plugin-shell', 'with_front' =&gt; false )\n )\n );\n }\n\n/*********************************************************\n BEGIN: CONTEXTABLE META BOX\n *********************************************************/\n\n /**\n *\n * CALLS ALL OF THE FUNCTIONS RESPONSIBLE FOR RENDERING THE CONTEXTABLE PLUGIN SHELL META BOX\n *\n * @since 0.0.0\n *\n **/\n function plugin_shell_add_contextable_meta_box() {\n $this-&gt;_plugin_shell_add_contextable();\n }\n\n /**\n *\n * RENDERS THE META BOX \n * Responsible for allowing the user to enter the plugin shell term.\n *\n * @since 0.0.0\n *\n **/\n function _plugin_shell_add_contextable() {\n add_meta_box( \n 'contextable-meta-box', \n __( 'Extended Context Meta Box', 'pluginshell-textdomain' ), \n array( &amp;$this, '_display_contextable_meta_box' ), \n 'plugin_shell', // CHANGE TO DESIRED post-type\n 'after_title', // CHANGE THIS TO 'after_editor' || 'after_title' || OR OTHER VALID CONTEXT LOCATION\n 'default' \n );\n }\n\n /**\n * \n * DISPLAYS THE CONTENTS OF THE PLUGIN SHELL TERM META BOX\n *\n * @since 0.0.0\n *\n **/ \n function _display_contextable_meta_box() {\n printf( '&lt;em&gt;Move this meta box with the extended context values&lt;/em&gt;&lt;br /&gt;&lt;strong&gt;after_title&lt;/strong&gt;&lt;br /&gt;&lt;strong&gt;after_editor&lt;/strong&gt;&lt;br /&gt;&amp;nbsp;&lt;br /&gt;To dettach the meta box to the bottom of the editor open &lt;em&gt;assets/css/admin/style.css&lt;/em&gt;&lt;br /&gt;&amp;nbsp;&lt;br /&gt;Add the style:&lt;br /&gt;&lt;strong&gt;#after_editor-sortables {&lt;/strong&gt;&lt;br /&gt;&lt;strong&gt;\n&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;padding-top: 40px;&lt;/strong&gt;&lt;br /&gt;\n&lt;strong&gt;}&lt;/strong&gt;&lt;br /&gt;&amp;nbsp;&lt;br /&gt;See &lt;strong&gt;comments&lt;/strong&gt; in &lt;em&gt;function _plugin_shell_add_contextable()&lt;/em&gt;' );\n }\n\n/*********************************************************\n END: CONTEXTABLE META BOX\n *********************************************************/\n\n /**\n * \n * CALLS ALL OF THE FUNCTIONS RESPONSIBLE FOR RENDERING THE PLUGIN SHELL META BOX\n *\n * @since 0.0.0\n *\n **/\n function plugin_shell_add_meta_boxes() {\n $this-&gt;_plugin_shell_add_meta_box();\n }\n\n /**\n *\n * RENDERS THE META BOX \n * Responsible for allowing the user to enter the plugin shell term.\n *\n * @since 0.0.0\n *\n **/\n function _plugin_shell_add_meta_box() {\n add_meta_box( 'plugin_shell', __('Plugin Shell Extra Meta Box', 'pluginshell-textdomain'), array( &amp;$this, '_plugin_shell_definiton_meta_box' ), 'plugin_shell', 'normal', 'high' );\n }\n\n /**\n * \n * DISPLAYS THE CONTENTS OF THE PLUGIN SHELL TERM META BOX\n *\n * @since 0.0.0\n *\n **/ \n function _plugin_shell_definiton_meta_box() {\n ?&gt;\n &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Nullam id dolor id nibh ultricies vehicula ut id elit. Donec id elit non mi porta gravida at eget metus.&lt;/p&gt;\n\n&lt;p&gt;Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Nullam quis risus eget urna mollis ornare vel eu leo. Vestibulum id ligula porta felis euismod semper. Curabitur blandit tempus porttitor. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.&lt;/p&gt;\n\n&lt;p&gt;Vestibulum id ligula porta felis euismod semper. Cras mattis consectetur purus sit amet fermentum. Vestibulum id ligula porta felis euismod semper. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.&lt;/p&gt;\n&lt;?php\n }\n\n /**\n * \n * SAVES PLUGIN SHELL TERM\n *\n * @since 0.0.0\n *\n **/\n function plugin_shell_meta_box_save( $post_id, $post ) {\n $key = '_plugin_shell_term';\n\n // verify the nonce\n if ( !isset($_POST['_plugin_shell_nonce']) || !wp_verify_nonce( $_POST['_plugin_shell_nonce'], plugin_basename(__FILE__) ) )\n return;\n\n // don't try to save the data under autosave, ajax, or future post.\n if ( defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE ) return;\n if ( defined('DOING_AJAX') &amp;&amp; DOING_AJAX ) return;\n if ( defined('DOING_CRON') &amp;&amp; DOING_CRON ) return;\n\n // is the user allowed to edit the URL?\n if ( ! current_user_can( 'edit_posts' ) || $post-&gt;post_type != 'plugin_shell' )\n return;\n\n $value = isset( $_POST[$key] ) ? $_POST[$key] : '';\n\n if ( $value ) {\n // save/update\n $my_post = array();\n update_post_meta($post-&gt;ID, $key, $value);\n } else {\n // delete if blank\n delete_post_meta($post-&gt;ID, $key);\n }\n\n }\n\n /**\n *\n * ADMIN MENU AND\n * SETTING FEILDS\n *\n **/\n\n /**\n * \n * BUILD THE SETTINGS OPTIONS PAGE\n *\n * @since 0.0.0\n *\n **/\n function _plugin_shell_build_options_page() { \n ?&gt;\n &lt;div id=\"plugin-shell-options-wrap\"&gt;\n &lt;div class=\"icon32\" id=\"icon-tools\"&gt; &lt;br /&gt; &lt;/div&gt;\n &lt;form method=\"post\" action=\"options.php\" enctype=\"multipart/form-data\"&gt;\n &lt;?php settings_fields('plugin_shell_option_group'); ?&gt;\n &lt;?php do_settings_sections(__FILE__); ?&gt;\n &lt;p class=\"submit\"&gt;\n &lt;input name=\"Submit\" type=\"submit\" class=\"button-primary\" value=\"&lt;?php esc_attr_e('Save Changes'); ?&gt;\" /&gt;\n &lt;/p&gt;\n &lt;/form&gt;\n &lt;p&gt;&lt;hr&gt;&lt;/p&gt;\n &lt;p&gt;* After editing the Slug the Permalinks Settings must be saved again.&lt;/p&gt;\n &lt;/div&gt;\n &lt;?php \n }\n\n /**\n * \n * REGISTER SETTINGS AND FIELDS FOR OPTIONS PAGE\n *\n * @since 0.0.0\n *\n **/\n function plugin_shell_register_and_build_fields() {\n register_setting('plugin_shell_option_group', 'plugin_shell_option_mainpage', 'plugin_shell_validate_setting');\n add_settings_section('plugin_shell_settings_general', 'Plugin Shell General Settings', array( &amp;$this, '_plugin_shell_settings_fields'), __FILE__);\n }\n\n /**\n * \n * RENDER THE SLUG SELECTION SETTINGS FIELD\n *\n * @since 0.9.2\n *\n **/\n function _plugin_shell_settings_fields() {\n add_settings_field('slug', 'Mainpage:', array( &amp;$this, '_plugin_shell_slug_url_setting'), __FILE__, 'plugin_shell_settings_general');\n } \n\n /**\n * \n * SANITIZE OPTIONS\n *\n * @since 0.0.0\n *\n **/\n function plugin_shell_validate_setting($plugin_shell_options) {\n return $plugin_shell_options;\n }\n\n\n /**\n * \n * GET DROPDOWN OF ALL PAGES FOR SLUG SETTING OPTION\n *\n * @since 0.0.0\n *\n **/\n function _plugin_shell_slug_url_setting() {\n $options = get_option('plugin_shell_options');\n wp_dropdown_pages(array('name' =&gt; 'theme_options[plugin_shell_slug_url_setting]', 'selected' =&gt; $options['plugin_shell_slug_url_setting'] ));\n }\n\n /**\n * \n * ADD THE OPTIONS PAGE\n *\n * @since 0.0.0\n *\n **/\n function plugin_shell_options_page() { \n add_options_page('Plugin Shell', 'Plugin Shell', 'administrator', __FILE__, array( &amp;$this, '_plugin_shell_build_options_page' ) );\n }\n};\n\n/**\n * \n * INSTANTIATE CLASS plugin_shell\n *\n * @since 0.0.0\n *\n **/\n$PluginShell = new plugin_shell;\n\n?&gt;\n</code></pre>\n" } ]
2016/03/16
[ "https://wordpress.stackexchange.com/questions/220822", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90671/" ]
I am trying to create two additional **add\_meta\_box** *context* locations ('after\_title' and 'after\_editor') within posts. This doesn't appear to do what I think it should. The meta box does appear on the page just within the normal *context*, not in the new defined *context* locations. Does anyone have any insight on this? Thank you in advance for your time and consideration, Tim **REFERENCES:** <http://adambrown.info/p/wp_hooks/hook/edit_form_after_editor?version=4.4&file=wp-admin/edit-form-advanced.php> <http://adambrown.info/p/wp_hooks/hook/edit_form_after_title?version=4.4&file=wp-admin/edit-form-advanced.php> **ACTION HOOKS:** ``` public function initialize_hooks() { add_action( 'edit_form_after_editor', array( $this, 'add_after_editor_meta_boxes' ) ); add_action( 'edit_form_after_title', array( $this, 'add_after_title_meta_boxes' ) ) ; } /** * Register meta box context location: after_editor * * @return null **/ public function add_after_editor_meta_boxes() { global $post, $wp_meta_boxes; # Output the `after_editor` meta boxes: do_meta_boxes( get_current_screen(), 'after_editor', $post ); } /** * Register meta box context location: after_title * * @return null **/ public function add_after_title_meta_boxes() { global $post, $wp_meta_boxes; # Output the `after_title` meta boxes: do_meta_boxes( get_current_screen(), 'after_title', $post ); } ``` **ADD META BOX:** ``` /** * The function responsible for creating the actual meta box. * * @since 0.2.0 **/ public function add_meta_box() { add_meta_box( 'new-meta-box', "New Meta Box", array( $this, 'display_meta_box' ), 'after_editor', 'high', 'default' ); ```
Here is a fully working dummy plugin to show how to add the new meta box contexts. **STEPS:** 1. Create the plugin structure below and copy the code into *plugin-shell.php*. 2. Leave the style sheets empty. 3. Install and activate the plugin. 4. Navigate to the plugin from the admin menu item 'Plugin Shell | Add New'. 5. Directions on use are in the meta box. I hope this is easy to follow. If you have any questions ask them in the comments. Best, Tim **PLUGIN DIRECTORY STRUCTURE:** ``` plugin-shell > plugin-shell.php plugin-shell > assets > css > admin > style.css plugin-shell > assets > css > frontend > style.css ``` **PLUGIN CODE:** ``` <?php /* Plugin Name: PluginShell Plugin URI: http://www.pluginshell.com/ Description: Aenean Vestibulum Risus Commodo Ullamcorper Author: PluginShell Author URI: http://www.pluginshell.com/ Version: 0.0.0 */ mb_internal_encoding("UTF-8"); class Plugin_Shell { /** * * CONSTRUCTOR * Adds all actions and filters to the class * * @since 0.0.0 * **/ function __construct() { //Actions add_action( 'init', array( &$this, 'plugin_shell_register_post_type' ) ); add_action( 'admin_init', array( &$this, 'plugin_shell_register_and_build_fields') ); add_action( 'wp_enqueue_scripts', array( &$this, 'plugin_shell_enqueue_style' ) ); add_action( 'admin_enqueue_scripts', array( &$this, 'plugin_shell_enqueue_options_style' ) ); add_action( 'admin_menu', array( &$this, 'plugin_shell_add_meta_boxes' ) ); add_action( 'admin_menu', array( &$this, 'plugin_shell_options_page' ) ); add_action( 'add_meta_boxes', array( &$this, 'plugin_shell_add_contextable_meta_box' ) ); add_action( 'save_post', array( &$this, 'plugin_shell_meta_box_save' ), 1, 2 ); add_action( 'edit_form_after_editor',array( &$this, 'add_after_editor_meta_boxes' ) ); add_action( 'edit_form_after_title', array( &$this, 'add_after_title_meta_boxes' ) ); } /** * * PHP4 CONSTRUCTOR * Calls __construct to create class * * @since 0.0.0 * **/ function plugin_shell() { $this->__construct(); } /** * * LOAD CSS INTO THE WEBSITE'S FRONT END * * @since 0.0.0 * **/ function plugin_shell_enqueue_style() { wp_register_style( 'plugin-shell-style', plugin_dir_url( __FILE__ ) . 'assets/css/frontend/style.css' ); wp_enqueue_style( 'plugin-shell-style' ); } /** * * LOAD CSS INTO THE ADMIN PAGE * * @since 0.0.0 * **/ function plugin_shell_enqueue_options_style() { wp_register_style( 'plugin-shell-options-style', plugin_dir_url( __FILE__ ) . 'assets/css/admin/style.css' ); wp_enqueue_style( 'plugin-shell-options-style' ); } /** * Register meta box context location: after_editor * * @return null **/ function add_after_editor_meta_boxes() { global $post, $wp_meta_boxes; # Output the `after_editor` meta boxes: do_meta_boxes( get_current_screen(), 'after_editor', $post ); } /** * Register meta box context location: after_title * * @return null **/ function add_after_title_meta_boxes() { global $post, $wp_meta_boxes; # Output the `after_title` meta boxes: do_meta_boxes( get_current_screen(), 'after_title', $post ); } /** * * REGISTER CUSTOM POST TYPE: plugin_shell * * @since 0.0.0 * **/ function plugin_shell_register_post_type() { $options = get_option('plugin_shell_options'); register_post_type( 'plugin_shell', array( 'labels' => array( 'name' => __( 'Plugin Shell' ), 'singular_name' => __( 'term' ), 'add_new' => __( 'Add New' ), 'add_new_item' => __( 'Add New Term' ), 'edit' => __( 'Edit' ), 'edit_item' => __( 'Edit Term' ), 'new_item' => __( 'New Term' ), 'view' => __( 'View Term' ), 'view_item' => __( 'View Term' ), 'search_items' => __( 'Search Term' ), 'not_found' => __( 'No Terms found' ), 'not_found_in_trash' => __( 'No Terms found in Trash' ) ), 'public' => true, 'query_var' => true, 'show_in_menu' => true, 'show_ui' => true, 'menu_icon' => 'dashicons-book-alt', 'supports' => array( 'title', 'editor' ), 'rewrite' => array( 'slug' => $options['plugin_shell_slug_url_setting'] ? get_post($options['plugin_shell_slug_url_setting'])->post_name : 'plugin-shell', 'with_front' => false ) ) ); } /********************************************************* BEGIN: CONTEXTABLE META BOX *********************************************************/ /** * * CALLS ALL OF THE FUNCTIONS RESPONSIBLE FOR RENDERING THE CONTEXTABLE PLUGIN SHELL META BOX * * @since 0.0.0 * **/ function plugin_shell_add_contextable_meta_box() { $this->_plugin_shell_add_contextable(); } /** * * RENDERS THE META BOX * Responsible for allowing the user to enter the plugin shell term. * * @since 0.0.0 * **/ function _plugin_shell_add_contextable() { add_meta_box( 'contextable-meta-box', __( 'Extended Context Meta Box', 'pluginshell-textdomain' ), array( &$this, '_display_contextable_meta_box' ), 'plugin_shell', // CHANGE TO DESIRED post-type 'after_title', // CHANGE THIS TO 'after_editor' || 'after_title' || OR OTHER VALID CONTEXT LOCATION 'default' ); } /** * * DISPLAYS THE CONTENTS OF THE PLUGIN SHELL TERM META BOX * * @since 0.0.0 * **/ function _display_contextable_meta_box() { printf( '<em>Move this meta box with the extended context values</em><br /><strong>after_title</strong><br /><strong>after_editor</strong><br />&nbsp;<br />To dettach the meta box to the bottom of the editor open <em>assets/css/admin/style.css</em><br />&nbsp;<br />Add the style:<br /><strong>#after_editor-sortables {</strong><br /><strong> &nbsp;&nbsp;&nbsp;&nbsp;padding-top: 40px;</strong><br /> <strong>}</strong><br />&nbsp;<br />See <strong>comments</strong> in <em>function _plugin_shell_add_contextable()</em>' ); } /********************************************************* END: CONTEXTABLE META BOX *********************************************************/ /** * * CALLS ALL OF THE FUNCTIONS RESPONSIBLE FOR RENDERING THE PLUGIN SHELL META BOX * * @since 0.0.0 * **/ function plugin_shell_add_meta_boxes() { $this->_plugin_shell_add_meta_box(); } /** * * RENDERS THE META BOX * Responsible for allowing the user to enter the plugin shell term. * * @since 0.0.0 * **/ function _plugin_shell_add_meta_box() { add_meta_box( 'plugin_shell', __('Plugin Shell Extra Meta Box', 'pluginshell-textdomain'), array( &$this, '_plugin_shell_definiton_meta_box' ), 'plugin_shell', 'normal', 'high' ); } /** * * DISPLAYS THE CONTENTS OF THE PLUGIN SHELL TERM META BOX * * @since 0.0.0 * **/ function _plugin_shell_definiton_meta_box() { ?> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Nullam id dolor id nibh ultricies vehicula ut id elit. Donec id elit non mi porta gravida at eget metus.</p> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Nullam quis risus eget urna mollis ornare vel eu leo. Vestibulum id ligula porta felis euismod semper. Curabitur blandit tempus porttitor. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.</p> <p>Vestibulum id ligula porta felis euismod semper. Cras mattis consectetur purus sit amet fermentum. Vestibulum id ligula porta felis euismod semper. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p> <?php } /** * * SAVES PLUGIN SHELL TERM * * @since 0.0.0 * **/ function plugin_shell_meta_box_save( $post_id, $post ) { $key = '_plugin_shell_term'; // verify the nonce if ( !isset($_POST['_plugin_shell_nonce']) || !wp_verify_nonce( $_POST['_plugin_shell_nonce'], plugin_basename(__FILE__) ) ) return; // don't try to save the data under autosave, ajax, or future post. if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return; if ( defined('DOING_AJAX') && DOING_AJAX ) return; if ( defined('DOING_CRON') && DOING_CRON ) return; // is the user allowed to edit the URL? if ( ! current_user_can( 'edit_posts' ) || $post->post_type != 'plugin_shell' ) return; $value = isset( $_POST[$key] ) ? $_POST[$key] : ''; if ( $value ) { // save/update $my_post = array(); update_post_meta($post->ID, $key, $value); } else { // delete if blank delete_post_meta($post->ID, $key); } } /** * * ADMIN MENU AND * SETTING FEILDS * **/ /** * * BUILD THE SETTINGS OPTIONS PAGE * * @since 0.0.0 * **/ function _plugin_shell_build_options_page() { ?> <div id="plugin-shell-options-wrap"> <div class="icon32" id="icon-tools"> <br /> </div> <form method="post" action="options.php" enctype="multipart/form-data"> <?php settings_fields('plugin_shell_option_group'); ?> <?php do_settings_sections(__FILE__); ?> <p class="submit"> <input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" /> </p> </form> <p><hr></p> <p>* After editing the Slug the Permalinks Settings must be saved again.</p> </div> <?php } /** * * REGISTER SETTINGS AND FIELDS FOR OPTIONS PAGE * * @since 0.0.0 * **/ function plugin_shell_register_and_build_fields() { register_setting('plugin_shell_option_group', 'plugin_shell_option_mainpage', 'plugin_shell_validate_setting'); add_settings_section('plugin_shell_settings_general', 'Plugin Shell General Settings', array( &$this, '_plugin_shell_settings_fields'), __FILE__); } /** * * RENDER THE SLUG SELECTION SETTINGS FIELD * * @since 0.9.2 * **/ function _plugin_shell_settings_fields() { add_settings_field('slug', 'Mainpage:', array( &$this, '_plugin_shell_slug_url_setting'), __FILE__, 'plugin_shell_settings_general'); } /** * * SANITIZE OPTIONS * * @since 0.0.0 * **/ function plugin_shell_validate_setting($plugin_shell_options) { return $plugin_shell_options; } /** * * GET DROPDOWN OF ALL PAGES FOR SLUG SETTING OPTION * * @since 0.0.0 * **/ function _plugin_shell_slug_url_setting() { $options = get_option('plugin_shell_options'); wp_dropdown_pages(array('name' => 'theme_options[plugin_shell_slug_url_setting]', 'selected' => $options['plugin_shell_slug_url_setting'] )); } /** * * ADD THE OPTIONS PAGE * * @since 0.0.0 * **/ function plugin_shell_options_page() { add_options_page('Plugin Shell', 'Plugin Shell', 'administrator', __FILE__, array( &$this, '_plugin_shell_build_options_page' ) ); } }; /** * * INSTANTIATE CLASS plugin_shell * * @since 0.0.0 * **/ $PluginShell = new plugin_shell; ?> ```
220,839
<p>I'd like to create a <em>Multi-Level Associative Object</em> on <code>$.post</code> method using WordPress, in order to make my code cleaner. The problem is, I don't know how to get those values to manipulate on the back-end.</p> <p>This is what I would like to do in <code>my_query.js</code> file, which contains and handles the <strong>AJAX</strong> request.</p> <pre><code>$.post( MyAjax.ajaxurl, { action: 'my_action', someValue: { one: 'Some Value One', two: 'Some Value Two', three: 'Some Value Three', four: 'Some Value Four', } } ); </code></pre> <p>And this is the current solution, which I <strong>DO NOT</strong> want to implement on my code.</p> <pre><code>$.post( MyAjax.ajaxurl, { action: 'my_action', someValueOne: 'Some Value One', someValueTwo: 'Some Value Two', someValueThree: 'Some Value Three', someValueFour: 'Some Value Four' } ); </code></pre> <p>The only way I could get those values on the back-end is by using the second option and doing this in the <code>.php</code> file.</p> <pre><code>$someValue = array( 'one' =&gt; $_POST[ 'someValueOne' ], 'two' =&gt; $_POST[ 'someValueTwo' ], 'three' =&gt; $_POST[ 'someValueThree' ], 'four' =&gt; $_POST[ 'someValueFour' ] ); echo $someValue[ 'one' ]; wp_die(); </code></pre> <h1>But... What is the problem anyways?</h1> <p>I <strong>DO NOT</strong> know how to have access to the <strong>AJAX Data Object</strong> inside my <code>.php</code> file by using the first example (which I'd like to), it only works by using the second one. How could I return the <code>someValue</code> object inside the <code>.php</code> file by using the first <strong>AJAX Request</strong> example?</p>
[ { "answer_id": 220846, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>If you want to pass a complex value, your best path is probably to jsonify it. Something like</p>\n\n<pre><code>$.post( MyAjax.ajaxurl, {\n action: 'my_action',\n someValue: JSON.stringify({\n one: 'Some Value One',\n two: 'Some Value Two',\n three: 'Some Value Three',\n four: 'Some Value Four',\n })\n} );\n</code></pre>\n\n<p>and then on the server side you decode the value with</p>\n\n<p><code>$someValue = json_decode($_POST['someValue']);</code></p>\n\n<p>At this point <code>$someValue</code> should be the array you wanted to pass.</p>\n" }, { "answer_id": 221197, "author": "iszwnc", "author_id": 90683, "author_profile": "https://wordpress.stackexchange.com/users/90683", "pm_score": 1, "selected": true, "text": "<p>Actually the solution I've found was very simple and didn't required much. For some reason I wasn't able to retrieve the data inside my <strong>AJAX Function Request</strong> on the Back-end.</p>\n\n<h2>JavaScript Code</h2>\n\n<p>As you can see below I defined the <code>someValue</code> property just the way I wanted, very clean and pretty.</p>\n\n<pre><code>$.post( MyAjax.ajaxurl, {\n action: 'my_action',\n someValue: {\n one: 'Some Value One',\n two: 'Some Value Two',\n three: 'Some Value Three',\n four: 'Some Value Four'\n }\n} );\n</code></pre>\n\n<h2>PHP Code</h2>\n\n<p>I must've forgot that I could associate all the properties defined inside the <strong>Data Object</strong> as an <strong>Array</strong> inside my Back-end <em>function</em>.</p>\n\n<pre><code>$someValue = array(\n 'one' =&gt; $_POST[ 'someValue' ][ 'one' ],\n 'two' =&gt; $_POST[ 'someValue' ][ 'two' ],\n 'three' =&gt; $_POST[ 'someValue' ][ 'three' ],\n 'four' =&gt; $_POST[ 'someValue' ][ 'four' ]\n);\n\nwp_die();\n</code></pre>\n\n<p>If you are unsure about what kind of data you're getting from the <strong>AJAX Request</strong>. I recommend you to do what our friend <a href=\"https://wordpress.stackexchange.com/users/74311/mmm\">@mmm</a> asked me, just <code>var_dump()</code> or <code>print_r()</code> the <code>$_POST</code> superglobal, then you'll see if you're actually getting something.</p>\n" } ]
2016/03/16
[ "https://wordpress.stackexchange.com/questions/220839", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90683/" ]
I'd like to create a *Multi-Level Associative Object* on `$.post` method using WordPress, in order to make my code cleaner. The problem is, I don't know how to get those values to manipulate on the back-end. This is what I would like to do in `my_query.js` file, which contains and handles the **AJAX** request. ``` $.post( MyAjax.ajaxurl, { action: 'my_action', someValue: { one: 'Some Value One', two: 'Some Value Two', three: 'Some Value Three', four: 'Some Value Four', } } ); ``` And this is the current solution, which I **DO NOT** want to implement on my code. ``` $.post( MyAjax.ajaxurl, { action: 'my_action', someValueOne: 'Some Value One', someValueTwo: 'Some Value Two', someValueThree: 'Some Value Three', someValueFour: 'Some Value Four' } ); ``` The only way I could get those values on the back-end is by using the second option and doing this in the `.php` file. ``` $someValue = array( 'one' => $_POST[ 'someValueOne' ], 'two' => $_POST[ 'someValueTwo' ], 'three' => $_POST[ 'someValueThree' ], 'four' => $_POST[ 'someValueFour' ] ); echo $someValue[ 'one' ]; wp_die(); ``` But... What is the problem anyways? =================================== I **DO NOT** know how to have access to the **AJAX Data Object** inside my `.php` file by using the first example (which I'd like to), it only works by using the second one. How could I return the `someValue` object inside the `.php` file by using the first **AJAX Request** example?
Actually the solution I've found was very simple and didn't required much. For some reason I wasn't able to retrieve the data inside my **AJAX Function Request** on the Back-end. JavaScript Code --------------- As you can see below I defined the `someValue` property just the way I wanted, very clean and pretty. ``` $.post( MyAjax.ajaxurl, { action: 'my_action', someValue: { one: 'Some Value One', two: 'Some Value Two', three: 'Some Value Three', four: 'Some Value Four' } } ); ``` PHP Code -------- I must've forgot that I could associate all the properties defined inside the **Data Object** as an **Array** inside my Back-end *function*. ``` $someValue = array( 'one' => $_POST[ 'someValue' ][ 'one' ], 'two' => $_POST[ 'someValue' ][ 'two' ], 'three' => $_POST[ 'someValue' ][ 'three' ], 'four' => $_POST[ 'someValue' ][ 'four' ] ); wp_die(); ``` If you are unsure about what kind of data you're getting from the **AJAX Request**. I recommend you to do what our friend [@mmm](https://wordpress.stackexchange.com/users/74311/mmm) asked me, just `var_dump()` or `print_r()` the `$_POST` superglobal, then you'll see if you're actually getting something.
220,873
<p>I have a custom post type called 'programmes' that details seminar information. Using a form visitors to the site can signup to a specific 'programme', once they have completed the form a new user is created with the following user meta:</p> <ul> <li>programme_id - the post ID of the 'programme' registered on</li> <li>programme_name - the title of the 'programme' registered on</li> <li>programme_end_date - the date the 'programme' ends</li> </ul> <p>The 'programme' dates are often changed (due to venue availability etc) after users have already registered, as a result I need to update the programme_end_date user meta field when these changes happen.</p> <p>I know it's going to be some combination of the <code>save_post</code> action along with <code>update_user_meta</code> and presumably a loop to check for all the users that have the specific updated 'programme' ID in the programme_id user meta field, but I can get my head round exactly how to do it. Any pointers would be excellent.</p>
[ { "answer_id": 220874, "author": "Christine Cooper", "author_id": 24875, "author_profile": "https://wordpress.stackexchange.com/users/24875", "pm_score": 0, "selected": false, "text": "<p>I am a bit unsure what your aim is but I can definitely get you on your feet. </p>\n\n<p>So you want to hook into <code>save_post</code>, confirm which <code>post_status</code> your are targeting, and then update user/post meta as you wish. </p>\n\n<p>I've written this for you, <strong>see the comments</strong> for clarification and adjust it as you please:</p>\n\n<pre><code>add_action('save_post', 'wp_220873', 10, 2);\n\nfunction wp_220873($id, $p) {\n\n // confirm if post is being published (or whatever post status you're targetting)\n if (\n (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE)\n || (defined('DOING_AJAX') &amp;&amp; DOING_AJAX)\n || ($p-&gt;post_status !== 'publish')\n ) {\n return;\n }\n\n // update post meta as you wish\n update_post_meta( $p-&gt;ID, 'meta_key', $value );\n\n // update user meta as you wish\n update_user_meta( $p-&gt;post_author, 'meta_key', $value );\n}\n</code></pre>\n" }, { "answer_id": 220875, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 0, "selected": false, "text": "<p>try this in the <code>save_post</code> hook</p>\n\n<pre><code>// search users which have this programme id\n\n$args = array(\n \"meta_query\" =&gt; [\n [\n \"key\" =&gt; \"programme_id\",\n \"value\" =&gt; $programme_id,\n ]\n ],\n);\n\n$wp_user_search = new \\WP_User_Query($args);\n$items = $wp_user_search-&gt;get_results();\n\n\nforeach ($items as $user) {\n\n // update end date\n\n update_user_meta($user-&gt;ID, \"programme_end_date\", $programme_end_date);\n\n\n}\n</code></pre>\n" }, { "answer_id": 220876, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 2, "selected": true, "text": "<p>You could query all the authors and loop through to update their dates. The below query pulls all users who have a <code>programme_id</code> of the current <code>post_id</code> and allocates an array of their IDs. You can then loop through to update whatever is necessary:</p>\n\n<pre><code>/** Save Custom Metaboxes **/\nfunction save_custom_meta_boxes( $post_id, $post ) {\n\n /** \n * Your Testing conditions should go here to ensure\n * That we're in the correct place and actually need to\n * run this query. I suggest checking against post type \n */\n\n $user_query = new WP_User_Query( array(\n 'meta_key' =&gt; 'programme_id',\n 'meta_value'=&gt; $post_id,\n 'fields' =&gt; 'ID',\n ) );\n\n if( ! empty( $user_query-&gt;results ) ) {\n foreach( $user_query-&gt;results as $user_id ) {\n update_user_meta( $user_id, 'programme_end_date', $_POST['some_data_here'] );\n }\n }\n}\nadd_action( 'save_post', 'save_custom_meta_boxes', 10, 2 );\n</code></pre>\n\n<p>I kept it as simple as possible and if you have a <em>ton</em> of users this may not be optimal. </p>\n" } ]
2016/03/16
[ "https://wordpress.stackexchange.com/questions/220873", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51458/" ]
I have a custom post type called 'programmes' that details seminar information. Using a form visitors to the site can signup to a specific 'programme', once they have completed the form a new user is created with the following user meta: * programme\_id - the post ID of the 'programme' registered on * programme\_name - the title of the 'programme' registered on * programme\_end\_date - the date the 'programme' ends The 'programme' dates are often changed (due to venue availability etc) after users have already registered, as a result I need to update the programme\_end\_date user meta field when these changes happen. I know it's going to be some combination of the `save_post` action along with `update_user_meta` and presumably a loop to check for all the users that have the specific updated 'programme' ID in the programme\_id user meta field, but I can get my head round exactly how to do it. Any pointers would be excellent.
You could query all the authors and loop through to update their dates. The below query pulls all users who have a `programme_id` of the current `post_id` and allocates an array of their IDs. You can then loop through to update whatever is necessary: ``` /** Save Custom Metaboxes **/ function save_custom_meta_boxes( $post_id, $post ) { /** * Your Testing conditions should go here to ensure * That we're in the correct place and actually need to * run this query. I suggest checking against post type */ $user_query = new WP_User_Query( array( 'meta_key' => 'programme_id', 'meta_value'=> $post_id, 'fields' => 'ID', ) ); if( ! empty( $user_query->results ) ) { foreach( $user_query->results as $user_id ) { update_user_meta( $user_id, 'programme_end_date', $_POST['some_data_here'] ); } } } add_action( 'save_post', 'save_custom_meta_boxes', 10, 2 ); ``` I kept it as simple as possible and if you have a *ton* of users this may not be optimal.
220,907
<p>Inside functions.php:</p> <pre><code>add_action('init','my_action'); function my_action() { if($dontknow) { $passme = "yes"; } else { $passme = "no"; } } </code></pre> <p>Inside index.php of the current theme:</p> <pre><code>echo $passme; </code></pre> <p>Is there a global to use for this purpose? Shall I use add_option (this is not a good idea for each request I guess)? Shall I use a custom global variable?</p> <p>Is there a better / usual / standard way to do this?</p>
[ { "answer_id": 220908, "author": "vancoder", "author_id": 26778, "author_profile": "https://wordpress.stackexchange.com/users/26778", "pm_score": 2, "selected": false, "text": "<p>It really depends on the use case. Anything that writes to the DB is probably overkill. Globals are messy. You could set a constant. You could turn the function into a class method, and create an additional method to return the variable. You could only check <code>$passme</code> when it's needed, instead of init.</p>\n" }, { "answer_id": 220910, "author": "fuxia", "author_id": 73, "author_profile": "https://wordpress.stackexchange.com/users/73", "pm_score": 4, "selected": true, "text": "<p>Use an object to keep the value of the variable and a custom action to print it out.</p>\n\n<p>In your theme’s <code>functions.php</code>, create a class, or better: move the class to a separate file.</p>\n\n<pre><code>class PassCheck\n{\n private $passed = 'no';\n\n public function check()\n {\n if ( is_user_logged_in() )\n $this-&gt;passed = 'yes';\n }\n\n public function print_pass()\n {\n echo $this-&gt;passed;\n }\n}\n</code></pre>\n\n<p>Then register the callbacks:</p>\n\n<pre><code>$passcheck = new PassCheck;\nadd_action( 'init', [ $passcheck, 'check' ] );\nadd_action( 'print_pass', [ $passcheck, 'print_pass' ] );\n</code></pre>\n\n<p>And in your template just call the proper action:</p>\n\n<pre><code>do_action( 'print_pass' );\n</code></pre>\n\n<p>This way, the template has no static dependency on the class: if you ever decide to remove the class or to register a completely different callback for that action, the theme will not break.</p>\n\n<p>You can also move the <code>check()</code> callback to another action (like <code>wp_loaded</code>) or separate it out into another class later.</p>\n\n<p>As a rule of thumb: templates (views) should be decoupled from business logic as much as possible. They shouldn't know class or function names. This isn't completely possible in WordPress’ architecture, but still a good regulative idea.</p>\n" }, { "answer_id": 220940, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>Without more details it hard to judge, but it feels like you have written <code>my_action</code> wrong, and it tries to do too many things.</p>\n\n<p>The <code>init</code> hook should be used just for initializing whatever you need, you should not precompute values in it. This should be done only when the need arises.</p>\n\n<p>You should just have a function called <code>print_pass</code> and call it wherever you need it. </p>\n\n<p>Doing too much on the <code>init</code> hook violates the principal of delaying code execution as much as possible. In this case the <code>init</code> hook will execute your <code>passme</code> logic even when handling admin in which that value is not needed.</p>\n\n<p>As for @toshco's answer, yes if you have some logic that might be better described with objects then <code>print_pass</code> should probably be a method in the class, but the wordpress hook system is functional in nature, and there is no need to go OOP when functional approach will be good enough. Functional is just more readable in the way the wordpress hook system works.</p>\n" }, { "answer_id": 221135, "author": "majick", "author_id": 76440, "author_profile": "https://wordpress.stackexchange.com/users/76440", "pm_score": -1, "selected": false, "text": "<p>Though you are asking about global <code>variables</code>, I think it worth adding that if you are just checking and setting this value <em>once</em> (as it seems like you <em>might</em> be) and it is not going to change later, it actually may make more sense just to use a <code>constant</code> instead of using a variable at all. </p>\n\n<pre><code>if ( ($thischeck) &amp;&amp; ($thatcheck) ) {$dontknow = true;} else {$dontknow = false;}\ndefine('DONTKNOW',$dontknow);\n\nadd_action('init','my_action');\nfunction my_action() {\n if (DONTKNOW) {$passme = \"yes\";} \n else {$passme = \"no\";}\n}\n</code></pre>\n\n<p>Because really, a 'static variable' is a basically a constant anyway.</p>\n" } ]
2016/03/16
[ "https://wordpress.stackexchange.com/questions/220907", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12035/" ]
Inside functions.php: ``` add_action('init','my_action'); function my_action() { if($dontknow) { $passme = "yes"; } else { $passme = "no"; } } ``` Inside index.php of the current theme: ``` echo $passme; ``` Is there a global to use for this purpose? Shall I use add\_option (this is not a good idea for each request I guess)? Shall I use a custom global variable? Is there a better / usual / standard way to do this?
Use an object to keep the value of the variable and a custom action to print it out. In your theme’s `functions.php`, create a class, or better: move the class to a separate file. ``` class PassCheck { private $passed = 'no'; public function check() { if ( is_user_logged_in() ) $this->passed = 'yes'; } public function print_pass() { echo $this->passed; } } ``` Then register the callbacks: ``` $passcheck = new PassCheck; add_action( 'init', [ $passcheck, 'check' ] ); add_action( 'print_pass', [ $passcheck, 'print_pass' ] ); ``` And in your template just call the proper action: ``` do_action( 'print_pass' ); ``` This way, the template has no static dependency on the class: if you ever decide to remove the class or to register a completely different callback for that action, the theme will not break. You can also move the `check()` callback to another action (like `wp_loaded`) or separate it out into another class later. As a rule of thumb: templates (views) should be decoupled from business logic as much as possible. They shouldn't know class or function names. This isn't completely possible in WordPress’ architecture, but still a good regulative idea.
220,911
<p>Came across this function to check if a page exists by its slug and it works great</p> <pre><code>function the_slug_exists($post_name) { global $wpdb; if($wpdb-&gt;get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A')) { return true; } else { return false; } </code></pre> <p>}</p> <p>but what i'm needing to do now is check if that exists, then output the title for that page, any help is appreciated.</p> <p>so when i put this code on the page to lookup the slug:</p> <pre><code>&lt;?php if (the_slug_exists('page-name')) { echo '$post_title'; } ?&gt; </code></pre> <p>everything is perfect other than the fact I need the function to output the title as well as lookup the slug, hopefully that makes more sense.</p>
[ { "answer_id": 220913, "author": "Motaz M. El Shazly", "author_id": 90216, "author_profile": "https://wordpress.stackexchange.com/users/90216", "pm_score": 0, "selected": false, "text": "<p>Here is an update to the same code for you</p>\n\n<pre><code>function the_slug_exists($post_name) {\nglobal $wpdb;\n//Sanitize title\n$post_name = sanitize_title($post_name);\nif($wpdb-&gt;get_row(\"SELECT post_name FROM wp_posts WHERE post_name = '\" . $post_name . \"'\", 'ARRAY_A')) {\n return $post_name;\n} else {\n return false;\n}\n</code></pre>\n\n<p>then you can run it by simply calling it with the echo function as in the following code, which will only print the post name if it exists.</p>\n\n<pre><code>echo the_slug_exists($post_name); \n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Alternatively you can rely on the default conditional WordPress function is_page() so your code becomes as simple as follows..</p>\n\n<pre><code>if( is_page($post_name) ):\n\n echo $post_name; \n\nendif;\n</code></pre>\n" }, { "answer_id": 220917, "author": "Prasad Nevase", "author_id": 62283, "author_profile": "https://wordpress.stackexchange.com/users/62283", "pm_score": 3, "selected": true, "text": "<p>looking at MySQL query in the function it becomes clear that though it matches the post_name and returns true or false. What you want to find is, if a page exists by its slug. So, in that case, the function you have chosen is wrong.</p>\n\n<p>To get the page by title you can simply use:</p>\n\n<pre><code>$page = get_page_by_title( 'Sample Page' );\necho $page-&gt;title\n</code></pre>\n\n<p>Just in case if you want to get page by slug you can use following code:</p>\n\n<pre><code>function get_page_title_for_slug($page_slug) {\n\n $page = get_page_by_path( $page_slug , OBJECT );\n\n if ( isset($page) )\n return $page-&gt;post_title;\n else\n return \"Match not found\";\n}\n</code></pre>\n\n<p>You may call above function like below:</p>\n\n<pre><code>echo \"&lt;h1&gt;\" . get_page_title_for_slug(\"sample-page\") . \"&lt;/h1&gt;\";\n</code></pre>\n\n<p>Let me know if that helps.</p>\n" }, { "answer_id": 220928, "author": "Pieter Goosen", "author_id": 31545, "author_profile": "https://wordpress.stackexchange.com/users/31545", "pm_score": 1, "selected": false, "text": "<p>It is almost always never adviced to run custom SQL when WordPress have native functions to do a specific job. The slug or <code>post_name</code> of a page is also the used in the page's path (URL) to identify and return the content of that page when such a page is visited. This means that, we can use <a href=\"https://developer.wordpress.org/reference/functions/get_page_by_path/\" rel=\"nofollow\"><code>get_page_by_path()</code></a> and just pass the slug (<em>post_name</em>) to the function and get the returned page object.</p>\n\n<pre><code>get_page_by_path ( \n string $page_path, \n string $output = OBJECT, \n string|array $post_type = 'page' \n)\n</code></pre>\n\n<p>Like many other functions and naming conventions (<em>like <code>post_name</code> which is actually the slug, and not the name</em>) in WordPress, <code>get_page_by_path()</code>'s name is confusing and IMHO stupid as you can pass any post type to the function</p>\n\n<p>We can use <code>get_page_by_path()</code> which will return nothing if the page is not found, or the page object on success. Lets write a proper wrapper function which will return false on failure and will always return the page object regardless if the page exists</p>\n\n<pre><code>function get_post_by_post_name( $slug = '', $post_type = '' )\n{\n //Make sure that we have values set for $slug and $post_type\n if ( !$slug\n || !$post_type\n )\n return false;\n\n // We will not sanitize the input as get_page_by_path() will handle that\n $post_object = get_page_by_path( $slug, OBJECT, $post_type );\n\n if ( !$post_object )\n return false;\n\n return $post_object;\n}\n</code></pre>\n\n<p>You can then use it as follow</p>\n\n<pre><code>if ( function_exists( 'get_post_by_post_name' ) ) {\n $post_object = get_post_by_post_name( 'post-name-better-known-as-slug', 'your_desired_post_type' );\n // Output only if we have a valid post \n if ( $post_object ) {\n echo apply_filters( 'the_title', $post_object-&gt;post_title );\n }\n}\n</code></pre>\n\n<p>If you really just need the post title returned, we can slightly alter the function</p>\n\n<pre><code>function get_post_title_by_post_name( $slug = '', $post_type = '' )\n{\n //Make sure that we have values set for $slug and $post_type\n if ( !$slug\n || !$post_type\n )\n return false;\n\n // We will not sanitize the input as get_page_by_path() will handle that\n $post_object = get_page_by_path( $slug, OBJECT, $post_type );\n\n if ( !$post_object )\n return false;\n\n return apply_filters( 'the_title', $post_object-&gt;post_title );\n}\n</code></pre>\n\n<p>and then use it as follow</p>\n\n<pre><code>if ( function_exists( 'get_post_title_by_post_name' ) ) {\n $post_title = get_post_title_by_post_name( 'post-name-better-known-as-slug', 'your_desired_post_type' );\n // Output only if we have a valid post \n if ( $post_title ) {\n echo $post_title;\n }\n}\n</code></pre>\n" } ]
2016/03/17
[ "https://wordpress.stackexchange.com/questions/220911", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90734/" ]
Came across this function to check if a page exists by its slug and it works great ``` function the_slug_exists($post_name) { global $wpdb; if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A')) { return true; } else { return false; } ``` } but what i'm needing to do now is check if that exists, then output the title for that page, any help is appreciated. so when i put this code on the page to lookup the slug: ``` <?php if (the_slug_exists('page-name')) { echo '$post_title'; } ?> ``` everything is perfect other than the fact I need the function to output the title as well as lookup the slug, hopefully that makes more sense.
looking at MySQL query in the function it becomes clear that though it matches the post\_name and returns true or false. What you want to find is, if a page exists by its slug. So, in that case, the function you have chosen is wrong. To get the page by title you can simply use: ``` $page = get_page_by_title( 'Sample Page' ); echo $page->title ``` Just in case if you want to get page by slug you can use following code: ``` function get_page_title_for_slug($page_slug) { $page = get_page_by_path( $page_slug , OBJECT ); if ( isset($page) ) return $page->post_title; else return "Match not found"; } ``` You may call above function like below: ``` echo "<h1>" . get_page_title_for_slug("sample-page") . "</h1>"; ``` Let me know if that helps.
220,930
<p>I'm using V2.0 and trying to create a post using the /posts endpoint.</p> <p>Here's the payload being sent with my request:</p> <pre><code>var payload = { title : "some title", format : "link", tags: ["tag1", "tag2"], categories: ["newsletter"], content: "http://someurl.com", status: "publish" }; </code></pre> <p>The posts are successfully being created and all other fields are added except for the category and tags. </p> <p>I see that both of them are supposed to take an array of strings. What am I missing here?</p> <p>Also, I've tried adding both categories and tags that already exist on the site, and brand new ones. both don't work.</p>
[ { "answer_id": 221047, "author": "Jevuska", "author_id": 18731, "author_profile": "https://wordpress.stackexchange.com/users/18731", "pm_score": 2, "selected": false, "text": "<p>You are using name in your terms. In default, try to use the existing term id ( in your case, cat ID and tag ID ).</p>\n\n<p>If you see <a href=\"https://plugins.trac.wordpress.org/browser/rest-api/trunk/lib/endpoints/class-wp-rest-posts-controller.php#L918\" rel=\"nofollow\">https://plugins.trac.wordpress.org/browser/rest-api/trunk/lib/endpoints/class-wp-rest-posts-controller.php#L918</a> they will handle your term with sanitize them into non-negative integer using <code>absint</code>. I hope this help.</p>\n\n<p>Here example code to hook <code>rest_insert_{$this-&gt;post_type}</code> to create terms ( tags and categories ) and set into post after post ID created by <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"nofollow\"><code>wp_insert_post</code></a>. Note: tags and category request are in name array as OP sample code.</p>\n\n<pre><code>add_action( 'rest_insert_post', 'wpse220930_rest_insert_post', 1, 3 );\nfunction wpse220930_rest_insert_post( $post, $request, $update = true )\n{\n if ( ! empty( $request['tags'] ) )\n wp_set_object_terms( $post-&gt;ID, $request['tags'], 'post_tag', $update );\n\n if ( ! empty( $request['categories'] ) )\n wp_set_object_terms( $post-&gt;ID, $request['categories'], 'category', $update );\n}\n</code></pre>\n" }, { "answer_id": 344294, "author": "Marcello Curto", "author_id": 153572, "author_profile": "https://wordpress.stackexchange.com/users/153572", "pm_score": 0, "selected": false, "text": "<p>Your array should look something like this:</p>\n\n<pre><code>var payload =\n {\n title : \"some title\",\n format : \"link\",\n tags: [1,2],\n categories: [3],\n content: \"http://someurl.com\",\n status: \"publish\"\n };\n</code></pre>\n\n<p>The numbers 1 and 2 reference the tags with the ID 1 and 2 and likewise 3 calls the category with the ID 3.</p>\n\n<p>I assume you don't want to reference only existing Tags and Categories, so you would have to first create them.</p>\n\n<p>The following function uses an array that includes your tag names (tag 1 and tag 2) and posts it to the <em>/wp-json/wp/v2/tags</em> endpoint. If the tag already exists, it returns the ID of that tag. If the tag doesn't exist, then it creates a new tag and returns the ID of it.</p>\n\n<p>postID is the ID of the post you want to add the tags to.</p>\n\n<pre><code> function getTagIDs(postID) {\n let tagNames = [tag 1, tag 2];\n let answers = tagNames.length;\n let receivedAnswers = 0;\n let tagIDList = [];\n $.each(tagNames, function(i, tagName) {\n let tagArguments = {\n 'name': tagName\n };\n let createPost = new XMLHttpRequest();\n let postURL = phpVariables.siteBaseURL + '/wp-json/wp/v2/tags';\n createPost.open('POST', postURL);\n createPost.setRequestHeader('X-WP-Nonce', phpVariables.nonce);\n createPost.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');\n createPost.onreadystatechange = function() {\n if (this.readyState === 4) {\n receivedAnswers++;\n responseText = JSON.parse(this.responseText);\n if (this.status === 400) {\n tagID = responseText.data.term_id;\n } else {\n tagID = responseText.id;\n }\n tagIDList.push(tagID);\n if (answers == receivedAnswers)\n PostToWpApi(postID, tagIDList);\n }\n };\n createPost.send(JSON.stringify(tagArguments));\n });\n };\n</code></pre>\n\n<p>Only after the function has saved all the tag IDs into the array tagIDList, will it execute another function called PostToWpApi.</p>\n\n<pre><code> function PostToWpApi(postID, tagIDs) {\n let postMetaData = {\n 'tags': tagIDs,\n };\n let createPost = new XMLHttpRequest();\n let postURL = phpVariables.siteBaseURL + '/wp-json/wp/v2/posts/' + postID;\n createPost.open('POST', postURL);\n createPost.setRequestHeader('X-WP-Nonce', phpVariables.nonce);\n createPost.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');\n createPost.send(JSON.stringify(postMetaData));\n };\n</code></pre>\n\n<p>I assume you have already done so, but for anyone else reading this, let me also explain where the <strong>phpVariables.siteBaseURL</strong> and <strong>phpVariables.nonce</strong> come from.</p>\n\n<p>Those variables were first generated in PHP and made accessible to JS via <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">wp_localize_script</a>.</p>\n\n<p>In whichever PHP file you enqueued your JS, you should also add the following:</p>\n\n<pre><code>public function enqueue(){\n wp_enqueue_script('scripthandle', 'urltoscript.com/script.js');\n wp_localize_script( 'scripthandle', 'phpVariables', array(\n 'nonce' =&gt; wp_create_nonce( 'wp_rest' ),\n 'siteBaseURL' =&gt; get_site_url(),\n ));\n}\n</code></pre>\n" } ]
2016/03/17
[ "https://wordpress.stackexchange.com/questions/220930", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37198/" ]
I'm using V2.0 and trying to create a post using the /posts endpoint. Here's the payload being sent with my request: ``` var payload = { title : "some title", format : "link", tags: ["tag1", "tag2"], categories: ["newsletter"], content: "http://someurl.com", status: "publish" }; ``` The posts are successfully being created and all other fields are added except for the category and tags. I see that both of them are supposed to take an array of strings. What am I missing here? Also, I've tried adding both categories and tags that already exist on the site, and brand new ones. both don't work.
You are using name in your terms. In default, try to use the existing term id ( in your case, cat ID and tag ID ). If you see <https://plugins.trac.wordpress.org/browser/rest-api/trunk/lib/endpoints/class-wp-rest-posts-controller.php#L918> they will handle your term with sanitize them into non-negative integer using `absint`. I hope this help. Here example code to hook `rest_insert_{$this->post_type}` to create terms ( tags and categories ) and set into post after post ID created by [`wp_insert_post`](https://developer.wordpress.org/reference/functions/wp_insert_post/). Note: tags and category request are in name array as OP sample code. ``` add_action( 'rest_insert_post', 'wpse220930_rest_insert_post', 1, 3 ); function wpse220930_rest_insert_post( $post, $request, $update = true ) { if ( ! empty( $request['tags'] ) ) wp_set_object_terms( $post->ID, $request['tags'], 'post_tag', $update ); if ( ! empty( $request['categories'] ) ) wp_set_object_terms( $post->ID, $request['categories'], 'category', $update ); } ```
220,935
<p>I'm trying to create a custom plugin where I want create a table when the plugin gets activated. I have tried the following code but it is not creating the table in the database </p> <pre><code>function create_plugin_database_table() { global $wpdb; $table_name = $wpdb-&gt;prefix . 'sandbox'; $sql = "CREATE TABLE $table_name ( id mediumint(9) unsigned NOT NULL AUTO_INCREMENT, title varchar(50) NOT NULL, structure longtext NOT NULL, author longtext NOT NULL, PRIMARY KEY (id) );"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } register_activation_hook( __FILE__, 'create_plugin_database_table' ); </code></pre>
[ { "answer_id": 220939, "author": "dipika", "author_id": 90752, "author_profile": "https://wordpress.stackexchange.com/users/90752", "pm_score": 5, "selected": true, "text": "<p>You have to include wpadmin/upgrade-functions.php file to create a table \nexample </p>\n\n<pre><code>function create_plugin_database_table()\n{\n global $table_prefix, $wpdb;\n\n $tblname = 'pin';\n $wp_track_table = $table_prefix . \"$tblname \";\n\n #Check to see if the table exists already, if not, then create it\n\n if($wpdb-&gt;get_var( \"show tables like '$wp_track_table'\" ) != $wp_track_table) \n {\n\n $sql = \"CREATE TABLE `\". $wp_track_table . \"` ( \";\n $sql .= \" `id` int(11) NOT NULL auto_increment, \";\n $sql .= \" `pincode` int(128) NOT NULL, \";\n $sql .= \" PRIMARY KEY `order_id` (`id`) \"; \n $sql .= \") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; \";\n require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );\n dbDelta($sql);\n }\n}\n\n register_activation_hook( __FILE__, 'create_plugin_database_table' );\n</code></pre>\n" }, { "answer_id": 289671, "author": "Pankaj Kumar", "author_id": 133931, "author_profile": "https://wordpress.stackexchange.com/users/133931", "pm_score": 1, "selected": false, "text": "<pre><code>function astro_plugin_table_install() {\n global $wpdb;\n global $charset_collate;\n $table_name = $wpdb-&gt;prefix . 'pin';\n $sql = \"CREATE TABLE IF NOT EXISTS $table_name (\n `id` bigint(20) NOT NULL AUTO_INCREMENT,\n `pincode` bignit(128) DEFAULT NOT NULL,\n PRIMARY KEY (`id`)\n )$charset_collate;\";\n require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );\n dbDelta( $sql );\n}\nregister_activation_hook(__FILE__,'astro_plugin_table_install');\n</code></pre>\n" }, { "answer_id": 296833, "author": "Jismon Thomas", "author_id": 138657, "author_profile": "https://wordpress.stackexchange.com/users/138657", "pm_score": 3, "selected": false, "text": "<p>This code works for me :</p>\n<pre><code>function installer(){\n include('installer.php');\n}\nregister_activation_hook(__file__, 'installer');\n</code></pre>\n<p>Then installer.php :</p>\n<pre><code>global $wpdb;\n$table_name = $wpdb-&gt;prefix . &quot;my_products&quot;;\n$my_products_db_version = '1.0.0';\n$charset_collate = $wpdb-&gt;get_charset_collate();\n\nif ( $wpdb-&gt;get_var(&quot;SHOW TABLES LIKE '{$table_name}'&quot;) != $table_name ) {\n\n $sql = &quot;CREATE TABLE $table_name (\n ID mediumint(9) NOT NULL AUTO_INCREMENT,\n `product-model` text NOT NULL,\n `product-name` text NOT NULL,\n `product-description` int(9) NOT NULL,\n PRIMARY KEY (ID)\n ) $charset_collate;&quot;;\n\n require_once(ABSPATH . 'wp-admin/includes/upgrade.php');\n dbDelta($sql);\n add_option('my_db_version', $my_products_db_version);\n}\n</code></pre>\n" } ]
2016/03/17
[ "https://wordpress.stackexchange.com/questions/220935", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90556/" ]
I'm trying to create a custom plugin where I want create a table when the plugin gets activated. I have tried the following code but it is not creating the table in the database ``` function create_plugin_database_table() { global $wpdb; $table_name = $wpdb->prefix . 'sandbox'; $sql = "CREATE TABLE $table_name ( id mediumint(9) unsigned NOT NULL AUTO_INCREMENT, title varchar(50) NOT NULL, structure longtext NOT NULL, author longtext NOT NULL, PRIMARY KEY (id) );"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } register_activation_hook( __FILE__, 'create_plugin_database_table' ); ```
You have to include wpadmin/upgrade-functions.php file to create a table example ``` function create_plugin_database_table() { global $table_prefix, $wpdb; $tblname = 'pin'; $wp_track_table = $table_prefix . "$tblname "; #Check to see if the table exists already, if not, then create it if($wpdb->get_var( "show tables like '$wp_track_table'" ) != $wp_track_table) { $sql = "CREATE TABLE `". $wp_track_table . "` ( "; $sql .= " `id` int(11) NOT NULL auto_increment, "; $sql .= " `pincode` int(128) NOT NULL, "; $sql .= " PRIMARY KEY `order_id` (`id`) "; $sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; "; require_once( ABSPATH . '/wp-admin/includes/upgrade.php' ); dbDelta($sql); } } register_activation_hook( __FILE__, 'create_plugin_database_table' ); ```
220,942
<p>I'm able to get certain info about the active theme using <code>wp_get_theme()</code>. For example:</p> <pre><code>$theme = wp_get_theme(); echo $theme-&gt;get( 'TextDomain' ); // twentyfifteen echo $theme-&gt;get( 'ThemeURI' ); // https://wordpress.org/themes/twentyfifteen/ </code></pre> <p>Is there a way to get the theme's slug? In this case it'd be <em>twentyfifteen</em>. Please note the theme's slug isn't always the same as the theme's text domain. I'd also like to avoid performing string replacement on the theme's URL if possible.</p> <p>Ref: <a href="https://codex.wordpress.org/Function_Reference/wp_get_theme" rel="noreferrer">https://codex.wordpress.org/Function_Reference/wp_get_theme</a></p>
[ { "answer_id": 220953, "author": "Bhavesh Nariya", "author_id": 90760, "author_profile": "https://wordpress.stackexchange.com/users/90760", "pm_score": -1, "selected": false, "text": "<p>Yo can get it by <code>get_template_directory_uri()</code></p>\n" }, { "answer_id": 220954, "author": "RRikesh", "author_id": 17305, "author_profile": "https://wordpress.stackexchange.com/users/17305", "pm_score": 3, "selected": false, "text": "<p>You can get the slug in the <code>options</code> table, stored under the name <code>stylesheet</code>.</p>\n\n<pre><code>echo get_option('stylesheet');\n</code></pre>\n" }, { "answer_id": 220955, "author": "henrywright", "author_id": 22599, "author_profile": "https://wordpress.stackexchange.com/users/22599", "pm_score": 2, "selected": true, "text": "<p>I found the closest thing to the theme's slug is the theme's directory name. This can be found using <code>get_template()</code>:</p>\n\n<pre><code>echo get_template(); // twentyfifteen\n</code></pre>\n\n<p>Ref: <a href=\"https://codex.wordpress.org/Function_Reference/get_template\" rel=\"nofollow\">https://codex.wordpress.org/Function_Reference/get_template</a></p>\n" }, { "answer_id": 319678, "author": "drdogbot7", "author_id": 105124, "author_profile": "https://wordpress.stackexchange.com/users/105124", "pm_score": 3, "selected": false, "text": "<p><strong>Short Answer: get_stylesheet();</strong></p>\n\n<p>There is technically no 'slug' value for a theme. The name of a given theme's directory is what you want.</p>\n\n<pre><code>get_template();\n</code></pre>\n\n<p>…will return the directory name of your theme, <strong><em>or the parent theme</em></strong> in the case that your current theme is a child theme.</p>\n\n<pre><code>get_option('stylesheet');\n</code></pre>\n\n<p>Will ALWAYS return the directory name of your active theme, whether or not it is a child theme.</p>\n\n<pre><code>get_stylesheet();\n</code></pre>\n\n<p>Will ALWAYS return the directory name of your active theme, whether or not it is a child theme. This function is essentially a wrapper for <code>get_option('stylesheet');</code>, except that it also applies a 'stylesheet' filter.</p>\n\n<pre><code>function get_stylesheet() {\n/**\n * Filters the name of current stylesheet.\n *\n * @since 1.5.0\n *\n * @param string $stylesheet Name of the current stylesheet.\n */\nreturn apply_filters( 'stylesheet', get_option( 'stylesheet' ) );\n}\n</code></pre>\n\n<p>I'm not sure what the 'stylesheet' filter does. Looks like it might have something to do with the customizer.</p>\n\n<p>In the vast majority of cases, these three functions would do the same thing, but <code>get_stylesheet();</code> seems like the safest bet.</p>\n" }, { "answer_id": 335088, "author": "Mahdi Yazdani", "author_id": 77814, "author_profile": "https://wordpress.stackexchange.com/users/77814", "pm_score": 2, "selected": false, "text": "<p><code>wp_get_theme</code> gets a <a href=\"https://developer.wordpress.org/reference/classes/wp_theme/\" rel=\"nofollow noreferrer\">WP_Theme</a> object for a theme.</p>\n\n<pre><code>$theme = wp_get_theme();\n\nif ( 'Conj' === $theme-&gt;name || 'conj' === $theme-&gt;template ) {\n // Do something...\n}\n</code></pre>\n" }, { "answer_id": 343985, "author": "ihsanberahim", "author_id": 102339, "author_profile": "https://wordpress.stackexchange.com/users/102339", "pm_score": 0, "selected": false, "text": "<pre><code>wp_get_active_and_valid_themes()\n</code></pre>\n\n<p>i found this in wp-settings.php</p>\n\n<pre><code>// Load the functions for the active theme, for both parent and child theme if applicable.\nforeach ( wp_get_active_and_valid_themes() as $theme ) {\n if ( file_exists( $theme . '/functions.php' ) ) {\n include $theme . '/functions.php';\n }\n}\n</code></pre>\n" } ]
2016/03/17
[ "https://wordpress.stackexchange.com/questions/220942", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22599/" ]
I'm able to get certain info about the active theme using `wp_get_theme()`. For example: ``` $theme = wp_get_theme(); echo $theme->get( 'TextDomain' ); // twentyfifteen echo $theme->get( 'ThemeURI' ); // https://wordpress.org/themes/twentyfifteen/ ``` Is there a way to get the theme's slug? In this case it'd be *twentyfifteen*. Please note the theme's slug isn't always the same as the theme's text domain. I'd also like to avoid performing string replacement on the theme's URL if possible. Ref: <https://codex.wordpress.org/Function_Reference/wp_get_theme>
I found the closest thing to the theme's slug is the theme's directory name. This can be found using `get_template()`: ``` echo get_template(); // twentyfifteen ``` Ref: <https://codex.wordpress.org/Function_Reference/get_template>
220,944
<p>Is it possible to use 2 shortcodes with the same function and change only the post type in the function depending on what shortcode it is?</p> <p>For instance, when I use <code>all_faq</code> shortcode the post type should be Faq. When I use <code>wordpress_faq</code> then the post type should be <code>wp-Faq</code>. It works now but is it possible to make the code shorter in one function? Like if <code>all_faq</code> is used change post type to <code>faq</code> and else if <code>wordpress faq</code> is used change post type to <code>wp-faq</code>.</p> <pre><code>//shortcode NORMAL FAQ add_shortcode( 'all_faq', 'display_custom_post_type' ); function display_custom_post_type(){ $args = array( 'post_type' =&gt; 'Faq', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; '-1' ); $string = ''; $query = new WP_Query( $args ); if( $query-&gt;have_posts() ){ $string .= '&lt;div class="container-fluid"&gt;'; $string .= '&lt;div class="grid-container"&gt;'; while( $query-&gt;have_posts() ){ $query-&gt;the_post(); $string .= '&lt;div class="sub-grid"&gt;'; $string .= '&lt;div class="faq-shortcode-title"&gt;' . get_the_title() . '&lt;/div&gt;'; $string .= '&lt;div class="faq-shortcode-content"&gt;' . get_the_content() . '&lt;/div&gt;'; $string .= '&lt;/div&gt;'; } $string .= '&lt;/div&gt;'; $string .= '&lt;/div&gt;'; } wp_reset_postdata(); return $string; } //shortcode WORDPRESS FAQ add_shortcode( 'wordpress_faq', 'display_wordpress_faq' ); function display_wordpress_faq(){ $args = array( 'post_type' =&gt; 'wp-Faq', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; '-1' ); $string = ''; $query = new WP_Query( $args ); if( $query-&gt;have_posts() ){ $string .= '&lt;div class="container-fluid"&gt;'; $string .= '&lt;div class="grid-container"&gt;'; while( $query-&gt;have_posts() ){ $query-&gt;the_post(); $string .= '&lt;div class="sub-grid"&gt;'; $string .= '&lt;div class="faq-shortcode-title"&gt;' . get_the_title() . '&lt;/div&gt;'; $string .= '&lt;div class="faq-shortcode-content"&gt;' . get_the_content() . '&lt;/div&gt;'; $string .= '&lt;/div&gt;'; } $string .= '&lt;/div&gt;'; $string .= '&lt;/div&gt;'; } wp_reset_postdata(); return $string; } </code></pre>
[ { "answer_id": 220945, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 1, "selected": false, "text": "<p>the callback function has 3 parameters and the 3rd is the tag name : </p>\n\n<pre><code>add_shortcode( 'all_faq', 'commonFunction' );\nadd_shortcode( 'wordpress_faq', 'commonFunction' );\n\n\nfunction commonFunction($attr, $content, $tag) {\n\n $cores = [\n \"all_faq\" =&gt; \"Faq\",\n \"wordpress_faq\" =&gt; \"wp-Faq\",\n ];\n\n\n $args = array(\n 'post_type' =&gt; $cores[$tag],\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; '-1'\n );\n\n\n // ...\n\n}\n</code></pre>\n" }, { "answer_id": 220947, "author": "Mat_", "author_id": 9122, "author_profile": "https://wordpress.stackexchange.com/users/9122", "pm_score": 0, "selected": false, "text": "<p>Maybe you could reverse the problem. \nWhat you need is simply add an argument to your shortcode and this way, you can have only one function and one shortcode.\nYou could have something like that at the beginning of you function :</p>\n\n<pre><code>$atts = shortcode_atts( array(\n 'posttype' =&gt; 'Faq'\n), $atts, 'all_faq' );\n\n$args = array(\n\n 'post_type' =&gt; $atts['posttype'],\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; '-1'\n);\n</code></pre>\n\n<p>Then, you can use your shortcode with a new parameter : <code>[all_faq posttype=\"Faq\"]</code></p>\n\n<p>Hope that helps.</p>\n" } ]
2016/03/17
[ "https://wordpress.stackexchange.com/questions/220944", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90756/" ]
Is it possible to use 2 shortcodes with the same function and change only the post type in the function depending on what shortcode it is? For instance, when I use `all_faq` shortcode the post type should be Faq. When I use `wordpress_faq` then the post type should be `wp-Faq`. It works now but is it possible to make the code shorter in one function? Like if `all_faq` is used change post type to `faq` and else if `wordpress faq` is used change post type to `wp-faq`. ``` //shortcode NORMAL FAQ add_shortcode( 'all_faq', 'display_custom_post_type' ); function display_custom_post_type(){ $args = array( 'post_type' => 'Faq', 'post_status' => 'publish', 'posts_per_page' => '-1' ); $string = ''; $query = new WP_Query( $args ); if( $query->have_posts() ){ $string .= '<div class="container-fluid">'; $string .= '<div class="grid-container">'; while( $query->have_posts() ){ $query->the_post(); $string .= '<div class="sub-grid">'; $string .= '<div class="faq-shortcode-title">' . get_the_title() . '</div>'; $string .= '<div class="faq-shortcode-content">' . get_the_content() . '</div>'; $string .= '</div>'; } $string .= '</div>'; $string .= '</div>'; } wp_reset_postdata(); return $string; } //shortcode WORDPRESS FAQ add_shortcode( 'wordpress_faq', 'display_wordpress_faq' ); function display_wordpress_faq(){ $args = array( 'post_type' => 'wp-Faq', 'post_status' => 'publish', 'posts_per_page' => '-1' ); $string = ''; $query = new WP_Query( $args ); if( $query->have_posts() ){ $string .= '<div class="container-fluid">'; $string .= '<div class="grid-container">'; while( $query->have_posts() ){ $query->the_post(); $string .= '<div class="sub-grid">'; $string .= '<div class="faq-shortcode-title">' . get_the_title() . '</div>'; $string .= '<div class="faq-shortcode-content">' . get_the_content() . '</div>'; $string .= '</div>'; } $string .= '</div>'; $string .= '</div>'; } wp_reset_postdata(); return $string; } ```
the callback function has 3 parameters and the 3rd is the tag name : ``` add_shortcode( 'all_faq', 'commonFunction' ); add_shortcode( 'wordpress_faq', 'commonFunction' ); function commonFunction($attr, $content, $tag) { $cores = [ "all_faq" => "Faq", "wordpress_faq" => "wp-Faq", ]; $args = array( 'post_type' => $cores[$tag], 'post_status' => 'publish', 'posts_per_page' => '-1' ); // ... } ```
220,946
<p>I am creating a WordPress plugin to help people protect their content from being copied. There are many plugins to protect content from being copied when JavaScript is on, but no plugins which protect content even when JS is off.</p> <p>How can I add the following custom CSS code in a PHP file, to protect content copy via CSS, and then install the PHP file as a WordPress plugin?</p> <pre><code>body { user-select: none; -moz-user-select: none; -webkit-user-select: none; -o-user-select: none; } </code></pre>
[ { "answer_id": 220948, "author": "RiaanP", "author_id": 66345, "author_profile": "https://wordpress.stackexchange.com/users/66345", "pm_score": 2, "selected": true, "text": "<p>I know this sounds like it's a good idea, but anyone can simply just view the source of the page and take whatever they want from there. They can also simply just hit Ctrl+S on their keyboard and save that entire page to their hard drive. They could even screenshot the page and use OCR technology to simply pull the text out if they wanted to. There's also Photoshop.</p>\n\n<p>In my opinion, this is a waste of time.</p>\n\n<p>With that out of the way, you could start by looking here: <a href=\"https://codex.wordpress.org/Writing_a_Plugin\" rel=\"nofollow\">https://codex.wordpress.org/Writing_a_Plugin</a></p>\n\n<p>That will cover a lot of important aspects of creating a plugin.</p>\n\n<p>Then, to understand the most simplest form of a plugin, have a look at the hello.php (Hello Dolly plugin) file in your Wordpress' wp-content/plugins/ directory. Changing that will allow you to achieve what you want.</p>\n\n<p>If you simply want to add this to your own site, you can do this in the footer:</p>\n\n<pre><code>&lt;?php\n echo '&lt;style&gt;body {\n user-select: none;\n -moz-user-select: none;\n -webkit-user-select: none;\n -o-user-select: none;\n}&lt;/style&gt;';\n?&gt;\n</code></pre>\n" }, { "answer_id": 220952, "author": "Alek Hartzog", "author_id": 87627, "author_profile": "https://wordpress.stackexchange.com/users/87627", "pm_score": 0, "selected": false, "text": "<p>You can hook that into a filter that applies on every page.</p>\n\n<pre><code>function block_copy(){\n echo '&lt;style&gt;body {\n user-select: none;\n -moz-user-select: none;\n -webkit-user-select: none;\n -o-user-select: none;\n }&lt;/style&gt;';\n}\nadd_action('wp_head', 'block_copy');\n</code></pre>\n\n<p>Drop that into your <code>functions.php</code></p>\n\n<p>If you're going to be using one header or footer file on each page you could also just paste the straight tag content in those.</p>\n" } ]
2016/03/17
[ "https://wordpress.stackexchange.com/questions/220946", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90758/" ]
I am creating a WordPress plugin to help people protect their content from being copied. There are many plugins to protect content from being copied when JavaScript is on, but no plugins which protect content even when JS is off. How can I add the following custom CSS code in a PHP file, to protect content copy via CSS, and then install the PHP file as a WordPress plugin? ``` body { user-select: none; -moz-user-select: none; -webkit-user-select: none; -o-user-select: none; } ```
I know this sounds like it's a good idea, but anyone can simply just view the source of the page and take whatever they want from there. They can also simply just hit Ctrl+S on their keyboard and save that entire page to their hard drive. They could even screenshot the page and use OCR technology to simply pull the text out if they wanted to. There's also Photoshop. In my opinion, this is a waste of time. With that out of the way, you could start by looking here: <https://codex.wordpress.org/Writing_a_Plugin> That will cover a lot of important aspects of creating a plugin. Then, to understand the most simplest form of a plugin, have a look at the hello.php (Hello Dolly plugin) file in your Wordpress' wp-content/plugins/ directory. Changing that will allow you to achieve what you want. If you simply want to add this to your own site, you can do this in the footer: ``` <?php echo '<style>body { user-select: none; -moz-user-select: none; -webkit-user-select: none; -o-user-select: none; }</style>'; ?> ```
220,979
<p>I'd like to include in my website a feature for users to only see posts from a certain author and a certain category. I'm able to do it separately but I can't seem to understand how to do it simultaneously.</p>
[ { "answer_id": 220980, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": -1, "selected": false, "text": "<p>use WP_Query() author parameters &amp; category parameters</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters\" rel=\"nofollow\">WP_Query Author Parameters</a></p>\n\n<p>similarly for certain category use WP_Query() category parameters.</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters\" rel=\"nofollow\">WP_Query Category Parameters</a></p>\n\n<p>if category is custom taxonomy then use the tax_query patameter in WP_Query().</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\">WP_QUery Taxonomy Parameters</a></p>\n\n<pre><code>&lt;?php\n/**\n* Query Posts with WP_Query.\n* For complete list of parametes follow link below.\n* CODEX: http://codex.wordpress.org/Class_Reference/WP_Query\n*/\n\n$args = array( \n\n /**\n * Author id : (int) author id.\n * use - to excluse author ID\n * e.g -1 will exclude -1 authors posts.\n */\n 'author' =&gt; 1,\n\n /**\n * Author name : use 'user_nicename' (NOT name)\n */\n 'author_name' =&gt; 'admin',\n\n /**\n * Show posts associated with certain category.\n * cat : (int) - use category id.\n */\n 'cat' =&gt; 5,\n\n /**\n * category_name : (string) - use category slug (NOT name).\n * can also pass comma seperated list\n * e.g 'news', 'events', etc...\n */\n 'category_name' =&gt; 'news', //\n\n 'posts_per_page' =&gt; 10,\n 'order' =&gt; 'DESC',\n 'orderby' =&gt; 'date',\n);\n\n$the_query = new WP_Query( $args );\n\n// The Loop\nif ( $the_query-&gt;have_posts() ) :\nwhile ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n // do something...\nendwhile;\nendif;\n\n// Reset Post Data\nwp_reset_postdata();\n?&gt;\n</code></pre>\n" }, { "answer_id": 220981, "author": "Kieran McClung", "author_id": 52293, "author_profile": "https://wordpress.stackexchange.com/users/52293", "pm_score": 3, "selected": true, "text": "<p>If you want your visitors to choose the category and author you can use the code below.</p>\n\n<p>If your loop in the template hasn't been changed you should get away with adding a query to the URL like so:</p>\n\n<p><code>http://website.com/post-title/?author=1&amp;cat=1</code></p>\n\n<p>If you have a custom query you could do the following:</p>\n\n<pre><code>$author = $_GET['author']; //Get Author ID from query\n$cat = $_GET['cat']; //Get Category ID from query string\n\n$args = array(\n 'posts_per_page' =&gt; 10\n);\n\nif ( $author ) { //If $author found add it to custom query\n $args['author'] = $author;\n}\n\nif ( $cat ) { //If $cat found add it to custom query\n $args['cat'] = $cat;\n}\n\n$custom_query = new WP_Query( $args );\n\nif ( $custom_query-&gt;have_posts() ) :\n while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post();\n //post stuff\n endwhile;\nelse :\n echo 'No posts found...';\nendif;\n</code></pre>\n\n<p>Then in your template:</p>\n\n<pre><code>&lt;form class=\"post-filters\"&gt;\n &lt;select name=\"author\"&gt;\n &lt;?php\n $author_options = array(\n '1' =&gt; 'Author 1',\n '2' =&gt; 'Author 2',\n '3' =&gt; 'Author 3'\n );\n\n foreach( $orderby_options as $value =&gt; $label ) {\n echo '&lt;option ' . selected( $_GET['author'], $value ) . ' value=\"' . $value . '\"&gt;$label&lt;/option&gt;';\n }\n ?&gt;\n &lt;/select&gt;\n &lt;select name=\"cat\"&gt;\n &lt;?php\n $cat_options = array(\n '1' =&gt; 'Category 1',\n '2' =&gt; 'Category 2'\n );\n\n foreach( $orderby_options as $value =&gt; $label ) {\n echo '&lt;option ' . selected( $_GET['cat'], $value ) . ' value=\"' . $value. '\"&gt;$label&lt;/option&gt;';\n }\n ?&gt;\n &lt;/select&gt;\n &lt;button type=\"submit\"&gt;Show Posts&lt;/button&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Else (forced to specific author / category basically what talentedaamer said)</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 10,\n 'author' =&gt; 1, //Author ID\n 'cat' =&gt; 1 //Category ID\n);\n\n$custom_query = new WP_Query( $args );\n\nif ( $custom_query-&gt;have_posts() ) :\n while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post();\n //post stuff\n endwhile;\nelse :\n echo 'No posts found...';\nendif;\n</code></pre>\n" } ]
2016/03/17
[ "https://wordpress.stackexchange.com/questions/220979", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90779/" ]
I'd like to include in my website a feature for users to only see posts from a certain author and a certain category. I'm able to do it separately but I can't seem to understand how to do it simultaneously.
If you want your visitors to choose the category and author you can use the code below. If your loop in the template hasn't been changed you should get away with adding a query to the URL like so: `http://website.com/post-title/?author=1&cat=1` If you have a custom query you could do the following: ``` $author = $_GET['author']; //Get Author ID from query $cat = $_GET['cat']; //Get Category ID from query string $args = array( 'posts_per_page' => 10 ); if ( $author ) { //If $author found add it to custom query $args['author'] = $author; } if ( $cat ) { //If $cat found add it to custom query $args['cat'] = $cat; } $custom_query = new WP_Query( $args ); if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); //post stuff endwhile; else : echo 'No posts found...'; endif; ``` Then in your template: ``` <form class="post-filters"> <select name="author"> <?php $author_options = array( '1' => 'Author 1', '2' => 'Author 2', '3' => 'Author 3' ); foreach( $orderby_options as $value => $label ) { echo '<option ' . selected( $_GET['author'], $value ) . ' value="' . $value . '">$label</option>'; } ?> </select> <select name="cat"> <?php $cat_options = array( '1' => 'Category 1', '2' => 'Category 2' ); foreach( $orderby_options as $value => $label ) { echo '<option ' . selected( $_GET['cat'], $value ) . ' value="' . $value. '">$label</option>'; } ?> </select> <button type="submit">Show Posts</button> </form> ``` Else (forced to specific author / category basically what talentedaamer said) ``` $args = array( 'posts_per_page' => 10, 'author' => 1, //Author ID 'cat' => 1 //Category ID ); $custom_query = new WP_Query( $args ); if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); //post stuff endwhile; else : echo 'No posts found...'; endif; ```
221,019
<p>this is my source</p> <pre><code> global $page; $page_exists = $page-&gt;post_title; $another_db_user = 'user'; $another_db_pass = 'pass'; $another_db_name = 'name'; $another_db_host = 'localhost'; $another_tb_prefix = 'wp_'; $mydb = new wpdb($another_db_user,$another_db_pass,$another_db_name,$another_db_host); $mydb-&gt;set_prefix($another_tb_prefix); $result = $mydb-&gt;get_results(" SELECT m0.post_title, m0.id, m0.post_name, m0.guid FROM ( select post_title, id, guid, post_name from wp_posts where post_type = 'bio' AND post_status = 'publish' ) AS m0 "); foreach ($result as $value) { if( $value-&gt;post_title == $page_exists ) { } else { $my_access = Array( 'post_author' =&gt; '1', 'post_title' =&gt; ''.$value-&gt;post_title.'', 'post_status' =&gt; 'publish', 'comment_status' =&gt; 'closed', 'ping_status' =&gt; 'closed', 'post_name' =&gt; ''.$value-&gt;post_name.'', 'post_type' =&gt; 'page', 'post_parent' =&gt; '115822', 'page_template' =&gt; 'template-profile-info.php' ); wp_insert_post($my_access); } } </code></pre>
[ { "answer_id": 220980, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": -1, "selected": false, "text": "<p>use WP_Query() author parameters &amp; category parameters</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters\" rel=\"nofollow\">WP_Query Author Parameters</a></p>\n\n<p>similarly for certain category use WP_Query() category parameters.</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters\" rel=\"nofollow\">WP_Query Category Parameters</a></p>\n\n<p>if category is custom taxonomy then use the tax_query patameter in WP_Query().</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\">WP_QUery Taxonomy Parameters</a></p>\n\n<pre><code>&lt;?php\n/**\n* Query Posts with WP_Query.\n* For complete list of parametes follow link below.\n* CODEX: http://codex.wordpress.org/Class_Reference/WP_Query\n*/\n\n$args = array( \n\n /**\n * Author id : (int) author id.\n * use - to excluse author ID\n * e.g -1 will exclude -1 authors posts.\n */\n 'author' =&gt; 1,\n\n /**\n * Author name : use 'user_nicename' (NOT name)\n */\n 'author_name' =&gt; 'admin',\n\n /**\n * Show posts associated with certain category.\n * cat : (int) - use category id.\n */\n 'cat' =&gt; 5,\n\n /**\n * category_name : (string) - use category slug (NOT name).\n * can also pass comma seperated list\n * e.g 'news', 'events', etc...\n */\n 'category_name' =&gt; 'news', //\n\n 'posts_per_page' =&gt; 10,\n 'order' =&gt; 'DESC',\n 'orderby' =&gt; 'date',\n);\n\n$the_query = new WP_Query( $args );\n\n// The Loop\nif ( $the_query-&gt;have_posts() ) :\nwhile ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n // do something...\nendwhile;\nendif;\n\n// Reset Post Data\nwp_reset_postdata();\n?&gt;\n</code></pre>\n" }, { "answer_id": 220981, "author": "Kieran McClung", "author_id": 52293, "author_profile": "https://wordpress.stackexchange.com/users/52293", "pm_score": 3, "selected": true, "text": "<p>If you want your visitors to choose the category and author you can use the code below.</p>\n\n<p>If your loop in the template hasn't been changed you should get away with adding a query to the URL like so:</p>\n\n<p><code>http://website.com/post-title/?author=1&amp;cat=1</code></p>\n\n<p>If you have a custom query you could do the following:</p>\n\n<pre><code>$author = $_GET['author']; //Get Author ID from query\n$cat = $_GET['cat']; //Get Category ID from query string\n\n$args = array(\n 'posts_per_page' =&gt; 10\n);\n\nif ( $author ) { //If $author found add it to custom query\n $args['author'] = $author;\n}\n\nif ( $cat ) { //If $cat found add it to custom query\n $args['cat'] = $cat;\n}\n\n$custom_query = new WP_Query( $args );\n\nif ( $custom_query-&gt;have_posts() ) :\n while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post();\n //post stuff\n endwhile;\nelse :\n echo 'No posts found...';\nendif;\n</code></pre>\n\n<p>Then in your template:</p>\n\n<pre><code>&lt;form class=\"post-filters\"&gt;\n &lt;select name=\"author\"&gt;\n &lt;?php\n $author_options = array(\n '1' =&gt; 'Author 1',\n '2' =&gt; 'Author 2',\n '3' =&gt; 'Author 3'\n );\n\n foreach( $orderby_options as $value =&gt; $label ) {\n echo '&lt;option ' . selected( $_GET['author'], $value ) . ' value=\"' . $value . '\"&gt;$label&lt;/option&gt;';\n }\n ?&gt;\n &lt;/select&gt;\n &lt;select name=\"cat\"&gt;\n &lt;?php\n $cat_options = array(\n '1' =&gt; 'Category 1',\n '2' =&gt; 'Category 2'\n );\n\n foreach( $orderby_options as $value =&gt; $label ) {\n echo '&lt;option ' . selected( $_GET['cat'], $value ) . ' value=\"' . $value. '\"&gt;$label&lt;/option&gt;';\n }\n ?&gt;\n &lt;/select&gt;\n &lt;button type=\"submit\"&gt;Show Posts&lt;/button&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Else (forced to specific author / category basically what talentedaamer said)</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 10,\n 'author' =&gt; 1, //Author ID\n 'cat' =&gt; 1 //Category ID\n);\n\n$custom_query = new WP_Query( $args );\n\nif ( $custom_query-&gt;have_posts() ) :\n while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post();\n //post stuff\n endwhile;\nelse :\n echo 'No posts found...';\nendif;\n</code></pre>\n" } ]
2016/03/18
[ "https://wordpress.stackexchange.com/questions/221019", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86437/" ]
this is my source ``` global $page; $page_exists = $page->post_title; $another_db_user = 'user'; $another_db_pass = 'pass'; $another_db_name = 'name'; $another_db_host = 'localhost'; $another_tb_prefix = 'wp_'; $mydb = new wpdb($another_db_user,$another_db_pass,$another_db_name,$another_db_host); $mydb->set_prefix($another_tb_prefix); $result = $mydb->get_results(" SELECT m0.post_title, m0.id, m0.post_name, m0.guid FROM ( select post_title, id, guid, post_name from wp_posts where post_type = 'bio' AND post_status = 'publish' ) AS m0 "); foreach ($result as $value) { if( $value->post_title == $page_exists ) { } else { $my_access = Array( 'post_author' => '1', 'post_title' => ''.$value->post_title.'', 'post_status' => 'publish', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_name' => ''.$value->post_name.'', 'post_type' => 'page', 'post_parent' => '115822', 'page_template' => 'template-profile-info.php' ); wp_insert_post($my_access); } } ```
If you want your visitors to choose the category and author you can use the code below. If your loop in the template hasn't been changed you should get away with adding a query to the URL like so: `http://website.com/post-title/?author=1&cat=1` If you have a custom query you could do the following: ``` $author = $_GET['author']; //Get Author ID from query $cat = $_GET['cat']; //Get Category ID from query string $args = array( 'posts_per_page' => 10 ); if ( $author ) { //If $author found add it to custom query $args['author'] = $author; } if ( $cat ) { //If $cat found add it to custom query $args['cat'] = $cat; } $custom_query = new WP_Query( $args ); if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); //post stuff endwhile; else : echo 'No posts found...'; endif; ``` Then in your template: ``` <form class="post-filters"> <select name="author"> <?php $author_options = array( '1' => 'Author 1', '2' => 'Author 2', '3' => 'Author 3' ); foreach( $orderby_options as $value => $label ) { echo '<option ' . selected( $_GET['author'], $value ) . ' value="' . $value . '">$label</option>'; } ?> </select> <select name="cat"> <?php $cat_options = array( '1' => 'Category 1', '2' => 'Category 2' ); foreach( $orderby_options as $value => $label ) { echo '<option ' . selected( $_GET['cat'], $value ) . ' value="' . $value. '">$label</option>'; } ?> </select> <button type="submit">Show Posts</button> </form> ``` Else (forced to specific author / category basically what talentedaamer said) ``` $args = array( 'posts_per_page' => 10, 'author' => 1, //Author ID 'cat' => 1 //Category ID ); $custom_query = new WP_Query( $args ); if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); //post stuff endwhile; else : echo 'No posts found...'; endif; ```
221,092
<p>I use Bootstrap Modals plugin. I have put the following code for modal in my page-contact.php.</p> <pre><code>&lt;h2&gt;Small Modal&lt;/h2&gt; &lt;button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal"&gt;Open Small Modal&lt;/button&gt; &lt;div class="modal fade" id="myModal" role="dialog"&gt; &lt;div class="modal-dialog modal-sm"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;×&lt;/button&gt; &lt;h4 class="modal-title"&gt;Modal Header&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;This is a small modal.&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ` </code></pre> <p>After clicking the button open modal, modal is appearing, and suddenly disappears. Weird is also that in the right top angle I have an x for closing the modal. Can someone advice?</p> <p>Regards, Ivana</p>
[ { "answer_id": 220980, "author": "Aamer Shahzad", "author_id": 42772, "author_profile": "https://wordpress.stackexchange.com/users/42772", "pm_score": -1, "selected": false, "text": "<p>use WP_Query() author parameters &amp; category parameters</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Author_Parameters\" rel=\"nofollow\">WP_Query Author Parameters</a></p>\n\n<p>similarly for certain category use WP_Query() category parameters.</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters\" rel=\"nofollow\">WP_Query Category Parameters</a></p>\n\n<p>if category is custom taxonomy then use the tax_query patameter in WP_Query().</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"nofollow\">WP_QUery Taxonomy Parameters</a></p>\n\n<pre><code>&lt;?php\n/**\n* Query Posts with WP_Query.\n* For complete list of parametes follow link below.\n* CODEX: http://codex.wordpress.org/Class_Reference/WP_Query\n*/\n\n$args = array( \n\n /**\n * Author id : (int) author id.\n * use - to excluse author ID\n * e.g -1 will exclude -1 authors posts.\n */\n 'author' =&gt; 1,\n\n /**\n * Author name : use 'user_nicename' (NOT name)\n */\n 'author_name' =&gt; 'admin',\n\n /**\n * Show posts associated with certain category.\n * cat : (int) - use category id.\n */\n 'cat' =&gt; 5,\n\n /**\n * category_name : (string) - use category slug (NOT name).\n * can also pass comma seperated list\n * e.g 'news', 'events', etc...\n */\n 'category_name' =&gt; 'news', //\n\n 'posts_per_page' =&gt; 10,\n 'order' =&gt; 'DESC',\n 'orderby' =&gt; 'date',\n);\n\n$the_query = new WP_Query( $args );\n\n// The Loop\nif ( $the_query-&gt;have_posts() ) :\nwhile ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n // do something...\nendwhile;\nendif;\n\n// Reset Post Data\nwp_reset_postdata();\n?&gt;\n</code></pre>\n" }, { "answer_id": 220981, "author": "Kieran McClung", "author_id": 52293, "author_profile": "https://wordpress.stackexchange.com/users/52293", "pm_score": 3, "selected": true, "text": "<p>If you want your visitors to choose the category and author you can use the code below.</p>\n\n<p>If your loop in the template hasn't been changed you should get away with adding a query to the URL like so:</p>\n\n<p><code>http://website.com/post-title/?author=1&amp;cat=1</code></p>\n\n<p>If you have a custom query you could do the following:</p>\n\n<pre><code>$author = $_GET['author']; //Get Author ID from query\n$cat = $_GET['cat']; //Get Category ID from query string\n\n$args = array(\n 'posts_per_page' =&gt; 10\n);\n\nif ( $author ) { //If $author found add it to custom query\n $args['author'] = $author;\n}\n\nif ( $cat ) { //If $cat found add it to custom query\n $args['cat'] = $cat;\n}\n\n$custom_query = new WP_Query( $args );\n\nif ( $custom_query-&gt;have_posts() ) :\n while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post();\n //post stuff\n endwhile;\nelse :\n echo 'No posts found...';\nendif;\n</code></pre>\n\n<p>Then in your template:</p>\n\n<pre><code>&lt;form class=\"post-filters\"&gt;\n &lt;select name=\"author\"&gt;\n &lt;?php\n $author_options = array(\n '1' =&gt; 'Author 1',\n '2' =&gt; 'Author 2',\n '3' =&gt; 'Author 3'\n );\n\n foreach( $orderby_options as $value =&gt; $label ) {\n echo '&lt;option ' . selected( $_GET['author'], $value ) . ' value=\"' . $value . '\"&gt;$label&lt;/option&gt;';\n }\n ?&gt;\n &lt;/select&gt;\n &lt;select name=\"cat\"&gt;\n &lt;?php\n $cat_options = array(\n '1' =&gt; 'Category 1',\n '2' =&gt; 'Category 2'\n );\n\n foreach( $orderby_options as $value =&gt; $label ) {\n echo '&lt;option ' . selected( $_GET['cat'], $value ) . ' value=\"' . $value. '\"&gt;$label&lt;/option&gt;';\n }\n ?&gt;\n &lt;/select&gt;\n &lt;button type=\"submit\"&gt;Show Posts&lt;/button&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Else (forced to specific author / category basically what talentedaamer said)</p>\n\n<pre><code>$args = array(\n 'posts_per_page' =&gt; 10,\n 'author' =&gt; 1, //Author ID\n 'cat' =&gt; 1 //Category ID\n);\n\n$custom_query = new WP_Query( $args );\n\nif ( $custom_query-&gt;have_posts() ) :\n while ( $custom_query-&gt;have_posts() ) : $custom_query-&gt;the_post();\n //post stuff\n endwhile;\nelse :\n echo 'No posts found...';\nendif;\n</code></pre>\n" } ]
2016/03/18
[ "https://wordpress.stackexchange.com/questions/221092", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90864/" ]
I use Bootstrap Modals plugin. I have put the following code for modal in my page-contact.php. ``` <h2>Small Modal</h2> <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <p>This is a small modal.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> ` ``` After clicking the button open modal, modal is appearing, and suddenly disappears. Weird is also that in the right top angle I have an x for closing the modal. Can someone advice? Regards, Ivana
If you want your visitors to choose the category and author you can use the code below. If your loop in the template hasn't been changed you should get away with adding a query to the URL like so: `http://website.com/post-title/?author=1&cat=1` If you have a custom query you could do the following: ``` $author = $_GET['author']; //Get Author ID from query $cat = $_GET['cat']; //Get Category ID from query string $args = array( 'posts_per_page' => 10 ); if ( $author ) { //If $author found add it to custom query $args['author'] = $author; } if ( $cat ) { //If $cat found add it to custom query $args['cat'] = $cat; } $custom_query = new WP_Query( $args ); if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); //post stuff endwhile; else : echo 'No posts found...'; endif; ``` Then in your template: ``` <form class="post-filters"> <select name="author"> <?php $author_options = array( '1' => 'Author 1', '2' => 'Author 2', '3' => 'Author 3' ); foreach( $orderby_options as $value => $label ) { echo '<option ' . selected( $_GET['author'], $value ) . ' value="' . $value . '">$label</option>'; } ?> </select> <select name="cat"> <?php $cat_options = array( '1' => 'Category 1', '2' => 'Category 2' ); foreach( $orderby_options as $value => $label ) { echo '<option ' . selected( $_GET['cat'], $value ) . ' value="' . $value. '">$label</option>'; } ?> </select> <button type="submit">Show Posts</button> </form> ``` Else (forced to specific author / category basically what talentedaamer said) ``` $args = array( 'posts_per_page' => 10, 'author' => 1, //Author ID 'cat' => 1 //Category ID ); $custom_query = new WP_Query( $args ); if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); //post stuff endwhile; else : echo 'No posts found...'; endif; ```
221,108
<p>Just finished moving my local Wordpress install to a live server. Imported my DB, and uploaded my core files to the new server. I also changed the siteurl and home fields in the wp_options table and added the new credentials to the new wp_config file.</p> <p>Basically followed all the directions <a href="http://www.wpbeginner.com/wp-tutorials/how-to-move-wordpress-from-local-server-to-live-site/" rel="nofollow">here</a>.</p> <p>The issue is my links are not working. They're redirecting I assume to the parent Wordpress index install.</p> <p>Heres the file structure of my server</p> <pre><code>-public_html (I have 4 add-on domains here) ----merchantsofdesign.ca (also a wordpress install) --------clients ------------creditassur ----------------wordpress (core files are here) </code></pre> <p>Can I even have a parent folder and child folder both running Wordpress? </p> <p>Thanks and hope that makes sense</p>
[ { "answer_id": 221111, "author": "nicogaldo", "author_id": 87880, "author_profile": "https://wordpress.stackexchange.com/users/87880", "pm_score": 4, "selected": true, "text": "<p>Go to settings » permalinks and save changes again.</p>\n" }, { "answer_id": 399291, "author": "Imthiyas Jawfar", "author_id": 215911, "author_profile": "https://wordpress.stackexchange.com/users/215911", "pm_score": 0, "selected": false, "text": "<p>I also faced this issue\nI just fixed it by creating new .htaccess file</p>\n<pre>\n # BEGIN WordPress\n\nRewriteEngine On\nRewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n\n# END WordPress\n</pre>\n<p>Thanks.</p>\n" } ]
2016/03/18
[ "https://wordpress.stackexchange.com/questions/221108", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87989/" ]
Just finished moving my local Wordpress install to a live server. Imported my DB, and uploaded my core files to the new server. I also changed the siteurl and home fields in the wp\_options table and added the new credentials to the new wp\_config file. Basically followed all the directions [here](http://www.wpbeginner.com/wp-tutorials/how-to-move-wordpress-from-local-server-to-live-site/). The issue is my links are not working. They're redirecting I assume to the parent Wordpress index install. Heres the file structure of my server ``` -public_html (I have 4 add-on domains here) ----merchantsofdesign.ca (also a wordpress install) --------clients ------------creditassur ----------------wordpress (core files are here) ``` Can I even have a parent folder and child folder both running Wordpress? Thanks and hope that makes sense
Go to settings » permalinks and save changes again.
221,201
<p>I would like to style two MediaElement players on the same page differently, and figured out the easier way to do this (compared to adding a completely new shortcode and enqueueing a new stylesheet, <a href="https://stackoverflow.com/questions/36111811/wordpress-4-4-media-player-different-css-stylesheet-depending-on-shortcode">which I couldn't get working either</a>) is to assign a different class to the audio shortcode of player A.</p> <p><a href="https://developer.wordpress.org/reference/functions/wp_audio_shortcode/#source-code" rel="nofollow noreferrer">The WordPress code reference</a> mentions adding a <code>class</code> attribute to the shortcode, <strong>but I can't get it to work.</strong> For instance, writing</p> <pre><code>[audio class="miniplayer" mp3="http://localhost/working_url.mp3"][/audio] </code></pre> <p>does give me a working player, but I can't see "miniplayer" assigned to it anywhere in my Firefox console. So how do I assign a class to my shortcode properly?</p>
[ { "answer_id": 221203, "author": "Jevuska", "author_id": 18731, "author_profile": "https://wordpress.stackexchange.com/users/18731", "pm_score": 2, "selected": false, "text": "<p>There are no options to add <code>class</code> as parameter in shortcode <a href=\"https://codex.wordpress.org/Audio_Shortcode\" rel=\"nofollow noreferrer\"><code>[audio]</code></a>. You need to use filter <a href=\"https://developer.wordpress.org/reference/hooks/wp_audio_shortcode_class/\" rel=\"nofollow noreferrer\"><code>wp_audio_shortcode_class</code></a> to change default class <code>wp-audio-shortcode</code> or add additional class. Here example code to filter it ( add into <code>functions.php</code> theme files ).</p>\n\n<pre><code>add_filter( 'wp_audio_shortcode_class', 'wpse221201_audio_shortcode_class', 1, 1 );\nfunction wpse221201_audio_shortcode_class( $class )\n{\n $class .= ' my-class'; /* additional class */\n return $class;\n}\n</code></pre>\n\n<p>For multiple shortcode <code>[audio]</code>, you can use <code>static $instance</code> to loop ( if you need to use global variable, take a look <a href=\"https://wordpress.stackexchange.com/a/221205/18731\">@iantsch answer</a> ):</p>\n\n<pre><code>add_filter( 'wp_audio_shortcode_class', 'wpse221201_audio_shortcode_class', 1, 1 );\nfunction wpse221201_audio_shortcode_class( $class )\n{\n static $instance = 0;\n $instance++;\n\n /* class name with increament number, change my-audio-class */\n $class = sprintf( '%s my-audio-class-%d', $class, $instance );\n return $class;\n}\n</code></pre>\n\n<p>Here another option for next <code>WordPress v4.5</code>, we hook <a href=\"https://developer.wordpress.org/reference/hooks/shortcode_atts_shortcode/\" rel=\"nofollow noreferrer\"><code>shortcode_atts_{$shortcode}</code></a> and target specific shortcode.</p>\n\n<pre><code>add_filter( 'shortcode_atts_audio', 'wpse221201_shortcode_atts_audio', 1, 4 );\nfunction wpse221201_shortcode_atts_audio( $out, $pairs, $atts, $shortcode )\n{\n //static $instance = 0;\n //$instance++;\n\n /* target parameter 'mp3' with its file\n or add your own parameter ( $atts[whatever] ) and use it in conditional statement\n */\n if ( isset( $out['mp3'] ) &amp;&amp; isset( $out['class'] ) &amp;&amp; 'source.mp3' == $out['mp3'] )\n $out['class'] = sprintf( '%s my-class', $out['class'] );//additional class\n\n return $out;\n}\n</code></pre>\n" }, { "answer_id": 221205, "author": "iantsch", "author_id": 90220, "author_profile": "https://wordpress.stackexchange.com/users/90220", "pm_score": 1, "selected": true, "text": "<p>WordPress allows least three options to manipulate the code to your needs.</p>\n\n<ol>\n<li><p>Use a global variable that you increment with @Jevuska 's answer.</p>\n\n<pre><code>global $my_audio_player_count;\n$my_audio_player_count = 0;\n\nadd_filter( 'wp_audio_shortcode_class', 'wpse221201_audio_shortcode_class', 1, 1 );\nfunction wpse221201_audio_shortcode_class( $class ) {\n global $my_audio_player_count;\n $class .= ' my-audio-player-'.$my_audio_player_count++;\n return $class;\n}\n</code></pre></li>\n<li><p>Remove the built-in shortcode and add your own</p>\n\n<pre><code>remove_shortcode('audio');\nadd_shortcode('audio', 'my_audio_shortcode');\n\nfunction my_audio_shortcode($args) {\n //TODO: Insert your own version of the shortcode\n}\n</code></pre></li>\n<li><p>Use the <code>wp_audio_shortcode_override</code> filter hook to override</p>\n\n<pre><code>add_filter('wp_audio_shortcode_override', 'my_audio_shortcode');\n\nfunction my_audio_shortcode($args) {\n //TODO: Insert your own version of the shortcode\n}\n</code></pre></li>\n</ol>\n" }, { "answer_id": 221214, "author": "Samuel LOL Hackson", "author_id": 90910, "author_profile": "https://wordpress.stackexchange.com/users/90910", "pm_score": 1, "selected": false, "text": "<p>I fiddled around with all of the suggestions and would like to present what is the most elegant solution to me (but I'll leave the \"answered\" badge where it is), so future readers can benefit from it as well. This combines the use of filters (thanks to @Jevuska) and the suggestion of adding a shortcode (s/o @iantsch).</p>\n\n<p>I've added a <code>thumbaudio</code> shortcode that will execute the <code>audio</code> shortcode with the modified class filter. That way, if a user types in the audio shortcode, it'll show the default player, but if (s)he typed in <code>thumbaudio</code>, it'll add <code>miniplayer</code> to the classes. The user has full control over which class is being applied where and when in the HTML file.</p>\n\n<pre><code>add_shortcode('thumbaudio', 'my_thumbaudio_shortcode');\n\nfunction wp_audio_shortcode_thumbclass( $class ) {\n $class .= ' miniplayer';\n return $class;\n}\n\nfunction my_thumbaudio_shortcode( $attr ) {\n add_filter( 'wp_audio_shortcode_class', 'wp_audio_shortcode_thumbclass', 1, 1 );\n echo wp_audio_shortcode( $attr );\n remove_filter( 'wp_audio_shortcode_class', 'wp_audio_shortcode_thumbclass', 1 );\n}\n</code></pre>\n" } ]
2016/03/20
[ "https://wordpress.stackexchange.com/questions/221201", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/90910/" ]
I would like to style two MediaElement players on the same page differently, and figured out the easier way to do this (compared to adding a completely new shortcode and enqueueing a new stylesheet, [which I couldn't get working either](https://stackoverflow.com/questions/36111811/wordpress-4-4-media-player-different-css-stylesheet-depending-on-shortcode)) is to assign a different class to the audio shortcode of player A. [The WordPress code reference](https://developer.wordpress.org/reference/functions/wp_audio_shortcode/#source-code) mentions adding a `class` attribute to the shortcode, **but I can't get it to work.** For instance, writing ``` [audio class="miniplayer" mp3="http://localhost/working_url.mp3"][/audio] ``` does give me a working player, but I can't see "miniplayer" assigned to it anywhere in my Firefox console. So how do I assign a class to my shortcode properly?
WordPress allows least three options to manipulate the code to your needs. 1. Use a global variable that you increment with @Jevuska 's answer. ``` global $my_audio_player_count; $my_audio_player_count = 0; add_filter( 'wp_audio_shortcode_class', 'wpse221201_audio_shortcode_class', 1, 1 ); function wpse221201_audio_shortcode_class( $class ) { global $my_audio_player_count; $class .= ' my-audio-player-'.$my_audio_player_count++; return $class; } ``` 2. Remove the built-in shortcode and add your own ``` remove_shortcode('audio'); add_shortcode('audio', 'my_audio_shortcode'); function my_audio_shortcode($args) { //TODO: Insert your own version of the shortcode } ``` 3. Use the `wp_audio_shortcode_override` filter hook to override ``` add_filter('wp_audio_shortcode_override', 'my_audio_shortcode'); function my_audio_shortcode($args) { //TODO: Insert your own version of the shortcode } ```
221,202
<p>I am starting a bit with the REST API. If I am not completly mislead, the <code>init</code> action hook is also executed when its a REST API request. Now, I want to execute some code only, when it is not a REST API request.</p> <p>So I was looking for a command like <code>is_rest()</code> in order to do something like</p> <pre><code>&lt;?php if( ! is_rest() ) echo 'no-rest-request'; ?&gt; </code></pre> <p>But I couldn't find something like this. Is there a <code>is_rest()</code> out there?</p>
[ { "answer_id": 221289, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>It's a good point by @Milo, the <code>REST_REQUEST</code> constant is <a href=\"https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/rest-api.php#L135-L141\" rel=\"noreferrer\">defined</a> as <code>true</code>, within <code>rest_api_loaded()</code> if <code>$GLOBALS['wp']-&gt;query_vars['rest_route']</code> is non-empty.</p>\n\n<p>It's <a href=\"https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/default-filters.php#L364-L367\" rel=\"noreferrer\">hooked</a> into <code>parse_request</code> via:</p>\n\n<pre><code>add_action( 'parse_request', 'rest_api_loaded' );\n</code></pre>\n\n<p>but <code>parse_request</code> fires later than <code>init</code> - See for example the Codex <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request\" rel=\"noreferrer\">here</a>. </p>\n\n<p>There was a suggestion (by Daniel Bachhuber) in ticket <a href=\"https://core.trac.wordpress.org/ticket/34373\" rel=\"noreferrer\">#34373</a> regarding <code>WP_Query::is_rest()</code>, but it was postponed/cancelled.</p>\n" }, { "answer_id": 279422, "author": "Paul G.", "author_id": 41288, "author_profile": "https://wordpress.stackexchange.com/users/41288", "pm_score": 3, "selected": false, "text": "<p>To solve this problem I wrote a simple custom function based on the assumption that if the URI being requested falls under the WordPress site's Rest API URL, then it follows that it's a Rest API request.</p>\n\n<p>Whether it's a valid endpoint, or authenticated, is not for this function to determine. The question is this: is the URL a potential Rest API url?</p>\n\n<pre><code>function isRestUrl() {\n $bIsRest = false;\n if ( function_exists( 'rest_url' ) &amp;&amp; !empty( $_SERVER[ 'REQUEST_URI' ] ) ) {\n $sRestUrlBase = get_rest_url( get_current_blog_id(), '/' );\n $sRestPath = trim( parse_url( $sRestUrlBase, PHP_URL_PATH ), '/' );\n $sRequestPath = trim( $_SERVER[ 'REQUEST_URI' ], '/' );\n $bIsRest = ( strpos( $sRequestPath, $sRestPath ) === 0 );\n }\n return $bIsRest;\n}\n</code></pre>\n\n<p>If your <code>$_SERVER['REQUEST_URI']</code> isn't properly populated, this function will still return <code>false</code>, regardless.</p>\n\n<p>There is no hard-coding of the URL so if you for some reason change your API URL base, this will adapt.</p>\n" }, { "answer_id": 317041, "author": "Matthias Günter", "author_id": 83335, "author_profile": "https://wordpress.stackexchange.com/users/83335", "pm_score": 4, "selected": false, "text": "<p>Just stumbled over the same problem and wrote a simple function <code>is_rest</code> that allows you to check if the current request is a WP REST API request.</p>\n<pre><code>&lt;?php\n\nif ( !function_exists( 'is_rest' ) ) {\n /**\n * Checks if the current request is a WP REST API request.\n *\n * Case #1: After WP_REST_Request initialisation\n * Case #2: Support &quot;plain&quot; permalink settings and check if `rest_route` starts with `/`\n * Case #3: It can happen that WP_Rewrite is not yet initialized,\n * so do this (wp-settings.php)\n * Case #4: URL Path begins with wp-json/ (your REST prefix)\n * Also supports WP installations in subfolders\n *\n * @returns boolean\n * @author matzeeable\n */\n function is_rest() {\n if (defined('REST_REQUEST') &amp;&amp; REST_REQUEST // (#1)\n || isset($_GET['rest_route']) // (#2)\n &amp;&amp; strpos( $_GET['rest_route'], '/', 0 ) === 0)\n return true;\n\n // (#3)\n global $wp_rewrite;\n if ($wp_rewrite === null) $wp_rewrite = new WP_Rewrite();\n \n // (#4)\n $rest_url = wp_parse_url( trailingslashit( rest_url( ) ) );\n $current_url = wp_parse_url( add_query_arg( array( ) ) );\n return strpos( $current_url['path'] ?? '/', $rest_url['path'], 0 ) === 0;\n }\n}\n</code></pre>\n<p>References:</p>\n<ul>\n<li><a href=\"https://gist.github.com/matzeeable/dfd82239f48c2fedef25141e48c8dc30\" rel=\"nofollow noreferrer\">https://gist.github.com/matzeeable/dfd82239f48c2fedef25141e48c8dc30</a></li>\n<li><a href=\"https://twitter.com/matzeeable/status/1052967482737258496\" rel=\"nofollow noreferrer\">https://twitter.com/matzeeable/status/1052967482737258496</a></li>\n</ul>\n" }, { "answer_id": 331251, "author": "Mark", "author_id": 19396, "author_profile": "https://wordpress.stackexchange.com/users/19396", "pm_score": 3, "selected": false, "text": "<p>Two options here really,</p>\n\n<ol>\n<li>Check if <code>REST_REQUEST</code> is defined.</li>\n<li>Hook into <a href=\"https://developer.wordpress.org/reference/hooks/rest_api_init/\" rel=\"noreferrer\"><code>rest_api_init</code></a> where you wanted to hook into <code>init</code>.</li>\n</ol>\n" }, { "answer_id": 339174, "author": "Charly", "author_id": 147499, "author_profile": "https://wordpress.stackexchange.com/users/147499", "pm_score": 2, "selected": false, "text": "<p>Maybe not right, but I ended up with</p>\n\n<pre><code>if (strpos($_SERVER[ 'REQUEST_URI' ], '/wp-json/') !== false) {\n // Cool API stuff here\n}\n</code></pre>\n\n<p>Feel free to let me know if this isn't right. Trying to make a helpful plugin starter to eventually share: <a href=\"https://gitlab.com/ripp.io/wordpress/plugin-starter\" rel=\"nofollow noreferrer\">https://gitlab.com/ripp.io/wordpress/plugin-starter</a></p>\n" }, { "answer_id": 356946, "author": "Lucas Bustamante", "author_id": 27278, "author_profile": "https://wordpress.stackexchange.com/users/27278", "pm_score": 3, "selected": false, "text": "<p>If you need it after <code>init</code> has fired:</p>\n<p><code>defined('REST_REQUEST') &amp;&amp; REST_REQUEST</code></p>\n<p>If you need it before <code>init</code>, there are two ways:</p>\n<p>Use <code>wp_is_json_request()</code> (Introduced in WordPress 5.0), or try to infer if it's a REST Request through the URL. Detecting the URL will vary whether the site is using permalinks or plain permalinks.</p>\n<p>WooCommerce does it like this, and it's a good solution:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function is_rest_api_request() {\n if ( empty( $_SERVER['REQUEST_URI'] ) ) {\n // Probably a CLI request\n return false;\n }\n\n $rest_prefix = trailingslashit( rest_get_url_prefix() );\n $is_rest_api_request = strpos( $_SERVER['REQUEST_URI'], $rest_prefix ) !== false;\n\n return apply_filters( 'is_rest_api_request', $is_rest_api_request );\n}\n</code></pre>\n" }, { "answer_id": 411040, "author": "Akhtarujjaman Shuvo", "author_id": 118077, "author_profile": "https://wordpress.stackexchange.com/users/118077", "pm_score": 1, "selected": false, "text": "<p>You can use <code>wp_is_json_request()</code> like below:</p>\n<pre><code>if ( wp_is_json_request() ) {\n // do you stuff here\n}\n</code></pre>\n<p>Make sure that you set <code>Accepts</code> or <code>Content-Type</code> as <code>application/json</code> otherwise <code>wp_is_json_request()</code> will return false.</p>\n<p>More Documentation: <a href=\"https://developer.wordpress.org/reference/functions/wp_is_json_request/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_is_json_request/</a></p>\n" } ]
2016/03/20
[ "https://wordpress.stackexchange.com/questions/221202", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48693/" ]
I am starting a bit with the REST API. If I am not completly mislead, the `init` action hook is also executed when its a REST API request. Now, I want to execute some code only, when it is not a REST API request. So I was looking for a command like `is_rest()` in order to do something like ``` <?php if( ! is_rest() ) echo 'no-rest-request'; ?> ``` But I couldn't find something like this. Is there a `is_rest()` out there?
It's a good point by @Milo, the `REST_REQUEST` constant is [defined](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/rest-api.php#L135-L141) as `true`, within `rest_api_loaded()` if `$GLOBALS['wp']->query_vars['rest_route']` is non-empty. It's [hooked](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/default-filters.php#L364-L367) into `parse_request` via: ``` add_action( 'parse_request', 'rest_api_loaded' ); ``` but `parse_request` fires later than `init` - See for example the Codex [here](http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request). There was a suggestion (by Daniel Bachhuber) in ticket [#34373](https://core.trac.wordpress.org/ticket/34373) regarding `WP_Query::is_rest()`, but it was postponed/cancelled.
221,240
<p>I am developing a site that has an SSL certificate. I've activated wp-admin being conducted over https (using <code>define('FORCE_SSL_ADMIN', true);</code> in wp-config.php).</p> <p>It's created a lot of issues using wp-admin.</p> <p>1) Whilst doing things in wp-admin I'll regularly get a message saying the session has expired. As far as I can tell, this mostly happens when jumping from one admin page (url) to another page (url).</p> <p>2) In Chrome I'll often see a little silver shield in the address bar indicating there are "unsafe scripts" the page is trying to load. I have to then manually tell it to load those scripts (I gather these are scripts wp-admin is trying to load over http, rather than https).</p> <p>3) Some pages load fine with full HTTPS support (no mixed content) and the EV greenbar, etc. But other pages (in admin) will generate mixed content errors. It seems to be that when switching from a URL with mixed content errors over to one with no such errors (or vice versa) this is when the session expiration issues occurs (not 100% sure about that, but certainly looks that way).</p> <p>On the front end I used whynopadlock.com to show me which resources were loading over HTTP when using HTTPS, and fixed them (it was simply images in posts, etc.). But since wp-admin requires one to log in, I don't have that option available.</p> <p>I have two questions:</p> <p>Q1) Is there a recommended way to get wp-admin to work correctly over SSL?</p> <p>Q2) What's a recommended way to troubleshoot why wp-admin over SSL is so unstable? (meaning it works on some admin pages, breaks on others, and causes session expiration on others).</p> <p>Thank you,</p> <p>Jonathan</p>
[ { "answer_id": 221289, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>It's a good point by @Milo, the <code>REST_REQUEST</code> constant is <a href=\"https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/rest-api.php#L135-L141\" rel=\"noreferrer\">defined</a> as <code>true</code>, within <code>rest_api_loaded()</code> if <code>$GLOBALS['wp']-&gt;query_vars['rest_route']</code> is non-empty.</p>\n\n<p>It's <a href=\"https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/default-filters.php#L364-L367\" rel=\"noreferrer\">hooked</a> into <code>parse_request</code> via:</p>\n\n<pre><code>add_action( 'parse_request', 'rest_api_loaded' );\n</code></pre>\n\n<p>but <code>parse_request</code> fires later than <code>init</code> - See for example the Codex <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request\" rel=\"noreferrer\">here</a>. </p>\n\n<p>There was a suggestion (by Daniel Bachhuber) in ticket <a href=\"https://core.trac.wordpress.org/ticket/34373\" rel=\"noreferrer\">#34373</a> regarding <code>WP_Query::is_rest()</code>, but it was postponed/cancelled.</p>\n" }, { "answer_id": 279422, "author": "Paul G.", "author_id": 41288, "author_profile": "https://wordpress.stackexchange.com/users/41288", "pm_score": 3, "selected": false, "text": "<p>To solve this problem I wrote a simple custom function based on the assumption that if the URI being requested falls under the WordPress site's Rest API URL, then it follows that it's a Rest API request.</p>\n\n<p>Whether it's a valid endpoint, or authenticated, is not for this function to determine. The question is this: is the URL a potential Rest API url?</p>\n\n<pre><code>function isRestUrl() {\n $bIsRest = false;\n if ( function_exists( 'rest_url' ) &amp;&amp; !empty( $_SERVER[ 'REQUEST_URI' ] ) ) {\n $sRestUrlBase = get_rest_url( get_current_blog_id(), '/' );\n $sRestPath = trim( parse_url( $sRestUrlBase, PHP_URL_PATH ), '/' );\n $sRequestPath = trim( $_SERVER[ 'REQUEST_URI' ], '/' );\n $bIsRest = ( strpos( $sRequestPath, $sRestPath ) === 0 );\n }\n return $bIsRest;\n}\n</code></pre>\n\n<p>If your <code>$_SERVER['REQUEST_URI']</code> isn't properly populated, this function will still return <code>false</code>, regardless.</p>\n\n<p>There is no hard-coding of the URL so if you for some reason change your API URL base, this will adapt.</p>\n" }, { "answer_id": 317041, "author": "Matthias Günter", "author_id": 83335, "author_profile": "https://wordpress.stackexchange.com/users/83335", "pm_score": 4, "selected": false, "text": "<p>Just stumbled over the same problem and wrote a simple function <code>is_rest</code> that allows you to check if the current request is a WP REST API request.</p>\n<pre><code>&lt;?php\n\nif ( !function_exists( 'is_rest' ) ) {\n /**\n * Checks if the current request is a WP REST API request.\n *\n * Case #1: After WP_REST_Request initialisation\n * Case #2: Support &quot;plain&quot; permalink settings and check if `rest_route` starts with `/`\n * Case #3: It can happen that WP_Rewrite is not yet initialized,\n * so do this (wp-settings.php)\n * Case #4: URL Path begins with wp-json/ (your REST prefix)\n * Also supports WP installations in subfolders\n *\n * @returns boolean\n * @author matzeeable\n */\n function is_rest() {\n if (defined('REST_REQUEST') &amp;&amp; REST_REQUEST // (#1)\n || isset($_GET['rest_route']) // (#2)\n &amp;&amp; strpos( $_GET['rest_route'], '/', 0 ) === 0)\n return true;\n\n // (#3)\n global $wp_rewrite;\n if ($wp_rewrite === null) $wp_rewrite = new WP_Rewrite();\n \n // (#4)\n $rest_url = wp_parse_url( trailingslashit( rest_url( ) ) );\n $current_url = wp_parse_url( add_query_arg( array( ) ) );\n return strpos( $current_url['path'] ?? '/', $rest_url['path'], 0 ) === 0;\n }\n}\n</code></pre>\n<p>References:</p>\n<ul>\n<li><a href=\"https://gist.github.com/matzeeable/dfd82239f48c2fedef25141e48c8dc30\" rel=\"nofollow noreferrer\">https://gist.github.com/matzeeable/dfd82239f48c2fedef25141e48c8dc30</a></li>\n<li><a href=\"https://twitter.com/matzeeable/status/1052967482737258496\" rel=\"nofollow noreferrer\">https://twitter.com/matzeeable/status/1052967482737258496</a></li>\n</ul>\n" }, { "answer_id": 331251, "author": "Mark", "author_id": 19396, "author_profile": "https://wordpress.stackexchange.com/users/19396", "pm_score": 3, "selected": false, "text": "<p>Two options here really,</p>\n\n<ol>\n<li>Check if <code>REST_REQUEST</code> is defined.</li>\n<li>Hook into <a href=\"https://developer.wordpress.org/reference/hooks/rest_api_init/\" rel=\"noreferrer\"><code>rest_api_init</code></a> where you wanted to hook into <code>init</code>.</li>\n</ol>\n" }, { "answer_id": 339174, "author": "Charly", "author_id": 147499, "author_profile": "https://wordpress.stackexchange.com/users/147499", "pm_score": 2, "selected": false, "text": "<p>Maybe not right, but I ended up with</p>\n\n<pre><code>if (strpos($_SERVER[ 'REQUEST_URI' ], '/wp-json/') !== false) {\n // Cool API stuff here\n}\n</code></pre>\n\n<p>Feel free to let me know if this isn't right. Trying to make a helpful plugin starter to eventually share: <a href=\"https://gitlab.com/ripp.io/wordpress/plugin-starter\" rel=\"nofollow noreferrer\">https://gitlab.com/ripp.io/wordpress/plugin-starter</a></p>\n" }, { "answer_id": 356946, "author": "Lucas Bustamante", "author_id": 27278, "author_profile": "https://wordpress.stackexchange.com/users/27278", "pm_score": 3, "selected": false, "text": "<p>If you need it after <code>init</code> has fired:</p>\n<p><code>defined('REST_REQUEST') &amp;&amp; REST_REQUEST</code></p>\n<p>If you need it before <code>init</code>, there are two ways:</p>\n<p>Use <code>wp_is_json_request()</code> (Introduced in WordPress 5.0), or try to infer if it's a REST Request through the URL. Detecting the URL will vary whether the site is using permalinks or plain permalinks.</p>\n<p>WooCommerce does it like this, and it's a good solution:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function is_rest_api_request() {\n if ( empty( $_SERVER['REQUEST_URI'] ) ) {\n // Probably a CLI request\n return false;\n }\n\n $rest_prefix = trailingslashit( rest_get_url_prefix() );\n $is_rest_api_request = strpos( $_SERVER['REQUEST_URI'], $rest_prefix ) !== false;\n\n return apply_filters( 'is_rest_api_request', $is_rest_api_request );\n}\n</code></pre>\n" }, { "answer_id": 411040, "author": "Akhtarujjaman Shuvo", "author_id": 118077, "author_profile": "https://wordpress.stackexchange.com/users/118077", "pm_score": 1, "selected": false, "text": "<p>You can use <code>wp_is_json_request()</code> like below:</p>\n<pre><code>if ( wp_is_json_request() ) {\n // do you stuff here\n}\n</code></pre>\n<p>Make sure that you set <code>Accepts</code> or <code>Content-Type</code> as <code>application/json</code> otherwise <code>wp_is_json_request()</code> will return false.</p>\n<p>More Documentation: <a href=\"https://developer.wordpress.org/reference/functions/wp_is_json_request/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_is_json_request/</a></p>\n" } ]
2016/03/21
[ "https://wordpress.stackexchange.com/questions/221240", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/11064/" ]
I am developing a site that has an SSL certificate. I've activated wp-admin being conducted over https (using `define('FORCE_SSL_ADMIN', true);` in wp-config.php). It's created a lot of issues using wp-admin. 1) Whilst doing things in wp-admin I'll regularly get a message saying the session has expired. As far as I can tell, this mostly happens when jumping from one admin page (url) to another page (url). 2) In Chrome I'll often see a little silver shield in the address bar indicating there are "unsafe scripts" the page is trying to load. I have to then manually tell it to load those scripts (I gather these are scripts wp-admin is trying to load over http, rather than https). 3) Some pages load fine with full HTTPS support (no mixed content) and the EV greenbar, etc. But other pages (in admin) will generate mixed content errors. It seems to be that when switching from a URL with mixed content errors over to one with no such errors (or vice versa) this is when the session expiration issues occurs (not 100% sure about that, but certainly looks that way). On the front end I used whynopadlock.com to show me which resources were loading over HTTP when using HTTPS, and fixed them (it was simply images in posts, etc.). But since wp-admin requires one to log in, I don't have that option available. I have two questions: Q1) Is there a recommended way to get wp-admin to work correctly over SSL? Q2) What's a recommended way to troubleshoot why wp-admin over SSL is so unstable? (meaning it works on some admin pages, breaks on others, and causes session expiration on others). Thank you, Jonathan
It's a good point by @Milo, the `REST_REQUEST` constant is [defined](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/rest-api.php#L135-L141) as `true`, within `rest_api_loaded()` if `$GLOBALS['wp']->query_vars['rest_route']` is non-empty. It's [hooked](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/default-filters.php#L364-L367) into `parse_request` via: ``` add_action( 'parse_request', 'rest_api_loaded' ); ``` but `parse_request` fires later than `init` - See for example the Codex [here](http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request). There was a suggestion (by Daniel Bachhuber) in ticket [#34373](https://core.trac.wordpress.org/ticket/34373) regarding `WP_Query::is_rest()`, but it was postponed/cancelled.
221,250
<p>I want to get category id by name so I am using <a href="https://codex.wordpress.org/Function_Reference/get_term_by" rel="nofollow">get_term_by</a></p> <p>This is working fine when name is simple but when '&amp;' is coming in term name it is not fetching category id.</p> <p>e.g I have a term named "Website Development &amp; Designing" under <strong>skills</strong> taxonomy and I am using following query to get its term id.</p> <pre><code>$value = "Website Development &amp; Designing" get_term_by('name',$value,'skills'); </code></pre> <p>but it does not return term object :(</p>
[ { "answer_id": 221289, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 5, "selected": true, "text": "<p>It's a good point by @Milo, the <code>REST_REQUEST</code> constant is <a href=\"https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/rest-api.php#L135-L141\" rel=\"noreferrer\">defined</a> as <code>true</code>, within <code>rest_api_loaded()</code> if <code>$GLOBALS['wp']-&gt;query_vars['rest_route']</code> is non-empty.</p>\n\n<p>It's <a href=\"https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/default-filters.php#L364-L367\" rel=\"noreferrer\">hooked</a> into <code>parse_request</code> via:</p>\n\n<pre><code>add_action( 'parse_request', 'rest_api_loaded' );\n</code></pre>\n\n<p>but <code>parse_request</code> fires later than <code>init</code> - See for example the Codex <a href=\"http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request\" rel=\"noreferrer\">here</a>. </p>\n\n<p>There was a suggestion (by Daniel Bachhuber) in ticket <a href=\"https://core.trac.wordpress.org/ticket/34373\" rel=\"noreferrer\">#34373</a> regarding <code>WP_Query::is_rest()</code>, but it was postponed/cancelled.</p>\n" }, { "answer_id": 279422, "author": "Paul G.", "author_id": 41288, "author_profile": "https://wordpress.stackexchange.com/users/41288", "pm_score": 3, "selected": false, "text": "<p>To solve this problem I wrote a simple custom function based on the assumption that if the URI being requested falls under the WordPress site's Rest API URL, then it follows that it's a Rest API request.</p>\n\n<p>Whether it's a valid endpoint, or authenticated, is not for this function to determine. The question is this: is the URL a potential Rest API url?</p>\n\n<pre><code>function isRestUrl() {\n $bIsRest = false;\n if ( function_exists( 'rest_url' ) &amp;&amp; !empty( $_SERVER[ 'REQUEST_URI' ] ) ) {\n $sRestUrlBase = get_rest_url( get_current_blog_id(), '/' );\n $sRestPath = trim( parse_url( $sRestUrlBase, PHP_URL_PATH ), '/' );\n $sRequestPath = trim( $_SERVER[ 'REQUEST_URI' ], '/' );\n $bIsRest = ( strpos( $sRequestPath, $sRestPath ) === 0 );\n }\n return $bIsRest;\n}\n</code></pre>\n\n<p>If your <code>$_SERVER['REQUEST_URI']</code> isn't properly populated, this function will still return <code>false</code>, regardless.</p>\n\n<p>There is no hard-coding of the URL so if you for some reason change your API URL base, this will adapt.</p>\n" }, { "answer_id": 317041, "author": "Matthias Günter", "author_id": 83335, "author_profile": "https://wordpress.stackexchange.com/users/83335", "pm_score": 4, "selected": false, "text": "<p>Just stumbled over the same problem and wrote a simple function <code>is_rest</code> that allows you to check if the current request is a WP REST API request.</p>\n<pre><code>&lt;?php\n\nif ( !function_exists( 'is_rest' ) ) {\n /**\n * Checks if the current request is a WP REST API request.\n *\n * Case #1: After WP_REST_Request initialisation\n * Case #2: Support &quot;plain&quot; permalink settings and check if `rest_route` starts with `/`\n * Case #3: It can happen that WP_Rewrite is not yet initialized,\n * so do this (wp-settings.php)\n * Case #4: URL Path begins with wp-json/ (your REST prefix)\n * Also supports WP installations in subfolders\n *\n * @returns boolean\n * @author matzeeable\n */\n function is_rest() {\n if (defined('REST_REQUEST') &amp;&amp; REST_REQUEST // (#1)\n || isset($_GET['rest_route']) // (#2)\n &amp;&amp; strpos( $_GET['rest_route'], '/', 0 ) === 0)\n return true;\n\n // (#3)\n global $wp_rewrite;\n if ($wp_rewrite === null) $wp_rewrite = new WP_Rewrite();\n \n // (#4)\n $rest_url = wp_parse_url( trailingslashit( rest_url( ) ) );\n $current_url = wp_parse_url( add_query_arg( array( ) ) );\n return strpos( $current_url['path'] ?? '/', $rest_url['path'], 0 ) === 0;\n }\n}\n</code></pre>\n<p>References:</p>\n<ul>\n<li><a href=\"https://gist.github.com/matzeeable/dfd82239f48c2fedef25141e48c8dc30\" rel=\"nofollow noreferrer\">https://gist.github.com/matzeeable/dfd82239f48c2fedef25141e48c8dc30</a></li>\n<li><a href=\"https://twitter.com/matzeeable/status/1052967482737258496\" rel=\"nofollow noreferrer\">https://twitter.com/matzeeable/status/1052967482737258496</a></li>\n</ul>\n" }, { "answer_id": 331251, "author": "Mark", "author_id": 19396, "author_profile": "https://wordpress.stackexchange.com/users/19396", "pm_score": 3, "selected": false, "text": "<p>Two options here really,</p>\n\n<ol>\n<li>Check if <code>REST_REQUEST</code> is defined.</li>\n<li>Hook into <a href=\"https://developer.wordpress.org/reference/hooks/rest_api_init/\" rel=\"noreferrer\"><code>rest_api_init</code></a> where you wanted to hook into <code>init</code>.</li>\n</ol>\n" }, { "answer_id": 339174, "author": "Charly", "author_id": 147499, "author_profile": "https://wordpress.stackexchange.com/users/147499", "pm_score": 2, "selected": false, "text": "<p>Maybe not right, but I ended up with</p>\n\n<pre><code>if (strpos($_SERVER[ 'REQUEST_URI' ], '/wp-json/') !== false) {\n // Cool API stuff here\n}\n</code></pre>\n\n<p>Feel free to let me know if this isn't right. Trying to make a helpful plugin starter to eventually share: <a href=\"https://gitlab.com/ripp.io/wordpress/plugin-starter\" rel=\"nofollow noreferrer\">https://gitlab.com/ripp.io/wordpress/plugin-starter</a></p>\n" }, { "answer_id": 356946, "author": "Lucas Bustamante", "author_id": 27278, "author_profile": "https://wordpress.stackexchange.com/users/27278", "pm_score": 3, "selected": false, "text": "<p>If you need it after <code>init</code> has fired:</p>\n<p><code>defined('REST_REQUEST') &amp;&amp; REST_REQUEST</code></p>\n<p>If you need it before <code>init</code>, there are two ways:</p>\n<p>Use <code>wp_is_json_request()</code> (Introduced in WordPress 5.0), or try to infer if it's a REST Request through the URL. Detecting the URL will vary whether the site is using permalinks or plain permalinks.</p>\n<p>WooCommerce does it like this, and it's a good solution:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function is_rest_api_request() {\n if ( empty( $_SERVER['REQUEST_URI'] ) ) {\n // Probably a CLI request\n return false;\n }\n\n $rest_prefix = trailingslashit( rest_get_url_prefix() );\n $is_rest_api_request = strpos( $_SERVER['REQUEST_URI'], $rest_prefix ) !== false;\n\n return apply_filters( 'is_rest_api_request', $is_rest_api_request );\n}\n</code></pre>\n" }, { "answer_id": 411040, "author": "Akhtarujjaman Shuvo", "author_id": 118077, "author_profile": "https://wordpress.stackexchange.com/users/118077", "pm_score": 1, "selected": false, "text": "<p>You can use <code>wp_is_json_request()</code> like below:</p>\n<pre><code>if ( wp_is_json_request() ) {\n // do you stuff here\n}\n</code></pre>\n<p>Make sure that you set <code>Accepts</code> or <code>Content-Type</code> as <code>application/json</code> otherwise <code>wp_is_json_request()</code> will return false.</p>\n<p>More Documentation: <a href=\"https://developer.wordpress.org/reference/functions/wp_is_json_request/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_is_json_request/</a></p>\n" } ]
2016/03/21
[ "https://wordpress.stackexchange.com/questions/221250", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89273/" ]
I want to get category id by name so I am using [get\_term\_by](https://codex.wordpress.org/Function_Reference/get_term_by) This is working fine when name is simple but when '&' is coming in term name it is not fetching category id. e.g I have a term named "Website Development & Designing" under **skills** taxonomy and I am using following query to get its term id. ``` $value = "Website Development & Designing" get_term_by('name',$value,'skills'); ``` but it does not return term object :(
It's a good point by @Milo, the `REST_REQUEST` constant is [defined](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/rest-api.php#L135-L141) as `true`, within `rest_api_loaded()` if `$GLOBALS['wp']->query_vars['rest_route']` is non-empty. It's [hooked](https://github.com/WordPress/WordPress/blob/8e41746cb11271d063608a63e3f6091a8685e677/wp-includes/default-filters.php#L364-L367) into `parse_request` via: ``` add_action( 'parse_request', 'rest_api_loaded' ); ``` but `parse_request` fires later than `init` - See for example the Codex [here](http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_an_Admin_Page_Request). There was a suggestion (by Daniel Bachhuber) in ticket [#34373](https://core.trac.wordpress.org/ticket/34373) regarding `WP_Query::is_rest()`, but it was postponed/cancelled.