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
292,240
<p>I'm working on tweaking a theme and I need to explode the post content to remove some text. The following code is what I am using: </p> <pre><code>$custom_Get_Post_Title = explode('|',get_post()-&gt;post_content); echo "&lt;h4&gt;" . $custom_Get_Post_Title[0] . "&lt;/h4&gt;"; echo "&lt;p&gt;" . $custom_Get_Post_Title[1] . "&lt;/p&gt;"; </code></pre> <p>Originally, the developer was using the follow code to display the post content, but it was making it hard for me to explode the data. </p> <pre><code>global $post; setup_postdata($post); the_content(); </code></pre> <p><strong>MY QUESTION</strong>: What is the difference between these two methods that both retrieve the post content?</p>
[ { "answer_id": 292241, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 2, "selected": false, "text": "<p><code>get_post()</code> is the same as <code>global $post</code></p>\n\n<p>functions such as <code>the_content()</code> can only be used inside of a loop.</p>\n\n<p>the <code>setup_postdata()</code> function can be used to make those functions available.</p>\n\n<p>Your top example could be rewritten as follows:</p>\n\n<pre><code>gloabl $post;\n$custom_Get_Post_Title = explode('|',$post-&gt;post_content);\n</code></pre>\n\n<p>or you could do something similar with the bottom example:</p>\n\n<pre><code>global $post;\n// setup_postdata($post); &lt;- not really needed\n$theContent = get_the_content($post-&gt;ID); // can used post-id to retrieve specific\n$custom_Get_Post_Title = explode('|',get_post()-&gt;post_content);\n</code></pre>\n" }, { "answer_id": 292254, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": false, "text": "<p><code>post_content</code> is a <em>property</em> of the <a href=\"https://developer.wordpress.org/reference/classes/wp_post/\" rel=\"noreferrer\"><code>WP_Post</code></a> object. <code>WP_Post</code> is an object representing the post data from the database. So <code>post_content</code> contains the raw content as stored in the database.</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/the_content/\" rel=\"noreferrer\"><code>the_content()</code></a> is a template tag that displays the content of the current post. The 'current post' is whatever the global <code>$post</code> variable is set to at the time the function is run. The global <code>$post</code> variable is normally set within <a href=\"https://developer.wordpress.org/themes/basics/the-loop/\" rel=\"noreferrer\">The Loop</a> with <code>while( have_posts() ) : the_post();</code>.</p>\n\n<p>The crucial difference is that <code>the_content()</code> runs the raw content through several filters that prepare it for display. These do things like adding paragraph tags, converting URLs to embeds for things like videos, and converting symbols like quotes to smart quotes etc. Many plugins use this filter as well, for adding things like Share buttons.</p>\n\n<p>So if you just echo the <code>post_content</code> it probably won't look right. You can mimic the output of <code>the_content()</code> on raw data by applying the <code>the_content</code> filter manually. So in your example you would do:</p>\n\n<pre><code>$post = get_post();\n\n$split_content = explode( '|', $post-&gt;post_content );\n\necho '&lt;h4&gt;' . $split_content[0] . '&lt;/h4&gt;'; \necho apply_filters( 'the_content', $split_content[1] );\n</code></pre>\n" } ]
2018/01/25
[ "https://wordpress.stackexchange.com/questions/292240", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135605/" ]
I'm working on tweaking a theme and I need to explode the post content to remove some text. The following code is what I am using: ``` $custom_Get_Post_Title = explode('|',get_post()->post_content); echo "<h4>" . $custom_Get_Post_Title[0] . "</h4>"; echo "<p>" . $custom_Get_Post_Title[1] . "</p>"; ``` Originally, the developer was using the follow code to display the post content, but it was making it hard for me to explode the data. ``` global $post; setup_postdata($post); the_content(); ``` **MY QUESTION**: What is the difference between these two methods that both retrieve the post content?
`post_content` is a *property* of the [`WP_Post`](https://developer.wordpress.org/reference/classes/wp_post/) object. `WP_Post` is an object representing the post data from the database. So `post_content` contains the raw content as stored in the database. [`the_content()`](https://developer.wordpress.org/reference/functions/the_content/) is a template tag that displays the content of the current post. The 'current post' is whatever the global `$post` variable is set to at the time the function is run. The global `$post` variable is normally set within [The Loop](https://developer.wordpress.org/themes/basics/the-loop/) with `while( have_posts() ) : the_post();`. The crucial difference is that `the_content()` runs the raw content through several filters that prepare it for display. These do things like adding paragraph tags, converting URLs to embeds for things like videos, and converting symbols like quotes to smart quotes etc. Many plugins use this filter as well, for adding things like Share buttons. So if you just echo the `post_content` it probably won't look right. You can mimic the output of `the_content()` on raw data by applying the `the_content` filter manually. So in your example you would do: ``` $post = get_post(); $split_content = explode( '|', $post->post_content ); echo '<h4>' . $split_content[0] . '</h4>'; echo apply_filters( 'the_content', $split_content[1] ); ```
292,245
<p>I'm having trouble finding a solution for this:</p> <p>I have a bunch of posts with restrict content, and to access the content of these pages the user has to submit a gravity form. I imagine the best way to do so is to set a cookie when <code>gform_after_submission</code> takes place. Then a function would check for that cookie and display this or that depending on the result. The thing is: I need a cookie for every single post rather than a single cookie for the whole site. This is what I have now:</p> <p><strong>Creating cookie after submission.</strong> My idea here was to use the post id to name the cookie and make it unique. After this but I'm not getting anywhere from here.</p> <pre><code>add_action( 'gform_after_submission_1', 'create_cookie' ); function create_cookie() { setcookie( 'cookie'.get_the_ID(), 1, strtotime( '+30 days' ), COOKIEPATH, COOKIE_DOMAIN, false, false); } </code></pre> <p><strong>Checking if that cookie exists.</strong> So after submission the page will reload and the cookie being set it would be detected by the browser and things would happen.</p> <pre><code>add_filter( 'the_content', 'checkingCookie' ); function checkingCookie($content) { if( !isset( $_COOKIE['cookie'.get_the_ID()] ) ) { return 'no cookies!'; } else { return 'cookies!'; } } </code></pre> <p>The thing is that this particular cookie created in a given page should only be detectable in its origin post so that if I go to another post the content there would still be restricted and waiting for its own submission to liberate content.</p> <p>so, any ideas?</p>
[ { "answer_id": 292247, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 3, "selected": true, "text": "<p>You can accomplish what you're after by first creating a hidden field in your form. Set the value to the current embed page:</p>\n\n<p><a href=\"https://i.stack.imgur.com/zZUkZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zZUkZ.png\" alt=\"enter image description here\"></a></p>\n\n<p>Take note of the hidden fields ID, for this demo, it's <code>3</code>.</p>\n\n<hr>\n\n<p>Then your code for the content is similar to what you had:</p>\n\n<pre><code>add_action( 'the_content', function ($content) {\n\n // check if user has submitted this pages form, if not, show only form\n if( !isset( $_COOKIE['unrestrict_'.get_the_ID()] ) ) {\n\n // get form #1\n $form = RGForms::get_form(1);\n\n // uncomment to review cookies\n // echo \"&lt;pre&gt;\".print_r($_COOKIE,true).\"&lt;/pre&gt;\";\n\n return '&lt;h2&gt;Restricted Content - Fill out Form&lt;/h2&gt;'.$form;\n } else {\n\n // user has in last 30 days submitted this pages form\n // show content\n return $content;\n }\n});\n</code></pre>\n\n<hr>\n\n<p>For the processing, we'll do</p>\n\n<pre><code>add_action( 'gform_after_submission_1', function ($entry, $form) {\n\n // uncomment to review the entry\n // echo \"&lt;pre&gt;\".print_r($entry,true).\"&lt;/pre&gt;\"; die;\n\n // get the hidden field, the embedded from page\n $from_page = rgar( $entry, '3' );\n\n // set the cookie\n setcookie( 'unrestrict_'.$from_page, 1, strtotime( '+30 days' ), COOKIEPATH, COOKIE_DOMAIN, false, false);\n\n // redirect so we dont land on gravity forms \"thank you\" page\n wp_redirect( get_permalink( $from_page ) );\n\n}, 10, 2);\n</code></pre>\n\n<hr>\n\n<p>If you want this to be on some pages, but not all, inside of <code>the_content</code> filter you could add your conditionals for the page ID you do/n't want. And you could explore using a checkbox with post_meta/metabox.</p>\n\n<p>You can choose to store one cookie per-page like above, or you could do one main cookie where the value is a serialized array of ID's that you add and look for.</p>\n\n<p>afaik using cookies this simply isn't secure, they can be faked. So if you're hiding delicate info you should review authentication, secure cookie storing, and cookie/user verification. If this is what I presume it's for, lead captures, this is a fine approach.</p>\n\n<p>I've used anonymous functions in the actions, if this is a public plugin/theme you may want to call the function instead.</p>\n" }, { "answer_id": 292363, "author": "Dave from Gravity Wiz", "author_id": 50224, "author_profile": "https://wordpress.stackexchange.com/users/50224", "pm_score": 0, "selected": false, "text": "<p>David's solution is perfectly fine just including this here as an alternative if you want to avoid touching code: </p>\n\n<p><a href=\"https://gravitywiz.com/submit-gravity-form-access-content/\" rel=\"nofollow noreferrer\">https://gravitywiz.com/submit-gravity-form-access-content/</a></p>\n" } ]
2018/01/25
[ "https://wordpress.stackexchange.com/questions/292245", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78848/" ]
I'm having trouble finding a solution for this: I have a bunch of posts with restrict content, and to access the content of these pages the user has to submit a gravity form. I imagine the best way to do so is to set a cookie when `gform_after_submission` takes place. Then a function would check for that cookie and display this or that depending on the result. The thing is: I need a cookie for every single post rather than a single cookie for the whole site. This is what I have now: **Creating cookie after submission.** My idea here was to use the post id to name the cookie and make it unique. After this but I'm not getting anywhere from here. ``` add_action( 'gform_after_submission_1', 'create_cookie' ); function create_cookie() { setcookie( 'cookie'.get_the_ID(), 1, strtotime( '+30 days' ), COOKIEPATH, COOKIE_DOMAIN, false, false); } ``` **Checking if that cookie exists.** So after submission the page will reload and the cookie being set it would be detected by the browser and things would happen. ``` add_filter( 'the_content', 'checkingCookie' ); function checkingCookie($content) { if( !isset( $_COOKIE['cookie'.get_the_ID()] ) ) { return 'no cookies!'; } else { return 'cookies!'; } } ``` The thing is that this particular cookie created in a given page should only be detectable in its origin post so that if I go to another post the content there would still be restricted and waiting for its own submission to liberate content. so, any ideas?
You can accomplish what you're after by first creating a hidden field in your form. Set the value to the current embed page: [![enter image description here](https://i.stack.imgur.com/zZUkZ.png)](https://i.stack.imgur.com/zZUkZ.png) Take note of the hidden fields ID, for this demo, it's `3`. --- Then your code for the content is similar to what you had: ``` add_action( 'the_content', function ($content) { // check if user has submitted this pages form, if not, show only form if( !isset( $_COOKIE['unrestrict_'.get_the_ID()] ) ) { // get form #1 $form = RGForms::get_form(1); // uncomment to review cookies // echo "<pre>".print_r($_COOKIE,true)."</pre>"; return '<h2>Restricted Content - Fill out Form</h2>'.$form; } else { // user has in last 30 days submitted this pages form // show content return $content; } }); ``` --- For the processing, we'll do ``` add_action( 'gform_after_submission_1', function ($entry, $form) { // uncomment to review the entry // echo "<pre>".print_r($entry,true)."</pre>"; die; // get the hidden field, the embedded from page $from_page = rgar( $entry, '3' ); // set the cookie setcookie( 'unrestrict_'.$from_page, 1, strtotime( '+30 days' ), COOKIEPATH, COOKIE_DOMAIN, false, false); // redirect so we dont land on gravity forms "thank you" page wp_redirect( get_permalink( $from_page ) ); }, 10, 2); ``` --- If you want this to be on some pages, but not all, inside of `the_content` filter you could add your conditionals for the page ID you do/n't want. And you could explore using a checkbox with post\_meta/metabox. You can choose to store one cookie per-page like above, or you could do one main cookie where the value is a serialized array of ID's that you add and look for. afaik using cookies this simply isn't secure, they can be faked. So if you're hiding delicate info you should review authentication, secure cookie storing, and cookie/user verification. If this is what I presume it's for, lead captures, this is a fine approach. I've used anonymous functions in the actions, if this is a public plugin/theme you may want to call the function instead.
292,285
<p>I've been looking for the solution of this issue for a while but cannot find the correct answer.</p> <p>I'm developing a custom Knowledge Base plugin for my site, as requested by my boss. The around plugins are not working for he want, so I need to create my own.</p> <p>I've a Custom Post Type called <code>wikicon_recurso</code> with it's own taxonomies, metadata and so on.</p> <p>What I'm having trouble now is for the search function inside my own "Wiki". When someone clicks on "Wikicon" at the menu, it will redirect to the Archive Template, which I have modified so it shows a search form and the last posts added to the wiki.</p> <p>When the search returns results, it redirects to my search-wikicon_recurso.php inside the plugin folder and shows the results as I want.</p> <p><strong>I'm having trouble to modify the template when no results are found</strong>. For example, I have a <em>"test"</em> resource, when I find <em>test</em> I'm redirected to the Search template, which is cool. But if I find <em>Hello</em>, as there is no results, I'm redirected to the default Wordpress/Theme no results page, where the search form is not taking the post_type parameter and is looking for everything.</p> <p><strong>How can I modify the destination of empty results to my Search Template, for example, so they can search again?</strong></p> <p>Actually on my plugin I'm redirecting to templates like this:</p> <pre><code>add_filter( 'template_include', 'include_template_function', 1 ); function include_template_function( $template_path ) { if ( get_post_type() == 'wikicon_recurso' ) { if ( is_singular() ) { $template_path = plugin_dir_path( __FILE__ ) . '/single-wikicon_recurso.php'; } elseif (is_search()) { $template_path = plugin_dir_path( __FILE__ ) . '/search-wikicon_recurso.php'; } elseif (is_archive()) { $template_path = plugin_dir_path( __FILE__ ) . '/archive-wikicon_recurso.php'; } } return $template_path; } </code></pre> <p>This is the search form I'm using from other answers I found around here. It's shown both on the archive-wikicon_recurso.php and search-wikicon_recurso.php:</p> <pre><code>&lt;form role="search" action="&lt;?php echo site_url('/'); ?&gt;" method="get" id="searchform"&gt; &lt;input type="text" name="s" placeholder="Search query"/&gt; &lt;input type="hidden" name="post_type" value="wikicon_recurso" /&gt; &lt;input type="submit" alt="Search" value="Search" /&gt; &lt;/form&gt; </code></pre> <p>I've tried multiple answers from this page and further searchs at Google but I cannot make any to work.</p> <p>I have to say is my first time creating a plugin this big for Wordpress so starting to learn. Thanks in advance.</p>
[ { "answer_id": 292299, "author": "onebc", "author_id": 121233, "author_profile": "https://wordpress.stackexchange.com/users/121233", "pm_score": 0, "selected": false, "text": "<p>Not a very indepth answer, and I'm not sure if this would work for your specific plugin scenario, but it seems to me that rather than trying to redirect to a different destination when there are no results, why don't you just handle it at the resulting destination? For instance, why not observe whether there are any posts (results) using have_posts and, if not, then provide the user a means of searching the wiki again?</p>\n" }, { "answer_id": 292310, "author": "Vlad Olaru", "author_id": 52726, "author_profile": "https://wordpress.stackexchange.com/users/52726", "pm_score": 3, "selected": true, "text": "<p>The problem is that when there are no posts in the search query, WordPress doesn't set the post type in the global WP_Query (<code>get_post_type()</code> relies on that). So, when there are no search results, <code>get_post_type()</code> will return false and all of your custom template logic will be skipped.</p>\n\n<p>What you can do is also consider looking at the request parameters and check if the post type is there and the right value. Also please note that you are not handling 404 for your custom post type (<code>is_404()</code>). Here is how your function would look with both cases taken into account:</p>\n\n<pre><code>function wikicon_include_templates( $template_path ) {\n if ( 'wikicon_recurso' === get_post_type() || 'wikicon_recurso' === get_query_var('post_type') ) {\n if ( is_singular() ) {\n $template_path = plugin_dir_path( __FILE__ ) . '/single-wikicon_recurso.php';\n }\n elseif ( is_search() ) {\n $template_path = plugin_dir_path( __FILE__ ) . '/search-wikicon_recurso.php';\n }\n elseif ( is_archive() || is_404() ) {\n $template_path = plugin_dir_path( __FILE__ ) . '/archive-wikicon_recurso.php';\n }\n }\n\n return $template_path;\n}\nadd_filter( 'template_include', 'wikicon_include_templates', 999, 1 );\n</code></pre>\n\n<p>A couple of tips:</p>\n\n<ul>\n<li>I added a prefix to your function as it is good practice to do so (<code>include_template_function</code> is quite a common name);</li>\n<li>there is no point in including <code>_function</code> in your function name :) ;</li>\n<li>if want to make sure that no other plugin or theme will filter the templates and override your logic (and have you banging your head against the wall wondering why it's not working), you should use a big priority number, like 999, to make sure your logic executes last.</li>\n</ul>\n\n<p>Let me know if this does the trick.</p>\n" } ]
2018/01/26
[ "https://wordpress.stackexchange.com/questions/292285", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135628/" ]
I've been looking for the solution of this issue for a while but cannot find the correct answer. I'm developing a custom Knowledge Base plugin for my site, as requested by my boss. The around plugins are not working for he want, so I need to create my own. I've a Custom Post Type called `wikicon_recurso` with it's own taxonomies, metadata and so on. What I'm having trouble now is for the search function inside my own "Wiki". When someone clicks on "Wikicon" at the menu, it will redirect to the Archive Template, which I have modified so it shows a search form and the last posts added to the wiki. When the search returns results, it redirects to my search-wikicon\_recurso.php inside the plugin folder and shows the results as I want. **I'm having trouble to modify the template when no results are found**. For example, I have a *"test"* resource, when I find *test* I'm redirected to the Search template, which is cool. But if I find *Hello*, as there is no results, I'm redirected to the default Wordpress/Theme no results page, where the search form is not taking the post\_type parameter and is looking for everything. **How can I modify the destination of empty results to my Search Template, for example, so they can search again?** Actually on my plugin I'm redirecting to templates like this: ``` add_filter( 'template_include', 'include_template_function', 1 ); function include_template_function( $template_path ) { if ( get_post_type() == 'wikicon_recurso' ) { if ( is_singular() ) { $template_path = plugin_dir_path( __FILE__ ) . '/single-wikicon_recurso.php'; } elseif (is_search()) { $template_path = plugin_dir_path( __FILE__ ) . '/search-wikicon_recurso.php'; } elseif (is_archive()) { $template_path = plugin_dir_path( __FILE__ ) . '/archive-wikicon_recurso.php'; } } return $template_path; } ``` This is the search form I'm using from other answers I found around here. It's shown both on the archive-wikicon\_recurso.php and search-wikicon\_recurso.php: ``` <form role="search" action="<?php echo site_url('/'); ?>" method="get" id="searchform"> <input type="text" name="s" placeholder="Search query"/> <input type="hidden" name="post_type" value="wikicon_recurso" /> <input type="submit" alt="Search" value="Search" /> </form> ``` I've tried multiple answers from this page and further searchs at Google but I cannot make any to work. I have to say is my first time creating a plugin this big for Wordpress so starting to learn. Thanks in advance.
The problem is that when there are no posts in the search query, WordPress doesn't set the post type in the global WP\_Query (`get_post_type()` relies on that). So, when there are no search results, `get_post_type()` will return false and all of your custom template logic will be skipped. What you can do is also consider looking at the request parameters and check if the post type is there and the right value. Also please note that you are not handling 404 for your custom post type (`is_404()`). Here is how your function would look with both cases taken into account: ``` function wikicon_include_templates( $template_path ) { if ( 'wikicon_recurso' === get_post_type() || 'wikicon_recurso' === get_query_var('post_type') ) { if ( is_singular() ) { $template_path = plugin_dir_path( __FILE__ ) . '/single-wikicon_recurso.php'; } elseif ( is_search() ) { $template_path = plugin_dir_path( __FILE__ ) . '/search-wikicon_recurso.php'; } elseif ( is_archive() || is_404() ) { $template_path = plugin_dir_path( __FILE__ ) . '/archive-wikicon_recurso.php'; } } return $template_path; } add_filter( 'template_include', 'wikicon_include_templates', 999, 1 ); ``` A couple of tips: * I added a prefix to your function as it is good practice to do so (`include_template_function` is quite a common name); * there is no point in including `_function` in your function name :) ; * if want to make sure that no other plugin or theme will filter the templates and override your logic (and have you banging your head against the wall wondering why it's not working), you should use a big priority number, like 999, to make sure your logic executes last. Let me know if this does the trick.
292,293
<p>By default, the product quantity is always "1" when viewing a product page. There doesn't seem an out-of-the-box option to set a different quantity value upon visit, and I don't know what hook or function to look for. </p> <p>Your help is appreciated.</p>
[ { "answer_id": 292297, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>You can use the <code>woocommerce_quantity_input_args</code> filter:</p>\n\n<pre><code>function wpse_292293_quantity_input_default( $args, $product ) {\n $args['input_value'] = 2;\n\n return $args;\n}\nadd_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 );\n</code></pre>\n\n<p>When the quantity input is output, it's output with the <code>woocommerce_quantity_input()</code> function. This function accepts several arguments including the default value for the input. This filter lets you replace values in the arguments across all uses of the function.</p>\n" }, { "answer_id": 374949, "author": "Aslam Khan", "author_id": 179201, "author_profile": "https://wordpress.stackexchange.com/users/179201", "pm_score": 1, "selected": false, "text": "<p>Using this code you can easy to set update quantity . qty box. i was also try this method\nit's working fine for me ...I hope it's also helpful thank you :)</p>\n<pre><code>function wpse_292293_quantity_input_default( $args, $product ) {\n\n\n$productID = $product-&gt;id;\n\nforeach( WC()-&gt;cart-&gt;get_cart() as $key =&gt; $item ){\n \n if( $item['product_id'] == $productID ){ \n $args['input_value'] = $item['quantity']; \n return $args; \n }\n \n} \n\n$args['input_value'] = 1;\nreturn $args;\n\n}\n add_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 );\n</code></pre>\n" }, { "answer_id": 405929, "author": "Sagive", "author_id": 7990, "author_profile": "https://wordpress.stackexchange.com/users/7990", "pm_score": 0, "selected": false, "text": "<p>There is a beautiful example in WooCommerce docs<br />\nthe example even includes a conditional amount.</p>\n<pre><code>/**\n * Adjust the quantity input values\n */\nadd_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 ); // Simple products\n\nfunction jk_woocommerce_quantity_input_args( $args, $product ) {\n if ( is_singular( 'product' ) ) {\n $args['input_value'] = 2; // Starting value (we only want to affect product pages, not cart)\n }\n $args['max_value'] = 80; // Maximum value\n $args['min_value'] = 2; // Minimum value\n $args['step'] = 2; // Quantity steps\n return $args;\n}\n</code></pre>\n<p>Ref:\n<a href=\"https://woocommerce.com/document/adjust-the-quantity-input-values/\" rel=\"nofollow noreferrer\">https://woocommerce.com/document/adjust-the-quantity-input-values/</a></p>\n<p>what you really need to set is the 'input_value' (meaning quantity) value. you have to change the min / max value or step values.. those control the actually input values.</p>\n" } ]
2018/01/26
[ "https://wordpress.stackexchange.com/questions/292293", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118984/" ]
By default, the product quantity is always "1" when viewing a product page. There doesn't seem an out-of-the-box option to set a different quantity value upon visit, and I don't know what hook or function to look for. Your help is appreciated.
You can use the `woocommerce_quantity_input_args` filter: ``` function wpse_292293_quantity_input_default( $args, $product ) { $args['input_value'] = 2; return $args; } add_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 ); ``` When the quantity input is output, it's output with the `woocommerce_quantity_input()` function. This function accepts several arguments including the default value for the input. This filter lets you replace values in the arguments across all uses of the function.
292,308
<p>I have a client that wants to manage the editing process on a CPT called Floor Plan. They want to be able to preview and approve/deny all edits to a Floor Plan. I thought I had a solution by having an Admin account create a Floor Plan and have a Contributor enter the necessary content, finally being approved and published by the Admin. </p> <p>The problem comes when the Floor Plan needs to be updated. Once published, a Contributor can no longer edit a post. If we switch the user to Author, then they can edit the post, but the only option then is to Update. Which updates the content on the published page, and the client still wants to be able to approve/deny edits.</p> <p>I know an Author could send a preview link to the Admin that they could view while logged in and approve or deny, but the Author still has the ability to hit Update and update the published post with unapproved content.</p> <p>I have been toying with <a href="http://editflow.org/" rel="nofollow noreferrer">Edit Flow</a> but it doesn't seem to address this particular problem. Unless I'm just not setting it up properly.</p> <p>Is there even a way to do this? All my searching has found nothing.</p>
[ { "answer_id": 292297, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>You can use the <code>woocommerce_quantity_input_args</code> filter:</p>\n\n<pre><code>function wpse_292293_quantity_input_default( $args, $product ) {\n $args['input_value'] = 2;\n\n return $args;\n}\nadd_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 );\n</code></pre>\n\n<p>When the quantity input is output, it's output with the <code>woocommerce_quantity_input()</code> function. This function accepts several arguments including the default value for the input. This filter lets you replace values in the arguments across all uses of the function.</p>\n" }, { "answer_id": 374949, "author": "Aslam Khan", "author_id": 179201, "author_profile": "https://wordpress.stackexchange.com/users/179201", "pm_score": 1, "selected": false, "text": "<p>Using this code you can easy to set update quantity . qty box. i was also try this method\nit's working fine for me ...I hope it's also helpful thank you :)</p>\n<pre><code>function wpse_292293_quantity_input_default( $args, $product ) {\n\n\n$productID = $product-&gt;id;\n\nforeach( WC()-&gt;cart-&gt;get_cart() as $key =&gt; $item ){\n \n if( $item['product_id'] == $productID ){ \n $args['input_value'] = $item['quantity']; \n return $args; \n }\n \n} \n\n$args['input_value'] = 1;\nreturn $args;\n\n}\n add_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 );\n</code></pre>\n" }, { "answer_id": 405929, "author": "Sagive", "author_id": 7990, "author_profile": "https://wordpress.stackexchange.com/users/7990", "pm_score": 0, "selected": false, "text": "<p>There is a beautiful example in WooCommerce docs<br />\nthe example even includes a conditional amount.</p>\n<pre><code>/**\n * Adjust the quantity input values\n */\nadd_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 ); // Simple products\n\nfunction jk_woocommerce_quantity_input_args( $args, $product ) {\n if ( is_singular( 'product' ) ) {\n $args['input_value'] = 2; // Starting value (we only want to affect product pages, not cart)\n }\n $args['max_value'] = 80; // Maximum value\n $args['min_value'] = 2; // Minimum value\n $args['step'] = 2; // Quantity steps\n return $args;\n}\n</code></pre>\n<p>Ref:\n<a href=\"https://woocommerce.com/document/adjust-the-quantity-input-values/\" rel=\"nofollow noreferrer\">https://woocommerce.com/document/adjust-the-quantity-input-values/</a></p>\n<p>what you really need to set is the 'input_value' (meaning quantity) value. you have to change the min / max value or step values.. those control the actually input values.</p>\n" } ]
2018/01/26
[ "https://wordpress.stackexchange.com/questions/292308", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111880/" ]
I have a client that wants to manage the editing process on a CPT called Floor Plan. They want to be able to preview and approve/deny all edits to a Floor Plan. I thought I had a solution by having an Admin account create a Floor Plan and have a Contributor enter the necessary content, finally being approved and published by the Admin. The problem comes when the Floor Plan needs to be updated. Once published, a Contributor can no longer edit a post. If we switch the user to Author, then they can edit the post, but the only option then is to Update. Which updates the content on the published page, and the client still wants to be able to approve/deny edits. I know an Author could send a preview link to the Admin that they could view while logged in and approve or deny, but the Author still has the ability to hit Update and update the published post with unapproved content. I have been toying with [Edit Flow](http://editflow.org/) but it doesn't seem to address this particular problem. Unless I'm just not setting it up properly. Is there even a way to do this? All my searching has found nothing.
You can use the `woocommerce_quantity_input_args` filter: ``` function wpse_292293_quantity_input_default( $args, $product ) { $args['input_value'] = 2; return $args; } add_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 ); ``` When the quantity input is output, it's output with the `woocommerce_quantity_input()` function. This function accepts several arguments including the default value for the input. This filter lets you replace values in the arguments across all uses of the function.
292,315
<p>I have a problem! I have my website with wordpress. I only have one category and I want to have 5 categories. The problem is that I have published more than 7000 post. How can I use a word of the content of the post and relationship to one of the new categories.</p> <p>Example cat (word of the Post_content) ----> cat (new category)</p> <p>Please, How is the "SQL queries"? Thanks</p>
[ { "answer_id": 292297, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>You can use the <code>woocommerce_quantity_input_args</code> filter:</p>\n\n<pre><code>function wpse_292293_quantity_input_default( $args, $product ) {\n $args['input_value'] = 2;\n\n return $args;\n}\nadd_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 );\n</code></pre>\n\n<p>When the quantity input is output, it's output with the <code>woocommerce_quantity_input()</code> function. This function accepts several arguments including the default value for the input. This filter lets you replace values in the arguments across all uses of the function.</p>\n" }, { "answer_id": 374949, "author": "Aslam Khan", "author_id": 179201, "author_profile": "https://wordpress.stackexchange.com/users/179201", "pm_score": 1, "selected": false, "text": "<p>Using this code you can easy to set update quantity . qty box. i was also try this method\nit's working fine for me ...I hope it's also helpful thank you :)</p>\n<pre><code>function wpse_292293_quantity_input_default( $args, $product ) {\n\n\n$productID = $product-&gt;id;\n\nforeach( WC()-&gt;cart-&gt;get_cart() as $key =&gt; $item ){\n \n if( $item['product_id'] == $productID ){ \n $args['input_value'] = $item['quantity']; \n return $args; \n }\n \n} \n\n$args['input_value'] = 1;\nreturn $args;\n\n}\n add_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 );\n</code></pre>\n" }, { "answer_id": 405929, "author": "Sagive", "author_id": 7990, "author_profile": "https://wordpress.stackexchange.com/users/7990", "pm_score": 0, "selected": false, "text": "<p>There is a beautiful example in WooCommerce docs<br />\nthe example even includes a conditional amount.</p>\n<pre><code>/**\n * Adjust the quantity input values\n */\nadd_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 ); // Simple products\n\nfunction jk_woocommerce_quantity_input_args( $args, $product ) {\n if ( is_singular( 'product' ) ) {\n $args['input_value'] = 2; // Starting value (we only want to affect product pages, not cart)\n }\n $args['max_value'] = 80; // Maximum value\n $args['min_value'] = 2; // Minimum value\n $args['step'] = 2; // Quantity steps\n return $args;\n}\n</code></pre>\n<p>Ref:\n<a href=\"https://woocommerce.com/document/adjust-the-quantity-input-values/\" rel=\"nofollow noreferrer\">https://woocommerce.com/document/adjust-the-quantity-input-values/</a></p>\n<p>what you really need to set is the 'input_value' (meaning quantity) value. you have to change the min / max value or step values.. those control the actually input values.</p>\n" } ]
2018/01/26
[ "https://wordpress.stackexchange.com/questions/292315", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135643/" ]
I have a problem! I have my website with wordpress. I only have one category and I want to have 5 categories. The problem is that I have published more than 7000 post. How can I use a word of the content of the post and relationship to one of the new categories. Example cat (word of the Post\_content) ----> cat (new category) Please, How is the "SQL queries"? Thanks
You can use the `woocommerce_quantity_input_args` filter: ``` function wpse_292293_quantity_input_default( $args, $product ) { $args['input_value'] = 2; return $args; } add_filter( 'woocommerce_quantity_input_args', 'wpse_292293_quantity_input_default', 10, 2 ); ``` When the quantity input is output, it's output with the `woocommerce_quantity_input()` function. This function accepts several arguments including the default value for the input. This filter lets you replace values in the arguments across all uses of the function.
292,341
<p>In the following code I would like to remove the div that wrap all the code and pass its class to article, but I do not know how to pass the variable $termString inside the post_class.</p> <p>Can anybody help me?</p> <pre><code>&lt;div class="&lt;?php echo $termsString;?&gt;"&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class('card'); ?&gt;&gt; &lt;?php echo get_the_post_thumbnail($post_id, 'large', array('class' =&gt; 'img-fluid card-img-top')); ?&gt; &lt;div class="overlay"&gt;&lt;/div&gt; &lt;div class="card-body text-right"&gt; &lt;h6 class="card-title"&gt;&lt;?php the_title(); ?&gt;&lt;/h6&gt; &lt;p&gt;Text description for this item&lt;/p&gt; &lt;/div&gt; &lt;a class="card-link" href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title_attribute(); ?&gt;"&gt;&lt;/a&gt; &lt;/article&gt; &lt;/div&gt; </code></pre> <p>So, I have this now, and it is what I expected:</p> <pre><code>&lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class('card grid-item wow fadeInUp ' . $termsString); ?&gt;&gt; </code></pre> <p>but I also need to add to these classes another class that comes from a custom field which name is "columns" and with value "col-12".</p> <p>This is what I am trying, but I think there's some syntax error, the result I see from the Firefox inspector is "Array" instead of the value of "columns":</p> <pre><code>&lt;?php $custom_values = get_post_meta($post-&gt;ID, 'columns', true); ?&gt; &lt;?php $classes = array( 'card', 'grid-item', 'wow', 'fadeInUp', $termsString, $custom_values ); ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class( $classes ); ?&gt;&gt; </code></pre> <p><strong>Edit:</strong> get_post_meta requires a third parameter, "false" returns the Array (default), "true" returns only the first result (NOT as an array). Now it is working! Thanks a lot. </p>
[ { "answer_id": 292342, "author": "swissspidy", "author_id": 12404, "author_profile": "https://wordpress.stackexchange.com/users/12404", "pm_score": 1, "selected": false, "text": "<p>You should be able to just use <code>post_class( 'card ' . $termString )</code>.</p>\n\n<p>The function accepts arrays and strings, see <a href=\"https://developer.wordpress.org/reference/functions/post_class/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/post_class/</a></p>\n\n<p>You can also use the post_class filter to add more classes if you prefer that way.</p>\n" }, { "answer_id": 292346, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>The <code>post_class</code> function does also accept an array of classes. You can pass them to the function as follows:</p>\n\n<pre><code>$classes = [\n 'card',\n 'grid-item',\n 'wow',\n 'fadeInUp',\n $termsString\n];\n\n&lt;div &lt;?php post_class ( $classes ); ?&gt;&gt;\n ...\n&lt;/div&gt;\n</code></pre>\n\n<p>You can store the custom field's value inside a variable, and then pass it to the function just like any other value.</p>\n" } ]
2018/01/26
[ "https://wordpress.stackexchange.com/questions/292341", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/70257/" ]
In the following code I would like to remove the div that wrap all the code and pass its class to article, but I do not know how to pass the variable $termString inside the post\_class. Can anybody help me? ``` <div class="<?php echo $termsString;?>"> <article id="post-<?php the_ID(); ?>" <?php post_class('card'); ?>> <?php echo get_the_post_thumbnail($post_id, 'large', array('class' => 'img-fluid card-img-top')); ?> <div class="overlay"></div> <div class="card-body text-right"> <h6 class="card-title"><?php the_title(); ?></h6> <p>Text description for this item</p> </div> <a class="card-link" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"></a> </article> </div> ``` So, I have this now, and it is what I expected: ``` <article id="post-<?php the_ID(); ?>" <?php post_class('card grid-item wow fadeInUp ' . $termsString); ?>> ``` but I also need to add to these classes another class that comes from a custom field which name is "columns" and with value "col-12". This is what I am trying, but I think there's some syntax error, the result I see from the Firefox inspector is "Array" instead of the value of "columns": ``` <?php $custom_values = get_post_meta($post->ID, 'columns', true); ?> <?php $classes = array( 'card', 'grid-item', 'wow', 'fadeInUp', $termsString, $custom_values ); ?> <article id="post-<?php the_ID(); ?>" <?php post_class( $classes ); ?>> ``` **Edit:** get\_post\_meta requires a third parameter, "false" returns the Array (default), "true" returns only the first result (NOT as an array). Now it is working! Thanks a lot.
The `post_class` function does also accept an array of classes. You can pass them to the function as follows: ``` $classes = [ 'card', 'grid-item', 'wow', 'fadeInUp', $termsString ]; <div <?php post_class ( $classes ); ?>> ... </div> ``` You can store the custom field's value inside a variable, and then pass it to the function just like any other value.
292,351
<p>I have a problem with ajaxurl, I would like to know how I could fix this error code js "not defined" by designthemes-core-features.</p> <pre><code>jQuery.noConflict(); jQuery(document).ready(function($) { jQuery(document).on( 'click', '.dt-plugin-notice .notice-dismiss', function() { jQuery.ajax({ url: ajaxurl, data: { action: 'dt_plugin_dismiss_notice' } }); }); }); </code></pre> <p>Nota: is the plugin of a theme, this code can be found in the admin.js file inside the JS folder. The code "url: ajaxurl," (says: "ajaxurl is not defined") Would there be any idea? Would you like some more information? Thank you</p>
[ { "answer_id": 292362, "author": "Nitin Sharma", "author_id": 43126, "author_profile": "https://wordpress.stackexchange.com/users/43126", "pm_score": -1, "selected": false, "text": "<p>Please try</p>\n\n<pre><code>dttheme_urls.ajaxurl\n</code></pre>\n" }, { "answer_id": 292513, "author": "Mario", "author_id": 135681, "author_profile": "https://wordpress.stackexchange.com/users/135681", "pm_score": 0, "selected": false, "text": "<p>is the \"designthemes-core-features\" plugin of a theme, this code can be found in the admin.js file inside the JS folder.\nThe code \"<code>url: ajaxurl</code>,\" (says: \"ajaxurl is not defined\")\nWould there be any idea?\nWould you like some more information?\nThank you</p>\n" } ]
2018/01/27
[ "https://wordpress.stackexchange.com/questions/292351", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135681/" ]
I have a problem with ajaxurl, I would like to know how I could fix this error code js "not defined" by designthemes-core-features. ``` jQuery.noConflict(); jQuery(document).ready(function($) { jQuery(document).on( 'click', '.dt-plugin-notice .notice-dismiss', function() { jQuery.ajax({ url: ajaxurl, data: { action: 'dt_plugin_dismiss_notice' } }); }); }); ``` Nota: is the plugin of a theme, this code can be found in the admin.js file inside the JS folder. The code "url: ajaxurl," (says: "ajaxurl is not defined") Would there be any idea? Would you like some more information? Thank you
is the "designthemes-core-features" plugin of a theme, this code can be found in the admin.js file inside the JS folder. The code "`url: ajaxurl`," (says: "ajaxurl is not defined") Would there be any idea? Would you like some more information? Thank you
292,364
<pre><code>PHP Warning: file_put_contents(http://lendersmatch.ca/wp-content/uploads/deals/deal1.pdf): failed to open stream: HTTP wrapper does not support writeable connections in /home/t21jv08zz60b/public_html/wp-content/plugins/mortgage/fpdf181/fpdf.php on line 1023 [27-Jan-2018 11:24:20 UTC] PHP Fatal error: Uncaught Exception: FPDF error: Unable to create output file: http://lendersmatch.ca/wp-content/uploads/deals/deal1.pdf in </code></pre> <p>My Code:</p> <pre><code>$filename=$upload_path.'deals/deal'.$page-&gt;id.'.pdf'; ob_clean(); $pdf-&gt;Output('F',$filename); </code></pre> <p>FPDF:</p> <pre><code>if(!file_put_contents($name,$this-&gt;buffer)) $this-&gt;Error('Unable to create output file: '.$name); break; </code></pre>
[ { "answer_id": 292365, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 3, "selected": true, "text": "<p><code>$name</code> apparently contains a URL. That won't work. Set it to a local path, as you did with <code>$filename</code>:</p>\n\n<pre><code> $upload_dir = wp_upload_dir();\n $filename = $upload_dir[\"basedir\"] . '/deals/deal' . $page-&gt;id . '.pdf';\n</code></pre>\n" }, { "answer_id": 309432, "author": "SaHiL ShiKalgar", "author_id": 147475, "author_profile": "https://wordpress.stackexchange.com/users/147475", "pm_score": -1, "selected": false, "text": "<p>You should first open public_html folder on 000wenhostapp.com and open .htaccess file add only one line of code :</p>\n\n<pre><code>php_flag output_buffering on\n</code></pre>\n" } ]
2018/01/27
[ "https://wordpress.stackexchange.com/questions/292364", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/95126/" ]
``` PHP Warning: file_put_contents(http://lendersmatch.ca/wp-content/uploads/deals/deal1.pdf): failed to open stream: HTTP wrapper does not support writeable connections in /home/t21jv08zz60b/public_html/wp-content/plugins/mortgage/fpdf181/fpdf.php on line 1023 [27-Jan-2018 11:24:20 UTC] PHP Fatal error: Uncaught Exception: FPDF error: Unable to create output file: http://lendersmatch.ca/wp-content/uploads/deals/deal1.pdf in ``` My Code: ``` $filename=$upload_path.'deals/deal'.$page->id.'.pdf'; ob_clean(); $pdf->Output('F',$filename); ``` FPDF: ``` if(!file_put_contents($name,$this->buffer)) $this->Error('Unable to create output file: '.$name); break; ```
`$name` apparently contains a URL. That won't work. Set it to a local path, as you did with `$filename`: ``` $upload_dir = wp_upload_dir(); $filename = $upload_dir["basedir"] . '/deals/deal' . $page->id . '.pdf'; ```
292,417
<p>I have a section in my website where i want to display just the private posts for logged in users, but the loop returns all posts (private and publish), is it possible to change this? I have the next code in my loop:</p> <pre><code>global $listingsearch, $listing_query, $wp_query; $view = listingpress_get_listing_search_view(); $desktop_view = $view['d']; </code></pre> <p>And this</p> <pre><code>if ( $wp_query-&gt;have_posts() ) : </code></pre> <p>And this</p> <pre><code>while ( $wp_query-&gt;have_posts() ) : $wp_query-&gt;the_post(); </code></pre>
[ { "answer_id": 292428, "author": "Vlad Olaru", "author_id": 52726, "author_profile": "https://wordpress.stackexchange.com/users/52726", "pm_score": 3, "selected": false, "text": "<p>You need to filter the main WordPress query using the <code>pre_get_posts</code> <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"noreferrer\">action</a>. This code will get you started:</p>\n\n<pre><code>function show_only_private_post_for_logged_in_users( $query ) {\n\n if ( ! $query-&gt;is_main_query() || is_admin() ) {\n return;\n }\n\n if ( is_user_logged_in() ) {\n $query-&gt;set( 'post_status', 'private' );\n }\n}\nadd_action( 'pre_get_posts', 'show_only_private_post_for_logged_in_users' );\n</code></pre>\n\n<p>It will only affect the main query and not on the WordPress admin side. </p>\n" }, { "answer_id": 292432, "author": "epierpont", "author_id": 135073, "author_profile": "https://wordpress.stackexchange.com/users/135073", "pm_score": 1, "selected": false, "text": "<p>If you don't want to alter the main loop and you're looking for more of a widget/section I would throw something similar to the code below in functions.php:</p>\n\n<pre><code>function render_private_posts(){\n\n if ( is_user_logged_in() ) {\n\n $private_post_args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'private',\n 'posts_per_page'=&gt; 5\n );\n\n $private_posts = new WP_Query( $private_post_args );\n\n $private_post_output = NULL;\n if ( $private_posts-&gt;have_posts() ) {\n $private_post_output = '&lt;ul&gt;';\n\n while ( $private_posts-&gt;have_posts() ) {\n $private_posts-&gt;the_post();\n $private_post_output .= '&lt;li&gt;&lt;a href=\"' . get_the_permalink() . '\"&gt;' . get_the_title() . '&lt;/a&gt;&lt;/li&gt;';\n }\n\n $private_post_output .= '&lt;/ul&gt;';\n }\n\n wp_reset_postdata();\n return $private_post_output;\n\n }\n\n return false;\n\n}\n</code></pre>\n\n<p>You would then use <code>echo render_private_posts();</code> where you want it.</p>\n" }, { "answer_id": 292468, "author": "John", "author_id": 135380, "author_profile": "https://wordpress.stackexchange.com/users/135380", "pm_score": 0, "selected": false, "text": "<p>what you can do is to get posts in a loop and get their ids, and pass it in another loop inside the first loop and simple just put this function </p>\n\n<pre><code>&lt;?php\n if ( get_post_status ( $ID ) == 'private' ) {\n // do something here\n }\n?&gt;\n</code></pre>\n\n<p>and this will return posts with visibility status private.\nlook at this link for better understanding\n<a href=\"https://codex.wordpress.org/Function_Reference/get_post_status\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_post_status</a></p>\n\n<p>hope this helps</p>\n" } ]
2018/01/28
[ "https://wordpress.stackexchange.com/questions/292417", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135728/" ]
I have a section in my website where i want to display just the private posts for logged in users, but the loop returns all posts (private and publish), is it possible to change this? I have the next code in my loop: ``` global $listingsearch, $listing_query, $wp_query; $view = listingpress_get_listing_search_view(); $desktop_view = $view['d']; ``` And this ``` if ( $wp_query->have_posts() ) : ``` And this ``` while ( $wp_query->have_posts() ) : $wp_query->the_post(); ```
You need to filter the main WordPress query using the `pre_get_posts` [action](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts). This code will get you started: ``` function show_only_private_post_for_logged_in_users( $query ) { if ( ! $query->is_main_query() || is_admin() ) { return; } if ( is_user_logged_in() ) { $query->set( 'post_status', 'private' ); } } add_action( 'pre_get_posts', 'show_only_private_post_for_logged_in_users' ); ``` It will only affect the main query and not on the WordPress admin side.
292,418
<p>I need some posts excludes from displaying in wp_query in some conditons. I use below code to do it, and the code works correctly, but I set the <code>posts_per_page</code> to <code>12</code> and by this code the skiped posts are counted , for example instead of <code>12</code> post in each page it has different post numbers (10,2,5 , ...)</p> <pre><code>while( $query-&gt;have_posts() ){ $query-&gt;the_post(); if(condition) { //Show the post } } </code></pre>
[ { "answer_id": 292424, "author": "Vlad Olaru", "author_id": 52726, "author_profile": "https://wordpress.stackexchange.com/users/52726", "pm_score": 2, "selected": false, "text": "<p>To have the pagination work properly you need to filter the posts at the WordPress main query level using the <code>pre_get_posts</code> <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">action</a>.</p>\n\n<p>By looking at your code, I don't see where the post specific information is involved. Is <code>$course_options</code> holding information for the post?</p>\n" }, { "answer_id": 292433, "author": "Joel M", "author_id": 93297, "author_profile": "https://wordpress.stackexchange.com/users/93297", "pm_score": -1, "selected": false, "text": "<p>It will be tricky to make the pagination work when you are using php to filter out posts. When you go to page 2 for example the query will have an offset and limit parameter, effectively grabbing posts from 12 to 24 directly from the sql. filtering those won't do you any good unless the sql knows about which of the first 12 it has to skip. In most cases you are going to want to look into using a meta_query in the $wp_query, or your get_posts() function (both rely use more or less the same code in the end). A meta query will work for many things but if your condition is too complicated then it just might be the case that you cannot replicate the filtering via sql. please let us know the condition and i can show you how to write in a meta query. also if you did not write the $wp_query yourself (ie. your on a page where it was already run for you like archive.php) then you'll need to use the pre_get_posts action to add the meta_query to the $wp_query.</p>\n" } ]
2018/01/28
[ "https://wordpress.stackexchange.com/questions/292418", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135706/" ]
I need some posts excludes from displaying in wp\_query in some conditons. I use below code to do it, and the code works correctly, but I set the `posts_per_page` to `12` and by this code the skiped posts are counted , for example instead of `12` post in each page it has different post numbers (10,2,5 , ...) ``` while( $query->have_posts() ){ $query->the_post(); if(condition) { //Show the post } } ```
To have the pagination work properly you need to filter the posts at the WordPress main query level using the `pre_get_posts` [action](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts). By looking at your code, I don't see where the post specific information is involved. Is `$course_options` holding information for the post?
292,421
<p>How can I delete a field in my database under the posts table?</p> <p>For example in my <code>posts</code> table where the ID is 800 I would like to delete the a field under the column <code>product_rank</code>.</p> <p>Any help will be appreciated.</p>
[ { "answer_id": 292423, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 3, "selected": true, "text": "<p>You can't \"delete\" a field in MySQL, this only works for complete rows.</p>\n\n<p>However, you can unset values, meaning setting them to their original state, usually <code>NULL</code> or an empty string.</p>\n\n<pre><code>$wpdb-&gt;update($wpdb-&gt;posts, array(\n 'product_rank' =&gt; NULL\n), array(\n 'ID' =&gt; $post_id\n));\n</code></pre>\n" }, { "answer_id": 404830, "author": "Samidul Islam", "author_id": 192435, "author_profile": "https://wordpress.stackexchange.com/users/192435", "pm_score": 0, "selected": false, "text": "<p><strong>This code not working, show an error. I'm tried</strong></p>\n<p>Please look at this screenshot <a href=\"https://prnt.sc/M3DYH_EmHCtM\" rel=\"nofollow noreferrer\">https://prnt.sc/M3DYH_EmHCtM</a></p>\n<pre><code>global $wpdb;\n\n$id = $_REQUEST['delete'];\n\n$table = 'custom_user_info';\n\n$wpdb-&gt;delete( $table, array( 'id' =&gt; $id ) );\n</code></pre>\n<p><strong>But when I'm using this code, It's working perfectly</strong></p>\n<pre><code>$db_config = mysqli_connect('localhost', 'root', '', 'develop');\n\n$id = $_REQUEST['delete'];\n\n$delete = &quot;DELETE FROM custom_user_info WHERE id=$id&quot;;\n\n$query = mysqli_query($db_config, $delete);\n</code></pre>\n" } ]
2018/01/28
[ "https://wordpress.stackexchange.com/questions/292421", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/132644/" ]
How can I delete a field in my database under the posts table? For example in my `posts` table where the ID is 800 I would like to delete the a field under the column `product_rank`. Any help will be appreciated.
You can't "delete" a field in MySQL, this only works for complete rows. However, you can unset values, meaning setting them to their original state, usually `NULL` or an empty string. ``` $wpdb->update($wpdb->posts, array( 'product_rank' => NULL ), array( 'ID' => $post_id )); ```
292,487
<p>I need to create masonry grid containing the latest posts. I created a grid based on <a href="https://masonry.desandro.com/" rel="nofollow noreferrer">https://masonry.desandro.com/</a> - the grid displays correctly.</p> <p>I am asking for help in creating a wp loop that will display posts in the grid.</p> <p>This is my grid:</p> <pre><code>&lt;!-- grid masonry layout --&gt; &lt;div class="news-wrapper container"&gt; &lt;div class="grid"&gt; &lt;div class="grid-sizer"&gt;&lt;/div&gt; &lt;div class="gutter-sizer"&gt;&lt;/div&gt; &lt;div class="grid-item grid-item--width2"&gt;&lt;/div&gt; &lt;div class="grid-item grid-item--height2"&gt;&lt;/div&gt; &lt;div class="grid-item grid-item--width2"&gt;&lt;/div&gt; &lt;div class="grid-item"&gt;&lt;/div&gt; &lt;div class="grid-item grid-item--width2"&gt;&lt;/div&gt; &lt;div class="grid-item grid-item--width2"&gt;&lt;/div&gt; &lt;div class="grid-item grid-item--height2"&gt;&lt;/div&gt; &lt;div class="grid-item grid-item--height2"&gt;&lt;/div&gt; &lt;div class="grid-item grid-item--width2"&gt;&lt;/div&gt; &lt;div class="grid-item grid-item--width2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>A single grid element should contain a single post (name of the post category, title, description, read more button). Posts should be displayed from the date of inclusion, from selected categories.</p> <p>I created this code:</p> <pre><code> &lt;?php $args = array( array( 'category__and' =&gt; array( 55, 61, 53, 59, 57 ) ), 'post_status' =&gt; 'publish', 'orderby' =&gt; 'ASC' ); $news_query = null; $news_query = new WP_Query( $args ); ?&gt; &lt;!-- grid masonry layout --&gt; &lt;div class="news-wrapper container"&gt; &lt;div class="grid"&gt; &lt;?php if ($news_query-&gt;have_posts()) : ?&gt; &lt;?php $count = 0; ?&gt; &lt;?php while ($news_query-&gt;have_posts()) : $news_query-&gt;the_post(); ?&gt; &lt;?php $count++; ?&gt; &lt;div class="grid-sizer"&gt;&lt;/div&gt; &lt;div class="gutter-sizer"&gt;&lt;/div&gt; &lt;?php if ( $count == 1 ) : ?&gt; &lt;div class="grid-item grid-item--width2"&gt; &lt;div class="card card-media"&gt; &lt;a href="#"&gt; &lt;div class="news-cat"&gt;&lt;?php the_category(', '); ?&gt;&lt;/div&gt; &lt;/a&gt; &lt;div class="card-body"&gt; &lt;h5 class="card-title"&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h5&gt; &lt;p class="card-text"&gt;&lt;?php the_excerpt(); ?&gt;&lt;/p&gt; &lt;a href="#" class="btn"&gt;&lt;span class="nav-text"&gt;Read more&lt;/span&gt;&lt;i class="fa-xs fas fa-arrow-right"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php elseif ($count == 2) : ?&gt; &lt;div class="grid-item grid-item--height2"&gt; (..and next grid item...) </code></pre> <p>I have introduced counting, because the grid elements have different styling (sometimes double width, double height), so I can not create identical grid elements in the loop, so how to change counting to display all posts (regardless of their number)?</p>
[ { "answer_id": 292423, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 3, "selected": true, "text": "<p>You can't \"delete\" a field in MySQL, this only works for complete rows.</p>\n\n<p>However, you can unset values, meaning setting them to their original state, usually <code>NULL</code> or an empty string.</p>\n\n<pre><code>$wpdb-&gt;update($wpdb-&gt;posts, array(\n 'product_rank' =&gt; NULL\n), array(\n 'ID' =&gt; $post_id\n));\n</code></pre>\n" }, { "answer_id": 404830, "author": "Samidul Islam", "author_id": 192435, "author_profile": "https://wordpress.stackexchange.com/users/192435", "pm_score": 0, "selected": false, "text": "<p><strong>This code not working, show an error. I'm tried</strong></p>\n<p>Please look at this screenshot <a href=\"https://prnt.sc/M3DYH_EmHCtM\" rel=\"nofollow noreferrer\">https://prnt.sc/M3DYH_EmHCtM</a></p>\n<pre><code>global $wpdb;\n\n$id = $_REQUEST['delete'];\n\n$table = 'custom_user_info';\n\n$wpdb-&gt;delete( $table, array( 'id' =&gt; $id ) );\n</code></pre>\n<p><strong>But when I'm using this code, It's working perfectly</strong></p>\n<pre><code>$db_config = mysqli_connect('localhost', 'root', '', 'develop');\n\n$id = $_REQUEST['delete'];\n\n$delete = &quot;DELETE FROM custom_user_info WHERE id=$id&quot;;\n\n$query = mysqli_query($db_config, $delete);\n</code></pre>\n" } ]
2018/01/29
[ "https://wordpress.stackexchange.com/questions/292487", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135780/" ]
I need to create masonry grid containing the latest posts. I created a grid based on <https://masonry.desandro.com/> - the grid displays correctly. I am asking for help in creating a wp loop that will display posts in the grid. This is my grid: ``` <!-- grid masonry layout --> <div class="news-wrapper container"> <div class="grid"> <div class="grid-sizer"></div> <div class="gutter-sizer"></div> <div class="grid-item grid-item--width2"></div> <div class="grid-item grid-item--height2"></div> <div class="grid-item grid-item--width2"></div> <div class="grid-item"></div> <div class="grid-item grid-item--width2"></div> <div class="grid-item grid-item--width2"></div> <div class="grid-item grid-item--height2"></div> <div class="grid-item grid-item--height2"></div> <div class="grid-item grid-item--width2"></div> <div class="grid-item grid-item--width2"></div> </div> </div> ``` A single grid element should contain a single post (name of the post category, title, description, read more button). Posts should be displayed from the date of inclusion, from selected categories. I created this code: ``` <?php $args = array( array( 'category__and' => array( 55, 61, 53, 59, 57 ) ), 'post_status' => 'publish', 'orderby' => 'ASC' ); $news_query = null; $news_query = new WP_Query( $args ); ?> <!-- grid masonry layout --> <div class="news-wrapper container"> <div class="grid"> <?php if ($news_query->have_posts()) : ?> <?php $count = 0; ?> <?php while ($news_query->have_posts()) : $news_query->the_post(); ?> <?php $count++; ?> <div class="grid-sizer"></div> <div class="gutter-sizer"></div> <?php if ( $count == 1 ) : ?> <div class="grid-item grid-item--width2"> <div class="card card-media"> <a href="#"> <div class="news-cat"><?php the_category(', '); ?></div> </a> <div class="card-body"> <h5 class="card-title"><a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h5> <p class="card-text"><?php the_excerpt(); ?></p> <a href="#" class="btn"><span class="nav-text">Read more</span><i class="fa-xs fas fa-arrow-right"></i></a> </div> </div> </div> <?php elseif ($count == 2) : ?> <div class="grid-item grid-item--height2"> (..and next grid item...) ``` I have introduced counting, because the grid elements have different styling (sometimes double width, double height), so I can not create identical grid elements in the loop, so how to change counting to display all posts (regardless of their number)?
You can't "delete" a field in MySQL, this only works for complete rows. However, you can unset values, meaning setting them to their original state, usually `NULL` or an empty string. ``` $wpdb->update($wpdb->posts, array( 'product_rank' => NULL ), array( 'ID' => $post_id )); ```
292,545
<p>I am asking in the last instance because I am totally confused after not being able to invoke custom javascript functions for 2 days straight. I am new to Wordpress plugin developmnet as my background is Java and NodeJS and I simply can't understand why my code is not working.</p> <p>I want to append a script in the html head based on the success event of a login, logout, and some other stuff. So I thought I could hook into the <code>wp_registration</code>, <code>wp_login</code> function and so on, enrich some data for the call and send this to a custom javascript. However the custom javascript is only invoked when I am calling the php function in the <code>wp_head</code> hook or by doing <code>add_action ('wp_enqueue_scripts', 'my_function' );</code> and <strong>never</strong> in the hook function where I need the invocation.</p> <p>For testing purposes I have installed a clean Wordpress instance and have added the following function in my plugin:</p> <pre><code>function my_function() { wp_register_script( 'custom-script', plugin_dir_url( __FILE__ ) . 'hook-test.js' ); wp_enqueue_script('custom-script'); $testVars = array( 'test' =&gt; __('I should see something!'), ); wp_localize_script('custom-script', 'test_script_vars', $testVars); } </code></pre> <p>Now <strong>how</strong> can I use this in the form (or with an analogous functionality): <code>add_action('wp_login', 'my_function');</code> ?</p> <p>The javascript is never executed. But when I am doing <code>add_action('wp_head', 'my_function');</code> and <code>add_action ('wp_enqueue_scripts', 'my_function');</code> it is...</p> <p>I am welcoming any explanation and advice. Can't imagine this is so hard to achieve...</p>
[ { "answer_id": 292554, "author": "Stefano Tombolini", "author_id": 96268, "author_profile": "https://wordpress.stackexchange.com/users/96268", "pm_score": 0, "selected": false, "text": "<p>That hook will be deprecated in Ultimate Member 2.0.</p>\n\n<p>Beside that, have you added the actual hook with do_action in the header.php file of your theme? It is necessary for add_action to work.</p>\n\n<p>I'm not sure it's the best soulution though.</p>\n\n<p>I would rather register the script separately, \"localize\" it separately at um_user_registration (or its new equivalent on 2.0) and enqueue it conditionally using some function from Ultimate Member if available or a result of the registration stored ad hoc in usermeta if not available.</p>\n" }, { "answer_id": 292823, "author": "Vegaaaa", "author_id": 135841, "author_profile": "https://wordpress.stackexchange.com/users/135841", "pm_score": 1, "selected": false, "text": "<p>As it turned out it was not a matter of my code but of the fact that you cannot echo some custom javascript inside the 'wp_login' hook. What I did to solve this is to call <code>set_transient</code> inside my <code>wp_login</code> hook and then checking in the <code>wp_head</code> if there is any transient set. In this case I am echoing my javascript script and deleting the transient afterwards, as explained in this answer: <a href=\"https://wordpress.stackexchange.com/questions/38285/run-javascript-code-after-wp-login-hook\">Run javascript code after wp_login hook?</a></p>\n\n<p>My code now is:</p>\n\n<pre><code>/**\n * Register scripts used for pushing in the dataLayer\n */\nfunction add_my_scripts() {\n wp_register_script( 'custom-script', plugin_dir_url( __FILE__ ) . 'js/append_user_status.js' );\n}\n\n/**\n * Set transient in wp_login hook function\n */\nfunction wp_login_hook( $user_login ) {\n set_transient( $user_login, '1', 0 );\n}\n\n/**\n * Add wp_login_hook as wp_login hook function\n */\nadd_action( 'wp_login', 'wp_login_hook' );\n\n/**\n * Check if there is a transient set and echo js script in wp_head hook\n */\nfunction echo_javascript_after_wp_login() {\n global $current_user;\n\n if ( ! is_user_logged_in() )\n return;\n\n if ( ! get_transient( $current_user-&gt;user_login ) )\n return;\n\n $testVars = array(\n 'test' =&gt; __('I should see something!'),\n );\n wp_enqueue_script ( 'custom-script' );\n wp_localize_script('custom-script', 'test_script_vars', $testVars);\n delete_transient( $current_user-&gt;user_login );\n}\n\n/**\n * Add echo_javascript_after_wp_login function as wp_head hook\n */\nadd_action ('wp_head', 'echo_javascript_after_wp_login', 9 );\n</code></pre>\n\n<p>If there are no additions to this, I will mark it as the answer to the question to help possibly other beginners in wordpress plugin development.</p>\n" }, { "answer_id": 292828, "author": "swissspidy", "author_id": 12404, "author_profile": "https://wordpress.stackexchange.com/users/12404", "pm_score": 1, "selected": false, "text": "<p>WordPress has various hooks to enqueue scripts in different areas.</p>\n\n<p>For the front end it's <a href=\"https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/\" rel=\"nofollow noreferrer\"><code>wp_enqueue_scripts</code></a>, for the back end it's <a href=\"https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/\" rel=\"nofollow noreferrer\"><code>admin_enqueue_scripts</code></a>, and for the login page it's <a href=\"https://developer.wordpress.org/reference/hooks/login_enqueue_scripts/\" rel=\"nofollow noreferrer\"><code>login_enqueue_scripts</code></a>.</p>\n\n<p>I don't know Ultimate Members, but if it uses <code>wp-login.php</code> the <code>login_enqueue_scripts</code> hook should work.</p>\n\n<p>If <code>um_user_registration</code> is called somewhere else on the front end though, you should totally be able to enqueue some JavaScript when hooking into <code>um_user_registration</code>. It will just be added to the footer.</p>\n\n<p>The same with the <code>wp_login</code> hook. As long as this hook is called before <code>wp_footer()</code> in your theme, you should be able to enqueue any scripts directly.</p>\n" } ]
2018/01/30
[ "https://wordpress.stackexchange.com/questions/292545", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135841/" ]
I am asking in the last instance because I am totally confused after not being able to invoke custom javascript functions for 2 days straight. I am new to Wordpress plugin developmnet as my background is Java and NodeJS and I simply can't understand why my code is not working. I want to append a script in the html head based on the success event of a login, logout, and some other stuff. So I thought I could hook into the `wp_registration`, `wp_login` function and so on, enrich some data for the call and send this to a custom javascript. However the custom javascript is only invoked when I am calling the php function in the `wp_head` hook or by doing `add_action ('wp_enqueue_scripts', 'my_function' );` and **never** in the hook function where I need the invocation. For testing purposes I have installed a clean Wordpress instance and have added the following function in my plugin: ``` function my_function() { wp_register_script( 'custom-script', plugin_dir_url( __FILE__ ) . 'hook-test.js' ); wp_enqueue_script('custom-script'); $testVars = array( 'test' => __('I should see something!'), ); wp_localize_script('custom-script', 'test_script_vars', $testVars); } ``` Now **how** can I use this in the form (or with an analogous functionality): `add_action('wp_login', 'my_function');` ? The javascript is never executed. But when I am doing `add_action('wp_head', 'my_function');` and `add_action ('wp_enqueue_scripts', 'my_function');` it is... I am welcoming any explanation and advice. Can't imagine this is so hard to achieve...
As it turned out it was not a matter of my code but of the fact that you cannot echo some custom javascript inside the 'wp\_login' hook. What I did to solve this is to call `set_transient` inside my `wp_login` hook and then checking in the `wp_head` if there is any transient set. In this case I am echoing my javascript script and deleting the transient afterwards, as explained in this answer: [Run javascript code after wp\_login hook?](https://wordpress.stackexchange.com/questions/38285/run-javascript-code-after-wp-login-hook) My code now is: ``` /** * Register scripts used for pushing in the dataLayer */ function add_my_scripts() { wp_register_script( 'custom-script', plugin_dir_url( __FILE__ ) . 'js/append_user_status.js' ); } /** * Set transient in wp_login hook function */ function wp_login_hook( $user_login ) { set_transient( $user_login, '1', 0 ); } /** * Add wp_login_hook as wp_login hook function */ add_action( 'wp_login', 'wp_login_hook' ); /** * Check if there is a transient set and echo js script in wp_head hook */ function echo_javascript_after_wp_login() { global $current_user; if ( ! is_user_logged_in() ) return; if ( ! get_transient( $current_user->user_login ) ) return; $testVars = array( 'test' => __('I should see something!'), ); wp_enqueue_script ( 'custom-script' ); wp_localize_script('custom-script', 'test_script_vars', $testVars); delete_transient( $current_user->user_login ); } /** * Add echo_javascript_after_wp_login function as wp_head hook */ add_action ('wp_head', 'echo_javascript_after_wp_login', 9 ); ``` If there are no additions to this, I will mark it as the answer to the question to help possibly other beginners in wordpress plugin development.
292,552
<p>using the standard <code>__('some-string', 'myplugin')</code> for translations, strings are being correctly loaded for a Japanese (ja) locale in every function and script other than my AJAX functions.</p> <p><strong>my-plugin.php:</strong></p> <pre><code>*Text Domain: myplugin *Domain Path: /languages/ */ add_action( 'init', 'myplugin_load_textdomain' ); function myplugin_load_textdomain() { load_plugin_textdomain( 'myplugin', false, basename( dirname( __FILE__ ) ) . '/languages' ); } require_once(basename( dirname( __FILE__)."/classes/myplugin_handler.class.php"); global $myplugin_handler; $myplugin_handler = new myplugin_handler(); </code></pre> <p><strong>myplugin_handler.class.php:</strong></p> <pre><code>class myplugin_handler { public function __construct() { add_action('wp_ajax_myplugin_ajax', array($this, 'myplugin_ajax_handler')); add_action('wp_ajax_nopriv_myplugin_ajax', array($this, 'myplugin_ajax_handler')); } public function myplugin_ajax_handler() { if ($_POST['action'] != 'myplugin_ajax') { wp_die(0); } if (!check_ajax_referer('myplugin-ajax-nonce', 'security')) { wp_die(0); } $closemsg = __('Close', 'myplugin'); wp_die($closemsg); } } </code></pre> <p><em>Close</em> should translate to <em>閉じる</em> but it does not. Where translation does work: </p> <ul> <li>plugin function calls from the theme</li> <li>plugin function calls from an admin screen</li> <li><code>_e()</code> and <code>__()</code> calls in embedded js in the footer</li> <li>seemingly everywhere else besides AJAX functions</li> </ul> <p>any help is appreciated </p>
[ { "answer_id": 292553, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 1, "selected": false, "text": "<p>I think you just need to load the translations earlier to make them available for ajax hooks:</p>\n\n<pre><code>add_action( 'plugins_loaded', 'myplugin_load_textdomain' );\nfunction myplugin_load_textdomain() {\n load_plugin_textdomain( 'myplugin', false, basename( dirname( __FILE__ ) ) . '/languages' ); \n} \n</code></pre>\n" }, { "answer_id": 293156, "author": "Evan", "author_id": 135842, "author_profile": "https://wordpress.stackexchange.com/users/135842", "pm_score": 1, "selected": true, "text": "<p>It turns out I had a typo in the text domain for every call in my ajax function. For examples sake I entered the text domain as 'myplugin' in my question, but the real text domain is 'asumil-wishlist'. Instead of a hyphen I accidentally put an underscore, so <code>__('somestring', 'asumil-wishlist')</code> was <code>__('somestring', 'asumil_wishlist')</code>.</p>\n\n<p>Thanks anyways for the suggestions everyone.</p>\n" } ]
2018/01/30
[ "https://wordpress.stackexchange.com/questions/292552", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135842/" ]
using the standard `__('some-string', 'myplugin')` for translations, strings are being correctly loaded for a Japanese (ja) locale in every function and script other than my AJAX functions. **my-plugin.php:** ``` *Text Domain: myplugin *Domain Path: /languages/ */ add_action( 'init', 'myplugin_load_textdomain' ); function myplugin_load_textdomain() { load_plugin_textdomain( 'myplugin', false, basename( dirname( __FILE__ ) ) . '/languages' ); } require_once(basename( dirname( __FILE__)."/classes/myplugin_handler.class.php"); global $myplugin_handler; $myplugin_handler = new myplugin_handler(); ``` **myplugin\_handler.class.php:** ``` class myplugin_handler { public function __construct() { add_action('wp_ajax_myplugin_ajax', array($this, 'myplugin_ajax_handler')); add_action('wp_ajax_nopriv_myplugin_ajax', array($this, 'myplugin_ajax_handler')); } public function myplugin_ajax_handler() { if ($_POST['action'] != 'myplugin_ajax') { wp_die(0); } if (!check_ajax_referer('myplugin-ajax-nonce', 'security')) { wp_die(0); } $closemsg = __('Close', 'myplugin'); wp_die($closemsg); } } ``` *Close* should translate to *閉じる* but it does not. Where translation does work: * plugin function calls from the theme * plugin function calls from an admin screen * `_e()` and `__()` calls in embedded js in the footer * seemingly everywhere else besides AJAX functions any help is appreciated
It turns out I had a typo in the text domain for every call in my ajax function. For examples sake I entered the text domain as 'myplugin' in my question, but the real text domain is 'asumil-wishlist'. Instead of a hyphen I accidentally put an underscore, so `__('somestring', 'asumil-wishlist')` was `__('somestring', 'asumil_wishlist')`. Thanks anyways for the suggestions everyone.
292,562
<p>I'm a Javascript developer and I am very new to PHP/Wordpress. So just like what I saw from samples around the internet I wrote my <code>functions.php</code> script to add my custom css file like this: </p> <p><strong>functions.php</strong></p> <pre><code>&lt;?php echo '&lt;h1&gt;CASH ME OUTSIDE&lt;/h1&gt;'; add_action('wp_enqueue_scripts', 'theme_styles'); function theme_styles() { echo '&lt;h1&gt;CASH ME INSIDE&lt;/h1&gt;'; wp_enqueue_style('theme_styles', get_template_directory_uri() . '/foo.css'); } ?&gt; </code></pre> <p>To check if the <code>functions.php</code> is being called I printed <code>&lt;h1&gt;CASH ME OUTSIDE&lt;/h1&gt;</code> and it did appear. How ever the echo inside the function <code>theme_styles()</code> is not being printed which leads me to the conclusion that the function is not being called. </p>
[ { "answer_id": 292563, "author": "Zex2911", "author_id": 51804, "author_profile": "https://wordpress.stackexchange.com/users/51804", "pm_score": 2, "selected": false, "text": "<p>View source for your website and CTRL+F for foo.css. wp_enqueue_scripts registers script / style and loads it on your website, it doesn't echo anything. \nHeader.php must have wp_head() tag, and footer.php must have wp_footer() tag.</p>\n" }, { "answer_id": 292566, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 1, "selected": false, "text": "<p><code>enqueue_scripts()</code> is not a hook which actually outputs anything by itself as it is run before the page is constructed - any output you put in there (which you shouldn't anyway) will be wiped away when the page is displayed. What it does is to add your script files to the list of scripts which will be printed by the <code>wp_head()</code> or <code>wp_footer()</code> functions. </p>\n\n<p>The best way to test a non-printing hook is to add something like </p>\n\n<p><code>echo \"&lt;h1&gt;CASH ME INSIDE&lt;/h1&gt;\"; wp_die();</code> </p>\n\n<p>the 2nd part of which will cause everything to come to an abrupt halt, thus not replacing your output with the actual page.</p>\n\n<p>Hope that helps</p>\n" }, { "answer_id": 292568, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 3, "selected": true, "text": "<p>A <code>echo</code> in functions.php, <code>wp_enqueue_scripts</code> or any other non-template file probably breaks the output due to a fatal error because of headers already sent. <code>echo</code> is not a proper way to debug. Delete the echo statements and check the HTML of the page, your css should be there. To debug, use error logs.</p>\n\n<p>Other than that, your code seems correct; be sure to include <code>wp_head()</code> and <code>wp_footer()</code> in your theme. Those functions are needed to print the enqueued scripts and styles; then just do this:</p>\n\n<pre><code> add_action('wp_enqueue_scripts', 'theme_styles');\n function theme_styles() {\n\n // You can use error_log, a native PHP function,\n // or any other custom log function\n if( WP_DEBUG ) {\n error_log('some debug information');\n }\n\n wp_enqueue_style('theme_styles', get_template_directory_uri() . '/foo.css');\n }\n</code></pre>\n" } ]
2018/01/30
[ "https://wordpress.stackexchange.com/questions/292562", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135849/" ]
I'm a Javascript developer and I am very new to PHP/Wordpress. So just like what I saw from samples around the internet I wrote my `functions.php` script to add my custom css file like this: **functions.php** ``` <?php echo '<h1>CASH ME OUTSIDE</h1>'; add_action('wp_enqueue_scripts', 'theme_styles'); function theme_styles() { echo '<h1>CASH ME INSIDE</h1>'; wp_enqueue_style('theme_styles', get_template_directory_uri() . '/foo.css'); } ?> ``` To check if the `functions.php` is being called I printed `<h1>CASH ME OUTSIDE</h1>` and it did appear. How ever the echo inside the function `theme_styles()` is not being printed which leads me to the conclusion that the function is not being called.
A `echo` in functions.php, `wp_enqueue_scripts` or any other non-template file probably breaks the output due to a fatal error because of headers already sent. `echo` is not a proper way to debug. Delete the echo statements and check the HTML of the page, your css should be there. To debug, use error logs. Other than that, your code seems correct; be sure to include `wp_head()` and `wp_footer()` in your theme. Those functions are needed to print the enqueued scripts and styles; then just do this: ``` add_action('wp_enqueue_scripts', 'theme_styles'); function theme_styles() { // You can use error_log, a native PHP function, // or any other custom log function if( WP_DEBUG ) { error_log('some debug information'); } wp_enqueue_style('theme_styles', get_template_directory_uri() . '/foo.css'); } ```
292,565
<p>I'm currently facing a few loose ends while dealing with the homepage of a theme I am working on. I got my loop set up to show the most recent posts in a certain style and it works perfectly.</p> <p>Now I am trying to position two sticky posts (or even posts from a certain category) on top of that loop, utilizing different styling and showing only a thumbnail and the headline. I want them to be up there no matter how old they are and want the regular loop to begin just below of them. Like on a typical magazine website, the top content stays where it is while the blog content below gets new posts more often. Please see attached draft. </p> <p><a href="https://i.stack.imgur.com/ocmHc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ocmHc.png" alt="Sticky posts above loop"></a></p> <p>I really don't know how to incorporate the two posts above my loop. I'd really appreciate any hint in the right direction where to start. </p>
[ { "answer_id": 292570, "author": "Quang Hoang", "author_id": 134874, "author_profile": "https://wordpress.stackexchange.com/users/134874", "pm_score": 1, "selected": false, "text": "<p>I think you should add a css class and in your loop, put a <code>$i</code> and let <code>$i</code> run, <code>if $i == 2</code> then you add the css class attribute to that sticky post.</p>\n\n<pre><code>$i = 0;\nwhile( have_posts() ):\n the_post();\n $i++;\n if($i == 2):\n $css_class = 'top-sticky';\n else:\n $css_class = ''; \n endif;\n\nendwhile;\nwp_reset_postdata();\n</code></pre>\n" }, { "answer_id": 292575, "author": "Vlad Olaru", "author_id": 52726, "author_profile": "https://wordpress.stackexchange.com/users/52726", "pm_score": 0, "selected": false, "text": "<p>You first need to have some way of marking these posts as they might change in time. Your best bet is to use a \"special\" tag (like <code>featured</code>) like Jetpack's <a href=\"https://jetpack.com/support/featured-content/\" rel=\"nofollow noreferrer\">Featured Content</a> module does (it also gives you a nice way of deciding what tag to use via the Customizer).</p>\n\n<p>After you have that setup, you use a custom query loop and display only those posts above the regular loop.</p>\n\n<p>To keep those featured posts out of the regular/main loop, you need to use the <code>pre_get_posts</code> action hook and, depending on certain conditions (maybe you only show the featured posts on your homepage - <code>is_home()</code>, not in category or tags archives), you exclude those posts by setting the <code>post__not_in</code> <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters\" rel=\"nofollow noreferrer\">WP_Query</a> parameter.</p>\n" } ]
2018/01/30
[ "https://wordpress.stackexchange.com/questions/292565", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76017/" ]
I'm currently facing a few loose ends while dealing with the homepage of a theme I am working on. I got my loop set up to show the most recent posts in a certain style and it works perfectly. Now I am trying to position two sticky posts (or even posts from a certain category) on top of that loop, utilizing different styling and showing only a thumbnail and the headline. I want them to be up there no matter how old they are and want the regular loop to begin just below of them. Like on a typical magazine website, the top content stays where it is while the blog content below gets new posts more often. Please see attached draft. [![Sticky posts above loop](https://i.stack.imgur.com/ocmHc.png)](https://i.stack.imgur.com/ocmHc.png) I really don't know how to incorporate the two posts above my loop. I'd really appreciate any hint in the right direction where to start.
I think you should add a css class and in your loop, put a `$i` and let `$i` run, `if $i == 2` then you add the css class attribute to that sticky post. ``` $i = 0; while( have_posts() ): the_post(); $i++; if($i == 2): $css_class = 'top-sticky'; else: $css_class = ''; endif; endwhile; wp_reset_postdata(); ```
292,567
<p>I have this simple piece of code that is not working:</p> <pre><code> if ( 'publish' != $post-&gt;post_status ) { return; } </code></pre> <p>When I use this in my code, it blocks posts that should have a status of 'publish'.</p> <p>If I replace this with:</p> <pre><code> if ( 'publish' != get_post_status( $post_id) ) { return; } </code></pre> <p>It works, however this is working on the post status from the last save, not the current edit activity.</p> <p>I've tried all sorts of combinations alternatives, but I still can't get it work. Any ideas what I may be doing wrong?</p>
[ { "answer_id": 292570, "author": "Quang Hoang", "author_id": 134874, "author_profile": "https://wordpress.stackexchange.com/users/134874", "pm_score": 1, "selected": false, "text": "<p>I think you should add a css class and in your loop, put a <code>$i</code> and let <code>$i</code> run, <code>if $i == 2</code> then you add the css class attribute to that sticky post.</p>\n\n<pre><code>$i = 0;\nwhile( have_posts() ):\n the_post();\n $i++;\n if($i == 2):\n $css_class = 'top-sticky';\n else:\n $css_class = ''; \n endif;\n\nendwhile;\nwp_reset_postdata();\n</code></pre>\n" }, { "answer_id": 292575, "author": "Vlad Olaru", "author_id": 52726, "author_profile": "https://wordpress.stackexchange.com/users/52726", "pm_score": 0, "selected": false, "text": "<p>You first need to have some way of marking these posts as they might change in time. Your best bet is to use a \"special\" tag (like <code>featured</code>) like Jetpack's <a href=\"https://jetpack.com/support/featured-content/\" rel=\"nofollow noreferrer\">Featured Content</a> module does (it also gives you a nice way of deciding what tag to use via the Customizer).</p>\n\n<p>After you have that setup, you use a custom query loop and display only those posts above the regular loop.</p>\n\n<p>To keep those featured posts out of the regular/main loop, you need to use the <code>pre_get_posts</code> action hook and, depending on certain conditions (maybe you only show the featured posts on your homepage - <code>is_home()</code>, not in category or tags archives), you exclude those posts by setting the <code>post__not_in</code> <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters\" rel=\"nofollow noreferrer\">WP_Query</a> parameter.</p>\n" } ]
2018/01/30
[ "https://wordpress.stackexchange.com/questions/292567", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134279/" ]
I have this simple piece of code that is not working: ``` if ( 'publish' != $post->post_status ) { return; } ``` When I use this in my code, it blocks posts that should have a status of 'publish'. If I replace this with: ``` if ( 'publish' != get_post_status( $post_id) ) { return; } ``` It works, however this is working on the post status from the last save, not the current edit activity. I've tried all sorts of combinations alternatives, but I still can't get it work. Any ideas what I may be doing wrong?
I think you should add a css class and in your loop, put a `$i` and let `$i` run, `if $i == 2` then you add the css class attribute to that sticky post. ``` $i = 0; while( have_posts() ): the_post(); $i++; if($i == 2): $css_class = 'top-sticky'; else: $css_class = ''; endif; endwhile; wp_reset_postdata(); ```
292,585
<p>I need a link to enable downloading of each audio file item within the native wordpress playlist.</p> <p>I've used the script from this thread >> <a href="https://wordpress.stackexchange.com/questions/141767/download-button-for-wp-audio-player">Download button for wp audio player</a></p> <p>but there isn't the ability to ask questions of the poster. I've just used the bottom script by Dave Romsey and placed it in a custom script plugin. Have I missed something by doing this? This produces a download icon on the right of the playlist item, has a hover state, but simply starts the playlist item when clicked.</p> <pre><code>&lt;script&gt; /** * Our custom playlist template for mp3 download`. */ function wpse_141767_wp_underscore_playlist_templates() { ?&gt; &lt;script type="text/html" id="tmpl-wp-playlist-current-item"&gt; &lt;# if ( data.image ) { #&gt; &lt;img src="{{ data.thumb.src }}"/&gt; &lt;# } #&gt; &lt;div class="wp-playlist-caption"&gt; &lt;span class="wp-playlist-item-meta wp-playlist-item-title"&gt;&amp;#8220;{{ data.title }}&amp;#8221;&lt;/span&gt; &lt;# if ( data.meta.album ) { #&gt;&lt;span class="wp-playlist-item-meta wp-playlist-item-album"&gt;{{ data.meta.album }}&lt;/span&gt;&lt;# } #&gt; &lt;# if ( data.meta.artist ) { #&gt;&lt;span class="wp-playlist-item-meta wp-playlist-item-artist"&gt;{{ data.meta.artist }}&lt;/span&gt;&lt;# } #&gt; &lt;/div&gt; &lt;/script&gt; &lt;script type="text/html" id="tmpl-wp-playlist-item"&gt; &lt;div class="wp-playlist-item"&gt; &lt;a class="wp-playlist-caption" href="{{ data.src }}"&gt; {{ data.index ? ( data.index + '. ' ) : '' }} &lt;# if ( data.caption ) { #&gt; {{ data.caption }} &lt;# } else { #&gt; &lt;span class="wp-playlist-item-title"&gt;&amp;#8220;{{{ data.title }}}&amp;#8221;&lt;/span&gt; &lt;# if ( data.artists &amp;&amp; data.meta.artist ) { #&gt; &lt;span class="wp-playlist-item-artist"&gt; &amp;mdash; {{ data.meta.artist }}&lt;/span&gt; &lt;# } #&gt; &lt;# } #&gt; &lt;/a&gt; &lt;# if ( data.meta.length_formatted ) { #&gt; &lt;div class="wp-playlist-item-length"&gt;&lt;span&gt; &lt;a href="{{ data.src }}"&gt;&lt;i class="fa fa-download" title="Download" aria-hidden="true"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/span&gt;{{ data.meta.length_formatted }}&lt;/div&gt; &lt;# } #&gt; &lt;/div&gt; &lt;/script&gt; &lt;?php } &lt;/script&gt; </code></pre> <p>but, as mentioned (and within that thread), the icon doesn't start a download, it simply activates the play function of the playlist item. I've tried moving the download icon section below the div (I'd still like it in it's original position if possible) to hopefully move the span outside of the div to remove it from the play attribute that everything inside that div obviously activates but this just opens the mp3 file in a new browser window:</p> <pre><code>&lt;div class="wp-playlist-item-length"&gt;&lt;span&gt; &lt;a href="{{ data.src }}"&gt;&lt;i class="fa fa-download" title="download" aria-hidden="true"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/span&gt;{{ data.meta.length_formatted }}&lt;/div&gt; &lt;# } #&gt; &lt;/div&gt; &lt;span&gt; &lt;a href="{{ data.src }}"&gt;&lt;i class="fa fa-download" title="download" aria-hidden="true"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/span&gt; </code></pre> <p>Is there a way to have the originally located download icon actually open a 'save' dialogue for each mp3? I'm no coder so not sure if this was what was supposed to happen when clicking the icon in the previous thread as there is no working example?</p> <p>I'm very grateful for the other thread as it's almost there but just need the icon to actually activate.</p> <p>Any help gratefully received. Thanks in advance : )</p> <p>edit: I found this earlier which apparently stops the parent event being triggered by the child. I've tried to incorporate this into the above code, at the top, but it doesn't work (no surprise there since I don't really understand the code) However, this still wouldn't give me a 'save as' dialogue but would stop the download button playing the clip.</p> <pre><code>$("#parentEle").click( function(e) { alert('parent ele clicked'); }); $("#parentEle").children().click( function(e) { //this prevent the event from bubbling to any event higher than the direct children e.stopPropagation(); }); </code></pre>
[ { "answer_id": 292736, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 1, "selected": false, "text": "<p>Actually, for the majority of modern browsers all you need to do is add <code>download</code> to your <code>&lt;a&gt;</code> element, eg:</p>\n\n<p><code>&lt;a href=\"{{ data.src }}\" download &gt;</code></p>\n" }, { "answer_id": 292952, "author": "Blix", "author_id": 135855, "author_profile": "https://wordpress.stackexchange.com/users/135855", "pm_score": 2, "selected": false, "text": "<p>Thanks to both of you for your help.\nJust so it might help others, this is what I did:\nDownloaded a wordpress plugin to allow custom scripts. I used this one >> <a href=\"https://wordpress.org/plugins/header-and-footer-scripts-inserter/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/header-and-footer-scripts-inserter/</a></p>\n\n<p>I then pasted this code within the plugin (thanks to Birgire above &amp; <a href=\"https://wordpress.stackexchange.com/a/142974/26350\">HERE</a> :</p>\n\n<pre><code>&lt;script type=\"text/html\" id=\"tmpl-wp-playlist-current-item\"&gt;\n &lt;# if ( data.image ) { #&gt;\n &lt;img src=\"{{ data.thumb.src }}\"/&gt;\n &lt;# } #&gt;\n &lt;div class=\"wp-playlist-caption\"&gt;\n &lt;span class=\"wp-playlist-item-meta wp-playlist-item-title\"&gt;{{ data.title }}&lt;/span&gt;\n &lt;# if ( data.meta.album ) { #&gt;&lt;span class=\"wp-playlist-item-meta wp-playlist-item-album\"&gt;{{ data.meta.album }}&lt;/span&gt;&lt;# } #&gt;\n &lt;# if ( data.meta.artist ) { #&gt;&lt;span class=\"wp-playlist-item-meta wp-playlist-item-artist\"&gt;{{ data.meta.artist }}&lt;/span&gt;&lt;# } #&gt;\n &lt;/div&gt;\n\n&lt;/script&gt;\n&lt;script type=\"text/html\" id=\"tmpl-wp-playlist-item\"&gt;\n &lt;div class=\"wp-playlist-item\"&gt;\n &lt;a class=\"wp-playlist-caption\" href=\"{{ data.src }}\"&gt;\n {{ data.index ? ( data.index + '. ' ) : '' }}\n &lt;# if ( data.caption ) { #&gt;\n {{ data.caption }}\n &lt;# } else { #&gt;\n &lt;span class=\"wp-playlist-item-title\"&gt;{{{ data.title }}}&lt;/span&gt;\n &lt;# if ( data.artists &amp;&amp; data.meta.artist ) { #&gt;\n &lt;span class=\"wp-playlist-item-artist\"&gt; — {{ data.meta.artist }}&lt;/span&gt;\n &lt;# } #&gt;\n &lt;# } #&gt;\n &lt;/a&gt;\n &lt;# if ( data.meta.length_formatted ) { #&gt;\n &lt;div class=\"wp-playlist-item-length\"&gt;{{ data.meta.length_formatted }}&lt;/div&gt;\n &lt;# } #&gt; \n &lt;/div&gt;\n\n &lt;!-- BEGIN CHANGES --&gt;\n &lt;a href=\"{{ data.src }}\" class=\"wpse-download\" download=\"\"&gt;&lt;i class=\"fa fa-download\" title=\"Download\" aria-hidden=\"true\"&gt;&lt;/i&gt;&lt;/a&gt;\n &lt;!-- END CHANGES --&gt;\n &lt;/script&gt;\n</code></pre>\n\n<p>\n\n<p>In the above code I also removed the speech / quote marks around the playlist title (this is hard coded into the WP core. I had asked a different question about removing these but this code resolves this too. Good times : )</p>\n\n<p>I then altered the css to place the download icon at the beginning, in front of the playlist title, then padded the title over to the right so it all fitted. (it was the 'absolute' positioning that I needed to stop this activating the playlist rather than the download)</p>\n\n<pre><code>/*playlist title - more to right*/\n.wp-playlist-item-title {\n padding-left:25px\n}\n\n/*download link styles - move within playlist &amp; to left of playlist title*/\n\n.wpse-download {\n margin-top: -22px;\n padding-left:5px;\n position: absolute;\n}\n\n/*change color of icon*/\n.wpse-download {\n color:white!important;\n}\n\n/*change hover / active state of download icon*/\n.wpse-download:hover, .wpse-download:visited\n{\n color:#aaa!important;\n}\n</code></pre>\n\n<p>I have styled the playlist further to suit my needs but here is what I ended up with. Thanks again : )</p>\n\n<p><a href=\"https://i.stack.imgur.com/DolFh.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DolFh.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2018/01/30
[ "https://wordpress.stackexchange.com/questions/292585", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135855/" ]
I need a link to enable downloading of each audio file item within the native wordpress playlist. I've used the script from this thread >> [Download button for wp audio player](https://wordpress.stackexchange.com/questions/141767/download-button-for-wp-audio-player) but there isn't the ability to ask questions of the poster. I've just used the bottom script by Dave Romsey and placed it in a custom script plugin. Have I missed something by doing this? This produces a download icon on the right of the playlist item, has a hover state, but simply starts the playlist item when clicked. ``` <script> /** * Our custom playlist template for mp3 download`. */ function wpse_141767_wp_underscore_playlist_templates() { ?> <script type="text/html" id="tmpl-wp-playlist-current-item"> <# if ( data.image ) { #> <img src="{{ data.thumb.src }}"/> <# } #> <div class="wp-playlist-caption"> <span class="wp-playlist-item-meta wp-playlist-item-title">&#8220;{{ data.title }}&#8221;</span> <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #> <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #> </div> </script> <script type="text/html" id="tmpl-wp-playlist-item"> <div class="wp-playlist-item"> <a class="wp-playlist-caption" href="{{ data.src }}"> {{ data.index ? ( data.index + '. ' ) : '' }} <# if ( data.caption ) { #> {{ data.caption }} <# } else { #> <span class="wp-playlist-item-title">&#8220;{{{ data.title }}}&#8221;</span> <# if ( data.artists && data.meta.artist ) { #> <span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span> <# } #> <# } #> </a> <# if ( data.meta.length_formatted ) { #> <div class="wp-playlist-item-length"><span> <a href="{{ data.src }}"><i class="fa fa-download" title="Download" aria-hidden="true"></i></a> </span>{{ data.meta.length_formatted }}</div> <# } #> </div> </script> <?php } </script> ``` but, as mentioned (and within that thread), the icon doesn't start a download, it simply activates the play function of the playlist item. I've tried moving the download icon section below the div (I'd still like it in it's original position if possible) to hopefully move the span outside of the div to remove it from the play attribute that everything inside that div obviously activates but this just opens the mp3 file in a new browser window: ``` <div class="wp-playlist-item-length"><span> <a href="{{ data.src }}"><i class="fa fa-download" title="download" aria-hidden="true"></i></a> </span>{{ data.meta.length_formatted }}</div> <# } #> </div> <span> <a href="{{ data.src }}"><i class="fa fa-download" title="download" aria-hidden="true"></i></a> </span> ``` Is there a way to have the originally located download icon actually open a 'save' dialogue for each mp3? I'm no coder so not sure if this was what was supposed to happen when clicking the icon in the previous thread as there is no working example? I'm very grateful for the other thread as it's almost there but just need the icon to actually activate. Any help gratefully received. Thanks in advance : ) edit: I found this earlier which apparently stops the parent event being triggered by the child. I've tried to incorporate this into the above code, at the top, but it doesn't work (no surprise there since I don't really understand the code) However, this still wouldn't give me a 'save as' dialogue but would stop the download button playing the clip. ``` $("#parentEle").click( function(e) { alert('parent ele clicked'); }); $("#parentEle").children().click( function(e) { //this prevent the event from bubbling to any event higher than the direct children e.stopPropagation(); }); ```
Thanks to both of you for your help. Just so it might help others, this is what I did: Downloaded a wordpress plugin to allow custom scripts. I used this one >> <https://wordpress.org/plugins/header-and-footer-scripts-inserter/> I then pasted this code within the plugin (thanks to Birgire above & [HERE](https://wordpress.stackexchange.com/a/142974/26350) : ``` <script type="text/html" id="tmpl-wp-playlist-current-item"> <# if ( data.image ) { #> <img src="{{ data.thumb.src }}"/> <# } #> <div class="wp-playlist-caption"> <span class="wp-playlist-item-meta wp-playlist-item-title">{{ data.title }}</span> <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #> <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #> </div> </script> <script type="text/html" id="tmpl-wp-playlist-item"> <div class="wp-playlist-item"> <a class="wp-playlist-caption" href="{{ data.src }}"> {{ data.index ? ( data.index + '. ' ) : '' }} <# if ( data.caption ) { #> {{ data.caption }} <# } else { #> <span class="wp-playlist-item-title">{{{ data.title }}}</span> <# if ( data.artists && data.meta.artist ) { #> <span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span> <# } #> <# } #> </a> <# if ( data.meta.length_formatted ) { #> <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div> <# } #> </div> <!-- BEGIN CHANGES --> <a href="{{ data.src }}" class="wpse-download" download=""><i class="fa fa-download" title="Download" aria-hidden="true"></i></a> <!-- END CHANGES --> </script> ``` In the above code I also removed the speech / quote marks around the playlist title (this is hard coded into the WP core. I had asked a different question about removing these but this code resolves this too. Good times : ) I then altered the css to place the download icon at the beginning, in front of the playlist title, then padded the title over to the right so it all fitted. (it was the 'absolute' positioning that I needed to stop this activating the playlist rather than the download) ``` /*playlist title - more to right*/ .wp-playlist-item-title { padding-left:25px } /*download link styles - move within playlist & to left of playlist title*/ .wpse-download { margin-top: -22px; padding-left:5px; position: absolute; } /*change color of icon*/ .wpse-download { color:white!important; } /*change hover / active state of download icon*/ .wpse-download:hover, .wpse-download:visited { color:#aaa!important; } ``` I have styled the playlist further to suit my needs but here is what I ended up with. Thanks again : ) [![enter image description here](https://i.stack.imgur.com/DolFh.jpg)](https://i.stack.imgur.com/DolFh.jpg)
292,617
<p>I have created several custom post types (for example: FAQs, products and case studies) and registered a global custom taxonomy for use across all CPTs. In my case this taxonomy is called <em>audiences</em>. These are listed as consumers, architects and merchants.</p> <p>In this example I'll use FAQs in the Merchants taxonomy.</p> <hr> <p>I'm struggling to figure out how to filter the FAQs to show for a specific audience. My <code>archive-faqs.php</code> lists all FAQs regardless of audience type.</p> <p>I want to be able to show all the FAQs tagged as merchant. What are my options for this?</p> <ul> <li>Do I create a custom <code>page.php</code> template and create a custom loop for it?</li> <li>Do I some how amend my <code>archive-faqs.php</code> to grab a query string?</li> <li>Is there a better way for me to achieve this goal?</li> </ul>
[ { "answer_id": 292736, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 1, "selected": false, "text": "<p>Actually, for the majority of modern browsers all you need to do is add <code>download</code> to your <code>&lt;a&gt;</code> element, eg:</p>\n\n<p><code>&lt;a href=\"{{ data.src }}\" download &gt;</code></p>\n" }, { "answer_id": 292952, "author": "Blix", "author_id": 135855, "author_profile": "https://wordpress.stackexchange.com/users/135855", "pm_score": 2, "selected": false, "text": "<p>Thanks to both of you for your help.\nJust so it might help others, this is what I did:\nDownloaded a wordpress plugin to allow custom scripts. I used this one >> <a href=\"https://wordpress.org/plugins/header-and-footer-scripts-inserter/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/header-and-footer-scripts-inserter/</a></p>\n\n<p>I then pasted this code within the plugin (thanks to Birgire above &amp; <a href=\"https://wordpress.stackexchange.com/a/142974/26350\">HERE</a> :</p>\n\n<pre><code>&lt;script type=\"text/html\" id=\"tmpl-wp-playlist-current-item\"&gt;\n &lt;# if ( data.image ) { #&gt;\n &lt;img src=\"{{ data.thumb.src }}\"/&gt;\n &lt;# } #&gt;\n &lt;div class=\"wp-playlist-caption\"&gt;\n &lt;span class=\"wp-playlist-item-meta wp-playlist-item-title\"&gt;{{ data.title }}&lt;/span&gt;\n &lt;# if ( data.meta.album ) { #&gt;&lt;span class=\"wp-playlist-item-meta wp-playlist-item-album\"&gt;{{ data.meta.album }}&lt;/span&gt;&lt;# } #&gt;\n &lt;# if ( data.meta.artist ) { #&gt;&lt;span class=\"wp-playlist-item-meta wp-playlist-item-artist\"&gt;{{ data.meta.artist }}&lt;/span&gt;&lt;# } #&gt;\n &lt;/div&gt;\n\n&lt;/script&gt;\n&lt;script type=\"text/html\" id=\"tmpl-wp-playlist-item\"&gt;\n &lt;div class=\"wp-playlist-item\"&gt;\n &lt;a class=\"wp-playlist-caption\" href=\"{{ data.src }}\"&gt;\n {{ data.index ? ( data.index + '. ' ) : '' }}\n &lt;# if ( data.caption ) { #&gt;\n {{ data.caption }}\n &lt;# } else { #&gt;\n &lt;span class=\"wp-playlist-item-title\"&gt;{{{ data.title }}}&lt;/span&gt;\n &lt;# if ( data.artists &amp;&amp; data.meta.artist ) { #&gt;\n &lt;span class=\"wp-playlist-item-artist\"&gt; — {{ data.meta.artist }}&lt;/span&gt;\n &lt;# } #&gt;\n &lt;# } #&gt;\n &lt;/a&gt;\n &lt;# if ( data.meta.length_formatted ) { #&gt;\n &lt;div class=\"wp-playlist-item-length\"&gt;{{ data.meta.length_formatted }}&lt;/div&gt;\n &lt;# } #&gt; \n &lt;/div&gt;\n\n &lt;!-- BEGIN CHANGES --&gt;\n &lt;a href=\"{{ data.src }}\" class=\"wpse-download\" download=\"\"&gt;&lt;i class=\"fa fa-download\" title=\"Download\" aria-hidden=\"true\"&gt;&lt;/i&gt;&lt;/a&gt;\n &lt;!-- END CHANGES --&gt;\n &lt;/script&gt;\n</code></pre>\n\n<p>\n\n<p>In the above code I also removed the speech / quote marks around the playlist title (this is hard coded into the WP core. I had asked a different question about removing these but this code resolves this too. Good times : )</p>\n\n<p>I then altered the css to place the download icon at the beginning, in front of the playlist title, then padded the title over to the right so it all fitted. (it was the 'absolute' positioning that I needed to stop this activating the playlist rather than the download)</p>\n\n<pre><code>/*playlist title - more to right*/\n.wp-playlist-item-title {\n padding-left:25px\n}\n\n/*download link styles - move within playlist &amp; to left of playlist title*/\n\n.wpse-download {\n margin-top: -22px;\n padding-left:5px;\n position: absolute;\n}\n\n/*change color of icon*/\n.wpse-download {\n color:white!important;\n}\n\n/*change hover / active state of download icon*/\n.wpse-download:hover, .wpse-download:visited\n{\n color:#aaa!important;\n}\n</code></pre>\n\n<p>I have styled the playlist further to suit my needs but here is what I ended up with. Thanks again : )</p>\n\n<p><a href=\"https://i.stack.imgur.com/DolFh.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DolFh.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2018/01/30
[ "https://wordpress.stackexchange.com/questions/292617", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62753/" ]
I have created several custom post types (for example: FAQs, products and case studies) and registered a global custom taxonomy for use across all CPTs. In my case this taxonomy is called *audiences*. These are listed as consumers, architects and merchants. In this example I'll use FAQs in the Merchants taxonomy. --- I'm struggling to figure out how to filter the FAQs to show for a specific audience. My `archive-faqs.php` lists all FAQs regardless of audience type. I want to be able to show all the FAQs tagged as merchant. What are my options for this? * Do I create a custom `page.php` template and create a custom loop for it? * Do I some how amend my `archive-faqs.php` to grab a query string? * Is there a better way for me to achieve this goal?
Thanks to both of you for your help. Just so it might help others, this is what I did: Downloaded a wordpress plugin to allow custom scripts. I used this one >> <https://wordpress.org/plugins/header-and-footer-scripts-inserter/> I then pasted this code within the plugin (thanks to Birgire above & [HERE](https://wordpress.stackexchange.com/a/142974/26350) : ``` <script type="text/html" id="tmpl-wp-playlist-current-item"> <# if ( data.image ) { #> <img src="{{ data.thumb.src }}"/> <# } #> <div class="wp-playlist-caption"> <span class="wp-playlist-item-meta wp-playlist-item-title">{{ data.title }}</span> <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #> <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #> </div> </script> <script type="text/html" id="tmpl-wp-playlist-item"> <div class="wp-playlist-item"> <a class="wp-playlist-caption" href="{{ data.src }}"> {{ data.index ? ( data.index + '. ' ) : '' }} <# if ( data.caption ) { #> {{ data.caption }} <# } else { #> <span class="wp-playlist-item-title">{{{ data.title }}}</span> <# if ( data.artists && data.meta.artist ) { #> <span class="wp-playlist-item-artist"> — {{ data.meta.artist }}</span> <# } #> <# } #> </a> <# if ( data.meta.length_formatted ) { #> <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div> <# } #> </div> <!-- BEGIN CHANGES --> <a href="{{ data.src }}" class="wpse-download" download=""><i class="fa fa-download" title="Download" aria-hidden="true"></i></a> <!-- END CHANGES --> </script> ``` In the above code I also removed the speech / quote marks around the playlist title (this is hard coded into the WP core. I had asked a different question about removing these but this code resolves this too. Good times : ) I then altered the css to place the download icon at the beginning, in front of the playlist title, then padded the title over to the right so it all fitted. (it was the 'absolute' positioning that I needed to stop this activating the playlist rather than the download) ``` /*playlist title - more to right*/ .wp-playlist-item-title { padding-left:25px } /*download link styles - move within playlist & to left of playlist title*/ .wpse-download { margin-top: -22px; padding-left:5px; position: absolute; } /*change color of icon*/ .wpse-download { color:white!important; } /*change hover / active state of download icon*/ .wpse-download:hover, .wpse-download:visited { color:#aaa!important; } ``` I have styled the playlist further to suit my needs but here is what I ended up with. Thanks again : ) [![enter image description here](https://i.stack.imgur.com/DolFh.jpg)](https://i.stack.imgur.com/DolFh.jpg)
292,639
<p>I created a plugin that displays staff people using a shortcode with custom category from a post type. eg. [board-members term="team1"] It works fine but only on a page or post. When I paste the shortcode into a tab (using whistles by Justin Tadlock) the profiles display outside the tab, above the tabs in the page body. what could I do to make it display inside the tab? This is the code...</p> <pre><code>require_once(dirname(__FILE__).'/post-type.php'); //file that registers CPT function wporg_shortcodes_init(){ function wporg_shortcode($atts = []) { extract( shortcode_atts( array( 'term' =&gt; 'columns' ), $atts ) ); $custom_taxonomy = $atts['term']; // add query of custom post type board_members $recentPosts = new WP_Query (array('posts_per_page' =&gt; -1, 'post_type' =&gt; array('board_members'), 'columns' =&gt; $custom_taxonomy )); while( $recentPosts-&gt;have_posts() ) : $recentPosts-&gt;the_post(); ?&gt; &lt;div class="b-thumb"&gt;&lt;?php the_post_thumbnail('thumbnail') ?&gt;&lt;/div&gt; &lt;p class="b-info"&gt; &lt;span class="b-name"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;br /&gt; &lt;span class="b-country"&gt;&lt;?php the_field('country'); ?&gt;&lt;/span&gt;&lt;br /&gt; &lt;span class="b-position"&gt;&lt;?php the_field('position'); ?&gt;&lt;/span&gt;&lt;br /&gt; &lt;span class="b-content"&gt;&lt;?php printf(get_the_content()); ?&gt;&lt;/span&gt;&lt;br /&gt; &lt;/p&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php endwhile; ?&gt; &lt;?php } add_shortcode('board-members', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); </code></pre> <p>Thanks</p>
[ { "answer_id": 292642, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>If you want content to display in a specific spot, you will need to wrap the content in a <code>&lt;div&gt;</code> with a 'class', where the 'class' has the CSS you need to display the content.</p>\n\n<p>The shortcode works on pages/posts because the shortcode is contained within the content of the page/post, in the <code>&lt;div&gt;</code> that surrounds the post content.</p>\n\n<p>You will need to make a class (called 'myshortcode') of and use that in your loop:</p>\n\n<pre><code>&lt;div class='myshortcode'&gt;\n &lt;div class=\"b-thumb\"&gt;&lt;?php the_post_thumbnail('thumbnail') ?&gt;&lt;/div&gt;\n &lt;p class=\"b-info\"&gt;\n &lt;span class=\"b-name\"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;br /&gt; \n &lt;span class=\"b-country\"&gt;&lt;?php the_field('country'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-position\"&gt;&lt;?php the_field('position'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-content\"&gt;&lt;?php printf(get_the_content()); ?&gt;&lt;/span&gt;&lt;br /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Then, some CSS for that new class:</p>\n\n<pre><code>.myshortcode {\n /* some CSS here */\n}\n</code></pre>\n" }, { "answer_id": 292643, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 3, "selected": true, "text": "<p>Sounds like you need to wrap your shortcode contents in <code>ob_start()</code>and <code>return ob_get_clean()</code></p>\n\n<pre><code>require_once(dirname(__FILE__).'/post-type.php'); //file that registers CPT\n\nfunction wporg_shortcodes_init(){\nfunction wporg_shortcode($atts = []) {\n extract( shortcode_atts( array(\n 'term' =&gt; 'columns'\n ), $atts ) );\n\n $custom_taxonomy = $atts['term']; \n\n ob_start(); // &lt;- works like magic\n\n // add query of custom post type board_members \n $recentPosts = new WP_Query\n (array('posts_per_page' =&gt; -1, 'post_type' =&gt; array('board_members'), 'columns' =&gt; $custom_taxonomy )); \n while( $recentPosts-&gt;have_posts() ) : $recentPosts-&gt;the_post(); ?&gt;\n\n &lt;div class=\"b-thumb\"&gt;&lt;?php the_post_thumbnail('thumbnail') ?&gt;&lt;/div&gt;\n &lt;p class=\"b-info\"&gt;\n &lt;span class=\"b-name\"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;br /&gt; \n &lt;span class=\"b-country\"&gt;&lt;?php the_field('country'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-position\"&gt;&lt;?php the_field('position'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-content\"&gt;&lt;?php printf(get_the_content()); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;/p&gt; \n\n &lt;?php wp_reset_postdata(); ?&gt; \n &lt;?php endwhile; ?&gt; \n &lt;?php \n\n return ob_get_clean(); // &lt;- more magic\n\n }\n add_shortcode('board-members', 'wporg_shortcode');\n }\n add_action('init', 'wporg_shortcodes_init'); \n</code></pre>\n\n<p>You can also modify the shortcode to return a single string, the following should work as well:</p>\n\n<pre><code>function wporg_shortcodes_init(){\n function wporg_shortcode($atts = []) {\n extract( shortcode_atts( array(\n 'term' =&gt; 'columns'\n ), $atts ) );\n\n $custom_taxonomy = $atts['term']; \n\n $output = '';\n\n // add query of custom post type board_members \n $recentPosts = new WP_Query\n (array('posts_per_page' =&gt; -1, 'post_type' =&gt; array('board_members'), 'columns' =&gt; $custom_taxonomy )); \n while( $recentPosts-&gt;have_posts() ) : $recentPosts-&gt;the_post();\n\n $output .= '&lt;div class=\"b-thumb\"&gt;'.the_post_thumbnail('thumbnail').'&lt;/div&gt;';\n $output .= '&lt;p class=\"b-info\"&gt;';\n $output .= '&lt;span class=\"b-name\"&gt;'.the_title().'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-country\"&gt;'.the_field('country').'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-position\"&gt;'.the_field('position').'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-content\"&gt;'.printf(get_the_content()).'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;/p&gt; ';\n\n endwhile;\n\n wp_reset_postdata();\n\n return $output;\n\n }\n add_shortcode('board-members', 'wporg_shortcode');\n}\nadd_action('init', 'wporg_shortcodes_init'); \n</code></pre>\n" } ]
2018/01/31
[ "https://wordpress.stackexchange.com/questions/292639", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67916/" ]
I created a plugin that displays staff people using a shortcode with custom category from a post type. eg. [board-members term="team1"] It works fine but only on a page or post. When I paste the shortcode into a tab (using whistles by Justin Tadlock) the profiles display outside the tab, above the tabs in the page body. what could I do to make it display inside the tab? This is the code... ``` require_once(dirname(__FILE__).'/post-type.php'); //file that registers CPT function wporg_shortcodes_init(){ function wporg_shortcode($atts = []) { extract( shortcode_atts( array( 'term' => 'columns' ), $atts ) ); $custom_taxonomy = $atts['term']; // add query of custom post type board_members $recentPosts = new WP_Query (array('posts_per_page' => -1, 'post_type' => array('board_members'), 'columns' => $custom_taxonomy )); while( $recentPosts->have_posts() ) : $recentPosts->the_post(); ?> <div class="b-thumb"><?php the_post_thumbnail('thumbnail') ?></div> <p class="b-info"> <span class="b-name"><?php the_title(); ?></span><br /> <span class="b-country"><?php the_field('country'); ?></span><br /> <span class="b-position"><?php the_field('position'); ?></span><br /> <span class="b-content"><?php printf(get_the_content()); ?></span><br /> </p> <?php wp_reset_postdata(); ?> <?php endwhile; ?> <?php } add_shortcode('board-members', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); ``` Thanks
Sounds like you need to wrap your shortcode contents in `ob_start()`and `return ob_get_clean()` ``` require_once(dirname(__FILE__).'/post-type.php'); //file that registers CPT function wporg_shortcodes_init(){ function wporg_shortcode($atts = []) { extract( shortcode_atts( array( 'term' => 'columns' ), $atts ) ); $custom_taxonomy = $atts['term']; ob_start(); // <- works like magic // add query of custom post type board_members $recentPosts = new WP_Query (array('posts_per_page' => -1, 'post_type' => array('board_members'), 'columns' => $custom_taxonomy )); while( $recentPosts->have_posts() ) : $recentPosts->the_post(); ?> <div class="b-thumb"><?php the_post_thumbnail('thumbnail') ?></div> <p class="b-info"> <span class="b-name"><?php the_title(); ?></span><br /> <span class="b-country"><?php the_field('country'); ?></span><br /> <span class="b-position"><?php the_field('position'); ?></span><br /> <span class="b-content"><?php printf(get_the_content()); ?></span><br /> </p> <?php wp_reset_postdata(); ?> <?php endwhile; ?> <?php return ob_get_clean(); // <- more magic } add_shortcode('board-members', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); ``` You can also modify the shortcode to return a single string, the following should work as well: ``` function wporg_shortcodes_init(){ function wporg_shortcode($atts = []) { extract( shortcode_atts( array( 'term' => 'columns' ), $atts ) ); $custom_taxonomy = $atts['term']; $output = ''; // add query of custom post type board_members $recentPosts = new WP_Query (array('posts_per_page' => -1, 'post_type' => array('board_members'), 'columns' => $custom_taxonomy )); while( $recentPosts->have_posts() ) : $recentPosts->the_post(); $output .= '<div class="b-thumb">'.the_post_thumbnail('thumbnail').'</div>'; $output .= '<p class="b-info">'; $output .= '<span class="b-name">'.the_title().'</span><br />'; $output .= '<span class="b-country">'.the_field('country').'</span><br />'; $output .= '<span class="b-position">'.the_field('position').'</span><br />'; $output .= '<span class="b-content">'.printf(get_the_content()).'</span><br />'; $output .= '</p> '; endwhile; wp_reset_postdata(); return $output; } add_shortcode('board-members', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); ```
292,651
<p>I have a legacy theme that has a lot of page template files. My site is too big to go through each page one by one to check it's template.</p> <p>Is there any way (either through adding a column to the pages list in the the backend, or in the database directly) to see which templates files are being used and determine which are surplus?</p>
[ { "answer_id": 292642, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>If you want content to display in a specific spot, you will need to wrap the content in a <code>&lt;div&gt;</code> with a 'class', where the 'class' has the CSS you need to display the content.</p>\n\n<p>The shortcode works on pages/posts because the shortcode is contained within the content of the page/post, in the <code>&lt;div&gt;</code> that surrounds the post content.</p>\n\n<p>You will need to make a class (called 'myshortcode') of and use that in your loop:</p>\n\n<pre><code>&lt;div class='myshortcode'&gt;\n &lt;div class=\"b-thumb\"&gt;&lt;?php the_post_thumbnail('thumbnail') ?&gt;&lt;/div&gt;\n &lt;p class=\"b-info\"&gt;\n &lt;span class=\"b-name\"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;br /&gt; \n &lt;span class=\"b-country\"&gt;&lt;?php the_field('country'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-position\"&gt;&lt;?php the_field('position'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-content\"&gt;&lt;?php printf(get_the_content()); ?&gt;&lt;/span&gt;&lt;br /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Then, some CSS for that new class:</p>\n\n<pre><code>.myshortcode {\n /* some CSS here */\n}\n</code></pre>\n" }, { "answer_id": 292643, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 3, "selected": true, "text": "<p>Sounds like you need to wrap your shortcode contents in <code>ob_start()</code>and <code>return ob_get_clean()</code></p>\n\n<pre><code>require_once(dirname(__FILE__).'/post-type.php'); //file that registers CPT\n\nfunction wporg_shortcodes_init(){\nfunction wporg_shortcode($atts = []) {\n extract( shortcode_atts( array(\n 'term' =&gt; 'columns'\n ), $atts ) );\n\n $custom_taxonomy = $atts['term']; \n\n ob_start(); // &lt;- works like magic\n\n // add query of custom post type board_members \n $recentPosts = new WP_Query\n (array('posts_per_page' =&gt; -1, 'post_type' =&gt; array('board_members'), 'columns' =&gt; $custom_taxonomy )); \n while( $recentPosts-&gt;have_posts() ) : $recentPosts-&gt;the_post(); ?&gt;\n\n &lt;div class=\"b-thumb\"&gt;&lt;?php the_post_thumbnail('thumbnail') ?&gt;&lt;/div&gt;\n &lt;p class=\"b-info\"&gt;\n &lt;span class=\"b-name\"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;br /&gt; \n &lt;span class=\"b-country\"&gt;&lt;?php the_field('country'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-position\"&gt;&lt;?php the_field('position'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-content\"&gt;&lt;?php printf(get_the_content()); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;/p&gt; \n\n &lt;?php wp_reset_postdata(); ?&gt; \n &lt;?php endwhile; ?&gt; \n &lt;?php \n\n return ob_get_clean(); // &lt;- more magic\n\n }\n add_shortcode('board-members', 'wporg_shortcode');\n }\n add_action('init', 'wporg_shortcodes_init'); \n</code></pre>\n\n<p>You can also modify the shortcode to return a single string, the following should work as well:</p>\n\n<pre><code>function wporg_shortcodes_init(){\n function wporg_shortcode($atts = []) {\n extract( shortcode_atts( array(\n 'term' =&gt; 'columns'\n ), $atts ) );\n\n $custom_taxonomy = $atts['term']; \n\n $output = '';\n\n // add query of custom post type board_members \n $recentPosts = new WP_Query\n (array('posts_per_page' =&gt; -1, 'post_type' =&gt; array('board_members'), 'columns' =&gt; $custom_taxonomy )); \n while( $recentPosts-&gt;have_posts() ) : $recentPosts-&gt;the_post();\n\n $output .= '&lt;div class=\"b-thumb\"&gt;'.the_post_thumbnail('thumbnail').'&lt;/div&gt;';\n $output .= '&lt;p class=\"b-info\"&gt;';\n $output .= '&lt;span class=\"b-name\"&gt;'.the_title().'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-country\"&gt;'.the_field('country').'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-position\"&gt;'.the_field('position').'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-content\"&gt;'.printf(get_the_content()).'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;/p&gt; ';\n\n endwhile;\n\n wp_reset_postdata();\n\n return $output;\n\n }\n add_shortcode('board-members', 'wporg_shortcode');\n}\nadd_action('init', 'wporg_shortcodes_init'); \n</code></pre>\n" } ]
2018/01/31
[ "https://wordpress.stackexchange.com/questions/292651", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135910/" ]
I have a legacy theme that has a lot of page template files. My site is too big to go through each page one by one to check it's template. Is there any way (either through adding a column to the pages list in the the backend, or in the database directly) to see which templates files are being used and determine which are surplus?
Sounds like you need to wrap your shortcode contents in `ob_start()`and `return ob_get_clean()` ``` require_once(dirname(__FILE__).'/post-type.php'); //file that registers CPT function wporg_shortcodes_init(){ function wporg_shortcode($atts = []) { extract( shortcode_atts( array( 'term' => 'columns' ), $atts ) ); $custom_taxonomy = $atts['term']; ob_start(); // <- works like magic // add query of custom post type board_members $recentPosts = new WP_Query (array('posts_per_page' => -1, 'post_type' => array('board_members'), 'columns' => $custom_taxonomy )); while( $recentPosts->have_posts() ) : $recentPosts->the_post(); ?> <div class="b-thumb"><?php the_post_thumbnail('thumbnail') ?></div> <p class="b-info"> <span class="b-name"><?php the_title(); ?></span><br /> <span class="b-country"><?php the_field('country'); ?></span><br /> <span class="b-position"><?php the_field('position'); ?></span><br /> <span class="b-content"><?php printf(get_the_content()); ?></span><br /> </p> <?php wp_reset_postdata(); ?> <?php endwhile; ?> <?php return ob_get_clean(); // <- more magic } add_shortcode('board-members', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); ``` You can also modify the shortcode to return a single string, the following should work as well: ``` function wporg_shortcodes_init(){ function wporg_shortcode($atts = []) { extract( shortcode_atts( array( 'term' => 'columns' ), $atts ) ); $custom_taxonomy = $atts['term']; $output = ''; // add query of custom post type board_members $recentPosts = new WP_Query (array('posts_per_page' => -1, 'post_type' => array('board_members'), 'columns' => $custom_taxonomy )); while( $recentPosts->have_posts() ) : $recentPosts->the_post(); $output .= '<div class="b-thumb">'.the_post_thumbnail('thumbnail').'</div>'; $output .= '<p class="b-info">'; $output .= '<span class="b-name">'.the_title().'</span><br />'; $output .= '<span class="b-country">'.the_field('country').'</span><br />'; $output .= '<span class="b-position">'.the_field('position').'</span><br />'; $output .= '<span class="b-content">'.printf(get_the_content()).'</span><br />'; $output .= '</p> '; endwhile; wp_reset_postdata(); return $output; } add_shortcode('board-members', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); ```
292,662
<p>If two vendors has the same product then when the second vendor publish the product in to the store, 2 is appended to the permalink since the same product from the first vendor already exist</p> <p>Is there any solution to remove the numeric from the permalink? Ideally, the two permalinks should look like this:</p> <p><a href="http://example.com/author-1/post-title/" rel="nofollow noreferrer">http://example.com/author-1/post-title/</a></p> <p><a href="http://example.com/author-2/post-title/" rel="nofollow noreferrer">http://example.com/author-2/post-title/</a></p> <p>But when I publish the second post, then its slug is changed to post-title-2, which makes the resulting URL <a href="http://example.com/author-2/post-title-2/" rel="nofollow noreferrer">http://example.com/author-2/post-title-2/</a>.</p>
[ { "answer_id": 292642, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>If you want content to display in a specific spot, you will need to wrap the content in a <code>&lt;div&gt;</code> with a 'class', where the 'class' has the CSS you need to display the content.</p>\n\n<p>The shortcode works on pages/posts because the shortcode is contained within the content of the page/post, in the <code>&lt;div&gt;</code> that surrounds the post content.</p>\n\n<p>You will need to make a class (called 'myshortcode') of and use that in your loop:</p>\n\n<pre><code>&lt;div class='myshortcode'&gt;\n &lt;div class=\"b-thumb\"&gt;&lt;?php the_post_thumbnail('thumbnail') ?&gt;&lt;/div&gt;\n &lt;p class=\"b-info\"&gt;\n &lt;span class=\"b-name\"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;br /&gt; \n &lt;span class=\"b-country\"&gt;&lt;?php the_field('country'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-position\"&gt;&lt;?php the_field('position'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-content\"&gt;&lt;?php printf(get_the_content()); ?&gt;&lt;/span&gt;&lt;br /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Then, some CSS for that new class:</p>\n\n<pre><code>.myshortcode {\n /* some CSS here */\n}\n</code></pre>\n" }, { "answer_id": 292643, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 3, "selected": true, "text": "<p>Sounds like you need to wrap your shortcode contents in <code>ob_start()</code>and <code>return ob_get_clean()</code></p>\n\n<pre><code>require_once(dirname(__FILE__).'/post-type.php'); //file that registers CPT\n\nfunction wporg_shortcodes_init(){\nfunction wporg_shortcode($atts = []) {\n extract( shortcode_atts( array(\n 'term' =&gt; 'columns'\n ), $atts ) );\n\n $custom_taxonomy = $atts['term']; \n\n ob_start(); // &lt;- works like magic\n\n // add query of custom post type board_members \n $recentPosts = new WP_Query\n (array('posts_per_page' =&gt; -1, 'post_type' =&gt; array('board_members'), 'columns' =&gt; $custom_taxonomy )); \n while( $recentPosts-&gt;have_posts() ) : $recentPosts-&gt;the_post(); ?&gt;\n\n &lt;div class=\"b-thumb\"&gt;&lt;?php the_post_thumbnail('thumbnail') ?&gt;&lt;/div&gt;\n &lt;p class=\"b-info\"&gt;\n &lt;span class=\"b-name\"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;br /&gt; \n &lt;span class=\"b-country\"&gt;&lt;?php the_field('country'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-position\"&gt;&lt;?php the_field('position'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-content\"&gt;&lt;?php printf(get_the_content()); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;/p&gt; \n\n &lt;?php wp_reset_postdata(); ?&gt; \n &lt;?php endwhile; ?&gt; \n &lt;?php \n\n return ob_get_clean(); // &lt;- more magic\n\n }\n add_shortcode('board-members', 'wporg_shortcode');\n }\n add_action('init', 'wporg_shortcodes_init'); \n</code></pre>\n\n<p>You can also modify the shortcode to return a single string, the following should work as well:</p>\n\n<pre><code>function wporg_shortcodes_init(){\n function wporg_shortcode($atts = []) {\n extract( shortcode_atts( array(\n 'term' =&gt; 'columns'\n ), $atts ) );\n\n $custom_taxonomy = $atts['term']; \n\n $output = '';\n\n // add query of custom post type board_members \n $recentPosts = new WP_Query\n (array('posts_per_page' =&gt; -1, 'post_type' =&gt; array('board_members'), 'columns' =&gt; $custom_taxonomy )); \n while( $recentPosts-&gt;have_posts() ) : $recentPosts-&gt;the_post();\n\n $output .= '&lt;div class=\"b-thumb\"&gt;'.the_post_thumbnail('thumbnail').'&lt;/div&gt;';\n $output .= '&lt;p class=\"b-info\"&gt;';\n $output .= '&lt;span class=\"b-name\"&gt;'.the_title().'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-country\"&gt;'.the_field('country').'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-position\"&gt;'.the_field('position').'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-content\"&gt;'.printf(get_the_content()).'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;/p&gt; ';\n\n endwhile;\n\n wp_reset_postdata();\n\n return $output;\n\n }\n add_shortcode('board-members', 'wporg_shortcode');\n}\nadd_action('init', 'wporg_shortcodes_init'); \n</code></pre>\n" } ]
2018/01/31
[ "https://wordpress.stackexchange.com/questions/292662", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114977/" ]
If two vendors has the same product then when the second vendor publish the product in to the store, 2 is appended to the permalink since the same product from the first vendor already exist Is there any solution to remove the numeric from the permalink? Ideally, the two permalinks should look like this: <http://example.com/author-1/post-title/> <http://example.com/author-2/post-title/> But when I publish the second post, then its slug is changed to post-title-2, which makes the resulting URL <http://example.com/author-2/post-title-2/>.
Sounds like you need to wrap your shortcode contents in `ob_start()`and `return ob_get_clean()` ``` require_once(dirname(__FILE__).'/post-type.php'); //file that registers CPT function wporg_shortcodes_init(){ function wporg_shortcode($atts = []) { extract( shortcode_atts( array( 'term' => 'columns' ), $atts ) ); $custom_taxonomy = $atts['term']; ob_start(); // <- works like magic // add query of custom post type board_members $recentPosts = new WP_Query (array('posts_per_page' => -1, 'post_type' => array('board_members'), 'columns' => $custom_taxonomy )); while( $recentPosts->have_posts() ) : $recentPosts->the_post(); ?> <div class="b-thumb"><?php the_post_thumbnail('thumbnail') ?></div> <p class="b-info"> <span class="b-name"><?php the_title(); ?></span><br /> <span class="b-country"><?php the_field('country'); ?></span><br /> <span class="b-position"><?php the_field('position'); ?></span><br /> <span class="b-content"><?php printf(get_the_content()); ?></span><br /> </p> <?php wp_reset_postdata(); ?> <?php endwhile; ?> <?php return ob_get_clean(); // <- more magic } add_shortcode('board-members', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); ``` You can also modify the shortcode to return a single string, the following should work as well: ``` function wporg_shortcodes_init(){ function wporg_shortcode($atts = []) { extract( shortcode_atts( array( 'term' => 'columns' ), $atts ) ); $custom_taxonomy = $atts['term']; $output = ''; // add query of custom post type board_members $recentPosts = new WP_Query (array('posts_per_page' => -1, 'post_type' => array('board_members'), 'columns' => $custom_taxonomy )); while( $recentPosts->have_posts() ) : $recentPosts->the_post(); $output .= '<div class="b-thumb">'.the_post_thumbnail('thumbnail').'</div>'; $output .= '<p class="b-info">'; $output .= '<span class="b-name">'.the_title().'</span><br />'; $output .= '<span class="b-country">'.the_field('country').'</span><br />'; $output .= '<span class="b-position">'.the_field('position').'</span><br />'; $output .= '<span class="b-content">'.printf(get_the_content()).'</span><br />'; $output .= '</p> '; endwhile; wp_reset_postdata(); return $output; } add_shortcode('board-members', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); ```
292,673
<p>I have registered taxonomy: </p> <pre><code>$taxonomySetup = [ 'label' =&gt; __('Products catalog'), 'has_archive' =&gt; false, 'hierarchical' =&gt; true, 'rewrite' =&gt; [ 'slug' =&gt; __('catalog'), 'hierarchical' =&gt; true, 'with_front' =&gt; true ], ]; register_taxonomy('products', ['product'], $taxonomySetup); add_action('init', 'addTaxonomiesToPages'); function addTaxonomiesToPages() { register_taxonomy_for_object_type('products', 'product'); } </code></pre> <p>which is linked to CPT: </p> <pre><code>register_post_type('product', [ 'labels' =&gt; [ // labels definitions ], 'public' =&gt; true, 'has_archive' =&gt; true, 'menu_icon' =&gt; 'dashicons-archive', 'show_in_nav_menus' =&gt; true, 'taxonomies' =&gt; ['products'], 'publicly_queryable' =&gt; false, 'rewrite' =&gt; [ 'pages' =&gt; true, ], 'supports' =&gt; [ // supported items ], ]); </code></pre> <p>Now I have categories (for this taxonomy) structure with results: </p> <ul> <li><code>http://example.com/catalog</code> - <strong>Not Found</strong></li> <li><code>http://example.com/catalog/subcategory-1</code> - <strong>taxonomy.php</strong></li> <li><code>http://example.com/catalog/subcategory-1/subcategory-2</code> - <strong>taxonomy.php</strong></li> <li><code>http://example.com/catalog/subcategory-1/subcategory-2/subcategory-3</code> - <strong>taxonomy.php</strong></li> <li><code>http://example.com/catalog/subcategory-1/subcategory-2/subcategory-3/subcategory-4</code> - <strong>taxonomy.php</strong></li> </ul> <p>I have created many files for it: </p> <ul> <li><code>taxonomy.php</code></li> <li><code>taxonomy-products.php</code></li> <li><code>taxonomy-product.php</code></li> <li><code>taxonomy-catalog.php</code></li> </ul> <p>Why it always loading base taxonomy template and for main catalog it rendering <code>404</code> error? </p> <p>btw. How can I control which template should be loaded for subcategory (I'm talking about sub-level, not naming)?</p>
[ { "answer_id": 292642, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>If you want content to display in a specific spot, you will need to wrap the content in a <code>&lt;div&gt;</code> with a 'class', where the 'class' has the CSS you need to display the content.</p>\n\n<p>The shortcode works on pages/posts because the shortcode is contained within the content of the page/post, in the <code>&lt;div&gt;</code> that surrounds the post content.</p>\n\n<p>You will need to make a class (called 'myshortcode') of and use that in your loop:</p>\n\n<pre><code>&lt;div class='myshortcode'&gt;\n &lt;div class=\"b-thumb\"&gt;&lt;?php the_post_thumbnail('thumbnail') ?&gt;&lt;/div&gt;\n &lt;p class=\"b-info\"&gt;\n &lt;span class=\"b-name\"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;br /&gt; \n &lt;span class=\"b-country\"&gt;&lt;?php the_field('country'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-position\"&gt;&lt;?php the_field('position'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-content\"&gt;&lt;?php printf(get_the_content()); ?&gt;&lt;/span&gt;&lt;br /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Then, some CSS for that new class:</p>\n\n<pre><code>.myshortcode {\n /* some CSS here */\n}\n</code></pre>\n" }, { "answer_id": 292643, "author": "admcfajn", "author_id": 123674, "author_profile": "https://wordpress.stackexchange.com/users/123674", "pm_score": 3, "selected": true, "text": "<p>Sounds like you need to wrap your shortcode contents in <code>ob_start()</code>and <code>return ob_get_clean()</code></p>\n\n<pre><code>require_once(dirname(__FILE__).'/post-type.php'); //file that registers CPT\n\nfunction wporg_shortcodes_init(){\nfunction wporg_shortcode($atts = []) {\n extract( shortcode_atts( array(\n 'term' =&gt; 'columns'\n ), $atts ) );\n\n $custom_taxonomy = $atts['term']; \n\n ob_start(); // &lt;- works like magic\n\n // add query of custom post type board_members \n $recentPosts = new WP_Query\n (array('posts_per_page' =&gt; -1, 'post_type' =&gt; array('board_members'), 'columns' =&gt; $custom_taxonomy )); \n while( $recentPosts-&gt;have_posts() ) : $recentPosts-&gt;the_post(); ?&gt;\n\n &lt;div class=\"b-thumb\"&gt;&lt;?php the_post_thumbnail('thumbnail') ?&gt;&lt;/div&gt;\n &lt;p class=\"b-info\"&gt;\n &lt;span class=\"b-name\"&gt;&lt;?php the_title(); ?&gt;&lt;/span&gt;&lt;br /&gt; \n &lt;span class=\"b-country\"&gt;&lt;?php the_field('country'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-position\"&gt;&lt;?php the_field('position'); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;span class=\"b-content\"&gt;&lt;?php printf(get_the_content()); ?&gt;&lt;/span&gt;&lt;br /&gt;\n &lt;/p&gt; \n\n &lt;?php wp_reset_postdata(); ?&gt; \n &lt;?php endwhile; ?&gt; \n &lt;?php \n\n return ob_get_clean(); // &lt;- more magic\n\n }\n add_shortcode('board-members', 'wporg_shortcode');\n }\n add_action('init', 'wporg_shortcodes_init'); \n</code></pre>\n\n<p>You can also modify the shortcode to return a single string, the following should work as well:</p>\n\n<pre><code>function wporg_shortcodes_init(){\n function wporg_shortcode($atts = []) {\n extract( shortcode_atts( array(\n 'term' =&gt; 'columns'\n ), $atts ) );\n\n $custom_taxonomy = $atts['term']; \n\n $output = '';\n\n // add query of custom post type board_members \n $recentPosts = new WP_Query\n (array('posts_per_page' =&gt; -1, 'post_type' =&gt; array('board_members'), 'columns' =&gt; $custom_taxonomy )); \n while( $recentPosts-&gt;have_posts() ) : $recentPosts-&gt;the_post();\n\n $output .= '&lt;div class=\"b-thumb\"&gt;'.the_post_thumbnail('thumbnail').'&lt;/div&gt;';\n $output .= '&lt;p class=\"b-info\"&gt;';\n $output .= '&lt;span class=\"b-name\"&gt;'.the_title().'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-country\"&gt;'.the_field('country').'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-position\"&gt;'.the_field('position').'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;span class=\"b-content\"&gt;'.printf(get_the_content()).'&lt;/span&gt;&lt;br /&gt;';\n $output .= '&lt;/p&gt; ';\n\n endwhile;\n\n wp_reset_postdata();\n\n return $output;\n\n }\n add_shortcode('board-members', 'wporg_shortcode');\n}\nadd_action('init', 'wporg_shortcodes_init'); \n</code></pre>\n" } ]
2018/01/31
[ "https://wordpress.stackexchange.com/questions/292673", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134456/" ]
I have registered taxonomy: ``` $taxonomySetup = [ 'label' => __('Products catalog'), 'has_archive' => false, 'hierarchical' => true, 'rewrite' => [ 'slug' => __('catalog'), 'hierarchical' => true, 'with_front' => true ], ]; register_taxonomy('products', ['product'], $taxonomySetup); add_action('init', 'addTaxonomiesToPages'); function addTaxonomiesToPages() { register_taxonomy_for_object_type('products', 'product'); } ``` which is linked to CPT: ``` register_post_type('product', [ 'labels' => [ // labels definitions ], 'public' => true, 'has_archive' => true, 'menu_icon' => 'dashicons-archive', 'show_in_nav_menus' => true, 'taxonomies' => ['products'], 'publicly_queryable' => false, 'rewrite' => [ 'pages' => true, ], 'supports' => [ // supported items ], ]); ``` Now I have categories (for this taxonomy) structure with results: * `http://example.com/catalog` - **Not Found** * `http://example.com/catalog/subcategory-1` - **taxonomy.php** * `http://example.com/catalog/subcategory-1/subcategory-2` - **taxonomy.php** * `http://example.com/catalog/subcategory-1/subcategory-2/subcategory-3` - **taxonomy.php** * `http://example.com/catalog/subcategory-1/subcategory-2/subcategory-3/subcategory-4` - **taxonomy.php** I have created many files for it: * `taxonomy.php` * `taxonomy-products.php` * `taxonomy-product.php` * `taxonomy-catalog.php` Why it always loading base taxonomy template and for main catalog it rendering `404` error? btw. How can I control which template should be loaded for subcategory (I'm talking about sub-level, not naming)?
Sounds like you need to wrap your shortcode contents in `ob_start()`and `return ob_get_clean()` ``` require_once(dirname(__FILE__).'/post-type.php'); //file that registers CPT function wporg_shortcodes_init(){ function wporg_shortcode($atts = []) { extract( shortcode_atts( array( 'term' => 'columns' ), $atts ) ); $custom_taxonomy = $atts['term']; ob_start(); // <- works like magic // add query of custom post type board_members $recentPosts = new WP_Query (array('posts_per_page' => -1, 'post_type' => array('board_members'), 'columns' => $custom_taxonomy )); while( $recentPosts->have_posts() ) : $recentPosts->the_post(); ?> <div class="b-thumb"><?php the_post_thumbnail('thumbnail') ?></div> <p class="b-info"> <span class="b-name"><?php the_title(); ?></span><br /> <span class="b-country"><?php the_field('country'); ?></span><br /> <span class="b-position"><?php the_field('position'); ?></span><br /> <span class="b-content"><?php printf(get_the_content()); ?></span><br /> </p> <?php wp_reset_postdata(); ?> <?php endwhile; ?> <?php return ob_get_clean(); // <- more magic } add_shortcode('board-members', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); ``` You can also modify the shortcode to return a single string, the following should work as well: ``` function wporg_shortcodes_init(){ function wporg_shortcode($atts = []) { extract( shortcode_atts( array( 'term' => 'columns' ), $atts ) ); $custom_taxonomy = $atts['term']; $output = ''; // add query of custom post type board_members $recentPosts = new WP_Query (array('posts_per_page' => -1, 'post_type' => array('board_members'), 'columns' => $custom_taxonomy )); while( $recentPosts->have_posts() ) : $recentPosts->the_post(); $output .= '<div class="b-thumb">'.the_post_thumbnail('thumbnail').'</div>'; $output .= '<p class="b-info">'; $output .= '<span class="b-name">'.the_title().'</span><br />'; $output .= '<span class="b-country">'.the_field('country').'</span><br />'; $output .= '<span class="b-position">'.the_field('position').'</span><br />'; $output .= '<span class="b-content">'.printf(get_the_content()).'</span><br />'; $output .= '</p> '; endwhile; wp_reset_postdata(); return $output; } add_shortcode('board-members', 'wporg_shortcode'); } add_action('init', 'wporg_shortcodes_init'); ```
292,723
<p>When I click on "Edit" for an image I see the editor and I see the thumbnails on the right, WordPress just won't show me the actual image in the main area.</p> <pre><code>/wp-admin/admin-ajax.php?action=imgedit-preview&amp;_ajax_nonce=de68a01318&amp;postid=29499&amp;rand=385 (couldn't not find image) </code></pre> <p>Here is what I have done to try to fix it:</p> <ul> <li>Turned off all plugins.</li> <li>Remove my own theme and changed to default theme.</li> <li>Removed all blank lines and whitespaces in <code>/wp-content/themes/name/functions.php</code> + the including files.</li> <li>Checked that <code>php5-gd</code> is installed.</li> <li>Permissions changed to <code>777</code> for testing <code>/wp-content/upload/</code> + sub folders</li> <li>Removed closing <code>?&gt;</code> tags in <code>/wp-content/themes/name/functions.php</code> + the including files.</li> </ul> <p>Still no preview displayed. What can be the problem?</p>
[ { "answer_id": 292929, "author": "steffanjj", "author_id": 88213, "author_profile": "https://wordpress.stackexchange.com/users/88213", "pm_score": 2, "selected": false, "text": "<p>The preview is now displayed again after I removed empty lines and whitespaces after <code>?&gt;</code> in my <code>wp-config.php</code> file. That solved the problem.</p>\n" }, { "answer_id": 334454, "author": "mtm", "author_id": 165130, "author_profile": "https://wordpress.stackexchange.com/users/165130", "pm_score": 2, "selected": false, "text": "<p>By default, <code>wp-config.php</code> might not have a closing tag <code>?&gt;</code> and this is acceptable and by design. The issue may arise from whitespace in some other <code>.php</code> file. In my case, I had whitespace after the closing tag of my <code>functions.php</code> file for my child theme. Once I removed that whitespace, the images are showing up again and I can crop.</p>\n" }, { "answer_id": 397465, "author": "Chris", "author_id": 214192, "author_profile": "https://wordpress.stackexchange.com/users/214192", "pm_score": 0, "selected": false, "text": "<p>I solved this via a CustomPostType issue.\nIf the CPT you make doesn't have Revisions turned on, then preview can't show the ACF changes.</p>\n" } ]
2018/01/31
[ "https://wordpress.stackexchange.com/questions/292723", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/88213/" ]
When I click on "Edit" for an image I see the editor and I see the thumbnails on the right, WordPress just won't show me the actual image in the main area. ``` /wp-admin/admin-ajax.php?action=imgedit-preview&_ajax_nonce=de68a01318&postid=29499&rand=385 (couldn't not find image) ``` Here is what I have done to try to fix it: * Turned off all plugins. * Remove my own theme and changed to default theme. * Removed all blank lines and whitespaces in `/wp-content/themes/name/functions.php` + the including files. * Checked that `php5-gd` is installed. * Permissions changed to `777` for testing `/wp-content/upload/` + sub folders * Removed closing `?>` tags in `/wp-content/themes/name/functions.php` + the including files. Still no preview displayed. What can be the problem?
The preview is now displayed again after I removed empty lines and whitespaces after `?>` in my `wp-config.php` file. That solved the problem.
292,727
<p>I'm trying to display all posts and only certain custom posts on the homepage.</p> <p>Essentially: <code>(post_type = post) OR (post_type = exhibition AND featured = 1)</code></p> <p>I'm stuck with the actual implementation though.</p> <p><code>pre_get_posts</code> and <code>$query-&gt;set(...);</code> don't seem to allow logic on the <code>post_type</code>, it seems you can only set <code>(post OR exhibition) AND (featured=1)</code>.</p> <p>I'd rather not have to set <code>featured=1</code> on every single post.</p> <p>Any help appreciated.</p>
[ { "answer_id": 292732, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>You can't specify <code>OR</code> or <code>AND</code> on arbitrary <code>WP_Query</code> arguments. Meta and Taxonomy queries let you specify <code>OR</code> or <code>AND</code> for those queries, but other arguments are all combined (<code>post_type</code> is a property of the post, not meta, so a meta query won't help). Refer to <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">the documentation</a> for each of the possible arguments and how to use them.</p>\n\n<p>You'll see that some arguments support an Array as a value, like <code>post_type</code>, so you can pass <code>'post_type' =&gt; ['post', 'exhibition']</code> and it will get both <code>exhibition</code> and <code>post</code> posts.</p>\n\n<p>However when you're doing this you can't specify that another argument or meta query only apply to one of the post types.</p>\n\n<p>If the posts are going to be displayed separately, then you could just perform 2 queries. Otherwise you will need to query the database directly with <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\"><code>wpdb</code></a>. That would look something like:</p>\n\n<pre><code>global $wpdb;\n\n$results = $wpdb-&gt;get_results(\n \"SELECT \n posts.* \n FROM \n $wpdb-&gt;posts posts \n LEFT JOIN \n $wpdb-&gt;postmeta ON \n ( posts.ID = postmeta.post_id AND postmeta.meta_key = 'featured' )\n WHERE\n posts.post_type = 'post' OR\n ( posts.post_type = 'exhibition' AND postmeta.meta_value = '1' )\n \"\n);\n</code></pre>\n\n<p>I haven't tested it, but that's the rough idea. You'd need to add SQL for the posts count and any ordering as well.</p>\n\n<p>There's also the <a href=\"https://developer.wordpress.org/reference/hooks/posts_where/\" rel=\"nofollow noreferrer\"><code>posts_where</code></a> and <a href=\"https://developer.wordpress.org/reference/hooks/posts_join/\" rel=\"nofollow noreferrer\"><code>posts_join</code></a> filters you could use to <em>modify</em> the existing query for the posts. That's a little bit more involved, but if you need to modify the main query or are relying on other <code>WP_Query</code> arguments and don't want to have to rewrite their SQL then you should use those filers.</p>\n" }, { "answer_id": 292744, "author": "Cam", "author_id": 65437, "author_profile": "https://wordpress.stackexchange.com/users/65437", "pm_score": 0, "selected": false, "text": "<p>If you are trying to return custom posts, use this.</p>\n\n<pre><code>$args = array(\n 'numberposts'=&gt; -1,\n 'post_type' =&gt; 'custom post type name'\n );\n$results = get_posts( $args ); //get all post data results\n\nforeach ($results as $rel){//sift through data and find relevant meta data\n $ret = get_post_meta($rel-&gt;ID,'meta_field',true);\n if(!empty($ret)){\n //do something with this post data\n }\n\n}\n</code></pre>\n\n<p>This will get all the posts that fall under that post type. Hopefully this helps get you started.</p>\n" } ]
2018/01/31
[ "https://wordpress.stackexchange.com/questions/292727", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I'm trying to display all posts and only certain custom posts on the homepage. Essentially: `(post_type = post) OR (post_type = exhibition AND featured = 1)` I'm stuck with the actual implementation though. `pre_get_posts` and `$query->set(...);` don't seem to allow logic on the `post_type`, it seems you can only set `(post OR exhibition) AND (featured=1)`. I'd rather not have to set `featured=1` on every single post. Any help appreciated.
You can't specify `OR` or `AND` on arbitrary `WP_Query` arguments. Meta and Taxonomy queries let you specify `OR` or `AND` for those queries, but other arguments are all combined (`post_type` is a property of the post, not meta, so a meta query won't help). Refer to [the documentation](https://developer.wordpress.org/reference/classes/wp_query/) for each of the possible arguments and how to use them. You'll see that some arguments support an Array as a value, like `post_type`, so you can pass `'post_type' => ['post', 'exhibition']` and it will get both `exhibition` and `post` posts. However when you're doing this you can't specify that another argument or meta query only apply to one of the post types. If the posts are going to be displayed separately, then you could just perform 2 queries. Otherwise you will need to query the database directly with [`wpdb`](https://codex.wordpress.org/Class_Reference/wpdb). That would look something like: ``` global $wpdb; $results = $wpdb->get_results( "SELECT posts.* FROM $wpdb->posts posts LEFT JOIN $wpdb->postmeta ON ( posts.ID = postmeta.post_id AND postmeta.meta_key = 'featured' ) WHERE posts.post_type = 'post' OR ( posts.post_type = 'exhibition' AND postmeta.meta_value = '1' ) " ); ``` I haven't tested it, but that's the rough idea. You'd need to add SQL for the posts count and any ordering as well. There's also the [`posts_where`](https://developer.wordpress.org/reference/hooks/posts_where/) and [`posts_join`](https://developer.wordpress.org/reference/hooks/posts_join/) filters you could use to *modify* the existing query for the posts. That's a little bit more involved, but if you need to modify the main query or are relying on other `WP_Query` arguments and don't want to have to rewrite their SQL then you should use those filers.
292,779
<p>I'm trying to make the following mock up with WordPress: <a href="https://imgur.com/a/Sem7y" rel="nofollow noreferrer">https://imgur.com/a/Sem7y</a></p> <p>I created a custom post type and I created two categories (general and filling instructions). I used ACF plugin to create custom fields for the post type: <a href="https://imgur.com/a/o2QJV" rel="nofollow noreferrer">https://imgur.com/a/o2QJV</a></p> <p>However, when I create the loop I can't get it to show posts for only the general category, it will show any category. Also, it only shows one post (most recent), I want it to show all of them for the one category.</p> <pre><code> &lt;ul class="pdfLinks"&gt; &lt;?php //The Arguments $args = array( 'posts_per_page' =&gt; 50, 'post_type' =&gt; 'documents', 'category_name' =&gt; 'general' ); //The Query $genral_documents = new WP_Query ( $args ); ?&gt; &lt;?php //If we have the posts... if (the_field ('title')) : while(the_field('title')) : the_field('title'); endwhile; endif; ?&gt; &lt;?php $pdf1 = get_field('pdf_1'); ?&gt; &lt;a class="download_button" target="_blank" href="&lt;?php echo $pdf1['url']; ?&gt;"&gt; &lt;li&gt; Download File &lt;/li&gt; &lt;/a&gt; &lt;/ul&gt; </code></pre> <p>I'm very new to coding for WordPress, so I'm not sure what I'm doing wrong. Thank you for your help :)</p>
[ { "answer_id": 292732, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": false, "text": "<p>You can't specify <code>OR</code> or <code>AND</code> on arbitrary <code>WP_Query</code> arguments. Meta and Taxonomy queries let you specify <code>OR</code> or <code>AND</code> for those queries, but other arguments are all combined (<code>post_type</code> is a property of the post, not meta, so a meta query won't help). Refer to <a href=\"https://developer.wordpress.org/reference/classes/wp_query/\" rel=\"nofollow noreferrer\">the documentation</a> for each of the possible arguments and how to use them.</p>\n\n<p>You'll see that some arguments support an Array as a value, like <code>post_type</code>, so you can pass <code>'post_type' =&gt; ['post', 'exhibition']</code> and it will get both <code>exhibition</code> and <code>post</code> posts.</p>\n\n<p>However when you're doing this you can't specify that another argument or meta query only apply to one of the post types.</p>\n\n<p>If the posts are going to be displayed separately, then you could just perform 2 queries. Otherwise you will need to query the database directly with <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\"><code>wpdb</code></a>. That would look something like:</p>\n\n<pre><code>global $wpdb;\n\n$results = $wpdb-&gt;get_results(\n \"SELECT \n posts.* \n FROM \n $wpdb-&gt;posts posts \n LEFT JOIN \n $wpdb-&gt;postmeta ON \n ( posts.ID = postmeta.post_id AND postmeta.meta_key = 'featured' )\n WHERE\n posts.post_type = 'post' OR\n ( posts.post_type = 'exhibition' AND postmeta.meta_value = '1' )\n \"\n);\n</code></pre>\n\n<p>I haven't tested it, but that's the rough idea. You'd need to add SQL for the posts count and any ordering as well.</p>\n\n<p>There's also the <a href=\"https://developer.wordpress.org/reference/hooks/posts_where/\" rel=\"nofollow noreferrer\"><code>posts_where</code></a> and <a href=\"https://developer.wordpress.org/reference/hooks/posts_join/\" rel=\"nofollow noreferrer\"><code>posts_join</code></a> filters you could use to <em>modify</em> the existing query for the posts. That's a little bit more involved, but if you need to modify the main query or are relying on other <code>WP_Query</code> arguments and don't want to have to rewrite their SQL then you should use those filers.</p>\n" }, { "answer_id": 292744, "author": "Cam", "author_id": 65437, "author_profile": "https://wordpress.stackexchange.com/users/65437", "pm_score": 0, "selected": false, "text": "<p>If you are trying to return custom posts, use this.</p>\n\n<pre><code>$args = array(\n 'numberposts'=&gt; -1,\n 'post_type' =&gt; 'custom post type name'\n );\n$results = get_posts( $args ); //get all post data results\n\nforeach ($results as $rel){//sift through data and find relevant meta data\n $ret = get_post_meta($rel-&gt;ID,'meta_field',true);\n if(!empty($ret)){\n //do something with this post data\n }\n\n}\n</code></pre>\n\n<p>This will get all the posts that fall under that post type. Hopefully this helps get you started.</p>\n" } ]
2018/01/31
[ "https://wordpress.stackexchange.com/questions/292779", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135993/" ]
I'm trying to make the following mock up with WordPress: <https://imgur.com/a/Sem7y> I created a custom post type and I created two categories (general and filling instructions). I used ACF plugin to create custom fields for the post type: <https://imgur.com/a/o2QJV> However, when I create the loop I can't get it to show posts for only the general category, it will show any category. Also, it only shows one post (most recent), I want it to show all of them for the one category. ``` <ul class="pdfLinks"> <?php //The Arguments $args = array( 'posts_per_page' => 50, 'post_type' => 'documents', 'category_name' => 'general' ); //The Query $genral_documents = new WP_Query ( $args ); ?> <?php //If we have the posts... if (the_field ('title')) : while(the_field('title')) : the_field('title'); endwhile; endif; ?> <?php $pdf1 = get_field('pdf_1'); ?> <a class="download_button" target="_blank" href="<?php echo $pdf1['url']; ?>"> <li> Download File </li> </a> </ul> ``` I'm very new to coding for WordPress, so I'm not sure what I'm doing wrong. Thank you for your help :)
You can't specify `OR` or `AND` on arbitrary `WP_Query` arguments. Meta and Taxonomy queries let you specify `OR` or `AND` for those queries, but other arguments are all combined (`post_type` is a property of the post, not meta, so a meta query won't help). Refer to [the documentation](https://developer.wordpress.org/reference/classes/wp_query/) for each of the possible arguments and how to use them. You'll see that some arguments support an Array as a value, like `post_type`, so you can pass `'post_type' => ['post', 'exhibition']` and it will get both `exhibition` and `post` posts. However when you're doing this you can't specify that another argument or meta query only apply to one of the post types. If the posts are going to be displayed separately, then you could just perform 2 queries. Otherwise you will need to query the database directly with [`wpdb`](https://codex.wordpress.org/Class_Reference/wpdb). That would look something like: ``` global $wpdb; $results = $wpdb->get_results( "SELECT posts.* FROM $wpdb->posts posts LEFT JOIN $wpdb->postmeta ON ( posts.ID = postmeta.post_id AND postmeta.meta_key = 'featured' ) WHERE posts.post_type = 'post' OR ( posts.post_type = 'exhibition' AND postmeta.meta_value = '1' ) " ); ``` I haven't tested it, but that's the rough idea. You'd need to add SQL for the posts count and any ordering as well. There's also the [`posts_where`](https://developer.wordpress.org/reference/hooks/posts_where/) and [`posts_join`](https://developer.wordpress.org/reference/hooks/posts_join/) filters you could use to *modify* the existing query for the posts. That's a little bit more involved, but if you need to modify the main query or are relying on other `WP_Query` arguments and don't want to have to rewrite their SQL then you should use those filers.
292,789
<p>I have a problem I'm wondering, need someone to help.</p> <p>I am doing a function that sends email to followers weekly and monthly. Currently, I have written a function to use, but one thing is I do not know how to use cron to run WP. Can anybody suggest or guide me to make? Thanks very much :)</p>
[ { "answer_id": 292791, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Your hosting place should have an option on their control panel for adding CRON jobs. If this is self-hosted, you'll need to look for information specific to your operating system; ask the googles.</p>\n" }, { "answer_id": 292798, "author": "wppit", "author_id": 136007, "author_profile": "https://wordpress.stackexchange.com/users/136007", "pm_score": 2, "selected": false, "text": "<p>i got this proplem with hight load in my <a href=\"https://www.wppit.com/\" rel=\"nofollow noreferrer\">wppit.com</a> so i checked my cpanel and i found the cronjob casue this hiegh load and \nbecause WordPress has to work on all sort of different platforms, OS's and configurations, it can't rely that there will be a cronjob service on the server that can handle scheduled tasks. This is why WordPress developers have created a workaround - the wp-cron.php file in your main WordPress folder is executed every time someone loads a page. It then checks if there's a scheduled task to be done and executes it if necessary.</p>\n\n<p>However, in some cases, this file may become target of a DOS attack, or caching plugins can interfere with its execution which can cause either a lot of server load or the scheduled tasks may not execute properly and timely. This is why, you can substitute this constant file execution with a real cron job.</p>\n\n<p>First, you need to disable the script to be executed every time someone loads one of your pages. To do this, open the wp-config.php file in your main WordPress folder and add the following line before the \"/* That's all, stop editing! Happy blogging. */\" line:\n1</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n\n<p>Once you do that, you need to setup a real cron job and execute the wp-cron.php file with it. You don't want to trigger it too often - 30 minutes should be fine for most of the websites. To do this, login to your cPanel and go to the Cron jobs tool located in the Advanced section.</p>\n\n<p>Then, add the following command to be executed every 30 minutes:\n1</p>\n\n<pre><code>wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron &gt;/dev/null 2&gt;&amp;1\n</code></pre>\n\n<p>You need to replace yourdomain.com with your actual domain name. The Cron jobs tool has some of the most common schedules preset, so you can just select Every 30 minutes from the minutes drop-down and place a \"*\" symbol in the others.</p>\n\n<p>more information here\n<a href=\"https://www.siteground.com/tutorials/wordpress/real-cron-job/\" rel=\"nofollow noreferrer\">https://www.siteground.com/tutorials/wordpress/real-cron-job/</a></p>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292789", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134874/" ]
I have a problem I'm wondering, need someone to help. I am doing a function that sends email to followers weekly and monthly. Currently, I have written a function to use, but one thing is I do not know how to use cron to run WP. Can anybody suggest or guide me to make? Thanks very much :)
i got this proplem with hight load in my [wppit.com](https://www.wppit.com/) so i checked my cpanel and i found the cronjob casue this hiegh load and because WordPress has to work on all sort of different platforms, OS's and configurations, it can't rely that there will be a cronjob service on the server that can handle scheduled tasks. This is why WordPress developers have created a workaround - the wp-cron.php file in your main WordPress folder is executed every time someone loads a page. It then checks if there's a scheduled task to be done and executes it if necessary. However, in some cases, this file may become target of a DOS attack, or caching plugins can interfere with its execution which can cause either a lot of server load or the scheduled tasks may not execute properly and timely. This is why, you can substitute this constant file execution with a real cron job. First, you need to disable the script to be executed every time someone loads one of your pages. To do this, open the wp-config.php file in your main WordPress folder and add the following line before the "/\* That's all, stop editing! Happy blogging. \*/" line: 1 ``` define('DISABLE_WP_CRON', true); ``` Once you do that, you need to setup a real cron job and execute the wp-cron.php file with it. You don't want to trigger it too often - 30 minutes should be fine for most of the websites. To do this, login to your cPanel and go to the Cron jobs tool located in the Advanced section. Then, add the following command to be executed every 30 minutes: 1 ``` wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1 ``` You need to replace yourdomain.com with your actual domain name. The Cron jobs tool has some of the most common schedules preset, so you can just select Every 30 minutes from the minutes drop-down and place a "\*" symbol in the others. more information here <https://www.siteground.com/tutorials/wordpress/real-cron-job/>
292,804
<p>I have created dynamic add/remove fields in frontend post submission page. I use <code>wp_json_encode</code> and <code>$wpdb-&gt;insert</code> to insert data into my custom WordPress database table. the system is working perfectly.</p> <p>The data is stored in “reward_details” column of my custom table.. It looks like :</p> <pre><code>{"reward_amount":["500","250","20000","3000"],"reward_title":["Horse","Cat","Tiger","Monkey"],"reward_description":["Horse Home","Cat Home","Tiger Home","Monkey Home"]} </code></pre> <p>But however I am not able to retrieve and display the data using <code>json_decode</code>. Following is my code:</p> <pre><code>&lt;?php $project_id = $_SESSION['project_id']; global $wpdb; $string = $wpdb-&gt;get_results( "SELECT reward_details FROM wpxa_rewards WHERE project_id = $project_id" ); $someArray = json_decode($string, true); $count = count( $someArray ); for ( $i = 0; $i &lt; $count; $i++ ) { ?&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-body"&gt; &lt;?php echo $someArray[$i]["reward_title"]; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>I want to retrieve and display data dynamically… Plz help…</p>
[ { "answer_id": 292791, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Your hosting place should have an option on their control panel for adding CRON jobs. If this is self-hosted, you'll need to look for information specific to your operating system; ask the googles.</p>\n" }, { "answer_id": 292798, "author": "wppit", "author_id": 136007, "author_profile": "https://wordpress.stackexchange.com/users/136007", "pm_score": 2, "selected": false, "text": "<p>i got this proplem with hight load in my <a href=\"https://www.wppit.com/\" rel=\"nofollow noreferrer\">wppit.com</a> so i checked my cpanel and i found the cronjob casue this hiegh load and \nbecause WordPress has to work on all sort of different platforms, OS's and configurations, it can't rely that there will be a cronjob service on the server that can handle scheduled tasks. This is why WordPress developers have created a workaround - the wp-cron.php file in your main WordPress folder is executed every time someone loads a page. It then checks if there's a scheduled task to be done and executes it if necessary.</p>\n\n<p>However, in some cases, this file may become target of a DOS attack, or caching plugins can interfere with its execution which can cause either a lot of server load or the scheduled tasks may not execute properly and timely. This is why, you can substitute this constant file execution with a real cron job.</p>\n\n<p>First, you need to disable the script to be executed every time someone loads one of your pages. To do this, open the wp-config.php file in your main WordPress folder and add the following line before the \"/* That's all, stop editing! Happy blogging. */\" line:\n1</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre>\n\n<p>Once you do that, you need to setup a real cron job and execute the wp-cron.php file with it. You don't want to trigger it too often - 30 minutes should be fine for most of the websites. To do this, login to your cPanel and go to the Cron jobs tool located in the Advanced section.</p>\n\n<p>Then, add the following command to be executed every 30 minutes:\n1</p>\n\n<pre><code>wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron &gt;/dev/null 2&gt;&amp;1\n</code></pre>\n\n<p>You need to replace yourdomain.com with your actual domain name. The Cron jobs tool has some of the most common schedules preset, so you can just select Every 30 minutes from the minutes drop-down and place a \"*\" symbol in the others.</p>\n\n<p>more information here\n<a href=\"https://www.siteground.com/tutorials/wordpress/real-cron-job/\" rel=\"nofollow noreferrer\">https://www.siteground.com/tutorials/wordpress/real-cron-job/</a></p>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292804", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124069/" ]
I have created dynamic add/remove fields in frontend post submission page. I use `wp_json_encode` and `$wpdb->insert` to insert data into my custom WordPress database table. the system is working perfectly. The data is stored in “reward\_details” column of my custom table.. It looks like : ``` {"reward_amount":["500","250","20000","3000"],"reward_title":["Horse","Cat","Tiger","Monkey"],"reward_description":["Horse Home","Cat Home","Tiger Home","Monkey Home"]} ``` But however I am not able to retrieve and display the data using `json_decode`. Following is my code: ``` <?php $project_id = $_SESSION['project_id']; global $wpdb; $string = $wpdb->get_results( "SELECT reward_details FROM wpxa_rewards WHERE project_id = $project_id" ); $someArray = json_decode($string, true); $count = count( $someArray ); for ( $i = 0; $i < $count; $i++ ) { ?> <div class="panel panel-default"> <div class="panel-body"> <?php echo $someArray[$i]["reward_title"]; ?> </div> </div> <?php } ?> ``` I want to retrieve and display data dynamically… Plz help…
i got this proplem with hight load in my [wppit.com](https://www.wppit.com/) so i checked my cpanel and i found the cronjob casue this hiegh load and because WordPress has to work on all sort of different platforms, OS's and configurations, it can't rely that there will be a cronjob service on the server that can handle scheduled tasks. This is why WordPress developers have created a workaround - the wp-cron.php file in your main WordPress folder is executed every time someone loads a page. It then checks if there's a scheduled task to be done and executes it if necessary. However, in some cases, this file may become target of a DOS attack, or caching plugins can interfere with its execution which can cause either a lot of server load or the scheduled tasks may not execute properly and timely. This is why, you can substitute this constant file execution with a real cron job. First, you need to disable the script to be executed every time someone loads one of your pages. To do this, open the wp-config.php file in your main WordPress folder and add the following line before the "/\* That's all, stop editing! Happy blogging. \*/" line: 1 ``` define('DISABLE_WP_CRON', true); ``` Once you do that, you need to setup a real cron job and execute the wp-cron.php file with it. You don't want to trigger it too often - 30 minutes should be fine for most of the websites. To do this, login to your cPanel and go to the Cron jobs tool located in the Advanced section. Then, add the following command to be executed every 30 minutes: 1 ``` wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1 ``` You need to replace yourdomain.com with your actual domain name. The Cron jobs tool has some of the most common schedules preset, so you can just select Every 30 minutes from the minutes drop-down and place a "\*" symbol in the others. more information here <https://www.siteground.com/tutorials/wordpress/real-cron-job/>
292,809
<p>in the Hungarian language we generally use the Lastname + Firstname format when we communicate with each oter. Therefore I would like to change this method in Woocommerce and special in the client e-mail?</p> <p>Where can I edit this emial template or should I use rather a filter? Thank you for your replies in advance! Joseph</p>
[ { "answer_id": 292934, "author": "vishalprajapati13", "author_id": 136086, "author_profile": "https://wordpress.stackexchange.com/users/136086", "pm_score": 0, "selected": false, "text": "<p>Edit your store's email templates, go to WooCommerce > Settings > Emails \nfrom here you can edit your email template.</p>\n" }, { "answer_id": 292970, "author": "József Kerekes - e-central", "author_id": 136020, "author_profile": "https://wordpress.stackexchange.com/users/136020", "pm_score": 1, "selected": false, "text": "<p>I figured out a workaround solution and it works, but not the most beautiful:</p>\n\n<pre><code>// I made the original action passive\n// do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email );\n\n// ... create a new solution from scratch \n$text_align = is_rtl() ? 'right' : 'left';\n\n//to escape # from order id \n\n$order_id = trim(str_replace('#', '', $order-&gt;get_order_number()));\necho $order_id;\n\necho '&lt;h2&gt;' . __( 'Customer comments', 'woocommerce' ) . '&lt;/h2&gt;';\n\n$text = apply_filters('the_excerpt', get_post_field('post_excerpt', $order_id)); \necho $text;\n\n?&gt;\n\n&lt;table id=\"addresses\" cellspacing=\"0\" cellpadding=\"0\" style=\"width: 100%; vertical-align: top;\" border=\"0\"&gt;\n &lt;tr&gt;\n &lt;td class=\"td\" style=\"text-align:&lt;?php echo $text_align; ?&gt;; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;\" valign=\"top\" width=\"50%\"&gt;\n &lt;h3&gt;&lt;?php _e( 'Számlázási cím', 'woocommerce' ); ?&gt;&lt;/h3&gt; \n &lt;?php \n echo $order-&gt;get_billing_last_name() . \" \";\n\n echo $order-&gt;get_billing_first_name() . \"&lt;br /&gt;\";\n\n echo $order-&gt;get_billing_address_1() . \"&lt;br /&gt;\"; \n\n echo $order-&gt;get_billing_address_2() . \"&lt;br /&gt;\"; \n\n echo $order-&gt;get_billing_postcode() . \"&lt;br /&gt;\";\n\n echo $order-&gt;get_billing_email() . \"&lt;br /&gt;\";\n\n echo $order-&gt;get_billing_phone() . \"&lt;br /&gt;\";\n\n ?&gt;\n &lt;/td&gt;\n &lt;td class=\"td\" style=\"text-align:&lt;?php echo $text_align; ?&gt;; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;\" valign=\"top\" width=\"50%\"&gt;\n &lt;h3&gt;&lt;?php _e( 'Shipping address', 'woocommerce' ); ?&gt;&lt;/h3&gt;\n &lt;?php \n echo $order-&gt;get_shipping_last_name() . \" \";\n\n echo $order-&gt;get_shipping_first_name() . \"&lt;br /&gt;\";\n\n echo $order-&gt;get_shipping_address_1() . \"&lt;br /&gt;\";\n\n echo $order-&gt;get_shipping_postcode() . \"&lt;br /&gt;\"; \n ?&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n\n&lt;?php\n/**\n * @hooked WC_Emails::email_footer() Output the email footer\n */ ...\n</code></pre>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292809", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136020/" ]
in the Hungarian language we generally use the Lastname + Firstname format when we communicate with each oter. Therefore I would like to change this method in Woocommerce and special in the client e-mail? Where can I edit this emial template or should I use rather a filter? Thank you for your replies in advance! Joseph
I figured out a workaround solution and it works, but not the most beautiful: ``` // I made the original action passive // do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email ); // ... create a new solution from scratch $text_align = is_rtl() ? 'right' : 'left'; //to escape # from order id $order_id = trim(str_replace('#', '', $order->get_order_number())); echo $order_id; echo '<h2>' . __( 'Customer comments', 'woocommerce' ) . '</h2>'; $text = apply_filters('the_excerpt', get_post_field('post_excerpt', $order_id)); echo $text; ?> <table id="addresses" cellspacing="0" cellpadding="0" style="width: 100%; vertical-align: top;" border="0"> <tr> <td class="td" style="text-align:<?php echo $text_align; ?>; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;" valign="top" width="50%"> <h3><?php _e( 'Számlázási cím', 'woocommerce' ); ?></h3> <?php echo $order->get_billing_last_name() . " "; echo $order->get_billing_first_name() . "<br />"; echo $order->get_billing_address_1() . "<br />"; echo $order->get_billing_address_2() . "<br />"; echo $order->get_billing_postcode() . "<br />"; echo $order->get_billing_email() . "<br />"; echo $order->get_billing_phone() . "<br />"; ?> </td> <td class="td" style="text-align:<?php echo $text_align; ?>; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;" valign="top" width="50%"> <h3><?php _e( 'Shipping address', 'woocommerce' ); ?></h3> <?php echo $order->get_shipping_last_name() . " "; echo $order->get_shipping_first_name() . "<br />"; echo $order->get_shipping_address_1() . "<br />"; echo $order->get_shipping_postcode() . "<br />"; ?> </td> </tr> </table> <?php /** * @hooked WC_Emails::email_footer() Output the email footer */ ... ```
292,813
<p>I have 6 related posts by tag in every post. But some tags have only 2 or 3 posts. So in these posts, related posts section shows only 2 or 3 post.</p> <p>I want to complete related posts (if not 6) with the new posts. </p> <p>I tried many codes but if tags have 2 posts, than related posts show 2 post only. Can I add new posts to complete to 6?</p> <p>Or can I display recent post order by same tag? So, there will be 6 posts and same tags will be shown first.</p> <p>Thanks in advance!</p>
[ { "answer_id": 292934, "author": "vishalprajapati13", "author_id": 136086, "author_profile": "https://wordpress.stackexchange.com/users/136086", "pm_score": 0, "selected": false, "text": "<p>Edit your store's email templates, go to WooCommerce > Settings > Emails \nfrom here you can edit your email template.</p>\n" }, { "answer_id": 292970, "author": "József Kerekes - e-central", "author_id": 136020, "author_profile": "https://wordpress.stackexchange.com/users/136020", "pm_score": 1, "selected": false, "text": "<p>I figured out a workaround solution and it works, but not the most beautiful:</p>\n\n<pre><code>// I made the original action passive\n// do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email );\n\n// ... create a new solution from scratch \n$text_align = is_rtl() ? 'right' : 'left';\n\n//to escape # from order id \n\n$order_id = trim(str_replace('#', '', $order-&gt;get_order_number()));\necho $order_id;\n\necho '&lt;h2&gt;' . __( 'Customer comments', 'woocommerce' ) . '&lt;/h2&gt;';\n\n$text = apply_filters('the_excerpt', get_post_field('post_excerpt', $order_id)); \necho $text;\n\n?&gt;\n\n&lt;table id=\"addresses\" cellspacing=\"0\" cellpadding=\"0\" style=\"width: 100%; vertical-align: top;\" border=\"0\"&gt;\n &lt;tr&gt;\n &lt;td class=\"td\" style=\"text-align:&lt;?php echo $text_align; ?&gt;; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;\" valign=\"top\" width=\"50%\"&gt;\n &lt;h3&gt;&lt;?php _e( 'Számlázási cím', 'woocommerce' ); ?&gt;&lt;/h3&gt; \n &lt;?php \n echo $order-&gt;get_billing_last_name() . \" \";\n\n echo $order-&gt;get_billing_first_name() . \"&lt;br /&gt;\";\n\n echo $order-&gt;get_billing_address_1() . \"&lt;br /&gt;\"; \n\n echo $order-&gt;get_billing_address_2() . \"&lt;br /&gt;\"; \n\n echo $order-&gt;get_billing_postcode() . \"&lt;br /&gt;\";\n\n echo $order-&gt;get_billing_email() . \"&lt;br /&gt;\";\n\n echo $order-&gt;get_billing_phone() . \"&lt;br /&gt;\";\n\n ?&gt;\n &lt;/td&gt;\n &lt;td class=\"td\" style=\"text-align:&lt;?php echo $text_align; ?&gt;; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;\" valign=\"top\" width=\"50%\"&gt;\n &lt;h3&gt;&lt;?php _e( 'Shipping address', 'woocommerce' ); ?&gt;&lt;/h3&gt;\n &lt;?php \n echo $order-&gt;get_shipping_last_name() . \" \";\n\n echo $order-&gt;get_shipping_first_name() . \"&lt;br /&gt;\";\n\n echo $order-&gt;get_shipping_address_1() . \"&lt;br /&gt;\";\n\n echo $order-&gt;get_shipping_postcode() . \"&lt;br /&gt;\"; \n ?&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n\n&lt;?php\n/**\n * @hooked WC_Emails::email_footer() Output the email footer\n */ ...\n</code></pre>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292813", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136023/" ]
I have 6 related posts by tag in every post. But some tags have only 2 or 3 posts. So in these posts, related posts section shows only 2 or 3 post. I want to complete related posts (if not 6) with the new posts. I tried many codes but if tags have 2 posts, than related posts show 2 post only. Can I add new posts to complete to 6? Or can I display recent post order by same tag? So, there will be 6 posts and same tags will be shown first. Thanks in advance!
I figured out a workaround solution and it works, but not the most beautiful: ``` // I made the original action passive // do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email ); // ... create a new solution from scratch $text_align = is_rtl() ? 'right' : 'left'; //to escape # from order id $order_id = trim(str_replace('#', '', $order->get_order_number())); echo $order_id; echo '<h2>' . __( 'Customer comments', 'woocommerce' ) . '</h2>'; $text = apply_filters('the_excerpt', get_post_field('post_excerpt', $order_id)); echo $text; ?> <table id="addresses" cellspacing="0" cellpadding="0" style="width: 100%; vertical-align: top;" border="0"> <tr> <td class="td" style="text-align:<?php echo $text_align; ?>; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;" valign="top" width="50%"> <h3><?php _e( 'Számlázási cím', 'woocommerce' ); ?></h3> <?php echo $order->get_billing_last_name() . " "; echo $order->get_billing_first_name() . "<br />"; echo $order->get_billing_address_1() . "<br />"; echo $order->get_billing_address_2() . "<br />"; echo $order->get_billing_postcode() . "<br />"; echo $order->get_billing_email() . "<br />"; echo $order->get_billing_phone() . "<br />"; ?> </td> <td class="td" style="text-align:<?php echo $text_align; ?>; font-family: 'Helvetica Neue', Helvetica, Roboto, Arial, sans-serif;" valign="top" width="50%"> <h3><?php _e( 'Shipping address', 'woocommerce' ); ?></h3> <?php echo $order->get_shipping_last_name() . " "; echo $order->get_shipping_first_name() . "<br />"; echo $order->get_shipping_address_1() . "<br />"; echo $order->get_shipping_postcode() . "<br />"; ?> </td> </tr> </table> <?php /** * @hooked WC_Emails::email_footer() Output the email footer */ ... ```
292,815
<p><br> the task is actually quite simple I believe. I want to query the status of a checkbox, pass it with $.post and JSON to a function, and then save the value.</p> <p><strong>my-html (relevant part)</strong></p> <pre><code>&lt;input type="checkbox" id="&lt;?php echo $category-&gt;column_handle; ?&gt;" name="&lt;?php echo $category-&gt;column_handle; ?&gt;" class="checkbox" &lt;?php if($my_notifications-&gt;{$category-&gt;column_handle}){echo 'checked="checked"';} ?&gt; value="1"&gt; </code></pre> <p><strong>my-script</strong></p> <pre><code>$('.checkbox').change(function(e){ var parent = $(this).parents('.container'); $.post({ dataType: 'json', url: ajax_object.ajaxurl, data:{ 'action': 'myaction', 'column': $(this).attr('id'), 'check': $(this).prop('checked') } }).done(function(data){ parent.find('.title').text(data.input); }); }); </code></pre> <p><strong>my-function</strong></p> <pre><code>function my_function(){ global $wpdb; $column = esc_attr($_POST['column']); $bool = esc_attr($_POST['check']); /*$id is correct and sourced elsewhere (I deleted that part)*/ $wpdb-&gt;update('my_dataset',array($column =&gt; $bool),array('ID' =&gt; $id)); echo json_encode(array('input' =&gt; $bool)); die(); } add_action('wp_ajax_myaction','my_function'); </code></pre> <p>the .done part is for testing and returns the status of the checkbox correctly. But it is not saved. I have already tried a lot, such as treating the status as a string or passing 0 and 1. Everything without success. Maybe one of you can help me.</p>
[ { "answer_id": 292816, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 1, "selected": false, "text": "<pre><code>.prop()\n</code></pre>\n\n<p>method return boolean type. True or false. You should send checked value and save it into database. And in HTML get your value and set it to your checkbox.\nAn example you have <code>&lt;input type=\"checkbox\" name=\"test\" class=\"checkbox\" value=\"checked\"&gt;</code>. You should send to php <code>$('.checkbox').val();</code> and then place checked attr to html.</p>\n\n<pre><code>&lt;?php $checked = 'your var from database'; ?&gt;\n&lt;input type=\"checkbox\" &lt;?php checked('checked', $checked); ?&gt; name=\"test\" class=\"checkbox\" value=\"checked\"&gt;\n</code></pre>\n\n<p>Something like this should work.</p>\n" }, { "answer_id": 293501, "author": "Sin", "author_id": 129895, "author_profile": "https://wordpress.stackexchange.com/users/129895", "pm_score": 1, "selected": true, "text": "<p>I solved the problem.</p>\n\n<p>I tried so many things that I seemingly skipped a variant that worked.</p>\n\n<p>So for anyone coming by this way it works:</p>\n\n<p><strong>my-script</strong> as in the question: </p>\n\n<pre><code>'check': $(this).prop('checked')\n</code></pre>\n\n<p><strong>my-function</strong> as follows:</p>\n\n<pre><code>function my_function(){\nglobal $wpdb;\n\n$column = esc_attr($_POST['column']);\n$bool = esc_attr($_POST['check']);\nif($bool == 'true'){$value = true;}else{$value = false;}\n$wpdb-&gt;update('my_dataset',array($column =&gt; $value),array('ID' =&gt; $id));\n\necho json_encode(array('input' =&gt; $bool));\n\ndie();\n}\n\nadd_action('wp_ajax_myaction','my_function');\n</code></pre>\n\n<p>$bool has to be treated like a string.</p>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292815", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129895/" ]
the task is actually quite simple I believe. I want to query the status of a checkbox, pass it with $.post and JSON to a function, and then save the value. **my-html (relevant part)** ``` <input type="checkbox" id="<?php echo $category->column_handle; ?>" name="<?php echo $category->column_handle; ?>" class="checkbox" <?php if($my_notifications->{$category->column_handle}){echo 'checked="checked"';} ?> value="1"> ``` **my-script** ``` $('.checkbox').change(function(e){ var parent = $(this).parents('.container'); $.post({ dataType: 'json', url: ajax_object.ajaxurl, data:{ 'action': 'myaction', 'column': $(this).attr('id'), 'check': $(this).prop('checked') } }).done(function(data){ parent.find('.title').text(data.input); }); }); ``` **my-function** ``` function my_function(){ global $wpdb; $column = esc_attr($_POST['column']); $bool = esc_attr($_POST['check']); /*$id is correct and sourced elsewhere (I deleted that part)*/ $wpdb->update('my_dataset',array($column => $bool),array('ID' => $id)); echo json_encode(array('input' => $bool)); die(); } add_action('wp_ajax_myaction','my_function'); ``` the .done part is for testing and returns the status of the checkbox correctly. But it is not saved. I have already tried a lot, such as treating the status as a string or passing 0 and 1. Everything without success. Maybe one of you can help me.
I solved the problem. I tried so many things that I seemingly skipped a variant that worked. So for anyone coming by this way it works: **my-script** as in the question: ``` 'check': $(this).prop('checked') ``` **my-function** as follows: ``` function my_function(){ global $wpdb; $column = esc_attr($_POST['column']); $bool = esc_attr($_POST['check']); if($bool == 'true'){$value = true;}else{$value = false;} $wpdb->update('my_dataset',array($column => $value),array('ID' => $id)); echo json_encode(array('input' => $bool)); die(); } add_action('wp_ajax_myaction','my_function'); ``` $bool has to be treated like a string.
292,831
<p>Is it poossible to add index to the meta_value column in the wp_postmeta table in order to make faster queries in Wordpress?</p> <p>I have about 5 million rows in the wp_postmeta table and my queries takes about 3 seconds when limited to 500 rows.</p> <p>I am trying to do add an index to meta_value in phpMyAdmin but i am getting an error message saying:</p> <blockquote> <p>column 'meta_value' used in key specification without a key length</p> </blockquote> <p>I was thinking of converting it to varchar(255) but i have a meta value of _wp_attachment_metadata that is around 1500 characters long. </p> <p>My query look like this:</p> <pre><code>Array ( [posts_per_page] =&gt; 500 [orderby] =&gt; name [order] =&gt; ASC [post_type] =&gt; company [post_status] =&gt; publish [meta_query] =&gt; Array ( [relation] =&gt; OR [0] =&gt; Array ( [key] =&gt; example1 [value] =&gt; 2 [type] =&gt; numeric [compare] =&gt; = ) [1] =&gt; Array ( [key] =&gt; example2 [value] =&gt; 2 [type] =&gt; numeric [compare] =&gt; = ) [2] =&gt; Array ( [key] =&gt; example3 [value] =&gt; 2 [type] =&gt; numeric [compare] =&gt; = ) [3] =&gt; Array ( [key] =&gt; example3 [value] =&gt; 2 [type] =&gt; numeric [compare] =&gt; = ) ) ) </code></pre>
[ { "answer_id": 292832, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 2, "selected": false, "text": "<p>Don't limit the field, instead, limit the index, e.g.</p>\n\n<pre><code>ALTER TABLE wp_postmeta ADD key(meta_value(100))\n</code></pre>\n\n<p>This limits the index to the first hundred bytes of meta_value.</p>\n\n<p>You'll probably want an index on post_id, meta_key, meta_value for joins. How much of meta_key and meta_value is required depends on your data, for example</p>\n\n<pre><code>ALTER TABLE wp_postmeta ADD key(post_id, meta_key(100), meta_value(100));\n</code></pre>\n\n<p>Whether that helps with your query is another question. Get the SQL generated with <code>$query-&gt;request</code> and then run it with \"EXPLAIN $SQL\" to see how MySQL handles it, which indexes are used etc pp.</p>\n" }, { "answer_id": 403019, "author": "lkraav", "author_id": 11614, "author_profile": "https://wordpress.stackexchange.com/users/11614", "pm_score": 2, "selected": false, "text": "<p>Ollie Jones is doing massive index upgrade work with <a href=\"https://wordpress.org/plugins/index-wp-mysql-for-speed/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/index-wp-mysql-for-speed/</a> right now.</p>\n<p>His current recommendation for modern Barracuda storage engine backed tables is</p>\n<pre><code>ALTER TABLE wp_postmeta\n ADD UNIQUE KEY meta_id (meta_id),\n DROP PRIMARY KEY,\n ADD PRIMARY KEY (post_id, meta_key, meta_id),\n DROP KEY meta_key,\n ADD KEY meta_key (meta_key, meta_value(32), post_id, meta_id),\n ADD KEY meta_value (meta_value(32), meta_id),\n DROP KEY post_id;\n</code></pre>\n<p>See <a href=\"https://www.plumislandmedia.net/index-wp-mysql-for-speed/tables_and_keys/\" rel=\"nofollow noreferrer\">https://www.plumislandmedia.net/index-wp-mysql-for-speed/tables_and_keys/</a> for details.</p>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292831", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44178/" ]
Is it poossible to add index to the meta\_value column in the wp\_postmeta table in order to make faster queries in Wordpress? I have about 5 million rows in the wp\_postmeta table and my queries takes about 3 seconds when limited to 500 rows. I am trying to do add an index to meta\_value in phpMyAdmin but i am getting an error message saying: > > column 'meta\_value' used in key specification without a key length > > > I was thinking of converting it to varchar(255) but i have a meta value of \_wp\_attachment\_metadata that is around 1500 characters long. My query look like this: ``` Array ( [posts_per_page] => 500 [orderby] => name [order] => ASC [post_type] => company [post_status] => publish [meta_query] => Array ( [relation] => OR [0] => Array ( [key] => example1 [value] => 2 [type] => numeric [compare] => = ) [1] => Array ( [key] => example2 [value] => 2 [type] => numeric [compare] => = ) [2] => Array ( [key] => example3 [value] => 2 [type] => numeric [compare] => = ) [3] => Array ( [key] => example3 [value] => 2 [type] => numeric [compare] => = ) ) ) ```
Don't limit the field, instead, limit the index, e.g. ``` ALTER TABLE wp_postmeta ADD key(meta_value(100)) ``` This limits the index to the first hundred bytes of meta\_value. You'll probably want an index on post\_id, meta\_key, meta\_value for joins. How much of meta\_key and meta\_value is required depends on your data, for example ``` ALTER TABLE wp_postmeta ADD key(post_id, meta_key(100), meta_value(100)); ``` Whether that helps with your query is another question. Get the SQL generated with `$query->request` and then run it with "EXPLAIN $SQL" to see how MySQL handles it, which indexes are used etc pp.
292,834
<p>I have a custom page template, I'm using a standard WPQuery to fetch the posts from the default posts custom post type. I'm looping through all the posts however now I have more posts than I allow in the settings of the admin. Instead of changing the limit I want to use some standard WP pagination. However, none of the functions work on a custom page template but do when used on <code>index.php</code>.</p> <pre><code>&lt;?php /* Template Name: News page */ get_header(); ?&gt; &lt;?php $args = array( 'post_type' =&gt; array( 'post' ), ); // The Query $query = new WP_Query( $args ); ?&gt; &lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main full-width pd" role="main"&gt; &lt;div class="news-loop"&gt; &lt;div class="row"&gt; &lt;?php if($query-&gt;have_posts()) : while($query-&gt;have_posts()) : $query-&gt;the_post();?&gt; &lt;div class="col col-md-4"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;div class="cut-box"&gt; &lt;?php the_post_thumbnail( 'gallery' ); ?&gt; &lt;/div&gt; &lt;/a&gt; &lt;span class="date"&gt; &lt;?php echo get_the_date('d/m/Y'); ?&gt; &lt;/span&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;?php the_excerpt(); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;Read More...&lt;/a&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;p class="nav"&gt;&lt;?php previous_posts_link(); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/main&gt; &lt;/div&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>I've used the <code>previous_posts_link()</code> function as a test but nothing is returned in the dom. </p> <p>Is it possible to use standard wp pagination on custom page templates? </p>
[ { "answer_id": 292832, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 2, "selected": false, "text": "<p>Don't limit the field, instead, limit the index, e.g.</p>\n\n<pre><code>ALTER TABLE wp_postmeta ADD key(meta_value(100))\n</code></pre>\n\n<p>This limits the index to the first hundred bytes of meta_value.</p>\n\n<p>You'll probably want an index on post_id, meta_key, meta_value for joins. How much of meta_key and meta_value is required depends on your data, for example</p>\n\n<pre><code>ALTER TABLE wp_postmeta ADD key(post_id, meta_key(100), meta_value(100));\n</code></pre>\n\n<p>Whether that helps with your query is another question. Get the SQL generated with <code>$query-&gt;request</code> and then run it with \"EXPLAIN $SQL\" to see how MySQL handles it, which indexes are used etc pp.</p>\n" }, { "answer_id": 403019, "author": "lkraav", "author_id": 11614, "author_profile": "https://wordpress.stackexchange.com/users/11614", "pm_score": 2, "selected": false, "text": "<p>Ollie Jones is doing massive index upgrade work with <a href=\"https://wordpress.org/plugins/index-wp-mysql-for-speed/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/index-wp-mysql-for-speed/</a> right now.</p>\n<p>His current recommendation for modern Barracuda storage engine backed tables is</p>\n<pre><code>ALTER TABLE wp_postmeta\n ADD UNIQUE KEY meta_id (meta_id),\n DROP PRIMARY KEY,\n ADD PRIMARY KEY (post_id, meta_key, meta_id),\n DROP KEY meta_key,\n ADD KEY meta_key (meta_key, meta_value(32), post_id, meta_id),\n ADD KEY meta_value (meta_value(32), meta_id),\n DROP KEY post_id;\n</code></pre>\n<p>See <a href=\"https://www.plumislandmedia.net/index-wp-mysql-for-speed/tables_and_keys/\" rel=\"nofollow noreferrer\">https://www.plumislandmedia.net/index-wp-mysql-for-speed/tables_and_keys/</a> for details.</p>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292834", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115473/" ]
I have a custom page template, I'm using a standard WPQuery to fetch the posts from the default posts custom post type. I'm looping through all the posts however now I have more posts than I allow in the settings of the admin. Instead of changing the limit I want to use some standard WP pagination. However, none of the functions work on a custom page template but do when used on `index.php`. ``` <?php /* Template Name: News page */ get_header(); ?> <?php $args = array( 'post_type' => array( 'post' ), ); // The Query $query = new WP_Query( $args ); ?> <div id="primary" class="content-area"> <main id="main" class="site-main full-width pd" role="main"> <div class="news-loop"> <div class="row"> <?php if($query->have_posts()) : while($query->have_posts()) : $query->the_post();?> <div class="col col-md-4"> <a href="<?php the_permalink(); ?>"> <div class="cut-box"> <?php the_post_thumbnail( 'gallery' ); ?> </div> </a> <span class="date"> <?php echo get_the_date('d/m/Y'); ?> </span> <h3><?php the_title(); ?></h3> <?php the_excerpt(); ?> <a href="<?php the_permalink(); ?>">Read More...</a> </div> <?php endwhile; ?> <p class="nav"><?php previous_posts_link(); ?></p> <?php endif; ?> <?php wp_reset_query(); ?> </div> </div> </main> </div> <?php get_footer(); ?> ``` I've used the `previous_posts_link()` function as a test but nothing is returned in the dom. Is it possible to use standard wp pagination on custom page templates?
Don't limit the field, instead, limit the index, e.g. ``` ALTER TABLE wp_postmeta ADD key(meta_value(100)) ``` This limits the index to the first hundred bytes of meta\_value. You'll probably want an index on post\_id, meta\_key, meta\_value for joins. How much of meta\_key and meta\_value is required depends on your data, for example ``` ALTER TABLE wp_postmeta ADD key(post_id, meta_key(100), meta_value(100)); ``` Whether that helps with your query is another question. Get the SQL generated with `$query->request` and then run it with "EXPLAIN $SQL" to see how MySQL handles it, which indexes are used etc pp.
292,838
<p>I want to show a custom taxonomy in the name of custom_tax in a plugin option page as dropdown that user can select terms of taxonomy. I know that I can use <a href="https://developer.wordpress.org/reference/functions/wp_dropdown_categories/" rel="nofollow noreferrer">wp_dropdown_categories()</a> but I don't want show the terms of category taxonomy. I'm going to show my custom taxonomy terms as dropdown. Is there any function to do that? or no how can I do that?</p>
[ { "answer_id": 292842, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_terms/\" rel=\"nofollow noreferrer\">get_terms() function</a>\nshould help you. An example:</p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' =&gt; 'custom_tax',\n) );\n</code></pre>\n" }, { "answer_id": 292848, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 2, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_dropdown_categories/\" rel=\"nofollow noreferrer\"><code>wp_dropdown_categories()</code></a> has the <code>taxonomy</code> parameter, which defaults to <code>category</code>, but can be used to retrieve custom taxonomies. Exemplary usage:</p>\n\n<pre><code>wp_dropdown_categories([\n 'taxonomy' =&gt; 'custom-taxonomy-name'\n]);\n</code></pre>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292838", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133808/" ]
I want to show a custom taxonomy in the name of custom\_tax in a plugin option page as dropdown that user can select terms of taxonomy. I know that I can use [wp\_dropdown\_categories()](https://developer.wordpress.org/reference/functions/wp_dropdown_categories/) but I don't want show the terms of category taxonomy. I'm going to show my custom taxonomy terms as dropdown. Is there any function to do that? or no how can I do that?
[`wp_dropdown_categories()`](https://developer.wordpress.org/reference/functions/wp_dropdown_categories/) has the `taxonomy` parameter, which defaults to `category`, but can be used to retrieve custom taxonomies. Exemplary usage: ``` wp_dropdown_categories([ 'taxonomy' => 'custom-taxonomy-name' ]); ```
292,861
<p>I'm trying to edit wording in terms &amp; conditions checkbox on checkout page (order review section), but without luck. It was easy to edit other fields like billing and shipping fields. But I'm not sure how to target this specific T&amp;C checkbox.</p> <p>For other input fields the code below works fine:</p> <pre><code> // WooCommerce Rename Checkout Fields add_filter( 'woocommerce_checkout_fields' , 'custom_rename_wc_checkout_fields' ); // Change placeholder and label text function custom_rename_wc_checkout_fields( $fields ) { $fields['billing']['billing_first_name']['placeholder'] = 'Type your first name...'; $fields['billing']['billing_first_name']['label'] = 'Your First Name'; return $fields; } </code></pre> <p>In terms &amp; conditions label, there isn't any <code>&lt;label for=""&gt;</code> and the text is nested in span, so how to target that specific field? HTML output for t&amp;c checkbox is:</p> <pre><code> &lt;p class="form-row terms wc-terms-and-conditions"&gt; &lt;label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox"&gt; &lt;input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="terms" id="terms"&gt; &lt;span&gt;Przeczytałem/am i akceptuję &lt;a href="#" target="_blank" class="woocommerce-terms-and-conditions-link"&gt;regulamin&lt;/a&gt;&lt;/span&gt; &lt;span class="required"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="hidden" name="terms-field" value="1"&gt; &lt;/p&gt; </code></pre> <p>=========</p> <p>I know that this is the question more related with Woocommerce, but maybe <code>gettext</code> is more generic... I also tried this code, and it didn't work:</p> <pre><code>add_filter('gettext', 'rd_translate_tc'); add_filter('ngettext', 'rd_translate_tc'); function rd_translate_tc($translated) { $translated = str_ireplace('Przeczytałem/am i akceptuję regulamin', 'New translated content', $translated); return $translated; } </code></pre>
[ { "answer_id": 314901, "author": "Bjorn", "author_id": 83707, "author_profile": "https://wordpress.stackexchange.com/users/83707", "pm_score": 1, "selected": false, "text": "<p>Woocommerce has moved some settings to the WP customizer.</p>\n\n<p>Go to:\nWP admin menu -> Appearance -> Customizer -> Woocommerce -> Checkout.</p>\n\n<p>There you can set the Privacy &amp; Terms.</p>\n" }, { "answer_id": 350114, "author": "Daniel Herrera", "author_id": 176521, "author_profile": "https://wordpress.stackexchange.com/users/176521", "pm_score": 0, "selected": false, "text": "<p>try with this function in function.php</p>\n\n<pre><code>function ca_terms_and_conditions_checkbox_text( $option ){\n $idioma = pll_current_language(); \n if($idioma == \"en\"){\n $traduccion = \"I have read and agree to the terms and conditions of the website and the privacy policies\";\n $option = __($traduccion, 'woocommerce');\n } \n return $option;\n}\n\nadd_filter( 'woocommerce_get_terms_and_conditions_checkbox_text', 'ca_terms_and_conditions_checkbox_text' );\n</code></pre>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292861", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133403/" ]
I'm trying to edit wording in terms & conditions checkbox on checkout page (order review section), but without luck. It was easy to edit other fields like billing and shipping fields. But I'm not sure how to target this specific T&C checkbox. For other input fields the code below works fine: ``` // WooCommerce Rename Checkout Fields add_filter( 'woocommerce_checkout_fields' , 'custom_rename_wc_checkout_fields' ); // Change placeholder and label text function custom_rename_wc_checkout_fields( $fields ) { $fields['billing']['billing_first_name']['placeholder'] = 'Type your first name...'; $fields['billing']['billing_first_name']['label'] = 'Your First Name'; return $fields; } ``` In terms & conditions label, there isn't any `<label for="">` and the text is nested in span, so how to target that specific field? HTML output for t&c checkbox is: ``` <p class="form-row terms wc-terms-and-conditions"> <label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox"> <input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="terms" id="terms"> <span>Przeczytałem/am i akceptuję <a href="#" target="_blank" class="woocommerce-terms-and-conditions-link">regulamin</a></span> <span class="required">*</span> </label> <input type="hidden" name="terms-field" value="1"> </p> ``` ========= I know that this is the question more related with Woocommerce, but maybe `gettext` is more generic... I also tried this code, and it didn't work: ``` add_filter('gettext', 'rd_translate_tc'); add_filter('ngettext', 'rd_translate_tc'); function rd_translate_tc($translated) { $translated = str_ireplace('Przeczytałem/am i akceptuję regulamin', 'New translated content', $translated); return $translated; } ```
Woocommerce has moved some settings to the WP customizer. Go to: WP admin menu -> Appearance -> Customizer -> Woocommerce -> Checkout. There you can set the Privacy & Terms.
292,870
<p>I have a custom page where I ask users to log in to access the page. Once they log in, I would like to redirect them to the same page but I want to add on their user ID to the URL string in the redirect. This is just for analytics, the actual content is being protected by <code>if (current_user_can('')){}</code> </p> <p>Here's the code I have tried in my password protected page:</p> <pre><code>&lt;?php $userID = get_current_user_id(); $args = array( 'echo' =&gt; true, 'remember' =&gt; true, 'redirect' =&gt; ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?uid=' . $userID, 'form_id' =&gt; 'loginform', 'id_username' =&gt; 'user_login', 'id_password' =&gt; 'user_pass', 'id_remember' =&gt; 'rememberme', 'id_submit' =&gt; 'wp-submit', 'label_username' =&gt; __( 'Username or Email Address' ), 'label_password' =&gt; __( 'Password' ), 'label_remember' =&gt; __( 'Remember Me' ), 'label_log_in' =&gt; __( 'Log In' ), 'value_username' =&gt; '', 'value_remember' =&gt; false ); wp_login_form($args); ?&gt; </code></pre> <p>Obviously this won't work(returns "0") since it's trying to get the user's ID before they're logged in, but I can't think of how I would go about this.</p>
[ { "answer_id": 292884, "author": "user13286", "author_id": 13286, "author_profile": "https://wordpress.stackexchange.com/users/13286", "pm_score": 0, "selected": false, "text": "<p>I was able to resolve this by separating the login page from the page with the content. So I have one page that has the login form and at the top it checks if the user is logged in, if they are, it redirects them to the protected content page with their User ID in the URL, otherwise it displays the login form.</p>\n" }, { "answer_id": 292897, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 3, "selected": true, "text": "<p>you can add the user identifier à the redirection URL with this filter</p>\n\n<pre><code>add_filter(\"login_redirect\", function ($redirect_to, $requested_redirect_to, $user) {\n\n $redirect_to = add_query_arg([\n \"user_id\" =&gt; $user-&gt;ID,\n ], $redirect_to);\n\n\n return $redirect_to;\n\n}, 10, 3);\n</code></pre>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292870", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/13286/" ]
I have a custom page where I ask users to log in to access the page. Once they log in, I would like to redirect them to the same page but I want to add on their user ID to the URL string in the redirect. This is just for analytics, the actual content is being protected by `if (current_user_can('')){}` Here's the code I have tried in my password protected page: ``` <?php $userID = get_current_user_id(); $args = array( 'echo' => true, 'remember' => true, 'redirect' => ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '?uid=' . $userID, 'form_id' => 'loginform', 'id_username' => 'user_login', 'id_password' => 'user_pass', 'id_remember' => 'rememberme', 'id_submit' => 'wp-submit', 'label_username' => __( 'Username or Email Address' ), 'label_password' => __( 'Password' ), 'label_remember' => __( 'Remember Me' ), 'label_log_in' => __( 'Log In' ), 'value_username' => '', 'value_remember' => false ); wp_login_form($args); ?> ``` Obviously this won't work(returns "0") since it's trying to get the user's ID before they're logged in, but I can't think of how I would go about this.
you can add the user identifier à the redirection URL with this filter ``` add_filter("login_redirect", function ($redirect_to, $requested_redirect_to, $user) { $redirect_to = add_query_arg([ "user_id" => $user->ID, ], $redirect_to); return $redirect_to; }, 10, 3); ```
292,875
<p>I have a website (<code>www.example.com</code>) that I'd like to add a WordPress blog to, but I want to keep the website's <code>index.php</code> as the homepage.</p> <p>I also want to add two links to the homepage, <code>example.com/newsletters</code> and <code>example.com/explainers</code>, which link to WordPress archive pages with all the posts tagged "newsletters"and "explainers" respectively.</p> <p>How would I achieve this?</p>
[ { "answer_id": 292884, "author": "user13286", "author_id": 13286, "author_profile": "https://wordpress.stackexchange.com/users/13286", "pm_score": 0, "selected": false, "text": "<p>I was able to resolve this by separating the login page from the page with the content. So I have one page that has the login form and at the top it checks if the user is logged in, if they are, it redirects them to the protected content page with their User ID in the URL, otherwise it displays the login form.</p>\n" }, { "answer_id": 292897, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 3, "selected": true, "text": "<p>you can add the user identifier à the redirection URL with this filter</p>\n\n<pre><code>add_filter(\"login_redirect\", function ($redirect_to, $requested_redirect_to, $user) {\n\n $redirect_to = add_query_arg([\n \"user_id\" =&gt; $user-&gt;ID,\n ], $redirect_to);\n\n\n return $redirect_to;\n\n}, 10, 3);\n</code></pre>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292875", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/19430/" ]
I have a website (`www.example.com`) that I'd like to add a WordPress blog to, but I want to keep the website's `index.php` as the homepage. I also want to add two links to the homepage, `example.com/newsletters` and `example.com/explainers`, which link to WordPress archive pages with all the posts tagged "newsletters"and "explainers" respectively. How would I achieve this?
you can add the user identifier à the redirection URL with this filter ``` add_filter("login_redirect", function ($redirect_to, $requested_redirect_to, $user) { $redirect_to = add_query_arg([ "user_id" => $user->ID, ], $redirect_to); return $redirect_to; }, 10, 3); ```
292,877
<p>I need to insert a menu in the text of one page. I found these two plugin but none of them work. Both of them haven't been updated for 6 years:</p> <p><a href="https://wordpress.org/plugins/custom-menu/" rel="nofollow noreferrer">https://wordpress.org/plugins/custom-menu/</a></p> <p><a href="https://wordpress.org/plugins/custom-menu-shortcode/" rel="nofollow noreferrer">https://wordpress.org/plugins/custom-menu-shortcode/</a></p> <p>I found this code to create my own shortcode</p> <pre><code> function print_menu_shortcode($atts, $content = null) { extract(shortcode_atts(array( 'name' =&gt; null, 'class' =&gt; null ), $atts)); return wp_nav_menu( array( 'menu' =&gt; $name, 'menu_class' =&gt; $class, 'echo' =&gt; false ) ); } add_shortcode('menu', 'print_menu_shortcode'); </code></pre> <p>And then shortcode should be: </p> <pre><code>[menu name="-your menu name-" class="-your class-"] </code></pre> <p>It works but the class is not printed at all. <strong>What is wrong in the function?</strong> I need to print the class.</p>
[ { "answer_id": 293006, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 5, "selected": true, "text": "<p>That code should work. Are you usign \"myclass\" as the class and not \".myclass\"? </p>\n\n<p>Is this for a specific use where class will always be the same? If you're only looking to ever use this on one place, you can do this:</p>\n\n<pre><code> function print_menu_shortcode($atts, $content = null) {\nextract(shortcode_atts(array( 'name' =&gt; null, 'class' =&gt; null ), $atts));\nreturn wp_nav_menu( array( 'menu' =&gt; $name, 'menu_class' =&gt; 'myclass', 'echo' =&gt; false ) );\n}\n\nadd_shortcode('menu', 'print_menu_shortcode');\n</code></pre>\n\n<p>Then change the section 'menu_class' => 'myclass' with the class you need. this will avoid having to use the class. Again, don't use the \".\" in front of the class here.</p>\n\n<p>Short code usage:</p>\n\n<pre><code>[menu name=\"menu_name\"]\n</code></pre>\n" }, { "answer_id": 390546, "author": "Robin Joshua Del Mundo", "author_id": 207787, "author_profile": "https://wordpress.stackexchange.com/users/207787", "pm_score": 0, "selected": false, "text": "<p>I know this years too late, but just in case anybody encounters this again, you can use this code to be able include a class with your shortcode and its return value. I modified it with the corresponding answers before in here.</p>\n<pre><code>function print_menu_shortcode($atts=[], $content = null) {\n $shortcode_atts = shortcode_atts([ 'name' =&gt; '', 'class' =&gt; '' ], $atts);\n $name = $shortcode_atts['name'];\n $class = $shortcode_atts['class'];\n return wp_nav_menu( array( 'menu' =&gt; $name, 'menu_class' =&gt; $class, 'echo' =&gt; false ) );\n}\n</code></pre>\n<p>Shortcode:\n<code>[menu name=&quot;menu_name&quot; class=&quot;your_class&quot;]</code></p>\n<p>I hope this helps anyone that may need it in the future!</p>\n" } ]
2018/02/01
[ "https://wordpress.stackexchange.com/questions/292877", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107273/" ]
I need to insert a menu in the text of one page. I found these two plugin but none of them work. Both of them haven't been updated for 6 years: <https://wordpress.org/plugins/custom-menu/> <https://wordpress.org/plugins/custom-menu-shortcode/> I found this code to create my own shortcode ``` function print_menu_shortcode($atts, $content = null) { extract(shortcode_atts(array( 'name' => null, 'class' => null ), $atts)); return wp_nav_menu( array( 'menu' => $name, 'menu_class' => $class, 'echo' => false ) ); } add_shortcode('menu', 'print_menu_shortcode'); ``` And then shortcode should be: ``` [menu name="-your menu name-" class="-your class-"] ``` It works but the class is not printed at all. **What is wrong in the function?** I need to print the class.
That code should work. Are you usign "myclass" as the class and not ".myclass"? Is this for a specific use where class will always be the same? If you're only looking to ever use this on one place, you can do this: ``` function print_menu_shortcode($atts, $content = null) { extract(shortcode_atts(array( 'name' => null, 'class' => null ), $atts)); return wp_nav_menu( array( 'menu' => $name, 'menu_class' => 'myclass', 'echo' => false ) ); } add_shortcode('menu', 'print_menu_shortcode'); ``` Then change the section 'menu\_class' => 'myclass' with the class you need. this will avoid having to use the class. Again, don't use the "." in front of the class here. Short code usage: ``` [menu name="menu_name"] ```
292,921
<p>Okay So I'm facing a weird problem as i'm receiving 404 errors on blog category and tag pages. I'm using custom theme which includes: </p> <ul> <li>tag.php</li> <li>category.php</li> <li>archive.php </li> <li>home.php</li> <li>index.php and </li> <li>404.php.</li> </ul> <p>The Blog archive is working fine but when i try to load tag pages or category pages i'm being redirected to 404.php template file.</p> <p>Also there is one other weird problem which i'm facing if i remove 404.php file from my theme folder the category and tag links are working fine and loads content from archive.php but it shows page not found on page title and error404 class is added inside the body tag of that page.</p> <p>Here is the list of items that i've tried so far to solve the issue:</p> <ol> <li>Refreshed Permalink Structure.</li> <li>Applied Category and Tag Base.</li> <li>Changing the theme to twentyseventeen in which everything was fine</li> <li>All the code in my header and footer.php file follows wordpress theme guidelines.</li> </ol> <p>Please suggest me a solution that might help to solve this as it works fine without 404.php. The Blogs and Categories on website are imported from other website using Wordpress importer.</p> <p>Question Update: Why Does Wordpress redirects to 404.php even tough files category.php, archive.php and index.php are present inside Wordpress theme folder on category or tag pages ??</p>
[ { "answer_id": 292923, "author": "vishalprajapati13", "author_id": 136086, "author_profile": "https://wordpress.stackexchange.com/users/136086", "pm_score": -1, "selected": false, "text": "<p>Go to your WordPress back-end with this path Settings > Permalinks. Ensure that the base of the category is \"category\" and the tag is the base \"tag\" (unless you have some very strange special settings) and just press the \"Save Changes\" button even if nothing has changed, clicking on the button may cause your category and tag pages to work again.</p>\n\n<p>Don’t forget to clean your WordPress cache for testing.</p>\n" }, { "answer_id": 292925, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<p>please set permalinks </p>\n\n<p><a href=\"https://i.stack.imgur.com/rETKv.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rETKv.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>then after check in category and tag url</p>\n" }, { "answer_id": 351790, "author": "Riyaz", "author_id": 140415, "author_profile": "https://wordpress.stackexchange.com/users/140415", "pm_score": 0, "selected": false, "text": "<p>I've had the same issue. However, I added the following to functions.php file (courtesy: wpbeginner.com) to view my custom post types in categories. WordPress does not display any custom post types in categories until we add the following filter.</p>\n\n<pre><code>add_filter('pre_get_posts', 'query_post_type');\nfunction query_post_type($query) {\n if( is_category() ) {\n $post_type = get_query_var('post_type');\n if($post_type)\n $post_type = $post_type;\n else\n $post_type = array('nav_menu_item', 'post', 'your_post_type_name'); // don't forget nav_menu_item to allow menus to work!\n $query-&gt;set('post_type',$post_type);\n return $query;\n }\n}\n</code></pre>\n" }, { "answer_id": 361109, "author": "Joni H.", "author_id": 184573, "author_profile": "https://wordpress.stackexchange.com/users/184573", "pm_score": 2, "selected": false, "text": "<p>I know this is an old question but I was having the same issue in a theme I inherited and came across this question in my search for answers.</p>\n\n<p>In my particular case, I found the following PHP code included in the theme's <code>function.php</code> file:</p>\n\n<pre><code>if( is_category() || is_date() || is_author() ) {\n global $wp_query;\n $wp_query-&gt;set_404(); //set to 404 not found page\n}\n</code></pre>\n\n<p>This code redirects any category, date, or author archive page to a 404 error (which brings up your 404 theme template). You may want to search for something similar in your theme (assuming you haven't already figured this out).</p>\n" } ]
2018/02/02
[ "https://wordpress.stackexchange.com/questions/292921", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129705/" ]
Okay So I'm facing a weird problem as i'm receiving 404 errors on blog category and tag pages. I'm using custom theme which includes: * tag.php * category.php * archive.php * home.php * index.php and * 404.php. The Blog archive is working fine but when i try to load tag pages or category pages i'm being redirected to 404.php template file. Also there is one other weird problem which i'm facing if i remove 404.php file from my theme folder the category and tag links are working fine and loads content from archive.php but it shows page not found on page title and error404 class is added inside the body tag of that page. Here is the list of items that i've tried so far to solve the issue: 1. Refreshed Permalink Structure. 2. Applied Category and Tag Base. 3. Changing the theme to twentyseventeen in which everything was fine 4. All the code in my header and footer.php file follows wordpress theme guidelines. Please suggest me a solution that might help to solve this as it works fine without 404.php. The Blogs and Categories on website are imported from other website using Wordpress importer. Question Update: Why Does Wordpress redirects to 404.php even tough files category.php, archive.php and index.php are present inside Wordpress theme folder on category or tag pages ??
I know this is an old question but I was having the same issue in a theme I inherited and came across this question in my search for answers. In my particular case, I found the following PHP code included in the theme's `function.php` file: ``` if( is_category() || is_date() || is_author() ) { global $wp_query; $wp_query->set_404(); //set to 404 not found page } ``` This code redirects any category, date, or author archive page to a 404 error (which brings up your 404 theme template). You may want to search for something similar in your theme (assuming you haven't already figured this out).
292,947
<p>I'm working an Ajaxifying form. This form is a custom page template. The saving of the data is working, but when the form is submitting, the page is redirects to <code>websiteurl/wp-admin/admin-ajax.php</code> with a white blank page. What I want is to prevent the reloading of the page. I didn't receive any error message from <code>error function</code>.</p> <p>How to fix this?</p> <p><strong>HTML</strong></p> <pre><code>&lt;form method="POST" action="&lt;?php echo admin_url('admin-ajax.php'); ?&gt;" id="modal-form-ajax" autocomplete="off"&gt; &lt;input type="hidden" name="form_title" value="Resume"/&gt; &lt;input placeholder="Last Name*" type="text" name="lastName" id="lastName" value="" required data-selectable="true"&gt; &lt;input placeholder="First Name*" type="text" name="firstName" id="firstName" value="" required data-selectable="true"&gt; &lt;input placeholder="Email Address" type="email" name="Email" id="Email" onblur="this.setAttribute('value', this.value);" value="" required data-selectable="true"&gt; &lt;input placeholder="Mobile Number*" type="text" name="contactNumber" id="contactNumber" onkeypress="return isNumberKey(event)" value="" size="11" minlength="11" maxlength="11" pattern ="^09\d{9}$" oninvalid="this.setCustomValidity('Please enter your 11-digits Philippine mobile number')" onchange="try{ setCustomValidity('') } catch(e){}" required data-selectable="true"&gt; &lt;div class="flex"&gt; &lt;label&gt;Upload CV &amp; Cover Letter&lt;/label&gt; &lt;input placeholder="CV" type="file" name="Resume" value="" required&gt; &lt;/div&gt; &lt;input type="hidden" name="action" value="validate_form_modal"/&gt; &lt;?php wp_nonce_field('validate_form_modal_nonce', 'name_of_nonce_field'); ?&gt; &lt;button id="submit-btn"&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <p><strong>JS</strong></p> <pre><code>(function($){ $("#modal-form-ajax").submit(function(e){ e.preventDefault(); var resumetest = $('input[name="form_title"]').val(); var lastName = $('input[name="lastName"]').val(); var firstName = $('input[name="firstName"]').val(); var Email = $('input[name="Email"]').val(); var contactNumber = $('input[name="contactNumber"]').val(); var ajaxUrl = { ajaxFormUrl: '//websiteurl/wp-admin/admin-ajax.php' } $.ajax({ type: 'post', dataType: "json", url: ajaxUrl.ajaxFormUrl, data: { action: 'validate_form_modal', lastName: lastName, firstName: firstName, Email: Email, contactNumber: contactNumber, Resume: Resume }, success: function(data){ console.log("Thank you for your application"); console.log($('#modal-form-ajax').serialize()); $("#modal-form-ajax").fadeOut('ease',function(){ $("#modal-form-ajax").html('&lt;div id="modal-form-success"&gt;&lt;div class="circle-loader"&gt;&lt;div class="checkmark draw"&gt;&lt;/div&gt;&lt;/div&gt;&lt;p&gt;Thank you for your application&lt;/p&gt;&lt;p&gt;We\'ll get back to you shortly.&lt;/p&gt;&lt;/div&gt;'); $("#modal-form-ajax").fadeIn('ease'); }); }, error: function(){ alert(response); } }); }); })(jQuery); </code></pre> <p><strong>PHP (functions.php)</strong></p> <pre><code>function ajax_modal_form_init(){ wp_localize_script('ajax-modal-form', 'modalFormAjax', array('ajaxurl' =&gt; admin_url( 'admin-ajax.php' ))); wp_enqueue_script('ajax-modal-form'); } add_action('wp_ajax_validate_form_modal', 'validate_form_modal'); add_action('wp_ajax_nopriv_validate_form_modal', 'validate_form_modal'); function validate_form_modal(){ ob_clean(); global $wpdb; if(!isset($_POST['name_of_nonce_field']) || ! wp_verify_nonce( $_POST['name_of_nonce_field'], 'validate_form_modal_nonce')){ exit('The form is not valid'); } $lastName = isset($_POST['lastName']) ? filter_var($_POST['lastName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH) : ''; $firstName = isset($_POST['firstName']) ? filter_var($_POST['firstName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH) : ''; $email = isset($_POST['Email']) ? filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL) : ''; $contactNumber = isset($_POST['contactNumber']) ? filter_var($_POST['contactNumber'], FILTER_VALIDATE_REGEXP) : ''; echo do_shortcode("[cfdb-save-form-post]"); wp_die(); } </code></pre>
[ { "answer_id": 292964, "author": "Anton Flärd", "author_id": 107106, "author_profile": "https://wordpress.stackexchange.com/users/107106", "pm_score": 0, "selected": false, "text": "<p>Try one of these:</p>\n\n<ol>\n<li>Put the submit button outside the form and bind the js-function to the button instead <code>$('#submit-btn).on('click', function(e){ e.preventDefault(); ...})</code>.</li>\n<li>Try to <code>return false;</code> and the end of your script, right after <code>$.ajax({...});</code>.</li>\n</ol>\n\n<p>Read more in <a href=\"https://stackoverflow.com/questions/8121958/jquery-ajax-post-inside-a-form-prevent-form-submission-on-ajax-call\">this SO question</a>.</p>\n" }, { "answer_id": 379117, "author": "Tony Djukic", "author_id": 60844, "author_profile": "https://wordpress.stackexchange.com/users/60844", "pm_score": 1, "selected": false, "text": "<p>Just saw it... ...in your HTML, take the action out entirely. We're not using the HTML to tell the form/submit button what to do, we're using JS/AJAX for that.</p>\n<p><code>&lt;form method=&quot;POST&quot; action=&quot;&lt;?php echo admin_url('admin-ajax.php'); ?&gt;&quot; id=&quot;modal-form-ajax&quot; autocomplete=&quot;off&quot;&gt;</code></p>\n<p>Should become:</p>\n<p><code>&lt;form method=&quot;POST&quot; id=&quot;modal-form-ajax&quot; autocomplete=&quot;off&quot;&gt;</code></p>\n<p>Also, instead of targeting the form, target the submit button, so the following:</p>\n<pre><code>$(&quot;#modal-form-ajax&quot;).submit(function(e){\n e.preventDefault();\n</code></pre>\n<p>Should become:</p>\n<pre><code>$(&quot;#submit-btn&quot;).on('click',function(e) {\n e.preventDefault();\n</code></pre>\n" } ]
2018/02/02
[ "https://wordpress.stackexchange.com/questions/292947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54602/" ]
I'm working an Ajaxifying form. This form is a custom page template. The saving of the data is working, but when the form is submitting, the page is redirects to `websiteurl/wp-admin/admin-ajax.php` with a white blank page. What I want is to prevent the reloading of the page. I didn't receive any error message from `error function`. How to fix this? **HTML** ``` <form method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>" id="modal-form-ajax" autocomplete="off"> <input type="hidden" name="form_title" value="Resume"/> <input placeholder="Last Name*" type="text" name="lastName" id="lastName" value="" required data-selectable="true"> <input placeholder="First Name*" type="text" name="firstName" id="firstName" value="" required data-selectable="true"> <input placeholder="Email Address" type="email" name="Email" id="Email" onblur="this.setAttribute('value', this.value);" value="" required data-selectable="true"> <input placeholder="Mobile Number*" type="text" name="contactNumber" id="contactNumber" onkeypress="return isNumberKey(event)" value="" size="11" minlength="11" maxlength="11" pattern ="^09\d{9}$" oninvalid="this.setCustomValidity('Please enter your 11-digits Philippine mobile number')" onchange="try{ setCustomValidity('') } catch(e){}" required data-selectable="true"> <div class="flex"> <label>Upload CV & Cover Letter</label> <input placeholder="CV" type="file" name="Resume" value="" required> </div> <input type="hidden" name="action" value="validate_form_modal"/> <?php wp_nonce_field('validate_form_modal_nonce', 'name_of_nonce_field'); ?> <button id="submit-btn">Submit</button> </form> ``` **JS** ``` (function($){ $("#modal-form-ajax").submit(function(e){ e.preventDefault(); var resumetest = $('input[name="form_title"]').val(); var lastName = $('input[name="lastName"]').val(); var firstName = $('input[name="firstName"]').val(); var Email = $('input[name="Email"]').val(); var contactNumber = $('input[name="contactNumber"]').val(); var ajaxUrl = { ajaxFormUrl: '//websiteurl/wp-admin/admin-ajax.php' } $.ajax({ type: 'post', dataType: "json", url: ajaxUrl.ajaxFormUrl, data: { action: 'validate_form_modal', lastName: lastName, firstName: firstName, Email: Email, contactNumber: contactNumber, Resume: Resume }, success: function(data){ console.log("Thank you for your application"); console.log($('#modal-form-ajax').serialize()); $("#modal-form-ajax").fadeOut('ease',function(){ $("#modal-form-ajax").html('<div id="modal-form-success"><div class="circle-loader"><div class="checkmark draw"></div></div><p>Thank you for your application</p><p>We\'ll get back to you shortly.</p></div>'); $("#modal-form-ajax").fadeIn('ease'); }); }, error: function(){ alert(response); } }); }); })(jQuery); ``` **PHP (functions.php)** ``` function ajax_modal_form_init(){ wp_localize_script('ajax-modal-form', 'modalFormAjax', array('ajaxurl' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script('ajax-modal-form'); } add_action('wp_ajax_validate_form_modal', 'validate_form_modal'); add_action('wp_ajax_nopriv_validate_form_modal', 'validate_form_modal'); function validate_form_modal(){ ob_clean(); global $wpdb; if(!isset($_POST['name_of_nonce_field']) || ! wp_verify_nonce( $_POST['name_of_nonce_field'], 'validate_form_modal_nonce')){ exit('The form is not valid'); } $lastName = isset($_POST['lastName']) ? filter_var($_POST['lastName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH) : ''; $firstName = isset($_POST['firstName']) ? filter_var($_POST['firstName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH) : ''; $email = isset($_POST['Email']) ? filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL) : ''; $contactNumber = isset($_POST['contactNumber']) ? filter_var($_POST['contactNumber'], FILTER_VALIDATE_REGEXP) : ''; echo do_shortcode("[cfdb-save-form-post]"); wp_die(); } ```
Just saw it... ...in your HTML, take the action out entirely. We're not using the HTML to tell the form/submit button what to do, we're using JS/AJAX for that. `<form method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>" id="modal-form-ajax" autocomplete="off">` Should become: `<form method="POST" id="modal-form-ajax" autocomplete="off">` Also, instead of targeting the form, target the submit button, so the following: ``` $("#modal-form-ajax").submit(function(e){ e.preventDefault(); ``` Should become: ``` $("#submit-btn").on('click',function(e) { e.preventDefault(); ```
292,971
<p>How can I sort an array of elements being hold on a query done by a template function, just before the output starts on a foreach loop? I wanted to order my elements by the Post Title. Here is my code:</p> <pre><code>&lt;?php $show_subproperties = apushome_get_config('show_property_sub', true); if (!$show_subproperties) { return; } $post = get_post(); $author_id = $post-&gt;post_author; $subproperties = Realia_Post_Type_Property::get_properties($author_id, "publish", get_the_ID()); ?&gt; &lt;?php if (is_array($subproperties) &amp;&amp; !empty($subproperties)) : ?&gt; &lt;div class="property-subproperties"&gt; &lt;h3&gt;&lt;?php echo esc_html__('Módulos Individuais', 'apushome'); ?&gt;&lt;/h3&gt; &lt;div class="clearfix"&gt; &lt;?php foreach ($subproperties as $subproperty) : ?&gt; &lt;div class="col-md-4 col-lg-3 col-sm-6 col-xs-12 modulos-i"&gt; &lt;?php echo Realia_Template_Loader::load('properties/box', array('property' =&gt; $subproperty)); ?&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; &lt;/div&gt;&lt;!-- /.row --&gt; &lt;/div&gt;&lt;!-- /.subproperties --&gt; &lt;?php endif ?&gt; </code></pre>
[ { "answer_id": 292964, "author": "Anton Flärd", "author_id": 107106, "author_profile": "https://wordpress.stackexchange.com/users/107106", "pm_score": 0, "selected": false, "text": "<p>Try one of these:</p>\n\n<ol>\n<li>Put the submit button outside the form and bind the js-function to the button instead <code>$('#submit-btn).on('click', function(e){ e.preventDefault(); ...})</code>.</li>\n<li>Try to <code>return false;</code> and the end of your script, right after <code>$.ajax({...});</code>.</li>\n</ol>\n\n<p>Read more in <a href=\"https://stackoverflow.com/questions/8121958/jquery-ajax-post-inside-a-form-prevent-form-submission-on-ajax-call\">this SO question</a>.</p>\n" }, { "answer_id": 379117, "author": "Tony Djukic", "author_id": 60844, "author_profile": "https://wordpress.stackexchange.com/users/60844", "pm_score": 1, "selected": false, "text": "<p>Just saw it... ...in your HTML, take the action out entirely. We're not using the HTML to tell the form/submit button what to do, we're using JS/AJAX for that.</p>\n<p><code>&lt;form method=&quot;POST&quot; action=&quot;&lt;?php echo admin_url('admin-ajax.php'); ?&gt;&quot; id=&quot;modal-form-ajax&quot; autocomplete=&quot;off&quot;&gt;</code></p>\n<p>Should become:</p>\n<p><code>&lt;form method=&quot;POST&quot; id=&quot;modal-form-ajax&quot; autocomplete=&quot;off&quot;&gt;</code></p>\n<p>Also, instead of targeting the form, target the submit button, so the following:</p>\n<pre><code>$(&quot;#modal-form-ajax&quot;).submit(function(e){\n e.preventDefault();\n</code></pre>\n<p>Should become:</p>\n<pre><code>$(&quot;#submit-btn&quot;).on('click',function(e) {\n e.preventDefault();\n</code></pre>\n" } ]
2018/02/02
[ "https://wordpress.stackexchange.com/questions/292971", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131677/" ]
How can I sort an array of elements being hold on a query done by a template function, just before the output starts on a foreach loop? I wanted to order my elements by the Post Title. Here is my code: ``` <?php $show_subproperties = apushome_get_config('show_property_sub', true); if (!$show_subproperties) { return; } $post = get_post(); $author_id = $post->post_author; $subproperties = Realia_Post_Type_Property::get_properties($author_id, "publish", get_the_ID()); ?> <?php if (is_array($subproperties) && !empty($subproperties)) : ?> <div class="property-subproperties"> <h3><?php echo esc_html__('Módulos Individuais', 'apushome'); ?></h3> <div class="clearfix"> <?php foreach ($subproperties as $subproperty) : ?> <div class="col-md-4 col-lg-3 col-sm-6 col-xs-12 modulos-i"> <?php echo Realia_Template_Loader::load('properties/box', array('property' => $subproperty)); ?> </div> <?php endforeach; ?> </div><!-- /.row --> </div><!-- /.subproperties --> <?php endif ?> ```
Just saw it... ...in your HTML, take the action out entirely. We're not using the HTML to tell the form/submit button what to do, we're using JS/AJAX for that. `<form method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>" id="modal-form-ajax" autocomplete="off">` Should become: `<form method="POST" id="modal-form-ajax" autocomplete="off">` Also, instead of targeting the form, target the submit button, so the following: ``` $("#modal-form-ajax").submit(function(e){ e.preventDefault(); ``` Should become: ``` $("#submit-btn").on('click',function(e) { e.preventDefault(); ```
293,008
<p>I need unregister this enqueue style of wp_footer() hook and add it to the top of site with hook wp_head(), this is possible?</p> <p>I'm optimizing my theme to validate in W3C, and one of the requirements of W3C is that all styles are within the tag <code>&lt;head&gt;&lt;/head&gt;</code>... I am using an specific plugin called <code>Crayon Syntax Highlighter</code>, and this plugin are inserting a style at the bottom of the page (probably using <code>wp_footer()</code> hook).</p> <p>The name/id of script is <code>crayon</code>: <a href="https://i.stack.imgur.com/6pdNN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6pdNN.png" alt="enter image description here"></a></p> <p>I've tryed all this functions but no success:</p> <pre><code>wp_deregister_style( 'crayon' ); wp_dequeue_style( 'crayon' ); remove_action( 'wp_enqueue_style' , 'crayon' , 10 ); wp_deregister_style( 'crayon-css' ); wp_dequeue_style( 'crayon-css' ); remove_action( 'wp_enqueue_style' , 'crayon-css' , 10 ); </code></pre>
[ { "answer_id": 293012, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>If you look at the <a href=\"https://plugins.trac.wordpress.org/browser/crayon-syntax-highlighter/trunk/crayon_wp.class.php\" rel=\"nofollow noreferrer\">source code</a>, you can see that <code>wp_enqueue_style( 'crayon' )</code> is called in <code>Crayon::enqueue_resources()</code> which itself is called either from either <code>Crayon::the_content()</code> or <code>Crayon::wp_head()</code>. The code in <code>Crayon::wp_head</code> is:</p>\n\n<pre><code>if (!CrayonGlobalSettings::val(CrayonSettings::EFFICIENT_ENQUEUE) || CrayonGlobalSettings::val(CrayonSettings::TAG_EDITOR_FRONT)) {\n CrayonLog::debug('head: force enqueue');\n // Efficient enqueuing disabled, always load despite enqueuing or not in the_post\n self::enqueue_resources();\n}\n</code></pre>\n\n<p>Which will enqueue the style only when certain settings are enabled. Otherwise, the style will only be enqueued from <code>the_content</code> filter which fires after <code>wp_head</code> has already been output.</p>\n\n<p>So your two options are:</p>\n\n<ol>\n<li>Have the CSS enqueued on all pages in the header</li>\n<li>Have the CSS enqueued only on necessary pages but in the footer</li>\n</ol>\n" }, { "answer_id": 293014, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Hmmmm.. the question is not very clear to me, if you could provide a little more info about your issue (like the specific files and scripts you need to modify) would be great. From what i understood, i'll try to help you. First, avoid plugins unless you really really need them. Now, you might be trying to move render-blocking JavaScript and CSS out of the tag, that's because when you start loading a page through your browser, the first scripts you download are those between the tag, by moving those scripts to your footer (footer.php or /public_html/wp-content/themes/yourtheme/footer.php) the Web page will start rendering all the data that needs to be visualized first, beginning from the top of the page and at last those scripts in the footer.php file. I bet\n<code>Crayon Syntax Highlighter</code> is causing the issue, just try to put this <code>&lt;!-- W3TC-include-js-head --&gt;</code> before the closing <code>&lt;/body&gt;</code> tag. </p>\n\n<p>If you want to use <code>wp_enqueue_scripts</code> look at this example</p>\n\n<pre><code>function themeslug_enqueue_style() {\n wp_enqueue_style( 'core', 'style.css', false ); \n}\n\nfunction themeslug_enqueue_script() {\n wp_enqueue_script( 'my-js', 'filename.js', false );\n}\n\nadd_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );\nadd_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' );\n</code></pre>\n\n<p>I hope this helps, good luck dude. :)</p>\n" } ]
2018/02/02
[ "https://wordpress.stackexchange.com/questions/293008", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39187/" ]
I need unregister this enqueue style of wp\_footer() hook and add it to the top of site with hook wp\_head(), this is possible? I'm optimizing my theme to validate in W3C, and one of the requirements of W3C is that all styles are within the tag `<head></head>`... I am using an specific plugin called `Crayon Syntax Highlighter`, and this plugin are inserting a style at the bottom of the page (probably using `wp_footer()` hook). The name/id of script is `crayon`: [![enter image description here](https://i.stack.imgur.com/6pdNN.png)](https://i.stack.imgur.com/6pdNN.png) I've tryed all this functions but no success: ``` wp_deregister_style( 'crayon' ); wp_dequeue_style( 'crayon' ); remove_action( 'wp_enqueue_style' , 'crayon' , 10 ); wp_deregister_style( 'crayon-css' ); wp_dequeue_style( 'crayon-css' ); remove_action( 'wp_enqueue_style' , 'crayon-css' , 10 ); ```
If you look at the [source code](https://plugins.trac.wordpress.org/browser/crayon-syntax-highlighter/trunk/crayon_wp.class.php), you can see that `wp_enqueue_style( 'crayon' )` is called in `Crayon::enqueue_resources()` which itself is called either from either `Crayon::the_content()` or `Crayon::wp_head()`. The code in `Crayon::wp_head` is: ``` if (!CrayonGlobalSettings::val(CrayonSettings::EFFICIENT_ENQUEUE) || CrayonGlobalSettings::val(CrayonSettings::TAG_EDITOR_FRONT)) { CrayonLog::debug('head: force enqueue'); // Efficient enqueuing disabled, always load despite enqueuing or not in the_post self::enqueue_resources(); } ``` Which will enqueue the style only when certain settings are enabled. Otherwise, the style will only be enqueued from `the_content` filter which fires after `wp_head` has already been output. So your two options are: 1. Have the CSS enqueued on all pages in the header 2. Have the CSS enqueued only on necessary pages but in the footer
293,018
<p>I've got a custom theme I've developed and it's basically a 4 page brochure site for a client and I've managed to do away with a few plugins by building in custom-post-types, gzipping via .htaccess and minifying via gulp etc etc.</p> <p>I'll be keeping the security plugin on the site, but I'd like to remove Yoast, the only benefit it brings, bearing in mind how optimised the site is, is that it allows me to add the <code>meta</code> tags and snippets for each page for SEO purposes.</p> <p>Is there a function that I can add add to my functions.php file that allows me to add <code>&lt;meta&gt;</code> tags to different pages via the page id?</p> <p>When one Googles this subject all you get is plugin articles, or info about general wp meta.</p> <p>Any help would be awesome.</p> <p>Paul.</p>
[ { "answer_id": 293019, "author": "Howdy_McGee", "author_id": 7355, "author_profile": "https://wordpress.stackexchange.com/users/7355", "pm_score": 5, "selected": false, "text": "<p>The hook you're looking for is specifically <a href=\"https://developer.wordpress.org/reference/hooks/wp_head/\" rel=\"nofollow noreferrer\"><code>wp_head</code></a> which could look something like this:</p>\n<pre><code>function theme_xyz_header_metadata() {\n \n // Post object if needed\n // global $post;\n \n // Page conditional if needed\n // if( is_page() ){}\n \n ?&gt;\n \n &lt;meta name=&quot;abc&quot; content=&quot;xyz&quot; /&gt;\n \n &lt;?php\n \n}\nadd_action( 'wp_head', 'theme_xyz_header_metadata' );\n</code></pre>\n<p>I believe in the long run though, since WordPress is so portable, Yoast SEO is probably the most reliable, flexible bet for SEO than something you would do yourself so I would advise against this personally.</p>\n" }, { "answer_id": 293032, "author": "scytale", "author_id": 128374, "author_profile": "https://wordpress.stackexchange.com/users/128374", "pm_score": 1, "selected": false, "text": "<p>DIY SEO:</p>\n\n<p>1: In the post/page editor for a page or post: Add custom field(s) (meta data) with required value(s) for your SEO meta tag(s). </p>\n\n<ul>\n<li>e.g. Open say your \"Terms &amp;Conditions\" page in the page editor and\nadd a custom field \"<code>my_noindex</code>\" with a value of \"y\".</li>\n<li>N.B. if the custom field box is not visible below the editor, click\nthe \"display options\" drop-down at the top of the page and then the\n\"custom fields\" check box that appears.</li>\n</ul>\n\n<p>2: In functions.php (or better still in your own theme independent site_functions plugin): Add your SEO function (to be \"called\" by wp_head) which take these values for the current page and inserts them in the HTML <code>&lt;head&gt;</code>. </p>\n\n<pre><code>// echo noindex tag if post or page has a \"my_noindex\" custom field with a value of \"y\"|\"Y\"|\"yes\" ...\nfunction my_meta_tags() {\n $noindex = (get_post_meta( get_queried_object_id(), 'my_noindex', true ));\n if (strtolower(substr($noindex,0,1)) == 'y') { \n ?&gt;&lt;meta name=\"robots\" content=\"noindex\" /&gt;\n &lt;?php return; // noindex so no point in doing any other SEO stuff\n }\n\n // other SEO stuff\n\n}\nadd_action( 'wp_head', 'my_meta_tags',2);\n</code></pre>\n\n<p>Jeff Starr's <a href=\"https://digwp.com/2013/08/basic-wp-seo/\" rel=\"nofollow noreferrer\">article on rolling your own SEO code</a> (including title and description) will help. It requires a custom/child theme as its code goes in header.php, however much of the code could be modified for the my_meta_tags function above. It may not apply SEO the way you want but that's the beauty of DIY: if you want to use your carefully crafted description in custom field (if present), else your custom excerpt, else first n chars of description; then you can write your code accordingly. I've also been intending to write an article on this subject - if I get round to it I'll add a link.</p>\n\n<p><strong>Omissions from article's code:</strong></p>\n\n<ul>\n<li><p><strong>Prevent duplicate title tags</strong> (as some themes insert their own). Modern,\nproperly designed themes should enable you to remove the themes title tag\nwhen you add the following to your site functions.php.</p>\n\n<pre><code>function my_remove_stuff() {\n remove_theme_support( 'title-tag' ); \n}\nadd_action('after_setup_theme', 'my_remove_stuff', 15);\n</code></pre></li>\n<li><p><strong>Canonical Tags</strong>. Add the following to the first function above:</p>\n\n<pre><code>//if post or page has a \"my_canon\" custom field\n$my_canon = get_post_meta( get_queried_object_id(), 'my_canon', true );\nif ( ! empty($my_canon)) :\n echo '&lt;link rel=\"canonical\" href=\"' . $my_canon . '\" /&gt;';\n remove_action('wp_head', 'rel_canonical'); // prevnts Wordpress inserting a canon tag - we don't want two\nendif;\n</code></pre></li>\n</ul>\n\n<p>An SEO plugin is the right option for many users. However if you are happy writing your own code there are many benefits:\navoid bloat, avoid lock-in/dependence on plugin, avoid (in some cases) paying for support, SEO works the way you want it; no SEO conflict issues with SEO on your own dynamic custom pages etc.</p>\n" } ]
2018/02/02
[ "https://wordpress.stackexchange.com/questions/293018", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/106972/" ]
I've got a custom theme I've developed and it's basically a 4 page brochure site for a client and I've managed to do away with a few plugins by building in custom-post-types, gzipping via .htaccess and minifying via gulp etc etc. I'll be keeping the security plugin on the site, but I'd like to remove Yoast, the only benefit it brings, bearing in mind how optimised the site is, is that it allows me to add the `meta` tags and snippets for each page for SEO purposes. Is there a function that I can add add to my functions.php file that allows me to add `<meta>` tags to different pages via the page id? When one Googles this subject all you get is plugin articles, or info about general wp meta. Any help would be awesome. Paul.
The hook you're looking for is specifically [`wp_head`](https://developer.wordpress.org/reference/hooks/wp_head/) which could look something like this: ``` function theme_xyz_header_metadata() { // Post object if needed // global $post; // Page conditional if needed // if( is_page() ){} ?> <meta name="abc" content="xyz" /> <?php } add_action( 'wp_head', 'theme_xyz_header_metadata' ); ``` I believe in the long run though, since WordPress is so portable, Yoast SEO is probably the most reliable, flexible bet for SEO than something you would do yourself so I would advise against this personally.
293,025
<p>I created a custom user_meta, but I cant update it via curl.</p> <p>I can do this with user_meta</p> <pre><code>curl --header "Authorization: Basic ACCESS_TOKEN" -X POST -d "description=New description" http://domain.com/wp-json/wp/v2/users/1 </code></pre> <p>But I cant do the same with custom meta</p> <pre><code>curl --header "Authorization: Basic ACCESS_TOKEN" -X POST -d "user_continent=Asia" http://domain.com/wp-json/wp/v2/users/1 </code></pre> <p><a href="https://i.stack.imgur.com/xJOQZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xJOQZ.jpg" alt="JSON screenshot"></a></p> <p>This may help</p> <p>How I add the custom meta to the API:</p> <pre><code>add_action( 'rest_api_init', 'adding_user_meta_rest' ); function adding_user_meta_rest() { $user_metas = array('account_psn_title', 'account_psn_id', 'account_steam_title', 'account_steam_id', 'account_twitch_title', 'account_twitch_id', 'account_xbox_title', 'account_xbox_id', 'account_youtube_title', 'account_youtube_id', '_uw_balance', 'user_continent', 'user_platform'); foreach ($user_metas as $user_meta) { register_rest_field( 'user', $user_meta, array( 'get_callback' =&gt; 'user_meta_callback', 'update_callback' =&gt; 'user_meta_update_callback', 'schema' =&gt; null, ) ); } } function user_meta_callback( $user, $field_name, $request) { return get_user_meta( $user[ 'id' ], $field_name, true ); } function user_meta_update_callback( $user, $field_name, $request) { update_user_meta( $user[ 'id' ], $field_name, XXXX ); } </code></pre> <p>function <code>user_meta_update_callback</code> is my attempt to make those custom meta editable.</p> <p>What should I put in <code>user_meta_update_callback</code> in place of the XXXX? Am I doing right?</p>
[ { "answer_id": 293027, "author": "janh", "author_id": 129206, "author_profile": "https://wordpress.stackexchange.com/users/129206", "pm_score": 1, "selected": false, "text": "<p>You'll get the value as the first parameter, or you could get it out of $request, which is a <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_request/\" rel=\"nofollow noreferrer\">WP_REST_Request</a> object. Since you're using <code>POST</code>, the parameters out of <code>$request-&gt;get_body_params()</code> which will return an array. If you just need the actual meta value, you don't need to do this.</p>\n\n<p>Your callback function should look something like this: </p>\n\n<pre><code>function user_meta_update_callback( $value, $user, $field_name, $request ) {\n update_user_meta( $user[ 'id' ], $field_name, $value );\n}\n</code></pre>\n" }, { "answer_id": 293089, "author": "mmm", "author_id": 74311, "author_profile": "https://wordpress.stackexchange.com/users/74311", "pm_score": 3, "selected": true, "text": "<p>arguments <code>get_callback</code> and <code>update_callback</code> receive different arguments.</p>\n\n<p>try this exemple which works for a field <code>user_continent</code></p>\n\n<pre><code>add_action(\"rest_api_init\", function () {\n\n\n register_rest_field(\n \"user\"\n , \"user_continent\"\n ,\n [\n \"get_callback\" =&gt; function ($user, $field_name, $request, $object_type) {\n\n return get_user_meta($user[\"id\"], $field_name, TRUE);\n\n },\n \"update_callback\" =&gt; function ($value, $user, $field_name, $request, $object_type) {\n\n update_user_meta($user-&gt;ID, $field_name, $value);\n\n },\n ]\n );\n\n\n});\n</code></pre>\n" } ]
2018/02/02
[ "https://wordpress.stackexchange.com/questions/293025", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68492/" ]
I created a custom user\_meta, but I cant update it via curl. I can do this with user\_meta ``` curl --header "Authorization: Basic ACCESS_TOKEN" -X POST -d "description=New description" http://domain.com/wp-json/wp/v2/users/1 ``` But I cant do the same with custom meta ``` curl --header "Authorization: Basic ACCESS_TOKEN" -X POST -d "user_continent=Asia" http://domain.com/wp-json/wp/v2/users/1 ``` [![JSON screenshot](https://i.stack.imgur.com/xJOQZ.jpg)](https://i.stack.imgur.com/xJOQZ.jpg) This may help How I add the custom meta to the API: ``` add_action( 'rest_api_init', 'adding_user_meta_rest' ); function adding_user_meta_rest() { $user_metas = array('account_psn_title', 'account_psn_id', 'account_steam_title', 'account_steam_id', 'account_twitch_title', 'account_twitch_id', 'account_xbox_title', 'account_xbox_id', 'account_youtube_title', 'account_youtube_id', '_uw_balance', 'user_continent', 'user_platform'); foreach ($user_metas as $user_meta) { register_rest_field( 'user', $user_meta, array( 'get_callback' => 'user_meta_callback', 'update_callback' => 'user_meta_update_callback', 'schema' => null, ) ); } } function user_meta_callback( $user, $field_name, $request) { return get_user_meta( $user[ 'id' ], $field_name, true ); } function user_meta_update_callback( $user, $field_name, $request) { update_user_meta( $user[ 'id' ], $field_name, XXXX ); } ``` function `user_meta_update_callback` is my attempt to make those custom meta editable. What should I put in `user_meta_update_callback` in place of the XXXX? Am I doing right?
arguments `get_callback` and `update_callback` receive different arguments. try this exemple which works for a field `user_continent` ``` add_action("rest_api_init", function () { register_rest_field( "user" , "user_continent" , [ "get_callback" => function ($user, $field_name, $request, $object_type) { return get_user_meta($user["id"], $field_name, TRUE); }, "update_callback" => function ($value, $user, $field_name, $request, $object_type) { update_user_meta($user->ID, $field_name, $value); }, ] ); }); ```
293,033
<p>I'm a complete noob but trying to learn, and I'm stumped.</p> <p>I have a login page as my static homepage, and want to make an if statement, so that if the user is logged in, and goes to the static home page, they are redirected to another page with content.</p> <p>So far, this is what I have, but it doesn't work:</p> <pre><code>if ( is_user_logged_in() &amp;&amp; is_page( home_url ) ) { wp_redirect('http://example.com/') ; } </code></pre> <p>Can you please not only give me an answer, but a little explanation for me to figure out how I went wrong?</p> <p>Thanks to anyone that can help.</p>
[ { "answer_id": 293034, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>First of all, <code>home_url</code> doesn't provide anything. You should use the <a href=\"https://codex.wordpress.org/Function_Reference/is_home\" rel=\"nofollow noreferrer\"><code>is_home()</code></a> \nfunction instead.</p>\n\n<p>After that, you need to exit the script when you are trying to redirect. So, your full code should be like this:</p>\n\n<pre><code>if ( is_user_logged_in() &amp;&amp; is_home() ) {\n wp_redirect('http://example.com/') ;\n exit();\n}\n</code></pre>\n\n<p>You should also hook into the right action hook. The proper hook to use for redirection is the <code>template_redirect</code>:</p>\n\n<pre><code>add_action ( 'template_redirect', 'redirect_my_homepage' );\nfunction redirect_my_homepage(){\n if ( is_user_logged_in() &amp;&amp; is_home() ) {\n wp_redirect('http://example.com/') ;\n exit();\n }\n}\n</code></pre>\n" }, { "answer_id": 293046, "author": "Marcelo Henriques Cortez", "author_id": 44437, "author_profile": "https://wordpress.stackexchange.com/users/44437", "pm_score": 0, "selected": false, "text": "<p>Well, you need to check fi the user is logged with 'is_user_logged_in()'.\n<a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow noreferrer\">Check the Code Reference</a></p>\n\n<p>After that, you need to check if the user is viewing the front page with 'is_front_page()'.\n<a href=\"https://developer.wordpress.org/reference/functions/is_front_page/\" rel=\"nofollow noreferrer\">Check the Code Reference</a></p>\n\n<p>After that, you need to redirect with 'wp_redirect()'.\n<a href=\"https://developer.wordpress.org/reference/functions/wp_redirect/\" rel=\"nofollow noreferrer\">Check the Code Reference</a></p>\n\n<p>And last, but not least, you need to 'exit', as it is shown on 'wp_redirect()'.</p>\n\n<p>So, your final code should look like:</p>\n\n<pre><code>if ( is_user_logged_in() &amp;&amp; is_front_page() ) {\n wp_redirect('http://yoursite.com/another-page') ;\n exit;\n}\n</code></pre>\n\n<p>you can use 'exit' or 'die', as they are kinda the same, but you must not forget to use one of them.</p>\n" } ]
2018/02/03
[ "https://wordpress.stackexchange.com/questions/293033", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136139/" ]
I'm a complete noob but trying to learn, and I'm stumped. I have a login page as my static homepage, and want to make an if statement, so that if the user is logged in, and goes to the static home page, they are redirected to another page with content. So far, this is what I have, but it doesn't work: ``` if ( is_user_logged_in() && is_page( home_url ) ) { wp_redirect('http://example.com/') ; } ``` Can you please not only give me an answer, but a little explanation for me to figure out how I went wrong? Thanks to anyone that can help.
First of all, `home_url` doesn't provide anything. You should use the [`is_home()`](https://codex.wordpress.org/Function_Reference/is_home) function instead. After that, you need to exit the script when you are trying to redirect. So, your full code should be like this: ``` if ( is_user_logged_in() && is_home() ) { wp_redirect('http://example.com/') ; exit(); } ``` You should also hook into the right action hook. The proper hook to use for redirection is the `template_redirect`: ``` add_action ( 'template_redirect', 'redirect_my_homepage' ); function redirect_my_homepage(){ if ( is_user_logged_in() && is_home() ) { wp_redirect('http://example.com/') ; exit(); } } ```
293,067
<p>I have a meta_key value 'গল্প' inside wp_post_meta as shown value: <a href="https://i.stack.imgur.com/pFjV3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pFjV3.png" alt="enter image description here"></a> </p> <p>Now I want to show all post having meta_key value 'গল্প'. Is there any template file to manage this option like tag.php?</p>
[ { "answer_id": 293069, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Template files are the 'responsibility' of the theme you are using. If your theme doesn't contain a template that meets your need, then you can modify one of the theme's templates and change the query to do what you want.</p>\n\n<p>Modifying a theme's files directly is not recommended, as any mods you do will get overwritten on a theme update. So it's best to create a Child Theme, then create a version of the template from the parent theme that you store in the Child Theme's folder. (Copy the parent theme template to the Child Theme folder, and modify that file, not the original theme.)</p>\n\n<p>Then change the name of the copied template, modify the query, save/upload to your site, and create a page that uses that modified template.</p>\n" }, { "answer_id": 293084, "author": "Eduardo Escobar", "author_id": 136130, "author_profile": "https://wordpress.stackexchange.com/users/136130", "pm_score": 1, "selected": false, "text": "<p>You might give it a shot this way:</p>\n\n<pre><code>add_filter( 'template_include', 'check_post_meta_template_include' );\nfunction check_post_meta_template_include( $template ) {\n if ( !is_single() ) {\n return $template;\n }\n global $post;\n if ( $post-&gt;post_type != 'post' ) { // Proceed only if post type = post\n return $template;\n }\n $category_meta = get_post_meta( $post-&gt;ID, 'Category', true );\n if ( $category_meta != 'গল্প' ) {\n return $template;\n }\n // Use locate_template() here.\n}\n</code></pre>\n\n<p>Reference: <a href=\"https://codex.wordpress.org/Function_Reference/locate_template\" rel=\"nofollow noreferrer\">locate_template</a> </p>\n" } ]
2018/02/03
[ "https://wordpress.stackexchange.com/questions/293067", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120824/" ]
I have a meta\_key value 'গল্প' inside wp\_post\_meta as shown value: [![enter image description here](https://i.stack.imgur.com/pFjV3.png)](https://i.stack.imgur.com/pFjV3.png) Now I want to show all post having meta\_key value 'গল্প'. Is there any template file to manage this option like tag.php?
You might give it a shot this way: ``` add_filter( 'template_include', 'check_post_meta_template_include' ); function check_post_meta_template_include( $template ) { if ( !is_single() ) { return $template; } global $post; if ( $post->post_type != 'post' ) { // Proceed only if post type = post return $template; } $category_meta = get_post_meta( $post->ID, 'Category', true ); if ( $category_meta != 'গল্প' ) { return $template; } // Use locate_template() here. } ``` Reference: [locate\_template](https://codex.wordpress.org/Function_Reference/locate_template)
293,148
<p>We're configuring a new WordPress to use custom post types, and we want our editors to log in and only see only the custominzed post types, not the default 'post' post type. We've been able to remove 'post' from the Admin menu using <a href="https://www.techjunkie.com/remove-default-post-type-from-admin-menu-wordpress/" rel="noreferrer">this trick</a>, but that still leaves the "+ New" Admin toolbar button, which contains a post option and defaults to creating a post. Is there an easy and safe way to remove post from the <em>new</em> toolbar button and/or hide the <em>new</em> toolbar button?</p>
[ { "answer_id": 293203, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 5, "selected": true, "text": "<p>You need to hook to 3 different action hooks to fully hide the default post type. However, a direct access to the default post by URL is still possible. So, let's get started.</p>\n<h2>The Side Menu</h2>\n<pre><code>add_action( 'admin_menu', 'remove_default_post_type' );\n\nfunction remove_default_post_type() {\n remove_menu_page( 'edit.php' );\n}\n</code></pre>\n<h2>The + New &gt; Post link in Admin Bar</h2>\n<pre><code>add_action( 'admin_bar_menu', 'remove_default_post_type_menu_bar', 999 );\n\nfunction remove_default_post_type_menu_bar( $wp_admin_bar ) {\n $wp_admin_bar-&gt;remove_node( 'new-post' );\n}\n</code></pre>\n<h2>The + New link in Admin Bar</h2>\n<pre><code>function remove_add_new_post_href_in_admin_bar() {\n ?&gt;\n &lt;script type=&quot;text/javascript&quot;&gt;\n function remove_add_new_post_href_in_admin_bar() {\n var add_new = document.getElementById('wp-admin-bar-new-content');\n if(!add_new) return;\n var add_new_a = add_new.getElementsByTagName('a')[0];\n if(add_new_a) add_new_a.setAttribute('href','#!');\n }\n remove_add_new_post_href_in_admin_bar();\n &lt;/script&gt;\n &lt;?php\n}\nadd_action( 'admin_footer', 'remove_add_new_post_href_in_admin_bar' );\n\n\nfunction remove_frontend_post_href(){\n if( is_user_logged_in() ) {\n add_action( 'wp_footer', 'remove_add_new_post_href_in_admin_bar' );\n }\n}\nadd_action( 'init', 'remove_frontend_post_href' );\n</code></pre>\n<h2>The Quick Draft Dashboard Widget</h2>\n<pre><code>add_action( 'wp_dashboard_setup', 'remove_draft_widget', 999 );\n\nfunction remove_draft_widget(){\n remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' );\n}\n</code></pre>\n" }, { "answer_id": 293207, "author": "Stefan", "author_id": 135965, "author_profile": "https://wordpress.stackexchange.com/users/135965", "pm_score": 2, "selected": false, "text": "<p>In principle it is possible to unregister already registered post types using <code>unregister_post_type()</code>. Unfortunately this is not possible for <code>_builtin</code> post types.</p>\n\n<p>Alternatively it is possible to change the capabilities which are required to edit/create/delete/... posts for a specific post type. You could use the <code>register_post_type_args</code> filter to change the capabilities which are required for the default <code>post</code> post type. Setting all capabilities to <code>false</code> will result in nobody having access to the default post post type. WordPress is smart enough to automatically hide the navigation entries.</p>\n\n<pre><code>add_filter('register_post_type_args', function($args, $postType){\n if ($postType === 'post') {\n $args['capabilities'] = [\n 'edit_post' =&gt; false,\n 'read_post' =&gt; false,\n 'delete_post' =&gt; false,\n 'edit_posts' =&gt; false,\n 'edit_others_posts' =&gt; false,\n 'publish_posts' =&gt; false,\n 'read' =&gt; false,\n 'delete_posts' =&gt; false,\n 'delete_private_posts' =&gt; false,\n 'delete_published_posts' =&gt; false,\n 'delete_others_posts' =&gt; false,\n 'edit_private_posts' =&gt; false,\n 'edit_published_posts' =&gt; false,\n 'create_posts' =&gt; false,\n ];\n }\n\n return $args\n}, 0, 2);\n</code></pre>\n" }, { "answer_id": 331938, "author": "rafa226", "author_id": 127863, "author_profile": "https://wordpress.stackexchange.com/users/127863", "pm_score": 0, "selected": false, "text": "<p>Stefan's solution is great, but if you active debug you can see :\nUndefined offset: 0 in wp-includes/capabilities.php on line 62\nplus there is a missing ; after return $args</p>\n\n<p>Exhaustive code should be :</p>\n\n<pre><code>add_filter('register_post_type_args', function($args, $postType){\n if ($postType === 'post' &amp;&amp; current_user_can( 'create_posts' ) &amp;&amp; current_user_can( 'edit_post' ) ) {\n $args['capabilities'] = [\n 'edit_post' =&gt; false,\n 'read_post' =&gt; false,\n 'delete_post' =&gt; false,\n 'edit_posts' =&gt; false,\n 'edit_others_posts' =&gt; false,\n 'publish_posts' =&gt; false,\n 'read' =&gt; false,\n 'delete_posts' =&gt; false,\n 'delete_private_posts' =&gt; false,\n 'delete_published_posts' =&gt; false,\n 'delete_others_posts' =&gt; false,\n 'edit_private_posts' =&gt; false,\n 'edit_published_posts' =&gt; false,\n 'create_posts' =&gt; false,\n ];\n }\n return $args;\n}, 0, 2);\n</code></pre>\n" }, { "answer_id": 355679, "author": "vtq", "author_id": 180561, "author_profile": "https://wordpress.stackexchange.com/users/180561", "pm_score": 3, "selected": false, "text": "<p>An alternative, but similar solution to Stefan and Rafa's. This does not throw errors, and notice if you navigate directly to /wp-admin/edit.php you will not be able to view the list of posts (default post type), or edit them.</p>\n\n<p>Note this code does not actually disable the default post type, i.e. existing post types will still be published and accessible via public URL. It effectively disables backend access to the default post type for all users.</p>\n\n<pre><code>function remove_default_post_type($args, $postType) {\n if ($postType === 'post') {\n $args['public'] = false;\n $args['show_ui'] = false;\n $args['show_in_menu'] = false;\n $args['show_in_admin_bar'] = false;\n $args['show_in_nav_menus'] = false;\n $args['can_export'] = false;\n $args['has_archive'] = false;\n $args['exclude_from_search'] = true;\n $args['publicly_queryable'] = false;\n $args['show_in_rest'] = false;\n }\n\n return $args;\n}\nadd_filter('register_post_type_args', 'remove_default_post_type', 0, 2);\n</code></pre>\n" } ]
2018/02/05
[ "https://wordpress.stackexchange.com/questions/293148", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136220/" ]
We're configuring a new WordPress to use custom post types, and we want our editors to log in and only see only the custominzed post types, not the default 'post' post type. We've been able to remove 'post' from the Admin menu using [this trick](https://www.techjunkie.com/remove-default-post-type-from-admin-menu-wordpress/), but that still leaves the "+ New" Admin toolbar button, which contains a post option and defaults to creating a post. Is there an easy and safe way to remove post from the *new* toolbar button and/or hide the *new* toolbar button?
You need to hook to 3 different action hooks to fully hide the default post type. However, a direct access to the default post by URL is still possible. So, let's get started. The Side Menu ------------- ``` add_action( 'admin_menu', 'remove_default_post_type' ); function remove_default_post_type() { remove_menu_page( 'edit.php' ); } ``` The + New > Post link in Admin Bar ---------------------------------- ``` add_action( 'admin_bar_menu', 'remove_default_post_type_menu_bar', 999 ); function remove_default_post_type_menu_bar( $wp_admin_bar ) { $wp_admin_bar->remove_node( 'new-post' ); } ``` The + New link in Admin Bar --------------------------- ``` function remove_add_new_post_href_in_admin_bar() { ?> <script type="text/javascript"> function remove_add_new_post_href_in_admin_bar() { var add_new = document.getElementById('wp-admin-bar-new-content'); if(!add_new) return; var add_new_a = add_new.getElementsByTagName('a')[0]; if(add_new_a) add_new_a.setAttribute('href','#!'); } remove_add_new_post_href_in_admin_bar(); </script> <?php } add_action( 'admin_footer', 'remove_add_new_post_href_in_admin_bar' ); function remove_frontend_post_href(){ if( is_user_logged_in() ) { add_action( 'wp_footer', 'remove_add_new_post_href_in_admin_bar' ); } } add_action( 'init', 'remove_frontend_post_href' ); ``` The Quick Draft Dashboard Widget -------------------------------- ``` add_action( 'wp_dashboard_setup', 'remove_draft_widget', 999 ); function remove_draft_widget(){ remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' ); } ```
293,149
<p>I'm still new to WordPress. I have been encountering <code>Failed to load resource: the server responded with a status of 404 (Not Found)</code> error and its pointing it in <code>wp-admin/admin-ajax.php</code>. I have check the folder and <code>admin-ajax.php</code> is there. I also tried calling <code>admin-ajax.php</code> using <code>network_admin_url()</code> instead of <code>admin_url()</code>. But I still keeps on having that error. Is there anyway to solve it? Thank you very much for your help.</p> <p>Here is the sample code </p> <pre><code>var ajaxurl = '&lt;?php echo admin_url('admin-ajax.php'); ?&gt;'; $.ajax({ type: "POST", url: ajaxurl, cache: false, data: { action: 'getInfo' }, success: function(data) { mIDs= mDisplay(data); } }).done(function( msg ) { }); </code></pre>
[ { "answer_id": 293151, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<p>finally the problem was that the hosting provider had blocked the admin-ajax.php file saying that this file was receiving too many request, and requests to this file bypasses cache , hence it was causing problems on server :)</p>\n" }, { "answer_id": 293153, "author": "Venkat", "author_id": 131006, "author_profile": "https://wordpress.stackexchange.com/users/131006", "pm_score": 0, "selected": false, "text": "<p>I assume you're writing javascript with in php file.</p>\n\n<p><code>var ajaxurl = '&lt;?php echo admin_url('admin-ajax.php'); ?&gt;';</code>\nYou're going to save the return value in <code>ajaxurl</code> variable, so you shouldn't <code>echo</code> it.</p>\n\n<p>For external js files, you have to use <code>wp_localize_script</code> to pass ajaxurl to js file</p>\n" }, { "answer_id": 293170, "author": "natsumiyu", "author_id": 136230, "author_profile": "https://wordpress.stackexchange.com/users/136230", "pm_score": 3, "selected": true, "text": "<p>I contact the hosting provider regarding it. They advise me to fix the .htaccess which causing the error. </p>\n" } ]
2018/02/05
[ "https://wordpress.stackexchange.com/questions/293149", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136230/" ]
I'm still new to WordPress. I have been encountering `Failed to load resource: the server responded with a status of 404 (Not Found)` error and its pointing it in `wp-admin/admin-ajax.php`. I have check the folder and `admin-ajax.php` is there. I also tried calling `admin-ajax.php` using `network_admin_url()` instead of `admin_url()`. But I still keeps on having that error. Is there anyway to solve it? Thank you very much for your help. Here is the sample code ``` var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; $.ajax({ type: "POST", url: ajaxurl, cache: false, data: { action: 'getInfo' }, success: function(data) { mIDs= mDisplay(data); } }).done(function( msg ) { }); ```
I contact the hosting provider regarding it. They advise me to fix the .htaccess which causing the error.
293,158
<p>Trying to fetch all data from <code>wp_postmeta</code> table. I am trying to fetch first <code>meta_key</code> column value. so I am running this query. When I am using <code>print_r</code> then all data showing but when I am using foreach loop then its not working.</p> <pre><code>&lt;?php global $wpdb; $myrows = $wpdb-&gt;get_results( "SELECT * FROM wp_postmeta" ); foreach($myrows as $value){ echo $value-&gt;sleeps; } </code></pre>
[ { "answer_id": 293151, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<p>finally the problem was that the hosting provider had blocked the admin-ajax.php file saying that this file was receiving too many request, and requests to this file bypasses cache , hence it was causing problems on server :)</p>\n" }, { "answer_id": 293153, "author": "Venkat", "author_id": 131006, "author_profile": "https://wordpress.stackexchange.com/users/131006", "pm_score": 0, "selected": false, "text": "<p>I assume you're writing javascript with in php file.</p>\n\n<p><code>var ajaxurl = '&lt;?php echo admin_url('admin-ajax.php'); ?&gt;';</code>\nYou're going to save the return value in <code>ajaxurl</code> variable, so you shouldn't <code>echo</code> it.</p>\n\n<p>For external js files, you have to use <code>wp_localize_script</code> to pass ajaxurl to js file</p>\n" }, { "answer_id": 293170, "author": "natsumiyu", "author_id": 136230, "author_profile": "https://wordpress.stackexchange.com/users/136230", "pm_score": 3, "selected": true, "text": "<p>I contact the hosting provider regarding it. They advise me to fix the .htaccess which causing the error. </p>\n" } ]
2018/02/05
[ "https://wordpress.stackexchange.com/questions/293158", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103961/" ]
Trying to fetch all data from `wp_postmeta` table. I am trying to fetch first `meta_key` column value. so I am running this query. When I am using `print_r` then all data showing but when I am using foreach loop then its not working. ``` <?php global $wpdb; $myrows = $wpdb->get_results( "SELECT * FROM wp_postmeta" ); foreach($myrows as $value){ echo $value->sleeps; } ```
I contact the hosting provider regarding it. They advise me to fix the .htaccess which causing the error.
293,189
<p>Is it possible to have different favicon on on different pages?</p> <p><strong>For example:</strong></p> <pre><code>mywebsite.com/blog-1 -&gt; favicon-1 mywebsite.com/blog -&gt; favicon-2 </code></pre> <p>And so on.</p> <p>I have custom domain name for each blog (And I don't want to put the same favicon on these pages)</p>
[ { "answer_id": 293196, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 0, "selected": false, "text": "<p>You can use a few solutions;</p>\n\n<ol>\n<li>Create meta-field with favicon in your page/post. And call this in your <code>header.php</code> file. But dont forget set default value, if meta-field will be empty.</li>\n<li>Wrap this meta tags in <code>apply_filter</code> and create filters for this.</li>\n<li>Use conditionals like <code>is_page()</code>, <code>is_singular('product')</code> etc..</li>\n<li>Remove meta tags from <code>header.php</code> and use <code>add_action('wp_head', 'your_functions_tags');</code></li>\n<li>Create <code>header-{slug}.php</code>. <code>header-fav1.php, header-fav2.php</code> and call in your template like <code>&lt;?php get_header('fav1'); ?&gt;</code></li>\n</ol>\n\n<p>Something for this list must help you.</p>\n" }, { "answer_id": 341538, "author": "ChristopherJones", "author_id": 168744, "author_profile": "https://wordpress.stackexchange.com/users/168744", "pm_score": 0, "selected": false, "text": "<p>This might be overkill, but if you are looking to swap out favicons for specific pages, post archives, or even single posts, here is something that should get you there. Hopefully it's clean enough to maintain. And you can drop in whatever sort of is_ conditional WordPress has to offer.</p>\n\n<pre><code> &lt;?php\n switch(true){\n case is_page(27) :\n $favicon_link = 'link_to_favicon_one.png';\n break;\n case is_page(array(23, 40, 44, 60)) :\n $favicon_link = 'link_to_favicon_two.png';\n break;\n case is_post_type_archive() :\n $favicon_link = 'link_to_favicon_three.png';\n break;\n case is_single(2001) :\n $favicon_link = 'link_to_favicon_four.png';\n break;\n default : // Always need a fallback\n $favicon_link = 'link_to_favicon.png';\n break;\n }\n?&gt;\n\n&lt;link rel=\"icon\" href=\"&lt;?=$favicon_link?&gt;\" sizes=\"32x32\" /&gt; \n</code></pre>\n\n<p>Hope this helps someone!</p>\n" }, { "answer_id": 381389, "author": "Sam Jacob Dev", "author_id": 34528, "author_profile": "https://wordpress.stackexchange.com/users/34528", "pm_score": 1, "selected": false, "text": "<p>As of WordPress version 5.6, any posts or pages has options on the editor to include any custom scripts/styles and meta tags to the header of the page. So if you put your &lt;link rel&quot;icon&quot; href=&quot;favicon.png&quot;/&gt; it should work.</p>\n<p>You upload your favicon into the media and after you uploaded the media. Refer the uploaded favicon png image reference directly to the link.</p>\n<p>Example of favicon in header block</p>\n<pre><code>&lt;link rel=&quot;icon&quot; href=&quot;https://domainname.com/uploads/2020/10/10/favicon-32x32.png&quot; /&gt;\n</code></pre>\n" } ]
2018/02/05
[ "https://wordpress.stackexchange.com/questions/293189", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136250/" ]
Is it possible to have different favicon on on different pages? **For example:** ``` mywebsite.com/blog-1 -> favicon-1 mywebsite.com/blog -> favicon-2 ``` And so on. I have custom domain name for each blog (And I don't want to put the same favicon on these pages)
As of WordPress version 5.6, any posts or pages has options on the editor to include any custom scripts/styles and meta tags to the header of the page. So if you put your <link rel"icon" href="favicon.png"/> it should work. You upload your favicon into the media and after you uploaded the media. Refer the uploaded favicon png image reference directly to the link. Example of favicon in header block ``` <link rel="icon" href="https://domainname.com/uploads/2020/10/10/favicon-32x32.png" /> ```
293,215
<p>I hesitated to ask this question, because it may be too fundamental. However, after digging in to the codex and other topics I became convinced that maybe it is not so fundamental because I could not find an answer to my question.</p> <p>My question is what purpose does the handle serve in functions like wp_enqueue_script() and wp_enqueue_style()? The codex explains that it is the name of the script or stylesheet, though clearly this does not need to be the name of the file that holds the script or style. I assume that it needs to be unique and I assume that it can be accessed via </p> <pre><code>global $wp_scripts; </code></pre> <p>The fact that the handle is explicitly defined suggests that it must have a clear purpose or be re-usable somehow. Otherwise, we would only need to load the script or stylesheet and it would work without the need for a handle. I would appreciate any insights into this.</p>
[ { "answer_id": 293217, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 3, "selected": true, "text": "<p>Below is an example of the <code>jquery</code> handle being used in various ways:</p>\n\n<pre><code>// add my js, written in jQuery\n// so it requires `jquery.min.js` to be output first\n// &amp; say I do this in a early hook like `init`\nwp_enqueue_script( 'my-js', 'js.js', array('jquery'));\n\n// later in theme:\n\n// remove Wordpress's default jquery,\n// change jquery to a specified version, and put in footer\n// &amp; say I do this in a later hook like `wp_loaded`\nwp_deregister_script( 'jquery' );\nwp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1', true );\nwp_enqueue_script( 'jquery' );\n</code></pre>\n\n<ul>\n<li><p>Even though I've enqued <code>my-js</code> first, I'm able to change and modify <code>jquery</code></p></li>\n<li><p>I'm able to easily change which <code>jquery</code> version and source I'm using, with ease</p></li>\n<li><p>I have a simple straightforward, pseudocode method to <a href=\"https://codex.wordpress.org/Function_Reference/wp_dequeue_script\" rel=\"nofollow noreferrer\">remove a script</a> that I don't want</p></li>\n<li><p>I changed <code>jquery</code>'s script, in a big way, but other plugins that rely on <code>jquery</code> will still get jQuery <em>(though the versions might be off, but not important right now)</em></p></li>\n<li><p>My <code>my-js</code> was done early and is default to be in <code>wp_head</code>. later, I changed <code>jquery</code> to be placed to the footer (import for speed preformace (re: Google PageSpeed). Since <code>my-js</code> depends on <code>jquery</code>, it gets moved down to the footer as well</p></li>\n</ul>\n\n<p>When you're dealing with multiple plugin and theme authors, who want to change and modify things, like jQuery, without knowing the dynamic URLs or what other theme/plugin has touched the <code>jquery</code> script -- doing anything like this without an handle would be an absolute nightmare.</p>\n" }, { "answer_id": 397274, "author": "Stefano", "author_id": 212922, "author_profile": "https://wordpress.stackexchange.com/users/212922", "pm_score": 0, "selected": false, "text": "<p>I was also confused about the function of the handle in wp_enqueue_style() and the previous answer was overcomplex. As far as I understand it, the handle is a name or an identifier you give to the script to be able to recall it or to refer to it.</p>\n<p>In the <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/#description\" rel=\"nofollow noreferrer\">description</a> of wp_enqueue_style() we can read: &quot;Registers the script if $src provided (does NOT overwrite), and enqueues it.&quot;</p>\n<p>But we could also have registered it before with <a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\">wp_register_script()</a>, which &quot;registers a script to be enqueued later using the wp_enqueue_script() function.&quot;. Also for this reason in wp_enqueue_style() the second argumet 'src' is optional.</p>\n<p>If we have a style.css file in our theme folder we must register it through wp_register_script() or wp_enqueue_style() and give it a (unique) name/identifier, to be able to use and access it.</p>\n" }, { "answer_id": 406783, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 0, "selected": false, "text": "<p>One of the key reasons for creating a handle for your styles and scripts, using wp_enqueue_style and wp_enqueue_script, is that this provides a unique name for the style or script that can be used to reference it with other functions.</p>\n<p>As an example consider using a style in a plugin that should only be initiated on certain pages:</p>\n<p>First register the style with a unique handle (my-report-style in this case)</p>\n<pre><code>function register_my_report_styles() {\n wp_register_style('my-report-style', plugins_url('css/my-style.css', __FILE__));\n}\nadd_action( 'init', 'register_my_report_styles' );\n</code></pre>\n<p>Having defined the handle, we can reference it directly in other functions. In this case, we want the style to load only on a particular page (e.g. our annual_report page) so we can enqueue the style only for this page using:</p>\n<pre><code>function enqueue_report_styles() {\n if ( is_page(array('annual_report')) ) {\n wp_enqueue_style( 'my-report-style' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'enqueue_report_styles' );\n</code></pre>\n<p>Continuing the example, suppose you now want to add an inline style to the already enqueued stylesheet (e.g. transform all h1 tags on this page to uppercase). You can do this as follows:</p>\n<pre><code>function update_report_styles() {\n $css = 'h1 {text-transform: uppercase;}';\n wp_add_inline_style('my-report-style', $css);\n}\nadd_action('wp_enqueue_scripts', 'my_theme_inline_css');\n</code></pre>\n<p>Notice that again, we referred to the already enqueued stylesheet only by the handle that we gave to the stylesheet when we registered it.</p>\n" } ]
2018/02/05
[ "https://wordpress.stackexchange.com/questions/293215", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129826/" ]
I hesitated to ask this question, because it may be too fundamental. However, after digging in to the codex and other topics I became convinced that maybe it is not so fundamental because I could not find an answer to my question. My question is what purpose does the handle serve in functions like wp\_enqueue\_script() and wp\_enqueue\_style()? The codex explains that it is the name of the script or stylesheet, though clearly this does not need to be the name of the file that holds the script or style. I assume that it needs to be unique and I assume that it can be accessed via ``` global $wp_scripts; ``` The fact that the handle is explicitly defined suggests that it must have a clear purpose or be re-usable somehow. Otherwise, we would only need to load the script or stylesheet and it would work without the need for a handle. I would appreciate any insights into this.
Below is an example of the `jquery` handle being used in various ways: ``` // add my js, written in jQuery // so it requires `jquery.min.js` to be output first // & say I do this in a early hook like `init` wp_enqueue_script( 'my-js', 'js.js', array('jquery')); // later in theme: // remove Wordpress's default jquery, // change jquery to a specified version, and put in footer // & say I do this in a later hook like `wp_loaded` wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1', true ); wp_enqueue_script( 'jquery' ); ``` * Even though I've enqued `my-js` first, I'm able to change and modify `jquery` * I'm able to easily change which `jquery` version and source I'm using, with ease * I have a simple straightforward, pseudocode method to [remove a script](https://codex.wordpress.org/Function_Reference/wp_dequeue_script) that I don't want * I changed `jquery`'s script, in a big way, but other plugins that rely on `jquery` will still get jQuery *(though the versions might be off, but not important right now)* * My `my-js` was done early and is default to be in `wp_head`. later, I changed `jquery` to be placed to the footer (import for speed preformace (re: Google PageSpeed). Since `my-js` depends on `jquery`, it gets moved down to the footer as well When you're dealing with multiple plugin and theme authors, who want to change and modify things, like jQuery, without knowing the dynamic URLs or what other theme/plugin has touched the `jquery` script -- doing anything like this without an handle would be an absolute nightmare.
293,300
<p>Hi my java script code doesn't work in my <code>wordpress</code> theme i enqueue my <code>scripts.js</code> file what is the problem and what is the expected behaviour? </p> <pre><code> function my_scripts() { wp_enqueue_style( 'responsive', get_template_directory_uri() .'/assets/css/responsive.css' , array() ); wp_enqueue_script( 'scripts', get_template_directory_uri() . '/assets/js/scripts.js', array(), true ); } add_action( 'wp_enqueue_scripts', 'my_scripts' ); </code></pre> <p><code>scripts.js</code> file:</p> <pre><code>jQuery(document).ready(function($){ /*------ Masonry ------*/ $(".post-four.grid .row").masonry({ itemSelector: ".post", horizontalOrder: true }); /*------ Search button ------*/ let hasFocus = false; $(".header-top .header-search .searchform i").click(function() { const setState = hasFocus ? 'blur' : 'focus'; $('.header-top .header-search .searchform #s')[setState](); hasFocus = !hasFocus; }); let hasFocusTwo = false; $(".header-sticky-inner .header-search i").click(function() { const setStateTwo = hasFocusTwo ? 'blur' : 'focus'; $('.header-sticky-inner .header-search #input-search')[setStateTwo](); hasFocusTwo = !hasFocusTwo; }); /*------ Sidebar ------*/ $(".sidebar-button #sidebarButton").click(function(){ $("body").addClass("sidebar-active"); }); $(".sidebar-right #closebtn").click(function(){ $("body").removeClass("sidebar-active"); }); $("#content-bg").click(function(){ $("body").removeClass("sidebar-active"); }); $(".sidebar-button-menu #sidebarButton").click(function(){ $("body").addClass("sidebar-active-menu"); }); $(".sidebar-menu #closebtn").click(function(){ $("body").removeClass("sidebar-active-menu"); }); $("#content-bg").click(function(){ $("body").removeClass("sidebar-active-menu"); }); /*------ Drop Down Menu ------*/ let dropdown = $(".has-child a"); let i; for (i = 0; i &lt; dropdown.length; i++) { dropdown[i].addEventListener("click", function() { this.classList.toggle("active"); let dropdownContent = this.nextElementSibling; if (dropdownContent.style.display === "block") { dropdownContent.style.display = "none"; } else { dropdownContent.style.display = "block"; } }); } /*------ Grid Tab ------*/ $('.grid-tab &gt; li &gt; a').on('click', function(e) { e.preventDefault(); $(this).closest('.grid-tab &gt; li').toggleClass('active-li') .siblings('.grid-tab &gt; li').removeClass('active-li'); }); /*------ Scroll ------*/ let previousScroll = 0; let memoScroll = $("header").height() - $(".header-sticky").height(); $(window).scroll(function(event){ let scrolled = $(window).scrollTop(); if (scrolled &gt; memoScroll){ if (scrolled &lt; previousScroll){ $(".header-sticky").addClass("visible"); } else { $(".header-sticky").removeClass("visible"); } }else { $(".header-sticky").removeClass("visible"); } previousScroll = scrolled; }); }); /*------ OWL Carousel ------*/ $(".owl-instagram, .owl-category, .owl-post-wg").owlCarousel({ items:1, dots:true }); $(".sidebar-right .owl-instagram,.sidebar-right .owl-category,.sidebar-right .owl-post-wg").owlCarousel({ items:1, dots:true }); $(".owl-instagram-feed").owlCarousel({ items:5, dots:false, nav: true, navText: ['&lt;i class="ion-android-arrow-back"&gt;&lt;/i&gt;','&lt;i class="ion-android-arrow-forward"&gt;&lt;/i&gt;'], loop: true, responsiveClass: true, responsive: { 0:{ items:2 }, 576:{ items:3 }, 768:{ items:4 }, 992:{ } } }); $(".owl-slider").owlCarousel({ items: 1, loop: true, nav: true, navText: ['&lt;i class="ion-android-arrow-back"&gt;&lt;/i&gt;','&lt;i class="ion-android-arrow-forward"&gt;&lt;/i&gt;'], dots: true, mouseDrag: false }); $(".owl-slider-center").owlCarousel({ items: 2, center: true, margin: 10, loop: true, nav: true, navText: ['&lt;i class="ion-android-arrow-back"&gt;&lt;/i&gt;','&lt;i class="ion-android-arrow-forward"&gt;&lt;/i&gt;'], dots: false, mouseDrag: true, removeClass: true, responsive:{ 0:{ center:false, items:1 }, 576:{ items:1, center:false }, 768:{ items:1, center:false }, 992:{ } } }); </code></pre>
[ { "answer_id": 293217, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 3, "selected": true, "text": "<p>Below is an example of the <code>jquery</code> handle being used in various ways:</p>\n\n<pre><code>// add my js, written in jQuery\n// so it requires `jquery.min.js` to be output first\n// &amp; say I do this in a early hook like `init`\nwp_enqueue_script( 'my-js', 'js.js', array('jquery'));\n\n// later in theme:\n\n// remove Wordpress's default jquery,\n// change jquery to a specified version, and put in footer\n// &amp; say I do this in a later hook like `wp_loaded`\nwp_deregister_script( 'jquery' );\nwp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1', true );\nwp_enqueue_script( 'jquery' );\n</code></pre>\n\n<ul>\n<li><p>Even though I've enqued <code>my-js</code> first, I'm able to change and modify <code>jquery</code></p></li>\n<li><p>I'm able to easily change which <code>jquery</code> version and source I'm using, with ease</p></li>\n<li><p>I have a simple straightforward, pseudocode method to <a href=\"https://codex.wordpress.org/Function_Reference/wp_dequeue_script\" rel=\"nofollow noreferrer\">remove a script</a> that I don't want</p></li>\n<li><p>I changed <code>jquery</code>'s script, in a big way, but other plugins that rely on <code>jquery</code> will still get jQuery <em>(though the versions might be off, but not important right now)</em></p></li>\n<li><p>My <code>my-js</code> was done early and is default to be in <code>wp_head</code>. later, I changed <code>jquery</code> to be placed to the footer (import for speed preformace (re: Google PageSpeed). Since <code>my-js</code> depends on <code>jquery</code>, it gets moved down to the footer as well</p></li>\n</ul>\n\n<p>When you're dealing with multiple plugin and theme authors, who want to change and modify things, like jQuery, without knowing the dynamic URLs or what other theme/plugin has touched the <code>jquery</code> script -- doing anything like this without an handle would be an absolute nightmare.</p>\n" }, { "answer_id": 397274, "author": "Stefano", "author_id": 212922, "author_profile": "https://wordpress.stackexchange.com/users/212922", "pm_score": 0, "selected": false, "text": "<p>I was also confused about the function of the handle in wp_enqueue_style() and the previous answer was overcomplex. As far as I understand it, the handle is a name or an identifier you give to the script to be able to recall it or to refer to it.</p>\n<p>In the <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/#description\" rel=\"nofollow noreferrer\">description</a> of wp_enqueue_style() we can read: &quot;Registers the script if $src provided (does NOT overwrite), and enqueues it.&quot;</p>\n<p>But we could also have registered it before with <a href=\"https://developer.wordpress.org/reference/functions/wp_register_script/\" rel=\"nofollow noreferrer\">wp_register_script()</a>, which &quot;registers a script to be enqueued later using the wp_enqueue_script() function.&quot;. Also for this reason in wp_enqueue_style() the second argumet 'src' is optional.</p>\n<p>If we have a style.css file in our theme folder we must register it through wp_register_script() or wp_enqueue_style() and give it a (unique) name/identifier, to be able to use and access it.</p>\n" }, { "answer_id": 406783, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 0, "selected": false, "text": "<p>One of the key reasons for creating a handle for your styles and scripts, using wp_enqueue_style and wp_enqueue_script, is that this provides a unique name for the style or script that can be used to reference it with other functions.</p>\n<p>As an example consider using a style in a plugin that should only be initiated on certain pages:</p>\n<p>First register the style with a unique handle (my-report-style in this case)</p>\n<pre><code>function register_my_report_styles() {\n wp_register_style('my-report-style', plugins_url('css/my-style.css', __FILE__));\n}\nadd_action( 'init', 'register_my_report_styles' );\n</code></pre>\n<p>Having defined the handle, we can reference it directly in other functions. In this case, we want the style to load only on a particular page (e.g. our annual_report page) so we can enqueue the style only for this page using:</p>\n<pre><code>function enqueue_report_styles() {\n if ( is_page(array('annual_report')) ) {\n wp_enqueue_style( 'my-report-style' );\n }\n}\nadd_action( 'wp_enqueue_scripts', 'enqueue_report_styles' );\n</code></pre>\n<p>Continuing the example, suppose you now want to add an inline style to the already enqueued stylesheet (e.g. transform all h1 tags on this page to uppercase). You can do this as follows:</p>\n<pre><code>function update_report_styles() {\n $css = 'h1 {text-transform: uppercase;}';\n wp_add_inline_style('my-report-style', $css);\n}\nadd_action('wp_enqueue_scripts', 'my_theme_inline_css');\n</code></pre>\n<p>Notice that again, we referred to the already enqueued stylesheet only by the handle that we gave to the stylesheet when we registered it.</p>\n" } ]
2018/02/06
[ "https://wordpress.stackexchange.com/questions/293300", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136327/" ]
Hi my java script code doesn't work in my `wordpress` theme i enqueue my `scripts.js` file what is the problem and what is the expected behaviour? ``` function my_scripts() { wp_enqueue_style( 'responsive', get_template_directory_uri() .'/assets/css/responsive.css' , array() ); wp_enqueue_script( 'scripts', get_template_directory_uri() . '/assets/js/scripts.js', array(), true ); } add_action( 'wp_enqueue_scripts', 'my_scripts' ); ``` `scripts.js` file: ``` jQuery(document).ready(function($){ /*------ Masonry ------*/ $(".post-four.grid .row").masonry({ itemSelector: ".post", horizontalOrder: true }); /*------ Search button ------*/ let hasFocus = false; $(".header-top .header-search .searchform i").click(function() { const setState = hasFocus ? 'blur' : 'focus'; $('.header-top .header-search .searchform #s')[setState](); hasFocus = !hasFocus; }); let hasFocusTwo = false; $(".header-sticky-inner .header-search i").click(function() { const setStateTwo = hasFocusTwo ? 'blur' : 'focus'; $('.header-sticky-inner .header-search #input-search')[setStateTwo](); hasFocusTwo = !hasFocusTwo; }); /*------ Sidebar ------*/ $(".sidebar-button #sidebarButton").click(function(){ $("body").addClass("sidebar-active"); }); $(".sidebar-right #closebtn").click(function(){ $("body").removeClass("sidebar-active"); }); $("#content-bg").click(function(){ $("body").removeClass("sidebar-active"); }); $(".sidebar-button-menu #sidebarButton").click(function(){ $("body").addClass("sidebar-active-menu"); }); $(".sidebar-menu #closebtn").click(function(){ $("body").removeClass("sidebar-active-menu"); }); $("#content-bg").click(function(){ $("body").removeClass("sidebar-active-menu"); }); /*------ Drop Down Menu ------*/ let dropdown = $(".has-child a"); let i; for (i = 0; i < dropdown.length; i++) { dropdown[i].addEventListener("click", function() { this.classList.toggle("active"); let dropdownContent = this.nextElementSibling; if (dropdownContent.style.display === "block") { dropdownContent.style.display = "none"; } else { dropdownContent.style.display = "block"; } }); } /*------ Grid Tab ------*/ $('.grid-tab > li > a').on('click', function(e) { e.preventDefault(); $(this).closest('.grid-tab > li').toggleClass('active-li') .siblings('.grid-tab > li').removeClass('active-li'); }); /*------ Scroll ------*/ let previousScroll = 0; let memoScroll = $("header").height() - $(".header-sticky").height(); $(window).scroll(function(event){ let scrolled = $(window).scrollTop(); if (scrolled > memoScroll){ if (scrolled < previousScroll){ $(".header-sticky").addClass("visible"); } else { $(".header-sticky").removeClass("visible"); } }else { $(".header-sticky").removeClass("visible"); } previousScroll = scrolled; }); }); /*------ OWL Carousel ------*/ $(".owl-instagram, .owl-category, .owl-post-wg").owlCarousel({ items:1, dots:true }); $(".sidebar-right .owl-instagram,.sidebar-right .owl-category,.sidebar-right .owl-post-wg").owlCarousel({ items:1, dots:true }); $(".owl-instagram-feed").owlCarousel({ items:5, dots:false, nav: true, navText: ['<i class="ion-android-arrow-back"></i>','<i class="ion-android-arrow-forward"></i>'], loop: true, responsiveClass: true, responsive: { 0:{ items:2 }, 576:{ items:3 }, 768:{ items:4 }, 992:{ } } }); $(".owl-slider").owlCarousel({ items: 1, loop: true, nav: true, navText: ['<i class="ion-android-arrow-back"></i>','<i class="ion-android-arrow-forward"></i>'], dots: true, mouseDrag: false }); $(".owl-slider-center").owlCarousel({ items: 2, center: true, margin: 10, loop: true, nav: true, navText: ['<i class="ion-android-arrow-back"></i>','<i class="ion-android-arrow-forward"></i>'], dots: false, mouseDrag: true, removeClass: true, responsive:{ 0:{ center:false, items:1 }, 576:{ items:1, center:false }, 768:{ items:1, center:false }, 992:{ } } }); ```
Below is an example of the `jquery` handle being used in various ways: ``` // add my js, written in jQuery // so it requires `jquery.min.js` to be output first // & say I do this in a early hook like `init` wp_enqueue_script( 'my-js', 'js.js', array('jquery')); // later in theme: // remove Wordpress's default jquery, // change jquery to a specified version, and put in footer // & say I do this in a later hook like `wp_loaded` wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1', true ); wp_enqueue_script( 'jquery' ); ``` * Even though I've enqued `my-js` first, I'm able to change and modify `jquery` * I'm able to easily change which `jquery` version and source I'm using, with ease * I have a simple straightforward, pseudocode method to [remove a script](https://codex.wordpress.org/Function_Reference/wp_dequeue_script) that I don't want * I changed `jquery`'s script, in a big way, but other plugins that rely on `jquery` will still get jQuery *(though the versions might be off, but not important right now)* * My `my-js` was done early and is default to be in `wp_head`. later, I changed `jquery` to be placed to the footer (import for speed preformace (re: Google PageSpeed). Since `my-js` depends on `jquery`, it gets moved down to the footer as well When you're dealing with multiple plugin and theme authors, who want to change and modify things, like jQuery, without knowing the dynamic URLs or what other theme/plugin has touched the `jquery` script -- doing anything like this without an handle would be an absolute nightmare.
293,308
<p>I have a theme with an option for setting the excerpt length for generated excerpts. Is there a way in the Customizer of conditionally changing the transport mechanism, depending on whether the preview page is showing excerpts?</p> <p>For example, I have another option that controls whether full content or excerpts are shown on archive pages, but the search page always shows excerpts. So I would prefer to not incur the whole page refresh if no excerpts are being previewed, but if it's the search page or the other option is set to show excerpts, I would need to use refresh when the excerpt length is changed.</p> <p>Or is this even worth the trouble of extra code?</p>
[ { "answer_id": 293424, "author": "ghoul", "author_id": 131136, "author_profile": "https://wordpress.stackexchange.com/users/131136", "pm_score": 0, "selected": false, "text": "<p>I didn't find any solution for this. But I would suggest you to use <code>active_callback</code> parameter such that if another option that controls full content or excerpts shows full content and the page previewed is other than search page, hide the control that controls the excerpt length.</p>\n\n<p>I guess this would be the better approach as you do want to show the relevent controls as per the previewed page.</p>\n" }, { "answer_id": 293701, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 2, "selected": true, "text": "<p>Yes, you can change the <code>transport</code> of a registered setting dynamically after the page loads. And actually the <code>active_callback</code> can be used in conjunction with JS to change the <code>transport</code> <em>instead of</em> causing the control to be hidden.</p>\n\n<p>Assuming you have registered a control with the ID of <code>excerpt_length</code>, and you have registered a setting and control as follows:</p>\n\n<pre><code>$wp_customize-&gt;add_setting( 'excerpt_length', array(\n 'transport' =&gt; 'refresh',\n 'sanitize_callback' =&gt; function( $value ) {\n return intval( $value );\n },\n) );\n\n$wp_customize-&gt;add_control( 'excerpt_length', array(\n 'label' =&gt; __( 'Excerpt length', 'example' ),\n 'section' =&gt; 'something',\n 'type' =&gt; 'number',\n 'active_callback' =&gt; function() {\n // Admin check is for initial state in customize.php.\n return is_admin() || is_archive() || ( is_home() &amp;&amp; ! is_front_page() );\n },\n) );\n</code></pre>\n\n<p>Then you can enqueue some JS for the Customizer controls app (at <code>customize_controls_enqueue_scripts</code>) which overrides the behavior for when the <code>active</code> state changes, like so to toggle the setting's <code>transport</code> when <code>active</code> state changes instead of toggling the visibility of control:</p>\n\n<pre><code>wp.customize.control( 'excerpt_length', function( control ) {\n control.onChangeActive = function( active ) {\n control.setting.transport = active ? 'refresh' : 'postMessage';\n };\n} );\n</code></pre>\n\n<p>There's other ways to do it, but this is probably the least amount of code.</p>\n" } ]
2018/02/06
[ "https://wordpress.stackexchange.com/questions/293308", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/43242/" ]
I have a theme with an option for setting the excerpt length for generated excerpts. Is there a way in the Customizer of conditionally changing the transport mechanism, depending on whether the preview page is showing excerpts? For example, I have another option that controls whether full content or excerpts are shown on archive pages, but the search page always shows excerpts. So I would prefer to not incur the whole page refresh if no excerpts are being previewed, but if it's the search page or the other option is set to show excerpts, I would need to use refresh when the excerpt length is changed. Or is this even worth the trouble of extra code?
Yes, you can change the `transport` of a registered setting dynamically after the page loads. And actually the `active_callback` can be used in conjunction with JS to change the `transport` *instead of* causing the control to be hidden. Assuming you have registered a control with the ID of `excerpt_length`, and you have registered a setting and control as follows: ``` $wp_customize->add_setting( 'excerpt_length', array( 'transport' => 'refresh', 'sanitize_callback' => function( $value ) { return intval( $value ); }, ) ); $wp_customize->add_control( 'excerpt_length', array( 'label' => __( 'Excerpt length', 'example' ), 'section' => 'something', 'type' => 'number', 'active_callback' => function() { // Admin check is for initial state in customize.php. return is_admin() || is_archive() || ( is_home() && ! is_front_page() ); }, ) ); ``` Then you can enqueue some JS for the Customizer controls app (at `customize_controls_enqueue_scripts`) which overrides the behavior for when the `active` state changes, like so to toggle the setting's `transport` when `active` state changes instead of toggling the visibility of control: ``` wp.customize.control( 'excerpt_length', function( control ) { control.onChangeActive = function( active ) { control.setting.transport = active ? 'refresh' : 'postMessage'; }; } ); ``` There's other ways to do it, but this is probably the least amount of code.
293,317
<p>I’ve found others (<a href="https://wordpress.stackexchange.com/questions/99655/advanced-custom-field-gallery-display-one-random-image">source 1</a>, <a href="https://support.advancedcustomfields.com/forums/topic/random-image-from-gallery-field/" rel="nofollow noreferrer">source 2</a>, <a href="https://gist.github.com/tjhole/8054985" rel="nofollow noreferrer">source 3</a>) using the following code for displaying a random gallery image (and it works) with the <a href="https://www.advancedcustomfields.com/" rel="nofollow noreferrer">ACF Plugin</a>:</p> <pre><code>&lt;?php $gallery = get_field('images'); $rand = array_rand($gallery, 1); if( $gallery ): ?&gt; &lt;img src="&lt;?php echo $gallery[$rand]['sizes']['large']; ?&gt;" alt="&lt;?php echo $gallery[$rand]['alt']; ?&gt;" /&gt; &lt;?php endif; ?&gt; </code></pre> <p>But I’m trying to do it with <code>wp_get_attachment_image()</code> (for responsive images) but not sure how to get the <code>$rand</code> variable working? The <a href="https://www.advancedcustomfields.com/resources/gallery/" rel="nofollow noreferrer">ACF Documentation for the Gallery field</a> has a 'Basic List of Images" example that uses <code>wp_get_attachment_image()</code> but I'm not needing to loop through the gallery.</p> <p>Any help would be greatly appreciated. I think it has to be something like the following, with the <code>$rand</code> variable added somewhere:</p> <pre><code>&lt;?php $images = get_field('gallery'); $size = 'full'; // (thumbnail, medium, large, full or custom size) $rand = array_rand($images, 1); if( $images ): ?&gt; &lt;?php echo wp_get_attachment_image( $images['ID'], $size ); ?&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 293321, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 2, "selected": false, "text": "<pre><code>&lt;?php \n $images = get_field('gallery');\n $size = 'full'; // (thumbnail, medium, large, full or custom size)\n $rand = array_rand($images, 1);\n\n if( $images ): ?&gt;\n &lt;?php echo wp_get_attachment_image( $images[$rand]['ID'], $size ); ?&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n\n<p>This code should work. <code>array_rand()</code> return key if second param set to 1 or array with keys if second param > 1</p>\n" }, { "answer_id": 293333, "author": "codeview", "author_id": 40679, "author_profile": "https://wordpress.stackexchange.com/users/40679", "pm_score": 2, "selected": true, "text": "<p>Answer found via <a href=\"https://support.advancedcustomfields.com/forums/topic/random-gallery-image-with-wp_get_attachment_image/\" rel=\"nofollow noreferrer\">ACF Forums</a>. Adding the <code>false</code> parameter returns raw/unformatted value. </p>\n\n<pre><code>&lt;?php \n $images = get_field('gallery', 'option', false); // Adding the `false` parameter returns raw/unformatted value\n $size = 'full'; // (thumbnail, medium, large, full or custom size)\n $rand = array_rand($images, 1);\n\n if( $images ): ?&gt;\n &lt;?php echo wp_get_attachment_image( $images[$rand], $size ); ?&gt;\n&lt;?php endif; ?&gt;\n</code></pre>\n" } ]
2018/02/06
[ "https://wordpress.stackexchange.com/questions/293317", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40679/" ]
I’ve found others ([source 1](https://wordpress.stackexchange.com/questions/99655/advanced-custom-field-gallery-display-one-random-image), [source 2](https://support.advancedcustomfields.com/forums/topic/random-image-from-gallery-field/), [source 3](https://gist.github.com/tjhole/8054985)) using the following code for displaying a random gallery image (and it works) with the [ACF Plugin](https://www.advancedcustomfields.com/): ``` <?php $gallery = get_field('images'); $rand = array_rand($gallery, 1); if( $gallery ): ?> <img src="<?php echo $gallery[$rand]['sizes']['large']; ?>" alt="<?php echo $gallery[$rand]['alt']; ?>" /> <?php endif; ?> ``` But I’m trying to do it with `wp_get_attachment_image()` (for responsive images) but not sure how to get the `$rand` variable working? The [ACF Documentation for the Gallery field](https://www.advancedcustomfields.com/resources/gallery/) has a 'Basic List of Images" example that uses `wp_get_attachment_image()` but I'm not needing to loop through the gallery. Any help would be greatly appreciated. I think it has to be something like the following, with the `$rand` variable added somewhere: ``` <?php $images = get_field('gallery'); $size = 'full'; // (thumbnail, medium, large, full or custom size) $rand = array_rand($images, 1); if( $images ): ?> <?php echo wp_get_attachment_image( $images['ID'], $size ); ?> <?php endif; ?> ```
Answer found via [ACF Forums](https://support.advancedcustomfields.com/forums/topic/random-gallery-image-with-wp_get_attachment_image/). Adding the `false` parameter returns raw/unformatted value. ``` <?php $images = get_field('gallery', 'option', false); // Adding the `false` parameter returns raw/unformatted value $size = 'full'; // (thumbnail, medium, large, full or custom size) $rand = array_rand($images, 1); if( $images ): ?> <?php echo wp_get_attachment_image( $images[$rand], $size ); ?> <?php endif; ?> ```
293,318
<p>I have a added custom column to a custom post type, and it works fine. I just want it to sort the names by title, so I tried this,</p> <pre><code>function sortable_custom_columns( $columns ) { $columns['custom_column'] = 'title'; return $columns; } add_filter( 'manage_edit-custom_sortable_columns', 'sortable_custom_columns' ); </code></pre> <p>However, that is returning very random sorting. I think it may have to do with the content of the column? Which I render like this;</p> <pre><code>function location_column_content( $column, $post_id ) { switch ( $column ) { case 'practice_name': $location_post_meta = get_post_meta( $post_id ); $practice_post_id = $location_post_meta['practice_id'][0]; echo '&lt;a href=&quot;' . get_edit_post_link( $practice_post_id ) . '&quot;&gt;' . get_the_title( $practice_post_id ) . '&lt;/a&gt;'; break; } } add_action( 'manage_sf-location_posts_custom_column', 'location_column_content', 10, 2 ); </code></pre> <p>Does this make sense? Any thoughts here? Thank you</p>
[ { "answer_id": 293323, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": -1, "selected": false, "text": "<p>you need sort table using pre_get_posts. Nice step-by-step instructions on <a href=\"https://code.tutsplus.com/articles/quick-tip-make-your-custom-column-sortable--wp-25095\" rel=\"nofollow noreferrer\">envato tips</a></p>\n" }, { "answer_id": 293403, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 5, "selected": false, "text": "<p>Make sure to change <code>MY_POST_TYPE</code>, <code>MY_CUSTOM_COLUMN</code> and <code>MY_META_KEY</code> to the actual values.</p>\n\n<p>First, add your custom column. Unset the date and set it again to keep it in the last column. You can skip this step.</p>\n\n<pre><code>&lt;?php\nfunction my_manage_MY_POST_TYPE_columns( $columns )\n{\n // save date to the variable\n $date = $columns['date'];\n // unset the 'date' column\n unset( $columns['date'] ); \n // unset any column when necessary\n // unset( $columns['comments'] );\n\n // add your column as new array element and give it table header text\n $columns['MY_CUSTOM_COLUMN'] = __('Custom Column Header Text');\n\n $columns['date'] = $date; // set the 'date' column again, after the custom column\n\n return $columns;\n}\n?&gt;\n</code></pre>\n\n<p>Second, make your column sortable using <code>manage_edit-{$post_type}_sortable_columns</code> filter (not documented yet).</p>\n\n<pre><code>&lt;?php\nfunction my_set_sortable_columns( $columns )\n{\n $columns['MY_CUSTOM_COLUMN'] = 'MY_CUSTOM_COLUMN';\n return $columns;\n}\n?&gt;\n</code></pre>\n\n<p>Third, populate column cells.</p>\n\n<pre><code>&lt;?php\nfunction my_populate_custom_columns( $column, $post_id )\n{\n switch ( $column ) {\n case 'MY_CUSTOM_COLUMN':\n echo get_post_meta($post_id, 'MY_META_KEY', true);\n break;\n case 'MAYBE_ANOTHER_CUSTOM_COLUMN':\n // additional code\n break;\n }\n}\n?&gt;\n</code></pre>\n\n<p>Now you are ready to actually sort that column.</p>\n\n<p>Note: if you don't check <code>meta_query</code> for empty (non-existent) values, your column will show <em>only</em> the posts having (non-empty) meta value until it will be sorted by another by default or another column </p>\n\n<pre><code>&lt;?php\nfunction my_sort_custom_column_query( $query )\n{\n $orderby = $query-&gt;get( 'orderby' );\n\n if ( 'MY_CUSTOM_COLUMN' == $orderby ) {\n\n $meta_query = array(\n 'relation' =&gt; 'OR',\n array(\n 'key' =&gt; 'MY_META_KEY',\n 'compare' =&gt; 'NOT EXISTS', // see note above\n ),\n array(\n 'key' =&gt; 'MY_META_KEY',\n ),\n );\n\n $query-&gt;set( 'meta_query', $meta_query );\n $query-&gt;set( 'orderby', 'meta_value' );\n }\n}\n?&gt;\n</code></pre>\n\n<p>And now let's apply filters and actions. Check if you are not on the front-end, on the right page and the right post type is chosen:</p>\n\n<pre><code>&lt;?php\nglobal $pagenow;\n\nif ( is_admin() &amp;&amp; 'edit.php' == $pagenow &amp;&amp; 'MY_POST_TYPE' == $_GET['post_type'] ) {\n\n // manage colunms\n add_filter( 'manage_MY_POST_TYPE_posts_columns', 'my_manage_MY_POST_TYPE_columns' );\n\n // make columns sortable\n add_filter( 'manage_edit-MY_POST_TYPE_sortable_columns', 'my_set_sortable_columns' );\n\n // populate column cells\n add_action( 'manage_MY_POST_TYPE_posts_custom_column', 'my_populate_custom_columns', 10, 2 );\n\n // set query to sort\n add_action( 'pre_get_posts', 'my_sort_custom_column_query' );\n}\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 390880, "author": "Abdullah Mahi", "author_id": 203775, "author_profile": "https://wordpress.stackexchange.com/users/203775", "pm_score": 2, "selected": false, "text": "<p><strong>Make Columns Sortable</strong></p>\n<p>By default the new custom columns are not sortable so this makes it hard to find data that you need. To sort the custom columns WordPress has another filter manage_edit-post_sortable_columns you can use to assign which columns are sortable.</p>\n<p>When this action is ran the function will pass in a parameter of all the columns which are currently sortable, by adding your new custom columns to this list will now make these columns sortable. The value you give this will be used in the URL so WordPress understands which column to order by.</p>\n<p>The following to allow you to sort by the custom column meta.</p>\n<pre><code>// Register the column as sortable\nfunction register_sortable_columns( $columns ) {\n $columns['meta'] = 'Custom Column';\n return $columns;\n}\nadd_filter( 'manage_edit-post_sortable_columns', 'register_sortable_columns' );\n</code></pre>\n" } ]
2018/02/06
[ "https://wordpress.stackexchange.com/questions/293318", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/20977/" ]
I have a added custom column to a custom post type, and it works fine. I just want it to sort the names by title, so I tried this, ``` function sortable_custom_columns( $columns ) { $columns['custom_column'] = 'title'; return $columns; } add_filter( 'manage_edit-custom_sortable_columns', 'sortable_custom_columns' ); ``` However, that is returning very random sorting. I think it may have to do with the content of the column? Which I render like this; ``` function location_column_content( $column, $post_id ) { switch ( $column ) { case 'practice_name': $location_post_meta = get_post_meta( $post_id ); $practice_post_id = $location_post_meta['practice_id'][0]; echo '<a href="' . get_edit_post_link( $practice_post_id ) . '">' . get_the_title( $practice_post_id ) . '</a>'; break; } } add_action( 'manage_sf-location_posts_custom_column', 'location_column_content', 10, 2 ); ``` Does this make sense? Any thoughts here? Thank you
Make sure to change `MY_POST_TYPE`, `MY_CUSTOM_COLUMN` and `MY_META_KEY` to the actual values. First, add your custom column. Unset the date and set it again to keep it in the last column. You can skip this step. ``` <?php function my_manage_MY_POST_TYPE_columns( $columns ) { // save date to the variable $date = $columns['date']; // unset the 'date' column unset( $columns['date'] ); // unset any column when necessary // unset( $columns['comments'] ); // add your column as new array element and give it table header text $columns['MY_CUSTOM_COLUMN'] = __('Custom Column Header Text'); $columns['date'] = $date; // set the 'date' column again, after the custom column return $columns; } ?> ``` Second, make your column sortable using `manage_edit-{$post_type}_sortable_columns` filter (not documented yet). ``` <?php function my_set_sortable_columns( $columns ) { $columns['MY_CUSTOM_COLUMN'] = 'MY_CUSTOM_COLUMN'; return $columns; } ?> ``` Third, populate column cells. ``` <?php function my_populate_custom_columns( $column, $post_id ) { switch ( $column ) { case 'MY_CUSTOM_COLUMN': echo get_post_meta($post_id, 'MY_META_KEY', true); break; case 'MAYBE_ANOTHER_CUSTOM_COLUMN': // additional code break; } } ?> ``` Now you are ready to actually sort that column. Note: if you don't check `meta_query` for empty (non-existent) values, your column will show *only* the posts having (non-empty) meta value until it will be sorted by another by default or another column ``` <?php function my_sort_custom_column_query( $query ) { $orderby = $query->get( 'orderby' ); if ( 'MY_CUSTOM_COLUMN' == $orderby ) { $meta_query = array( 'relation' => 'OR', array( 'key' => 'MY_META_KEY', 'compare' => 'NOT EXISTS', // see note above ), array( 'key' => 'MY_META_KEY', ), ); $query->set( 'meta_query', $meta_query ); $query->set( 'orderby', 'meta_value' ); } } ?> ``` And now let's apply filters and actions. Check if you are not on the front-end, on the right page and the right post type is chosen: ``` <?php global $pagenow; if ( is_admin() && 'edit.php' == $pagenow && 'MY_POST_TYPE' == $_GET['post_type'] ) { // manage colunms add_filter( 'manage_MY_POST_TYPE_posts_columns', 'my_manage_MY_POST_TYPE_columns' ); // make columns sortable add_filter( 'manage_edit-MY_POST_TYPE_sortable_columns', 'my_set_sortable_columns' ); // populate column cells add_action( 'manage_MY_POST_TYPE_posts_custom_column', 'my_populate_custom_columns', 10, 2 ); // set query to sort add_action( 'pre_get_posts', 'my_sort_custom_column_query' ); } ?> ```
293,365
<p>I have conntected T5_Nav_Menu_Walker to my WP website. <a href="https://gist.github.com/thefuxia/1053467" rel="nofollow noreferrer">https://gist.github.com/thefuxia/1053467</a></p> <p>And I want customize my WP menu to be able to add icons from wp-admin via FontAwesome classes. Screenshot: <a href="https://screenshots.firefox.com/lfGD5DWtdP901KuE/test12.md7.info" rel="nofollow noreferrer">Show</a></p> <p>But when I add CSS class in menu nothing outputting in HTML code, because I use t5_nav_walker. How I can add icons in this wordpress walker? Php code of this walker:</p> <pre><code>&lt;?php # -*- coding: utf-8 -*- /** * Create a nav menu with very basic markup. * * @author Thomas Scholz http://toscho.de * @version 1.0 */ class menu_walker extends Walker_Nav_Menu { /** * Start the element output. * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. May be used for padding. * @param array $args Additional strings. * @return void */ public function start_el( &amp;$output, $item, $depth, $args ) { $output .= '&lt;li&gt;'; // $output .= '&lt;li'.($item-&gt;current ? ' class="current"':'').'&gt;'; $attributes = 'class="app-menu__item"'; ! empty ( $item-&gt;attr_title ) // Avoid redundant titles and $item-&gt;attr_title !== $item-&gt;title and $attributes .= ' title="' . esc_attr( $item-&gt;attr_title ) .'"'; ! empty ( $item-&gt;url ) and $attributes .= ' href="' . esc_attr( $item-&gt;url ) .'"'; $attributes = trim( $attributes ); $title = apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID ); $item_output = "$args-&gt;before&lt;a $attributes&gt;$args-&gt;link_before$title&lt;/a&gt;" . "$args-&gt;link_after$args-&gt;after"; // Since $output is called by reference we don't need to return anything. $output .= apply_filters( 'walker_nav_menu_start_el' , $item_output , $item , $depth , $args ); } /** * @see Walker::start_lvl() * * @param string $output Passed by reference. Used to append additional content. * @return void */ public function start_lvl( &amp;$output ) { $output .= '&lt;ul class="treeview-menu"&gt;'; } /** * @see Walker::end_lvl() * * @param string $output Passed by reference. Used to append additional content. * @return void */ public function end_lvl( &amp;$output ) { $output .= '&lt;/ul&gt;'; } /** * @see Walker::end_el() * * @param string $output Passed by reference. Used to append additional content. * @return void */ function end_el( &amp;$output ) { $output .= '&lt;/li&gt;'; } } </code></pre>
[ { "answer_id": 293323, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": -1, "selected": false, "text": "<p>you need sort table using pre_get_posts. Nice step-by-step instructions on <a href=\"https://code.tutsplus.com/articles/quick-tip-make-your-custom-column-sortable--wp-25095\" rel=\"nofollow noreferrer\">envato tips</a></p>\n" }, { "answer_id": 293403, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 5, "selected": false, "text": "<p>Make sure to change <code>MY_POST_TYPE</code>, <code>MY_CUSTOM_COLUMN</code> and <code>MY_META_KEY</code> to the actual values.</p>\n\n<p>First, add your custom column. Unset the date and set it again to keep it in the last column. You can skip this step.</p>\n\n<pre><code>&lt;?php\nfunction my_manage_MY_POST_TYPE_columns( $columns )\n{\n // save date to the variable\n $date = $columns['date'];\n // unset the 'date' column\n unset( $columns['date'] ); \n // unset any column when necessary\n // unset( $columns['comments'] );\n\n // add your column as new array element and give it table header text\n $columns['MY_CUSTOM_COLUMN'] = __('Custom Column Header Text');\n\n $columns['date'] = $date; // set the 'date' column again, after the custom column\n\n return $columns;\n}\n?&gt;\n</code></pre>\n\n<p>Second, make your column sortable using <code>manage_edit-{$post_type}_sortable_columns</code> filter (not documented yet).</p>\n\n<pre><code>&lt;?php\nfunction my_set_sortable_columns( $columns )\n{\n $columns['MY_CUSTOM_COLUMN'] = 'MY_CUSTOM_COLUMN';\n return $columns;\n}\n?&gt;\n</code></pre>\n\n<p>Third, populate column cells.</p>\n\n<pre><code>&lt;?php\nfunction my_populate_custom_columns( $column, $post_id )\n{\n switch ( $column ) {\n case 'MY_CUSTOM_COLUMN':\n echo get_post_meta($post_id, 'MY_META_KEY', true);\n break;\n case 'MAYBE_ANOTHER_CUSTOM_COLUMN':\n // additional code\n break;\n }\n}\n?&gt;\n</code></pre>\n\n<p>Now you are ready to actually sort that column.</p>\n\n<p>Note: if you don't check <code>meta_query</code> for empty (non-existent) values, your column will show <em>only</em> the posts having (non-empty) meta value until it will be sorted by another by default or another column </p>\n\n<pre><code>&lt;?php\nfunction my_sort_custom_column_query( $query )\n{\n $orderby = $query-&gt;get( 'orderby' );\n\n if ( 'MY_CUSTOM_COLUMN' == $orderby ) {\n\n $meta_query = array(\n 'relation' =&gt; 'OR',\n array(\n 'key' =&gt; 'MY_META_KEY',\n 'compare' =&gt; 'NOT EXISTS', // see note above\n ),\n array(\n 'key' =&gt; 'MY_META_KEY',\n ),\n );\n\n $query-&gt;set( 'meta_query', $meta_query );\n $query-&gt;set( 'orderby', 'meta_value' );\n }\n}\n?&gt;\n</code></pre>\n\n<p>And now let's apply filters and actions. Check if you are not on the front-end, on the right page and the right post type is chosen:</p>\n\n<pre><code>&lt;?php\nglobal $pagenow;\n\nif ( is_admin() &amp;&amp; 'edit.php' == $pagenow &amp;&amp; 'MY_POST_TYPE' == $_GET['post_type'] ) {\n\n // manage colunms\n add_filter( 'manage_MY_POST_TYPE_posts_columns', 'my_manage_MY_POST_TYPE_columns' );\n\n // make columns sortable\n add_filter( 'manage_edit-MY_POST_TYPE_sortable_columns', 'my_set_sortable_columns' );\n\n // populate column cells\n add_action( 'manage_MY_POST_TYPE_posts_custom_column', 'my_populate_custom_columns', 10, 2 );\n\n // set query to sort\n add_action( 'pre_get_posts', 'my_sort_custom_column_query' );\n}\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 390880, "author": "Abdullah Mahi", "author_id": 203775, "author_profile": "https://wordpress.stackexchange.com/users/203775", "pm_score": 2, "selected": false, "text": "<p><strong>Make Columns Sortable</strong></p>\n<p>By default the new custom columns are not sortable so this makes it hard to find data that you need. To sort the custom columns WordPress has another filter manage_edit-post_sortable_columns you can use to assign which columns are sortable.</p>\n<p>When this action is ran the function will pass in a parameter of all the columns which are currently sortable, by adding your new custom columns to this list will now make these columns sortable. The value you give this will be used in the URL so WordPress understands which column to order by.</p>\n<p>The following to allow you to sort by the custom column meta.</p>\n<pre><code>// Register the column as sortable\nfunction register_sortable_columns( $columns ) {\n $columns['meta'] = 'Custom Column';\n return $columns;\n}\nadd_filter( 'manage_edit-post_sortable_columns', 'register_sortable_columns' );\n</code></pre>\n" } ]
2018/02/07
[ "https://wordpress.stackexchange.com/questions/293365", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123015/" ]
I have conntected T5\_Nav\_Menu\_Walker to my WP website. <https://gist.github.com/thefuxia/1053467> And I want customize my WP menu to be able to add icons from wp-admin via FontAwesome classes. Screenshot: [Show](https://screenshots.firefox.com/lfGD5DWtdP901KuE/test12.md7.info) But when I add CSS class in menu nothing outputting in HTML code, because I use t5\_nav\_walker. How I can add icons in this wordpress walker? Php code of this walker: ``` <?php # -*- coding: utf-8 -*- /** * Create a nav menu with very basic markup. * * @author Thomas Scholz http://toscho.de * @version 1.0 */ class menu_walker extends Walker_Nav_Menu { /** * Start the element output. * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. May be used for padding. * @param array $args Additional strings. * @return void */ public function start_el( &$output, $item, $depth, $args ) { $output .= '<li>'; // $output .= '<li'.($item->current ? ' class="current"':'').'>'; $attributes = 'class="app-menu__item"'; ! empty ( $item->attr_title ) // Avoid redundant titles and $item->attr_title !== $item->title and $attributes .= ' title="' . esc_attr( $item->attr_title ) .'"'; ! empty ( $item->url ) and $attributes .= ' href="' . esc_attr( $item->url ) .'"'; $attributes = trim( $attributes ); $title = apply_filters( 'the_title', $item->title, $item->ID ); $item_output = "$args->before<a $attributes>$args->link_before$title</a>" . "$args->link_after$args->after"; // Since $output is called by reference we don't need to return anything. $output .= apply_filters( 'walker_nav_menu_start_el' , $item_output , $item , $depth , $args ); } /** * @see Walker::start_lvl() * * @param string $output Passed by reference. Used to append additional content. * @return void */ public function start_lvl( &$output ) { $output .= '<ul class="treeview-menu">'; } /** * @see Walker::end_lvl() * * @param string $output Passed by reference. Used to append additional content. * @return void */ public function end_lvl( &$output ) { $output .= '</ul>'; } /** * @see Walker::end_el() * * @param string $output Passed by reference. Used to append additional content. * @return void */ function end_el( &$output ) { $output .= '</li>'; } } ```
Make sure to change `MY_POST_TYPE`, `MY_CUSTOM_COLUMN` and `MY_META_KEY` to the actual values. First, add your custom column. Unset the date and set it again to keep it in the last column. You can skip this step. ``` <?php function my_manage_MY_POST_TYPE_columns( $columns ) { // save date to the variable $date = $columns['date']; // unset the 'date' column unset( $columns['date'] ); // unset any column when necessary // unset( $columns['comments'] ); // add your column as new array element and give it table header text $columns['MY_CUSTOM_COLUMN'] = __('Custom Column Header Text'); $columns['date'] = $date; // set the 'date' column again, after the custom column return $columns; } ?> ``` Second, make your column sortable using `manage_edit-{$post_type}_sortable_columns` filter (not documented yet). ``` <?php function my_set_sortable_columns( $columns ) { $columns['MY_CUSTOM_COLUMN'] = 'MY_CUSTOM_COLUMN'; return $columns; } ?> ``` Third, populate column cells. ``` <?php function my_populate_custom_columns( $column, $post_id ) { switch ( $column ) { case 'MY_CUSTOM_COLUMN': echo get_post_meta($post_id, 'MY_META_KEY', true); break; case 'MAYBE_ANOTHER_CUSTOM_COLUMN': // additional code break; } } ?> ``` Now you are ready to actually sort that column. Note: if you don't check `meta_query` for empty (non-existent) values, your column will show *only* the posts having (non-empty) meta value until it will be sorted by another by default or another column ``` <?php function my_sort_custom_column_query( $query ) { $orderby = $query->get( 'orderby' ); if ( 'MY_CUSTOM_COLUMN' == $orderby ) { $meta_query = array( 'relation' => 'OR', array( 'key' => 'MY_META_KEY', 'compare' => 'NOT EXISTS', // see note above ), array( 'key' => 'MY_META_KEY', ), ); $query->set( 'meta_query', $meta_query ); $query->set( 'orderby', 'meta_value' ); } } ?> ``` And now let's apply filters and actions. Check if you are not on the front-end, on the right page and the right post type is chosen: ``` <?php global $pagenow; if ( is_admin() && 'edit.php' == $pagenow && 'MY_POST_TYPE' == $_GET['post_type'] ) { // manage colunms add_filter( 'manage_MY_POST_TYPE_posts_columns', 'my_manage_MY_POST_TYPE_columns' ); // make columns sortable add_filter( 'manage_edit-MY_POST_TYPE_sortable_columns', 'my_set_sortable_columns' ); // populate column cells add_action( 'manage_MY_POST_TYPE_posts_custom_column', 'my_populate_custom_columns', 10, 2 ); // set query to sort add_action( 'pre_get_posts', 'my_sort_custom_column_query' ); } ?> ```
293,420
<p>How can I place categories onto a page using short code from the following function.</p> <pre><code>&lt;?php echo get_the_category_list(); ?&gt; </code></pre>
[ { "answer_id": 293425, "author": "Anton Flärd", "author_id": 107106, "author_profile": "https://wordpress.stackexchange.com/users/107106", "pm_score": 0, "selected": false, "text": "<p>To display it on a page using a shortcode you can add this to your <code>functions.php</code>:</p>\n\n<pre><code>function display_category_list( $atts ) {\n return get_the_category_list();\n}\nadd_shortcode( 'display-categories', 'display_category_list' );\n</code></pre>\n\n<p>and then on your page simply write <code>[display-categories]</code>.</p>\n\n<p>Source: <a href=\"https://codex.wordpress.org/Function_Reference/add_shortcode\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/add_shortcode</a></p>\n\n<p>I suggest looking into the <code>wp_list_categories</code>-function since it can display a more detailed list, but I'm not sure what your goal is, so take it as a tip:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_list_categories/</a></p>\n" }, { "answer_id": 293426, "author": "ghoul", "author_id": 131136, "author_profile": "https://wordpress.stackexchange.com/users/131136", "pm_score": 1, "selected": false, "text": "<p><code>get_the_category_list</code> works on <a href=\"https://codex.wordpress.org/The_Loop\" rel=\"nofollow noreferrer\">The Loop</a> only and needs a <code>post_id</code> as a parameter. As a page does not have category, it won't work by default in a page. </p>\n\n<p>If you want to retrieve all the categories on a page, you should use one of the following:</p>\n\n<pre><code>wp_list_categories\n\nget_categories( array( 'echo' =&gt; false ) );\n</code></pre>\n" } ]
2018/02/07
[ "https://wordpress.stackexchange.com/questions/293420", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136408/" ]
How can I place categories onto a page using short code from the following function. ``` <?php echo get_the_category_list(); ?> ```
`get_the_category_list` works on [The Loop](https://codex.wordpress.org/The_Loop) only and needs a `post_id` as a parameter. As a page does not have category, it won't work by default in a page. If you want to retrieve all the categories on a page, you should use one of the following: ``` wp_list_categories get_categories( array( 'echo' => false ) ); ```
293,427
<p><strong>BACKGROUND</strong></p> <p>After the user on <em>domain1</em> clicks a link to <em>domain 2</em>, I need to <strong>send also the user-data (username,email,..) from server1/domain1 to server2/domain2</strong> and to save it temporary in the server2/database.</p> <p>Both are wordpress websites.</p> <p><strong>CURRENT WORK</strong></p> <p>Lets say, <code>$url = 'http://my-domain2.com'</code>; So far I found out, that cURL can do this job:</p> <pre><code>function curlTest($url, $fields){ try{ $ch = curl_init($url); if (!$ch) throw new Exception('Failed to initialize'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 10); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields))); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); $response = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (!$response) throw new Exception(curl_error($ch), curl_errno($ch)); curl_close( $ch ); return (int) $status; //status 200 = success } catch(Exception $e) { trigger_error(sprintf( 'Curl failed with error #%d: %s', $e-&gt;getCode(), $e-&gt;getMessage()), E_USER_ERROR); } } </code></pre> <p>or objective orientated like descriped <a href="https://stackoverflow.com/questions/2138527/php-curl-http-post-sample-code">here</a>. </p> <p>Later I found a <strong>wordpress solution</strong> like this:</p> <pre><code> $response = wp_remote_post( &amp;url, array( 'data' =&gt; $fields) ); </code></pre> <p>explained <a href="https://deliciousbrains.com/php-curl-how-wordpress-makes-http-requests/" rel="nofollow noreferrer">here</a>.</p> <p>The cURL call seems to be successfully, but I have no idea how to fetch the data on the other server. So far I put the user-data on server1 in an array (<em>$fields</em>) and using POST to send it to server2. But <strong>how can I fetch the data</strong> on server2? </p> <p>According to the example of Ed Cradock below the <a href="http://php.net/manual/de/function.curl-setopt.php" rel="nofollow noreferrer">offical documentation</a> it seems to be possible to grap the request on the other side with this code:</p> <pre><code> if($_SERVER['REQUEST_METHOD'] == 'PUT') { parse_str(file_get_contents('php://input'), $requestData); print_r($requestData); // Save requested Data to database here } </code></pre> <p>But it doesn't work for me because I guess the URL is wrong: <code>http://my-domain2.com/&lt;whats-here?&gt;</code></p> <p><strong>QUESTION</strong></p> <p>How to fetch the Data of a POST cURL request with wordpress in a secure way?</p>
[ { "answer_id": 293429, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_remote_get/\" rel=\"noreferrer\">wp_remote_get()</a>\nand <a href=\"https://developer.wordpress.org/reference/functions/wp_remote_post/\" rel=\"noreferrer\">wp_remote_post()</a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_remote_request/\" rel=\"noreferrer\">wp_remote_request()</a> should answer on your questions.This is best practice for WordPress.</p>\n" }, { "answer_id": 293438, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p><code>wp_remote_post</code>, which is better to use than calling curl directly, is sending a POST request to the other side, which means you can just fetch it with the <code>$_POST</code> global. There is no reason or need to use PUT requests for what you are doing.</p>\n" } ]
2018/02/07
[ "https://wordpress.stackexchange.com/questions/293427", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122620/" ]
**BACKGROUND** After the user on *domain1* clicks a link to *domain 2*, I need to **send also the user-data (username,email,..) from server1/domain1 to server2/domain2** and to save it temporary in the server2/database. Both are wordpress websites. **CURRENT WORK** Lets say, `$url = 'http://my-domain2.com'`; So far I found out, that cURL can do this job: ``` function curlTest($url, $fields){ try{ $ch = curl_init($url); if (!$ch) throw new Exception('Failed to initialize'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 10); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields))); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); $response = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (!$response) throw new Exception(curl_error($ch), curl_errno($ch)); curl_close( $ch ); return (int) $status; //status 200 = success } catch(Exception $e) { trigger_error(sprintf( 'Curl failed with error #%d: %s', $e->getCode(), $e->getMessage()), E_USER_ERROR); } } ``` or objective orientated like descriped [here](https://stackoverflow.com/questions/2138527/php-curl-http-post-sample-code). Later I found a **wordpress solution** like this: ``` $response = wp_remote_post( &url, array( 'data' => $fields) ); ``` explained [here](https://deliciousbrains.com/php-curl-how-wordpress-makes-http-requests/). The cURL call seems to be successfully, but I have no idea how to fetch the data on the other server. So far I put the user-data on server1 in an array (*$fields*) and using POST to send it to server2. But **how can I fetch the data** on server2? According to the example of Ed Cradock below the [offical documentation](http://php.net/manual/de/function.curl-setopt.php) it seems to be possible to grap the request on the other side with this code: ``` if($_SERVER['REQUEST_METHOD'] == 'PUT') { parse_str(file_get_contents('php://input'), $requestData); print_r($requestData); // Save requested Data to database here } ``` But it doesn't work for me because I guess the URL is wrong: `http://my-domain2.com/<whats-here?>` **QUESTION** How to fetch the Data of a POST cURL request with wordpress in a secure way?
[wp\_remote\_get()](https://developer.wordpress.org/reference/functions/wp_remote_get/) and [wp\_remote\_post()](https://developer.wordpress.org/reference/functions/wp_remote_post/) and [wp\_remote\_request()](https://developer.wordpress.org/reference/functions/wp_remote_request/) should answer on your questions.This is best practice for WordPress.
293,431
<p>I want to fire an event for when AFTER a new widget has been added to the previewer, and then AFTER a widget has been removed.</p> <p>Use Case: After the widget has been added to the previewer DOM, I want to change it's class based on how many other widgets are in that same sidebar area. So when </p> <pre><code>wp.customize('sidebars_widgets[sidebar-1]').get().length </code></pre> <p>fires, its a little too early to count all the widgets.</p> <p>So like, I'm thinking I add a widget in the Customizer controls sidebar, then the previewer adds the widget, once the widget is added to the Previewer DOM I was hoping it would emit an event saying "this widget has been added". I could listen for that event and then run some code to change the class names on all the widgets in that sidebar.</p> <p>I already have this working, by having the Customizer send some data to the Previewer, waiting 1 second, and then counting the widgets. But that doesnt seem very reliable (what if it takes 1.3 seconds for the widget to load?).</p> <p>In my Previewer javascript (loaded via the <code>customize_preview_init</code> hook, I have the following:</p> <pre><code> $( document ).on( 'widget-added', function(event, widget) { console.log(widget); }); </code></pre> <p>But this doesn't seem to do anything.</p> <p>Anyone know what that would be?</p>
[ { "answer_id": 293429, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_remote_get/\" rel=\"noreferrer\">wp_remote_get()</a>\nand <a href=\"https://developer.wordpress.org/reference/functions/wp_remote_post/\" rel=\"noreferrer\">wp_remote_post()</a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_remote_request/\" rel=\"noreferrer\">wp_remote_request()</a> should answer on your questions.This is best practice for WordPress.</p>\n" }, { "answer_id": 293438, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p><code>wp_remote_post</code>, which is better to use than calling curl directly, is sending a POST request to the other side, which means you can just fetch it with the <code>$_POST</code> global. There is no reason or need to use PUT requests for what you are doing.</p>\n" } ]
2018/02/07
[ "https://wordpress.stackexchange.com/questions/293431", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/19536/" ]
I want to fire an event for when AFTER a new widget has been added to the previewer, and then AFTER a widget has been removed. Use Case: After the widget has been added to the previewer DOM, I want to change it's class based on how many other widgets are in that same sidebar area. So when ``` wp.customize('sidebars_widgets[sidebar-1]').get().length ``` fires, its a little too early to count all the widgets. So like, I'm thinking I add a widget in the Customizer controls sidebar, then the previewer adds the widget, once the widget is added to the Previewer DOM I was hoping it would emit an event saying "this widget has been added". I could listen for that event and then run some code to change the class names on all the widgets in that sidebar. I already have this working, by having the Customizer send some data to the Previewer, waiting 1 second, and then counting the widgets. But that doesnt seem very reliable (what if it takes 1.3 seconds for the widget to load?). In my Previewer javascript (loaded via the `customize_preview_init` hook, I have the following: ``` $( document ).on( 'widget-added', function(event, widget) { console.log(widget); }); ``` But this doesn't seem to do anything. Anyone know what that would be?
[wp\_remote\_get()](https://developer.wordpress.org/reference/functions/wp_remote_get/) and [wp\_remote\_post()](https://developer.wordpress.org/reference/functions/wp_remote_post/) and [wp\_remote\_request()](https://developer.wordpress.org/reference/functions/wp_remote_request/) should answer on your questions.This is best practice for WordPress.
293,443
<p>I have a custom field manually coded using CMB2: <a href="https://cmb2.io/" rel="nofollow noreferrer">https://cmb2.io/</a>. Here is the code:</p> <pre><code>$cmb_pages_customtext-&gt;add_field( array( 'name' =&gt; esc_html__( 'Content', 'defaulttheme' ), 'id' =&gt; $prefix . 'customtext_content', 'type' =&gt; 'wysiwyg', 'sanitization_cb' =&gt; false, )); </code></pre> <p>I want to be able to add an iframe to the custom field. When I add the iframe code to the field, it saves it in the page edit screen but the iframe doesn't display when viewing the actual page. Is there something I need to add to get the iframe to display on the actual page?</p>
[ { "answer_id": 299470, "author": "Leonardo", "author_id": 138721, "author_profile": "https://wordpress.stackexchange.com/users/138721", "pm_score": 0, "selected": false, "text": "<p>how do you assign the variable? use something like this?</p>\n\n<pre><code>$variable = esc_html( get_post_meta(get_the_ID(), 'example', true) );\n</code></pre>\n\n<p>if yes, try removing <a href=\"https://codex.wordpress.org/Function_Reference/esc_html\" rel=\"nofollow noreferrer\">esc_html()</a></p>\n" }, { "answer_id": 299607, "author": "mdailey77", "author_id": 119722, "author_profile": "https://wordpress.stackexchange.com/users/119722", "pm_score": -1, "selected": true, "text": "<p>I actually figured out the problem. It was a wp_kses_post function that was the cause. The wp_kses_post function was stripping the iframe tag. Obviously I removed the wp_kses_post function. </p>\n" } ]
2018/02/07
[ "https://wordpress.stackexchange.com/questions/293443", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119722/" ]
I have a custom field manually coded using CMB2: <https://cmb2.io/>. Here is the code: ``` $cmb_pages_customtext->add_field( array( 'name' => esc_html__( 'Content', 'defaulttheme' ), 'id' => $prefix . 'customtext_content', 'type' => 'wysiwyg', 'sanitization_cb' => false, )); ``` I want to be able to add an iframe to the custom field. When I add the iframe code to the field, it saves it in the page edit screen but the iframe doesn't display when viewing the actual page. Is there something I need to add to get the iframe to display on the actual page?
I actually figured out the problem. It was a wp\_kses\_post function that was the cause. The wp\_kses\_post function was stripping the iframe tag. Obviously I removed the wp\_kses\_post function.
293,445
<p>I'm working on a website that needs to be RTL, after reading some articles online I understood that in order for the website to be RTL I need to change the site language to a RTL language.</p> <p>Through this path: <strong>Settings >> General >> Site Language</strong></p> <p>Did that and it changed the website to RTL but it changed all the website's content (front-end and admin panel) to the RTL language.</p> <p>Can I change only the front-end part to RTL without changing my admin panel's language?</p> <p>Thanks.</p>
[ { "answer_id": 293506, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 1, "selected": false, "text": "<p>Set your WordPress to a RTL language, then use the following code in <code>functions.php</code> or as the plugin:</p>\n\n<pre><code>&lt;?php\nadd_filter( 'locale', 'my_set_admin_locale' );\n\nfunction my_set_admin_locale( $locale ) {\n\n // check if you are in the Admin area\n if( is_admin() ) {\n // set LTR locale\n $locale = 'en_US';\n }\n\n return( $locale );\n}\n</code></pre>\n\n<p>Or otherwise, set WordPress to LTR and set front-end to RTL:</p>\n\n<pre><code> if( ! is_admin() ) { // not admin area\n // set RTL locale\n $locale = 'ar';\n }\n</code></pre>\n" }, { "answer_id": 343931, "author": "Mr.Hosseini", "author_id": 147413, "author_profile": "https://wordpress.stackexchange.com/users/147413", "pm_score": 0, "selected": false, "text": "<p>Like so :</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>add_filter('locale', function ($locale) {\n\n global $wp_locale;\n\n if (isset($_COOKIE['farsi'])) {\n $wp_locale-&gt;text_direction = 'rtl';\n return 'fa_IR';\n\n } else {\n $wp_locale-&gt;text_direction = 'ltr';\n return 'en_US';\n }\n\n});\n</code></pre>\n" } ]
2018/02/07
[ "https://wordpress.stackexchange.com/questions/293445", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136416/" ]
I'm working on a website that needs to be RTL, after reading some articles online I understood that in order for the website to be RTL I need to change the site language to a RTL language. Through this path: **Settings >> General >> Site Language** Did that and it changed the website to RTL but it changed all the website's content (front-end and admin panel) to the RTL language. Can I change only the front-end part to RTL without changing my admin panel's language? Thanks.
Set your WordPress to a RTL language, then use the following code in `functions.php` or as the plugin: ``` <?php add_filter( 'locale', 'my_set_admin_locale' ); function my_set_admin_locale( $locale ) { // check if you are in the Admin area if( is_admin() ) { // set LTR locale $locale = 'en_US'; } return( $locale ); } ``` Or otherwise, set WordPress to LTR and set front-end to RTL: ``` if( ! is_admin() ) { // not admin area // set RTL locale $locale = 'ar'; } ```
293,454
<p>I have build a function to fetch a post in Wordpress served over ajax.</p> <pre><code>$.ajax({ url: '/wp-admin/admin-ajax.php', type: 'POST', cache: false, data: { action: 'get_post_info', postId: postId, }, success: function(data){ }); </code></pre> <p>In order to make it work if the user is not logged in, I have used wp_ajax_nopriv. But when the user is logged in now, the functionality crashes.</p> <pre><code>add_action('wp_ajax_nopriv_get_post_info', 'get_post_info'); function get_post_info(){ } </code></pre> <p>Is there a function like wp_ajax that work for both logged_in and not logged_in users?</p>
[ { "answer_id": 293456, "author": "user2752173", "author_id": 136422, "author_profile": "https://wordpress.stackexchange.com/users/136422", "pm_score": 2, "selected": false, "text": "<p>As it is said in the <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)\" rel=\"nofollow noreferrer\">codex</a>\nThe <code>wp_ajax_nopriv</code> hook will not fire for authenticated users, i.e. when is_user_logged_in() returns true. To handle both unauthenticated and authenticated users, also use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">wp_ajax_(action)</a>.</p>\n" }, { "answer_id": 293463, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 2, "selected": false, "text": "<pre><code>add_action('wp_ajax_get_post_info', 'get_post_info');\nadd_action('wp_ajax_nopriv_get_post_info', 'get_post_info');\n</code></pre>\n\n<p><a href=\"http://add_action(&#39;wp_ajax_nopriv_get_post_info&#39;,%20&#39;get_post_info&#39;);\" rel=\"nofollow noreferrer\">wp_ajax_nopriv_(action)</a>\nonly on front-end and only for non logged users. Use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\">wp_ajax_(action)</a> for logged in users.</p>\n" } ]
2018/02/07
[ "https://wordpress.stackexchange.com/questions/293454", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/130759/" ]
I have build a function to fetch a post in Wordpress served over ajax. ``` $.ajax({ url: '/wp-admin/admin-ajax.php', type: 'POST', cache: false, data: { action: 'get_post_info', postId: postId, }, success: function(data){ }); ``` In order to make it work if the user is not logged in, I have used wp\_ajax\_nopriv. But when the user is logged in now, the functionality crashes. ``` add_action('wp_ajax_nopriv_get_post_info', 'get_post_info'); function get_post_info(){ } ``` Is there a function like wp\_ajax that work for both logged\_in and not logged\_in users?
As it is said in the [codex](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)) The `wp_ajax_nopriv` hook will not fire for authenticated users, i.e. when is\_user\_logged\_in() returns true. To handle both unauthenticated and authenticated users, also use [wp\_ajax\_(action)](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)).
293,465
<p>following code is returning <code>name</code> of all terms associated with my custom Post Type which are under `generetax taxonomy only</p> <pre><code>$terms = get_the_term_list($post-&gt;ID, 'generetax'); echo $terms; </code></pre> <p>Can you please let me know how to get the <code>term_id</code> instead of name? I tried this way</p> <pre><code> echo $terms-&gt;term_id; </code></pre> <p>but it is not returning any thing</p> <p>**</p> <blockquote> <p>Update</p> </blockquote> <p>**</p> <p>Ok On rnnung this method</p> <pre><code> $terms = get_the_terms($post-&gt;ID, 'generetax'); foeach($terms as $term){ print_r($term); } </code></pre> <blockquote> <p>WP_Term Object ( [term_id] => 3 [name] => Semi [slug] => semi [term_group] => 0 [term_taxonomy_id] => 3 [taxonomy] => generetax[description] => [parent] => 0 [count] => 1 [filter] => raw )</p> </blockquote> <p>but still <code>$terms-&gt;term_id;</code> return nothing on</p> <pre><code> $terms = get_the_terms($post-&gt;ID, 'generetax'); foeach($terms as $term){ echo $terms-&gt;term_id; } </code></pre>
[ { "answer_id": 293467, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 2, "selected": true, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_terms/\" rel=\"nofollow noreferrer\">get_the_terms()</a>\nwill help you. Function return array with terms objects and you can foreach array and retrieve term id for each term attached to post. </p>\n" }, { "answer_id": 407375, "author": "Lalaina RAHAJASON", "author_id": 205632, "author_profile": "https://wordpress.stackexchange.com/users/205632", "pm_score": 0, "selected": false, "text": "<p>If only getting ids of each term in array, no need to foreach each term item, just use php array_column native function :</p>\n<pre><code>$terms = get_the_terms($post_id, 'taxonomy');\n$terms_ids = array_column($terms, 'term_id');\n//output\n[array_of_ids]\n</code></pre>\n<p>Kiss</p>\n" } ]
2018/02/07
[ "https://wordpress.stackexchange.com/questions/293465", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/35444/" ]
following code is returning `name` of all terms associated with my custom Post Type which are under `generetax taxonomy only ``` $terms = get_the_term_list($post->ID, 'generetax'); echo $terms; ``` Can you please let me know how to get the `term_id` instead of name? I tried this way ``` echo $terms->term_id; ``` but it is not returning any thing \*\* > > Update > > > \*\* Ok On rnnung this method ``` $terms = get_the_terms($post->ID, 'generetax'); foeach($terms as $term){ print_r($term); } ``` > > WP\_Term Object ( [term\_id] => 3 [name] => Semi [slug] => semi > [term\_group] => 0 [term\_taxonomy\_id] => 3 [taxonomy] => > generetax[description] => [parent] => 0 [count] => 1 [filter] => raw ) > > > but still `$terms->term_id;` return nothing on ``` $terms = get_the_terms($post->ID, 'generetax'); foeach($terms as $term){ echo $terms->term_id; } ```
[get\_the\_terms()](https://developer.wordpress.org/reference/functions/get_the_terms/) will help you. Function return array with terms objects and you can foreach array and retrieve term id for each term attached to post.
293,491
<p>i have the code that can add a post in a custom post type but adding the category is not working.</p> <pre><code>$args = array( 'post_title' =&gt; $title , 'post_status' =&gt; 'publish', 'post_type' =&gt; 'mypost' ); $post_id = wp_insert_post($args); $category_ids = array(38,39); wp_set_post_categories( $post_id, $category_ids, 'category'); </code></pre>
[ { "answer_id": 293494, "author": "Parth Patel", "author_id": 136444, "author_profile": "https://wordpress.stackexchange.com/users/136444", "pm_score": 0, "selected": false, "text": "<p>As you are doing this for the custom post type, you need to use taxonomy. I will suggest you <code>&lt;?php wp_set_post_terms( $post_id, $terms, $taxonomy, $append ) ?&gt;</code> to use.\nplease refer <a href=\"https://codex.wordpress.org/Function_Reference/wp_set_post_terms\" rel=\"nofollow noreferrer\">this link</a> for the detailed use of the function.</p>\n" }, { "answer_id": 293508, "author": "cybmeta", "author_id": 37428, "author_profile": "https://wordpress.stackexchange.com/users/37428", "pm_score": 2, "selected": false, "text": "<p>You need to register the custom post type with support for the <code>category</code> taxonomy:</p>\n\n<pre><code>add_action('init', 'cyb_register_post_type');\nfunction cyb_register_post_type() {\n $args = array(\n // All the other args\n 'taxonomies' =&gt; array( 'category' ),\n );\n\n register_post_type( 'my_post_type', $args );\n}\n</code></pre>\n\n<p>Then you can set relationships between the custom post type and the <code>categoy</code> taxonomy as you was doing, but you have to correct the code.</p>\n\n<p>From this:</p>\n\n<pre><code>wp_set_post_categories( $post_id, $category_ids, 'category');\n</code></pre>\n\n<p>To this (previous categories are deleted and replaced by the new categories):</p>\n\n<pre><code>wp_set_post_categories( $post_id, $category_ids );\n// The above line is equivalent to\n// wp_set_post_categories( $post_id, $category_ids, false );\n// or\n// wp_set_post_terms( $post_id, $category_ids, 'category', false );\n</code></pre>\n\n<p>Or to (previous categories are not deleted, new categories are appended):</p>\n\n<pre><code>wp_set_post_categories( $post_id, $category_ids, true );\n</code></pre>\n\n<p>You can also register a custom taxonomy and use it for your custom post type:</p>\n\n<pre><code>add_action('init', 'cyb_register_post_type_and_taxonomy');\nfunction cyb_register_post_type_and_taxonomy() {\n\n $post_type_args = array(\n // All the other args\n 'taxonomies' =&gt; array( 'my_custom_taxonomy' ),\n );\n\n register_post_type( 'my_post_type', $post_type_args );\n\n $taxonomy_args = array(\n // Arguments for the custom taxonomy\n // See https://developer.wordpress.org/reference/functions/register_taxonomy/\n );\n\n register_taxonomy( 'my_custom_taxonomy', 'my_post_type', $args );\n\n}\n</code></pre>\n\n<p>And then use <code>wp_set_post_terms()</code>, not <code>wp_set_post_categories()</code>:</p>\n\n<pre><code>wp_set_post_terms( $post_id, $category_ids, 'my_custom_taxonomy');\n</code></pre>\n" } ]
2018/02/08
[ "https://wordpress.stackexchange.com/questions/293491", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131529/" ]
i have the code that can add a post in a custom post type but adding the category is not working. ``` $args = array( 'post_title' => $title , 'post_status' => 'publish', 'post_type' => 'mypost' ); $post_id = wp_insert_post($args); $category_ids = array(38,39); wp_set_post_categories( $post_id, $category_ids, 'category'); ```
You need to register the custom post type with support for the `category` taxonomy: ``` add_action('init', 'cyb_register_post_type'); function cyb_register_post_type() { $args = array( // All the other args 'taxonomies' => array( 'category' ), ); register_post_type( 'my_post_type', $args ); } ``` Then you can set relationships between the custom post type and the `categoy` taxonomy as you was doing, but you have to correct the code. From this: ``` wp_set_post_categories( $post_id, $category_ids, 'category'); ``` To this (previous categories are deleted and replaced by the new categories): ``` wp_set_post_categories( $post_id, $category_ids ); // The above line is equivalent to // wp_set_post_categories( $post_id, $category_ids, false ); // or // wp_set_post_terms( $post_id, $category_ids, 'category', false ); ``` Or to (previous categories are not deleted, new categories are appended): ``` wp_set_post_categories( $post_id, $category_ids, true ); ``` You can also register a custom taxonomy and use it for your custom post type: ``` add_action('init', 'cyb_register_post_type_and_taxonomy'); function cyb_register_post_type_and_taxonomy() { $post_type_args = array( // All the other args 'taxonomies' => array( 'my_custom_taxonomy' ), ); register_post_type( 'my_post_type', $post_type_args ); $taxonomy_args = array( // Arguments for the custom taxonomy // See https://developer.wordpress.org/reference/functions/register_taxonomy/ ); register_taxonomy( 'my_custom_taxonomy', 'my_post_type', $args ); } ``` And then use `wp_set_post_terms()`, not `wp_set_post_categories()`: ``` wp_set_post_terms( $post_id, $category_ids, 'my_custom_taxonomy'); ```
293,543
<p><a href="https://i.stack.imgur.com/wUqky.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wUqky.png" alt="WooCommerce panel in Customizer"></a></p> <p>I have used the below code to remove other items from Customizer. But unable to remove the WooCommerce section. </p> <pre><code>function my_customize_register() { global $wp_customize; $wp_customize-&gt;remove_section( 'colors' ); $wp_customize-&gt;remove_section( 'static_front_page' ); $wp_customize-&gt;remove_section( 'background_image' ); $wp_customize-&gt;remove_section( 'themes' ); $wp_customize-&gt;remove_section( 'header_image'); } add_action( 'customize_register', 'my_customize_register', 11 ); add_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999); function remove_unnecessary_wordpress_menus(){ global $submenu; foreach($submenu['themes.php'] as $menu_index =&gt; $theme_menu){ if($theme_menu[0] == 'Header' || $theme_menu[0] == 'Background') unset($submenu['themes.php'][$menu_index]); } } </code></pre>
[ { "answer_id": 293550, "author": "Max Yudin", "author_id": 11761, "author_profile": "https://wordpress.stackexchange.com/users/11761", "pm_score": 1, "selected": false, "text": "<p>Open admin page HTML source and find there all <code>&lt;li&gt;</code> elements having <code>id</code> attribute starting with <code>accordion-section-</code>. For example, for Homepage Settings it looks like:</p>\n\n<pre><code>&lt;li id=\"accordion-section-static_front_page\" class=\"accordion-section control-section control-section-default\" aria-owns=\"sub-accordion-section-static_front_page\" style=\"\"&gt;\n</code></pre>\n\n<p>One of these <code>&lt;li&gt;</code> elements is WooCommerce-related, you'll see it. The last part of it's <code>id</code> (following the <code>accordion-section-</code> part) should be used in <code>$wp_customize-&gt;remove_section()</code>.</p>\n" }, { "answer_id": 293561, "author": "Iceable", "author_id": 136263, "author_profile": "https://wordpress.stackexchange.com/users/136263", "pm_score": 3, "selected": true, "text": "<p>WooCommerce adds itself to the customizer as a \"panel\", not a \"section\".</p>\n\n<p>Add this to your <code>my_customize_register()</code> function and it will be gone:</p>\n\n<pre><code>$wp_customize-&gt;remove_panel( 'woocommerce' );\n</code></pre>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"https://github.com/woocommerce/woocommerce/blob/master/includes/customizer/class-wc-shop-customizer.php#L31\" rel=\"nofollow noreferrer\"><code>woocommerce/includes/customizer/class-wc-shop-customizer.php</code> line 31</a></li>\n</ul>\n\n<p>As a rule of thumb, when you want to remove something (a customizer section, an action or filter, etc.) looking for how it is added in the first place is a good first step. More often than not it will point you in the right direction.<br>\nThere are as many ways to remove things as there are to add them, and the right way to remove something often depends on how it was added.</p>\n" } ]
2018/02/08
[ "https://wordpress.stackexchange.com/questions/293543", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135161/" ]
[![WooCommerce panel in Customizer](https://i.stack.imgur.com/wUqky.png)](https://i.stack.imgur.com/wUqky.png) I have used the below code to remove other items from Customizer. But unable to remove the WooCommerce section. ``` function my_customize_register() { global $wp_customize; $wp_customize->remove_section( 'colors' ); $wp_customize->remove_section( 'static_front_page' ); $wp_customize->remove_section( 'background_image' ); $wp_customize->remove_section( 'themes' ); $wp_customize->remove_section( 'header_image'); } add_action( 'customize_register', 'my_customize_register', 11 ); add_action('admin_menu', 'remove_unnecessary_wordpress_menus', 999); function remove_unnecessary_wordpress_menus(){ global $submenu; foreach($submenu['themes.php'] as $menu_index => $theme_menu){ if($theme_menu[0] == 'Header' || $theme_menu[0] == 'Background') unset($submenu['themes.php'][$menu_index]); } } ```
WooCommerce adds itself to the customizer as a "panel", not a "section". Add this to your `my_customize_register()` function and it will be gone: ``` $wp_customize->remove_panel( 'woocommerce' ); ``` References: * [`woocommerce/includes/customizer/class-wc-shop-customizer.php` line 31](https://github.com/woocommerce/woocommerce/blob/master/includes/customizer/class-wc-shop-customizer.php#L31) As a rule of thumb, when you want to remove something (a customizer section, an action or filter, etc.) looking for how it is added in the first place is a good first step. More often than not it will point you in the right direction. There are as many ways to remove things as there are to add them, and the right way to remove something often depends on how it was added.
293,546
<p>I'm installing Multisite for a fair-sized business, who's WordPress website has been running for around 5 years.</p> <p>When trying to install it, I am receiving the following warning message:</p> <p>"Because your installation is not new, the sites in your WordPress network must use sub-domains. The main site in a sub-directory installation will need to use a modified permalink structure, potentially breaking existing links."</p> <p>Sub-domains are not an option for us. The main site is mysite.co.uk, and the websites will be mysite.com/fr, mysite.com/pt, etc.</p> <p>What are my options?</p> <p>Is there any way around this without causing serious SEO/Google issues, which is what I assume the warning refers to?</p> <p>Thanks James</p>
[ { "answer_id": 323441, "author": "keepkalm", "author_id": 26744, "author_profile": "https://wordpress.stackexchange.com/users/26744", "pm_score": 2, "selected": false, "text": "<p>You should just start with a new install and import the existing site into the new install. </p>\n\n<p>Starting with an existing install triggers that warning but if you start fresh you can setup the subfolder structure. </p>\n\n<p>You can add this to functions.php to allow a subfolder install in multisite:</p>\n\n<pre><code> add_filter( 'allow_subdirectory_install',\ncreate_function( '', 'return true;' )\n);\n</code></pre>\n\n<p>Untested by me, use at your own risk (test server), and let me know how it works! I am recommending new install and migration as a cleaner solution. <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow noreferrer\">Duplicator</a> is pretty simple to import your content. </p>\n" }, { "answer_id": 383633, "author": "Albert Peschar", "author_id": 68287, "author_profile": "https://wordpress.stackexchange.com/users/68287", "pm_score": 2, "selected": false, "text": "<p>Add this to your <code>wp-config.php</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('ALLOW_SUBDIRECTORY_INSTALL', true);\n</code></pre>\n" } ]
2018/02/08
[ "https://wordpress.stackexchange.com/questions/293546", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127880/" ]
I'm installing Multisite for a fair-sized business, who's WordPress website has been running for around 5 years. When trying to install it, I am receiving the following warning message: "Because your installation is not new, the sites in your WordPress network must use sub-domains. The main site in a sub-directory installation will need to use a modified permalink structure, potentially breaking existing links." Sub-domains are not an option for us. The main site is mysite.co.uk, and the websites will be mysite.com/fr, mysite.com/pt, etc. What are my options? Is there any way around this without causing serious SEO/Google issues, which is what I assume the warning refers to? Thanks James
You should just start with a new install and import the existing site into the new install. Starting with an existing install triggers that warning but if you start fresh you can setup the subfolder structure. You can add this to functions.php to allow a subfolder install in multisite: ``` add_filter( 'allow_subdirectory_install', create_function( '', 'return true;' ) ); ``` Untested by me, use at your own risk (test server), and let me know how it works! I am recommending new install and migration as a cleaner solution. [Duplicator](https://wordpress.org/plugins/duplicator/) is pretty simple to import your content.
293,557
<p>I'm running a multilingual site, and I want the emails sent to the user to be in their language. The scheme I already have is the following:</p> <ol> <li>The website determines the user's country through their IP.</li> <li>The website redirects the user to the site's version of the language of their country (eg. if the IP detected is from France, then it redirects the user to a WPML french version of the site).</li> </ol> <p>The problem is that I want to have emails translated as well, based on the IP of the user. (eg. the user registers through <a href="https://mysite/fr/signup" rel="nofollow noreferrer">https://mysite/fr/signup</a>, then the email sent to him for completing his registration should be in French.)</p> <p>I have WPML and Loco Translate activated for translation, along with Geo Redirect to redirect users to various site's languages.</p> <p>Is this achievable? and how?</p>
[ { "answer_id": 323441, "author": "keepkalm", "author_id": 26744, "author_profile": "https://wordpress.stackexchange.com/users/26744", "pm_score": 2, "selected": false, "text": "<p>You should just start with a new install and import the existing site into the new install. </p>\n\n<p>Starting with an existing install triggers that warning but if you start fresh you can setup the subfolder structure. </p>\n\n<p>You can add this to functions.php to allow a subfolder install in multisite:</p>\n\n<pre><code> add_filter( 'allow_subdirectory_install',\ncreate_function( '', 'return true;' )\n);\n</code></pre>\n\n<p>Untested by me, use at your own risk (test server), and let me know how it works! I am recommending new install and migration as a cleaner solution. <a href=\"https://wordpress.org/plugins/duplicator/\" rel=\"nofollow noreferrer\">Duplicator</a> is pretty simple to import your content. </p>\n" }, { "answer_id": 383633, "author": "Albert Peschar", "author_id": 68287, "author_profile": "https://wordpress.stackexchange.com/users/68287", "pm_score": 2, "selected": false, "text": "<p>Add this to your <code>wp-config.php</code>:</p>\n<pre class=\"lang-php prettyprint-override\"><code>define('ALLOW_SUBDIRECTORY_INSTALL', true);\n</code></pre>\n" } ]
2018/02/08
[ "https://wordpress.stackexchange.com/questions/293557", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136502/" ]
I'm running a multilingual site, and I want the emails sent to the user to be in their language. The scheme I already have is the following: 1. The website determines the user's country through their IP. 2. The website redirects the user to the site's version of the language of their country (eg. if the IP detected is from France, then it redirects the user to a WPML french version of the site). The problem is that I want to have emails translated as well, based on the IP of the user. (eg. the user registers through <https://mysite/fr/signup>, then the email sent to him for completing his registration should be in French.) I have WPML and Loco Translate activated for translation, along with Geo Redirect to redirect users to various site's languages. Is this achievable? and how?
You should just start with a new install and import the existing site into the new install. Starting with an existing install triggers that warning but if you start fresh you can setup the subfolder structure. You can add this to functions.php to allow a subfolder install in multisite: ``` add_filter( 'allow_subdirectory_install', create_function( '', 'return true;' ) ); ``` Untested by me, use at your own risk (test server), and let me know how it works! I am recommending new install and migration as a cleaner solution. [Duplicator](https://wordpress.org/plugins/duplicator/) is pretty simple to import your content.
293,559
<p>I have recently installed WordPress Multisite on my local dev environment.</p> <p>The original website, mysite.co.uk, however no longer displays any pages which were in the /includes folder.</p> <p>Anything in the normal pages directory works fine. It is just pages from the /includes subdirectory which have suddenly stopped working.</p> <p>Any ideas what I might be doing wrong?</p> <p>My htaccess file contains the following:</p> <pre><code>RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^wp-admin$ wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^(wp-(content|admin|includes).*) $1 [L] RewriteRule ^(.*\.php)$ $1 [L] RewriteRule . index.php [L] </code></pre> <p>My wp-config file contains the following:</p> <pre><code>define( 'WP_ALLOW_MULTISITE', true ); define('MULTISITE', true); define('SUBDOMAIN_INSTALL', true); define('DOMAIN_CURRENT_SITE', 'local.mysite.co.uk'); define('PATH_CURRENT_SITE', '/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); </code></pre> <p>Thanks James</p>
[ { "answer_id": 293560, "author": "rugbert", "author_id": 19536, "author_profile": "https://wordpress.stackexchange.com/users/19536", "pm_score": 0, "selected": false, "text": "<p>I'm guessing that 1 of 2 things is happening</p>\n\n<ol>\n<li>your .htaccess file might be misconfigured</li>\n<li>your wpconfig file does not have the proper settings</li>\n</ol>\n\n<p>For information on site configurations needed for mutlisite, check out this page: <a href=\"https://codex.wordpress.org/Multisite_Network_Administration\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Multisite_Network_Administration</a> </p>\n" }, { "answer_id": 293641, "author": "iwillbeawebdeveloper", "author_id": 127880, "author_profile": "https://wordpress.stackexchange.com/users/127880", "pm_score": 2, "selected": true, "text": "<p>The problem was caused by the change to permalinks.</p>\n\n<p>When I changed it to /%category%/%postname%/, it worked.</p>\n" } ]
2018/02/08
[ "https://wordpress.stackexchange.com/questions/293559", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127880/" ]
I have recently installed WordPress Multisite on my local dev environment. The original website, mysite.co.uk, however no longer displays any pages which were in the /includes folder. Anything in the normal pages directory works fine. It is just pages from the /includes subdirectory which have suddenly stopped working. Any ideas what I might be doing wrong? My htaccess file contains the following: ``` RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^wp-admin$ wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^(wp-(content|admin|includes).*) $1 [L] RewriteRule ^(.*\.php)$ $1 [L] RewriteRule . index.php [L] ``` My wp-config file contains the following: ``` define( 'WP_ALLOW_MULTISITE', true ); define('MULTISITE', true); define('SUBDOMAIN_INSTALL', true); define('DOMAIN_CURRENT_SITE', 'local.mysite.co.uk'); define('PATH_CURRENT_SITE', '/'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); ``` Thanks James
The problem was caused by the change to permalinks. When I changed it to /%category%/%postname%/, it worked.
293,603
<p>I am using a plugin <code>Chargebee WP Membership</code> to connect up to their API to process payments. At the moment they are only using shortcodes to restrict content. </p> <p>What I am trying to do, is output the functions of these shortcodes inside the page template. So far I've attempted the <code>do_shortcode</code> method but would rather access the function directly.</p> <p>Github file: <a href="https://github.com/brendenplugin/chargebee-wp-membership-plugin/blob/master/admin/helper/class-chargebee-membership-shortcodes.php" rel="nofollow noreferrer">https://github.com/brendenplugin/chargebee-wp-membership-plugin/blob/master/admin/helper/class-chargebee-membership-shortcodes.php</a></p> <p>For <code>cb_content_show</code> the shortcode format is currently:</p> <pre><code>[cb_content_show level="1"] This content will be shown to any users who have plan associated with Level 1 [/cb_content_show] </code></pre> <p>What is the best method to access this function directly? I believe it derives from the function <code>render_content_show_hide()</code> - Line 707</p> <pre><code>public function render_content_show_hide( $attr, $content = null, $shortcode_name = '' ) { ... </code></pre> <p>Ideally I'd like to access as the function for example:</p> <pre><code>&lt;?php if (cb_content_show('level') == 1) : //do something endif; ?&gt; </code></pre>
[ { "answer_id": 293606, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 1, "selected": false, "text": "<p>Looks like function <code>render_content_show_hide()</code> is a method of class. If you want access this function directly - you can create new class instance.</p>\n\n<p>If your plugin code looks like:</p>\n\n<pre><code>class Shortcode_Builder{\n //...methods\n public function render_content_show_hide( $attr, $content = null, $shortcode_name = '' ) { \n //...\n }\n\n //...other methods.\n\n\n}\n</code></pre>\n\n<p>Create new instance</p>\n\n<pre><code>$builder = new Shortcode_Builder();\n</code></pre>\n\n<p>And access to your function <code>$builder-&gt;render_content_show_hide()</code></p>\n" }, { "answer_id": 293677, "author": "scopeak", "author_id": 87036, "author_profile": "https://wordpress.stackexchange.com/users/87036", "pm_score": 1, "selected": true, "text": "<p>Managed to get it working by accessing the <code>get_user_meta</code> values. </p>\n\n<pre><code>&lt;?php \n$user_id = get_current_user_id();\n$key = 'chargebee_user_subscriptions';\n$all_meta_for_user = get_user_meta( $user_id, $key, true );\nprint_r($all_meta_for_user);\n</code></pre>\n" } ]
2018/02/09
[ "https://wordpress.stackexchange.com/questions/293603", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87036/" ]
I am using a plugin `Chargebee WP Membership` to connect up to their API to process payments. At the moment they are only using shortcodes to restrict content. What I am trying to do, is output the functions of these shortcodes inside the page template. So far I've attempted the `do_shortcode` method but would rather access the function directly. Github file: <https://github.com/brendenplugin/chargebee-wp-membership-plugin/blob/master/admin/helper/class-chargebee-membership-shortcodes.php> For `cb_content_show` the shortcode format is currently: ``` [cb_content_show level="1"] This content will be shown to any users who have plan associated with Level 1 [/cb_content_show] ``` What is the best method to access this function directly? I believe it derives from the function `render_content_show_hide()` - Line 707 ``` public function render_content_show_hide( $attr, $content = null, $shortcode_name = '' ) { ... ``` Ideally I'd like to access as the function for example: ``` <?php if (cb_content_show('level') == 1) : //do something endif; ?> ```
Managed to get it working by accessing the `get_user_meta` values. ``` <?php $user_id = get_current_user_id(); $key = 'chargebee_user_subscriptions'; $all_meta_for_user = get_user_meta( $user_id, $key, true ); print_r($all_meta_for_user); ```
293,610
<p>I have a query based on two parameters on a multilingual website (with WPML). To simplify, let's say that one of my filter is the language of the post to retrieve : English, French or all languages. English and French are working fine but I can't make the "all languages" filter work.</p> <p>Here is my code:</p> <pre><code>&lt;?php // First I get the "lang" Get value $langGet = get_query_var('lang', ICL_LANGUAGE_CODE); ?&gt; /* Then have my form to filter posts */ &lt;form action="&lt;?php echo get_permalink( get_the_ID() ); ?&gt;" method="get"&gt; &lt;label for="lang"&gt;&lt;?php _e( 'Languages', 'mytextdomain' ); ?&gt;&lt;/label&gt; &lt;?php $languages = apply_filters( 'wpml_active_languages', NULL ); if($languages) { ?&gt; &lt;select name="lang"&gt; &lt;?php foreach($languages as $language) : ?&gt; &lt;option value="&lt;?php echo $language['language_code']; ?&gt;" &lt;?php echo ( $langGet == $language['language_code'] ) ? 'selected' : ''; ?&gt;&gt;&lt;?php echo $language['translated_name']; ?&gt;&lt;/option&gt; &lt;?php endforeach; ?&gt; &lt;option value="all" &lt;?php echo ( $langGet == 'all' ) ? 'selected' : ''; ?&gt;&gt;&lt;?php _e('All languages', 'mytextdomain'); ?&gt;&lt;/option&gt; &lt;/select&gt; &lt;?php } ?&gt; &lt;input type="submit" value="&lt;?php _e( 'Filter projects', 'mytextdomain' ); ?&gt;"&gt; &lt;/form&gt; &lt;?php // Then I set up the switch for current language if($langGet != 'all') { global $sitepress; $current_lang = $sitepress-&gt;get_current_language(); $sitepress-&gt;switch_lang($langGet, true); } // Then I define my query // Here is the line that is supposed to show all languages but it's not working. $filters = ( $langGet == 'all' ) ? true : false; $taxId = apply_filters( 'wpml_object_id', 755, 'project_category' ); $paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1; $args = array( 'posts_per_page' =&gt; 16, 'post_type' =&gt; 'projects', 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'project_category', 'field' =&gt; 'term_id', 'terms' =&gt; $taxId, ) ), 'orderby' =&gt; 'date', 'order' =&gt; 'ASC', 'paged' =&gt; $paged, 'suppress_filters' =&gt; $filters ); $projects = new WP_Query($args); </code></pre> <p>But this is not showing all languages. Moreover I noticed that a <code>#038;lang=all</code> gets added at the end of my url when I am on page 2.</p> <p>Can someone help me on this? Thanks!</p>
[ { "answer_id": 294054, "author": "Ravinder Kumar", "author_id": 74268, "author_profile": "https://wordpress.stackexchange.com/users/74268", "pm_score": 0, "selected": false, "text": "<p>Please check this article from wpml</p>\n\n<p><a href=\"https://wpml.org/forums/topic/problems-to-show-in-all-languages-suppress_filters-true-not-working/\" rel=\"nofollow noreferrer\">https://wpml.org/forums/topic/problems-to-show-in-all-languages-suppress_filters-true-not-working/</a></p>\n" }, { "answer_id": 294524, "author": "Pipo", "author_id": 54879, "author_profile": "https://wordpress.stackexchange.com/users/54879", "pm_score": 3, "selected": true, "text": "<p>So I've made it work. The problem was not with the filter but with tax query. Here is the solution for those who might be interested.</p>\n\n<pre><code>&lt;?php\n// I check the lang query var if it's empty we'll display all languages\n$langGet = get_query_var('lang', 'all');\n?&gt;\n\n/* Then have my form to filter posts */\n&lt;form action=\"&lt;?php echo get_permalink( get_the_ID() ); ?&gt;\" method=\"get\"&gt;\n &lt;label for=\"lang\"&gt;&lt;?php _e( 'Languages', 'mytextdomain' ); ?&gt;&lt;/label&gt;\n &lt;?php\n $languages = apply_filters( 'wpml_active_languages', NULL );\n if($languages) { ?&gt;\n &lt;select name=\"lang\"&gt;\n &lt;?php foreach($languages as $language) : ?&gt;\n &lt;option value=\"&lt;?php echo $language['language_code']; ?&gt;\" &lt;?php echo ( $langGet == $language['language_code'] ) ? 'selected' : ''; ?&gt;&gt;&lt;?php echo $language['translated_name']; ?&gt;&lt;/option&gt;\n &lt;?php endforeach; ?&gt;\n &lt;option value=\"all\" &lt;?php echo ( $langGet == 'all' ) ? 'selected' : ''; ?&gt;&gt;&lt;?php _e('All languages', 'mytextdomain'); ?&gt;&lt;/option&gt;\n &lt;/select&gt;\n &lt;?php } ?&gt;\n &lt;input type=\"submit\" value=\"&lt;?php _e( 'Filter projects', 'mytextdomain' ); ?&gt;\"&gt;\n&lt;/form&gt;\n\n&lt;?php\n// Then I set up the switch for current language\nif( $langGet != 'all' ) {\n global $sitepress;\n $current_lang = $sitepress-&gt;get_current_language();\n $sitepress-&gt;switch_lang($langGet, true);\n $taxTerms = array( apply_filters( 'wpml_object_id', 755, 'project_category' ) );\n $filters = false;\n} else {\n // If we want to display all languages we have to remove filters\n global $sitepress;\n remove_filter( 'get_terms_args', array( $sitepress, 'get_terms_args_filter' ), 10 );\n remove_filter( 'get_term', array( $sitepress, 'get_term_adjust_id' ), 1 );\n remove_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ), 10 );\n $taxTerms = array( 755, 776, 777, 778 );\n $filters = true;\n}\n\n$paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1;\n\n// Then we set the query\n$args = array(\n 'posts_per_page' =&gt; $postsperpage,\n 'post_type' =&gt; 'projects',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'project_category',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; $taxTerms\n )\n ),\n 'orderby' =&gt; $orderby,\n 'order' =&gt; $order,\n 'meta_key' =&gt; $metakey,\n 'paged' =&gt; $paged,\n 'suppress_filters' =&gt; $filters\n);\n$projects = new WP_Query($args); \n</code></pre>\n" } ]
2018/02/09
[ "https://wordpress.stackexchange.com/questions/293610", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54879/" ]
I have a query based on two parameters on a multilingual website (with WPML). To simplify, let's say that one of my filter is the language of the post to retrieve : English, French or all languages. English and French are working fine but I can't make the "all languages" filter work. Here is my code: ``` <?php // First I get the "lang" Get value $langGet = get_query_var('lang', ICL_LANGUAGE_CODE); ?> /* Then have my form to filter posts */ <form action="<?php echo get_permalink( get_the_ID() ); ?>" method="get"> <label for="lang"><?php _e( 'Languages', 'mytextdomain' ); ?></label> <?php $languages = apply_filters( 'wpml_active_languages', NULL ); if($languages) { ?> <select name="lang"> <?php foreach($languages as $language) : ?> <option value="<?php echo $language['language_code']; ?>" <?php echo ( $langGet == $language['language_code'] ) ? 'selected' : ''; ?>><?php echo $language['translated_name']; ?></option> <?php endforeach; ?> <option value="all" <?php echo ( $langGet == 'all' ) ? 'selected' : ''; ?>><?php _e('All languages', 'mytextdomain'); ?></option> </select> <?php } ?> <input type="submit" value="<?php _e( 'Filter projects', 'mytextdomain' ); ?>"> </form> <?php // Then I set up the switch for current language if($langGet != 'all') { global $sitepress; $current_lang = $sitepress->get_current_language(); $sitepress->switch_lang($langGet, true); } // Then I define my query // Here is the line that is supposed to show all languages but it's not working. $filters = ( $langGet == 'all' ) ? true : false; $taxId = apply_filters( 'wpml_object_id', 755, 'project_category' ); $paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1; $args = array( 'posts_per_page' => 16, 'post_type' => 'projects', 'tax_query' => array( array( 'taxonomy' => 'project_category', 'field' => 'term_id', 'terms' => $taxId, ) ), 'orderby' => 'date', 'order' => 'ASC', 'paged' => $paged, 'suppress_filters' => $filters ); $projects = new WP_Query($args); ``` But this is not showing all languages. Moreover I noticed that a `#038;lang=all` gets added at the end of my url when I am on page 2. Can someone help me on this? Thanks!
So I've made it work. The problem was not with the filter but with tax query. Here is the solution for those who might be interested. ``` <?php // I check the lang query var if it's empty we'll display all languages $langGet = get_query_var('lang', 'all'); ?> /* Then have my form to filter posts */ <form action="<?php echo get_permalink( get_the_ID() ); ?>" method="get"> <label for="lang"><?php _e( 'Languages', 'mytextdomain' ); ?></label> <?php $languages = apply_filters( 'wpml_active_languages', NULL ); if($languages) { ?> <select name="lang"> <?php foreach($languages as $language) : ?> <option value="<?php echo $language['language_code']; ?>" <?php echo ( $langGet == $language['language_code'] ) ? 'selected' : ''; ?>><?php echo $language['translated_name']; ?></option> <?php endforeach; ?> <option value="all" <?php echo ( $langGet == 'all' ) ? 'selected' : ''; ?>><?php _e('All languages', 'mytextdomain'); ?></option> </select> <?php } ?> <input type="submit" value="<?php _e( 'Filter projects', 'mytextdomain' ); ?>"> </form> <?php // Then I set up the switch for current language if( $langGet != 'all' ) { global $sitepress; $current_lang = $sitepress->get_current_language(); $sitepress->switch_lang($langGet, true); $taxTerms = array( apply_filters( 'wpml_object_id', 755, 'project_category' ) ); $filters = false; } else { // If we want to display all languages we have to remove filters global $sitepress; remove_filter( 'get_terms_args', array( $sitepress, 'get_terms_args_filter' ), 10 ); remove_filter( 'get_term', array( $sitepress, 'get_term_adjust_id' ), 1 ); remove_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ), 10 ); $taxTerms = array( 755, 776, 777, 778 ); $filters = true; } $paged = (get_query_var('paged')) ? absint(get_query_var('paged')) : 1; // Then we set the query $args = array( 'posts_per_page' => $postsperpage, 'post_type' => 'projects', 'tax_query' => array( array( 'taxonomy' => 'project_category', 'field' => 'term_id', 'terms' => $taxTerms ) ), 'orderby' => $orderby, 'order' => $order, 'meta_key' => $metakey, 'paged' => $paged, 'suppress_filters' => $filters ); $projects = new WP_Query($args); ```
293,655
<p>I am using this code to count number of posts for one custom post type. </p> <p>What's the best way to change this to sum up together 3 different custom post types?</p> <pre><code>function get_all_them_ven_posts(){ $post_type = 'restaurants'; $count_posts = wp_count_posts( $post_type ); $published_posts = $count_posts-&gt;publish; return $published_posts; } </code></pre>
[ { "answer_id": 293663, "author": "Nathan Johnson", "author_id": 106269, "author_profile": "https://wordpress.stackexchange.com/users/106269", "pm_score": 3, "selected": true, "text": "<p>Why not just get the count for each post type and sum them?</p>\n\n<pre><code>function get_all_them_ven_posts(){\n $count= 0;\n $post_types = [ 'postType1', 'postType2', 'postType3' ];\n foreach( $post_types as $post_type ) {\n $count_posts = wp_count_posts( $post_type );\n $count = $count + $count_posts-&gt;publish;\n }\n return $count;\n}\n</code></pre>\n" }, { "answer_id": 293664, "author": "Nicolai Grossherr", "author_id": 22534, "author_profile": "https://wordpress.stackexchange.com/users/22534", "pm_score": 0, "selected": false, "text": "<p>I was curious, so I <a href=\"http://php.net/manual/de/function.microtime.php\" rel=\"nofollow noreferrer\"><code>microtime</code></a>d it with three post types and about 120 posts shared across them. Comparing three <a href=\"https://developer.wordpress.org/reference/functions/wp_count_posts/\" rel=\"nofollow noreferrer\"><code>wp_count_posts()</code></a> calls with one <a href=\"https://developer.wordpress.org/reference/functions/get_posts/\" rel=\"nofollow noreferrer\"><code>get_posts()</code></a> call. If you make use of the <code>fields</code> parameter of the latter, with the value <code>ids</code>, then they are about the same speed, otherwise it is 30 times slower. The <code>get_posts()</code> method is possibly in the 95% rang in comparison, so it might be a little bit faster, but I didn't run nearly enough iterations to have a conclusive result. So I would say you can do it either way.</p>\n\n<pre><code>// use either\n$p1c = wp_count_posts( 'post-type-1' )-&gt;publish;\n$p2c = wp_count_posts( 'post-type-2' )-&gt;publish;\n$p3c = wp_count_posts( 'post-type-3' )-&gt;publish;\n$res = $p1c + $p2c + $p3c;\n//alternatively\n$pts = [ 'product', 'post', 'page' ];\n$res = 0;\nforeach ( $pts as $pt) {\n $res = $res + wp_count_posts( $pt )-&gt;publish;\n}\n\n// or use this\n$res = count( get_posts( [ \n 'post_type' =&gt; [ 'product', 'post', 'page' ], \n 'posts_per_page' =&gt; -1, \n 'fields' =&gt; 'ids' \n] ) );\n</code></pre>\n" }, { "answer_id": 293700, "author": "Abhay Yadav", "author_id": 136553, "author_profile": "https://wordpress.stackexchange.com/users/136553", "pm_score": 0, "selected": false, "text": "<p>Get total number of post in custom post type</p>\n\n<pre><code>$args = array( 'post_type' =&gt; 'custompost', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1);\n$loop = new WP_Query( $args );\n$total = $loop-&gt;found_posts;\necho $total;\n</code></pre>\n" } ]
2018/02/09
[ "https://wordpress.stackexchange.com/questions/293655", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40727/" ]
I am using this code to count number of posts for one custom post type. What's the best way to change this to sum up together 3 different custom post types? ``` function get_all_them_ven_posts(){ $post_type = 'restaurants'; $count_posts = wp_count_posts( $post_type ); $published_posts = $count_posts->publish; return $published_posts; } ```
Why not just get the count for each post type and sum them? ``` function get_all_them_ven_posts(){ $count= 0; $post_types = [ 'postType1', 'postType2', 'postType3' ]; foreach( $post_types as $post_type ) { $count_posts = wp_count_posts( $post_type ); $count = $count + $count_posts->publish; } return $count; } ```
293,661
<p>I have a site with around 8000 products, with a slightly poor site structure - instead of custom taxonomies the Brand Name and Retailer are Parent Categories with the various individual brands, and retailers as sub categories.</p> <p>Brands (Cat ID 187 - around 300 brands as sub cats)</p> <ul> <li>Brand 1</li> <li>Brand 2</li> <li>Brand 3 etc</li> </ul> <p>Retailers (Cat ID 186 - around 20 retailers as sub cats)</p> <ul> <li>Retailer 1</li> <li>Retailer 2</li> <li>Retailer 3 etc</li> </ul> <p>I have a list of the individual brands and retailers individual subcat IDs, and for site maintenance was wondering if there was a way to display all posts which are accidentally assigned to more than one retailer, or more than one brand?</p> <p>I've found solutions for locating all posts assigned to 2 specific categories, but not any that can display posts which appear in any 2 of the categories featured in a long array.</p> <p>Or alternatively any posts which belong to 2 or more sub categories of a certain parent ID - if that's less complicated than one long array of sub cat IDs?</p> <p>It doesn't matter if it's slow, as it's only me who'll be seeing the output in order to maintain the website.</p> <p>If anyone can give me any pointers, I'd be very grateful - Thank you in advance :)</p> <p>Joey</p> <p>Edit: The only quick solution I can think of would be to output all posts IDs with a comma separated list of categories that they belong to, then remove all the non relevant categories with search and replace (or do this with the initial query), and then import this data into Excel and see which posts had more than 2 columns for Brand and Retailer? Was wondering if there was a more elegant solution than this? Thanks</p>
[ { "answer_id": 293666, "author": "Colin Smillie", "author_id": 136396, "author_profile": "https://wordpress.stackexchange.com/users/136396", "pm_score": 2, "selected": false, "text": "<p>I think I'd setup a loop for all posts and the do something like this inside the loop:</p>\n\n<pre><code>$post_cats = get_the_category();\n$brand_cats = 0;\n$retail_cats = 0;\nforeach ( $post_cats as $post_cat ) {\n if ($post_cat-&gt;category_parent == 187) {\n $brand_cats++;\n if ($post_cat-&gt;category_parent == 186) {\n $retail_cats++;\n }\n}\nif ( $brand_cats &gt; 1 )\n echo \"Duplicate Brand for Post #\".get_the_ID;\nif ( $retail_cats &gt; 1 )\n echo \"Duplicate Retailer for Post #\".get_the_ID;\n</code></pre>\n\n<p>The code is untested but should give you the general approach.</p>\n" }, { "answer_id": 293710, "author": "Joey", "author_id": 115825, "author_profile": "https://wordpress.stackexchange.com/users/115825", "pm_score": 0, "selected": false, "text": "<p>Thanks to Colin, I've managed to work the following answer:</p>\n\n<pre><code> &lt;?php\n$id = get_the_ID();\n$post_cats = get_the_category();\n$brand_cats = 0;\n$retail_cats = 0;\nforeach ( $post_cats as $post_cat ) {\n if ($post_cat-&gt;category_parent == 187) {\n $brand_cats++; }\n if ($post_cat-&gt;category_parent == 186) {\n $retail_cats++;\n }\n}\nif ( $brand_cats &gt; 1 ) {\n echo \"Multiple Brands \";\n echo $id;\n echo \"&lt;br&gt;\";\n } else {\n echo \"\";\n}\n\nif ( $retail_cats &gt; 1 ) {\n echo \"Multiple Retailers \";\n echo $id;\n echo \"&lt;br&gt;\";\n } else {\n echo \"\";\n}\n ?&gt;\n</code></pre>\n\n<p>and then use that within WP Query to select the posts I need to search - this outputs a list of post IDs together with whether the issue is too many retailer categories, or too many brands.</p>\n" } ]
2018/02/09
[ "https://wordpress.stackexchange.com/questions/293661", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115825/" ]
I have a site with around 8000 products, with a slightly poor site structure - instead of custom taxonomies the Brand Name and Retailer are Parent Categories with the various individual brands, and retailers as sub categories. Brands (Cat ID 187 - around 300 brands as sub cats) * Brand 1 * Brand 2 * Brand 3 etc Retailers (Cat ID 186 - around 20 retailers as sub cats) * Retailer 1 * Retailer 2 * Retailer 3 etc I have a list of the individual brands and retailers individual subcat IDs, and for site maintenance was wondering if there was a way to display all posts which are accidentally assigned to more than one retailer, or more than one brand? I've found solutions for locating all posts assigned to 2 specific categories, but not any that can display posts which appear in any 2 of the categories featured in a long array. Or alternatively any posts which belong to 2 or more sub categories of a certain parent ID - if that's less complicated than one long array of sub cat IDs? It doesn't matter if it's slow, as it's only me who'll be seeing the output in order to maintain the website. If anyone can give me any pointers, I'd be very grateful - Thank you in advance :) Joey Edit: The only quick solution I can think of would be to output all posts IDs with a comma separated list of categories that they belong to, then remove all the non relevant categories with search and replace (or do this with the initial query), and then import this data into Excel and see which posts had more than 2 columns for Brand and Retailer? Was wondering if there was a more elegant solution than this? Thanks
I think I'd setup a loop for all posts and the do something like this inside the loop: ``` $post_cats = get_the_category(); $brand_cats = 0; $retail_cats = 0; foreach ( $post_cats as $post_cat ) { if ($post_cat->category_parent == 187) { $brand_cats++; if ($post_cat->category_parent == 186) { $retail_cats++; } } if ( $brand_cats > 1 ) echo "Duplicate Brand for Post #".get_the_ID; if ( $retail_cats > 1 ) echo "Duplicate Retailer for Post #".get_the_ID; ``` The code is untested but should give you the general approach.
293,667
<p>I'm sorry to be asking a question that's (from what I've gathered) asked with relative frequency, but I think I've complicated the problem by leaving a project and then coming back to it after my skills have gotten rusty. So, in a very basic theme I created a while ago for a friend, I used PHP in the stylesheet to create some variables so that colors of certain elements can be randomized. The way I achieved this was to name the stylesheet <code>style.php</code> (as opposed to CSS), and included <code>&lt;?php header("Content-type: text/css; charset: UTF-8"); ?&gt;</code> at the top of the file.</p> <p>This worked great at the time, but since I completed it, my friend has stopped using their website, and I decided I'd use the theme for my own personal site. I got a ManagedWP GoDaddy account and uploaded the theme, but now it is <em>not</em> working. Here is where I'm having trouble diagnosing the problem. The most obvious problem to me is that something is causing WordPress to no longer like using a PHP stylesheet, so one thing I've tried is to rename the stylesheet to <code>style.css</code> and then modify <code>.htaccess</code> to get it to be parsed as PHP. Modifying <code>.htaccess</code> is a new thing to me, so I may be doing something silly in there, but I've been using <a href="http://jafty.com/blog/tag/use-php-to-create-css-in-wordpress/" rel="nofollow noreferrer">this</a> article as a guide, and now the <code>.htaccess</code> in the theme's directory (the same directory level as <code>style.css</code>) reads as such:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress &lt;FilesMatch "^.*?style.*?$"&gt; SetHandler php5-script &lt;/FilesMatch&gt; </code></pre> <p>However, I'm still not achieving the same result as before when WordPress seemed to be fine with using a PHP stylesheet, and I'm at a loss with what the right questions are to ask. I have a feeling a large part of this is retracing my steps, but I'm not sure which direction to go! Any help would be greatly appreciated!</p>
[ { "answer_id": 293673, "author": "C C", "author_id": 83299, "author_profile": "https://wordpress.stackexchange.com/users/83299", "pm_score": 2, "selected": false, "text": "<p>Suggest you move your desired functionality to javascript; you are so badly attempting to overload the purpose of these constructs...even if you get it to work you are going to have a very fragile and difficult to maintain system on your hands. </p>\n\n<p>Note that the idea of inlining style may work -- but future Content Security Policy may kill that idea...inline CSS is a weak spot; see this <a href=\"https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.234_-_CSS_Escape_And_Strictly_Validate_Before_Inserting_Untrusted_Data_into_HTML_Style_Property_Values\" rel=\"nofollow noreferrer\">OWASP explanation</a> for more information.</p>\n" }, { "answer_id": 293674, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>At this point in wordpress life it is just something you should not do (and should not have done in the first place). Experience shows that this kind of CSS file is very fragile* and easily breaks when wordpress related server setup is not the vanilla one, something that is probably true with all managed services.</p>\n\n<p>Just add whatever you want as an inline style in your theme using the <code>wp_head</code> hook. (no, they are not a weak spot and it will not get killed in any future, unless someone will want to break all sites on the internet)</p>\n\n<p>*this kind of files were known to have security problems, and break when directory structure changed</p>\n" }, { "answer_id": 293745, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 1, "selected": false, "text": "<p>(You appear to have 2 WordPress code blocks for some reason...?! I assume that's some kind of copy/paste error in your question?)</p>\n\n<blockquote>\n <p>and now the <code>.htaccess</code> in the theme's directory (the same directory level as style.css) reads as</p>\n</blockquote>\n\n<p>Creating multiple <code>.htaccess</code> files in different directories is likely to cause more problems. (Is this why you have duplicated the WP front-controller?) You should add the relevant directives to the main <code>.htaccess</code> file in the document root, but be careful of the ordering.</p>\n\n<blockquote>\n <p>something is causing WordPress to no longer like using a PHP stylesheet<br>\n :<br>\n WordPress seemed to be fine with using a PHP stylesheet</p>\n</blockquote>\n\n<p>WordPress itself shouldn't have anything to do with the CSS/PHP file. However, your \"ManagedWP\" hosting may have additional security that is preventing these \"rogue\" (or rather, non-WordPress) PHP files being parsed?</p>\n\n<blockquote>\n<pre><code>&lt;FilesMatch \"^.*?style.*?$\"&gt;\nSetHandler php5-script\n&lt;/FilesMatch&gt;\n</code></pre>\n</blockquote>\n\n<p>Parsing all files that simply contain the word \"style\" as PHP could potentially cause problems. However, using <code>SetHandler</code> can be very server specific, so this may not work anyway.</p>\n\n<p>An alternative is to keep the file named <code>style.php</code> (ie. with a <code>.php</code> file extension), but reference this as <code>style.css</code> in your HTML. Then, using mod_rewrite in <code>.htaccess</code> internally rewrite a request for <code>style.css</code> to <code>style.php</code> <em>before</em> the WordPress front-controller.</p>\n\n<p>For example:</p>\n\n<pre><code>RewriteRule ^url-path/to/style\\.css$ /filesystem-path/to/style.php [L]\n</code></pre>\n\n<p>(Stress... this must go <em>before</em> the WordPress front-controller.)</p>\n" } ]
2018/02/09
[ "https://wordpress.stackexchange.com/questions/293667", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102900/" ]
I'm sorry to be asking a question that's (from what I've gathered) asked with relative frequency, but I think I've complicated the problem by leaving a project and then coming back to it after my skills have gotten rusty. So, in a very basic theme I created a while ago for a friend, I used PHP in the stylesheet to create some variables so that colors of certain elements can be randomized. The way I achieved this was to name the stylesheet `style.php` (as opposed to CSS), and included `<?php header("Content-type: text/css; charset: UTF-8"); ?>` at the top of the file. This worked great at the time, but since I completed it, my friend has stopped using their website, and I decided I'd use the theme for my own personal site. I got a ManagedWP GoDaddy account and uploaded the theme, but now it is *not* working. Here is where I'm having trouble diagnosing the problem. The most obvious problem to me is that something is causing WordPress to no longer like using a PHP stylesheet, so one thing I've tried is to rename the stylesheet to `style.css` and then modify `.htaccess` to get it to be parsed as PHP. Modifying `.htaccess` is a new thing to me, so I may be doing something silly in there, but I've been using [this](http://jafty.com/blog/tag/use-php-to-create-css-in-wordpress/) article as a guide, and now the `.htaccess` in the theme's directory (the same directory level as `style.css`) reads as such: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress <FilesMatch "^.*?style.*?$"> SetHandler php5-script </FilesMatch> ``` However, I'm still not achieving the same result as before when WordPress seemed to be fine with using a PHP stylesheet, and I'm at a loss with what the right questions are to ask. I have a feeling a large part of this is retracing my steps, but I'm not sure which direction to go! Any help would be greatly appreciated!
Suggest you move your desired functionality to javascript; you are so badly attempting to overload the purpose of these constructs...even if you get it to work you are going to have a very fragile and difficult to maintain system on your hands. Note that the idea of inlining style may work -- but future Content Security Policy may kill that idea...inline CSS is a weak spot; see this [OWASP explanation](https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.234_-_CSS_Escape_And_Strictly_Validate_Before_Inserting_Untrusted_Data_into_HTML_Style_Property_Values) for more information.
293,698
<p>I have this action: </p> <pre><code>add_action( 'wp_enqueue_scripts', 'my_custom_script_load3' ); function my_custom_script_load3(){ wp_enqueue_script( 'my-custom-script3', '/members/user.js' ); } </code></pre> <p>It works great when I have it in functions.php of my root directory WordPress installation. </p> <p>But I also have a second WordPress installation which is in it's own directory, on the root:</p> <p>/second-wordpress-site/</p> <p>I have this action also installed in this second WordPress site in functions.php</p> <p>In this second WordPress site, the action keeps pulling the script up like:</p> <p>/second-wordpress-site/members/user.js </p> <p>instead of how it should be: </p> <p>/members/user.js </p> <p>Any suggestions on the correct syntax for the site, so the path is correct? </p> <p>I've tried several path variations, with no luck.</p> <p>Thanks for any help.</p>
[ { "answer_id": 293673, "author": "C C", "author_id": 83299, "author_profile": "https://wordpress.stackexchange.com/users/83299", "pm_score": 2, "selected": false, "text": "<p>Suggest you move your desired functionality to javascript; you are so badly attempting to overload the purpose of these constructs...even if you get it to work you are going to have a very fragile and difficult to maintain system on your hands. </p>\n\n<p>Note that the idea of inlining style may work -- but future Content Security Policy may kill that idea...inline CSS is a weak spot; see this <a href=\"https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.234_-_CSS_Escape_And_Strictly_Validate_Before_Inserting_Untrusted_Data_into_HTML_Style_Property_Values\" rel=\"nofollow noreferrer\">OWASP explanation</a> for more information.</p>\n" }, { "answer_id": 293674, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>At this point in wordpress life it is just something you should not do (and should not have done in the first place). Experience shows that this kind of CSS file is very fragile* and easily breaks when wordpress related server setup is not the vanilla one, something that is probably true with all managed services.</p>\n\n<p>Just add whatever you want as an inline style in your theme using the <code>wp_head</code> hook. (no, they are not a weak spot and it will not get killed in any future, unless someone will want to break all sites on the internet)</p>\n\n<p>*this kind of files were known to have security problems, and break when directory structure changed</p>\n" }, { "answer_id": 293745, "author": "MrWhite", "author_id": 8259, "author_profile": "https://wordpress.stackexchange.com/users/8259", "pm_score": 1, "selected": false, "text": "<p>(You appear to have 2 WordPress code blocks for some reason...?! I assume that's some kind of copy/paste error in your question?)</p>\n\n<blockquote>\n <p>and now the <code>.htaccess</code> in the theme's directory (the same directory level as style.css) reads as</p>\n</blockquote>\n\n<p>Creating multiple <code>.htaccess</code> files in different directories is likely to cause more problems. (Is this why you have duplicated the WP front-controller?) You should add the relevant directives to the main <code>.htaccess</code> file in the document root, but be careful of the ordering.</p>\n\n<blockquote>\n <p>something is causing WordPress to no longer like using a PHP stylesheet<br>\n :<br>\n WordPress seemed to be fine with using a PHP stylesheet</p>\n</blockquote>\n\n<p>WordPress itself shouldn't have anything to do with the CSS/PHP file. However, your \"ManagedWP\" hosting may have additional security that is preventing these \"rogue\" (or rather, non-WordPress) PHP files being parsed?</p>\n\n<blockquote>\n<pre><code>&lt;FilesMatch \"^.*?style.*?$\"&gt;\nSetHandler php5-script\n&lt;/FilesMatch&gt;\n</code></pre>\n</blockquote>\n\n<p>Parsing all files that simply contain the word \"style\" as PHP could potentially cause problems. However, using <code>SetHandler</code> can be very server specific, so this may not work anyway.</p>\n\n<p>An alternative is to keep the file named <code>style.php</code> (ie. with a <code>.php</code> file extension), but reference this as <code>style.css</code> in your HTML. Then, using mod_rewrite in <code>.htaccess</code> internally rewrite a request for <code>style.css</code> to <code>style.php</code> <em>before</em> the WordPress front-controller.</p>\n\n<p>For example:</p>\n\n<pre><code>RewriteRule ^url-path/to/style\\.css$ /filesystem-path/to/style.php [L]\n</code></pre>\n\n<p>(Stress... this must go <em>before</em> the WordPress front-controller.)</p>\n" } ]
2018/02/10
[ "https://wordpress.stackexchange.com/questions/293698", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/134788/" ]
I have this action: ``` add_action( 'wp_enqueue_scripts', 'my_custom_script_load3' ); function my_custom_script_load3(){ wp_enqueue_script( 'my-custom-script3', '/members/user.js' ); } ``` It works great when I have it in functions.php of my root directory WordPress installation. But I also have a second WordPress installation which is in it's own directory, on the root: /second-wordpress-site/ I have this action also installed in this second WordPress site in functions.php In this second WordPress site, the action keeps pulling the script up like: /second-wordpress-site/members/user.js instead of how it should be: /members/user.js Any suggestions on the correct syntax for the site, so the path is correct? I've tried several path variations, with no luck. Thanks for any help.
Suggest you move your desired functionality to javascript; you are so badly attempting to overload the purpose of these constructs...even if you get it to work you are going to have a very fragile and difficult to maintain system on your hands. Note that the idea of inlining style may work -- but future Content Security Policy may kill that idea...inline CSS is a weak spot; see this [OWASP explanation](https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.234_-_CSS_Escape_And_Strictly_Validate_Before_Inserting_Untrusted_Data_into_HTML_Style_Property_Values) for more information.
293,714
<p>I have a code in my theme's stylesheet that looks like this. I would like for my code to not use the width property that is set in here. Deleting is not the option as that would be only temporary solution until the next update of my theme. What can i do, so that this with property is not used?</p> <pre><code>@media (max-width: 991px) and (min-width: 544px){ .footer-bottom-widgets .columns { position: relative; float: left; min-height: 1px; padding-left: .9375rem; padding-right: .9375rem; width:33.333%; } } </code></pre>
[ { "answer_id": 293716, "author": "C C", "author_id": 83299, "author_profile": "https://wordpress.stackexchange.com/users/83299", "pm_score": 2, "selected": false, "text": "<p>Research the the topic <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">creating a child theme</a> - this will enable you to continue to use the unchanged parent (original) theme, but have your modifications in a separate directory structure. </p>\n\n<p>The parent theme will continue to have the ability to be updated, but you can also do whatever you want to override/change the style or even page template components, if you wish to.</p>\n\n<p>Your use case is one of the reasons the child theme mechanism is in place.</p>\n\n<p>See <a href=\"https://wordpress.stackexchange.com/questions/163301/versioning-import-of-parent-themes-style-css\">this topic</a> as well, as it discusses the correct handling of .css components.</p>\n" }, { "answer_id": 293757, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": true, "text": "<p>I would not suggest creating a child theme to override a single CSS line. You can simply use the theme customizer and add your CSS to the additional CSS box. Most CSS properties accept an <code>unset</code> or <code>inherit</code> value. So, you can paste the following code into the additional CSS box:</p>\n\n<pre><code>@media (max-width: 991px) and (min-width: 544px){\n .footer-bottom-widgets .columns {\n width: unset;\n }\n}\n</code></pre>\n\n<p>Since the additional CSS is added as inline, the priority is higher than the original CSS, which will override the original styles.</p>\n" } ]
2018/02/10
[ "https://wordpress.stackexchange.com/questions/293714", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136588/" ]
I have a code in my theme's stylesheet that looks like this. I would like for my code to not use the width property that is set in here. Deleting is not the option as that would be only temporary solution until the next update of my theme. What can i do, so that this with property is not used? ``` @media (max-width: 991px) and (min-width: 544px){ .footer-bottom-widgets .columns { position: relative; float: left; min-height: 1px; padding-left: .9375rem; padding-right: .9375rem; width:33.333%; } } ```
I would not suggest creating a child theme to override a single CSS line. You can simply use the theme customizer and add your CSS to the additional CSS box. Most CSS properties accept an `unset` or `inherit` value. So, you can paste the following code into the additional CSS box: ``` @media (max-width: 991px) and (min-width: 544px){ .footer-bottom-widgets .columns { width: unset; } } ``` Since the additional CSS is added as inline, the priority is higher than the original CSS, which will override the original styles.
293,742
<p>I have one custom post type 'team' to create and display team-members and all works fine (screenshot how it needs to look):</p> <p><a href="https://i.stack.imgur.com/XcVCl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XcVCl.png" alt="enter image description here"></a></p> <p>In admin panel user entries team member position into input field and attach featured image and publish post and all works fine.</p> <p>but last item of the list of team member it's image with link "SEND CV" when all previous items it's image with team member position without any links. So I need to create another custom post type just for this one image with link or it's any way I can change last post to have link instead of position?</p> <p>Here is my query:</p> <pre><code>&lt;?php $query = new WP_Query(array( 'post_type' =&gt; array('team'), 'orderby' =&gt; 'menu_order', 'order' =&gt; 'ASC', )); if ($query-&gt;have_posts()) { while ($query-&gt;have_posts()) { $query-&gt;the_post(); ?&gt; &lt;li class="col-lg-3 d-flex text-center"&gt; &lt;div class="team-member-wrapper text-center mx-auto"&gt; &lt;div class="img-border"&gt; &lt;?php the_post_thumbnail('full', array('class' =&gt; 'team-member-img img-fluid')); ?&gt; &lt;/div&gt; &lt;?php echo '&lt;span class="team-member-position"&gt;' . get_post_meta(get_the_ID(), 'position', true) . '&lt;/span&gt;'; ?&gt; &lt;/div&gt; &lt;/li&gt; &lt;?php } } else { } wp_reset_query(); wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 293763, "author": "Joel M", "author_id": 93297, "author_profile": "https://wordpress.stackexchange.com/users/93297", "pm_score": 0, "selected": false, "text": "<p>add a link field to every team member and do an if else statement in your loop. if the link field is there... link it, otherwise don't. </p>\n" }, { "answer_id": 293775, "author": "Aqib Ashef", "author_id": 84179, "author_profile": "https://wordpress.stackexchange.com/users/84179", "pm_score": 1, "selected": false, "text": "<p>Here are some options I think you can try:</p>\n\n<h3>First Option: </h3>\n\n<p>If you always have that element in your archive page, you can add this element at the end of the list outside the loop. It should look something like this: </p>\n\n<pre><code>&lt;?php\n $query = new WP_Query(array(\n 'post_type' =&gt; array('team'),\n 'orderby' =&gt; 'menu_order',\n 'order' =&gt; 'ASC',\n ));\n\n if ($query-&gt;have_posts()) {\n while ($query-&gt;have_posts()) {\n $query-&gt;the_post(); ?&gt;\n\n &lt;li class=\"col-lg-3 d-flex text-center\"&gt;\n &lt;div class=\"team-member-wrapper text-center mx-auto\"&gt;\n &lt;div class=\"img-border\"&gt;\n &lt;?php\n the_post_thumbnail('full', array('class' =&gt; 'team-member-img img-fluid'));\n ?&gt;\n &lt;/div&gt;\n &lt;?php\n echo '&lt;span class=\"team-member-position\"&gt;' . get_post_meta(get_the_ID(), 'position', true) . '&lt;/span&gt;';\n ?&gt;\n &lt;/div&gt;\n &lt;/li&gt;\n &lt;?php\n }\n ?&gt;\n &lt;!-- This is where your last Send CV Element will go --&gt;\n &lt;?php\n} else {\n\n}\nwp_reset_query();\nwp_reset_postdata(); ?&gt;\n</code></pre>\n\n<h3>2nd Option</h3>\n\n<p>You can add a meta box in the post editor and create a send cv post and mark it as a send cv type. Then you can check for it in the front end.</p>\n" } ]
2018/02/10
[ "https://wordpress.stackexchange.com/questions/293742", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135678/" ]
I have one custom post type 'team' to create and display team-members and all works fine (screenshot how it needs to look): [![enter image description here](https://i.stack.imgur.com/XcVCl.png)](https://i.stack.imgur.com/XcVCl.png) In admin panel user entries team member position into input field and attach featured image and publish post and all works fine. but last item of the list of team member it's image with link "SEND CV" when all previous items it's image with team member position without any links. So I need to create another custom post type just for this one image with link or it's any way I can change last post to have link instead of position? Here is my query: ``` <?php $query = new WP_Query(array( 'post_type' => array('team'), 'orderby' => 'menu_order', 'order' => 'ASC', )); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); ?> <li class="col-lg-3 d-flex text-center"> <div class="team-member-wrapper text-center mx-auto"> <div class="img-border"> <?php the_post_thumbnail('full', array('class' => 'team-member-img img-fluid')); ?> </div> <?php echo '<span class="team-member-position">' . get_post_meta(get_the_ID(), 'position', true) . '</span>'; ?> </div> </li> <?php } } else { } wp_reset_query(); wp_reset_postdata(); ?> ```
Here are some options I think you can try: ### First Option: If you always have that element in your archive page, you can add this element at the end of the list outside the loop. It should look something like this: ``` <?php $query = new WP_Query(array( 'post_type' => array('team'), 'orderby' => 'menu_order', 'order' => 'ASC', )); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); ?> <li class="col-lg-3 d-flex text-center"> <div class="team-member-wrapper text-center mx-auto"> <div class="img-border"> <?php the_post_thumbnail('full', array('class' => 'team-member-img img-fluid')); ?> </div> <?php echo '<span class="team-member-position">' . get_post_meta(get_the_ID(), 'position', true) . '</span>'; ?> </div> </li> <?php } ?> <!-- This is where your last Send CV Element will go --> <?php } else { } wp_reset_query(); wp_reset_postdata(); ?> ``` ### 2nd Option You can add a meta box in the post editor and create a send cv post and mark it as a send cv type. Then you can check for it in the front end.
293,747
<p>I have this script that cuts down my menu and adds a "+" dropdown if there are too many menu items in an attempt to prettify long menus, as such:</p> <p><a href="https://i.stack.imgur.com/7ZRGm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7ZRGm.png" alt="Menu With the Script"></a></p> <p>Without the script running:</p> <p><a href="https://i.stack.imgur.com/HR308.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HR308.png" alt="Menu Without the Script"></a></p> <p>Which I call in <code>functions.php</code> with:</p> <pre><code>function _s_scripts() { wp_enqueue_script( 'main', get_template_directory_uri() . '/js/main_res.js', array( 'jquery' ), '', false ); } add_action( 'wp_enqueue_scripts', '_s_scripts' ); </code></pre> <p>Unfortunately, this results in late-execution and jagginess. Is there any way I can hook this script into "as soon as you're done generating X part (menu)" do this?</p> <p>The effect is very noticeable for the user:</p> <p><a href="https://imgur.com/aoFcYKe" rel="nofollow noreferrer">https://imgur.com/aoFcYKe</a></p> <p>and here's the script, just for testing purposes, <code>main_res.js</code>:</p> <pre><code>function sliceMenu(desired_len) { var menu_len = document.querySelectorAll('#primary-menu &gt; li').length; if (menu_len &gt; desired_len) { var append_menu_el = document.createElement('div'); append_menu_el.innerHTML = ('&lt;div id="js-cover-menu"&gt;&lt;img class="plus" src="$PATH/svg/plus_menu.svg" alt="more-menu"&gt;&lt;/div&gt;').replace('$PATH', ABSPATH); document.getElementById('primary-menu').parentNode.appendChild(append_menu_el); let diff = menu_len - desired_len; let sliced_lis = [...(document.querySelectorAll('#primary-menu &gt; li'))].slice(-diff); var js_menu_el = document.createElement('ul'); js_menu_el.setAttribute('id', 'js-cover-menu-dropdown'); document.getElementById('js-cover-menu').appendChild(js_menu_el); js_cover_menu_el = document.getElementById('js-cover-menu-dropdown'); for(var i = 0, length = sliced_lis.length; i &lt; length; i++) { js_cover_menu_el.appendChild(sliced_lis[i]); } document.querySelectorAll('#js-cover-menu-dropdown &gt; li &gt; ul').forEach(node =&gt; node.remove()); } else { return; } } </code></pre>
[ { "answer_id": 293763, "author": "Joel M", "author_id": 93297, "author_profile": "https://wordpress.stackexchange.com/users/93297", "pm_score": 0, "selected": false, "text": "<p>add a link field to every team member and do an if else statement in your loop. if the link field is there... link it, otherwise don't. </p>\n" }, { "answer_id": 293775, "author": "Aqib Ashef", "author_id": 84179, "author_profile": "https://wordpress.stackexchange.com/users/84179", "pm_score": 1, "selected": false, "text": "<p>Here are some options I think you can try:</p>\n\n<h3>First Option: </h3>\n\n<p>If you always have that element in your archive page, you can add this element at the end of the list outside the loop. It should look something like this: </p>\n\n<pre><code>&lt;?php\n $query = new WP_Query(array(\n 'post_type' =&gt; array('team'),\n 'orderby' =&gt; 'menu_order',\n 'order' =&gt; 'ASC',\n ));\n\n if ($query-&gt;have_posts()) {\n while ($query-&gt;have_posts()) {\n $query-&gt;the_post(); ?&gt;\n\n &lt;li class=\"col-lg-3 d-flex text-center\"&gt;\n &lt;div class=\"team-member-wrapper text-center mx-auto\"&gt;\n &lt;div class=\"img-border\"&gt;\n &lt;?php\n the_post_thumbnail('full', array('class' =&gt; 'team-member-img img-fluid'));\n ?&gt;\n &lt;/div&gt;\n &lt;?php\n echo '&lt;span class=\"team-member-position\"&gt;' . get_post_meta(get_the_ID(), 'position', true) . '&lt;/span&gt;';\n ?&gt;\n &lt;/div&gt;\n &lt;/li&gt;\n &lt;?php\n }\n ?&gt;\n &lt;!-- This is where your last Send CV Element will go --&gt;\n &lt;?php\n} else {\n\n}\nwp_reset_query();\nwp_reset_postdata(); ?&gt;\n</code></pre>\n\n<h3>2nd Option</h3>\n\n<p>You can add a meta box in the post editor and create a send cv post and mark it as a send cv type. Then you can check for it in the front end.</p>\n" } ]
2018/02/10
[ "https://wordpress.stackexchange.com/questions/293747", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133461/" ]
I have this script that cuts down my menu and adds a "+" dropdown if there are too many menu items in an attempt to prettify long menus, as such: [![Menu With the Script](https://i.stack.imgur.com/7ZRGm.png)](https://i.stack.imgur.com/7ZRGm.png) Without the script running: [![Menu Without the Script](https://i.stack.imgur.com/HR308.png)](https://i.stack.imgur.com/HR308.png) Which I call in `functions.php` with: ``` function _s_scripts() { wp_enqueue_script( 'main', get_template_directory_uri() . '/js/main_res.js', array( 'jquery' ), '', false ); } add_action( 'wp_enqueue_scripts', '_s_scripts' ); ``` Unfortunately, this results in late-execution and jagginess. Is there any way I can hook this script into "as soon as you're done generating X part (menu)" do this? The effect is very noticeable for the user: <https://imgur.com/aoFcYKe> and here's the script, just for testing purposes, `main_res.js`: ``` function sliceMenu(desired_len) { var menu_len = document.querySelectorAll('#primary-menu > li').length; if (menu_len > desired_len) { var append_menu_el = document.createElement('div'); append_menu_el.innerHTML = ('<div id="js-cover-menu"><img class="plus" src="$PATH/svg/plus_menu.svg" alt="more-menu"></div>').replace('$PATH', ABSPATH); document.getElementById('primary-menu').parentNode.appendChild(append_menu_el); let diff = menu_len - desired_len; let sliced_lis = [...(document.querySelectorAll('#primary-menu > li'))].slice(-diff); var js_menu_el = document.createElement('ul'); js_menu_el.setAttribute('id', 'js-cover-menu-dropdown'); document.getElementById('js-cover-menu').appendChild(js_menu_el); js_cover_menu_el = document.getElementById('js-cover-menu-dropdown'); for(var i = 0, length = sliced_lis.length; i < length; i++) { js_cover_menu_el.appendChild(sliced_lis[i]); } document.querySelectorAll('#js-cover-menu-dropdown > li > ul').forEach(node => node.remove()); } else { return; } } ```
Here are some options I think you can try: ### First Option: If you always have that element in your archive page, you can add this element at the end of the list outside the loop. It should look something like this: ``` <?php $query = new WP_Query(array( 'post_type' => array('team'), 'orderby' => 'menu_order', 'order' => 'ASC', )); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); ?> <li class="col-lg-3 d-flex text-center"> <div class="team-member-wrapper text-center mx-auto"> <div class="img-border"> <?php the_post_thumbnail('full', array('class' => 'team-member-img img-fluid')); ?> </div> <?php echo '<span class="team-member-position">' . get_post_meta(get_the_ID(), 'position', true) . '</span>'; ?> </div> </li> <?php } ?> <!-- This is where your last Send CV Element will go --> <?php } else { } wp_reset_query(); wp_reset_postdata(); ?> ``` ### 2nd Option You can add a meta box in the post editor and create a send cv post and mark it as a send cv type. Then you can check for it in the front end.
293,751
<p>I am using the ACF plugin for custom posts types and am fairly new to using it. I have a field called "app_url" that is a url that I need to include as a link in my header.php file so it is on all pages, the custom post type is called "slider". If I just use </p> <pre><code>&lt;a&gt;&lt;?php get_field('app_url'); ?&gt;&lt;/&gt; </code></pre> <p>It doesn't work. I also tried </p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'slider'); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); &lt;a&gt;&lt;?php get_field('app_url'); ?&gt;&lt;/&gt; endwhile; ?&gt; </code></pre> <p>which gives me a blank page. I'm fairly new to the concept of loops and am wondering if you can even have a loop in a header if there is another one in the page.php content and maybe that's why that wouldn't work.</p>
[ { "answer_id": 293754, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>I'm observing three problems here.</p>\n\n<h2>1- Your anchors do not have a <code>href</code> attribute.</h2>\n\n<p>As you mentioned, the <code>app_url</code> field is a URL, and should be output in the <code>href</code> attribute of an anchor. So, this is how your anchor should look like:</p>\n\n<pre><code>&lt;a href=\"&lt;?php echo esc_url( get_field( 'app_url' ) ); ?&gt;\"&gt;My Link&lt;/a&gt;\n</code></pre>\n\n<p>Note that I've also escaped the value by using the <a href=\"https://codex.wordpress.org/Function_Reference/esc_url\" rel=\"nofollow noreferrer\"><code>esc_url()</code></a> function, to eliminate invalid characters.</p>\n\n<h2>2- The <code>get_field()</code> function accepts a post ID.</h2>\n\n<p>The second parameter of the <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\"><code>get_field()</code></a> function accepts a post ID. So, let's pass it to the function in the loop:</p>\n\n<pre><code>&lt;?php \n\n $args = array( 'post_type' =&gt; 'slider');\n $loop = new WP_Query( $args );\n while ( $loop-&gt;have_posts() ) : \n $loop-&gt;the_post(); ?&gt;\n &lt;a href=\"&lt;?php echo esc_url( get_field( 'app_url', get_the_ID() ) ); ?&gt;\"&gt;\n &lt;?php the_title(); ?&gt;\n &lt;/a&gt;&lt;?php\n endwhile; \n\n?&gt;\n</code></pre>\n\n<h2>3- You forgot to use the PHP tags</h2>\n\n<p>Note that you didn't have opening and closing PHP tags around your anchors in the loop ( The <code>&lt;?php</code> and <code>?&gt;</code> tags ), and there was a missing <code>a</code> in your closing <code>&lt;/a&gt;</code> tag.</p>\n" }, { "answer_id": 293784, "author": "Developer.Sumit", "author_id": 118194, "author_profile": "https://wordpress.stackexchange.com/users/118194", "pm_score": 0, "selected": false, "text": "<p><strong>You can also try this coding to fetch the post-type module according to Ascending(ASC) or Descending(DESC):-</strong></p>\n\n<pre><code>&lt;?php\n $args=array(\n 'post_type' =&gt; 'slider',\n 'post_status' =&gt; 'publish',\n 'order' =&gt; 'ASC',\n 'posts_per_page' =&gt; -1\n );\n $myposts = null;\n $myposts = new WP_Query($args);\n if( $myposts-&gt;have_posts() ) {\n $i=0;\n while ($myposts-&gt;have_posts()) : $myposts-&gt;the_post();\n $i=$i+1;\n ?&gt;\n &lt;a href=\"&lt;?php echo get_field('app_url'); ?&gt;\"&gt;link&lt;/a&gt;\n &lt;!-- or --&gt;\n &lt;a href=\"&lt;?php echo esc_url( get_field( 'app_url' ) ); ?&gt;\"&gt; link&lt;/a&gt;\n &lt;?php\n endwhile;\n }\n ?&gt;\n</code></pre>\n" } ]
2018/02/11
[ "https://wordpress.stackexchange.com/questions/293751", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127290/" ]
I am using the ACF plugin for custom posts types and am fairly new to using it. I have a field called "app\_url" that is a url that I need to include as a link in my header.php file so it is on all pages, the custom post type is called "slider". If I just use ``` <a><?php get_field('app_url'); ?></> ``` It doesn't work. I also tried ``` <?php $args = array( 'post_type' => 'slider'); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); <a><?php get_field('app_url'); ?></> endwhile; ?> ``` which gives me a blank page. I'm fairly new to the concept of loops and am wondering if you can even have a loop in a header if there is another one in the page.php content and maybe that's why that wouldn't work.
I'm observing three problems here. 1- Your anchors do not have a `href` attribute. ----------------------------------------------- As you mentioned, the `app_url` field is a URL, and should be output in the `href` attribute of an anchor. So, this is how your anchor should look like: ``` <a href="<?php echo esc_url( get_field( 'app_url' ) ); ?>">My Link</a> ``` Note that I've also escaped the value by using the [`esc_url()`](https://codex.wordpress.org/Function_Reference/esc_url) function, to eliminate invalid characters. 2- The `get_field()` function accepts a post ID. ------------------------------------------------ The second parameter of the [`get_field()`](https://www.advancedcustomfields.com/resources/get_field/) function accepts a post ID. So, let's pass it to the function in the loop: ``` <?php $args = array( 'post_type' => 'slider'); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <a href="<?php echo esc_url( get_field( 'app_url', get_the_ID() ) ); ?>"> <?php the_title(); ?> </a><?php endwhile; ?> ``` 3- You forgot to use the PHP tags --------------------------------- Note that you didn't have opening and closing PHP tags around your anchors in the loop ( The `<?php` and `?>` tags ), and there was a missing `a` in your closing `</a>` tag.
293,764
<p>I have this function that helps me nicely trim post titles:</p> <pre><code>namespace Helpers; .. function _s_trim_post_title ( $length = null, $delimiter = null ) { $title = get_the_title(); $trimmed_title = mb_strimwidth( $title, 0, $length === null ? BIG_INT : $length, '' // Won't use, bugs out. ); $url = esc_url( get_permalink() ); if( strlen( $title ) == strlen( $trimmed_title ) ) { $delimiter = ''; } $delimiter = $delimiter === null ? '' : (string)$delimiter; $output = '&lt;h2 class="post-title"&gt;&lt;a href="' . $url . '" rel="bookmark"&gt;' . $trimmed_title . $delimiter . '&lt;/a&gt;&lt;/h2&gt;'; return $output; } </code></pre> <p>I call it, on <code>content.php</code> as follows:</p> <pre><code>echo Helpers\_s_trim_post_title(24, '...'); </code></pre> <p>And I was thinking, how about of doing all that with a filter:</p> <pre><code>add_filter( 'the_title', 'Helpers\\_s_trim_post_title', 24, '...'); </code></pre> <p>And now, on my <code>content.php</code>, I'd replace all that stuff with the simple:</p> <p><code>the_title()</code></p> <p>Unfortunately, this breaks the whole server and sends it into a continuous loop.</p> <p>Why?</p>
[ { "answer_id": 293768, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 2, "selected": false, "text": "<p>First of all, please try to understand how filter hooks work inside WordPress. These two functions will help you in this case <a href=\"https://developer.wordpress.org/reference/functions/apply_filters/\" rel=\"nofollow noreferrer\"><code>apply_fitlers()</code></a> and <a href=\"https://developer.wordpress.org/reference/functions/add_filter/\" rel=\"nofollow noreferrer\"><code>add_filter()</code></a></p>\n\n<p>Then please check how <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_title\" rel=\"nofollow noreferrer\"><code>the_title</code></a> filter hook works and what it does and how it does.</p>\n\n<p><code>the_title</code> filter hook is used in lots of places. It's been used in front-end as well as backend and it only works with the title. But you added heading <code>h2</code> tag and anchor <code>a</code> tag with it. You can use <a href=\"https://codex.wordpress.org/Function_Reference/is_admin\" rel=\"nofollow noreferrer\"><code>is_admin()</code></a> conditional function to apply the filter only on front-end. So make sure your <code>the_title</code> filter callback only works with title and does not return any markup.</p>\n\n<p>Your <code>the_title</code> filter hook callback <code>Helpers\\_s_trim_post_title()</code> does not work with the arguments that it gets from the filter hook. And you called <code>get_the_title()</code> template tag inside <code>the_title</code> which became recursive call, an infinite loop! That's why your system isn't working as expected.</p>\n" }, { "answer_id": 293853, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 2, "selected": true, "text": "<p>Here's the correct code snippet. Hope it'll work for you.</p>\n\n<p><strong>Helper function</strong></p>\n\n<pre><code>namespace Helpers;\n..\nfunction _s_trim_content( $content = '', $length = null, $delimiter = null ) {\n $trimmed_content = mb_strimwidth( $content, \n 0, \n is_null( $length ) ? BIG_INT : $length, \n '' // Won't use, bugs out.\n );\n\n if ( mb_strlen( $content ) === mb_strlen( $trimmed_content ) || is_null( $delimiter ) ) {\n $delimiter = '';\n }\n\n return $trimmed_content . $delimiter;\n}\n</code></pre>\n\n<p><strong><code>the_title</code> filter</strong></p>\n\n<pre><code>add_filter( 'the_title', function( $title, $post_id ) {\n if ( 'post' === get_post_type( $post_id ) ) {\n return \\Helpers\\_s_trim_content( $title, 24, '...' );\n }\n return $title;\n}, 10, 2 );\n</code></pre>\n" } ]
2018/02/11
[ "https://wordpress.stackexchange.com/questions/293764", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/133461/" ]
I have this function that helps me nicely trim post titles: ``` namespace Helpers; .. function _s_trim_post_title ( $length = null, $delimiter = null ) { $title = get_the_title(); $trimmed_title = mb_strimwidth( $title, 0, $length === null ? BIG_INT : $length, '' // Won't use, bugs out. ); $url = esc_url( get_permalink() ); if( strlen( $title ) == strlen( $trimmed_title ) ) { $delimiter = ''; } $delimiter = $delimiter === null ? '' : (string)$delimiter; $output = '<h2 class="post-title"><a href="' . $url . '" rel="bookmark">' . $trimmed_title . $delimiter . '</a></h2>'; return $output; } ``` I call it, on `content.php` as follows: ``` echo Helpers\_s_trim_post_title(24, '...'); ``` And I was thinking, how about of doing all that with a filter: ``` add_filter( 'the_title', 'Helpers\\_s_trim_post_title', 24, '...'); ``` And now, on my `content.php`, I'd replace all that stuff with the simple: `the_title()` Unfortunately, this breaks the whole server and sends it into a continuous loop. Why?
Here's the correct code snippet. Hope it'll work for you. **Helper function** ``` namespace Helpers; .. function _s_trim_content( $content = '', $length = null, $delimiter = null ) { $trimmed_content = mb_strimwidth( $content, 0, is_null( $length ) ? BIG_INT : $length, '' // Won't use, bugs out. ); if ( mb_strlen( $content ) === mb_strlen( $trimmed_content ) || is_null( $delimiter ) ) { $delimiter = ''; } return $trimmed_content . $delimiter; } ``` **`the_title` filter** ``` add_filter( 'the_title', function( $title, $post_id ) { if ( 'post' === get_post_type( $post_id ) ) { return \Helpers\_s_trim_content( $title, 24, '...' ); } return $title; }, 10, 2 ); ```
293,771
<p>How to insert new element to existing array in usermeta? This code doesn't work because it makes nested array.</p> <pre><code>$data = array( get_user_meta(2, 'fruits', false), 'apple', 'pear', 'peach' ); update_user_meta(2, 'fruits', $data , false); $sud = get_user_meta(2, 'fruits', false); echo print_r($sud); </code></pre>
[ { "answer_id": 293773, "author": "Aqib Ashef", "author_id": 84179, "author_profile": "https://wordpress.stackexchange.com/users/84179", "pm_score": 1, "selected": false, "text": "<p>try this:</p>\n\n<pre><code>$data = get_user_meta(2, 'fruits', false);\narray_push($data, 'apple', 'pear', 'peach');\nupdate_user_meta(2, 'fruits', $data , false);\n$sud = get_user_meta(2, 'fruits', false);\n\necho print_r($sud);\n</code></pre>\n" }, { "answer_id": 293785, "author": "swissspidy", "author_id": 12404, "author_profile": "https://wordpress.stackexchange.com/users/12404", "pm_score": 3, "selected": true, "text": "<p>Let's analyze your code and what it does.</p>\n\n<p>Assuming that the current fruits stored in the database are 'pineapple' and 'orange', <code>get_user_meta(2, 'fruits', false)</code> will return something like this:</p>\n\n<pre><code>array( array( 'pineapple', 'orange' ) )\n</code></pre>\n\n<p>This is because you passed <code>false</code> as the third argument, <code>$single</code>. The function returns an array if <code>$single</code> is <code>false</code> and the value of the meta data field if <code>$single</code> is <code>true</code> (<a href=\"https://developer.wordpress.org/reference/functions/get_user_meta/\" rel=\"nofollow noreferrer\">docs</a>). That is because there could be multiple <code>fruits</code> entries in the database, so WordPress would return all of them if not explicitly told not to.</p>\n\n<p>Since you only have one meta key storing all your fruits, we don't want a list of all entries. Setting <code>$single</code> to <code>true</code> will result in this:</p>\n\n<pre><code>array( 'pineapple', 'orange' )\n</code></pre>\n\n<p>Let's combine this with your <code>$data</code> array:</p>\n\n<pre><code>$data = array(\n get_user_meta(2, 'fruits', false),\n 'apple',\n 'pear',\n 'peach'\n);\n\n// results in: array( array( array( 'pineapple', 'orange' ) ), 'apple', 'pear', peach' )\n\n$data = array(\n get_user_meta(2, 'fruits', true),\n 'apple',\n 'pear',\n 'peach'\n);\n\n// results in: array( array( 'pineapple', 'orange' ), 'apple', 'pear', peach' )\n</code></pre>\n\n<p>Still not ideal! What you want is one single array containing all fruits. That means you need to <em>merge</em> these arrays:</p>\n\n<pre><code>$data = array_merge(\n get_user_meta(2, 'fruits', true),\n array(\n 'apple',\n 'pear',\n 'peach'\n )\n);\n\n// results in: array( 'pineapple', 'orange', 'apple', 'pear', peach' )\n</code></pre>\n\n<p>Now, we can finally update the user meta accordingly:</p>\n\n<pre><code>update_user_meta(2, 'fruits', $data , false);\n</code></pre>\n\n<p>Here's another <code>false</code> at the fourth position. What does it mean? It's the <code>$prev_value</code> argument. If specified, the function only updates existing metadata entries with the specified value. Otherwise, it updates all entries (<a href=\"https://developer.wordpress.org/reference/functions/update_metadata/\" rel=\"nofollow noreferrer\">docs</a>). Passing <code>false</code> is the same as not specifying anything.</p>\n\n<p>But what if we passed <code>$prev_value</code>? Let's have a look!</p>\n\n<pre><code>update_user_meta( 2, 'fruits', $data , array( 'pineapple', 'orange' ) );\n// does update, because that's what's in the database.\n\nupdate_user_meta( 2, 'fruits', $data );\n// does update as well\n\nupdate_user_meta( 2, 'fruits', $data , array( 'cherry', 'banana' ) );\n// does not update, because that's not what is in the database.\n</code></pre>\n\n<p>In your case, I'd simply use <code>update_user_meta( 2, 'fruits', $data );</code> because WordPress automatically turns it into the third example.</p>\n\n<p>Let's get our updated data from the database again! Remember, you don't want an array of entries, so we use <code>get_user_meta( 2, 'fruits', true )</code></p>\n\n<pre><code>get_user_meta(2, 'fruits', false);\n\n// results in array( 'pineapple', 'orange', 'apple', 'pear', peach' )\n</code></pre>\n\n<p>That's it!</p>\n" } ]
2018/02/11
[ "https://wordpress.stackexchange.com/questions/293771", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136622/" ]
How to insert new element to existing array in usermeta? This code doesn't work because it makes nested array. ``` $data = array( get_user_meta(2, 'fruits', false), 'apple', 'pear', 'peach' ); update_user_meta(2, 'fruits', $data , false); $sud = get_user_meta(2, 'fruits', false); echo print_r($sud); ```
Let's analyze your code and what it does. Assuming that the current fruits stored in the database are 'pineapple' and 'orange', `get_user_meta(2, 'fruits', false)` will return something like this: ``` array( array( 'pineapple', 'orange' ) ) ``` This is because you passed `false` as the third argument, `$single`. The function returns an array if `$single` is `false` and the value of the meta data field if `$single` is `true` ([docs](https://developer.wordpress.org/reference/functions/get_user_meta/)). That is because there could be multiple `fruits` entries in the database, so WordPress would return all of them if not explicitly told not to. Since you only have one meta key storing all your fruits, we don't want a list of all entries. Setting `$single` to `true` will result in this: ``` array( 'pineapple', 'orange' ) ``` Let's combine this with your `$data` array: ``` $data = array( get_user_meta(2, 'fruits', false), 'apple', 'pear', 'peach' ); // results in: array( array( array( 'pineapple', 'orange' ) ), 'apple', 'pear', peach' ) $data = array( get_user_meta(2, 'fruits', true), 'apple', 'pear', 'peach' ); // results in: array( array( 'pineapple', 'orange' ), 'apple', 'pear', peach' ) ``` Still not ideal! What you want is one single array containing all fruits. That means you need to *merge* these arrays: ``` $data = array_merge( get_user_meta(2, 'fruits', true), array( 'apple', 'pear', 'peach' ) ); // results in: array( 'pineapple', 'orange', 'apple', 'pear', peach' ) ``` Now, we can finally update the user meta accordingly: ``` update_user_meta(2, 'fruits', $data , false); ``` Here's another `false` at the fourth position. What does it mean? It's the `$prev_value` argument. If specified, the function only updates existing metadata entries with the specified value. Otherwise, it updates all entries ([docs](https://developer.wordpress.org/reference/functions/update_metadata/)). Passing `false` is the same as not specifying anything. But what if we passed `$prev_value`? Let's have a look! ``` update_user_meta( 2, 'fruits', $data , array( 'pineapple', 'orange' ) ); // does update, because that's what's in the database. update_user_meta( 2, 'fruits', $data ); // does update as well update_user_meta( 2, 'fruits', $data , array( 'cherry', 'banana' ) ); // does not update, because that's not what is in the database. ``` In your case, I'd simply use `update_user_meta( 2, 'fruits', $data );` because WordPress automatically turns it into the third example. Let's get our updated data from the database again! Remember, you don't want an array of entries, so we use `get_user_meta( 2, 'fruits', true )` ``` get_user_meta(2, 'fruits', false); // results in array( 'pineapple', 'orange', 'apple', 'pear', peach' ) ``` That's it!
293,772
<p>This is going to be a big explanation as I don't have any shortcut ways to explain the whole scenario.</p> <p>Let's say I have following category structure. (category ids are withing bracket in front of the each category)</p> <pre><code>First Level 1 (100) Second Level 1 (104) Third Level 1 (108) Third Level 2 (109) Third Level 3 (110) Third Level 4 (111) Second Level 2 (105) Third Level 1 (112) Third Level 2 (113) First Level 2 (101) Second Level 1 (106) Third Level 1 (114) Third Level 2 (115) Third Level 3 (116) Second Level 2 (107) Third Level 1 (117) Third Level 2 (118) First Level 3 (102) First Level 4 (103) </code></pre> <p>I have requirement to give users freedom to select the categories (which I call filters) what they need to see in the blog. So, I have given the same structure for users by pre-selecting all categories, if someone needs to exclude a category then user can untick it. </p> <p>But I have certain logic to show posts according to filters as bellow.</p> <p><strong>How filters work:</strong></p> <p><code>Second Level</code> is an internal level which has nothing to do with user selection, although it helps to keep the hierarchy. Users can only tick the <code>Third Level</code> categories by ticking their parent <code>First Level</code>. If user untick <code>First Level</code> the children are automatically locked.</p> <p><strong>LOGIC:</strong> (I will consider a post for explanation purposes)</p> <p><strong>FIRST RULE:</strong></p> <p>If someone tick <code>First Level</code> category and if it has the children I should go to the second step as bellow.</p> <p>Post will only be shown if at least one of the <code>Third Level</code> category of the post are also ticked in the filters of the user. But this we need to check under each <code>Second Level</code> sections separately. </p> <p>E.g. <code>Third Level 1</code> and <code>Third Level 2</code> are ticked in post (under the <code>First Level 1</code> &amp; <code>Second Level 1</code>)</p> <p>User unticked <code>Third Level 1</code> but ticked <code>Third Level 2</code>, then it will still be shown (green light)</p> <p>But user ticked only <code>Third Level 3</code> (under the <code>First Level 1</code> &amp; <code>Second Level 1</code>) in filters, then the post would not be shown. (red light)</p> <p>So, a post will only be shown if ALL <code>Second Level</code> sections are showing a green light. In above example <code>Second Level 1</code> and <code>Second Level 2</code> (under the <code>First Level 1</code>) should fulfilled the above logic to show the post.</p> <p>Eg: User interested in <code>First Level 1</code> (from filters). Post is also classified as <code>First Level 1</code></p> <p>Then I should go to the second step which I need to check all the <code>Second Level</code> sections fulfilling the above logic.</p> <ul> <li><code>Second Level 1</code> </li> <li><code>Second Level 2</code></li> </ul> <p>If one of the <code>Second Level</code> section shows a red light the deal will not be shown.</p> <p><strong>SECOND RULE:</strong></p> <p>If one of <code>First Level</code> categories doesn’t have any children, then the tick of it self taking as fulfilling the filter requirements. </p> <p><strong>THIRD RULE:</strong></p> <p>When ever any post has fulfilled at least one <code>First Level</code> requirement that considered as the post will be shown on the blog.</p> <p>So that is the logic to show posts on the blog as per the users filter inputs. Now what I really need is to build a <code>WP_Query</code>. Honestly, I have no clue even how to start it as I am not having much experience in Wordpress. But my initial try was with <code>category__in</code> with all the ticked category ids which is not fulfilling the new logic.</p> <p>Any help will be highly appreciate as I am stuck on this for few days now.</p> <p>Thanks in advance.</p> <p><strong>UPDATE 1:</strong></p> <p>if someone untick <code>110</code> &amp; <code>111</code> rest all is considered to be ticked, then the sameple algorithm with <code>tax_query</code> would be like bellow. But in real this is not loading at all. </p> <pre><code>$args = array( 'post_type' =&gt; 'post', 'tax_query' =&gt; array( 'relation' =&gt; 'OR', array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'term_id', 'terms' =&gt; array( 108,109 ), 'operator' =&gt; 'IN', ), array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'term_id', 'terms' =&gt; array( 112,113 ), 'operator' =&gt; 'IN', ) ), array( 'relation' =&gt; 'AND', array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'term_id', 'terms' =&gt; array( 114,115,116 ), 'operator' =&gt; 'IN', ), array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'term_id', 'terms' =&gt; array( 117,118 ), 'operator' =&gt; 'IN', ) ), array( 'taxonomy' =&gt; 'category', 'field' =&gt; 'term_id', 'terms' =&gt; array( 102, 103 ), 'operator' =&gt; 'IN', ), ), ); </code></pre>
[ { "answer_id": 294060, "author": "Vlad Olaru", "author_id": 52726, "author_profile": "https://wordpress.stackexchange.com/users/52726", "pm_score": 1, "selected": false, "text": "<p>The query you need to use is not so complicated as you basically just what to get posts from only certain taxonomies. You are right that you should use the <code>tax_query</code>.</p>\n\n<p>The first thing that you should do is collate all your category IDs in only one array as there is no need for multiple ones since you are only using the <code>IN</code> condition (that means posts that belong to at least one category in the list). It makes code error-prone and slow to have multiple tax queries when one would suffice.</p>\n\n<p>The problem with your query is that you are using a <code>AND</code> relation that is never true in your case (ie. you don't have a post that is <em>at the same time</em> in categories 108 or 109, <em>and</em> in categories 112 or 113).</p>\n\n<p>So I would suggest you use WP_Query args like so:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'post',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; array( 108, 109, 112, 113, 114, 115, 116, 117, 118, 102, 103 ),\n 'operator' =&gt; 'IN',\n ),\n ),\n);\n</code></pre>\n\n<p>I understand that you have a multi-step logic to select the posts to display in certain categories. I have given it some thought and it would be quite cumbersome to implement this logic in a tax query through various AND/OR relationships. I think you should do all of the category selection in PHP and end up with an array of category ids that you would use like above. This will allow you to separate your logic from the actual posts selection.</p>\n" }, { "answer_id": 294500, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 1, "selected": true, "text": "<p>After a long research, the only way I found was, get the results with custom sql query as bellow.</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS blog_posts.* FROM (\nSELECT blog_posts.* FROM blog_posts \nINNER JOIN blog_term_relationships AS tt0 ON (blog_posts.ID = tt0.object_id AND tt0.term_taxonomy_id IN (108,109)) \nINNER JOIN blog_term_relationships AS tt1 ON (blog_posts.ID = tt1.object_id AND tt1.term_taxonomy_id IN (112,113)) \nWHERE blog_posts.post_type = 'post' AND (blog_posts.post_status = 'publish') \nUNION \nSELECT blog_posts.* FROM blog_posts \nINNER JOIN blog_term_relationships AS tt3 ON (blog_posts.ID = tt3.object_id AND tt3.term_taxonomy_id IN (114,115,116)) \nINNER JOIN blog_term_relationships AS tt4 ON (blog_posts.ID = tt4.object_id AND tt4.term_taxonomy_id IN (117,118)) \nWHERE blog_posts.post_type = 'post' AND (blog_posts.post_status = 'publish') ) blog_posts \nGROUP BY blog_posts.ID ORDER BY blog_posts.post_date DESC LIMIT 0, 12;\n</code></pre>\n\n<p>following code was used to retrieve the results as per the <a href=\"https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query</a></p>\n\n<pre><code>$pageposts = $wpdb-&gt;get_results($querystr, OBJECT);\n</code></pre>\n" } ]
2018/02/11
[ "https://wordpress.stackexchange.com/questions/293772", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68403/" ]
This is going to be a big explanation as I don't have any shortcut ways to explain the whole scenario. Let's say I have following category structure. (category ids are withing bracket in front of the each category) ``` First Level 1 (100) Second Level 1 (104) Third Level 1 (108) Third Level 2 (109) Third Level 3 (110) Third Level 4 (111) Second Level 2 (105) Third Level 1 (112) Third Level 2 (113) First Level 2 (101) Second Level 1 (106) Third Level 1 (114) Third Level 2 (115) Third Level 3 (116) Second Level 2 (107) Third Level 1 (117) Third Level 2 (118) First Level 3 (102) First Level 4 (103) ``` I have requirement to give users freedom to select the categories (which I call filters) what they need to see in the blog. So, I have given the same structure for users by pre-selecting all categories, if someone needs to exclude a category then user can untick it. But I have certain logic to show posts according to filters as bellow. **How filters work:** `Second Level` is an internal level which has nothing to do with user selection, although it helps to keep the hierarchy. Users can only tick the `Third Level` categories by ticking their parent `First Level`. If user untick `First Level` the children are automatically locked. **LOGIC:** (I will consider a post for explanation purposes) **FIRST RULE:** If someone tick `First Level` category and if it has the children I should go to the second step as bellow. Post will only be shown if at least one of the `Third Level` category of the post are also ticked in the filters of the user. But this we need to check under each `Second Level` sections separately. E.g. `Third Level 1` and `Third Level 2` are ticked in post (under the `First Level 1` & `Second Level 1`) User unticked `Third Level 1` but ticked `Third Level 2`, then it will still be shown (green light) But user ticked only `Third Level 3` (under the `First Level 1` & `Second Level 1`) in filters, then the post would not be shown. (red light) So, a post will only be shown if ALL `Second Level` sections are showing a green light. In above example `Second Level 1` and `Second Level 2` (under the `First Level 1`) should fulfilled the above logic to show the post. Eg: User interested in `First Level 1` (from filters). Post is also classified as `First Level 1` Then I should go to the second step which I need to check all the `Second Level` sections fulfilling the above logic. * `Second Level 1` * `Second Level 2` If one of the `Second Level` section shows a red light the deal will not be shown. **SECOND RULE:** If one of `First Level` categories doesn’t have any children, then the tick of it self taking as fulfilling the filter requirements. **THIRD RULE:** When ever any post has fulfilled at least one `First Level` requirement that considered as the post will be shown on the blog. So that is the logic to show posts on the blog as per the users filter inputs. Now what I really need is to build a `WP_Query`. Honestly, I have no clue even how to start it as I am not having much experience in Wordpress. But my initial try was with `category__in` with all the ticked category ids which is not fulfilling the new logic. Any help will be highly appreciate as I am stuck on this for few days now. Thanks in advance. **UPDATE 1:** if someone untick `110` & `111` rest all is considered to be ticked, then the sameple algorithm with `tax_query` would be like bellow. But in real this is not loading at all. ``` $args = array( 'post_type' => 'post', 'tax_query' => array( 'relation' => 'OR', array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => array( 108,109 ), 'operator' => 'IN', ), array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => array( 112,113 ), 'operator' => 'IN', ) ), array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => array( 114,115,116 ), 'operator' => 'IN', ), array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => array( 117,118 ), 'operator' => 'IN', ) ), array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => array( 102, 103 ), 'operator' => 'IN', ), ), ); ```
After a long research, the only way I found was, get the results with custom sql query as bellow. ``` SELECT SQL_CALC_FOUND_ROWS blog_posts.* FROM ( SELECT blog_posts.* FROM blog_posts INNER JOIN blog_term_relationships AS tt0 ON (blog_posts.ID = tt0.object_id AND tt0.term_taxonomy_id IN (108,109)) INNER JOIN blog_term_relationships AS tt1 ON (blog_posts.ID = tt1.object_id AND tt1.term_taxonomy_id IN (112,113)) WHERE blog_posts.post_type = 'post' AND (blog_posts.post_status = 'publish') UNION SELECT blog_posts.* FROM blog_posts INNER JOIN blog_term_relationships AS tt3 ON (blog_posts.ID = tt3.object_id AND tt3.term_taxonomy_id IN (114,115,116)) INNER JOIN blog_term_relationships AS tt4 ON (blog_posts.ID = tt4.object_id AND tt4.term_taxonomy_id IN (117,118)) WHERE blog_posts.post_type = 'post' AND (blog_posts.post_status = 'publish') ) blog_posts GROUP BY blog_posts.ID ORDER BY blog_posts.post_date DESC LIMIT 0, 12; ``` following code was used to retrieve the results as per the <https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query> ``` $pageposts = $wpdb->get_results($querystr, OBJECT); ```
293,776
<p>I’m looking to convert around 300 categories, each with advanced custom fields, to a custom taxonomy so I have better website structure.</p> <p>However with all of the plugins I’ve used so far, I can move the terms from the Category taxonomy to the custom taxonomy called Brands, and it keeps the standard WordPress data (Name, slug, description etc) but seems to lose the Advanced Custom Fields and Yoast data associated with that term – but as soon as I move the term back to the original “Category”, the data reappears.</p> <p>I was wondering if anyone knew of a method of bulk converting Categories to a custom taxonomy, so that it keeps access to the ACF/Yoast data?</p> <p>Thank you in advance </p>
[ { "answer_id": 294060, "author": "Vlad Olaru", "author_id": 52726, "author_profile": "https://wordpress.stackexchange.com/users/52726", "pm_score": 1, "selected": false, "text": "<p>The query you need to use is not so complicated as you basically just what to get posts from only certain taxonomies. You are right that you should use the <code>tax_query</code>.</p>\n\n<p>The first thing that you should do is collate all your category IDs in only one array as there is no need for multiple ones since you are only using the <code>IN</code> condition (that means posts that belong to at least one category in the list). It makes code error-prone and slow to have multiple tax queries when one would suffice.</p>\n\n<p>The problem with your query is that you are using a <code>AND</code> relation that is never true in your case (ie. you don't have a post that is <em>at the same time</em> in categories 108 or 109, <em>and</em> in categories 112 or 113).</p>\n\n<p>So I would suggest you use WP_Query args like so:</p>\n\n<pre><code>$args = array(\n 'post_type' =&gt; 'post',\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'category',\n 'field' =&gt; 'term_id',\n 'terms' =&gt; array( 108, 109, 112, 113, 114, 115, 116, 117, 118, 102, 103 ),\n 'operator' =&gt; 'IN',\n ),\n ),\n);\n</code></pre>\n\n<p>I understand that you have a multi-step logic to select the posts to display in certain categories. I have given it some thought and it would be quite cumbersome to implement this logic in a tax query through various AND/OR relationships. I think you should do all of the category selection in PHP and end up with an array of category ids that you would use like above. This will allow you to separate your logic from the actual posts selection.</p>\n" }, { "answer_id": 294500, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 1, "selected": true, "text": "<p>After a long research, the only way I found was, get the results with custom sql query as bellow.</p>\n\n<pre><code>SELECT SQL_CALC_FOUND_ROWS blog_posts.* FROM (\nSELECT blog_posts.* FROM blog_posts \nINNER JOIN blog_term_relationships AS tt0 ON (blog_posts.ID = tt0.object_id AND tt0.term_taxonomy_id IN (108,109)) \nINNER JOIN blog_term_relationships AS tt1 ON (blog_posts.ID = tt1.object_id AND tt1.term_taxonomy_id IN (112,113)) \nWHERE blog_posts.post_type = 'post' AND (blog_posts.post_status = 'publish') \nUNION \nSELECT blog_posts.* FROM blog_posts \nINNER JOIN blog_term_relationships AS tt3 ON (blog_posts.ID = tt3.object_id AND tt3.term_taxonomy_id IN (114,115,116)) \nINNER JOIN blog_term_relationships AS tt4 ON (blog_posts.ID = tt4.object_id AND tt4.term_taxonomy_id IN (117,118)) \nWHERE blog_posts.post_type = 'post' AND (blog_posts.post_status = 'publish') ) blog_posts \nGROUP BY blog_posts.ID ORDER BY blog_posts.post_date DESC LIMIT 0, 12;\n</code></pre>\n\n<p>following code was used to retrieve the results as per the <a href=\"https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query</a></p>\n\n<pre><code>$pageposts = $wpdb-&gt;get_results($querystr, OBJECT);\n</code></pre>\n" } ]
2018/02/11
[ "https://wordpress.stackexchange.com/questions/293776", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/115825/" ]
I’m looking to convert around 300 categories, each with advanced custom fields, to a custom taxonomy so I have better website structure. However with all of the plugins I’ve used so far, I can move the terms from the Category taxonomy to the custom taxonomy called Brands, and it keeps the standard WordPress data (Name, slug, description etc) but seems to lose the Advanced Custom Fields and Yoast data associated with that term – but as soon as I move the term back to the original “Category”, the data reappears. I was wondering if anyone knew of a method of bulk converting Categories to a custom taxonomy, so that it keeps access to the ACF/Yoast data? Thank you in advance
After a long research, the only way I found was, get the results with custom sql query as bellow. ``` SELECT SQL_CALC_FOUND_ROWS blog_posts.* FROM ( SELECT blog_posts.* FROM blog_posts INNER JOIN blog_term_relationships AS tt0 ON (blog_posts.ID = tt0.object_id AND tt0.term_taxonomy_id IN (108,109)) INNER JOIN blog_term_relationships AS tt1 ON (blog_posts.ID = tt1.object_id AND tt1.term_taxonomy_id IN (112,113)) WHERE blog_posts.post_type = 'post' AND (blog_posts.post_status = 'publish') UNION SELECT blog_posts.* FROM blog_posts INNER JOIN blog_term_relationships AS tt3 ON (blog_posts.ID = tt3.object_id AND tt3.term_taxonomy_id IN (114,115,116)) INNER JOIN blog_term_relationships AS tt4 ON (blog_posts.ID = tt4.object_id AND tt4.term_taxonomy_id IN (117,118)) WHERE blog_posts.post_type = 'post' AND (blog_posts.post_status = 'publish') ) blog_posts GROUP BY blog_posts.ID ORDER BY blog_posts.post_date DESC LIMIT 0, 12; ``` following code was used to retrieve the results as per the <https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query> ``` $pageposts = $wpdb->get_results($querystr, OBJECT); ```
293,795
<p>By default, <a href="https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/" rel="nofollow noreferrer">wp_resource_hints()</a> prints hints for <code>s.w.org</code>, I am trying to change the default printed value. I am not trying to get rid of the hook, I indeed need it and want to use it, however witout <code>s.w.org</code>.</p> <pre><code>function resource_hints( $hints, $relation_type ) { if ( 'dns-prefetch' === $relation_type ) { $key = array_search( '//s.w.org', $hints, true ); if ( false !== $key ) { unset( $hints[ $key ] ); } $hints[] = 'http://make.wordpress.org'; } elseif ( 'prerender' === $relation_type ) { $hints[] = 'https://make.wordpress.org/great-again'; } return $hints; } add_filter( 'wp_resource_hints', 'resource_hints', 999, 2 ); </code></pre> <p>The function works for adding values for <code>dns-prefetch</code>, <code>preconnect</code>, <code>prefetch</code>, and <code>prerender</code>, however I cannot get rid or edit the first <code>s.w.org</code> resource hint. How can I do this please?</p>
[ { "answer_id": 293797, "author": "lowtechsun", "author_id": 77054, "author_profile": "https://wordpress.stackexchange.com/users/77054", "pm_score": 2, "selected": false, "text": "<pre><code>var_export( $hints );\n</code></pre>\n\n<p>gave me </p>\n\n<pre><code>array (\n 0 =&gt; 'https://s.w.org/images/core/emoji/2.4/svg/',\n)\n</code></pre>\n\n<p>so that means the array key is not <code>s.w.org</code> but <code>https://s.w.org/images/core/emoji/2.4/svg/</code>.</p>\n\n<p>Changing the function and using the key of the array with the full url did remove the s.w.org hint while still letting me use resource hints.</p>\n\n<pre><code>function resource_hints( $hints, $relation_type ) {\n if ( 'dns-prefetch' === $relation_type ) {\n // Export the value of the $hints variable\n // to see what is inside of it.\n var_export( $hints );\n\n // Knowing that the url is not s.w.org but\n // 'https://s.w.org/images/core/emoji/2.4/svg/'\n // I can search for it in the array\n $key = array_search( 'https://s.w.org/images/core/emoji/2.4/svg/', $hints, true );\n if ( false !== $key ) {\n\n // and here I can unset this key\n unset( $hints[ $key ] );\n }\n\n // while I can add custom, site specific hints here\n $hints[] = 'http://make.wordpress.org';\n\n } elseif ( 'prerender' === $relation_type ) {\n $hints[] = 'https://make.wordpress.org/great-again';\n }\n return $hints;\n}\nadd_filter( 'wp_resource_hints', 'resource_hints', 999, 2 );\n</code></pre>\n" }, { "answer_id": 302123, "author": "Roziel Torres", "author_id": 142643, "author_profile": "https://wordpress.stackexchange.com/users/142643", "pm_score": 1, "selected": false, "text": "<p>I had the same problem.</p>\n\n<p>This worked for me</p>\n\n<pre>\n/* Add anothers dns-prefetches */\nfunction makewp_example_resource_hints( $hints, $relation_type ) {\n if ( 'dns-prefetch' === $relation_type ) {\n $hints[] = '//something.com';\n $hints[] = '//something.net';\n $hints[] = '//something.org';\n }\n\n return $hints;\n}\nadd_filter( 'wp_resource_hints', 'makewp_example_resource_hints', 10, 2 );\n/* Remove s.w.org dns-prefetch */\nadd_filter( 'emoji_svg_url', '__return_false' );\n</pre>\n" } ]
2018/02/11
[ "https://wordpress.stackexchange.com/questions/293795", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77054/" ]
By default, [wp\_resource\_hints()](https://make.wordpress.org/core/2016/07/06/resource-hints-in-4-6/) prints hints for `s.w.org`, I am trying to change the default printed value. I am not trying to get rid of the hook, I indeed need it and want to use it, however witout `s.w.org`. ``` function resource_hints( $hints, $relation_type ) { if ( 'dns-prefetch' === $relation_type ) { $key = array_search( '//s.w.org', $hints, true ); if ( false !== $key ) { unset( $hints[ $key ] ); } $hints[] = 'http://make.wordpress.org'; } elseif ( 'prerender' === $relation_type ) { $hints[] = 'https://make.wordpress.org/great-again'; } return $hints; } add_filter( 'wp_resource_hints', 'resource_hints', 999, 2 ); ``` The function works for adding values for `dns-prefetch`, `preconnect`, `prefetch`, and `prerender`, however I cannot get rid or edit the first `s.w.org` resource hint. How can I do this please?
``` var_export( $hints ); ``` gave me ``` array ( 0 => 'https://s.w.org/images/core/emoji/2.4/svg/', ) ``` so that means the array key is not `s.w.org` but `https://s.w.org/images/core/emoji/2.4/svg/`. Changing the function and using the key of the array with the full url did remove the s.w.org hint while still letting me use resource hints. ``` function resource_hints( $hints, $relation_type ) { if ( 'dns-prefetch' === $relation_type ) { // Export the value of the $hints variable // to see what is inside of it. var_export( $hints ); // Knowing that the url is not s.w.org but // 'https://s.w.org/images/core/emoji/2.4/svg/' // I can search for it in the array $key = array_search( 'https://s.w.org/images/core/emoji/2.4/svg/', $hints, true ); if ( false !== $key ) { // and here I can unset this key unset( $hints[ $key ] ); } // while I can add custom, site specific hints here $hints[] = 'http://make.wordpress.org'; } elseif ( 'prerender' === $relation_type ) { $hints[] = 'https://make.wordpress.org/great-again'; } return $hints; } add_filter( 'wp_resource_hints', 'resource_hints', 999, 2 ); ```
293,829
<p>how to disable WordPress flash up-loader and force to use browser up-loader instead ? any solution, is there any function code i can use?</p>
[ { "answer_id": 293831, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>function disable_flash_uploader() {\n return false;\n}\n\nadd_filter( 'flash_uploader', 'disable_flash_uploader', 1 );\n</code></pre>\n\n<p>Or disable/uninstall the plug in</p>\n" }, { "answer_id": 293844, "author": "Mahafuz", "author_id": 115945, "author_profile": "https://wordpress.stackexchange.com/users/115945", "pm_score": 0, "selected": false, "text": "<p>With the help of the Browser uploaders, there is less trouble and therefore easy to abandon the added value of Flash uploaders, like loading multiple files simultaneously. You can disable the Flash uploader by using a filter. This can be done either in your theme, stored in the <code>functions.php</code> or in a Plugin.</p>\n\n<pre><code>function disable_flash_uploader() {\n return false;\n}\n\nadd_filter( 'flash_uploader', 'disable_flash_uploader', 1 );\n</code></pre>\n" } ]
2018/02/11
[ "https://wordpress.stackexchange.com/questions/293829", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136651/" ]
how to disable WordPress flash up-loader and force to use browser up-loader instead ? any solution, is there any function code i can use?
``` function disable_flash_uploader() { return false; } add_filter( 'flash_uploader', 'disable_flash_uploader', 1 ); ``` Or disable/uninstall the plug in
293,862
<p>I want to remove/disable the 'Active Theme' section from customizer. What could be the best way to do it? <a href="https://i.stack.imgur.com/j34tO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j34tO.png" alt="enter image description here"></a></p>
[ { "answer_id": 293831, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>function disable_flash_uploader() {\n return false;\n}\n\nadd_filter( 'flash_uploader', 'disable_flash_uploader', 1 );\n</code></pre>\n\n<p>Or disable/uninstall the plug in</p>\n" }, { "answer_id": 293844, "author": "Mahafuz", "author_id": 115945, "author_profile": "https://wordpress.stackexchange.com/users/115945", "pm_score": 0, "selected": false, "text": "<p>With the help of the Browser uploaders, there is less trouble and therefore easy to abandon the added value of Flash uploaders, like loading multiple files simultaneously. You can disable the Flash uploader by using a filter. This can be done either in your theme, stored in the <code>functions.php</code> or in a Plugin.</p>\n\n<pre><code>function disable_flash_uploader() {\n return false;\n}\n\nadd_filter( 'flash_uploader', 'disable_flash_uploader', 1 );\n</code></pre>\n" } ]
2018/02/12
[ "https://wordpress.stackexchange.com/questions/293862", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135161/" ]
I want to remove/disable the 'Active Theme' section from customizer. What could be the best way to do it? [![enter image description here](https://i.stack.imgur.com/j34tO.png)](https://i.stack.imgur.com/j34tO.png)
``` function disable_flash_uploader() { return false; } add_filter( 'flash_uploader', 'disable_flash_uploader', 1 ); ``` Or disable/uninstall the plug in
293,912
<p>I'm trying to help a friend access his website after a different developer created it, but when I visit the site.com/wp-admin, it doesn't take me to the typical dashboard and backend I'm used to seeing. It looks like this.</p> <p><a href="https://i.stack.imgur.com/s8JpA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s8JpA.png" alt="enter image description here"></a></p> <p>When you click through all those links, it just shows all the wp-super-cache data and maybe one page of code, but it's all uneditable. What could be the case? How can I find a way to access the dashboard again? Did the old developers hide it so that we can't go in and fix it ourselves?</p> <p>Thanks so much for all your help!</p>
[ { "answer_id": 293831, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>function disable_flash_uploader() {\n return false;\n}\n\nadd_filter( 'flash_uploader', 'disable_flash_uploader', 1 );\n</code></pre>\n\n<p>Or disable/uninstall the plug in</p>\n" }, { "answer_id": 293844, "author": "Mahafuz", "author_id": 115945, "author_profile": "https://wordpress.stackexchange.com/users/115945", "pm_score": 0, "selected": false, "text": "<p>With the help of the Browser uploaders, there is less trouble and therefore easy to abandon the added value of Flash uploaders, like loading multiple files simultaneously. You can disable the Flash uploader by using a filter. This can be done either in your theme, stored in the <code>functions.php</code> or in a Plugin.</p>\n\n<pre><code>function disable_flash_uploader() {\n return false;\n}\n\nadd_filter( 'flash_uploader', 'disable_flash_uploader', 1 );\n</code></pre>\n" } ]
2018/02/12
[ "https://wordpress.stackexchange.com/questions/293912", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136710/" ]
I'm trying to help a friend access his website after a different developer created it, but when I visit the site.com/wp-admin, it doesn't take me to the typical dashboard and backend I'm used to seeing. It looks like this. [![enter image description here](https://i.stack.imgur.com/s8JpA.png)](https://i.stack.imgur.com/s8JpA.png) When you click through all those links, it just shows all the wp-super-cache data and maybe one page of code, but it's all uneditable. What could be the case? How can I find a way to access the dashboard again? Did the old developers hide it so that we can't go in and fix it ourselves? Thanks so much for all your help!
``` function disable_flash_uploader() { return false; } add_filter( 'flash_uploader', 'disable_flash_uploader', 1 ); ``` Or disable/uninstall the plug in
293,944
<p>I would like to disable the Uncategorized public URL (i.e. <code>/category/uncategorized</code>), since I'm not using post categories and already have the posts list with pagination on the main Blog posts page. Having the Uncategorized category URLs simply creates duplicate pages.</p> <p>Is there a way to disable post categories entirely until I'm ready to use them? It seems WordPress forces posts to be associated to a category.</p> <p>In lieu of this, is it a good practice to simply redirect the uncategorized URL in plugin code? For example:</p> <pre><code>function redirect_uncategorized_category($request) { if(array_key_exists('category_name' , $request) &amp;&amp; $request['category_name'] == "uncategorized") { wp_redirect(get_post_type_archive_link('post'), 301); exit; } else { return $request; } } add_filter('request', 'redirect_uncategorized_category'); </code></pre> <p>Or I can create a <code>category-uncategorized.php</code> file and force a redirect in there like so:</p> <pre><code>&lt;?php wp_redirect(get_post_type_archive_link('post'), 301); exit; ?&gt; </code></pre> <p>Is this the best way?</p> <p>Thanks.</p>
[ { "answer_id": 293947, "author": "Harsh Barach", "author_id": 112248, "author_profile": "https://wordpress.stackexchange.com/users/112248", "pm_score": 0, "selected": false, "text": "<p>First you need to go in <code>Setting &gt;&gt; Writing</code>. Then, you need to follow below steps.</p>\n\n<p><strong>Step 1: Change Your Default Post Category</strong></p>\n\n<p><strong>Step 2: Delete Uncategorized</strong></p>\n\n<p>It may chance that you may have some posts in <code>Uncategorized</code> category. You just need to transfer those <code>posts</code> to new <code>default category</code>. So, don't worry your problem will solved.</p>\n" }, { "answer_id": 293985, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>You can't remove the last category. If you wish to remove the categories from the default post type, you can use the <a href=\"https://codex.wordpress.org/Function_Reference/remove_post_type_support\" rel=\"nofollow noreferrer\"><code>remove_post_type_support()</code></a> function:</p>\n\n<pre><code>add_action( 'init', 'remove_categories_from_posts' );\nfunction remove_categories_from_posts() {\n remove_post_type_support( 'post', [ 'taxonomy' =&gt; [ 'category' ] ] );\n}\n</code></pre>\n\n<p>This is untested, but it should do the trick.</p>\n\n<p>There is <a href=\"https://stackoverflow.com/q/21095725/9159152\">another question</a> about this on the StackOverflow which might be useful for you.</p>\n" }, { "answer_id": 337461, "author": "mtm", "author_id": 165130, "author_profile": "https://wordpress.stackexchange.com/users/165130", "pm_score": 1, "selected": false, "text": "<p><code>Categories</code> is a core feature for organizing Posts, providing users with a searchable, context-aware, and relational user experience.</p>\n\n<p>Rather than trying to modify the taxonomy itself, <strong>modify the view.</strong> Comb through your site's widgets and menus and remove any filters or widgets that display Posts based on <code>Categories</code> data. For example, modify <code>Default Sidebar</code> at <strong>yoursite.com//wp-admin/customize.php</strong> by removing the <code>Categories</code> widget.</p>\n\n<p>This approach leaves the door open for you to add <code>Categories</code> where it makes sense later on. Consider whether <code>Pages</code> might better suit your needs, as they assume a more fixed organization.</p>\n" }, { "answer_id": 344578, "author": "Farzad Jafari", "author_id": 173133, "author_profile": "https://wordpress.stackexchange.com/users/173133", "pm_score": -1, "selected": false, "text": "<pre><code>if((get_the_category_list() !== 'Uncategorized')){\n the_category();\n }\n</code></pre>\n" }, { "answer_id": 367067, "author": "made2popular", "author_id": 173347, "author_profile": "https://wordpress.stackexchange.com/users/173347", "pm_score": 0, "selected": false, "text": "<p>Instead of deleting the \"Uncategorized\", i.e. default post category, one should rename it as defined here. Or any generic category name that can be matched with the niche of the blog/website. </p>\n\n<p>Link: <a href=\"https://www.wpdeveloper.xyz/beginners-guide/rename-the-uncategorized-category-on-your-wordpress-blog/\" rel=\"nofollow noreferrer\">https://www.wpdeveloper.xyz/beginners-guide/rename-the-uncategorized-category-on-your-wordpress-blog/</a></p>\n" } ]
2018/02/13
[ "https://wordpress.stackexchange.com/questions/293944", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/135743/" ]
I would like to disable the Uncategorized public URL (i.e. `/category/uncategorized`), since I'm not using post categories and already have the posts list with pagination on the main Blog posts page. Having the Uncategorized category URLs simply creates duplicate pages. Is there a way to disable post categories entirely until I'm ready to use them? It seems WordPress forces posts to be associated to a category. In lieu of this, is it a good practice to simply redirect the uncategorized URL in plugin code? For example: ``` function redirect_uncategorized_category($request) { if(array_key_exists('category_name' , $request) && $request['category_name'] == "uncategorized") { wp_redirect(get_post_type_archive_link('post'), 301); exit; } else { return $request; } } add_filter('request', 'redirect_uncategorized_category'); ``` Or I can create a `category-uncategorized.php` file and force a redirect in there like so: ``` <?php wp_redirect(get_post_type_archive_link('post'), 301); exit; ?> ``` Is this the best way? Thanks.
`Categories` is a core feature for organizing Posts, providing users with a searchable, context-aware, and relational user experience. Rather than trying to modify the taxonomy itself, **modify the view.** Comb through your site's widgets and menus and remove any filters or widgets that display Posts based on `Categories` data. For example, modify `Default Sidebar` at **yoursite.com//wp-admin/customize.php** by removing the `Categories` widget. This approach leaves the door open for you to add `Categories` where it makes sense later on. Consider whether `Pages` might better suit your needs, as they assume a more fixed organization.
293,995
<p>I'm trying to add a checkbox to the "Menus" panel in the customizer, but for some reason, it's not showing up. If I try changing it from "nav_menus" to "title_tagline," or "colors," the checkbox shows up just fine. What could be preventing it from showing up on the "Menus" panel?</p> <pre><code>// add custom options to the Customizer function nssra_customizer_options($wp_customize) { // add "menu primary flex" checkbox setting $wp_customize-&gt;add_setting("menu_primary_flex", array( "capability" =&gt; "edit_theme_options", "default" =&gt; "1", "sanitize_callback" =&gt; "nssra_sanitize_checkbox", )); // add "menu primary flex" checkbox control $wp_customize-&gt;add_control("menu_primary_flex", array( "label" =&gt; __("Stretch the primary menu to fill the available space.", "nssra"), "section" =&gt; "nav_menus", "settings" =&gt; "menu_primary_flex", "std" =&gt; "1", "type" =&gt; "checkbox", "priority" =&gt; 1, )); } add_action("customize_register", "nssra_customizer_options"); // sanitize checkbox fields function nssra_sanitize_checkbox($input, $setting) { return sanitize_key($input) === "1" ? 1 : 0; } </code></pre>
[ { "answer_id": 293997, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 4, "selected": true, "text": "<p>You cannot add any control/setting to <code>nav_menus</code> because that's not a section that's a panel. And control/setting can be added to the section only. So you have to create a section first under <code>nav_menus</code> panel then add your control/setting to that section. Check the following code</p>\n\n<pre><code>function nssra_customizer_options( $wp_customize ) {\n // add a custom section\n $wp_customize-&gt;add_section( 'nav_menus_custom', array(\n 'title' =&gt; __( 'Custom Section Title', 'nssra' ),\n 'panel' =&gt; 'nav_menus'\n ) );\n\n // add \"menu primary flex\" checkbox setting\n $wp_customize-&gt;add_setting( 'menu_primary_flex', array(\n 'capability' =&gt; 'edit_theme_options',\n 'default' =&gt; '1',\n 'sanitize_callback' =&gt; 'nssra_sanitize_checkbox',\n ) );\n\n // add 'menu primary flex' checkbox control\n $wp_customize-&gt;add_control( 'menu_primary_flex', array(\n 'label' =&gt; __( 'Stretch the primary menu to fill the available space.', 'nssra' ),\n 'section' =&gt; 'nav_menus_custom',\n 'settings' =&gt; 'menu_primary_flex',\n 'std' =&gt; '1',\n 'type' =&gt; 'checkbox',\n 'priority' =&gt; 1,\n ));\n}\nadd_action( 'customize_register', 'nssra_customizer_options' );\n\n// sanitize checkbox fields\nfunction nssra_sanitize_checkbox( $input, $setting ) {\n return sanitize_key( $input ) === '1' ? 1 : 0;\n}\n</code></pre>\n\n<p><strong><code>Update</code></strong></p>\n\n<p>You have to add section <code>description</code> to create the <em>Menu Locations</em> like appearance and if you want to change the section location then you can set <code>priority</code>. <code>priority =&gt; 5</code> will place the custom section before <em>Menu Locations</em>, if you do this then you may have to adjust some styling. Please check the code below for updated section config.</p>\n\n<pre><code>$wp_customize-&gt;add_section( 'nav_menus_custom', array(\n 'title' =&gt; __( 'Custom Section Title', 'nssra' ),\n 'panel' =&gt; 'nav_menus',\n 'description' =&gt; __( 'Section description goes here.', 'nssra' ),\n 'priority' =&gt; 5\n) );\n</code></pre>\n" }, { "answer_id": 366362, "author": "dj.cowan", "author_id": 25515, "author_profile": "https://wordpress.stackexchange.com/users/25515", "pm_score": 0, "selected": false, "text": "<p>Adding the following here in case you got lost along the way like I did.\nThe solution by @odiPlabon is correct for the &quot;nav_menus&quot; panel.\nI came looking to add settings the individual menu sections e.g. Theme menus like the &quot;Primary Menu&quot; or &quot;Secondary Menu&quot;.</p>\n<p>For those as lost as I was the 'section' you're looking for is &quot;nav_menu[<em>$n</em>]&quot;.\nWhere <em>$n</em> is the term_id of the navigation menu.</p>\n<p>You can see the term_id in the query parameters of the url in the address bar for the currently viewed menu – on the Wordpress Admin &gt; Appearance &gt; Menus page\ni.e &quot;?action=edit&amp;menu=43&quot; &lt;-- 43 being the term_id</p>\n<pre><code>$menus = wp_get_nav_menus();\nif ( ! $menus &amp;&amp; ! is_iterable($menus)) :\n return;\nendif;\n\n foreach ($menus as $menu) :\n //\n $wp_customize-&gt;add_setting(\n 'menu_postition_' . $menu-&gt;term_id, // your setting name\n array(\n 'settings' =&gt; 'nav_menu[' . $menu-&gt;term_id . ']',\n 'default' =&gt; 'menu-static',\n )\n );\n //\n $wp_customize-&gt;add_control(\n 'menu_postition_' . $menu-&gt;term_id, // your setting name\n array(\n 'type' =&gt; 'select',\n 'priority' =&gt; 20,\n 'label' =&gt; __('Menu Position:','text-domain),\n 'section' =&gt; 'nav_menu[' . $menu-&gt;term_id . ']',\n 'choices' =&gt; array(\n 'menu-static' =&gt; 'Normal',\n 'menu-fixed-top' =&gt; 'Fixed Top',\n 'menu-sticky-top' =&gt; 'Sticky Top',\n ),\n )\n );\n endforeach;\n</code></pre>\n" } ]
2018/02/13
[ "https://wordpress.stackexchange.com/questions/293995", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24566/" ]
I'm trying to add a checkbox to the "Menus" panel in the customizer, but for some reason, it's not showing up. If I try changing it from "nav\_menus" to "title\_tagline," or "colors," the checkbox shows up just fine. What could be preventing it from showing up on the "Menus" panel? ``` // add custom options to the Customizer function nssra_customizer_options($wp_customize) { // add "menu primary flex" checkbox setting $wp_customize->add_setting("menu_primary_flex", array( "capability" => "edit_theme_options", "default" => "1", "sanitize_callback" => "nssra_sanitize_checkbox", )); // add "menu primary flex" checkbox control $wp_customize->add_control("menu_primary_flex", array( "label" => __("Stretch the primary menu to fill the available space.", "nssra"), "section" => "nav_menus", "settings" => "menu_primary_flex", "std" => "1", "type" => "checkbox", "priority" => 1, )); } add_action("customize_register", "nssra_customizer_options"); // sanitize checkbox fields function nssra_sanitize_checkbox($input, $setting) { return sanitize_key($input) === "1" ? 1 : 0; } ```
You cannot add any control/setting to `nav_menus` because that's not a section that's a panel. And control/setting can be added to the section only. So you have to create a section first under `nav_menus` panel then add your control/setting to that section. Check the following code ``` function nssra_customizer_options( $wp_customize ) { // add a custom section $wp_customize->add_section( 'nav_menus_custom', array( 'title' => __( 'Custom Section Title', 'nssra' ), 'panel' => 'nav_menus' ) ); // add "menu primary flex" checkbox setting $wp_customize->add_setting( 'menu_primary_flex', array( 'capability' => 'edit_theme_options', 'default' => '1', 'sanitize_callback' => 'nssra_sanitize_checkbox', ) ); // add 'menu primary flex' checkbox control $wp_customize->add_control( 'menu_primary_flex', array( 'label' => __( 'Stretch the primary menu to fill the available space.', 'nssra' ), 'section' => 'nav_menus_custom', 'settings' => 'menu_primary_flex', 'std' => '1', 'type' => 'checkbox', 'priority' => 1, )); } add_action( 'customize_register', 'nssra_customizer_options' ); // sanitize checkbox fields function nssra_sanitize_checkbox( $input, $setting ) { return sanitize_key( $input ) === '1' ? 1 : 0; } ``` **`Update`** You have to add section `description` to create the *Menu Locations* like appearance and if you want to change the section location then you can set `priority`. `priority => 5` will place the custom section before *Menu Locations*, if you do this then you may have to adjust some styling. Please check the code below for updated section config. ``` $wp_customize->add_section( 'nav_menus_custom', array( 'title' => __( 'Custom Section Title', 'nssra' ), 'panel' => 'nav_menus', 'description' => __( 'Section description goes here.', 'nssra' ), 'priority' => 5 ) ); ```
293,999
<p>I have created a Custom Post Type called <code>Products</code>.</p> <p>Now I need a functionality that will allow me to select or check a product as featured. <br>There can be only one featured product. <br>When one product is selected the others are deselected automatically.<br>This featured product will be displayed on homepage.</p> <p><strong>Question:</strong></p> <p>What is the best way to store the <code>featured_product_id</code> to identify the one that is featured?</p>
[ { "answer_id": 293997, "author": "obiPlabon", "author_id": 135737, "author_profile": "https://wordpress.stackexchange.com/users/135737", "pm_score": 4, "selected": true, "text": "<p>You cannot add any control/setting to <code>nav_menus</code> because that's not a section that's a panel. And control/setting can be added to the section only. So you have to create a section first under <code>nav_menus</code> panel then add your control/setting to that section. Check the following code</p>\n\n<pre><code>function nssra_customizer_options( $wp_customize ) {\n // add a custom section\n $wp_customize-&gt;add_section( 'nav_menus_custom', array(\n 'title' =&gt; __( 'Custom Section Title', 'nssra' ),\n 'panel' =&gt; 'nav_menus'\n ) );\n\n // add \"menu primary flex\" checkbox setting\n $wp_customize-&gt;add_setting( 'menu_primary_flex', array(\n 'capability' =&gt; 'edit_theme_options',\n 'default' =&gt; '1',\n 'sanitize_callback' =&gt; 'nssra_sanitize_checkbox',\n ) );\n\n // add 'menu primary flex' checkbox control\n $wp_customize-&gt;add_control( 'menu_primary_flex', array(\n 'label' =&gt; __( 'Stretch the primary menu to fill the available space.', 'nssra' ),\n 'section' =&gt; 'nav_menus_custom',\n 'settings' =&gt; 'menu_primary_flex',\n 'std' =&gt; '1',\n 'type' =&gt; 'checkbox',\n 'priority' =&gt; 1,\n ));\n}\nadd_action( 'customize_register', 'nssra_customizer_options' );\n\n// sanitize checkbox fields\nfunction nssra_sanitize_checkbox( $input, $setting ) {\n return sanitize_key( $input ) === '1' ? 1 : 0;\n}\n</code></pre>\n\n<p><strong><code>Update</code></strong></p>\n\n<p>You have to add section <code>description</code> to create the <em>Menu Locations</em> like appearance and if you want to change the section location then you can set <code>priority</code>. <code>priority =&gt; 5</code> will place the custom section before <em>Menu Locations</em>, if you do this then you may have to adjust some styling. Please check the code below for updated section config.</p>\n\n<pre><code>$wp_customize-&gt;add_section( 'nav_menus_custom', array(\n 'title' =&gt; __( 'Custom Section Title', 'nssra' ),\n 'panel' =&gt; 'nav_menus',\n 'description' =&gt; __( 'Section description goes here.', 'nssra' ),\n 'priority' =&gt; 5\n) );\n</code></pre>\n" }, { "answer_id": 366362, "author": "dj.cowan", "author_id": 25515, "author_profile": "https://wordpress.stackexchange.com/users/25515", "pm_score": 0, "selected": false, "text": "<p>Adding the following here in case you got lost along the way like I did.\nThe solution by @odiPlabon is correct for the &quot;nav_menus&quot; panel.\nI came looking to add settings the individual menu sections e.g. Theme menus like the &quot;Primary Menu&quot; or &quot;Secondary Menu&quot;.</p>\n<p>For those as lost as I was the 'section' you're looking for is &quot;nav_menu[<em>$n</em>]&quot;.\nWhere <em>$n</em> is the term_id of the navigation menu.</p>\n<p>You can see the term_id in the query parameters of the url in the address bar for the currently viewed menu – on the Wordpress Admin &gt; Appearance &gt; Menus page\ni.e &quot;?action=edit&amp;menu=43&quot; &lt;-- 43 being the term_id</p>\n<pre><code>$menus = wp_get_nav_menus();\nif ( ! $menus &amp;&amp; ! is_iterable($menus)) :\n return;\nendif;\n\n foreach ($menus as $menu) :\n //\n $wp_customize-&gt;add_setting(\n 'menu_postition_' . $menu-&gt;term_id, // your setting name\n array(\n 'settings' =&gt; 'nav_menu[' . $menu-&gt;term_id . ']',\n 'default' =&gt; 'menu-static',\n )\n );\n //\n $wp_customize-&gt;add_control(\n 'menu_postition_' . $menu-&gt;term_id, // your setting name\n array(\n 'type' =&gt; 'select',\n 'priority' =&gt; 20,\n 'label' =&gt; __('Menu Position:','text-domain),\n 'section' =&gt; 'nav_menu[' . $menu-&gt;term_id . ']',\n 'choices' =&gt; array(\n 'menu-static' =&gt; 'Normal',\n 'menu-fixed-top' =&gt; 'Fixed Top',\n 'menu-sticky-top' =&gt; 'Sticky Top',\n ),\n )\n );\n endforeach;\n</code></pre>\n" } ]
2018/02/13
[ "https://wordpress.stackexchange.com/questions/293999", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/65324/" ]
I have created a Custom Post Type called `Products`. Now I need a functionality that will allow me to select or check a product as featured. There can be only one featured product. When one product is selected the others are deselected automatically. This featured product will be displayed on homepage. **Question:** What is the best way to store the `featured_product_id` to identify the one that is featured?
You cannot add any control/setting to `nav_menus` because that's not a section that's a panel. And control/setting can be added to the section only. So you have to create a section first under `nav_menus` panel then add your control/setting to that section. Check the following code ``` function nssra_customizer_options( $wp_customize ) { // add a custom section $wp_customize->add_section( 'nav_menus_custom', array( 'title' => __( 'Custom Section Title', 'nssra' ), 'panel' => 'nav_menus' ) ); // add "menu primary flex" checkbox setting $wp_customize->add_setting( 'menu_primary_flex', array( 'capability' => 'edit_theme_options', 'default' => '1', 'sanitize_callback' => 'nssra_sanitize_checkbox', ) ); // add 'menu primary flex' checkbox control $wp_customize->add_control( 'menu_primary_flex', array( 'label' => __( 'Stretch the primary menu to fill the available space.', 'nssra' ), 'section' => 'nav_menus_custom', 'settings' => 'menu_primary_flex', 'std' => '1', 'type' => 'checkbox', 'priority' => 1, )); } add_action( 'customize_register', 'nssra_customizer_options' ); // sanitize checkbox fields function nssra_sanitize_checkbox( $input, $setting ) { return sanitize_key( $input ) === '1' ? 1 : 0; } ``` **`Update`** You have to add section `description` to create the *Menu Locations* like appearance and if you want to change the section location then you can set `priority`. `priority => 5` will place the custom section before *Menu Locations*, if you do this then you may have to adjust some styling. Please check the code below for updated section config. ``` $wp_customize->add_section( 'nav_menus_custom', array( 'title' => __( 'Custom Section Title', 'nssra' ), 'panel' => 'nav_menus', 'description' => __( 'Section description goes here.', 'nssra' ), 'priority' => 5 ) ); ```
294,003
<p>I have a custom post type <code>products</code> and a custom taxonomy 'Product Categories' with the slug <code>products</code>.</p> <p><strong>My goal:</strong> I'm trying to create a URL structure like so:</p> <p>Product Post Type Archive: <code>products/</code></p> <p>Product Top-level Category Archives: <code>products/product-category</code></p> <p>Product Category Archives: <code>products/product-category/product-sub-category</code></p> <p>Product Page: <code>products/product-category/product-sub-category/product-page</code></p> <p><strong>The problem:</strong> Product pages seem to only want to use actual categories. So URL structure is looking something like <code>products/uncategorized/product-page</code>. Category archive pages won't maintain the cpt base. So they turn out something like <code>category/sub-category</code>.</p> <p><strong>What I've tried:</strong> Innumerous google searches, quite a few snippets (the ones I remember I'll include below), a few custom functions, and a few plugins. No avail.</p> <p>I have the following code.</p> <pre><code>add_action( 'init', 'products_cpt', 0); add_action( 'init', 'register_taxonomies', 0 ); //A custom post type for all products function products_cpt(){ $labels = array( 'name' =&gt; _x('Products', 'Post Type General Name'), 'singular_name' =&gt; _x('Product', 'Post Type Singluar Name'), 'menu_name' =&gt; __('Products'), 'parent_item_colon' =&gt; __('Parent Product'), 'all_items' =&gt; __('All Products'), 'view_item' =&gt; __('View Product'), 'add_new_item' =&gt; __('Add New Product'), 'add_new' =&gt; __('Add New'), 'edit_item' =&gt; __('Edit Product'), 'update_item' =&gt; __('Update Product'), 'search_items' =&gt; __('Search Products'), 'not_found' =&gt; __('Not Found'), 'not_found_in_trash' =&gt; __('Not Found in Trash') ); $supports = array( 'title', 'editor', 'excerpt', 'thumbnail', 'custom-fields', 'revisions' ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'exclude_from_search' =&gt; false, 'show_in_admin_bar' =&gt; true, 'show_in_nav_menus' =&gt; true, 'publicly_queryable' =&gt; true, 'query_var' =&gt; true, 'taxonomies' =&gt; array( 'chemicals' ), 'supports' =&gt; $supports, 'has_archive' =&gt; 'products' ); register_post_type('products', $args); } function register_taxonomies() { $taxonomies = array( 'products' =&gt; array( 'Product', 'Products' ), ); foreach($taxonomies as $slug =&gt; $name){ create_product_taxonomy($slug,$name[0],$name[1]); } } function create_product_taxonomy($slug, $singular, $plural) { $labels = array( 'name' =&gt; _x( $singular.' Categories', 'Taxonomy General Name', 'text_domain' ), 'singular_name' =&gt; _x( $singular.' Category', 'Taxonomy Singular Name', 'text_domain' ), 'menu_name' =&gt; __( $singular.' Categories', 'text_domain' ), 'all_items' =&gt; __( 'All '.$singular.' Categories', 'text_domain' ), 'parent_item' =&gt; __( 'Parent '.$singular.' Category', 'text_domain' ), 'parent_item_colon' =&gt; __( 'Parent '.$singular.' Category:', 'text_domain' ), 'new_item_name' =&gt; __( 'New '.$singular.' Category Name', 'text_domain' ), 'add_new_item' =&gt; __( 'Add New '.$singular.' Category', 'text_domain' ), 'edit_item' =&gt; __( 'Edit '.$singular.' Category', 'text_domain' ), 'update_item' =&gt; __( 'Update '.$singular.' Category', 'text_domain' ), 'view_item' =&gt; __( 'View '.$singular.' Category', 'text_domain' ), 'separate_items_with_commas' =&gt; __( 'Separate '.$singular.' Categories with commas', 'text_domain' ), 'add_or_remove_items' =&gt; __( 'Add or remove '.$singular.' Categories', 'text_domain' ), 'choose_from_most_used' =&gt; __( 'Choose from the most used '.$singular.' Categories', 'text_domain' ), 'popular_items' =&gt; __( 'Popular '.$singular.' Categories', 'text_domain' ), 'search_items' =&gt; __( 'Search '.$singular.' Categories', 'text_domain' ), 'not_found' =&gt; __( 'Not Found', 'text_domain' ), 'no_terms' =&gt; __( 'No '.$singular.' Categories', 'text_domain' ), 'items_list' =&gt; __( $singular.' Categories list', 'text_domain' ), 'items_list_navigation' =&gt; __( $singular.' Categories list navigation', 'text_domain' ), ); $args = array( 'labels' =&gt; $labels, 'hierarchical' =&gt; true, 'public' =&gt; true, 'show_ui' =&gt; true, 'show_admin_column' =&gt; true, 'show_in_nav_menus' =&gt; true, 'show_tagcloud' =&gt; true, 'has_archive' =&gt; $plural, 'rewrite' =&gt; array( 'slug' =&gt; 'products', 'with_front' =&gt; true, 'hierarchical' =&gt; true ) ); register_taxonomy( $slug, 'products', $args ); } </code></pre> <p>First things first, I set the permalinks setting to the following: <a href="https://i.stack.imgur.com/1uz5M.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1uz5M.png" alt="Permalink Settings"></a></p> <p>Next, I tried adding the following code, however it only worked for product pages. Product Category Archives still 404'd.</p> <pre><code>add_filter( 'post_type_link', 'products_post_link', 1, 3 ); function products_post_link( $post_link, $id = 0 ){ $post = get_post($id); if ( is_object( $post ) ){ $terms = wp_get_object_terms( $post-&gt;ID, 'products_category' ); $slug_url = ''; $last_id = 0; if( $terms ){ foreach($terms as $term) { if ($term === reset($terms)){ foreach($terms as $termInner){ if($termInner-&gt;term_id == 0){ $slug_url .= $termInner-&gt;slug.'/'; } } }elseif ($term === end($terms)){ foreach($terms as $termInner){ if($termInner-&gt;parent == $last_id){ $slug_url .= $termInner-&gt;slug; $last_id = $termInner-&gt;term_id; } } }else{ foreach($terms as $termInner){ if($termInner-&gt;parent == $last_id){ $slug_url .= $termInner-&gt;slug.'/'; $last_id = $termInner-&gt;term_id; } } } } return str_replace( '%category%' , $slug_url , $post_link ); } } return $post_link; } </code></pre> <p>And this to the CPT init function:</p> <pre><code> 'rewrite' =&gt; array( 'slug' =&gt; 'products/%category%', 'with_front' =&gt; false, 'hierarchical' =&gt; true, ), </code></pre> <p>I also tried the following, don't remember what happened but I remember it didn't work:</p> <pre><code>add_action('init', 'custom_resource_rewrite_rules'); function custom_resource_rewrite_rules() { add_rewrite_rule('products/([A-Za-z0-9\-\_]+)/?', '$matches[1]', 'top'); } </code></pre> <p>I also tried playing with the <code>term_link</code> filter. No bueno.</p> <p>Lastly, I tried the following Plugins, also no luck.</p> <p><a href="https://wordpress.org/plugins/custom-permalinks/" rel="noreferrer">Custom Permalinks</a></p> <p><a href="https://wordpress.org/plugins/permalinks-customizer/" rel="noreferrer">Permalinks Customizer</a></p> <p><a href="https://wordpress.org/plugins/custom-post-type-permalinks/" rel="noreferrer">Custom Post Type Permalinks</a></p> <p>Does anyone have a solution to this? I'm pulling my hair out.</p>
[ { "answer_id": 294542, "author": "J Robz", "author_id": 112485, "author_profile": "https://wordpress.stackexchange.com/users/112485", "pm_score": 4, "selected": true, "text": "<p>After forever, I figured out an answer!</p>\n<p>First: we register the custom post type &amp; custom taxonomy:</p>\n<pre><code>add_action( 'init', 'register_sps_products_post_type' );\nfunction register_sps_products_post_type() {\n register_post_type( 'sps-product',\n array(\n 'labels' =&gt; array(\n 'name' =&gt; 'Products',\n 'menu_name' =&gt; 'Product Manager',\n 'singular_name' =&gt; 'Product',\n 'all_items' =&gt; 'All Products'\n ),\n 'public' =&gt; true,\n 'publicly_queryable' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'post-formats', 'revisions' ),\n 'hierarchical' =&gt; false,\n 'has_archive' =&gt; 'products',\n 'taxonomies' =&gt; array('product-category'),\n 'rewrite' =&gt; array( 'slug' =&gt; 'products/%product_category%', 'hierarchical' =&gt; true, 'with_front' =&gt; false )\n )\n );\n register_taxonomy( 'product-category', array( 'sps-product' ),\n array(\n 'labels' =&gt; array(\n 'name' =&gt; 'Product Categories',\n 'menu_name' =&gt; 'Product Categories',\n 'singular_name' =&gt; 'Product Category',\n 'all_items' =&gt; 'All Categories'\n ),\n 'public' =&gt; true,\n 'hierarchical' =&gt; true,\n 'show_ui' =&gt; true,\n 'rewrite' =&gt; array( 'slug' =&gt; 'products', 'hierarchical' =&gt; true, 'with_front' =&gt; false ),\n )\n );\n}\n</code></pre>\n<p>Next, we add a new rewrite rule so Wordpress knows how to interpret our new permalink structure:</p>\n<pre><code>add_action( 'generate_rewrite_rules', 'register_product_rewrite_rules' );\nfunction register_product_rewrite_rules( $wp_rewrite ) {\n $new_rules = array( \n 'products/([^/]+)/?$' =&gt; 'index.php?product-category=' . $wp_rewrite-&gt;preg_index( 1 ), // 'products/any-character/'\n 'products/([^/]+)/([^/]+)/?$' =&gt; 'index.php?post_type=sps-product&amp;product-category=' . $wp_rewrite-&gt;preg_index( 1 ) . '&amp;sps-product=' . $wp_rewrite-&gt;preg_index( 2 ), // 'products/any-character/post-slug/'\n 'products/([^/]+)/([^/]+)/page/(\\d{1,})/?$' =&gt; 'index.php?post_type=sps-product&amp;product-category=' . $wp_rewrite-&gt;preg_index( 1 ) . '&amp;paged=' . $wp_rewrite-&gt;preg_index( 3 ), // match paginated results for a sub-category archive\n 'products/([^/]+)/([^/]+)/([^/]+)/?$' =&gt; 'index.php?post_type=sps-product&amp;product-category=' . $wp_rewrite-&gt;preg_index( 2 ) . '&amp;sps-product=' . $wp_rewrite-&gt;preg_index( 3 ), // 'products/any-character/sub-category/post-slug/'\n 'products/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$' =&gt; 'index.php?post_type=sps-product&amp;product-category=' . $wp_rewrite-&gt;preg_index( 3 ) . '&amp;sps-product=' . $wp_rewrite-&gt;preg_index( 4 ), // 'products/any-character/sub-category/sub-sub-category/post-slug/'\n );\n $wp_rewrite-&gt;rules = $new_rules + $wp_rewrite-&gt;rules;\n}\n</code></pre>\n<p>The next function on the other hand fixes the issue with the sub-categories. The issue itself consists in the fact, that when you try to load a page with URL faq/category/child-category/, WordPress would try to load a post with slug “child-category” instead of the sub-category with slug “child-category”.</p>\n<pre><code>// A hacky way of adding support for flexible custom permalinks\n// There is one case in which the rewrite rules from register_kb_rewrite_rules() fail:\n// When you visit the archive page for a child section(for example: http://example.com/faq/category/child-category)\n// The deal is that in this situation, the URL is parsed as a Knowledgebase post with slug &quot;child-category&quot; from the &quot;category&quot; section\nfunction fix_product_subcategory_query($query) {\n if ( isset( $query['post_type'] ) &amp;&amp; 'sps-product' == $query['post_type'] ) {\n if ( isset( $query['sps-product'] ) &amp;&amp; $query['sps-product'] &amp;&amp; isset( $query['product-category'] ) &amp;&amp; $query['product-category'] ) {\n $query_old = $query;\n // Check if this is a paginated result(like search results)\n if ( 'page' == $query['product-category'] ) {\n $query['paged'] = $query['name'];\n unset( $query['product-category'], $query['name'], $query['sps-product'] );\n }\n // Make it easier on the DB\n $query['fields'] = 'ids';\n $query['posts_per_page'] = 1;\n // See if we have results or not\n $_query = new WP_Query( $query );\n if ( ! $_query-&gt;posts ) {\n $query = array( 'product-category' =&gt; $query['sps-product'] );\n if ( isset( $query_old['product-category'] ) &amp;&amp; 'page' == $query_old['product-category'] ) {\n $query['paged'] = $query_old['name'];\n }\n }\n }\n }\n return $query;\n}\nadd_filter( 'request', 'fix_product_subcategory_query', 10 );\n</code></pre>\n<p>This function lets WordPress know how to handle %product_category% in your custom post type rewrite slug structure:</p>\n<pre><code>function filter_post_type_link($link, $post)\n{\n if ($post-&gt;post_type != 'sps-product')\n return $link;\n\n if ($cats = get_the_terms($post-&gt;ID, 'product-category'))\n {\n $link = str_replace('%product_category%', get_taxonomy_parents(array_pop($cats)-&gt;term_id, 'product-category', false, '/', true), $link); // see custom function defined below\\\n $link = str_replace('//', '/', $link);\n $link = str_replace('http:/', 'http://', $link);\n }\n return $link;\n}\nadd_filter('post_type_link', 'filter_post_type_link', 10, 2);\n</code></pre>\n<p>A custom function based off of <code>get_category_parents</code>. It gets the taxonomy's parents:</p>\n<pre><code>// my own function to do what get_category_parents does for other taxonomies\nfunction get_taxonomy_parents($id, $taxonomy, $link = false, $separator = '/', $nicename = false, $visited = array()) { \n $chain = ''; \n $parent = &amp;get_term($id, $taxonomy);\n\n if (is_wp_error($parent)) {\n return $parent;\n }\n\n if ($nicename) \n $name = $parent -&gt; slug; \nelse \n $name = $parent -&gt; name;\n\n if ($parent -&gt; parent &amp;&amp; ($parent -&gt; parent != $parent -&gt; term_id) &amp;&amp; !in_array($parent -&gt; parent, $visited)) { \n $visited[] = $parent -&gt; parent; \n $chain .= get_taxonomy_parents($parent -&gt; parent, $taxonomy, $link, $separator, $nicename, $visited);\n\n }\n\n if ($link) {\n // nothing, can't get this working :(\n } else \n $chain .= $name . $separator; \n return $chain; \n}\n</code></pre>\n<h2>Sources:</h2>\n<ul>\n<li><a href=\"https://wordpress.stackexchange.com/questions/196797/add-taxonomy-in-custom-permalink-structure/196799\">Add Taxonomy in Custom Permalink Structure</a></li>\n<li><a href=\"http://themoonwatch.com/en/2012/custom-permalinks-hierarchical-taxonomies/#sthash.6UaovMFc.dpbs\" rel=\"nofollow noreferrer\">Custom Permalinks Hierarchical Taxonomies</a></li>\n</ul>\n" }, { "answer_id": 364034, "author": "user1676224", "author_id": 28228, "author_profile": "https://wordpress.stackexchange.com/users/28228", "pm_score": 2, "selected": false, "text": "<p>Actually, this is a horrible way of doing this.</p>\n<p>If you add the taxonomy before the custom post type using the timing of the <code>add_action</code>, you'll be able to use the custom post type rewrite rule to prefix the taxonomy.</p>\n<p>ex.</p>\n<pre><code> \n // Register Custom Taxonomy\n function type_taxonomy() {\n \n $labels = array(\n 'name' =&gt; _x( 'Types', 'Taxonomy General Name', 'asw' ),\n 'singular_name' =&gt; _x( 'Type', 'Taxonomy Singular Name', 'asw' ),\n );\n $rewrite = array(\n 'slug' =&gt; 'update/type',\n 'with_front' =&gt; false,\n 'hierarchical' =&gt; false,\n );\n $args = array(\n 'labels' =&gt; $labels,\n 'hierarchical' =&gt; true,\n 'public' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_admin_column' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'show_tagcloud' =&gt; true,\n 'rewrite' =&gt; $rewrite,\n 'show_in_rest' =&gt; true,\n );\n register_taxonomy( 'type', array( 'updates' ), $args );\n \n }\n// Set the timing before the post type\n add_action( 'init', 'type_taxonomy', $timing = 0 );\n \n }\n \n if ( ! function_exists('updates_post_type') ) {\n \n // Register Custom Post Type\n function updates_post_type() {\n \n $labels = array(\n 'name' =&gt; _x( 'Updates', 'Post Type General Name', 'asw' ),\n 'singular_name' =&gt; _x( 'Updates', 'Post Type Singular Name', 'asw' ),\n );\n $rewrite = array(\n 'slug' =&gt; 'update',\n 'with_front' =&gt; true,\n 'pages' =&gt; true,\n 'feeds' =&gt; true,\n );\n $args = array(\n 'label' =&gt; __( 'Updates', 'asw' ),\n 'description' =&gt; __( 'Posts should include important updates on health, well being and community', 'asw' ),\n 'labels' =&gt; $labels,\n 'supports' =&gt; array( 'title', 'editor', 'thumbnail' ),\n 'taxonomies' =&gt; array( 'type', 'category', 'post_tag', 'brands', 'markets' ),\n 'hierarchical' =&gt; false,\n 'public' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'menu_position' =&gt; 5,\n 'menu_icon' =&gt; 'dashicons-heart',\n 'show_in_admin_bar' =&gt; true,\n 'show_in_nav_menus' =&gt; true,\n 'can_export' =&gt; true,\n 'has_archive' =&gt; true,\n 'exclude_from_search' =&gt; false,\n 'publicly_queryable' =&gt; true,\n 'rewrite' =&gt; $rewrite,\n 'capability_type' =&gt; 'page',\n 'show_in_rest' =&gt; true,\n );\n register_post_type( 'updates', $args );\n \n }\n// Set the timing after the taxonomy \n add_action( 'init', 'updates_post_type', $timing = 10 );\n \n }\n</code></pre>\n" } ]
2018/02/13
[ "https://wordpress.stackexchange.com/questions/294003", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112485/" ]
I have a custom post type `products` and a custom taxonomy 'Product Categories' with the slug `products`. **My goal:** I'm trying to create a URL structure like so: Product Post Type Archive: `products/` Product Top-level Category Archives: `products/product-category` Product Category Archives: `products/product-category/product-sub-category` Product Page: `products/product-category/product-sub-category/product-page` **The problem:** Product pages seem to only want to use actual categories. So URL structure is looking something like `products/uncategorized/product-page`. Category archive pages won't maintain the cpt base. So they turn out something like `category/sub-category`. **What I've tried:** Innumerous google searches, quite a few snippets (the ones I remember I'll include below), a few custom functions, and a few plugins. No avail. I have the following code. ``` add_action( 'init', 'products_cpt', 0); add_action( 'init', 'register_taxonomies', 0 ); //A custom post type for all products function products_cpt(){ $labels = array( 'name' => _x('Products', 'Post Type General Name'), 'singular_name' => _x('Product', 'Post Type Singluar Name'), 'menu_name' => __('Products'), 'parent_item_colon' => __('Parent Product'), 'all_items' => __('All Products'), 'view_item' => __('View Product'), 'add_new_item' => __('Add New Product'), 'add_new' => __('Add New'), 'edit_item' => __('Edit Product'), 'update_item' => __('Update Product'), 'search_items' => __('Search Products'), 'not_found' => __('Not Found'), 'not_found_in_trash' => __('Not Found in Trash') ); $supports = array( 'title', 'editor', 'excerpt', 'thumbnail', 'custom-fields', 'revisions' ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'exclude_from_search' => false, 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'publicly_queryable' => true, 'query_var' => true, 'taxonomies' => array( 'chemicals' ), 'supports' => $supports, 'has_archive' => 'products' ); register_post_type('products', $args); } function register_taxonomies() { $taxonomies = array( 'products' => array( 'Product', 'Products' ), ); foreach($taxonomies as $slug => $name){ create_product_taxonomy($slug,$name[0],$name[1]); } } function create_product_taxonomy($slug, $singular, $plural) { $labels = array( 'name' => _x( $singular.' Categories', 'Taxonomy General Name', 'text_domain' ), 'singular_name' => _x( $singular.' Category', 'Taxonomy Singular Name', 'text_domain' ), 'menu_name' => __( $singular.' Categories', 'text_domain' ), 'all_items' => __( 'All '.$singular.' Categories', 'text_domain' ), 'parent_item' => __( 'Parent '.$singular.' Category', 'text_domain' ), 'parent_item_colon' => __( 'Parent '.$singular.' Category:', 'text_domain' ), 'new_item_name' => __( 'New '.$singular.' Category Name', 'text_domain' ), 'add_new_item' => __( 'Add New '.$singular.' Category', 'text_domain' ), 'edit_item' => __( 'Edit '.$singular.' Category', 'text_domain' ), 'update_item' => __( 'Update '.$singular.' Category', 'text_domain' ), 'view_item' => __( 'View '.$singular.' Category', 'text_domain' ), 'separate_items_with_commas' => __( 'Separate '.$singular.' Categories with commas', 'text_domain' ), 'add_or_remove_items' => __( 'Add or remove '.$singular.' Categories', 'text_domain' ), 'choose_from_most_used' => __( 'Choose from the most used '.$singular.' Categories', 'text_domain' ), 'popular_items' => __( 'Popular '.$singular.' Categories', 'text_domain' ), 'search_items' => __( 'Search '.$singular.' Categories', 'text_domain' ), 'not_found' => __( 'Not Found', 'text_domain' ), 'no_terms' => __( 'No '.$singular.' Categories', 'text_domain' ), 'items_list' => __( $singular.' Categories list', 'text_domain' ), 'items_list_navigation' => __( $singular.' Categories list navigation', 'text_domain' ), ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, 'has_archive' => $plural, 'rewrite' => array( 'slug' => 'products', 'with_front' => true, 'hierarchical' => true ) ); register_taxonomy( $slug, 'products', $args ); } ``` First things first, I set the permalinks setting to the following: [![Permalink Settings](https://i.stack.imgur.com/1uz5M.png)](https://i.stack.imgur.com/1uz5M.png) Next, I tried adding the following code, however it only worked for product pages. Product Category Archives still 404'd. ``` add_filter( 'post_type_link', 'products_post_link', 1, 3 ); function products_post_link( $post_link, $id = 0 ){ $post = get_post($id); if ( is_object( $post ) ){ $terms = wp_get_object_terms( $post->ID, 'products_category' ); $slug_url = ''; $last_id = 0; if( $terms ){ foreach($terms as $term) { if ($term === reset($terms)){ foreach($terms as $termInner){ if($termInner->term_id == 0){ $slug_url .= $termInner->slug.'/'; } } }elseif ($term === end($terms)){ foreach($terms as $termInner){ if($termInner->parent == $last_id){ $slug_url .= $termInner->slug; $last_id = $termInner->term_id; } } }else{ foreach($terms as $termInner){ if($termInner->parent == $last_id){ $slug_url .= $termInner->slug.'/'; $last_id = $termInner->term_id; } } } } return str_replace( '%category%' , $slug_url , $post_link ); } } return $post_link; } ``` And this to the CPT init function: ``` 'rewrite' => array( 'slug' => 'products/%category%', 'with_front' => false, 'hierarchical' => true, ), ``` I also tried the following, don't remember what happened but I remember it didn't work: ``` add_action('init', 'custom_resource_rewrite_rules'); function custom_resource_rewrite_rules() { add_rewrite_rule('products/([A-Za-z0-9\-\_]+)/?', '$matches[1]', 'top'); } ``` I also tried playing with the `term_link` filter. No bueno. Lastly, I tried the following Plugins, also no luck. [Custom Permalinks](https://wordpress.org/plugins/custom-permalinks/) [Permalinks Customizer](https://wordpress.org/plugins/permalinks-customizer/) [Custom Post Type Permalinks](https://wordpress.org/plugins/custom-post-type-permalinks/) Does anyone have a solution to this? I'm pulling my hair out.
After forever, I figured out an answer! First: we register the custom post type & custom taxonomy: ``` add_action( 'init', 'register_sps_products_post_type' ); function register_sps_products_post_type() { register_post_type( 'sps-product', array( 'labels' => array( 'name' => 'Products', 'menu_name' => 'Product Manager', 'singular_name' => 'Product', 'all_items' => 'All Products' ), 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'show_in_nav_menus' => true, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'post-formats', 'revisions' ), 'hierarchical' => false, 'has_archive' => 'products', 'taxonomies' => array('product-category'), 'rewrite' => array( 'slug' => 'products/%product_category%', 'hierarchical' => true, 'with_front' => false ) ) ); register_taxonomy( 'product-category', array( 'sps-product' ), array( 'labels' => array( 'name' => 'Product Categories', 'menu_name' => 'Product Categories', 'singular_name' => 'Product Category', 'all_items' => 'All Categories' ), 'public' => true, 'hierarchical' => true, 'show_ui' => true, 'rewrite' => array( 'slug' => 'products', 'hierarchical' => true, 'with_front' => false ), ) ); } ``` Next, we add a new rewrite rule so Wordpress knows how to interpret our new permalink structure: ``` add_action( 'generate_rewrite_rules', 'register_product_rewrite_rules' ); function register_product_rewrite_rules( $wp_rewrite ) { $new_rules = array( 'products/([^/]+)/?$' => 'index.php?product-category=' . $wp_rewrite->preg_index( 1 ), // 'products/any-character/' 'products/([^/]+)/([^/]+)/?$' => 'index.php?post_type=sps-product&product-category=' . $wp_rewrite->preg_index( 1 ) . '&sps-product=' . $wp_rewrite->preg_index( 2 ), // 'products/any-character/post-slug/' 'products/([^/]+)/([^/]+)/page/(\d{1,})/?$' => 'index.php?post_type=sps-product&product-category=' . $wp_rewrite->preg_index( 1 ) . '&paged=' . $wp_rewrite->preg_index( 3 ), // match paginated results for a sub-category archive 'products/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=sps-product&product-category=' . $wp_rewrite->preg_index( 2 ) . '&sps-product=' . $wp_rewrite->preg_index( 3 ), // 'products/any-character/sub-category/post-slug/' 'products/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=sps-product&product-category=' . $wp_rewrite->preg_index( 3 ) . '&sps-product=' . $wp_rewrite->preg_index( 4 ), // 'products/any-character/sub-category/sub-sub-category/post-slug/' ); $wp_rewrite->rules = $new_rules + $wp_rewrite->rules; } ``` The next function on the other hand fixes the issue with the sub-categories. The issue itself consists in the fact, that when you try to load a page with URL faq/category/child-category/, WordPress would try to load a post with slug “child-category” instead of the sub-category with slug “child-category”. ``` // A hacky way of adding support for flexible custom permalinks // There is one case in which the rewrite rules from register_kb_rewrite_rules() fail: // When you visit the archive page for a child section(for example: http://example.com/faq/category/child-category) // The deal is that in this situation, the URL is parsed as a Knowledgebase post with slug "child-category" from the "category" section function fix_product_subcategory_query($query) { if ( isset( $query['post_type'] ) && 'sps-product' == $query['post_type'] ) { if ( isset( $query['sps-product'] ) && $query['sps-product'] && isset( $query['product-category'] ) && $query['product-category'] ) { $query_old = $query; // Check if this is a paginated result(like search results) if ( 'page' == $query['product-category'] ) { $query['paged'] = $query['name']; unset( $query['product-category'], $query['name'], $query['sps-product'] ); } // Make it easier on the DB $query['fields'] = 'ids'; $query['posts_per_page'] = 1; // See if we have results or not $_query = new WP_Query( $query ); if ( ! $_query->posts ) { $query = array( 'product-category' => $query['sps-product'] ); if ( isset( $query_old['product-category'] ) && 'page' == $query_old['product-category'] ) { $query['paged'] = $query_old['name']; } } } } return $query; } add_filter( 'request', 'fix_product_subcategory_query', 10 ); ``` This function lets WordPress know how to handle %product\_category% in your custom post type rewrite slug structure: ``` function filter_post_type_link($link, $post) { if ($post->post_type != 'sps-product') return $link; if ($cats = get_the_terms($post->ID, 'product-category')) { $link = str_replace('%product_category%', get_taxonomy_parents(array_pop($cats)->term_id, 'product-category', false, '/', true), $link); // see custom function defined below\ $link = str_replace('//', '/', $link); $link = str_replace('http:/', 'http://', $link); } return $link; } add_filter('post_type_link', 'filter_post_type_link', 10, 2); ``` A custom function based off of `get_category_parents`. It gets the taxonomy's parents: ``` // my own function to do what get_category_parents does for other taxonomies function get_taxonomy_parents($id, $taxonomy, $link = false, $separator = '/', $nicename = false, $visited = array()) { $chain = ''; $parent = &get_term($id, $taxonomy); if (is_wp_error($parent)) { return $parent; } if ($nicename) $name = $parent -> slug; else $name = $parent -> name; if ($parent -> parent && ($parent -> parent != $parent -> term_id) && !in_array($parent -> parent, $visited)) { $visited[] = $parent -> parent; $chain .= get_taxonomy_parents($parent -> parent, $taxonomy, $link, $separator, $nicename, $visited); } if ($link) { // nothing, can't get this working :( } else $chain .= $name . $separator; return $chain; } ``` Sources: -------- * [Add Taxonomy in Custom Permalink Structure](https://wordpress.stackexchange.com/questions/196797/add-taxonomy-in-custom-permalink-structure/196799) * [Custom Permalinks Hierarchical Taxonomies](http://themoonwatch.com/en/2012/custom-permalinks-hierarchical-taxonomies/#sthash.6UaovMFc.dpbs)
294,004
<p>I am currently using a Plugin, which has created a Stylesheet within the following directory: <code>/wp-content/uploads/plugin-name/css</code>.</p> <p>I would like to remove this Plugin's Stylesheet, since it is being called after my Custom Stylesheet, where the Plugin is performing unwanted overrides of the Custom Stylesheet.</p> <p>Instead, I want to remove the Plugin's Stylesheet; copying only required styles into the Custom Stylesheet.</p> <p>I tried placing the following into the <code>functions.php</code> file, within the Child Theme:</p> <pre><code>&lt;?php function dequeue_dequeue_plugin_style(){ wp_dequeue_style( 'plugin-css' ); //Name of Style ID. } add_action( 'wp_enqueue_scripts', 'dequeue_dequeue_plugin_style', 999 ); ?&gt; </code></pre> <p>Unfortunately, this did not work. Is anyone able to see if I have gone wrong with my Code or whether Plugin Styles have priority over all files within a Child Theme etc. </p>
[ { "answer_id": 294005, "author": "Craig", "author_id": 112472, "author_profile": "https://wordpress.stackexchange.com/users/112472", "pm_score": 3, "selected": true, "text": "<p>My error. All I had to do was knock off the <code>-css</code> and it worked.</p>\n\n<p>Working code:</p>\n\n<pre><code>&lt;?php\nfunction dequeue_dequeue_plugin_style(){\n wp_dequeue_style( 'plugin' ); //Name of Style ID.\n}\nadd_action( 'wp_enqueue_scripts', 'dequeue_dequeue_plugin_style', 999 );\n?&gt; \n</code></pre>\n" }, { "answer_id": 373493, "author": "Zakaria Binsaifullah", "author_id": 158754, "author_profile": "https://wordpress.stackexchange.com/users/158754", "pm_score": 1, "selected": false, "text": "<p>You can easily do it.\nFor style, you have to follow the following codes-</p>\n<pre><code>function scp_assets_dequeue() {\n wp_dequeue_style( 'wpcp-slick' ); // style id\n} \nadd_action( 'wp_enqueue_scripts', 'scp_assets_dequeue', 9999);\n</code></pre>\n<p>Similarly for script, you have to try the following code-</p>\n<pre><code>function scp_assets_dequeue() {\n wp_dequeue_script( 'wpcp-slick' ); // script id\n} \nadd_action( 'wp_enqueue_scripts', 'scp_assets_dequeue', 9999);\n</code></pre>\n" } ]
2018/02/13
[ "https://wordpress.stackexchange.com/questions/294004", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112472/" ]
I am currently using a Plugin, which has created a Stylesheet within the following directory: `/wp-content/uploads/plugin-name/css`. I would like to remove this Plugin's Stylesheet, since it is being called after my Custom Stylesheet, where the Plugin is performing unwanted overrides of the Custom Stylesheet. Instead, I want to remove the Plugin's Stylesheet; copying only required styles into the Custom Stylesheet. I tried placing the following into the `functions.php` file, within the Child Theme: ``` <?php function dequeue_dequeue_plugin_style(){ wp_dequeue_style( 'plugin-css' ); //Name of Style ID. } add_action( 'wp_enqueue_scripts', 'dequeue_dequeue_plugin_style', 999 ); ?> ``` Unfortunately, this did not work. Is anyone able to see if I have gone wrong with my Code or whether Plugin Styles have priority over all files within a Child Theme etc.
My error. All I had to do was knock off the `-css` and it worked. Working code: ``` <?php function dequeue_dequeue_plugin_style(){ wp_dequeue_style( 'plugin' ); //Name of Style ID. } add_action( 'wp_enqueue_scripts', 'dequeue_dequeue_plugin_style', 999 ); ?> ```
294,011
<p>I am running a site where I let users create a profile, which is a custom post type, which is submitted/edited through an ACF front-end form. Everything works as expected, except when users both use the same 'headline' (which is sanitized and used as permalink).</p> <p>I want the permalink to have the following 'structure': /post-type/city/{post-title}-{post-id}. My thought was to add a post id, so each link would be unique, but I now found out this is not the case.</p> <p>If I would have 2 profiles: www.domain.com/profile/city/i-am-cool-123 www.domain.com/profile/city/i-am-cool-456</p> <p>Then www.domain.com/profile/city/i-am-cool-456 redirects to www.domain.com/profile/city/i-am-cool-123.</p> <p>I knew you can't have 2 the same permalinks, but I might have misunderstood how permalinks are 'registered'.</p> <p>Below is my code.</p> <p>First I've added the necessary query vars for the new vars and added custom rewrite tags.</p> <pre><code>function sd_custom_rewrite_tag() { add_rewrite_tag( '%city%', '([^&amp;]+)', 'city=' ); add_rewrite_tag( '%postname%', '([^&amp;]+)', 'name=' ); } add_action( 'init', 'sd_custom_rewrite_tag', 10, 0 ); function sd_add_query_vars( $vars ) { $vars[] = "city"; $vars[] = "postname"; return $vars; } add_filter( 'query_vars', 'sd_add_query_vars' ); </code></pre> <p>To get the permalink I want, I have the following code in place.</p> <pre><code>function sd_new_profile_permalink( $permalink, $post, $leavename = false ) { if ( strpos( $permalink, '%city%' ) === FALSE ) { return $permalink; } // Get post if ( ! $post ) { return $permalink; } // Get custom info $city_info = get_field( 'sd_city_selector', $post-&gt;ID ); $post_slug = $post-&gt;post_name; if ( ! is_wp_error( $city_info ) &amp;&amp; ! empty( $city_info ) ) { $city_replace = str_replace( '\'', '', $city_info[ 'cityName' ] ); $city_replace = str_replace( ' ', '-', $city_replace ); $city_slug = strtolower( $city_replace ); $new_permalink = str_replace( array( '%city%', '%postname%', '%post_id%' ), array( $city_slug, $post_slug, $post-&gt;ID ), $permalink ); return $new_permalink; } return $permalink; } add_filter( 'post_link', 'sd_new_profile_permalink', 10, 3 ); add_filter( 'post_type_link', 'sd_new_profile_permalink', 10, 3 ); </code></pre> <p>So far nothing weird is happening, this is all doing what it's supposed to do, but now we get down to the issue (I think).</p> <p>I update the slug through a WPDB action, after the post is submitted, as seen below. </p> <pre><code>function set_profile_title_from_headline( $post_id ) { if ( empty( $_POST[ 'acf' ] ) ) { return; } if ( ! empty( $_POST[ 'acf' ][ 'field_57e3ed6c92ea0' ] ) ) { $entered_title = $_POST[ 'acf' ][ 'field_57e3ed6c92ea0' ]; $cleaned_title = preg_replace( '/[^A-Za-z0-9\-\s]/', '', $entered_title ); $post_name = sanitize_title( $cleaned_title ); update_field( 'sd_ad_title', $cleaned_title, $post_id ); global $wpdb; $wpdb-&gt;update( $wpdb-&gt;posts, array( 'post_title' =&gt; $cleaned_title, 'post_name' =&gt; $post_name ), array( 'ID' =&gt; $post_id ) ); clean_post_cache( $post_id ); } } add_action( 'acf/save_post', 'set_profile_title_from_headline', 20 ); </code></pre> <p>And then finally I rewrite the url.</p> <pre><code>function sd_single_profile_rewrite() { global $wp_rewrite; $wp_rewrite-&gt;add_permastruct( 'profile', 'profile/%city%/%postname%-%post_id%/', false ); add_rewrite_rule( 'profile\/([a-z-]+)\/(.+)-[0-9]+\/?$', 'index.php?post_type=profile&amp;p=$matches[2]&amp;city=$matches[1]&amp;name=$matches[2]', 'top' ); } add_action( 'init', 'sd_single_profile_rewrite' ); </code></pre> <p>Basically my question is: Is there a way to 'do' what I want to do ? And if so, how :)</p>
[ { "answer_id": 294034, "author": "Slam", "author_id": 82256, "author_profile": "https://wordpress.stackexchange.com/users/82256", "pm_score": -1, "selected": false, "text": "<p>Are <code>/i-am-cool-123</code> and <code>i-am-cool-456</code> actually two different posts?</p>\n\n<p>If so then sure you want two different permalinks. </p>\n\n<p>But your use case sounds like you have one post and you want to track visits from different pages on your site. In which case you might want to <a href=\"http://www.wpbeginner.com/wp-tutorials/how-to-track-links-in-wordpress-using-google-analytics/\" rel=\"nofollow noreferrer\">add UTM codes to the ends of you URLs</a> to track them. </p>\n\n<p>Edit: I think you mean you'd have two profiles... but in different cities? The <code>i-am-cool-123</code> part is the post name and they must be unique. There doesn't seem to be a point in creating an <code>i-am-cool-234</code> and redirecting it to <code>i-am-cool-123</code> because no-one would be able to visit the content at <code>i-am-cool-234</code> — clicking that link would take you to <code>i-am-cool-123</code>.</p>\n\n<p>The part before the post_name, the rest of the URL... doesn't matter. <code>red/apples</code> and <code>yellow/apples</code> both would normally go to the post named <code>apples</code>. The path is generated by Wordpress and multiple paths can go to the same post (which is why for SEO purposes it's a good idea to define a canonical URL).</p>\n\n<p>You might be able to make a custom permalink that parses the path. Maybe <code>yellow/apples</code> redirects to <code>yellow/apples-yellow</code> and <code>red/apples</code> redirects to <code>red/apples-red</code>, but your rewrite would need to grab something from the path to extract and put at the end of the post name. Sounds like a PITA. </p>\n\n<p>But nothing stops you from having the same post titles. <code>/i-am-cool-123</code> and <code>i-am-cool-456</code> would both appear in the URL, but the title of both pages would still be I Am Cool. </p>\n" }, { "answer_id": 294099, "author": "Beee", "author_id": 103402, "author_profile": "https://wordpress.stackexchange.com/users/103402", "pm_score": 3, "selected": true, "text": "<p>I was thinking too 'difficult'. Instead of rebuilding a new permalink structure I could have easily updated the new permalink the way I want to have it.</p>\n\n<p>So I deleted the entire rewrite part and changed the query in acf/save_post to the following:</p>\n\n<pre><code>if ( ! empty( $_POST[ 'acf' ][ $ad_title ] ) ) {\n\n $entered_title = $_POST[ 'acf' ][ $ad_title ];\n $cleaned_title = preg_replace( '/[^A-Za-z0-9\\-\\s]/', '', \n $entered_title ); // Removes special chars.\n $post_name = sanitize_title( $cleaned_title );\n $city_name = get_field( 'sd_city_search_value', $post_id );\n $new_slug = strtolower( $city_name ) . '-' . $post_name . '-' . $post_id;\n\n // update acf field\n update_field( 'sd_ad_title', $cleaned_title, $post_id );\n\n // update post status + post title (if needed)\n global $wpdb;\n $wpdb-&gt;update(\n $wpdb-&gt;posts,\n array(\n 'post_title' =&gt; $cleaned_title,\n 'post_name' =&gt; strtolower( get_field( 'sd_city_search_value', $post_id ) ) . '-' . $post_name . '-' . $post_id\n ),\n array(\n 'ID' =&gt; $post_id\n )\n );\n\n clean_post_cache( $post_id );\n\n}\n</code></pre>\n" } ]
2018/02/13
[ "https://wordpress.stackexchange.com/questions/294011", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103402/" ]
I am running a site where I let users create a profile, which is a custom post type, which is submitted/edited through an ACF front-end form. Everything works as expected, except when users both use the same 'headline' (which is sanitized and used as permalink). I want the permalink to have the following 'structure': /post-type/city/{post-title}-{post-id}. My thought was to add a post id, so each link would be unique, but I now found out this is not the case. If I would have 2 profiles: www.domain.com/profile/city/i-am-cool-123 www.domain.com/profile/city/i-am-cool-456 Then www.domain.com/profile/city/i-am-cool-456 redirects to www.domain.com/profile/city/i-am-cool-123. I knew you can't have 2 the same permalinks, but I might have misunderstood how permalinks are 'registered'. Below is my code. First I've added the necessary query vars for the new vars and added custom rewrite tags. ``` function sd_custom_rewrite_tag() { add_rewrite_tag( '%city%', '([^&]+)', 'city=' ); add_rewrite_tag( '%postname%', '([^&]+)', 'name=' ); } add_action( 'init', 'sd_custom_rewrite_tag', 10, 0 ); function sd_add_query_vars( $vars ) { $vars[] = "city"; $vars[] = "postname"; return $vars; } add_filter( 'query_vars', 'sd_add_query_vars' ); ``` To get the permalink I want, I have the following code in place. ``` function sd_new_profile_permalink( $permalink, $post, $leavename = false ) { if ( strpos( $permalink, '%city%' ) === FALSE ) { return $permalink; } // Get post if ( ! $post ) { return $permalink; } // Get custom info $city_info = get_field( 'sd_city_selector', $post->ID ); $post_slug = $post->post_name; if ( ! is_wp_error( $city_info ) && ! empty( $city_info ) ) { $city_replace = str_replace( '\'', '', $city_info[ 'cityName' ] ); $city_replace = str_replace( ' ', '-', $city_replace ); $city_slug = strtolower( $city_replace ); $new_permalink = str_replace( array( '%city%', '%postname%', '%post_id%' ), array( $city_slug, $post_slug, $post->ID ), $permalink ); return $new_permalink; } return $permalink; } add_filter( 'post_link', 'sd_new_profile_permalink', 10, 3 ); add_filter( 'post_type_link', 'sd_new_profile_permalink', 10, 3 ); ``` So far nothing weird is happening, this is all doing what it's supposed to do, but now we get down to the issue (I think). I update the slug through a WPDB action, after the post is submitted, as seen below. ``` function set_profile_title_from_headline( $post_id ) { if ( empty( $_POST[ 'acf' ] ) ) { return; } if ( ! empty( $_POST[ 'acf' ][ 'field_57e3ed6c92ea0' ] ) ) { $entered_title = $_POST[ 'acf' ][ 'field_57e3ed6c92ea0' ]; $cleaned_title = preg_replace( '/[^A-Za-z0-9\-\s]/', '', $entered_title ); $post_name = sanitize_title( $cleaned_title ); update_field( 'sd_ad_title', $cleaned_title, $post_id ); global $wpdb; $wpdb->update( $wpdb->posts, array( 'post_title' => $cleaned_title, 'post_name' => $post_name ), array( 'ID' => $post_id ) ); clean_post_cache( $post_id ); } } add_action( 'acf/save_post', 'set_profile_title_from_headline', 20 ); ``` And then finally I rewrite the url. ``` function sd_single_profile_rewrite() { global $wp_rewrite; $wp_rewrite->add_permastruct( 'profile', 'profile/%city%/%postname%-%post_id%/', false ); add_rewrite_rule( 'profile\/([a-z-]+)\/(.+)-[0-9]+\/?$', 'index.php?post_type=profile&p=$matches[2]&city=$matches[1]&name=$matches[2]', 'top' ); } add_action( 'init', 'sd_single_profile_rewrite' ); ``` Basically my question is: Is there a way to 'do' what I want to do ? And if so, how :)
I was thinking too 'difficult'. Instead of rebuilding a new permalink structure I could have easily updated the new permalink the way I want to have it. So I deleted the entire rewrite part and changed the query in acf/save\_post to the following: ``` if ( ! empty( $_POST[ 'acf' ][ $ad_title ] ) ) { $entered_title = $_POST[ 'acf' ][ $ad_title ]; $cleaned_title = preg_replace( '/[^A-Za-z0-9\-\s]/', '', $entered_title ); // Removes special chars. $post_name = sanitize_title( $cleaned_title ); $city_name = get_field( 'sd_city_search_value', $post_id ); $new_slug = strtolower( $city_name ) . '-' . $post_name . '-' . $post_id; // update acf field update_field( 'sd_ad_title', $cleaned_title, $post_id ); // update post status + post title (if needed) global $wpdb; $wpdb->update( $wpdb->posts, array( 'post_title' => $cleaned_title, 'post_name' => strtolower( get_field( 'sd_city_search_value', $post_id ) ) . '-' . $post_name . '-' . $post_id ), array( 'ID' => $post_id ) ); clean_post_cache( $post_id ); } ```
294,039
<p>I have added the full array in end of the post. I have passed 'post_type', 'posts_per_page', 'tax_query' and 'meta_query' for <code>WP_Query</code>.</p> <p>This page take around 10 - 15 seconds to load... It is too much :-(... [Sorry : 10-15 seconds is wrong, when calculating it is about a minute... ]</p> <p>So I was looking at why it is too slow....</p> <p>If I remove <code>tax_query</code> part page load within 2 seconds... If I remove <code>meta_query</code> part again page load within 2 seconds.</p> <p>But when I use both <code>tax_query</code> and <code>meta_query</code> page takes more than 10 seconds.... What is the reason for it? How can I do to make this speed up?</p> <blockquote> <p>According to comments and <a href="https://tomjn.com/2016/12/05/post-meta-abuse/" rel="nofollow noreferrer">https://tomjn.com/2016/12/05/post-meta-abuse/</a>, meta queries are too slow. </p> <p><strong>Then question is</strong>, If I remove <code>tax_query</code> part page load within 2 seconds... If I remove <code>meta_query</code> part again page load within 2 seconds.</p> <p>But when I use both <code>tax_query</code> and <code>meta_query</code> page takes too much time.... What is the reason for it? How can I do to make this speed up?</p> </blockquote> <pre><code>$args = array( 'post_type' =&gt; 'movie', 'posts_per_page'=&gt;-1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'movie-type', 'field' =&gt; 'id', 'terms' =&gt; $movie_type, ), array( 'taxonomy' =&gt; 'genre', 'field' =&gt; 'id', 'terms' =&gt; $genre, ), array( 'taxonomy' =&gt; 'distributor', 'field' =&gt; 'id', 'terms' =&gt; $distributor, ), array( 'taxonomy' =&gt; 'orgin', 'field' =&gt; 'id', 'terms' =&gt; $orgin, ), array( 'taxonomy' =&gt; 'stage', 'field' =&gt; 'id', 'terms' =&gt; $stage, ), ), 'meta_query' =&gt; array( array( 'key' =&gt; 'wpcf-episode', 'value' =&gt; $episode, 'type' =&gt; 'numeric', 'compare' =&gt; 'IN', ), array( 'key' =&gt; 'wpcf-interval-period', 'value' =&gt; $interval, 'type' =&gt; 'numeric', 'compare' =&gt; 'IN', ), array( 'key' =&gt; 'wpcf-domestic-total-gross-usd', 'value' =&gt; array( $domestic_total_gross_usd_s, $domestic_total_gross_usd_f ), 'type' =&gt; 'numeric', 'compare' =&gt; 'BETWEEN', ), array( 'key' =&gt; 'wpcf-domestic-opening-usd', 'value' =&gt; array( $domestic_opening_usd_s, $domestic_opening_usd_f ), 'type' =&gt; 'numeric', 'compare' =&gt; 'BETWEEN', ), array( 'key' =&gt; 'wpcf-international-total-gross-usd', 'value' =&gt; array(0,1000000000), 'type' =&gt; 'numeric', 'compare' =&gt; 'BETWEEN', ), ), ); $all_movies = new WP_Query( $args ); </code></pre>
[ { "answer_id": 294178, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 5, "selected": true, "text": "<p>This is a stupendously expensive query, you can mitigate but you can't eliminate the performance issues.</p>\n\n<p>So lets start with the low hanging fruit and work our way up to the big problems</p>\n\n<h2>posts_per_page</h2>\n\n<p>Always set a maximum, even if it's one you never expect to reach. <code>-1</code> is asking for trouble:</p>\n\n<ul>\n<li>There's no upper limit, so the DB keeps working even after you have what you wanted</li>\n<li>There's no upper limit, so it's a very real possibility you'll get more results than you can store in memory, leading to memory exhaustion</li>\n<li>There's no upper limit, so there may be so many results that simply transferring them from the database may take too much time</li>\n<li>There's no upper limit, so you may run out of execution time trying to display them all</li>\n<li>There's no upper limit, so the DB can't factor in optimisations to save memory</li>\n</ul>\n\n<p>All the while, other people are using the site at the same time. This is a recipe for high CPU and memory usage (especially when combined with the later problems)</p>\n\n<p>So set it to 50 or 100, and use pagination</p>\n\n<h2>Post status</h2>\n\n<p>You don't set the post status, which most people don't, but if you did <code>WP_Query</code> would be able to optimise the query to better use table indexes! Always explicitly set the post status you want for performance reasons.</p>\n\n<p>This is because the default is not just <code>publish</code>, but it also factors in <code>private</code> posts that only you can see</p>\n\n<h2>pre_get_posts</h2>\n\n<p>If I'm not mistaken this looks like search functionality for finding and filtering movies. Why is this a custom query on a page template? Just think of the time spent on that main query that's been discarded, time wasted, resources spent then thrown away</p>\n\n<blockquote>\n <p><strong>me:</strong> I once asked my assistant for a hot chocolate but then changed my mind.\n Rather than say so, I waited until they came back from the coffee shop with the hot chocolate to tell them I actually wanted a tea, sending them out a second time.</p>\n \n <p>Now my tea is 30 minutes late and I had to throw away a hot chocolate, and people are complaining I'm slow</p>\n \n <p><strong>you:</strong> Couldn't you have mentioned it before they went instead of waiting till the end to tell them?</p>\n</blockquote>\n\n<p>By using <code>pre_get_posts</code> you can simplify your loop while eliminating an entire query. I strongly recommend you ask this as a new question:</p>\n\n<blockquote>\n <p>How do I use <code>pre_get_posts</code> on a page template to avoid a second query?</p>\n</blockquote>\n\n<h2>Multi-dimensional Taxonomy Query</h2>\n\n<p>Taxonomies are faster than post meta, much faster, but they are not free.</p>\n\n<p>A single taxonomy query can be quick, but multiple in the same query can drag things down</p>\n\n<p>If you can reduce or combine these in any way, the query will get faster. Intermediate values derived from existing ones can be used for performance purposes by calculating in advance.</p>\n\n<h2>Multi-dimensional Post Meta Queries</h2>\n\n<p>I cannot overstate how awful the performance of post meta queries are. They are in the top 3 of things to do to slow down your site.</p>\n\n<p>I suspect that the poor performance you're getting from these is actually on the optimistic end, and that as the site gets used, performance will actually get worse as the post meta table expands.</p>\n\n<p><strong><em>Avoid post meta queries at all costs</em></strong></p>\n\n<p>But to have multiple post meta queries, is even slower.</p>\n\n<p>For this I'll need several sub-sections:</p>\n\n<h3>It's Multiplication not Addition</h3>\n\n<blockquote>\n <p>If I remove tax_query part page load within 2 seconds... If I remove meta_query part again page load within 2 seconds.</p>\n \n <p>But when I use both tax_query and meta_query page takes more than 10 seconds</p>\n</blockquote>\n\n<p>Because the cost is not additive, <code>speed != taxspeed + metaspeed</code>, it's more like <code>speed = taxspeed * metaspeed</code>. Not just that, each dimension of the query has its own properties that can multiply it further. The end result is that adding 1 more dimension to the query scales the query logarithmically, not linearly.</p>\n\n<p>In addition, you're now involving an additional set of tables for MySQL to search across. Twice as many tables to search, twice as many indexes to load, twice as many temporary tables ( potentially a lot more than twice )</p>\n\n<h3>Table Scans</h3>\n\n<p>Lets consider these particular meta queries:</p>\n\n<pre><code>array(\n 'key' =&gt; 'wpcf-international-total-gross-usd',\n 'value' =&gt; array(0,1000000000),\n 'type' =&gt; 'numeric',\n 'compare' =&gt; 'BETWEEN',\n), \n</code></pre>\n\n<p>These can't rely on an index as there's math that needs to take place to determine if it fits or doesn't fit. As a result, MySQL now needs to do a table scan to build a temporary table. It has to do this for each of these, and table scans are slooow, and temporary tables take up memory. Then it has to do the original query but using these new temporary tables, adding more tables to the mix. Then it has to clean up these tables.</p>\n\n<p>You might even have ran out of physical memory during this process, pushing things on to the HD in swap memory, slowing down the entire process. Lets say that it only takes up half of memory in the worst scenario, that's still a maximum of 2 queries at a time before the site starts to suffer</p>\n\n<h1>Fixing The Query</h1>\n\n<p>Here is what I'm prescribing:</p>\n\n<ul>\n<li>reduce the number of options to search by, or use Elastic Search</li>\n<li>eliminate the post meta queries entirely</li>\n<li>store some post meta as taxonomies</li>\n<li>Store intermediate terms for post meta as buckets</li>\n</ul>\n\n<h2>reduce the number of options to search by, or use Elastic Search</h2>\n\n<p>You're simply querying for too many things. MySQL isn't built for these kinds of things! So either reduce the number of things you're querying for, precalculate groups so you can combine them, or use elastic search</p>\n\n<p>ES is okayish for simply queries, but it really shines when these kinds of queries crop up. As a bonus your site search becomes significantly better. You won't find ES on shared hosting, but you will on some managed hosting. You can also set it up yourself on VPS'</p>\n\n<h2>Eliminate the post meta queries entirely</h2>\n\n<p>If it's a choice between taxquery and metaquery, taxquery always wins, hands down. It has better performance, better memory management, faster queries, etc</p>\n\n<h2>store some post meta as taxonomies</h2>\n\n<p>These meta queries should be tax queries:</p>\n\n<pre><code>array(\n 'key' =&gt; 'wpcf-episode',\n 'value' =&gt; $episode,\n 'type' =&gt; 'numeric',\n 'compare' =&gt; 'IN',\n),\narray(\n 'key' =&gt; 'wpcf-interval-period',\n 'value' =&gt; $interval,\n 'type' =&gt; 'numeric',\n 'compare' =&gt; 'IN',\n),\n</code></pre>\n\n<p>Storing movie episode and interval period as post meta is inefficient now we know that they're searchable/filterable. <strong>They should be stored as a taxonomy</strong></p>\n\n<p>What's more, this calculation could have been done when the movie post was saved, and stored as a taxonomy term/tag/category:</p>\n\n<pre><code>array(\n 'key' =&gt; 'wpcf-international-total-gross-usd',\n 'value' =&gt; array(0,1000000000),\n 'type' =&gt; 'numeric',\n 'compare' =&gt; 'BETWEEN',\n),\n</code></pre>\n\n<p>It's basically asking did the movie get between 0 and 1 billion gross USD, which is pretty much every movie. With this in mind, is it really necessary? Could this field simply be eliminated?</p>\n\n<h2>Store intermediate terms for post meta as buckets</h2>\n\n<p>I'm looking at these:</p>\n\n<pre><code>array(\n 'key' =&gt; 'wpcf-domestic-total-gross-usd',\n 'value' =&gt; array( $domestic_total_gross_usd_s, $domestic_total_gross_usd_f ),\n 'type' =&gt; 'numeric',\n 'compare' =&gt; 'BETWEEN',\n),\narray(\n 'key' =&gt; 'wpcf-domestic-opening-usd',\n 'value' =&gt; array( $domestic_opening_usd_s, $domestic_opening_usd_f ),\n 'type' =&gt; 'numeric',\n 'compare' =&gt; 'BETWEEN',\n), \n</code></pre>\n\n<p>And I can imagine that there is a set of input boxes, that the user can type numbers into. My inner DB performance guru squirms in horror, but why?</p>\n\n<p>Most things in programming have a tradeoff, even if you don't realise it. In this case, you've ran into a performance vs accuracy tradeoff, and have chosen accuracy. So the solution here is to compromise.</p>\n\n<p>Keep these values stored as post meta, but don't query on them. Instead, query on calculated values, specifically, taxonomy terms representing buckets.</p>\n\n<p>A lot of people do this, if you look at e-commerce sites they don't give you input boxes, they give you ranges to choose from. $500-$1000, $1000-$2000, etc ranges of memory capacity, and so on. This simplifies the UI and improves UX, but importantly, it dramatically improves the performance of filters.</p>\n\n<p>So, create 2 new taxonomies, <code>domestic-opening</code> and <code>domestic-total-gross</code>, create buckets to put your movie posts into, and then present those as filter options. Now you have eliminated post meta queries.</p>\n\n<p>As a bonus, you now have <code>taxonomy-domestic-opening.php</code> and a free archive, as well as better REST support. Use some hooks on <code>save_post</code> to make sure these terms get set using the post meta value to set them, and all will be good</p>\n\n<h1>I'm already nearly done I don't have time to go back and redo all my content</h1>\n\n<p>And you don't have to! Use the power of WP CLI to convert your existing content so you don't have to recreate it.</p>\n\n<p>If you're on shared hosting and can't run WP CLI commands, download your site to a local environment, such as VVV, then run the WP CLI command on your own computer and upload the result back to your host.</p>\n" }, { "answer_id": 402419, "author": "O. Jones", "author_id": 13596, "author_profile": "https://wordpress.stackexchange.com/users/13596", "pm_score": 0, "selected": false, "text": "<p>Modern versions of MySQL and MariaDB make it much easier to index wp_postmeta and the other metadata tables to handle meta queries efficiently. Here's a <a href=\"https://wordpress.org/plugins/index-wp-mysql-for-speed/\" rel=\"nofollow noreferrer\">plugin</a> to do that.</p>\n<p>The new database versions make it possible to stop using prefix indexes (like <code>meta_key (meta_key(191))</code> on the columns in the meta tables, and index them completely.</p>\n<p>That, in turn, makes it possible to exploit the clustered primary key data structures in the new versions.</p>\n<p>This SQL statement does, to wp_postmeta, what the plugin does.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>ALTER TABLE wp_postmeta \n ADD UNIQUE KEY meta_id (meta_id), \n DROP PRIMARY KEY, ADD PRIMARY KEY (post_id, meta_key, meta_id),\n DROP KEY meta_key, ADD KEY meta_key (meta_key, meta_value(32), post_id, meta_id), \n ADD KEY meta_value (meta_value(32), meta_id),\n DROP KEY post_id;\n</code></pre>\n<p>Be careful, if you drop the primary key, to do two things:</p>\n<ul>\n<li>ADD a UNIQUE key on <code>meta_id</code> first.</li>\n<li>DROP the old primary key and ADD the new one in a single SQL statement.</li>\n</ul>\n<p>See also <a href=\"https://github.com/WordPress/performance/issues/132\" rel=\"nofollow noreferrer\">this Github issue</a> and <a href=\"https://www.plumislandmedia.net/index-wp-mysql-for-speed/tables_and_keys/\" rel=\"nofollow noreferrer\">this writeup</a> of the situation.</p>\n" } ]
2018/02/14
[ "https://wordpress.stackexchange.com/questions/294039", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123092/" ]
I have added the full array in end of the post. I have passed 'post\_type', 'posts\_per\_page', 'tax\_query' and 'meta\_query' for `WP_Query`. This page take around 10 - 15 seconds to load... It is too much :-(... [Sorry : 10-15 seconds is wrong, when calculating it is about a minute... ] So I was looking at why it is too slow.... If I remove `tax_query` part page load within 2 seconds... If I remove `meta_query` part again page load within 2 seconds. But when I use both `tax_query` and `meta_query` page takes more than 10 seconds.... What is the reason for it? How can I do to make this speed up? > > According to comments and > <https://tomjn.com/2016/12/05/post-meta-abuse/>, meta queries are > too slow. > > > **Then question is**, If I remove `tax_query` part page load within 2 seconds... If I remove `meta_query` part again page load within 2 > seconds. > > > But when I use both `tax_query` and `meta_query` page takes too much time.... What is the reason for it? How can I do to make this > speed up? > > > ``` $args = array( 'post_type' => 'movie', 'posts_per_page'=>-1, 'tax_query' => array( array( 'taxonomy' => 'movie-type', 'field' => 'id', 'terms' => $movie_type, ), array( 'taxonomy' => 'genre', 'field' => 'id', 'terms' => $genre, ), array( 'taxonomy' => 'distributor', 'field' => 'id', 'terms' => $distributor, ), array( 'taxonomy' => 'orgin', 'field' => 'id', 'terms' => $orgin, ), array( 'taxonomy' => 'stage', 'field' => 'id', 'terms' => $stage, ), ), 'meta_query' => array( array( 'key' => 'wpcf-episode', 'value' => $episode, 'type' => 'numeric', 'compare' => 'IN', ), array( 'key' => 'wpcf-interval-period', 'value' => $interval, 'type' => 'numeric', 'compare' => 'IN', ), array( 'key' => 'wpcf-domestic-total-gross-usd', 'value' => array( $domestic_total_gross_usd_s, $domestic_total_gross_usd_f ), 'type' => 'numeric', 'compare' => 'BETWEEN', ), array( 'key' => 'wpcf-domestic-opening-usd', 'value' => array( $domestic_opening_usd_s, $domestic_opening_usd_f ), 'type' => 'numeric', 'compare' => 'BETWEEN', ), array( 'key' => 'wpcf-international-total-gross-usd', 'value' => array(0,1000000000), 'type' => 'numeric', 'compare' => 'BETWEEN', ), ), ); $all_movies = new WP_Query( $args ); ```
This is a stupendously expensive query, you can mitigate but you can't eliminate the performance issues. So lets start with the low hanging fruit and work our way up to the big problems posts\_per\_page ---------------- Always set a maximum, even if it's one you never expect to reach. `-1` is asking for trouble: * There's no upper limit, so the DB keeps working even after you have what you wanted * There's no upper limit, so it's a very real possibility you'll get more results than you can store in memory, leading to memory exhaustion * There's no upper limit, so there may be so many results that simply transferring them from the database may take too much time * There's no upper limit, so you may run out of execution time trying to display them all * There's no upper limit, so the DB can't factor in optimisations to save memory All the while, other people are using the site at the same time. This is a recipe for high CPU and memory usage (especially when combined with the later problems) So set it to 50 or 100, and use pagination Post status ----------- You don't set the post status, which most people don't, but if you did `WP_Query` would be able to optimise the query to better use table indexes! Always explicitly set the post status you want for performance reasons. This is because the default is not just `publish`, but it also factors in `private` posts that only you can see pre\_get\_posts --------------- If I'm not mistaken this looks like search functionality for finding and filtering movies. Why is this a custom query on a page template? Just think of the time spent on that main query that's been discarded, time wasted, resources spent then thrown away > > **me:** I once asked my assistant for a hot chocolate but then changed my mind. > Rather than say so, I waited until they came back from the coffee shop with the hot chocolate to tell them I actually wanted a tea, sending them out a second time. > > > Now my tea is 30 minutes late and I had to throw away a hot chocolate, and people are complaining I'm slow > > > **you:** Couldn't you have mentioned it before they went instead of waiting till the end to tell them? > > > By using `pre_get_posts` you can simplify your loop while eliminating an entire query. I strongly recommend you ask this as a new question: > > How do I use `pre_get_posts` on a page template to avoid a second query? > > > Multi-dimensional Taxonomy Query -------------------------------- Taxonomies are faster than post meta, much faster, but they are not free. A single taxonomy query can be quick, but multiple in the same query can drag things down If you can reduce or combine these in any way, the query will get faster. Intermediate values derived from existing ones can be used for performance purposes by calculating in advance. Multi-dimensional Post Meta Queries ----------------------------------- I cannot overstate how awful the performance of post meta queries are. They are in the top 3 of things to do to slow down your site. I suspect that the poor performance you're getting from these is actually on the optimistic end, and that as the site gets used, performance will actually get worse as the post meta table expands. ***Avoid post meta queries at all costs*** But to have multiple post meta queries, is even slower. For this I'll need several sub-sections: ### It's Multiplication not Addition > > If I remove tax\_query part page load within 2 seconds... If I remove meta\_query part again page load within 2 seconds. > > > But when I use both tax\_query and meta\_query page takes more than 10 seconds > > > Because the cost is not additive, `speed != taxspeed + metaspeed`, it's more like `speed = taxspeed * metaspeed`. Not just that, each dimension of the query has its own properties that can multiply it further. The end result is that adding 1 more dimension to the query scales the query logarithmically, not linearly. In addition, you're now involving an additional set of tables for MySQL to search across. Twice as many tables to search, twice as many indexes to load, twice as many temporary tables ( potentially a lot more than twice ) ### Table Scans Lets consider these particular meta queries: ``` array( 'key' => 'wpcf-international-total-gross-usd', 'value' => array(0,1000000000), 'type' => 'numeric', 'compare' => 'BETWEEN', ), ``` These can't rely on an index as there's math that needs to take place to determine if it fits or doesn't fit. As a result, MySQL now needs to do a table scan to build a temporary table. It has to do this for each of these, and table scans are slooow, and temporary tables take up memory. Then it has to do the original query but using these new temporary tables, adding more tables to the mix. Then it has to clean up these tables. You might even have ran out of physical memory during this process, pushing things on to the HD in swap memory, slowing down the entire process. Lets say that it only takes up half of memory in the worst scenario, that's still a maximum of 2 queries at a time before the site starts to suffer Fixing The Query ================ Here is what I'm prescribing: * reduce the number of options to search by, or use Elastic Search * eliminate the post meta queries entirely * store some post meta as taxonomies * Store intermediate terms for post meta as buckets reduce the number of options to search by, or use Elastic Search ---------------------------------------------------------------- You're simply querying for too many things. MySQL isn't built for these kinds of things! So either reduce the number of things you're querying for, precalculate groups so you can combine them, or use elastic search ES is okayish for simply queries, but it really shines when these kinds of queries crop up. As a bonus your site search becomes significantly better. You won't find ES on shared hosting, but you will on some managed hosting. You can also set it up yourself on VPS' Eliminate the post meta queries entirely ---------------------------------------- If it's a choice between taxquery and metaquery, taxquery always wins, hands down. It has better performance, better memory management, faster queries, etc store some post meta as taxonomies ---------------------------------- These meta queries should be tax queries: ``` array( 'key' => 'wpcf-episode', 'value' => $episode, 'type' => 'numeric', 'compare' => 'IN', ), array( 'key' => 'wpcf-interval-period', 'value' => $interval, 'type' => 'numeric', 'compare' => 'IN', ), ``` Storing movie episode and interval period as post meta is inefficient now we know that they're searchable/filterable. **They should be stored as a taxonomy** What's more, this calculation could have been done when the movie post was saved, and stored as a taxonomy term/tag/category: ``` array( 'key' => 'wpcf-international-total-gross-usd', 'value' => array(0,1000000000), 'type' => 'numeric', 'compare' => 'BETWEEN', ), ``` It's basically asking did the movie get between 0 and 1 billion gross USD, which is pretty much every movie. With this in mind, is it really necessary? Could this field simply be eliminated? Store intermediate terms for post meta as buckets ------------------------------------------------- I'm looking at these: ``` array( 'key' => 'wpcf-domestic-total-gross-usd', 'value' => array( $domestic_total_gross_usd_s, $domestic_total_gross_usd_f ), 'type' => 'numeric', 'compare' => 'BETWEEN', ), array( 'key' => 'wpcf-domestic-opening-usd', 'value' => array( $domestic_opening_usd_s, $domestic_opening_usd_f ), 'type' => 'numeric', 'compare' => 'BETWEEN', ), ``` And I can imagine that there is a set of input boxes, that the user can type numbers into. My inner DB performance guru squirms in horror, but why? Most things in programming have a tradeoff, even if you don't realise it. In this case, you've ran into a performance vs accuracy tradeoff, and have chosen accuracy. So the solution here is to compromise. Keep these values stored as post meta, but don't query on them. Instead, query on calculated values, specifically, taxonomy terms representing buckets. A lot of people do this, if you look at e-commerce sites they don't give you input boxes, they give you ranges to choose from. $500-$1000, $1000-$2000, etc ranges of memory capacity, and so on. This simplifies the UI and improves UX, but importantly, it dramatically improves the performance of filters. So, create 2 new taxonomies, `domestic-opening` and `domestic-total-gross`, create buckets to put your movie posts into, and then present those as filter options. Now you have eliminated post meta queries. As a bonus, you now have `taxonomy-domestic-opening.php` and a free archive, as well as better REST support. Use some hooks on `save_post` to make sure these terms get set using the post meta value to set them, and all will be good I'm already nearly done I don't have time to go back and redo all my content ============================================================================ And you don't have to! Use the power of WP CLI to convert your existing content so you don't have to recreate it. If you're on shared hosting and can't run WP CLI commands, download your site to a local environment, such as VVV, then run the WP CLI command on your own computer and upload the result back to your host.
294,058
<p>I want to host Google fonts locally to hopefully shave some page loading time off.</p> <p>I hope to use <a href="https://google-webfonts-helper.herokuapp.com/fonts" rel="nofollow noreferrer">google-webfonts-helper</a> to do this.</p> <p>I would need to ensure our theme, Divi, does not load the original Google fonts.</p> <p>Currently, our site has the following in the head.</p> <pre><code>&lt;link data-asynced='1' as='style' onload='this.rel="stylesheet"' rel='preload' id='divi-fonts-css' href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&amp;#038;subset=latin,latin-ext' type='text/css' media='all' /&gt; </code></pre> <p>In <code>/Divi/core/functions.php</code>, there is:</p> <pre><code>if ( ! function_exists( 'et_core_get_main_fonts' ) ) : function et_core_get_main_fonts() { global $wp_version; if ( version_compare( $wp_version, '4.6', '&lt;' ) ) { return ''; } $fonts_url = ''; /* Translators: If there are characters in your language that are not * supported by Open Sans, translate this to 'off'. Do not translate * into your own language. */ $open_sans = _x( 'on', 'Open Sans font: on or off', 'Divi' ); if ( 'off' !== $open_sans ) { $font_families = array(); if ( 'off' !== $open_sans ) $font_families[] = 'Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800'; $protocol = is_ssl() ? 'https' : 'http'; $query_args = array( 'family' =&gt; implode( '%7C', $font_families ), 'subset' =&gt; 'latin,latin-ext', ); $fonts_url = add_query_arg( $query_args, "$protocol://fonts.googleapis.com/css" ); } return $fonts_url; } endif; if ( ! function_exists( 'et_core_load_main_fonts' ) ) : function et_core_load_main_fonts() { $fonts_url = et_core_get_main_fonts(); if ( empty( $fonts_url ) ) { return; } wp_enqueue_style( 'et-core-main-fonts', esc_url_raw( $fonts_url ), array(), null ); } endif; </code></pre> <p>How would I stop the Divi theme from loading the Google font?</p> <p>Do I need to disable the function <code>et_core_load_main_fonts</code> ?</p> <p>Help appreciated.</p>
[ { "answer_id": 294061, "author": "Maxim Sarandi", "author_id": 135962, "author_profile": "https://wordpress.stackexchange.com/users/135962", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://developer.wordpress.org/reference/functions/wp_dequeue_style/\" rel=\"nofollow noreferrer\">wp_dequeue_style()</a> should help you. You should dequeue style and enqueue your fonts.</p>\n\n<pre><code>wp_dequeue_style('et-core-main-fonts');\nwp_enqueue_style('your_fonts_handle', 'path_to_your_fonts');\n</code></pre>\n\n<p>Or redeclare function with your fonts.</p>\n\n<pre><code>et_core_load_main_fonts() {\n $fonts_url = et_core_get_main_fonts();\n if ( empty( $fonts_url ) ) {\n return;\n }\n\n wp_enqueue_style( 'et-core-main-fonts', esc_url_raw( 'path_to_your_style' ), array(), null );\n}\n</code></pre>\n" }, { "answer_id": 294062, "author": "Steve", "author_id": 3206, "author_profile": "https://wordpress.stackexchange.com/users/3206", "pm_score": 2, "selected": true, "text": "<p>Looks like someone has already done what I need to do.</p>\n\n<p>From <a href=\"https://designsbytierney.com/2017/06/optimize-google-font-delivery-wordpress-divi-theme/\" rel=\"nofollow noreferrer\">this post</a>, I can add the following code to my child theme's <code>functions.php</code>:</p>\n\n<pre><code>// REMOVE OPEN SANS GOOGLE FONT FROM DIVI\nfunction disable_open_sans_divi() {\nwp_dequeue_style( 'divi-fonts' );\n}\nadd_action( 'wp_enqueue_scripts', 'disable_open_sans_divi', 20 );\n</code></pre>\n" } ]
2018/02/14
[ "https://wordpress.stackexchange.com/questions/294058", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/3206/" ]
I want to host Google fonts locally to hopefully shave some page loading time off. I hope to use [google-webfonts-helper](https://google-webfonts-helper.herokuapp.com/fonts) to do this. I would need to ensure our theme, Divi, does not load the original Google fonts. Currently, our site has the following in the head. ``` <link data-asynced='1' as='style' onload='this.rel="stylesheet"' rel='preload' id='divi-fonts-css' href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&#038;subset=latin,latin-ext' type='text/css' media='all' /> ``` In `/Divi/core/functions.php`, there is: ``` if ( ! function_exists( 'et_core_get_main_fonts' ) ) : function et_core_get_main_fonts() { global $wp_version; if ( version_compare( $wp_version, '4.6', '<' ) ) { return ''; } $fonts_url = ''; /* Translators: If there are characters in your language that are not * supported by Open Sans, translate this to 'off'. Do not translate * into your own language. */ $open_sans = _x( 'on', 'Open Sans font: on or off', 'Divi' ); if ( 'off' !== $open_sans ) { $font_families = array(); if ( 'off' !== $open_sans ) $font_families[] = 'Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800'; $protocol = is_ssl() ? 'https' : 'http'; $query_args = array( 'family' => implode( '%7C', $font_families ), 'subset' => 'latin,latin-ext', ); $fonts_url = add_query_arg( $query_args, "$protocol://fonts.googleapis.com/css" ); } return $fonts_url; } endif; if ( ! function_exists( 'et_core_load_main_fonts' ) ) : function et_core_load_main_fonts() { $fonts_url = et_core_get_main_fonts(); if ( empty( $fonts_url ) ) { return; } wp_enqueue_style( 'et-core-main-fonts', esc_url_raw( $fonts_url ), array(), null ); } endif; ``` How would I stop the Divi theme from loading the Google font? Do I need to disable the function `et_core_load_main_fonts` ? Help appreciated.
Looks like someone has already done what I need to do. From [this post](https://designsbytierney.com/2017/06/optimize-google-font-delivery-wordpress-divi-theme/), I can add the following code to my child theme's `functions.php`: ``` // REMOVE OPEN SANS GOOGLE FONT FROM DIVI function disable_open_sans_divi() { wp_dequeue_style( 'divi-fonts' ); } add_action( 'wp_enqueue_scripts', 'disable_open_sans_divi', 20 ); ```
294,104
<p>I'm quite new to WordPress and wonder if there is a way to take the content in a normal page created in WP and show this content in a div tag through a page template?</p> <p>The setup is two divs next to each other showing different content based on the two WP pages. When I change a page's content, the output in the corresponding div tag should change as well.</p>
[ { "answer_id": 294111, "author": "Den Isahac", "author_id": 113233, "author_profile": "https://wordpress.stackexchange.com/users/113233", "pm_score": 1, "selected": false, "text": "<p>Assuming you have the following pages:</p>\n\n<ol>\n<li><strong>Home</strong></li>\n<li><strong>About us</strong> that has a slug of <code>about-us</code></li>\n</ol>\n\n<p>And you want to display the content of the <strong>About us</strong> page into the <strong>Home</strong> page.</p>\n\n<pre><code>&lt;?php \n $about_us = get_page_by_path('about-us'); // supply the page slug; i.e. about-us\n\n $about_us_content = get_the_content($about_us-&gt;ID);\n?&gt;\n\n&lt;div&gt;&lt;?php echo $about_us_content ; ?&gt;&lt;/div&gt;\n</code></pre>\n\n<p>Alternatively, you can use the <a href=\"https://codex.wordpress.org/Function_Reference/get_page_by_title\" rel=\"nofollow noreferrer\">get_page_by_title</a> to retrieve the post using its page <strong>title</strong></p>\n" }, { "answer_id": 294143, "author": "Abhay Yadav", "author_id": 136553, "author_profile": "https://wordpress.stackexchange.com/users/136553", "pm_score": 0, "selected": false, "text": "<p>you can get page data by id.</p>\n\n<pre><code>$pagecontent = get_post('hereispageid'); \necho $pagecontent -&gt;post_content;\n</code></pre>\n" } ]
2018/02/14
[ "https://wordpress.stackexchange.com/questions/294104", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/136852/" ]
I'm quite new to WordPress and wonder if there is a way to take the content in a normal page created in WP and show this content in a div tag through a page template? The setup is two divs next to each other showing different content based on the two WP pages. When I change a page's content, the output in the corresponding div tag should change as well.
Assuming you have the following pages: 1. **Home** 2. **About us** that has a slug of `about-us` And you want to display the content of the **About us** page into the **Home** page. ``` <?php $about_us = get_page_by_path('about-us'); // supply the page slug; i.e. about-us $about_us_content = get_the_content($about_us->ID); ?> <div><?php echo $about_us_content ; ?></div> ``` Alternatively, you can use the [get\_page\_by\_title](https://codex.wordpress.org/Function_Reference/get_page_by_title) to retrieve the post using its page **title**
294,105
<p>I am trying to setup a local version of a website that is live, I have downloaded the files and database and believe it is all ready and sorted, but I am having an issue whereby the site is trying to force HTTPS and so all browsers are reporting 'This site can’t provide a secure connection, localhost sent an invalid response.'.</p> <p>What is the way to handle this? Am I supposed to try to install a certificate?</p> <p>I am running MAMP for the apache and mysql servers. </p>
[ { "answer_id": 294107, "author": "sandrodz", "author_id": 115734, "author_profile": "https://wordpress.stackexchange.com/users/115734", "pm_score": 3, "selected": false, "text": "<p>WordPress keeps <code>WP_HOME</code> and <code>WP_SITEURL</code> in DB, this is set during initial installation and usually is the domain of your website, in your case it is a domain with <code>https</code>.</p>\n\n<p>Your visiting site via local domain, but WordPress redirects to https live domain, causing redirect loop which obviously fails.</p>\n\n<p>To fix this, change <code>WP_HOME</code> and <code>WP_SITEURL</code> values in DB.</p>\n\n<p>Or simply add this to wp-config.php:</p>\n\n<pre><code>define('WP_HOME','http://domain.local');\ndefine('WP_SITEURL','http://domain.local');\n</code></pre>\n\n<p>Also remember that your browser is caching redirects aggressively. You need to clean cache to see results, or use browser incognito mode.</p>\n" }, { "answer_id": 339751, "author": "Developeratchrome", "author_id": 153358, "author_profile": "https://wordpress.stackexchange.com/users/153358", "pm_score": 0, "selected": false, "text": "<p>you can also check if there are any plugins you have installed to support SSL. If so remove the plugin manually from the plugins folder.</p>\n" } ]
2018/02/14
[ "https://wordpress.stackexchange.com/questions/294105", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82748/" ]
I am trying to setup a local version of a website that is live, I have downloaded the files and database and believe it is all ready and sorted, but I am having an issue whereby the site is trying to force HTTPS and so all browsers are reporting 'This site can’t provide a secure connection, localhost sent an invalid response.'. What is the way to handle this? Am I supposed to try to install a certificate? I am running MAMP for the apache and mysql servers.
WordPress keeps `WP_HOME` and `WP_SITEURL` in DB, this is set during initial installation and usually is the domain of your website, in your case it is a domain with `https`. Your visiting site via local domain, but WordPress redirects to https live domain, causing redirect loop which obviously fails. To fix this, change `WP_HOME` and `WP_SITEURL` values in DB. Or simply add this to wp-config.php: ``` define('WP_HOME','http://domain.local'); define('WP_SITEURL','http://domain.local'); ``` Also remember that your browser is caching redirects aggressively. You need to clean cache to see results, or use browser incognito mode.
294,122
<p>Hello I have a menu with parent and children. Here is the code I am using to display it:</p> <pre><code>&lt;?php wp_nav_menu( array('menu' =&gt; 'Main Menu')); ?&gt; </code></pre> <p>This spits out something like this:</p> <pre><code>&lt;div class="main-menu-menu-container"&gt; &lt;ul class="main-menu-menu"&gt; &lt;li&gt; &lt;a href=""&gt;Parent&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href=""&gt;Parent&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href=""&gt;Parent&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Is there any way to use arguments such as items_wrap to remove the overall <code>&lt;ul&gt;</code> and turn the parent list items into divs? So the html would look like this:</p> <pre><code>&lt;div class="main-menu-menu-container"&gt; &lt;div&gt; &lt;a href=""&gt;Parent&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div&gt; &lt;a href=""&gt;Parent&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div&gt; &lt;a href=""&gt;Parent&lt;/a&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt;Child&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Its a pretty insane request so if its not possible its fine.</p> <p>Thanks!</p>
[ { "answer_id": 294124, "author": "cup_of", "author_id": 112836, "author_profile": "https://wordpress.stackexchange.com/users/112836", "pm_score": 0, "selected": false, "text": "<p>I figured it out with jQuery if anyone is interested.</p>\n\n<pre><code>jQuery('.main-menu-menu-container ul').wrap('&lt;div class=\"parent\"/&gt;').contents().unwrap();\njQuery('.main-menu-menu-container .menu-item-has-children').wrap('&lt;div class=\"child\"/&gt;').contents().unwrap();\n</code></pre>\n\n<p>I am still interested to know if its possible using php, so if anyone has a solution let me know!</p>\n" }, { "answer_id": 294131, "author": "guido", "author_id": 98339, "author_profile": "https://wordpress.stackexchange.com/users/98339", "pm_score": 3, "selected": true, "text": "<p>Since WordPress make use of <code>Walkers</code> you can extend the class <code>Walker_Nav_Menu</code> with your own and pass the instance of it to the function <code>wp_nav_menu</code>. </p>\n\n<p>So your call will be: </p>\n\n<pre><code>&lt;?php wp_nav_menu( array(\n 'menu' =&gt; 'Main Menu'\n 'walker' =&gt; new Custom_Nav_Walker()\n) ); ?&gt;\n</code></pre>\n\n<p>Then in a separated file create the class <code>Custom_Nav_Walker</code> that will be your walker.</p>\n\n<p>The class extends two methods of <code>Walker_Nav_Menu</code> that are <code>start_el</code> and <code>end_el</code>. The code within them is pretty the same of the main class, except that we introduce a little tweak to wrap the nav items with a <code>div</code>.</p>\n\n<p>WordPress unfortunately mix up php and html code sometimes using string like this one <code>$output .= $indent . '&lt;li' . $id . $class_names . '&gt;';</code> </p>\n\n<p>Within the <code>Walker_Nav_Menu::start_el</code> you'll find that line of code that is the opened tag for all of the list items ( the method is called everytime a new item need to be added to the list ). </p>\n\n<p>If we change it with this one <code>$output .= $indent . (0 === $depth ? '&lt;div ' : '&lt;li ' ) . $id . $class_names . '&gt;';</code> we'll use the <code>div</code> tag for all of the items at the first level. </p>\n\n<p>Then in the method <code>end_el</code> we change this one <code>$output .= \"&lt;/li&gt;{$n}\";</code> with <code>$output .= (0 === $depth ? \"&lt;/div&gt;{$n}\" : \"&lt;/li&gt;{$n}\");</code> so we can close the previously opened <code>div</code> tag.</p>\n\n<p>Unfortunately unless you deep into complicated regexp this is the best and rapid solution to achive your goal. </p>\n\n<p>The problem with this solution is that you must extend the <code>Walker_Nav_Menu</code> class and override the two methods above, meaning unnecessary code to maintain in case of WordPress change something.</p>\n\n<p>Here the entire subclass used as walker for the menu.</p>\n\n<pre><code>class Custom_Nav_Walker extends Walker_Nav_Menu {\n\npublic function start_el( &amp;$output, $item, $depth = 0, $args = [], $id = 0 ) {\n\n if ( isset( $args-&gt;item_spacing ) &amp;&amp; 'discard' === $args-&gt;item_spacing ) {\n $t = '';\n $n = '';\n } else {\n $t = \"\\t\";\n $n = \"\\n\";\n }\n $indent = ( $depth ) ? str_repeat( $t, $depth ) : '';\n\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $classes[] = 'menu-item-' . $item-&gt;ID;\n\n /**\n * Filters the arguments for a single nav menu item.\n *\n * @since 4.4.0\n *\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param WP_Post $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );\n\n /**\n * Filters the CSS class(es) applied to a menu item's list item element.\n *\n * @since 3.0.0\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param array $classes The CSS classes that are applied to the menu item's `&lt;li&gt;` element.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );\n $class_names = $class_names ? ' class=\"' . esc_attr( $class_names ) . '\"' : '';\n\n /**\n * Filters the ID applied to a menu item's list item element.\n *\n * @since 3.0.1\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param string $menu_id The ID that is applied to the menu item's `&lt;li&gt;` element.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item-&gt;ID, $item, $args, $depth );\n $id = $id ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n\n $output .= $indent . (0 === $depth ? '&lt;div ' : '&lt;li ' ) . $id . $class_names . '&gt;';\n\n $atts = array();\n $atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : '';\n $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : '';\n $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : '';\n $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : '';\n\n /**\n * Filters the HTML attributes applied to a menu item's anchor element.\n *\n * @since 3.6.0\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param array $atts {\n * The HTML attributes applied to the menu item's `&lt;a&gt;` element, empty strings are ignored.\n *\n * @type string $title Title attribute.\n * @type string $target Target attribute.\n * @type string $rel The rel attribute.\n * @type string $href The href attribute.\n * }\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );\n\n $attributes = '';\n foreach ( $atts as $attr =&gt; $value ) {\n if ( ! empty( $value ) ) {\n $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );\n $attributes .= ' ' . $attr . '=\"' . $value . '\"';\n }\n }\n\n /** This filter is documented in wp-includes/post-template.php */\n $title = apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID );\n\n /**\n * Filters a menu item's title.\n *\n * @since 4.4.0\n *\n * @param string $title The menu item's title.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );\n\n $item_output = $args-&gt;before;\n $item_output .= '&lt;a' . $attributes . '&gt;';\n $item_output .= $args-&gt;link_before . $title . $args-&gt;link_after;\n $item_output .= '&lt;/a&gt;';\n $item_output .= $args-&gt;after;\n\n /**\n * Filters a menu item's starting output.\n *\n * The menu item's starting output only includes `$args-&gt;before`, the opening `&lt;a&gt;`,\n * the menu item's title, the closing `&lt;/a&gt;`, and `$args-&gt;after`. Currently, there is\n * no filter for modifying the opening and closing `&lt;li&gt;` for a menu item.\n *\n * @since 3.0.0\n *\n * @param string $item_output The menu item's starting HTML output.\n * @param WP_Post $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n */\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n}\n\npublic function end_el( &amp;$output, $item, $depth = 0, $args = [] ) {\n\n if ( isset( $args-&gt;item_spacing ) &amp;&amp; 'discard' === $args-&gt;item_spacing ) {\n $t = '';\n $n = '';\n } else {\n $t = \"\\t\";\n $n = \"\\n\";\n }\n $output .= (0 === $depth ? \"&lt;/div&gt;{$n}\" : \"&lt;/li&gt;{$n}\");\n}\n</code></pre>\n\n<p>}</p>\n\n<p>I leave it the comments blocks from the original methods, but you get rid of them if you don't want to have info about the filters.</p>\n\n<p>The class <code>Walker_Nav_Menu</code> is located into <code>wp-includes/class-walker-nav-menu.php</code>.</p>\n" } ]
2018/02/14
[ "https://wordpress.stackexchange.com/questions/294122", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112836/" ]
Hello I have a menu with parent and children. Here is the code I am using to display it: ``` <?php wp_nav_menu( array('menu' => 'Main Menu')); ?> ``` This spits out something like this: ``` <div class="main-menu-menu-container"> <ul class="main-menu-menu"> <li> <a href="">Parent</a> <ul class="sub-menu"> <li><a>Child</a></li> <li><a>Child</a></li> </ul> </li> <li> <a href="">Parent</a> <ul class="sub-menu"> <li><a>Child</a></li> <li><a>Child</a></li> </ul> </li> <li> <a href="">Parent</a> <ul class="sub-menu"> <li><a>Child</a></li> <li><a>Child</a></li> </ul> </li> </ul> </div> ``` Is there any way to use arguments such as items\_wrap to remove the overall `<ul>` and turn the parent list items into divs? So the html would look like this: ``` <div class="main-menu-menu-container"> <div> <a href="">Parent</a> <ul class="sub-menu"> <li><a>Child</a></li> <li><a>Child</a></li> </ul> </div> <div> <a href="">Parent</a> <ul class="sub-menu"> <li><a>Child</a></li> <li><a>Child</a></li> </ul> </div> <div> <a href="">Parent</a> <ul class="sub-menu"> <li><a>Child</a></li> <li><a>Child</a></li> </ul> </div> </div> ``` Its a pretty insane request so if its not possible its fine. Thanks!
Since WordPress make use of `Walkers` you can extend the class `Walker_Nav_Menu` with your own and pass the instance of it to the function `wp_nav_menu`. So your call will be: ``` <?php wp_nav_menu( array( 'menu' => 'Main Menu' 'walker' => new Custom_Nav_Walker() ) ); ?> ``` Then in a separated file create the class `Custom_Nav_Walker` that will be your walker. The class extends two methods of `Walker_Nav_Menu` that are `start_el` and `end_el`. The code within them is pretty the same of the main class, except that we introduce a little tweak to wrap the nav items with a `div`. WordPress unfortunately mix up php and html code sometimes using string like this one `$output .= $indent . '<li' . $id . $class_names . '>';` Within the `Walker_Nav_Menu::start_el` you'll find that line of code that is the opened tag for all of the list items ( the method is called everytime a new item need to be added to the list ). If we change it with this one `$output .= $indent . (0 === $depth ? '<div ' : '<li ' ) . $id . $class_names . '>';` we'll use the `div` tag for all of the items at the first level. Then in the method `end_el` we change this one `$output .= "</li>{$n}";` with `$output .= (0 === $depth ? "</div>{$n}" : "</li>{$n}");` so we can close the previously opened `div` tag. Unfortunately unless you deep into complicated regexp this is the best and rapid solution to achive your goal. The problem with this solution is that you must extend the `Walker_Nav_Menu` class and override the two methods above, meaning unnecessary code to maintain in case of WordPress change something. Here the entire subclass used as walker for the menu. ``` class Custom_Nav_Walker extends Walker_Nav_Menu { public function start_el( &$output, $item, $depth = 0, $args = [], $id = 0 ) { if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $indent = ( $depth ) ? str_repeat( $t, $depth ) : ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = 'menu-item-' . $item->ID; /** * Filters the arguments for a single nav menu item. * * @since 4.4.0 * * @param stdClass $args An object of wp_nav_menu() arguments. * @param WP_Post $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. */ $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth ); /** * Filters the CSS class(es) applied to a menu item's list item element. * * @since 3.0.0 * @since 4.1.0 The `$depth` parameter was added. * * @param array $classes The CSS classes that are applied to the menu item's `<li>` element. * @param WP_Post $item The current menu item. * @param stdClass $args An object of wp_nav_menu() arguments. * @param int $depth Depth of menu item. Used for padding. */ $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) ); $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; /** * Filters the ID applied to a menu item's list item element. * * @since 3.0.1 * @since 4.1.0 The `$depth` parameter was added. * * @param string $menu_id The ID that is applied to the menu item's `<li>` element. * @param WP_Post $item The current menu item. * @param stdClass $args An object of wp_nav_menu() arguments. * @param int $depth Depth of menu item. Used for padding. */ $id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . (0 === $depth ? '<div ' : '<li ' ) . $id . $class_names . '>'; $atts = array(); $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; $atts['href'] = ! empty( $item->url ) ? $item->url : ''; /** * Filters the HTML attributes applied to a menu item's anchor element. * * @since 3.6.0 * @since 4.1.0 The `$depth` parameter was added. * * @param array $atts { * The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored. * * @type string $title Title attribute. * @type string $target Target attribute. * @type string $rel The rel attribute. * @type string $href The href attribute. * } * @param WP_Post $item The current menu item. * @param stdClass $args An object of wp_nav_menu() arguments. * @param int $depth Depth of menu item. Used for padding. */ $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } /** This filter is documented in wp-includes/post-template.php */ $title = apply_filters( 'the_title', $item->title, $item->ID ); /** * Filters a menu item's title. * * @since 4.4.0 * * @param string $title The menu item's title. * @param WP_Post $item The current menu item. * @param stdClass $args An object of wp_nav_menu() arguments. * @param int $depth Depth of menu item. Used for padding. */ $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth ); $item_output = $args->before; $item_output .= '<a' . $attributes . '>'; $item_output .= $args->link_before . $title . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; /** * Filters a menu item's starting output. * * The menu item's starting output only includes `$args->before`, the opening `<a>`, * the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is * no filter for modifying the opening and closing `<li>` for a menu item. * * @since 3.0.0 * * @param string $item_output The menu item's starting HTML output. * @param WP_Post $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param stdClass $args An object of wp_nav_menu() arguments. */ $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } public function end_el( &$output, $item, $depth = 0, $args = [] ) { if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $output .= (0 === $depth ? "</div>{$n}" : "</li>{$n}"); } ``` } I leave it the comments blocks from the original methods, but you get rid of them if you don't want to have info about the filters. The class `Walker_Nav_Menu` is located into `wp-includes/class-walker-nav-menu.php`.
294,132
<p>I have created a custom post type called 'reports' to provide an easy method for providing monthly reports to specific people. I don't want users to have to login to view the reports and I also don't want any user to find reports intended for another user. </p> <p>So I have created a custom taxonomy so I can create a term for each user. The term slug will be a random set of letters and numbers. I can manually create a 'random' slug, but I thought it would be better if the slug was programmatically created when adding the term. In this case the user would have to know their random term slug to view their reports, but they would never be able to guess another users slug. </p> <p>Example slugs would be: /c8etv35n/john-doe-report-january-2018 /c8etv35n/john-doe-report-february-2018 /76w8o9ev/jane-doe-report-january-2018</p> <p>With this type of arrangement, John Doe could view all of his reports in the taxonomy archive based on his random slug, but Jane Doe would not be able to guess how and where to find his reports and vice versa.</p> <p>I have search high and low for help on this, but I have not found a clear explanation for how to do it. I have looked into the edit_terms hook and others like wp_update_term. </p> <p>What I am hoping for is something like the save_post hook, then some way to affect the slug. I can handle the random string generation and everything else. If this is all possible, I would then just hide the 'slug' field from the Add Term screen and let the slug be generated randomly. </p>
[ { "answer_id": 294124, "author": "cup_of", "author_id": 112836, "author_profile": "https://wordpress.stackexchange.com/users/112836", "pm_score": 0, "selected": false, "text": "<p>I figured it out with jQuery if anyone is interested.</p>\n\n<pre><code>jQuery('.main-menu-menu-container ul').wrap('&lt;div class=\"parent\"/&gt;').contents().unwrap();\njQuery('.main-menu-menu-container .menu-item-has-children').wrap('&lt;div class=\"child\"/&gt;').contents().unwrap();\n</code></pre>\n\n<p>I am still interested to know if its possible using php, so if anyone has a solution let me know!</p>\n" }, { "answer_id": 294131, "author": "guido", "author_id": 98339, "author_profile": "https://wordpress.stackexchange.com/users/98339", "pm_score": 3, "selected": true, "text": "<p>Since WordPress make use of <code>Walkers</code> you can extend the class <code>Walker_Nav_Menu</code> with your own and pass the instance of it to the function <code>wp_nav_menu</code>. </p>\n\n<p>So your call will be: </p>\n\n<pre><code>&lt;?php wp_nav_menu( array(\n 'menu' =&gt; 'Main Menu'\n 'walker' =&gt; new Custom_Nav_Walker()\n) ); ?&gt;\n</code></pre>\n\n<p>Then in a separated file create the class <code>Custom_Nav_Walker</code> that will be your walker.</p>\n\n<p>The class extends two methods of <code>Walker_Nav_Menu</code> that are <code>start_el</code> and <code>end_el</code>. The code within them is pretty the same of the main class, except that we introduce a little tweak to wrap the nav items with a <code>div</code>.</p>\n\n<p>WordPress unfortunately mix up php and html code sometimes using string like this one <code>$output .= $indent . '&lt;li' . $id . $class_names . '&gt;';</code> </p>\n\n<p>Within the <code>Walker_Nav_Menu::start_el</code> you'll find that line of code that is the opened tag for all of the list items ( the method is called everytime a new item need to be added to the list ). </p>\n\n<p>If we change it with this one <code>$output .= $indent . (0 === $depth ? '&lt;div ' : '&lt;li ' ) . $id . $class_names . '&gt;';</code> we'll use the <code>div</code> tag for all of the items at the first level. </p>\n\n<p>Then in the method <code>end_el</code> we change this one <code>$output .= \"&lt;/li&gt;{$n}\";</code> with <code>$output .= (0 === $depth ? \"&lt;/div&gt;{$n}\" : \"&lt;/li&gt;{$n}\");</code> so we can close the previously opened <code>div</code> tag.</p>\n\n<p>Unfortunately unless you deep into complicated regexp this is the best and rapid solution to achive your goal. </p>\n\n<p>The problem with this solution is that you must extend the <code>Walker_Nav_Menu</code> class and override the two methods above, meaning unnecessary code to maintain in case of WordPress change something.</p>\n\n<p>Here the entire subclass used as walker for the menu.</p>\n\n<pre><code>class Custom_Nav_Walker extends Walker_Nav_Menu {\n\npublic function start_el( &amp;$output, $item, $depth = 0, $args = [], $id = 0 ) {\n\n if ( isset( $args-&gt;item_spacing ) &amp;&amp; 'discard' === $args-&gt;item_spacing ) {\n $t = '';\n $n = '';\n } else {\n $t = \"\\t\";\n $n = \"\\n\";\n }\n $indent = ( $depth ) ? str_repeat( $t, $depth ) : '';\n\n $classes = empty( $item-&gt;classes ) ? array() : (array) $item-&gt;classes;\n $classes[] = 'menu-item-' . $item-&gt;ID;\n\n /**\n * Filters the arguments for a single nav menu item.\n *\n * @since 4.4.0\n *\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param WP_Post $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );\n\n /**\n * Filters the CSS class(es) applied to a menu item's list item element.\n *\n * @since 3.0.0\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param array $classes The CSS classes that are applied to the menu item's `&lt;li&gt;` element.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );\n $class_names = $class_names ? ' class=\"' . esc_attr( $class_names ) . '\"' : '';\n\n /**\n * Filters the ID applied to a menu item's list item element.\n *\n * @since 3.0.1\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param string $menu_id The ID that is applied to the menu item's `&lt;li&gt;` element.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item-&gt;ID, $item, $args, $depth );\n $id = $id ? ' id=\"' . esc_attr( $id ) . '\"' : '';\n\n $output .= $indent . (0 === $depth ? '&lt;div ' : '&lt;li ' ) . $id . $class_names . '&gt;';\n\n $atts = array();\n $atts['title'] = ! empty( $item-&gt;attr_title ) ? $item-&gt;attr_title : '';\n $atts['target'] = ! empty( $item-&gt;target ) ? $item-&gt;target : '';\n $atts['rel'] = ! empty( $item-&gt;xfn ) ? $item-&gt;xfn : '';\n $atts['href'] = ! empty( $item-&gt;url ) ? $item-&gt;url : '';\n\n /**\n * Filters the HTML attributes applied to a menu item's anchor element.\n *\n * @since 3.6.0\n * @since 4.1.0 The `$depth` parameter was added.\n *\n * @param array $atts {\n * The HTML attributes applied to the menu item's `&lt;a&gt;` element, empty strings are ignored.\n *\n * @type string $title Title attribute.\n * @type string $target Target attribute.\n * @type string $rel The rel attribute.\n * @type string $href The href attribute.\n * }\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );\n\n $attributes = '';\n foreach ( $atts as $attr =&gt; $value ) {\n if ( ! empty( $value ) ) {\n $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );\n $attributes .= ' ' . $attr . '=\"' . $value . '\"';\n }\n }\n\n /** This filter is documented in wp-includes/post-template.php */\n $title = apply_filters( 'the_title', $item-&gt;title, $item-&gt;ID );\n\n /**\n * Filters a menu item's title.\n *\n * @since 4.4.0\n *\n * @param string $title The menu item's title.\n * @param WP_Post $item The current menu item.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n * @param int $depth Depth of menu item. Used for padding.\n */\n $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );\n\n $item_output = $args-&gt;before;\n $item_output .= '&lt;a' . $attributes . '&gt;';\n $item_output .= $args-&gt;link_before . $title . $args-&gt;link_after;\n $item_output .= '&lt;/a&gt;';\n $item_output .= $args-&gt;after;\n\n /**\n * Filters a menu item's starting output.\n *\n * The menu item's starting output only includes `$args-&gt;before`, the opening `&lt;a&gt;`,\n * the menu item's title, the closing `&lt;/a&gt;`, and `$args-&gt;after`. Currently, there is\n * no filter for modifying the opening and closing `&lt;li&gt;` for a menu item.\n *\n * @since 3.0.0\n *\n * @param string $item_output The menu item's starting HTML output.\n * @param WP_Post $item Menu item data object.\n * @param int $depth Depth of menu item. Used for padding.\n * @param stdClass $args An object of wp_nav_menu() arguments.\n */\n $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );\n}\n\npublic function end_el( &amp;$output, $item, $depth = 0, $args = [] ) {\n\n if ( isset( $args-&gt;item_spacing ) &amp;&amp; 'discard' === $args-&gt;item_spacing ) {\n $t = '';\n $n = '';\n } else {\n $t = \"\\t\";\n $n = \"\\n\";\n }\n $output .= (0 === $depth ? \"&lt;/div&gt;{$n}\" : \"&lt;/li&gt;{$n}\");\n}\n</code></pre>\n\n<p>}</p>\n\n<p>I leave it the comments blocks from the original methods, but you get rid of them if you don't want to have info about the filters.</p>\n\n<p>The class <code>Walker_Nav_Menu</code> is located into <code>wp-includes/class-walker-nav-menu.php</code>.</p>\n" } ]
2018/02/15
[ "https://wordpress.stackexchange.com/questions/294132", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119171/" ]
I have created a custom post type called 'reports' to provide an easy method for providing monthly reports to specific people. I don't want users to have to login to view the reports and I also don't want any user to find reports intended for another user. So I have created a custom taxonomy so I can create a term for each user. The term slug will be a random set of letters and numbers. I can manually create a 'random' slug, but I thought it would be better if the slug was programmatically created when adding the term. In this case the user would have to know their random term slug to view their reports, but they would never be able to guess another users slug. Example slugs would be: /c8etv35n/john-doe-report-january-2018 /c8etv35n/john-doe-report-february-2018 /76w8o9ev/jane-doe-report-january-2018 With this type of arrangement, John Doe could view all of his reports in the taxonomy archive based on his random slug, but Jane Doe would not be able to guess how and where to find his reports and vice versa. I have search high and low for help on this, but I have not found a clear explanation for how to do it. I have looked into the edit\_terms hook and others like wp\_update\_term. What I am hoping for is something like the save\_post hook, then some way to affect the slug. I can handle the random string generation and everything else. If this is all possible, I would then just hide the 'slug' field from the Add Term screen and let the slug be generated randomly.
Since WordPress make use of `Walkers` you can extend the class `Walker_Nav_Menu` with your own and pass the instance of it to the function `wp_nav_menu`. So your call will be: ``` <?php wp_nav_menu( array( 'menu' => 'Main Menu' 'walker' => new Custom_Nav_Walker() ) ); ?> ``` Then in a separated file create the class `Custom_Nav_Walker` that will be your walker. The class extends two methods of `Walker_Nav_Menu` that are `start_el` and `end_el`. The code within them is pretty the same of the main class, except that we introduce a little tweak to wrap the nav items with a `div`. WordPress unfortunately mix up php and html code sometimes using string like this one `$output .= $indent . '<li' . $id . $class_names . '>';` Within the `Walker_Nav_Menu::start_el` you'll find that line of code that is the opened tag for all of the list items ( the method is called everytime a new item need to be added to the list ). If we change it with this one `$output .= $indent . (0 === $depth ? '<div ' : '<li ' ) . $id . $class_names . '>';` we'll use the `div` tag for all of the items at the first level. Then in the method `end_el` we change this one `$output .= "</li>{$n}";` with `$output .= (0 === $depth ? "</div>{$n}" : "</li>{$n}");` so we can close the previously opened `div` tag. Unfortunately unless you deep into complicated regexp this is the best and rapid solution to achive your goal. The problem with this solution is that you must extend the `Walker_Nav_Menu` class and override the two methods above, meaning unnecessary code to maintain in case of WordPress change something. Here the entire subclass used as walker for the menu. ``` class Custom_Nav_Walker extends Walker_Nav_Menu { public function start_el( &$output, $item, $depth = 0, $args = [], $id = 0 ) { if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $indent = ( $depth ) ? str_repeat( $t, $depth ) : ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = 'menu-item-' . $item->ID; /** * Filters the arguments for a single nav menu item. * * @since 4.4.0 * * @param stdClass $args An object of wp_nav_menu() arguments. * @param WP_Post $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. */ $args = apply_filters( 'nav_menu_item_args', $args, $item, $depth ); /** * Filters the CSS class(es) applied to a menu item's list item element. * * @since 3.0.0 * @since 4.1.0 The `$depth` parameter was added. * * @param array $classes The CSS classes that are applied to the menu item's `<li>` element. * @param WP_Post $item The current menu item. * @param stdClass $args An object of wp_nav_menu() arguments. * @param int $depth Depth of menu item. Used for padding. */ $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) ); $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; /** * Filters the ID applied to a menu item's list item element. * * @since 3.0.1 * @since 4.1.0 The `$depth` parameter was added. * * @param string $menu_id The ID that is applied to the menu item's `<li>` element. * @param WP_Post $item The current menu item. * @param stdClass $args An object of wp_nav_menu() arguments. * @param int $depth Depth of menu item. Used for padding. */ $id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . (0 === $depth ? '<div ' : '<li ' ) . $id . $class_names . '>'; $atts = array(); $atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : ''; $atts['target'] = ! empty( $item->target ) ? $item->target : ''; $atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : ''; $atts['href'] = ! empty( $item->url ) ? $item->url : ''; /** * Filters the HTML attributes applied to a menu item's anchor element. * * @since 3.6.0 * @since 4.1.0 The `$depth` parameter was added. * * @param array $atts { * The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored. * * @type string $title Title attribute. * @type string $target Target attribute. * @type string $rel The rel attribute. * @type string $href The href attribute. * } * @param WP_Post $item The current menu item. * @param stdClass $args An object of wp_nav_menu() arguments. * @param int $depth Depth of menu item. Used for padding. */ $atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( ! empty( $value ) ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } /** This filter is documented in wp-includes/post-template.php */ $title = apply_filters( 'the_title', $item->title, $item->ID ); /** * Filters a menu item's title. * * @since 4.4.0 * * @param string $title The menu item's title. * @param WP_Post $item The current menu item. * @param stdClass $args An object of wp_nav_menu() arguments. * @param int $depth Depth of menu item. Used for padding. */ $title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth ); $item_output = $args->before; $item_output .= '<a' . $attributes . '>'; $item_output .= $args->link_before . $title . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; /** * Filters a menu item's starting output. * * The menu item's starting output only includes `$args->before`, the opening `<a>`, * the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is * no filter for modifying the opening and closing `<li>` for a menu item. * * @since 3.0.0 * * @param string $item_output The menu item's starting HTML output. * @param WP_Post $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param stdClass $args An object of wp_nav_menu() arguments. */ $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } public function end_el( &$output, $item, $depth = 0, $args = [] ) { if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $output .= (0 === $depth ? "</div>{$n}" : "</li>{$n}"); } ``` } I leave it the comments blocks from the original methods, but you get rid of them if you don't want to have info about the filters. The class `Walker_Nav_Menu` is located into `wp-includes/class-walker-nav-menu.php`.
294,138
<p>I want to display products that are related either by category or attributes (not tags)</p> <p>I've modified the solution posted here <a href="https://stackoverflow.com/questions/40769017/wordpress-woocommerce-related-products-by-attribute">here</a> to my needs:</p> <pre><code>function custom_related_product_args ( $args ){ global $product; $cats = wc_get_product_terms( $product-&gt;id, 'product_cat', array( 'fields' =&gt; 'slugs' ) ); $brands = wc_get_product_terms( $product-&gt;id, 'pa_brand', array( 'fields' =&gt; 'slugs' ) ); $collections = wc_get_product_terms( $product-&gt;id, 'pa_collection', array( 'fields' =&gt; 'slugs' ) ); unset( $args['post__in'] ); $args['tax_query'] = array( 'relation' =&gt; 'OR', array( 'taxonomy' =&gt; 'product_cat', 'field' =&gt; 'slug', 'terms' =&gt; $cats, ), array( 'relation' =&gt; 'OR', array( 'taxonomy' =&gt; 'pa_brand', 'field' =&gt; 'slug', 'terms' =&gt; $brands, ), array( 'taxonomy' =&gt; 'pa_collection', 'field' =&gt; 'slug', 'terms' =&gt; $collections, ) ) ); return $args; } add_filter('woocommerce_related_products_args', 'custom_related_product_args'); </code></pre> <p>However it doesn't seem to work for me and I can't figure out what I'm doing wrong?</p>
[ { "answer_id": 294139, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<pre><code>global $product;\n\n$cats = wc_get_product_terms( $product-&gt;id, 'product_cat', array( 'fields' =&gt; 'slugs' ) );\n$brands = wc_get_product_terms( $product-&gt;id, 'pa_brand', array( 'fields' =&gt; 'slugs' ) );\n$artists = wc_get_product_terms( $product-&gt;id, 'pa_artist', array( 'fields' =&gt; 'slugs' ) ); \n$manufacturers = wc_get_product_terms( $product-&gt;id, 'pa_manufacturer', array( 'fields' =&gt; 'slugs' ) );\n\nunset( $args['post__in'] );\n$args['tax_query'] = array( \n 'relation' =&gt; 'AND',\n array(\n 'taxonomy' =&gt; 'product_cat',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $cats,\n ),\n array(\n 'relation' =&gt; 'OR',\n array(\n 'taxonomy' =&gt; 'pa_brand',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $brands,\n ),\n array(\n 'taxonomy' =&gt; 'pa_artist',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $artists,\n ),\n array(\n 'taxonomy' =&gt; 'pa_manufacturer',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $manufacturers,\n )\n )\n);\n\nreturn $args;\n</code></pre>\n" }, { "answer_id": 367030, "author": "Paris Koutroumanos", "author_id": 81401, "author_profile": "https://wordpress.stackexchange.com/users/81401", "pm_score": 1, "selected": false, "text": "<p>Disable default Related Products and try this (Add custom code to the functions.php)</p>\n\n<pre><code>add_action( 'woocommerce_after_single_product_summary', 'custom_output_product_collection', 12 );\nfunction custom_output_product_collection(){\n\n ## --- YOUR SETTINGS --- ##\n\n $attribute = \"attribute_slug\"; // &lt;== HERE define your attribute slug\n $limit = \"5\"; // &lt;== Number of products to be displayed\n $cols = \"5\"; // &lt;== Number of columns\n $orderby = \"rand\"; // &lt;== Order by argument (random order here)\n\n ## --- THE CODE --- ##\n\n global $post, $wpdb;\n\n // Formatting the attribute\n $attribute = sanitize_title( $attribute );\n $taxonomy = 'pa_' . $attribute;\n\n // Get the WP_Term object for the current product and the defined product attribute\n $terms = wp_get_post_terms( $post-&gt;ID, $taxonomy );\n $term = reset($terms);\n\n // Get all product IDs that have the same product attribute value (except current product ID)\n $product_ids = $wpdb-&gt;get_col( \"SELECT DISTINCT tr.object_id\n FROM {$wpdb-&gt;prefix}term_relationships as tr\n JOIN {$wpdb-&gt;prefix}term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id\n JOIN {$wpdb-&gt;prefix}terms as t ON tt.term_id = t.term_id\n WHERE tt.taxonomy LIKE '$taxonomy' AND t.term_id = '{$term-&gt;term_id}' AND tr.object_id != '{$post-&gt;ID}'\" );\n\n // Convert array values to a coma separated string\n $ids = implode( ',', $product_ids );\n\n ## --- THE OUTPUT --- ##\n\n echo '&lt;section class=\"'.$attribute.' '.$attribute.'-'.$term-&gt;slug.' products\"&gt;\n &lt;h2&gt;'.__( \"Collection\", \"woocommerce\" ).': '.$term-&gt;name.'&lt;/h2&gt;';\n\n echo do_shortcode(\"[products ids='$ids' columns='$cols' limit='$limit' orderby='$orderby']\");\n\n echo '&lt;/section&gt;';\n}\n</code></pre>\n" } ]
2018/02/15
[ "https://wordpress.stackexchange.com/questions/294138", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131684/" ]
I want to display products that are related either by category or attributes (not tags) I've modified the solution posted here [here](https://stackoverflow.com/questions/40769017/wordpress-woocommerce-related-products-by-attribute) to my needs: ``` function custom_related_product_args ( $args ){ global $product; $cats = wc_get_product_terms( $product->id, 'product_cat', array( 'fields' => 'slugs' ) ); $brands = wc_get_product_terms( $product->id, 'pa_brand', array( 'fields' => 'slugs' ) ); $collections = wc_get_product_terms( $product->id, 'pa_collection', array( 'fields' => 'slugs' ) ); unset( $args['post__in'] ); $args['tax_query'] = array( 'relation' => 'OR', array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => $cats, ), array( 'relation' => 'OR', array( 'taxonomy' => 'pa_brand', 'field' => 'slug', 'terms' => $brands, ), array( 'taxonomy' => 'pa_collection', 'field' => 'slug', 'terms' => $collections, ) ) ); return $args; } add_filter('woocommerce_related_products_args', 'custom_related_product_args'); ``` However it doesn't seem to work for me and I can't figure out what I'm doing wrong?
Disable default Related Products and try this (Add custom code to the functions.php) ``` add_action( 'woocommerce_after_single_product_summary', 'custom_output_product_collection', 12 ); function custom_output_product_collection(){ ## --- YOUR SETTINGS --- ## $attribute = "attribute_slug"; // <== HERE define your attribute slug $limit = "5"; // <== Number of products to be displayed $cols = "5"; // <== Number of columns $orderby = "rand"; // <== Order by argument (random order here) ## --- THE CODE --- ## global $post, $wpdb; // Formatting the attribute $attribute = sanitize_title( $attribute ); $taxonomy = 'pa_' . $attribute; // Get the WP_Term object for the current product and the defined product attribute $terms = wp_get_post_terms( $post->ID, $taxonomy ); $term = reset($terms); // Get all product IDs that have the same product attribute value (except current product ID) $product_ids = $wpdb->get_col( "SELECT DISTINCT tr.object_id FROM {$wpdb->prefix}term_relationships as tr JOIN {$wpdb->prefix}term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id JOIN {$wpdb->prefix}terms as t ON tt.term_id = t.term_id WHERE tt.taxonomy LIKE '$taxonomy' AND t.term_id = '{$term->term_id}' AND tr.object_id != '{$post->ID}'" ); // Convert array values to a coma separated string $ids = implode( ',', $product_ids ); ## --- THE OUTPUT --- ## echo '<section class="'.$attribute.' '.$attribute.'-'.$term->slug.' products"> <h2>'.__( "Collection", "woocommerce" ).': '.$term->name.'</h2>'; echo do_shortcode("[products ids='$ids' columns='$cols' limit='$limit' orderby='$orderby']"); echo '</section>'; } ```