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
272,021
<p>I use wordpress theme in my website. Question is simple, i want to add inside my articles as an inline note, caution, warning quote like picture. How can i do that? Is there any plugin or way to do that? </p> <p><a href="https://i.stack.imgur.com/KuF4z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KuF4z.png" alt="enter image description here"></a></p>
[ { "answer_id": 272034, "author": "BenB", "author_id": 62909, "author_profile": "https://wordpress.stackexchange.com/users/62909", "pm_score": 0, "selected": false, "text": "<p>Run in your theme the CSS of admin dashboard. </p>\n\n<pre><code>wp_enqueue_style( 'wp-admin' );\n</code></pre>\...
2017/07/02
[ "https://wordpress.stackexchange.com/questions/272021", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122986/" ]
I use wordpress theme in my website. Question is simple, i want to add inside my articles as an inline note, caution, warning quote like picture. How can i do that? Is there any plugin or way to do that? [![enter image description here](https://i.stack.imgur.com/KuF4z.png)](https://i.stack.imgur.com/KuF4z.png)
You can hook into [`the_content`](https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content) filter and add your note after every post. Then you can style it to have a nice quote. ``` add_filter('the_content','add_my_note'); function add_my_note($content){ // Write your note here $note = ' <div class="my-note"> <h3>Note Header</h3> <p>Note body</p> </div>'; // Append the note to the content $content = $content . $note; // Return the modified content return $content; } ``` This will add the note to your post's content. Now time to style it. ``` .my-note { display:block; background:lightgray; border-width: 0 0 0 3px; border-color:grey; color:black; border-style:solid; padding: 1em; } .my-note h3 { display:block; font-size: 2em } .my-note p { display:block; font-size : 1em; } ``` I've done some basic styling for you, which you can change to fit your tastes,
272,053
<p>I am currently using a <code>WP_Query</code> that'll trigger from an AJAX call when a button is pressed. The post meta fields <code>lat</code> <code>lng</code> will be used as location data for a google map. The query outputs fine without AJAX but cannot seem to get it to return the results with it. </p> <p>The response I receive - <code>[{name: "", lng: null, lat: null}, {name: "", lng: null, lat: null}]</code></p> <p>Now I believe the error is when transforming the results into JSON at <code>json_encode</code> stage, but not too sure? Any help would be great, fairly new to AJAX!</p> <p><strong>Function.php</strong></p> <pre><code>&lt;?php //Search Function function ek_search(){ $args = array( 'orderby' =&gt; 'date', 'order' =&gt; $_POST['date'], 'post_type' =&gt; 'property', 'posts_per_page' =&gt; 20, 'date_query' =&gt; array( array( 'after' =&gt; $_POST['property_added'] ), ), ); $query = new WP_Query( $args ); $posts = $query-&gt;get_posts(); foreach( $posts as $post ) { $locations[] = array( "name" =&gt; get_the_title(), "lng" =&gt; get_field('loc_lng'), "lat" =&gt; get_field('loc_lat') ); } $location = json_encode($locations); echo $location; die(); } add_action( 'wp_ajax_nopriv_ek_search', 'ek_search' ); add_action( 'wp_ajax_ek_search', 'ek_search' ); </code></pre> <p><strong>Form</strong></p> <pre><code>&lt;form id="filter"&gt; &lt;button&gt;Search&lt;/button&gt; &lt;input type="hidden" name="action" value="ek_search"&gt; &lt;/form&gt; </code></pre> <p><strong>JS</strong></p> <pre><code>jQuery(function($){ $('#filter').submit(function(){ var filter = $('#filter'); var ajaxurl = '&lt;?php echo admin_url("admin-ajax.php", null); ?&gt;'; data = { action: "ek_search"}; $.ajax({ url: ajaxurl, data:data, type: 'post', dataType: 'json', success: function(response) { console.log(response); } }); return false; }); }); </code></pre>
[ { "answer_id": 272065, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 4, "selected": true, "text": "<p>Admin-AJAX is not optimized for JSON. If you need your answer to be in JSON, use the REST-API instead. This ...
2017/07/02
[ "https://wordpress.stackexchange.com/questions/272053", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87036/" ]
I am currently using a `WP_Query` that'll trigger from an AJAX call when a button is pressed. The post meta fields `lat` `lng` will be used as location data for a google map. The query outputs fine without AJAX but cannot seem to get it to return the results with it. The response I receive - `[{name: "", lng: null, lat: null}, {name: "", lng: null, lat: null}]` Now I believe the error is when transforming the results into JSON at `json_encode` stage, but not too sure? Any help would be great, fairly new to AJAX! **Function.php** ``` <?php //Search Function function ek_search(){ $args = array( 'orderby' => 'date', 'order' => $_POST['date'], 'post_type' => 'property', 'posts_per_page' => 20, 'date_query' => array( array( 'after' => $_POST['property_added'] ), ), ); $query = new WP_Query( $args ); $posts = $query->get_posts(); foreach( $posts as $post ) { $locations[] = array( "name" => get_the_title(), "lng" => get_field('loc_lng'), "lat" => get_field('loc_lat') ); } $location = json_encode($locations); echo $location; die(); } add_action( 'wp_ajax_nopriv_ek_search', 'ek_search' ); add_action( 'wp_ajax_ek_search', 'ek_search' ); ``` **Form** ``` <form id="filter"> <button>Search</button> <input type="hidden" name="action" value="ek_search"> </form> ``` **JS** ``` jQuery(function($){ $('#filter').submit(function(){ var filter = $('#filter'); var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>'; data = { action: "ek_search"}; $.ajax({ url: ajaxurl, data:data, type: 'post', dataType: 'json', success: function(response) { console.log(response); } }); return false; }); }); ```
Admin-AJAX is not optimized for JSON. If you need your answer to be in JSON, use the REST-API instead. This API generates JSON response by default. All you have to do is to register a rest route, and access the URL: ``` add_action( 'rest_api_init', function () { //Path to REST route and the callback function register_rest_route( 'scopeak/v2', '/my_request/', array( 'methods' => 'POST', 'callback' => 'my_json_response' ) ); }); ``` Now, the callback function: ``` function my_json_response(){ $args = array( 'orderby' => 'date', 'order' => $_POST['date'], 'post_type' => 'property', 'posts_per_page' => 20, 'date_query' => array( array( 'after' => $_POST['property_added'] ), ), ); $query = new WP_Query( $args ); if($query->have_posts()){ while($query->have_posts()){ $query->the_post(); $locations[]['name'] = get_the_title(); $locations[]['lat'] = get_field('loc_lng'); $locations[]['lng'] = get_field('loc_lat'); } } //Return the data return $locations; } ``` Now, you can get your JSON response by visiting the following URL: ``` wp-json/scopeak/v2/my_json_response/ ``` For testing purposes, you can change `POST` method to `GET` and directly access this URL. If you get a response, then change it back to `POST` and work on your javascript. That's all.
272,075
<p>Apologies, for the very long title.</p> <p>I'd really appreciate any help that anyone can offer with a situation I have currently before I go for the plugin option.</p> <p>About a month ago I moved my site from:</p> <p><code>http</code> to <code>https</code></p> <p>I did the move myself and all went well.</p> <p>Last night I decided to update the Permalink Structure from:</p> <blockquote> <p>/category/postname/</p> </blockquote> <p>to</p> <blockquote> <p>/postname/</p> </blockquote> <p>This switch went well and the site is running perfectly.</p> <p>Now what I need to address is all the old URLs indexed in Google.</p> <p>I have this <code>.htaccess</code> file on the .com version of my site:</p> <pre><code>RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] # 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 </code></pre> <p>And I'm wondering if there is a modification that could be made to the above to permanently redirect the indexed URLs to there corresponding post on the new blog.</p> <p>Indexed URLs such as:</p> <blockquote> <p>www.oldsite.net/category/postname</p> </blockquote> <p>are returning a 404.</p> <p>Any help would be really appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 272058, "author": "wplearner", "author_id": 120693, "author_profile": "https://wordpress.stackexchange.com/users/120693", "pm_score": 2, "selected": true, "text": "<p>I am able to locate that file in my theme.\nFor categories woocommerce.php in root directory of my theme i...
2017/07/02
[ "https://wordpress.stackexchange.com/questions/272075", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123028/" ]
Apologies, for the very long title. I'd really appreciate any help that anyone can offer with a situation I have currently before I go for the plugin option. About a month ago I moved my site from: `http` to `https` I did the move myself and all went well. Last night I decided to update the Permalink Structure from: > > /category/postname/ > > > to > > /postname/ > > > This switch went well and the site is running perfectly. Now what I need to address is all the old URLs indexed in Google. I have this `.htaccess` file on the .com version of my site: ``` RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] # 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 ``` And I'm wondering if there is a modification that could be made to the above to permanently redirect the indexed URLs to there corresponding post on the new blog. Indexed URLs such as: > > www.oldsite.net/category/postname > > > are returning a 404. Any help would be really appreciated. Thanks.
I am able to locate that file in my theme. For categories woocommerce.php in root directory of my theme is working and i am able to complete my task. Thank you!
272,106
<p>I'm having a little problem getting an information. In my plugin, I got a situation where I have to throw, in a very specific situation, a 403 error. But I can't find in the documentation if there is a recommended way to throw a 403, because WP LOVES wrap everything it's own way.</p> <p>So! Do you know a way to trigger a 403 manually ?</p> <p>Thanks</p>
[ { "answer_id": 272107, "author": "Junaid", "author_id": 66571, "author_profile": "https://wordpress.stackexchange.com/users/66571", "pm_score": 2, "selected": false, "text": "<p>Is there any limitation/issue setting/thowing <code>403</code> the usual PHP way?</p>\n\n<pre><code>header('HT...
2017/07/03
[ "https://wordpress.stackexchange.com/questions/272106", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94823/" ]
I'm having a little problem getting an information. In my plugin, I got a situation where I have to throw, in a very specific situation, a 403 error. But I can't find in the documentation if there is a recommended way to throw a 403, because WP LOVES wrap everything it's own way. So! Do you know a way to trigger a 403 manually ? Thanks
Is there any limitation/issue setting/thowing `403` the usual PHP way? ``` header('HTTP/1.0 403 Forbidden'); die('You are not allowed to access this file.'); ```
272,108
<p>I'm trying to add a login/register button to my home page only when a user is logged out. I've tried using the do_shortcode call into the relevant template: (I know there is currently no conditional to check if logged in but I just want to ensure that the shortcode actually works first of all) <pre><code>add_shortcode('loginout_button','add_loginout_button'); function add_loginout_button { $content = '&lt;div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"&gt;&lt;a href=""&gt; LOGIN/REGISTER &lt;/a&gt; &lt;/div&gt;'; return $content; } </code></pre> <p>which is then called using the </p> <pre><code>echo do_shortcode('[loginout_button']); </code></pre> <p>in the template, but the shortcode is not registering- it's only echoing [loginout_button]. I guess this is not the way to do it then! Do I have to use a filter and then apply_filters? It made sense in my head but I honestly now need some help with this one- thanks in advance!</p>
[ { "answer_id": 272107, "author": "Junaid", "author_id": 66571, "author_profile": "https://wordpress.stackexchange.com/users/66571", "pm_score": 2, "selected": false, "text": "<p>Is there any limitation/issue setting/thowing <code>403</code> the usual PHP way?</p>\n\n<pre><code>header('HT...
2017/07/03
[ "https://wordpress.stackexchange.com/questions/272108", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123044/" ]
I'm trying to add a login/register button to my home page only when a user is logged out. I've tried using the do\_shortcode call into the relevant template: (I know there is currently no conditional to check if logged in but I just want to ensure that the shortcode actually works first of all) ``` add_shortcode('loginout_button','add_loginout_button'); function add_loginout_button { $content = '<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href=""> LOGIN/REGISTER </a> </div>'; return $content; } ``` which is then called using the ``` echo do_shortcode('[loginout_button']); ``` in the template, but the shortcode is not registering- it's only echoing [loginout\_button]. I guess this is not the way to do it then! Do I have to use a filter and then apply\_filters? It made sense in my head but I honestly now need some help with this one- thanks in advance!
Is there any limitation/issue setting/thowing `403` the usual PHP way? ``` header('HTTP/1.0 403 Forbidden'); die('You are not allowed to access this file.'); ```
272,111
<p>I'm using <code>get_pages()</code> to create a custom navigation that lists pages with a link, title and thumbnail for each page. How can I add a "current-item" class to the item corresponding to the current page?</p> <p>I'm using the following code:</p> <pre><code>&lt;?php $our_pages = get_pages( array( 'sort_column' =&gt; 'menu_order' ) ); foreach ($our_pages as $key =&gt; $page_item): ?&gt; &lt;div class="menu-item"&gt; &lt;a href="&lt;?php echo esc_url(get_permalink($page_item-&gt;ID)); ?&gt;" class="menu-item-clicker"&gt;&lt;span&gt;&lt;?php echo $page_item-&gt;post_title ; ?&gt;&lt;/span&gt;&lt;/a&gt; &lt;?php echo get_the_post_thumbnail($page_item-&gt;ID,'full'); ?&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>The following does not display the class, but to illustrate what I'm trying to do, here's the conditional I tried, with no success:</p> <pre><code>&lt;?php $our_pages = get_pages( array( 'sort_column' =&gt; 'menu_order' ) ); foreach ($our_pages as $key =&gt; $page_item) : if($page-&gt;ID == $page_item-&gt;ID) { $class = 'current-item'; } ?&gt; &lt;div class="menu-item &lt;?php echo $class; ?&gt;"&gt; &lt;a href="&lt;?php echo esc_url(get_permalink($page_item-&gt;ID)); ?&gt;" class="menu-item-clicker"&gt;&lt;span&gt;&lt;?php echo $page_item-&gt;post_title ; ?&gt;&lt;/span&gt;&lt;/a&gt; &lt;?php echo get_the_post_thumbnail($page_item-&gt;ID,'full'); ?&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; </code></pre> <p>Looking forward to your input!</p>
[ { "answer_id": 272107, "author": "Junaid", "author_id": 66571, "author_profile": "https://wordpress.stackexchange.com/users/66571", "pm_score": 2, "selected": false, "text": "<p>Is there any limitation/issue setting/thowing <code>403</code> the usual PHP way?</p>\n\n<pre><code>header('HT...
2017/07/03
[ "https://wordpress.stackexchange.com/questions/272111", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113555/" ]
I'm using `get_pages()` to create a custom navigation that lists pages with a link, title and thumbnail for each page. How can I add a "current-item" class to the item corresponding to the current page? I'm using the following code: ``` <?php $our_pages = get_pages( array( 'sort_column' => 'menu_order' ) ); foreach ($our_pages as $key => $page_item): ?> <div class="menu-item"> <a href="<?php echo esc_url(get_permalink($page_item->ID)); ?>" class="menu-item-clicker"><span><?php echo $page_item->post_title ; ?></span></a> <?php echo get_the_post_thumbnail($page_item->ID,'full'); ?> </div> <?php endforeach; ?> ``` The following does not display the class, but to illustrate what I'm trying to do, here's the conditional I tried, with no success: ``` <?php $our_pages = get_pages( array( 'sort_column' => 'menu_order' ) ); foreach ($our_pages as $key => $page_item) : if($page->ID == $page_item->ID) { $class = 'current-item'; } ?> <div class="menu-item <?php echo $class; ?>"> <a href="<?php echo esc_url(get_permalink($page_item->ID)); ?>" class="menu-item-clicker"><span><?php echo $page_item->post_title ; ?></span></a> <?php echo get_the_post_thumbnail($page_item->ID,'full'); ?> </div> <?php endforeach; ?> ``` Looking forward to your input!
Is there any limitation/issue setting/thowing `403` the usual PHP way? ``` header('HTTP/1.0 403 Forbidden'); die('You are not allowed to access this file.'); ```
272,128
<p>I did little tweak for date archive permalink.</p> <pre><code>function my_rewrite_rules($wp_rewrite){ $rules = array(); $rules['news/([0-9]{4})/?$'] = 'index.php?year=$matches[1]'; $wp_rewrite-&gt;rules = $rules + $wp_rewrite-&gt;rules; } add_action('generate_rewrite_rules', 'my_rewrite_rules'); </code></pre> <p>Then hit the url below.</p> <pre><code>http://blahblah.blahblah/wp/news/2017/ </code></pre> <p>This successfully shows posts belong to 2017. </p> <p>Now I want to generate the links for date archive, but this doesn't generate the code I want.</p> <pre><code>get_year_link($year); </code></pre> <p>Still generate the default permalink like this:</p> <pre><code>http://blahblah.blahblah/wp/date/2017/ </code></pre> <p>So how do I tell wordpress what permastructure to use? Otherwise I may have to hard code...</p>
[ { "answer_id": 276819, "author": "Luca Reghellin", "author_id": 10381, "author_profile": "https://wordpress.stackexchange.com/users/10381", "pm_score": 1, "selected": false, "text": "<p>Yes norixxx, your comment above is the right answer:</p>\n\n<pre><code>add_filter('year_link', 'change...
2017/07/03
[ "https://wordpress.stackexchange.com/questions/272128", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/37130/" ]
I did little tweak for date archive permalink. ``` function my_rewrite_rules($wp_rewrite){ $rules = array(); $rules['news/([0-9]{4})/?$'] = 'index.php?year=$matches[1]'; $wp_rewrite->rules = $rules + $wp_rewrite->rules; } add_action('generate_rewrite_rules', 'my_rewrite_rules'); ``` Then hit the url below. ``` http://blahblah.blahblah/wp/news/2017/ ``` This successfully shows posts belong to 2017. Now I want to generate the links for date archive, but this doesn't generate the code I want. ``` get_year_link($year); ``` Still generate the default permalink like this: ``` http://blahblah.blahblah/wp/date/2017/ ``` So how do I tell wordpress what permastructure to use? Otherwise I may have to hard code...
You can change the date links by directly modifying the `date_structure`: ``` function wpd_change_date_structure(){ global $wp_rewrite; $wp_rewrite->date_structure = 'news/%year%/%monthnum%/%day%'; } add_action( 'init', 'wpd_change_date_structure' ); ``` Don't forget to flush rewrite rules after the change. WordPress will use this to generate the rewrite rules for incoming requests as well as URL output when using API functions like `get_year_link`, so there's no need for a filter.
272,130
<p>I have already tried about 20 different methods to get this working with no solution.</p> <p>I am trying to change the classes of the buttons in the WooCommerce mini cart widget as shown below.</p> <p><a href="https://i.stack.imgur.com/XO8L9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XO8L9.png" alt="enter image description here"></a></p> <p>The mark up for those buttons is written in two functions inside the wc-template-functions.php file:</p> <pre><code>if ( ! function_exists( 'woocommerce_widget_shopping_cart_button_view_cart' ) ) { /** * Output the proceed to checkout button. * * @subpackage Cart */ function woocommerce_widget_shopping_cart_button_view_cart() { echo '&lt;a href="' . esc_url( wc_get_cart_url() ) . '" class="button wc-forward"&gt;' . esc_html__( 'View cart', 'woocommerce' ) . '&lt;/a&gt;'; } } if ( ! function_exists( 'woocommerce_widget_shopping_cart_proceed_to_checkout' ) ) { /** * Output the proceed to checkout button. * * @subpackage Cart */ function woocommerce_widget_shopping_cart_proceed_to_checkout() { echo '&lt;a href="' . esc_url( wc_get_checkout_url() ) . '" class="button checkout wc-forward"&gt;' . esc_html__( 'Checkout', 'woocommerce' ) . '&lt;/a&gt;'; } } </code></pre> <p>What is the correct way to override these functions within my own theme so that i can change the classes of those two buttons?</p>
[ { "answer_id": 281853, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 2, "selected": false, "text": "<p>Not sure if you still need help with this but this might help others in your situation.</p>\n\n<p>If you want to ...
2017/07/03
[ "https://wordpress.stackexchange.com/questions/272130", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118673/" ]
I have already tried about 20 different methods to get this working with no solution. I am trying to change the classes of the buttons in the WooCommerce mini cart widget as shown below. [![enter image description here](https://i.stack.imgur.com/XO8L9.png)](https://i.stack.imgur.com/XO8L9.png) The mark up for those buttons is written in two functions inside the wc-template-functions.php file: ``` if ( ! function_exists( 'woocommerce_widget_shopping_cart_button_view_cart' ) ) { /** * Output the proceed to checkout button. * * @subpackage Cart */ function woocommerce_widget_shopping_cart_button_view_cart() { echo '<a href="' . esc_url( wc_get_cart_url() ) . '" class="button wc-forward">' . esc_html__( 'View cart', 'woocommerce' ) . '</a>'; } } if ( ! function_exists( 'woocommerce_widget_shopping_cart_proceed_to_checkout' ) ) { /** * Output the proceed to checkout button. * * @subpackage Cart */ function woocommerce_widget_shopping_cart_proceed_to_checkout() { echo '<a href="' . esc_url( wc_get_checkout_url() ) . '" class="button checkout wc-forward">' . esc_html__( 'Checkout', 'woocommerce' ) . '</a>'; } } ``` What is the correct way to override these functions within my own theme so that i can change the classes of those two buttons?
Not sure if you still need help with this but this might help others in your situation. If you want to change the class of the `<p>` tag in your example, the file you need to edit can be found in `/wp-content/plugins/woocommerce/templates/cart/mini-cart.php` Obviously, don't directly edit the file. Copy it in to your theme (or preferably child theme) folder under `/wp-content/themes/your-theme-folder/woocommerce/cart/mini-cart.php` and you can edit line #75 to put in your own CSS class(es). Line #75 reads: ``` <p class="woocommerce-mini-cart__buttons buttons"><?php do_action( 'woocommerce_widget_shopping_cart_buttons' ); ?></p> ``` If you want to alter the CSS class of the `<a>` tag, then you'll need to remove the default 'action' and create your own within your theme (or preferably child themes) `functions.php` file eg. ``` remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart', 10 ); remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_proceed_to_checkout', 20 ); function my_woocommerce_widget_shopping_cart_button_view_cart() { echo '<a href="' . esc_url( wc_get_cart_url() ) . '" class="btn btn-default">' . esc_html__( 'View cart', 'woocommerce' ) . '</a>'; } function my_woocommerce_widget_shopping_cart_proceed_to_checkout() { echo '<a href="' . esc_url( wc_get_checkout_url() ) . '" class="btn btn-default">' . esc_html__( 'Checkout', 'woocommerce' ) . '</a>'; } add_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_button_view_cart', 10 ); add_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_proceed_to_checkout', 20 ); ``` You'll need to clear your browser cache or add another item to the cart to see the changes as the cart content is saved in the browsers sessionStorage to avoid pulling a new copy on every page.
272,135
<p>I have created a page on one of our sites which has a few snippets of custom CSS to make it display in a very modern, 100% width style <a href="http://www.hotrs.co.uk/" rel="nofollow noreferrer">like this</a>, as opposed to the standard, more constrained style of pages the site's theme allows. </p> <p>This style of page, however, is not going to be used site-wide, so getting a new theme or editing the existing theme's child isn't really an option. </p> <p>What I'd instead like to do is create a simple plugin that will add a checkbox to the edit page that, when checked, will load this custom CSS on the page in question. I know roughly how to set a plugin up, but how would I write it to;</p> <ul> <li>Add a checkbox to the edit page?</li> <li>If the checkbox is ticked, load the custom CSS?</li> </ul> <p>While I could just add this custom CSS to each page manually, creating a plugin would mean transporting the code around from site to site will be much easier, and also mean that the risk of overwriting and losing it would be minimized.</p>
[ { "answer_id": 281853, "author": "Mat", "author_id": 37985, "author_profile": "https://wordpress.stackexchange.com/users/37985", "pm_score": 2, "selected": false, "text": "<p>Not sure if you still need help with this but this might help others in your situation.</p>\n\n<p>If you want to ...
2017/07/03
[ "https://wordpress.stackexchange.com/questions/272135", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120427/" ]
I have created a page on one of our sites which has a few snippets of custom CSS to make it display in a very modern, 100% width style [like this](http://www.hotrs.co.uk/), as opposed to the standard, more constrained style of pages the site's theme allows. This style of page, however, is not going to be used site-wide, so getting a new theme or editing the existing theme's child isn't really an option. What I'd instead like to do is create a simple plugin that will add a checkbox to the edit page that, when checked, will load this custom CSS on the page in question. I know roughly how to set a plugin up, but how would I write it to; * Add a checkbox to the edit page? * If the checkbox is ticked, load the custom CSS? While I could just add this custom CSS to each page manually, creating a plugin would mean transporting the code around from site to site will be much easier, and also mean that the risk of overwriting and losing it would be minimized.
Not sure if you still need help with this but this might help others in your situation. If you want to change the class of the `<p>` tag in your example, the file you need to edit can be found in `/wp-content/plugins/woocommerce/templates/cart/mini-cart.php` Obviously, don't directly edit the file. Copy it in to your theme (or preferably child theme) folder under `/wp-content/themes/your-theme-folder/woocommerce/cart/mini-cart.php` and you can edit line #75 to put in your own CSS class(es). Line #75 reads: ``` <p class="woocommerce-mini-cart__buttons buttons"><?php do_action( 'woocommerce_widget_shopping_cart_buttons' ); ?></p> ``` If you want to alter the CSS class of the `<a>` tag, then you'll need to remove the default 'action' and create your own within your theme (or preferably child themes) `functions.php` file eg. ``` remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart', 10 ); remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_proceed_to_checkout', 20 ); function my_woocommerce_widget_shopping_cart_button_view_cart() { echo '<a href="' . esc_url( wc_get_cart_url() ) . '" class="btn btn-default">' . esc_html__( 'View cart', 'woocommerce' ) . '</a>'; } function my_woocommerce_widget_shopping_cart_proceed_to_checkout() { echo '<a href="' . esc_url( wc_get_checkout_url() ) . '" class="btn btn-default">' . esc_html__( 'Checkout', 'woocommerce' ) . '</a>'; } add_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_button_view_cart', 10 ); add_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_proceed_to_checkout', 20 ); ``` You'll need to clear your browser cache or add another item to the cart to see the changes as the cart content is saved in the browsers sessionStorage to avoid pulling a new copy on every page.
272,158
<p>I have a custom post type called <code>vacancies</code> and another called <code>our_homes</code></p> <p>How do I get the google map coordinates from <code>our_homes</code> and display inside the <code>vacancies</code> single post template?</p> <p>My attempt below shows my tragic attempt at code inside the single-vacancies.php file:</p> <pre><code> &lt;?php //Query custom post type our_homes and display tabs for each $query = new WP_Query( array( 'post_type' =&gt; 'our_homes', 'field' =&gt; 'slug', 'posts_per_page' =&gt; 999 ) ); if ( $query-&gt;have_posts() ) : //$count = 1; //$title = the_title(); //$location = get_field('google_map_coordinates'); ?&gt; &lt;?php while ( $query-&gt;have_posts() ) : $query-&gt;the_post(); $location = get_field('google_map_coordinates', post_title); ?&gt; &lt;?php if($title = $label) { echo $title; } //echo $label; ?&gt; &lt;?php endwhile; wp_reset_postdata(); ?&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 272164, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": -1, "selected": false, "text": "<p>Try to do this inside the loop</p>\n\n<pre><code>$location = get_field('google_map_coordi...
2017/07/03
[ "https://wordpress.stackexchange.com/questions/272158", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63480/" ]
I have a custom post type called `vacancies` and another called `our_homes` How do I get the google map coordinates from `our_homes` and display inside the `vacancies` single post template? My attempt below shows my tragic attempt at code inside the single-vacancies.php file: ``` <?php //Query custom post type our_homes and display tabs for each $query = new WP_Query( array( 'post_type' => 'our_homes', 'field' => 'slug', 'posts_per_page' => 999 ) ); if ( $query->have_posts() ) : //$count = 1; //$title = the_title(); //$location = get_field('google_map_coordinates'); ?> <?php while ( $query->have_posts() ) : $query->the_post(); $location = get_field('google_map_coordinates', post_title); ?> <?php if($title = $label) { echo $title; } //echo $label; ?> <?php endwhile; wp_reset_postdata(); ?> <?php endif; ?> ```
Although your question is confusing, but based on your attempts, I can say that you are using a loop inside another loop. You should store an array of main loop's titles in an array, and then write another loop **outside** the original loop and check the array. So, this is what your main query would look like (I summarized it and removed the actual loop): ``` if(have_posts()){ // Define an empty array $posts_title = array(); while(have_posts()){ // Store each title inside the array $posts_title[] = get_the_title(); } } ``` Now, you have an array of post titles. Write this query after the main query is finished, and closed: ``` $query = new WP_Query( array( 'post_type' => 'our_homes', 'posts_per_page' => -1 ) ); if ( $query->have_posts() ) { $count = 0; while ( $query->have_posts() ) { $query->the_post(); $count++; // Check if this post's title matches the $label if( in_array( get_the_title(), $posts_title )) { // Do whatever you want the_title(); } } } wp_reset_postdata(); ``` Also, if you need to get the post's or page's ID by their title, you can use [`get_page_by_title('TITLE HERE')`](https://codex.wordpress.org/Function_Reference/get_page_by_title) function.
272,161
<p>I am customizing a theme that has the following code to display comments:</p> <pre><code>if ( have_comments() ) : ?&gt; &lt;h2 class="comments-title"&gt; &lt;?php printf( // WPCS: XSS OK. esc_html( _nx( 'One thought on &amp;ldquo;%2$s&amp;rdquo;', '%1$s thoughts on &amp;ldquo;%2$s&amp;rdquo;', get_comments_number(), 'comments title', 'kadabra' ) ), number_format_i18n( get_comments_number() ), '&lt;span&gt;' . get_the_title() . '&lt;/span&gt;' ); ?&gt; &lt;/h2&gt; </code></pre> <p>however it always shows the following:</p> <pre><code>0 thoughts on “Post title” </code></pre> <p>even though I have several comments and the <code>if ( have_comments() ) :</code> part is passed. Any ideas?</p> <p>PS: wp_debug is enabled and show no errors as well.</p>
[ { "answer_id": 272178, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>From quick look at the source there seems to be three possibilities:</p>\n\n<ol>\n<li><code>get_post()</code> retur...
2017/07/03
[ "https://wordpress.stackexchange.com/questions/272161", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103046/" ]
I am customizing a theme that has the following code to display comments: ``` if ( have_comments() ) : ?> <h2 class="comments-title"> <?php printf( // WPCS: XSS OK. esc_html( _nx( 'One thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', get_comments_number(), 'comments title', 'kadabra' ) ), number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' ); ?> </h2> ``` however it always shows the following: ``` 0 thoughts on “Post title” ``` even though I have several comments and the `if ( have_comments() ) :` part is passed. Any ideas? PS: wp\_debug is enabled and show no errors as well.
From quick look at the source there seems to be three possibilities: 1. `get_post()` returned *falsy* value, so current post context is invalid in some way. 2. `$post->comment_count` is `0`. 3. `get_comments_number` filter is being used to adjust the output. Most commonly it would be case 1/2 with something interfering with global post context, dump `get_post()` at the point and see if it contains expected instance.
272,163
<p>I create a new db connection with: $mydb = new wpdb (<em>db info</em>)</p> <p>I know it connects but for some reason I am unable to get any data from: </p> <pre><code>$pulled = $mydb-&gt;get_results($mydb-&gt;prepare($query), "ARRAY_A"). </code></pre> <p>I know the query it self is written correctly but for some reason $pulled contains no data. Anyone have any suggestions or solutions, please and thank you.</p>
[ { "answer_id": 272178, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>From quick look at the source there seems to be three possibilities:</p>\n\n<ol>\n<li><code>get_post()</code> retur...
2017/07/03
[ "https://wordpress.stackexchange.com/questions/272163", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123061/" ]
I create a new db connection with: $mydb = new wpdb (*db info*) I know it connects but for some reason I am unable to get any data from: ``` $pulled = $mydb->get_results($mydb->prepare($query), "ARRAY_A"). ``` I know the query it self is written correctly but for some reason $pulled contains no data. Anyone have any suggestions or solutions, please and thank you.
From quick look at the source there seems to be three possibilities: 1. `get_post()` returned *falsy* value, so current post context is invalid in some way. 2. `$post->comment_count` is `0`. 3. `get_comments_number` filter is being used to adjust the output. Most commonly it would be case 1/2 with something interfering with global post context, dump `get_post()` at the point and see if it contains expected instance.
272,179
<p>I know this has been covered in different ways a thousand times (I read all the posts), but it seems not specifically for my case. I can't really get it to work myself, being a big development noobie. </p> <p>I have a template which shows the last posts on the front page. I changed the type of posts shown to <code>question</code> (my website is a Q&amp;A one) but then pagination was only showing 13 pages while there are 29 pages of questions. 13 pages being the number of non-custom-type normal posts. So I added this code in <code>functions.php</code>: </p> <pre><code>add_action( 'pre_get_posts', function($q) { if( !is_admin() &amp;&amp; $q-&gt;is_main_query() &amp;&amp; !$q-&gt;is_tax() ) { $q-&gt;set ('post_type', array( 'question' ) ); } }); </code></pre> <p>Now it counts the number of Questions correctly but it throws a 404 error every time I click on the link to a question. I understand that <code>pre_get_posts</code> is not the best approach, but I really don't know how to change it and use <code>WP_Query</code> instead, as I saw was advised to.</p> <p>Any fix to that ? Thank you &lt;3 </p>
[ { "answer_id": 272178, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": false, "text": "<p>From quick look at the source there seems to be three possibilities:</p>\n\n<ol>\n<li><code>get_post()</code> retur...
2017/07/03
[ "https://wordpress.stackexchange.com/questions/272179", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107594/" ]
I know this has been covered in different ways a thousand times (I read all the posts), but it seems not specifically for my case. I can't really get it to work myself, being a big development noobie. I have a template which shows the last posts on the front page. I changed the type of posts shown to `question` (my website is a Q&A one) but then pagination was only showing 13 pages while there are 29 pages of questions. 13 pages being the number of non-custom-type normal posts. So I added this code in `functions.php`: ``` add_action( 'pre_get_posts', function($q) { if( !is_admin() && $q->is_main_query() && !$q->is_tax() ) { $q->set ('post_type', array( 'question' ) ); } }); ``` Now it counts the number of Questions correctly but it throws a 404 error every time I click on the link to a question. I understand that `pre_get_posts` is not the best approach, but I really don't know how to change it and use `WP_Query` instead, as I saw was advised to. Any fix to that ? Thank you <3
From quick look at the source there seems to be three possibilities: 1. `get_post()` returned *falsy* value, so current post context is invalid in some way. 2. `$post->comment_count` is `0`. 3. `get_comments_number` filter is being used to adjust the output. Most commonly it would be case 1/2 with something interfering with global post context, dump `get_post()` at the point and see if it contains expected instance.
272,236
<p>I am trying to load several scripts and stylesheets into a plugin I am creating. I want to load scripts into multiple CPTs within admin. I have got this far:</p> <pre><code>function fhaac_admin_enqueue_scripts(){ global $pagenow, $typenow; if ( ($pagenow == 'post.php' || $pagenow == 'post-new.php') &amp;&amp; $typenow == 'fhaac' ){} } </code></pre> <p>The scripts are being loaded into the fhaac, but nothing else. I am not sure how to add multiple CPTs. I tried adding them in an array, but it didn't work. </p> <p>Help would be greatly appreciated.</p> <p>Cheers</p>
[ { "answer_id": 272241, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>There is a built-in function that you can use, instead of globals. The <a href=\"https://codex.wordpress.org...
2017/07/04
[ "https://wordpress.stackexchange.com/questions/272236", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58313/" ]
I am trying to load several scripts and stylesheets into a plugin I am creating. I want to load scripts into multiple CPTs within admin. I have got this far: ``` function fhaac_admin_enqueue_scripts(){ global $pagenow, $typenow; if ( ($pagenow == 'post.php' || $pagenow == 'post-new.php') && $typenow == 'fhaac' ){} } ``` The scripts are being loaded into the fhaac, but nothing else. I am not sure how to add multiple CPTs. I tried adding them in an array, but it didn't work. Help would be greatly appreciated. Cheers
There is a built-in function that you can use, instead of globals. The [`get_current_screen()`](https://codex.wordpress.org/Function_Reference/get_current_screen) function allows you to get the information associated with the current page. One of its return values is `post_type`. So you can check against an array of post types to see if anyone matches. ``` function fhaac_admin_enqueue_scripts(){ $screen = get_current_screen(); if ( in_array( $screen->post_type, array('fhaac','blabla')) && $screen->base == 'post' ) { // Do something } } ```
272,249
<p>I honestly did expect to get here...<br /> I tried every tool in the book...<br /> <code>Save changes</code> on the <code>permalinks</code> page...<br /> I installed <code>debug this</code> to see what going on with the <code>query</code>...<br /> I repeated other operations and changes to configurations but of no avail.<br /> I've spent hours reading on <code>.htaccess</code> params as well as <code>nginx</code> server block configurations...nothing worx.<br /> My <code>menu</code> keeps on giving <code>404</code> unless I set <code>permalinks</code> to <code>plain</code>.<br /> I am on <code>linode VPS</code>, <code>ubuntu 14.04</code> + <code>LEMP</code> stack<br /> Here are my <code>.htaccess</code> &amp; my site's configs...</p> <p><strong>.htaccess</strong></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 &lt;Files 403.shtml&gt; order allow,deny allow from all &lt;/Files&gt; # Leverage Browser Caching Ninja -- Starts here &lt;IfModule mod_expires.c&gt; ExpiresActive On ExpiresDefault "access plus 1 month" ExpiresByType image/x-icon "access plus 1 year" ExpiresByType image/gif "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType image/jpg "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType text/css "access 1 month" ExpiresByType application/javascript "access plus 1 year" &lt;/IfModule&gt; # Leverage Browser Caching Ninja -- Ends here # compress text, html, javascript, css, xml: AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript </code></pre> <p><strong>nginx server block</strong></p> <pre><code>server { server_name www.xxx.com xxx.com; root /home/alma/xxx.com; index index.php; include global/restrictions.conf; include global/wordpress_xxx.conf; error_log /var/log/nginx/xxx_error.log; access_log /var/log/nginx/xxx_access.log; } </code></pre> <p><strong>global/wordpress_xxx.conf</strong></p> <pre><code># http://wiki.nginx.org/HttpCoreModule location / { #try_files $uri $uri/ /index.php?$args; try_files $uri $uri/ /index.php?q=$uri&amp;$args; } # Add trailing slash to */wp-admin requests. rewrite /wp-admin$ $scheme://$host$uri/ permanent; # Directives to send expires headers and turn off 404 error logging. location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ { access_log off; log_not_found off; expires max; } # Pass all .php files onto a php-fpm/php-fcgi server. location ~ [^/]\.php(/|$) { fastcgi_split_path_info ^(.+?\.php)(/.*)$; if (!-f $document_root$fastcgi_script_name) { return 404; } fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; # fastcgi_intercept_errors on; fastcgi_param PHP_VALUE "upload_max_filesize = 16M \n post_max_size=18M"; client_max_body_size 68M; include fastcgi_params; } location ~ ^/(wp-admin|wp-login\.php) { auth_basic "Welcome - Admin Restricted Content"; auth_basic_user_file /etc/nginx/.htpasswd; } location = /wp-login.php { deny all; try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; include fastcgi_params; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PHP_VALUE "upload_max_filesize = 16M \n post_max_size=18M"; client_max_body_size 68M; } </code></pre> <p><strong>global/restrictions.conf</strong></p> <pre><code># Global restrictions configuration file. location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } location ~ /\. { deny all; } location ~* /(?:uploads|files)/.*\.php$ { deny all; } </code></pre> <p>These all worked prior to the last <code>update</code>...<br /> Has anyone encountered such an issue? Does anyone know how to resolve this? Is there something in my configuration that might be causing the issue after the <code>update</code> to 4.8?<br /> Thanx</p> <p>P.s. the error logs are not showing anything in particular...</p>
[ { "answer_id": 272258, "author": "Mandu", "author_id": 74623, "author_profile": "https://wordpress.stackexchange.com/users/74623", "pm_score": 0, "selected": false, "text": "<p>You might try <code>flush_rewrite_rules( $hard );</code>\nBe sure to remove the function aftewards though. </p>...
2017/07/04
[ "https://wordpress.stackexchange.com/questions/272249", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52581/" ]
I honestly did expect to get here... I tried every tool in the book... `Save changes` on the `permalinks` page... I installed `debug this` to see what going on with the `query`... I repeated other operations and changes to configurations but of no avail. I've spent hours reading on `.htaccess` params as well as `nginx` server block configurations...nothing worx. My `menu` keeps on giving `404` unless I set `permalinks` to `plain`. I am on `linode VPS`, `ubuntu 14.04` + `LEMP` stack Here are my `.htaccess` & my site's configs... **.htaccess** ``` # 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 <Files 403.shtml> order allow,deny allow from all </Files> # Leverage Browser Caching Ninja -- Starts here <IfModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 1 month" ExpiresByType image/x-icon "access plus 1 year" ExpiresByType image/gif "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType image/jpg "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType text/css "access 1 month" ExpiresByType application/javascript "access plus 1 year" </IfModule> # Leverage Browser Caching Ninja -- Ends here # compress text, html, javascript, css, xml: AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript ``` **nginx server block** ``` server { server_name www.xxx.com xxx.com; root /home/alma/xxx.com; index index.php; include global/restrictions.conf; include global/wordpress_xxx.conf; error_log /var/log/nginx/xxx_error.log; access_log /var/log/nginx/xxx_access.log; } ``` **global/wordpress\_xxx.conf** ``` # http://wiki.nginx.org/HttpCoreModule location / { #try_files $uri $uri/ /index.php?$args; try_files $uri $uri/ /index.php?q=$uri&$args; } # Add trailing slash to */wp-admin requests. rewrite /wp-admin$ $scheme://$host$uri/ permanent; # Directives to send expires headers and turn off 404 error logging. location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ { access_log off; log_not_found off; expires max; } # Pass all .php files onto a php-fpm/php-fcgi server. location ~ [^/]\.php(/|$) { fastcgi_split_path_info ^(.+?\.php)(/.*)$; if (!-f $document_root$fastcgi_script_name) { return 404; } fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; # fastcgi_intercept_errors on; fastcgi_param PHP_VALUE "upload_max_filesize = 16M \n post_max_size=18M"; client_max_body_size 68M; include fastcgi_params; } location ~ ^/(wp-admin|wp-login\.php) { auth_basic "Welcome - Admin Restricted Content"; auth_basic_user_file /etc/nginx/.htpasswd; } location = /wp-login.php { deny all; try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; include fastcgi_params; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PHP_VALUE "upload_max_filesize = 16M \n post_max_size=18M"; client_max_body_size 68M; } ``` **global/restrictions.conf** ``` # Global restrictions configuration file. location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } location ~ /\. { deny all; } location ~* /(?:uploads|files)/.*\.php$ { deny all; } ``` These all worked prior to the last `update`... Has anyone encountered such an issue? Does anyone know how to resolve this? Is there something in my configuration that might be causing the issue after the `update` to 4.8? Thanx P.s. the error logs are not showing anything in particular...
I've ran into that trouble before with some of my sites when I transferred them to another server. Here's what I did. edit your `apache2.conf` at `/etc/apache2/` folder. Run the following command: ``` nano /etc/apache2/apache2.conf ``` Scroll down and look for this section with a comment: ``` # your system is serving content from a sub-directory in /srv you must allow # access here, or in any related virtual host. ``` Make sure that this is the one in there: ``` <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride all Require all granted </Directory> ``` For short, grant it. For your permalinks not to fail. -Dave
272,261
<p>Quite difficult to explain this one but I will do my best.</p> <p>Let's assume we have the theme <strong>T</strong> and plugin <strong>P</strong>.</p> <p><strong>T</strong> has a bunch of custom taxonomies and so does <strong>P</strong>, the plugin.</p> <p>What I am trying to achieve is display content from the custom taxonomies in <strong>P</strong> in the <strong>T</strong> template/single files, without modifying any of the files in <strong>T</strong>. Basically, I want to "hijack" the single views from the theme by writing the code in <strong>P</strong>. Is that achievable? And if so, how?</p> <p>I just couldn't find a better word than "hijack". It's just adding different sections in the single view, based on the content that is saved in the custom taxonomies in the plugin.</p> <p>Thank you in advance!</p>
[ { "answer_id": 272258, "author": "Mandu", "author_id": 74623, "author_profile": "https://wordpress.stackexchange.com/users/74623", "pm_score": 0, "selected": false, "text": "<p>You might try <code>flush_rewrite_rules( $hard );</code>\nBe sure to remove the function aftewards though. </p>...
2017/07/04
[ "https://wordpress.stackexchange.com/questions/272261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123147/" ]
Quite difficult to explain this one but I will do my best. Let's assume we have the theme **T** and plugin **P**. **T** has a bunch of custom taxonomies and so does **P**, the plugin. What I am trying to achieve is display content from the custom taxonomies in **P** in the **T** template/single files, without modifying any of the files in **T**. Basically, I want to "hijack" the single views from the theme by writing the code in **P**. Is that achievable? And if so, how? I just couldn't find a better word than "hijack". It's just adding different sections in the single view, based on the content that is saved in the custom taxonomies in the plugin. Thank you in advance!
I've ran into that trouble before with some of my sites when I transferred them to another server. Here's what I did. edit your `apache2.conf` at `/etc/apache2/` folder. Run the following command: ``` nano /etc/apache2/apache2.conf ``` Scroll down and look for this section with a comment: ``` # your system is serving content from a sub-directory in /srv you must allow # access here, or in any related virtual host. ``` Make sure that this is the one in there: ``` <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride all Require all granted </Directory> ``` For short, grant it. For your permalinks not to fail. -Dave
272,276
<p>I have created a custom map view page on my classified ads website and I seem to be having issues with the page loading, here is the code for the page.</p> <pre><code> &lt;?php $featured_query = ''; if(!empty($stm_listing_filter['featured'])) { $featured_query = $stm_listing_filter['featured']; } $listing = $stm_listing_filter['listing_query']; $filter_badges = $stm_listing_filter['badges']; $filter_links = stm_get_car_filter_links(); $listing_filter_position = get_theme_mod('listing_filter_position', 'left'); if(!empty($_GET['filter_position']) and $_GET['filter_position'] == 'right') { $listing_filter_position = 'right'; } $regular_price_label = get_post_meta(get_the_ID(), 'regular_price_label', true); $special_price_label = get_post_meta(get_the_ID(),'special_price_label',true); $price = get_post_meta(get_the_id(),'price',true); $sale_price = get_post_meta(get_the_id(),'sale_price',true); $car_price_form_label = get_post_meta(get_the_ID(), 'car_price_form_label', true); $data_price = '0'; if(!empty($price)) { $data_price = $price; } if(!empty($sale_price)) { $data_price = $sale_price; } if(empty($price) and !empty($sale_price)) { $price = $sale_price; } $mileage = get_post_meta(get_the_id(),'mileage',true); $data_mileage = '0'; if(!empty($mileage)) { $data_mileage = $mileage; } $taxonomies = stm_get_taxonomies(); $categories = wp_get_post_terms(get_the_ID(), $taxonomies); $classes = array(); if(!empty($categories)) { foreach($categories as $category) { $classes[] = $category-&gt;slug.'-'.$category-&gt;term_id; } } //Fav $cars_in_favourite = array(); if(!empty($_COOKIE['stm_car_favourites'])) { $cars_in_favourite = $_COOKIE['stm_car_favourites']; $cars_in_favourite = explode(',', $cars_in_favourite); } if(is_user_logged_in()) { $user = wp_get_current_user(); $user_id = $user-&gt;ID; $user_added_fav = get_the_author_meta('stm_user_favourites', $user_id ); if(!empty($user_added_fav)) { $user_added_fav = explode(',', $user_added_fav); $cars_in_favourite = $user_added_fav; } } $car_already_added_to_favourite = ''; $car_favourite_status = esc_html__('Add to favorites', 'motors'); if(!empty($cars_in_favourite) and in_array(get_the_ID(), $cars_in_favourite)){ $car_already_added_to_favourite = 'active'; $car_favourite_status = esc_html__('Remove from favorites', 'motors'); } $show_favorite = get_theme_mod('enable_favorite_items', true); //Compare $show_compare = get_theme_mod('show_listing_compare', true); $cars_in_compare = array(); if(!empty($_COOKIE['compare_ids'])) { $cars_in_compare = $_COOKIE['compare_ids']; } $car_already_added_to_compare = ''; $car_compare_status = esc_html__('Add to compare', 'motors'); if(!empty($cars_in_compare) and in_array(get_the_ID(), $cars_in_compare)){ $car_already_added_to_compare = 'active'; $car_compare_status = esc_html__('Remove from compare', 'motors'); } /*Media*/ $car_media = stm_get_car_medias(get_the_id()); ?&gt; &lt;div class="stm-isotope-sorting" style="display: none;"&gt; &lt;?php while($listing-&gt;have_posts()): get_template_part( 'partials/listing-cars/listing-list', 'loop' ); endwhile; ?&gt; &lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function() { var markersInfo = $('.ia-card').map(function() { var info = { id: $(this).data('map-id'), address: $(this).data('map-address'), title: $(this).data('map-title'), price: $(this).data('map-price'), latitude: $(this).data('map-latitude'), longitude: $(this).data('map-longitude'), html: "&lt;img src=" + $(this).data('map-image') + "&gt;", link: $(this).data("map-link"), contentHtml: "&lt;div class='image'&gt;" + "&lt;img src=" + $(this).data('map-image') + "&gt;" + "&lt;/div&gt;" + '&lt;b&gt;' + $(this).data('map-title') + '&lt;/b&gt;&lt;br&gt;' + "&lt;div class='changeprice'&gt;&lt;div style='display: none;' class='currency-selector'&gt;&lt;/div&gt;" + $(this).data('map-price') + "&lt;/div&gt;" + "&lt;br&gt;&lt;a href='" + $(this).data("map-link") + "'&gt;More&gt;&gt;&lt;/a&gt;" }; return info; }).get(); var distinctMarkerInfo = []; markersInfo.forEach(function(item) { if (!distinctMarkerInfo.some(function(distinct) { return distinct.id == item.id; })) distinctMarkerInfo.push(item); }); initGoogleMap(distinctMarkerInfo); // GMAP ON SEARCH RESULTS PAGE function initGoogleMap(markersInfo) { var mapOptions = { // zoom: 2, // center: new google.maps.LatLng(53.334430, -7.736673) // center of Ireland }, bounds = new google.maps.LatLngBounds(), mapElement = document.getElementById('stm_map_results'), map = new google.maps.Map(mapElement, mapOptions); markerList = []; // create an array to hold the markers var geocoder = new google.maps.Geocoder(); var iconBase = 'http://throttlebuddies.com/wp-content/themes/motors/assets/images/'; $.each(markersInfo, function(key, val) { var marker = new google.maps.Marker({ //map: map, position: {lat: parseFloat(val.latitude), lng: parseFloat(val.longitude)}, title: val.title, icon: iconBase + 'single.png', info: new google.maps.InfoWindow({ content: val.contentHtml }) }); markerList.push(marker); // add the marker to the list google.maps.event.addListener(marker, 'click', function() { marker.info.open(map, marker); }); loc = new google.maps.LatLng(val.latitude, val.longitude); bounds.extend(loc); }); map.fitBounds(bounds); map.panToBounds(bounds); var markerCluster = new MarkerClusterer(map, markerList, { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' }); }; }); &lt;/script&gt; &lt;div id="stm_map_results" style="width:100%; height:600px;"&gt;&lt;/div&gt; &lt;style&gt; .stm-isotope-sorting { position: relative; height: 600px !important; } &lt;/style&gt; </code></pre> <p>The page loads fine however when I get rid of the following code. But I need this code to populate the map.</p> <pre><code> &lt;div class="stm-isotope-sorting" style="display: none;"&gt; &lt;?php while($listing-&gt;have_posts()): get_template_part( 'partials/listing-cars/listing-list', 'loop' ); endwhile; ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 272277, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 1, "selected": false, "text": "<p>This loop:</p>\n\n<pre><code>while($listing-&gt;have_posts()):\n get_template_part( 'partials/listing-cars/list...
2017/07/04
[ "https://wordpress.stackexchange.com/questions/272276", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123084/" ]
I have created a custom map view page on my classified ads website and I seem to be having issues with the page loading, here is the code for the page. ``` <?php $featured_query = ''; if(!empty($stm_listing_filter['featured'])) { $featured_query = $stm_listing_filter['featured']; } $listing = $stm_listing_filter['listing_query']; $filter_badges = $stm_listing_filter['badges']; $filter_links = stm_get_car_filter_links(); $listing_filter_position = get_theme_mod('listing_filter_position', 'left'); if(!empty($_GET['filter_position']) and $_GET['filter_position'] == 'right') { $listing_filter_position = 'right'; } $regular_price_label = get_post_meta(get_the_ID(), 'regular_price_label', true); $special_price_label = get_post_meta(get_the_ID(),'special_price_label',true); $price = get_post_meta(get_the_id(),'price',true); $sale_price = get_post_meta(get_the_id(),'sale_price',true); $car_price_form_label = get_post_meta(get_the_ID(), 'car_price_form_label', true); $data_price = '0'; if(!empty($price)) { $data_price = $price; } if(!empty($sale_price)) { $data_price = $sale_price; } if(empty($price) and !empty($sale_price)) { $price = $sale_price; } $mileage = get_post_meta(get_the_id(),'mileage',true); $data_mileage = '0'; if(!empty($mileage)) { $data_mileage = $mileage; } $taxonomies = stm_get_taxonomies(); $categories = wp_get_post_terms(get_the_ID(), $taxonomies); $classes = array(); if(!empty($categories)) { foreach($categories as $category) { $classes[] = $category->slug.'-'.$category->term_id; } } //Fav $cars_in_favourite = array(); if(!empty($_COOKIE['stm_car_favourites'])) { $cars_in_favourite = $_COOKIE['stm_car_favourites']; $cars_in_favourite = explode(',', $cars_in_favourite); } if(is_user_logged_in()) { $user = wp_get_current_user(); $user_id = $user->ID; $user_added_fav = get_the_author_meta('stm_user_favourites', $user_id ); if(!empty($user_added_fav)) { $user_added_fav = explode(',', $user_added_fav); $cars_in_favourite = $user_added_fav; } } $car_already_added_to_favourite = ''; $car_favourite_status = esc_html__('Add to favorites', 'motors'); if(!empty($cars_in_favourite) and in_array(get_the_ID(), $cars_in_favourite)){ $car_already_added_to_favourite = 'active'; $car_favourite_status = esc_html__('Remove from favorites', 'motors'); } $show_favorite = get_theme_mod('enable_favorite_items', true); //Compare $show_compare = get_theme_mod('show_listing_compare', true); $cars_in_compare = array(); if(!empty($_COOKIE['compare_ids'])) { $cars_in_compare = $_COOKIE['compare_ids']; } $car_already_added_to_compare = ''; $car_compare_status = esc_html__('Add to compare', 'motors'); if(!empty($cars_in_compare) and in_array(get_the_ID(), $cars_in_compare)){ $car_already_added_to_compare = 'active'; $car_compare_status = esc_html__('Remove from compare', 'motors'); } /*Media*/ $car_media = stm_get_car_medias(get_the_id()); ?> <div class="stm-isotope-sorting" style="display: none;"> <?php while($listing->have_posts()): get_template_part( 'partials/listing-cars/listing-list', 'loop' ); endwhile; ?> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script> <script> $(document).ready(function() { var markersInfo = $('.ia-card').map(function() { var info = { id: $(this).data('map-id'), address: $(this).data('map-address'), title: $(this).data('map-title'), price: $(this).data('map-price'), latitude: $(this).data('map-latitude'), longitude: $(this).data('map-longitude'), html: "<img src=" + $(this).data('map-image') + ">", link: $(this).data("map-link"), contentHtml: "<div class='image'>" + "<img src=" + $(this).data('map-image') + ">" + "</div>" + '<b>' + $(this).data('map-title') + '</b><br>' + "<div class='changeprice'><div style='display: none;' class='currency-selector'></div>" + $(this).data('map-price') + "</div>" + "<br><a href='" + $(this).data("map-link") + "'>More>></a>" }; return info; }).get(); var distinctMarkerInfo = []; markersInfo.forEach(function(item) { if (!distinctMarkerInfo.some(function(distinct) { return distinct.id == item.id; })) distinctMarkerInfo.push(item); }); initGoogleMap(distinctMarkerInfo); // GMAP ON SEARCH RESULTS PAGE function initGoogleMap(markersInfo) { var mapOptions = { // zoom: 2, // center: new google.maps.LatLng(53.334430, -7.736673) // center of Ireland }, bounds = new google.maps.LatLngBounds(), mapElement = document.getElementById('stm_map_results'), map = new google.maps.Map(mapElement, mapOptions); markerList = []; // create an array to hold the markers var geocoder = new google.maps.Geocoder(); var iconBase = 'http://throttlebuddies.com/wp-content/themes/motors/assets/images/'; $.each(markersInfo, function(key, val) { var marker = new google.maps.Marker({ //map: map, position: {lat: parseFloat(val.latitude), lng: parseFloat(val.longitude)}, title: val.title, icon: iconBase + 'single.png', info: new google.maps.InfoWindow({ content: val.contentHtml }) }); markerList.push(marker); // add the marker to the list google.maps.event.addListener(marker, 'click', function() { marker.info.open(map, marker); }); loc = new google.maps.LatLng(val.latitude, val.longitude); bounds.extend(loc); }); map.fitBounds(bounds); map.panToBounds(bounds); var markerCluster = new MarkerClusterer(map, markerList, { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' }); }; }); </script> <div id="stm_map_results" style="width:100%; height:600px;"></div> <style> .stm-isotope-sorting { position: relative; height: 600px !important; } </style> ``` The page loads fine however when I get rid of the following code. But I need this code to populate the map. ``` <div class="stm-isotope-sorting" style="display: none;"> <?php while($listing->have_posts()): get_template_part( 'partials/listing-cars/listing-list', 'loop' ); endwhile; ?> </div> ```
This loop: ``` while($listing->have_posts()): get_template_part( 'partials/listing-cars/listing-list', 'loop' ); endwhile; ``` will never terminate, because `$listing->have_posts()` will never be false. You need `$listing->the_post()` to advance the loop to the next post in each iteration. Then, when the last post is reached, `$listing->have_posts()` will be false and the loop will end. ``` while($listing->have_posts()): $listing->the_post(); get_template_part( 'partials/listing-cars/listing-list', 'loop' ); endwhile; ```
272,291
<p>I developed a site in WordPress where you can click on the featured image and title of the featured image and it should take you to the corresponding page same as if you would click on the nav item:</p> <p><a href="https://i.stack.imgur.com/VwD9y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VwD9y.jpg" alt="enter image description here"></a></p> <p>This was done using Custom Post Type UI that I called Quick Links:</p> <p><a href="https://i.stack.imgur.com/O9fZw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O9fZw.png" alt="enter image description here"></a></p> <p>I think I may have made this more complex than it needs to be though because when you click on one of the images or title the permalink takes you to yousite.com/quick-links/news instead of just yoursite.com/news</p> <p>I am not sure if I should just gut the Custom Post Type UI, the source code for this page is this one at home-page.php:</p> <pre><code>&lt;?php /* Template Name: Home Page */ // Advanced Custom Fields $quick_links_title = get_field('quick_links_title'); get_header(); ?&gt; &lt;?php get_template_part('content','hero'); ?&gt; &lt;?php get_template_part('content','donate'); ?&gt; &lt;div class="container-fluid"&gt; &lt;div class="row"&gt; &lt;div class="col-md-8"&gt; &lt;div class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h3 class="panel-title"&gt;Welcome to Three Green Birds!&lt;/h3&gt; &lt;/div&gt;&lt;!-- panel-heading --&gt; &lt;div class="panel-body"&gt; &lt;?php if (have_posts()) : ?&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;!--&lt;div class="spacer"&gt;&lt;/div&gt;--&gt; &lt;div class="post-title"&gt; &lt;?php if (function_exists('get_cat_icon')) get_cat_icon('class=myicons'); ?&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="spacer"&gt;&lt;/div&gt; &lt;div class="post-content"&gt; &lt;?php the_content('Read the rest of this entry &amp;raquo;'); ?&gt; &lt;/div&gt; &lt;div class="spacer"&gt;&lt;/div&gt; &lt;div class="post-footer"&gt;&lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;div class="navigation"&gt; &lt;br/&gt;&lt;br/&gt; &lt;div class="alignleft"&gt;&lt;?php next_posts_link('&amp;laquo; Older Entries') ?&gt;&lt;/div&gt; &lt;div class="alignright"&gt;&lt;?php previous_posts_link('Newer Entries &amp;raquo;') ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php else : ?&gt; &lt;div class="post-title"&gt;Not Found&lt;/div&gt; &lt;p class="post-content"&gt;Sorry, but you are looking for something that isn't here.&lt;/p&gt; &lt;?php include (TEMPLATEPATH . "/searchform.php"); ?&gt; &lt;?php endif; ?&gt; &lt;!-- Quick Links ======================================================== --&gt; &lt;section id="quick-links"&gt; &lt;div class="container"&gt; &lt;h2&gt;&lt;?php echo $quick_links_title; ?&gt;&lt;/h2&gt; &lt;div class="row"&gt; &lt;?php $loop = new WP_Query(array('post_type' =&gt; 'quick_links', 'orderby' =&gt; 'post_id', 'order' =&gt; 'ASC')); ?&gt; &lt;?php while($loop-&gt;have_posts()) : $loop-&gt;the_post(); ?&gt; &lt;div class="col-sm-3"&gt; &lt;a href="&lt;?php echo the_permalink(); ?&gt;"&gt;&lt;?php if(has_post_thumbnail()) { the_post_thumbnail(); } ?&gt;&lt;/a&gt; &lt;a href="&lt;?php echo the_permalink(); ?&gt;"&gt;&lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt;&lt;/a&gt; &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt; &lt;/div&gt;&lt;!-- end col --&gt; &lt;?php endwhile; ?&gt;&lt;!-- end of the loop --&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;/div&gt;&lt;!-- row --&gt; &lt;/div&gt;&lt;!-- container --&gt; &lt;/section&gt;&lt;!-- quick-links --&gt; &lt;/div&gt;&lt;!-- panel-body --&gt; &lt;/div&gt;&lt;!-- panel panel-default --&gt; &lt;/div&gt;&lt;!-- col-md-8 --&gt; &lt;!-- SIDEBAR ====================================================================== --&gt; &lt;div class="col-md-4"&gt; &lt;?php if (is_active_sidebar('sidebar')) : ?&gt; &lt;?php dynamic_sidebar('sidebar'); ?&gt; &lt;?php endif; ?&gt; &lt;/div&gt;&lt;!-- col-md-4 --&gt; &lt;/div&gt;&lt;!-- row --&gt; &lt;/div&gt;&lt;!-- container-fluid --&gt; &lt;?php get_sidebar(); ?&gt; &lt;?php get_footer(); ?&gt; </code></pre> <p>If I were to gut the Custom Post Type UI, could I still use the code above to get the browser to render what you see above, the quick-links title notwithstanding since that is a variable so I am not sure that would appear if I am no longer using the Quick Links Custom Post Type.</p> <p>So to be clear I just want the user to click on the News image or text and have the user be taken to mysite.com/news and not mysite.com/quick-links/news.</p> <p>I believe the problem is here:</p> <pre><code>&lt;?php $loop = new WP_Query(array('post_type' =&gt; 'quick_links', 'orderby' =&gt; 'post_id', 'order' =&gt; 'ASC')); ?&gt; </code></pre> <p>I get mysite.com/quick-links/news when I hover over the featured images and title of the featured image, but I just want it to go to mysite.com/news as if I were clicking on the news item in the nav menu. So what I did was edit the $loop I am using so that the site no longer displays mysite.com/quick-links/news but just mysite.com/news. I changed the $loop from:</p> <pre><code>&lt;?php $loop = new WP_Query(array('post_type' =&gt; 'quick_links', 'orderby' =&gt; 'post_id', 'order' =&gt; 'ASC')); ?&gt; </code></pre> <p>to</p> <pre><code>&lt;?php $loop = new WP_Query(array('post_type' =&gt; 'page', 'orderby' =&gt; 'post_id', 'order' =&gt; 'ASC')); ?&gt; </code></pre> <p>but now the Quick Links section of the home page wants to display all the pages and not just news, about us and get involved. Any ideas on how to query only those three specific pages?</p>
[ { "answer_id": 272303, "author": "Regolith", "author_id": 103884, "author_profile": "https://wordpress.stackexchange.com/users/103884", "pm_score": 0, "selected": false, "text": "<p>first off you are using <code>echo the_permalink()</code></p>\n\n<pre><code>&lt;a href=\"&lt;?php echo the...
2017/07/04
[ "https://wordpress.stackexchange.com/questions/272291", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109760/" ]
I developed a site in WordPress where you can click on the featured image and title of the featured image and it should take you to the corresponding page same as if you would click on the nav item: [![enter image description here](https://i.stack.imgur.com/VwD9y.jpg)](https://i.stack.imgur.com/VwD9y.jpg) This was done using Custom Post Type UI that I called Quick Links: [![enter image description here](https://i.stack.imgur.com/O9fZw.png)](https://i.stack.imgur.com/O9fZw.png) I think I may have made this more complex than it needs to be though because when you click on one of the images or title the permalink takes you to yousite.com/quick-links/news instead of just yoursite.com/news I am not sure if I should just gut the Custom Post Type UI, the source code for this page is this one at home-page.php: ``` <?php /* Template Name: Home Page */ // Advanced Custom Fields $quick_links_title = get_field('quick_links_title'); get_header(); ?> <?php get_template_part('content','hero'); ?> <?php get_template_part('content','donate'); ?> <div class="container-fluid"> <div class="row"> <div class="col-md-8"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Welcome to Three Green Birds!</h3> </div><!-- panel-heading --> <div class="panel-body"> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <!--<div class="spacer"></div>--> <div class="post-title"> <?php if (function_exists('get_cat_icon')) get_cat_icon('class=myicons'); ?><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></div> <div class="spacer"></div> <div class="post-content"> <?php the_content('Read the rest of this entry &raquo;'); ?> </div> <div class="spacer"></div> <div class="post-footer"></div> <?php endwhile; ?> <div class="navigation"> <br/><br/> <div class="alignleft"><?php next_posts_link('&laquo; Older Entries') ?></div> <div class="alignright"><?php previous_posts_link('Newer Entries &raquo;') ?></div> </div> <?php else : ?> <div class="post-title">Not Found</div> <p class="post-content">Sorry, but you are looking for something that isn't here.</p> <?php include (TEMPLATEPATH . "/searchform.php"); ?> <?php endif; ?> <!-- Quick Links ======================================================== --> <section id="quick-links"> <div class="container"> <h2><?php echo $quick_links_title; ?></h2> <div class="row"> <?php $loop = new WP_Query(array('post_type' => 'quick_links', 'orderby' => 'post_id', 'order' => 'ASC')); ?> <?php while($loop->have_posts()) : $loop->the_post(); ?> <div class="col-sm-3"> <a href="<?php echo the_permalink(); ?>"><?php if(has_post_thumbnail()) { the_post_thumbnail(); } ?></a> <a href="<?php echo the_permalink(); ?>"><h3><?php the_title(); ?></h3></a> <p><?php the_content(); ?></p> </div><!-- end col --> <?php endwhile; ?><!-- end of the loop --> <?php wp_reset_postdata(); ?> </div><!-- row --> </div><!-- container --> </section><!-- quick-links --> </div><!-- panel-body --> </div><!-- panel panel-default --> </div><!-- col-md-8 --> <!-- SIDEBAR ====================================================================== --> <div class="col-md-4"> <?php if (is_active_sidebar('sidebar')) : ?> <?php dynamic_sidebar('sidebar'); ?> <?php endif; ?> </div><!-- col-md-4 --> </div><!-- row --> </div><!-- container-fluid --> <?php get_sidebar(); ?> <?php get_footer(); ?> ``` If I were to gut the Custom Post Type UI, could I still use the code above to get the browser to render what you see above, the quick-links title notwithstanding since that is a variable so I am not sure that would appear if I am no longer using the Quick Links Custom Post Type. So to be clear I just want the user to click on the News image or text and have the user be taken to mysite.com/news and not mysite.com/quick-links/news. I believe the problem is here: ``` <?php $loop = new WP_Query(array('post_type' => 'quick_links', 'orderby' => 'post_id', 'order' => 'ASC')); ?> ``` I get mysite.com/quick-links/news when I hover over the featured images and title of the featured image, but I just want it to go to mysite.com/news as if I were clicking on the news item in the nav menu. So what I did was edit the $loop I am using so that the site no longer displays mysite.com/quick-links/news but just mysite.com/news. I changed the $loop from: ``` <?php $loop = new WP_Query(array('post_type' => 'quick_links', 'orderby' => 'post_id', 'order' => 'ASC')); ?> ``` to ``` <?php $loop = new WP_Query(array('post_type' => 'page', 'orderby' => 'post_id', 'order' => 'ASC')); ?> ``` but now the Quick Links section of the home page wants to display all the pages and not just news, about us and get involved. Any ideas on how to query only those three specific pages?
I learned that in the WP Query I had to specify page instead of quick\_links which was the custom post type. In fact I completely removed the Custom Post Type UI and the plugin. It was all completely unnecessary. I did not want every single page, just the news, about us and get involved so I researched if there was a way to grab specific pages, namely, those with a featured image and in the correct order and from what I found online I was able to piece together this code: ``` <?php $loop = new WP_Query(array('post_type' => 'page', 'meta_key' => '_thumbnail_id', 'order' => 'asc')); ?> ``` and it works: [![enter image description here](https://i.stack.imgur.com/GRnnI.jpg)](https://i.stack.imgur.com/GRnnI.jpg)
272,324
<p>I accidentally deleted about 20 blog posts and they were in my trash folder for over a month and now have permanently deleted. I was wondering if there's a way to recover these? For example I have seen mention of MySql database and phpMyAdmin, and was wondering if these would be applicable in my case and, if so, how do I use them? Thanks in advance!</p>
[ { "answer_id": 272303, "author": "Regolith", "author_id": 103884, "author_profile": "https://wordpress.stackexchange.com/users/103884", "pm_score": 0, "selected": false, "text": "<p>first off you are using <code>echo the_permalink()</code></p>\n\n<pre><code>&lt;a href=\"&lt;?php echo the...
2017/07/05
[ "https://wordpress.stackexchange.com/questions/272324", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123197/" ]
I accidentally deleted about 20 blog posts and they were in my trash folder for over a month and now have permanently deleted. I was wondering if there's a way to recover these? For example I have seen mention of MySql database and phpMyAdmin, and was wondering if these would be applicable in my case and, if so, how do I use them? Thanks in advance!
I learned that in the WP Query I had to specify page instead of quick\_links which was the custom post type. In fact I completely removed the Custom Post Type UI and the plugin. It was all completely unnecessary. I did not want every single page, just the news, about us and get involved so I researched if there was a way to grab specific pages, namely, those with a featured image and in the correct order and from what I found online I was able to piece together this code: ``` <?php $loop = new WP_Query(array('post_type' => 'page', 'meta_key' => '_thumbnail_id', 'order' => 'asc')); ?> ``` and it works: [![enter image description here](https://i.stack.imgur.com/GRnnI.jpg)](https://i.stack.imgur.com/GRnnI.jpg)
272,331
<p>Hi I just switched woocomerce version from 3.0.9 to 3.1.0. And I received this mesage "WooCommerce data update – We need to update your store database to the latest version"</p> <p>So can I udpate safely woocommerce data?</p> <p>Thanks</p>
[ { "answer_id": 272303, "author": "Regolith", "author_id": 103884, "author_profile": "https://wordpress.stackexchange.com/users/103884", "pm_score": 0, "selected": false, "text": "<p>first off you are using <code>echo the_permalink()</code></p>\n\n<pre><code>&lt;a href=\"&lt;?php echo the...
2017/07/05
[ "https://wordpress.stackexchange.com/questions/272331", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119118/" ]
Hi I just switched woocomerce version from 3.0.9 to 3.1.0. And I received this mesage "WooCommerce data update – We need to update your store database to the latest version" So can I udpate safely woocommerce data? Thanks
I learned that in the WP Query I had to specify page instead of quick\_links which was the custom post type. In fact I completely removed the Custom Post Type UI and the plugin. It was all completely unnecessary. I did not want every single page, just the news, about us and get involved so I researched if there was a way to grab specific pages, namely, those with a featured image and in the correct order and from what I found online I was able to piece together this code: ``` <?php $loop = new WP_Query(array('post_type' => 'page', 'meta_key' => '_thumbnail_id', 'order' => 'asc')); ?> ``` and it works: [![enter image description here](https://i.stack.imgur.com/GRnnI.jpg)](https://i.stack.imgur.com/GRnnI.jpg)
272,337
<p>I am attempting to filter results based on what the user has inputted.</p> <pre><code>function custom_archive() { if ( is_post_type_archive( 'profiles' ) ) { // if we are on a profiles archive page, edit the query according to the posted data. $data = $_POST['networks']; if ( isset( $data ) ) { //count the array if ( count( $data ) &gt; 1 ) { $data = implode( ',', $data ); } else { //$data = $data[0]; } //set the query to only search for whatever the user wants, eg news $wp_query-&gt;set( 'tax_query', array( array( 'taxonomy' =&gt; 'networks', 'field' =&gt; 'id', 'terms' =&gt; $data, 'operator' =&gt; 'IN', ), ) ); } } } add_action( 'pre_get_posts', 'custom_archive' ); </code></pre> <p>I have debugged my code and the data get's inputted correctly. Although, I get no posts back.</p> <p>Are there any problems with this code? I believe the error may be elsewhere in my theme, but I do wish to check out this code so I can take it out of the equation. Cheers!</p> <p><strong>EDIT:</strong> One thing I should mention is that I have a version of this code working for my Blog page. I am trying to now get this code working for an archive, and for it to return the correct posts still within the archive page, but instead it redirects me to a Search page. </p>
[ { "answer_id": 272338, "author": "Picard", "author_id": 118566, "author_profile": "https://wordpress.stackexchange.com/users/118566", "pm_score": 0, "selected": false, "text": "<p>You should provide an array of id's to the tax_query - like here in the example from the <a href=\"https://c...
2017/07/05
[ "https://wordpress.stackexchange.com/questions/272337", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/118553/" ]
I am attempting to filter results based on what the user has inputted. ``` function custom_archive() { if ( is_post_type_archive( 'profiles' ) ) { // if we are on a profiles archive page, edit the query according to the posted data. $data = $_POST['networks']; if ( isset( $data ) ) { //count the array if ( count( $data ) > 1 ) { $data = implode( ',', $data ); } else { //$data = $data[0]; } //set the query to only search for whatever the user wants, eg news $wp_query->set( 'tax_query', array( array( 'taxonomy' => 'networks', 'field' => 'id', 'terms' => $data, 'operator' => 'IN', ), ) ); } } } add_action( 'pre_get_posts', 'custom_archive' ); ``` I have debugged my code and the data get's inputted correctly. Although, I get no posts back. Are there any problems with this code? I believe the error may be elsewhere in my theme, but I do wish to check out this code so I can take it out of the equation. Cheers! **EDIT:** One thing I should mention is that I have a version of this code working for my Blog page. I am trying to now get this code working for an archive, and for it to return the correct posts still within the archive page, but instead it redirects me to a Search page.
So there's a few things wrong with the code: 1. You're not using the query object that's passed to the pre\_get\_posts hook, so you're not modifying the actual query. 2. Field is set to `id` instead of `term_id`. 3. If you're using `IN` as the operator, pass an array to terms. 4. You're not sanitizing the value of $\_POST['networks']. You *might* be ok without it, since WordPress shouldn't let anything too nasty happen, but it's a good idea to at least ensure that the values are the correct type. This version of the function addresses these issues: ``` function my_query_by_selected_networks( $query ) { if ( is_admin() ) { return; } if ( $query->is_main_query() && $query->is_post_type_archive( 'profiles' ) ) { if ( isset( $_POST['networks'] ) ) { if ( is_array( $_POST['networks'] ) ) { $networks = array_map( 'intval', $_POST['networks']) } else { $networks = array( intval( $_POST['networks'] ) ); } $tax_query = $query->get( 'tax_query' ) ?: array(); $tax_query[] = array( 'taxonomy' => 'networks', 'field' => 'term_id', 'terms' => $networks, 'operator' => 'IN', ); $query->set( 'tax_query', $tax_query ); } } } add_action( 'pre_get_posts', 'my_query_by_selected_networks' ); ``` Note: 1. The function accepts the `$query` variable and uses that the update the query. 2. It uses `term_id` as the value for `field`. 3. `$networks`, the value passed to the tax query is left as an array, or made an array if `$_POST['networks']` isn't already an array. 4. It sanitizes the value of `$_POST['networks']` with `intval`, making sure that `$networks` is an array of integers, which is what the tax query expects. Additionally, I modified the tax\_query code so that it doesn't entirely replace any tax queries that could be made by other plugins. It does this by checking if there's already a tax query and adding on to it if there is. This is probably unnecessary, but it's a habit of mine. **EDIT:** As per Tom's suggestion I've added in `$query->is_main_query()`, to make sure that we're only modifying the main loop, so this doesn't go and affect things like widgets and menus etc. I also added a bit at the top to bail if we're in the admin, since we don't want to modify back-end queries. Also, `custom_archive` is a very generic name for a function, and could easily be shared by other plugins or WordPress itself. It's a good idea to be more descriptive, but most importantly, you should prefix functions with something unique to your theme or plugin to avoid conflicts. In my example it's just `my_`. I suggest replacing it, since `my_` is a common example prefix.
272,351
<p>I have a simple control that displays a checkbox in the Customizer:</p> <pre><code>$wp_customize-&gt;add_setting( 'display_about_text', array( 'default' =&gt; true ) ); $wp_customize-&gt;add_control( 'display_about_text', array( 'label' =&gt; __( 'Display Text', 'my_theme_name' ), 'type' =&gt; 'checkbox', 'section' =&gt; 'about' ) ); </code></pre> <p>I would like to bold <code>Display Text</code> in the Customizer, so I changed the label line to:</p> <pre><code> 'label' =&gt; __( '&lt;strong&gt;Display Text&lt;/strong&gt;', 'minitheme' ), </code></pre> <p>However, it just outputs the HTML tags in the Customizer like this:</p> <p><code>&lt;strong&gt;Display Text&lt;/strong&gt;</code></p> <p>How do I get it to display bold instead of outputting the HTML? I've run into this problem several times when I try to output HTML in the Customizer. Same problem with <code>esc_html()</code>.</p>
[ { "answer_id": 272409, "author": "Dave Romsey", "author_id": 2807, "author_profile": "https://wordpress.stackexchange.com/users/2807", "pm_score": 1, "selected": false, "text": "<p>The Customizer runs the label text through <code>esc_html()</code>, so HTML is not permitted in labels by d...
2017/07/05
[ "https://wordpress.stackexchange.com/questions/272351", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40536/" ]
I have a simple control that displays a checkbox in the Customizer: ``` $wp_customize->add_setting( 'display_about_text', array( 'default' => true ) ); $wp_customize->add_control( 'display_about_text', array( 'label' => __( 'Display Text', 'my_theme_name' ), 'type' => 'checkbox', 'section' => 'about' ) ); ``` I would like to bold `Display Text` in the Customizer, so I changed the label line to: ``` 'label' => __( '<strong>Display Text</strong>', 'minitheme' ), ``` However, it just outputs the HTML tags in the Customizer like this: `<strong>Display Text</strong>` How do I get it to display bold instead of outputting the HTML? I've run into this problem several times when I try to output HTML in the Customizer. Same problem with `esc_html()`.
You should use CSS for this. For example: ``` #customize-control-display_about_text label { font-weight: bold; } ``` Enqueue the stylesheet for this at the `customize_controls_enqueue_scripts` action. If you must use JS to modify a control, then note that I would not advise using `jQuery.ready` in the other answer. You should instead make use of the Customizer JS API to access the control once it is ready, for example enqueue a script at the `customize_controls_enqueue_scripts` action which contains: ``` wp.customize.control( 'display_about_text', function( control ) { control.deferred.embedded.done( function() { control.container.find( 'label' ).wrapInner( '<strong></strong>' ); }); }); ``` This pattern can be seen in core actually in how the `textarea` for the Custom CSS feature is extended: <https://github.com/WordPress/wordpress-develop/blob/4.8.0/src/wp-admin/js/customize-controls.js#L5343-L5346>
272,360
<p>I need to 'soft' disable posts in a WordPress site. By that I mean I am hiding the 'Posts' menu item from admin... and not much else.</p> <p>I would also like to disable 'posts' from appearing in the Menu admin. This can already be turned off by deselecting it from 'Screen Options', but is there a way to do this programmatically and, as a bonus, also hide the 'posts' checkbox from the Screen Options panel?</p>
[ { "answer_id": 272372, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 1, "selected": false, "text": "<p>Now create your own function called post_remove() and add code in functions.php as:</p>\n\n<pre><code>fu...
2017/07/05
[ "https://wordpress.stackexchange.com/questions/272360", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60816/" ]
I need to 'soft' disable posts in a WordPress site. By that I mean I am hiding the 'Posts' menu item from admin... and not much else. I would also like to disable 'posts' from appearing in the Menu admin. This can already be turned off by deselecting it from 'Screen Options', but is there a way to do this programmatically and, as a bonus, also hide the 'posts' checkbox from the Screen Options panel?
We can use the `register_post_type_args` filter to adjust how the `post` post type is displayed in the backend with e.g.: ``` add_filter( 'register_post_type_args', function( $args, $name ) { if( 'post' === $name ) { // $args['show_ui'] = false; // Display the user-interface $args['show_in_nav_menus'] = false; // Display for selection in navigation menus $args['show_in_menu'] = false; // Display in the admin menu $args['show_in_admin_bar'] = false; // Display in the WordPress admin bar } return $args; }, 10, 2 ); ``` More info on the parameters [here](https://developer.wordpress.org/reference/functions/register_post_type/) in the Codex.
272,375
<p>I'm searching a lot about custom widgets, it seems that it can be displayed just in the sidebar, but I want to display it in my theme's footer It's just a copyright custom text that I want to add into a widget to easily change it in WP admin, I was following this tutorial: <a href="http://www.wpbeginner.com/wp-tutorials/how-to-create-a-custom-wordpress-widget/" rel="nofollow noreferrer">http://www.wpbeginner.com/wp-tutorials/how-to-create-a-custom-wordpress-widget/</a></p> <p>I have the following structure:</p> <pre><code>theme-folder ----includes --------widgets ------------copyright.php //functions.php include_once( 'includes/widgets/copyright.php' ); if (function_exists("register_sidebar")) { register_sidebar(); } </code></pre> <p>copyright.php file:</p> <pre><code>&lt;?php function register_my_widget() {// function to register my widget register_widget( 'My_Widget' ); } function My_Widget() { $widget_ops = array( 'classname' =&gt; 'example', 'description' =&gt; __('A widget that displays the authors name ', 'example') ); $control_ops = array( 'width' =&gt; 300, 'height' =&gt; 350, 'id_base' =&gt; 'example-widget' ); $this-&gt;WP_Widget( 'example-widget', __('Example Widget', 'example'), $widget_ops, $control_ops ); } add_action( 'widgets_init', 'register_my_widget' );// function to load my widget class my_widget extends WP_Widget {// The example widget class // constructor function __construct() { parent::__construct( false, __( 'My Widget', 'my-widget' ), array( 'description' =&gt; __( 'My sample widget', 'my-widget' ) ) ); } } function widget( $args, $instance ) {// display the widget extract( $args ); $title = apply_filters('widget_title', $instance['title'] ); $name = $instance['name']; $show_info = isset( $instance['show_info'] ) ? $instance['show_info'] : false; echo $before_widget; // Display the widget title if ( $title ) echo $before_title . $title . $after_title; //Display the name if ( $name ) printf( '&lt;p&gt;' . __('Hey their Sailor! My name is %1$s.', 'example') . '&lt;/p&gt;', $name ); if ( $show_info ) printf( $name ); echo $after_widget; } function update( $new_instance, $old_instance ) {// update the widget $instance = $old_instance; //Strip tags from title and name to remove HTML $instance['title'] = strip_tags( $new_instance['title'] ); $instance['name'] = strip_tags( $new_instance['name'] ); $instance['show_info'] = $new_instance['show_info']; return $instance; } function form() {// and of course the form for the widget options //Set up some default widget settings. $defaults = array( 'title' =&gt; __('Example', 'example'), 'name' =&gt; __('Bilal Shaheen', 'example'), 'show_info' =&gt; true ); $instance = wp_parse_args( (array) $instance, $defaults ); //Text Input // &lt;p&gt; // &lt;label for="echo $this-&gt;get_field_id( 'name' );"&gt;&lt;?php _e('Your Name:', 'example');&lt;/label&gt; // &lt;input id="echo $this-&gt;get_field_id( 'name' );" name="echo $this-&gt;get_field_name( 'name' );" value="echo $instance['name'];" style="width:100%;" /&gt; // &lt;/p&gt; } ?&gt; </code></pre> <p>I needed to comment the html because it's not being recognized, and I don't know how to call the widget inside my footer.php, anyone have tried to do the same before?</p>
[ { "answer_id": 272372, "author": "Pratik bhatt", "author_id": 60922, "author_profile": "https://wordpress.stackexchange.com/users/60922", "pm_score": 1, "selected": false, "text": "<p>Now create your own function called post_remove() and add code in functions.php as:</p>\n\n<pre><code>fu...
2017/07/05
[ "https://wordpress.stackexchange.com/questions/272375", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/26805/" ]
I'm searching a lot about custom widgets, it seems that it can be displayed just in the sidebar, but I want to display it in my theme's footer It's just a copyright custom text that I want to add into a widget to easily change it in WP admin, I was following this tutorial: <http://www.wpbeginner.com/wp-tutorials/how-to-create-a-custom-wordpress-widget/> I have the following structure: ``` theme-folder ----includes --------widgets ------------copyright.php //functions.php include_once( 'includes/widgets/copyright.php' ); if (function_exists("register_sidebar")) { register_sidebar(); } ``` copyright.php file: ``` <?php function register_my_widget() {// function to register my widget register_widget( 'My_Widget' ); } function My_Widget() { $widget_ops = array( 'classname' => 'example', 'description' => __('A widget that displays the authors name ', 'example') ); $control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'example-widget' ); $this->WP_Widget( 'example-widget', __('Example Widget', 'example'), $widget_ops, $control_ops ); } add_action( 'widgets_init', 'register_my_widget' );// function to load my widget class my_widget extends WP_Widget {// The example widget class // constructor function __construct() { parent::__construct( false, __( 'My Widget', 'my-widget' ), array( 'description' => __( 'My sample widget', 'my-widget' ) ) ); } } function widget( $args, $instance ) {// display the widget extract( $args ); $title = apply_filters('widget_title', $instance['title'] ); $name = $instance['name']; $show_info = isset( $instance['show_info'] ) ? $instance['show_info'] : false; echo $before_widget; // Display the widget title if ( $title ) echo $before_title . $title . $after_title; //Display the name if ( $name ) printf( '<p>' . __('Hey their Sailor! My name is %1$s.', 'example') . '</p>', $name ); if ( $show_info ) printf( $name ); echo $after_widget; } function update( $new_instance, $old_instance ) {// update the widget $instance = $old_instance; //Strip tags from title and name to remove HTML $instance['title'] = strip_tags( $new_instance['title'] ); $instance['name'] = strip_tags( $new_instance['name'] ); $instance['show_info'] = $new_instance['show_info']; return $instance; } function form() {// and of course the form for the widget options //Set up some default widget settings. $defaults = array( 'title' => __('Example', 'example'), 'name' => __('Bilal Shaheen', 'example'), 'show_info' => true ); $instance = wp_parse_args( (array) $instance, $defaults ); //Text Input // <p> // <label for="echo $this->get_field_id( 'name' );"><?php _e('Your Name:', 'example');</label> // <input id="echo $this->get_field_id( 'name' );" name="echo $this->get_field_name( 'name' );" value="echo $instance['name'];" style="width:100%;" /> // </p> } ?> ``` I needed to comment the html because it's not being recognized, and I don't know how to call the widget inside my footer.php, anyone have tried to do the same before?
We can use the `register_post_type_args` filter to adjust how the `post` post type is displayed in the backend with e.g.: ``` add_filter( 'register_post_type_args', function( $args, $name ) { if( 'post' === $name ) { // $args['show_ui'] = false; // Display the user-interface $args['show_in_nav_menus'] = false; // Display for selection in navigation menus $args['show_in_menu'] = false; // Display in the admin menu $args['show_in_admin_bar'] = false; // Display in the WordPress admin bar } return $args; }, 10, 2 ); ``` More info on the parameters [here](https://developer.wordpress.org/reference/functions/register_post_type/) in the Codex.
272,386
<p>I'm trying to create a secure download plugin.</p> <p>I found the rest api the best option for this task, but i cant change headers like <code>Content-Type:</code>. In the <code>register_rest_route</code> callback these headers already set. If i set <code>Content-disposition: attachment, filename=asd.txt</code> i get <code>ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION</code> in chrome.</p> <p>I know rest is not meant to handle these tasks, but i couldn't find any alternatives. If there is, pls tell me about it.</p> <p>The data downloaded seems like it's json encoded.</p> <p>I'm sick of wordpress "magic". These tasks would be so easy using plain PHP but wordpress just makes it complicated.</p> <p>Please someone tell me how to disable these magic headers *** or recommend me a way for secured (php) downloads in my plugin.</p> <p>(No, i don't want to use third party plugins. I've tried many of them. None of them worked so far... :D These whole wordpress thing is a huge step backwards after symfony...)</p> <p>Here is my <strong>experimental</strong> code:</p> <pre><code>add_action('rest_api_init', function() { register_rest_route('secure-downloads/v1', '/download/(?P&lt;filename&gt;.*)', array( 'methods' =&gt; 'GET', 'callback' =&gt; 'secure_downloads_handle_download' )); }); function secure_downloads_handle_download(WP_REST_Request $request) { $filename = urldecode($request-&gt;offsetGet('filename')); if(strpos($filename, '/..')) { return new WP_REST_Response('', 403); } $path = SECURE_DOWNLOADS_UPLOAD_DIR . $filename; return new WP_REST_Response(file_get_contents($path), 200, array( 'Content-Type' =&gt; 'application/octet-stream', 'Content-Transfer-Encoding' =&gt; 'Binary', 'Content-disposition' =&gt; 'attachment, filename=\\' . $filename . '\\' )); } </code></pre>
[ { "answer_id": 272389, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>It should be enough to add the content disposition field.</p>\n\n<p>But specifically it's Content-<strong>D<...
2017/07/05
[ "https://wordpress.stackexchange.com/questions/272386", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123204/" ]
I'm trying to create a secure download plugin. I found the rest api the best option for this task, but i cant change headers like `Content-Type:`. In the `register_rest_route` callback these headers already set. If i set `Content-disposition: attachment, filename=asd.txt` i get `ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION` in chrome. I know rest is not meant to handle these tasks, but i couldn't find any alternatives. If there is, pls tell me about it. The data downloaded seems like it's json encoded. I'm sick of wordpress "magic". These tasks would be so easy using plain PHP but wordpress just makes it complicated. Please someone tell me how to disable these magic headers \*\*\* or recommend me a way for secured (php) downloads in my plugin. (No, i don't want to use third party plugins. I've tried many of them. None of them worked so far... :D These whole wordpress thing is a huge step backwards after symfony...) Here is my **experimental** code: ``` add_action('rest_api_init', function() { register_rest_route('secure-downloads/v1', '/download/(?P<filename>.*)', array( 'methods' => 'GET', 'callback' => 'secure_downloads_handle_download' )); }); function secure_downloads_handle_download(WP_REST_Request $request) { $filename = urldecode($request->offsetGet('filename')); if(strpos($filename, '/..')) { return new WP_REST_Response('', 403); } $path = SECURE_DOWNLOADS_UPLOAD_DIR . $filename; return new WP_REST_Response(file_get_contents($path), 200, array( 'Content-Type' => 'application/octet-stream', 'Content-Transfer-Encoding' => 'Binary', 'Content-disposition' => 'attachment, filename=\\' . $filename . '\\' )); } ```
Here is what i found out: The `ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION` error was the bad composition of the `Content-Disposition` header. Here is the correct one: ``` array( 'Content-Disposition' => 'attachment; filename="' . $filename . '"' ) ``` Note the **semicolon** after attachment, the **doublequotes** around the filename and the **capital D** in disposition word as @Tom J Nowell pointed out. This solved the headers problem but the `WP_REST_Response` still outputs the files like they were json encoded. So i went the conventional way: ``` header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Content-Type: application/octet-stream'); readfile($path); exit; ```
272,406
<p>I am migrating a static site over to WP. Currently I have a header function that changes the inverted logo to full color on user scroll using JS. <a href="https://synchronygroup.com/" rel="nofollow noreferrer">See Function on scroll</a></p> <p><strong>Current JS for Scroll function:</strong></p> <pre><code>$(window).scroll(function() { var top = $(window).scrollTop(); //Clears navbar timing functions on initial scroll clearTimeout(timeout); //Conditional to make function run if header is scroll pased 100px if ((top &gt; 100) &amp;&amp; $('#mainNav').is(':hidden')) { showNav(); timeout = setTimeout(hideNav, 2000); } else if ((top &gt; 100) &amp;&amp; $('#mainNav').is(':visible')) { showNav(); $('#logo').attr('src', './assets/sg-logo-inverted.svg'); $('.nav-trigger-line').css({'background-color':'#fff'}); } else { $('header').css({ 'background-color': 'transparent' }); $('#logo').attr('src', './assets/sg-logo-inverted.svg'); $('#logo').css({'width': '175px'}); $('.nav-trigger-line').css({'background-color':'#fff'}); } }); </code></pre> <p><strong>Current HTML Markup:</strong></p> <pre><code>&lt;header class="fixed-top p-3"&gt; &lt;!-- Logo and Burger --&gt; &lt;div class="container-fluid brand-wrap"&gt; &lt;div class="row"&gt; &lt;div class="col-6"&gt; &lt;a href="index.html"&gt;&lt;img id="logo" src="./assets/sg-logo-inverted.svg" class="img-fluid" alt="Synchrony Group"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col-6 trigger-wrapper py-1"&gt; &lt;div id="burger"&gt; &lt;div class="nav-trigger-line"&gt;&lt;/div&gt; &lt;div class="nav-trigger-line"&gt;&lt;/div&gt; &lt;div class="nav-trigger-line"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/header&gt; </code></pre> <p>I have revised the mark in my header.php file to dynamically include the site logo via the WP Dashboard:</p> <p><strong>Revised HTML Markup:</strong></p> <pre><code>&lt;header class="fixed-top p-3"&gt; &lt;!-- Logo and Burger --&gt; &lt;div class="container-fluid brand-wrap"&gt; &lt;div class="row"&gt; &lt;?php if ( get_header_image() ) : ?&gt; &lt;div class="col-6"&gt; &lt;a href="&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;" rel="home"&gt; &lt;img id="logo" src="&lt;?php header_image(); ?&gt;" class="img-fluid" alt="Synchrony Group"&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;div class="col-6 trigger-wrapper py-1"&gt; &lt;div id="burger"&gt; &lt;div class="nav-trigger-line"&gt;&lt;/div&gt; &lt;div class="nav-trigger-line"&gt;&lt;/div&gt; &lt;div class="nav-trigger-line"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/header&gt; </code></pre> <p>The Scroll Function still works but fails to replace the image because it looks for the image in the specific dir of the page, which does not exist.</p> <p><strong>Question:</strong> How can I dynamically change the logo on scroll function? Is this something that is handled by PHP rather than JS. What is the correct method to go about doing this?</p>
[ { "answer_id": 272403, "author": "Den Isahac", "author_id": 113233, "author_profile": "https://wordpress.stackexchange.com/users/113233", "pm_score": 4, "selected": true, "text": "<p>As stated in the official blog of <strong>jQuery</strong>. Note that <strong>WordPress</strong> is mentio...
2017/07/05
[ "https://wordpress.stackexchange.com/questions/272406", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104284/" ]
I am migrating a static site over to WP. Currently I have a header function that changes the inverted logo to full color on user scroll using JS. [See Function on scroll](https://synchronygroup.com/) **Current JS for Scroll function:** ``` $(window).scroll(function() { var top = $(window).scrollTop(); //Clears navbar timing functions on initial scroll clearTimeout(timeout); //Conditional to make function run if header is scroll pased 100px if ((top > 100) && $('#mainNav').is(':hidden')) { showNav(); timeout = setTimeout(hideNav, 2000); } else if ((top > 100) && $('#mainNav').is(':visible')) { showNav(); $('#logo').attr('src', './assets/sg-logo-inverted.svg'); $('.nav-trigger-line').css({'background-color':'#fff'}); } else { $('header').css({ 'background-color': 'transparent' }); $('#logo').attr('src', './assets/sg-logo-inverted.svg'); $('#logo').css({'width': '175px'}); $('.nav-trigger-line').css({'background-color':'#fff'}); } }); ``` **Current HTML Markup:** ``` <header class="fixed-top p-3"> <!-- Logo and Burger --> <div class="container-fluid brand-wrap"> <div class="row"> <div class="col-6"> <a href="index.html"><img id="logo" src="./assets/sg-logo-inverted.svg" class="img-fluid" alt="Synchrony Group"></a> </div> <div class="col-6 trigger-wrapper py-1"> <div id="burger"> <div class="nav-trigger-line"></div> <div class="nav-trigger-line"></div> <div class="nav-trigger-line"></div> </div> </div> </div> </div> </header> ``` I have revised the mark in my header.php file to dynamically include the site logo via the WP Dashboard: **Revised HTML Markup:** ``` <header class="fixed-top p-3"> <!-- Logo and Burger --> <div class="container-fluid brand-wrap"> <div class="row"> <?php if ( get_header_image() ) : ?> <div class="col-6"> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"> <img id="logo" src="<?php header_image(); ?>" class="img-fluid" alt="Synchrony Group"> </a> </div> <?php endif; ?> <div class="col-6 trigger-wrapper py-1"> <div id="burger"> <div class="nav-trigger-line"></div> <div class="nav-trigger-line"></div> <div class="nav-trigger-line"></div> </div> </div> </div> </div> </header> ``` The Scroll Function still works but fails to replace the image because it looks for the image in the specific dir of the page, which does not exist. **Question:** How can I dynamically change the logo on scroll function? Is this something that is handled by PHP rather than JS. What is the correct method to go about doing this?
As stated in the official blog of **jQuery**. Note that **WordPress** is mentioned in the quote. > > jQuery Migrate 1.4.1 released, and the path to jQuery 3.0 > ========================================================= > > > Version 1.4.1 of the jQuery Migrate plugin has been released. It has only a few changes but the most important of them fixes a problem with unquoted selectors that seems to be very common in some **WordPress** themes. In most cases Migrate can automatically fix this problem when it is used with jQuery 1.12.x or 2.2.x, although it may not be able to repair some complex selectors. The good news is that all the cases of unquoted selectors reported in **WordPress** themes appear to be fixable by this version of Migrate! > > > A quick answer to your question; **yes** you can remove the *jQuery migration* script and if you don't see any unwanted behavior after the removal of the script, then it's safe to say that you can completely remove the reference migration script. Can be read in [here](https://blog.jquery.com/2016/05/19/jquery-migrate-1-4-1-released-and-the-path-to-jquery-3-0/)
272,456
<p>Hello i use woocommerce and i want to remove the field from the admin panel. How can I do it right? <a href="https://i.stack.imgur.com/QrJvu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QrJvu.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 272459, "author": "tushonline", "author_id": 15946, "author_profile": "https://wordpress.stackexchange.com/users/15946", "pm_score": 3, "selected": true, "text": "<p>You cannot remove the field using a code but you can disable using the sale price across the store. </p>\n\...
2017/07/06
[ "https://wordpress.stackexchange.com/questions/272456", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113939/" ]
Hello i use woocommerce and i want to remove the field from the admin panel. How can I do it right? [![enter image description here](https://i.stack.imgur.com/QrJvu.jpg)](https://i.stack.imgur.com/QrJvu.jpg)
You cannot remove the field using a code but you can disable using the sale price across the store. **To disable sale price** ``` function custom_wc_get_sale_price( $sale_price, $product ) { return $product->get_regular_price(); return $sale_price; } add_filter( 'woocommerce_get_sale_price', 'custom_wc_get_sale_price', 50, 2 ); add_filter( 'woocommerce_get_price', 'custom_wc_get_sale_price', 50, 2 ); ``` **To hide this field,** you can use a CSS to hide it from Product Edit screen. But that CSS needs to be loaded on the admin side, so putting this in theme style sheet may not work.
272,471
<p>I am trying to implement a feature on our site where a user is able to join a team by clicking a button on that teams page (teams being custom roles set up in User Role Editor). However, if the user is already a member of that team, I don't want the button to be displayed for them. </p> <p>I already have the code working to enable someone to join a team:</p> <pre><code>&lt;?php add_shortcode( 'select_marketing', 'select_marketing' ); function select_marketing() { // Stop if user is not logged in. if ( ! is_user_logged_in() ) return; ob_start(); ?&gt; &lt;form method="post" action=""&gt; &lt;button class="btn btn-default" type="submit" name="role" value="marketing"&gt;Join this Team&lt;/button&gt; &lt;/form&gt; &lt;?php // Do not process anything if it's not $_POST if ( ! isset( $_POST['role'] ) ) return; // Never trust user input. $role = sanitize_key( $_POST['role'] ); if ( ! in_array( $role, array( 'marketing', ) ) ) return; // Get the user object $user = new WP_User( get_current_user_id() ); $index = key( $user-&gt;roles ); $user_role = $user-&gt;roles[ $index ]; // User already got that user if ( $user_role == $role ) { echo sprintf( __( 'You already have %s role.' ), $role ); } else { // update user role $user-&gt;set_role( $role ); echo sprintf( __( 'Your role was changed to %s.' ), $role ); } $output = ob_get_contents(); ob_end_clean(); return $output; } ?&gt; </code></pre> <p>However I can't for the life of me figure out how to hide the button for just one specific role, in the example above it would be the marketing role.</p> <p>If anyone could give me a hand, that would be highly appreciated.</p> <p>Oh, and if there is a more elegant approach to doing what I am trying achieve, please feel free to let me know. I'm quite new to wordpress and php. </p> <p>The above code is slightly modified from this post: <a href="https://wordpress.stackexchange.com/questions/240230/how-to-allow-registered-users-to-change-their-user-role-through-frontend">How to allow registered users to change their user role through frontend?</a></p>
[ { "answer_id": 272459, "author": "tushonline", "author_id": 15946, "author_profile": "https://wordpress.stackexchange.com/users/15946", "pm_score": 3, "selected": true, "text": "<p>You cannot remove the field using a code but you can disable using the sale price across the store. </p>\n\...
2017/07/06
[ "https://wordpress.stackexchange.com/questions/272471", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123279/" ]
I am trying to implement a feature on our site where a user is able to join a team by clicking a button on that teams page (teams being custom roles set up in User Role Editor). However, if the user is already a member of that team, I don't want the button to be displayed for them. I already have the code working to enable someone to join a team: ``` <?php add_shortcode( 'select_marketing', 'select_marketing' ); function select_marketing() { // Stop if user is not logged in. if ( ! is_user_logged_in() ) return; ob_start(); ?> <form method="post" action=""> <button class="btn btn-default" type="submit" name="role" value="marketing">Join this Team</button> </form> <?php // Do not process anything if it's not $_POST if ( ! isset( $_POST['role'] ) ) return; // Never trust user input. $role = sanitize_key( $_POST['role'] ); if ( ! in_array( $role, array( 'marketing', ) ) ) return; // Get the user object $user = new WP_User( get_current_user_id() ); $index = key( $user->roles ); $user_role = $user->roles[ $index ]; // User already got that user if ( $user_role == $role ) { echo sprintf( __( 'You already have %s role.' ), $role ); } else { // update user role $user->set_role( $role ); echo sprintf( __( 'Your role was changed to %s.' ), $role ); } $output = ob_get_contents(); ob_end_clean(); return $output; } ?> ``` However I can't for the life of me figure out how to hide the button for just one specific role, in the example above it would be the marketing role. If anyone could give me a hand, that would be highly appreciated. Oh, and if there is a more elegant approach to doing what I am trying achieve, please feel free to let me know. I'm quite new to wordpress and php. The above code is slightly modified from this post: [How to allow registered users to change their user role through frontend?](https://wordpress.stackexchange.com/questions/240230/how-to-allow-registered-users-to-change-their-user-role-through-frontend)
You cannot remove the field using a code but you can disable using the sale price across the store. **To disable sale price** ``` function custom_wc_get_sale_price( $sale_price, $product ) { return $product->get_regular_price(); return $sale_price; } add_filter( 'woocommerce_get_sale_price', 'custom_wc_get_sale_price', 50, 2 ); add_filter( 'woocommerce_get_price', 'custom_wc_get_sale_price', 50, 2 ); ``` **To hide this field,** you can use a CSS to hide it from Product Edit screen. But that CSS needs to be loaded on the admin side, so putting this in theme style sheet may not work.
272,476
<p>I have a post-type Collection with custom-post-type categories.</p> <p>I want the following url structure: www.baseurl.com/collection/current-category-name/postname</p> <p>How do I accomplish this?</p>
[ { "answer_id": 272477, "author": "berend", "author_id": 120717, "author_profile": "https://wordpress.stackexchange.com/users/120717", "pm_score": 2, "selected": true, "text": "<p>Yes you can use the rewrite parameter when creating your custom post type:</p>\n\n<pre><code>register_post_ty...
2017/07/06
[ "https://wordpress.stackexchange.com/questions/272476", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/31706/" ]
I have a post-type Collection with custom-post-type categories. I want the following url structure: www.baseurl.com/collection/current-category-name/postname How do I accomplish this?
Yes you can use the rewrite parameter when creating your custom post type: ``` register_post_type( 'example_type', array( 'labels' => array( 'name' => "Example-Type", 'singular_name' => "example-type" ), 'public' => true, 'has_archive' => true, 'rewrite' => array('slug' => 'the-url-you-want', ) ); } ``` You will need to reset your permalinks for it to take effect as well. EDIT: ``` function custom_post_link( $post_link, $id = 0 ){ $post = get_post($id); if ( is_object( $post ) ){ $terms = wp_get_object_terms( $post->ID, 'category' ); if( $terms ){ return str_replace( '%category%' , $terms[0]->slug , $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'custom_post_link', 1, 3 ); ```
272,488
<p>So far I have tried these three options and all 3 of them are not working.</p> <h2>Option 1</h2> <pre><code>$options = array( 'meta_key' =&gt; 'first_name', 'meta_value' =&gt; '', 'meta_compare' =&gt; '=', ); $users = get_users( $options ); </code></pre> <h2>Option 2</h2> <pre><code>$options = array( 'meta_key' =&gt; 'first_name', 'meta_value' =&gt; null, 'meta_compare' =&gt; '=', ); $users = get_users( $options ); </code></pre> <h2>Option 3</h2> <pre><code>$options = array( 'meta_query' =&gt; array( array( 'key' =&gt; 'first_name', 'compare' =&gt; 'NOT EXISTS', ), ) ); $users = get_users( $options ); </code></pre>
[ { "answer_id": 272492, "author": "birgire", "author_id": 26350, "author_profile": "https://wordpress.stackexchange.com/users/26350", "pm_score": 2, "selected": true, "text": "<p>It looks like you're searching for the <code>first_name</code> meta keys with <strong>empty</strong> string me...
2017/07/06
[ "https://wordpress.stackexchange.com/questions/272488", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24579/" ]
So far I have tried these three options and all 3 of them are not working. Option 1 -------- ``` $options = array( 'meta_key' => 'first_name', 'meta_value' => '', 'meta_compare' => '=', ); $users = get_users( $options ); ``` Option 2 -------- ``` $options = array( 'meta_key' => 'first_name', 'meta_value' => null, 'meta_compare' => '=', ); $users = get_users( $options ); ``` Option 3 -------- ``` $options = array( 'meta_query' => array( array( 'key' => 'first_name', 'compare' => 'NOT EXISTS', ), ) ); $users = get_users( $options ); ```
It looks like you're searching for the `first_name` meta keys with **empty** string meta values: ``` $options = array( 'meta_query' => array( array( 'key' => 'first_name', 'value' => '', 'compare' => '=', ), ) ); $users = get_users( $options ); ``` that generates this kind of SQL query: ``` SELECT wp_users.* FROM wp_users INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) WHERE 1=1 AND ( ( wp_usermeta.meta_key = 'first_name' AND wp_usermeta.meta_value = '' ) ) ORDER BY user_login ASC ``` Note that ``` $options = array( 'meta_key' => 'first_name', 'meta_value' => '', 'meta_compare' => '=', ); $users = get_users( $options ); ``` generates this kind of SQL query: ``` SELECT wp_users.* FROM wp_users INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) WHERE 1=1 AND ( wp_usermeta.meta_key = 'first_name' ) ORDER BY user_login ASC ; ```
272,515
<p>Slowly going crazy over trying to make taxonomy admin columns sortable by a custom field number. I have a custom taxonomy called "typer" and these taxonomies have a custom field called "prioritet". </p> <p>I managed to get my code to show the column, and make it sortable. Only issue is, that the fields are sorted alphabetically, despite all being numbers. thats means that a fieldset of [1, 3, 14, 22] would show as:</p> <p>1</p> <p>14</p> <p>22</p> <p>3</p> <p>My code so far</p> <pre><code>function create_date_column_for_issues($issue_columns) { $issue_columns['prioritet'] = 'Prioritet / sortering'; return $issue_columns; } add_filter('manage_edit-typer_columns', 'create_date_column_for_issues'); function populate_date_column_for_issues($value, $column_name, $term_id) { $issue = get_term($term_id, 'typer'); $date = get_field('prioritet', $issue); switch($column_name) { case 'prioritet': $value = $date; break; default: break; } return $value; } add_filter('manage_typer_custom_column', 'populate_date_column_for_issues', 10, 3); function register_date_column_for_issues_sortable($columns) { $columns['prioritet'] = 'prioritet'; return $columns; } add_filter('manage_edit-typer_sortable_columns', 'register_date_column_for_issues_sortable'); add_filter( 'terms_clauses', 'filter_terms_clauses', 10, 3 ); /** * Filter WP_Term_Query meta query * * @param object $query WP_Term_Query * @return object */ function filter_terms_clauses( $pieces, $taxonomies, $args ) { global $pagenow, $wpdb; // Require ordering $orderby = ( isset( $_GET['orderby'] ) ) ? trim( sanitize_text_field( $_GET['orderby'] ) ) : ''; if ( empty( $orderby ) ) { return $pieces; } // set taxonomy $taxonomy = $taxonomies[0]; // only if current taxonomy or edit page in admin if ( !is_admin() || $pagenow !== 'edit-tags.php' || !in_array( $taxonomy, [ 'typer' ] ) ) { return $pieces; } // and ordering matches if ( $orderby === 'prioritet' ) { $pieces['join'] .= ' INNER JOIN ' . $wpdb-&gt;termmeta . ' AS tm ON t.term_id = tm.term_id '; $pieces['where'] .= ' AND tm.meta_key = "prioritet"'; $pieces['orderby'] = ' ORDER BY tm.meta_value '; } return $pieces; } </code></pre> <p>My knowledge on MySQL is next to nothing, so i have no idea where to go width this. </p> <p>As an extra:</p> <p>Right now the sorting will exclude all taxonomies that has an empty field. Would be nice to have these shown in the bottom, but i do realize i requires a way more complicated query. So only join in on that if just so happen to have the solution on the top of your head.</p>
[ { "answer_id": 284925, "author": "dipak_pusti", "author_id": 44528, "author_profile": "https://wordpress.stackexchange.com/users/44528", "pm_score": 2, "selected": false, "text": "<p>The code I am posting is a modified and simplified version of yours. I got my solution using your code.</...
2017/07/06
[ "https://wordpress.stackexchange.com/questions/272515", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104160/" ]
Slowly going crazy over trying to make taxonomy admin columns sortable by a custom field number. I have a custom taxonomy called "typer" and these taxonomies have a custom field called "prioritet". I managed to get my code to show the column, and make it sortable. Only issue is, that the fields are sorted alphabetically, despite all being numbers. thats means that a fieldset of [1, 3, 14, 22] would show as: 1 14 22 3 My code so far ``` function create_date_column_for_issues($issue_columns) { $issue_columns['prioritet'] = 'Prioritet / sortering'; return $issue_columns; } add_filter('manage_edit-typer_columns', 'create_date_column_for_issues'); function populate_date_column_for_issues($value, $column_name, $term_id) { $issue = get_term($term_id, 'typer'); $date = get_field('prioritet', $issue); switch($column_name) { case 'prioritet': $value = $date; break; default: break; } return $value; } add_filter('manage_typer_custom_column', 'populate_date_column_for_issues', 10, 3); function register_date_column_for_issues_sortable($columns) { $columns['prioritet'] = 'prioritet'; return $columns; } add_filter('manage_edit-typer_sortable_columns', 'register_date_column_for_issues_sortable'); add_filter( 'terms_clauses', 'filter_terms_clauses', 10, 3 ); /** * Filter WP_Term_Query meta query * * @param object $query WP_Term_Query * @return object */ function filter_terms_clauses( $pieces, $taxonomies, $args ) { global $pagenow, $wpdb; // Require ordering $orderby = ( isset( $_GET['orderby'] ) ) ? trim( sanitize_text_field( $_GET['orderby'] ) ) : ''; if ( empty( $orderby ) ) { return $pieces; } // set taxonomy $taxonomy = $taxonomies[0]; // only if current taxonomy or edit page in admin if ( !is_admin() || $pagenow !== 'edit-tags.php' || !in_array( $taxonomy, [ 'typer' ] ) ) { return $pieces; } // and ordering matches if ( $orderby === 'prioritet' ) { $pieces['join'] .= ' INNER JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id '; $pieces['where'] .= ' AND tm.meta_key = "prioritet"'; $pieces['orderby'] = ' ORDER BY tm.meta_value '; } return $pieces; } ``` My knowledge on MySQL is next to nothing, so i have no idea where to go width this. As an extra: Right now the sorting will exclude all taxonomies that has an empty field. Would be nice to have these shown in the bottom, but i do realize i requires a way more complicated query. So only join in on that if just so happen to have the solution on the top of your head.
The code I am posting is a modified and simplified version of yours. I got my solution using your code. ``` /** * Filter WP_Term_Query meta query * * @param object $query WP_Term_Query * @return object */ function filter_terms_clauses( $pieces, $taxonomies, $args ) { global $pagenow, $wpdb; if(!is_admin()) { return $pieces; } if( is_admin() && $pagenow == 'edit-tags.php' && $taxonomies[0] == 'typer' && ( isset($_GET['orderby']) && $_GET['orderby'] == 'prioritet' ) ) { $pieces['join'] .= ' INNER JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id '; $pieces['where'] .= ' AND tm.meta_key = "prioritet"'; $pieces['orderby'] = ' ORDER BY tm.meta_value '; $pieces['order'] = isset($_GET['order']) ? $_GET['order'] : "DESC"; } return $pieces; } add_filter( 'terms_clauses', 'filter_terms_clauses', 10, 3 ); ``` Hope this one helps.
272,525
<p>I have created <strong>Dynamic Add/Remove Custom Fields (Repeater Fields)</strong> in my custom Post types. It is working perfectly. I want to add a new <strong>JQuery Date Picker</strong> field. I tried hard to create code and also searched the web but found no luck.</p> <p>Plz Help me.</p> <p>Following is my code.</p> <pre><code>function project_rewards_select_options() { $options = array ( 'Option 1' =&gt; 'Option 1', 'Option 2' =&gt; 'Option 2', 'Option 3' =&gt; 'Option 3', ); return $options; } function project_reward_callback( $post ) { wp_nonce_field( 'project_reward_nonce', 'project_reward_nonce' ); $reward_value = get_post_meta( get_the_ID(), '_project_rewards', true ); $options = project_rewards_select_options(); ?&gt; &lt;script type="text/javascript"&gt; jQuery(document).ready(function( $ ){ $( '#add-row' ).on('click', function() { var row = $( '.empty-row.screen-reader-text' ).clone(true); row.removeClass( 'empty-row screen-reader-text' ); row.insertBefore( '#repeatable-fieldset-one tbody&gt;tr:last' ); return false; }); $( '.remove-row' ).on('click', function() { $(this).parents('tr').remove(); return false; }); }); &lt;/script&gt; &lt;table id="repeatable-fieldset-one" width="100%"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th width="15%"&gt;Reward Amount&lt;/th&gt; &lt;th width="25%"&gt;Reward Title&lt;/th&gt; &lt;th width="10%"&gt;Shipping&lt;/th&gt; &lt;th width="45%"&gt;Reward Description&lt;/th&gt; &lt;th width="5%"&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php ( $reward_value ); foreach ( $reward_value as $field ) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" class="widefat" name="reward[]" value="&lt;?php if ( isset ( $field['reward'] ) ) echo esc_attr( $field['reward'] ); ?&gt;" pattern="[1-9]\d*" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" class="widefat" name="reward_title[]" value="&lt;?php if ( isset ( $field['reward_title'] ) ) echo esc_attr( $field['reward_title'] ); ?&gt;" /&gt;&lt;/td&gt; &lt;td&gt; &lt;select class="widefat" name="reward_shipping[]"&gt; &lt;?php foreach ( $options as $label =&gt; $value ) : ?&gt; &lt;option value="&lt;?php echo $value; ?&gt;"&lt;?php selected( $field['reward_shipping'], $value ); ?&gt;&gt;&lt;?php echo $label; ?&gt;&lt;/option&gt; &lt;?php endforeach; ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;td&gt;&lt;textarea class="widefat" name="reward_description[]"&gt;&lt;?php if ( isset ( $field['reward_description'] ) ) echo esc_attr( $field['reward_description'] ); ?&gt;&lt;/textarea&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="image" class="remove-row" src="&lt;?php bloginfo('template_directory'); ?&gt;/assets/images/remove-icon.png" alt="Submit" width="35" height="35"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; &lt;!-- empty hidden one for jQuery --&gt; &lt;tr class="empty-row screen-reader-text"&gt; &lt;td&gt;&lt;input type="text" class="widefat" name="reward[]" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" class="widefat" name="reward_title[]" /&gt;&lt;/td&gt; &lt;td&gt; &lt;select class="widefat" name="reward_shipping[]"&gt; &lt;?php foreach ( $options as $label =&gt; $value ) : ?&gt; &lt;option value="&lt;?php echo $value; ?&gt;"&gt;&lt;?php echo $label; ?&gt;&lt;/option&gt; &lt;?php endforeach; ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;td&gt;&lt;textarea class="widefat" name="reward_description[]" &gt;&lt;/textarea&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="image" class="remove-row" src="&lt;?php bloginfo('template_directory'); ?&gt;/assets/images/remove-icon.png" alt="Submit" width="35" height="35"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;&lt;a id="add-row" class="button" href="#"&gt;Add Reward&lt;/a&gt;&lt;/p&gt; &lt;?php } function save_project_reward( $post_id ) { // Check if our nonce is set. if ( ! isset( $_POST['project_reward_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['project_reward_nonce'], 'project_reward_nonce' ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) &amp;&amp; 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } $reward_data = array(); $options = project_rewards_select_options(); $rewards = $_POST['reward']; $reward_titles = $_POST['reward_title']; $reward_shippings = $_POST['reward_shipping']; $reward_descriptions = $_POST['reward_description']; $count = count( $rewards ); for ( $i = 0; $i &lt; $count; $i++ ) { if ( $rewards[$i] != '' ) : $reward_data[$i]['reward'] = stripslashes( strip_tags( $rewards[$i] ) ); if ( in_array( $reward_shippings[$i], $options ) ) $reward_data[$i]['reward_shipping'] = stripslashes( strip_tags( $reward_shippings[$i] ) ); else $reward_data[$i]['reward_shipping'] = ''; endif; if ( $reward_titles[$i] != '' ) : $reward_data[$i]['reward_title'] = stripslashes( strip_tags( $reward_titles[$i] ) ); endif; if ( $reward_descriptions[$i] != '' ) : $reward_data[$i]['reward_description'] = stripslashes( $reward_descriptions[$i] ); endif; } update_post_meta( $post_id, '_project_rewards', $reward_data ); } add_action( 'save_post', 'save_project_reward' ); </code></pre>
[ { "answer_id": 272631, "author": "LWS-Mo", "author_id": 88895, "author_profile": "https://wordpress.stackexchange.com/users/88895", "pm_score": 1, "selected": false, "text": "<p>Wordpress has the jQuery datepicker already included. So you can enqueue the default WP script. However, as fa...
2017/07/06
[ "https://wordpress.stackexchange.com/questions/272525", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113946/" ]
I have created **Dynamic Add/Remove Custom Fields (Repeater Fields)** in my custom Post types. It is working perfectly. I want to add a new **JQuery Date Picker** field. I tried hard to create code and also searched the web but found no luck. Plz Help me. Following is my code. ``` function project_rewards_select_options() { $options = array ( 'Option 1' => 'Option 1', 'Option 2' => 'Option 2', 'Option 3' => 'Option 3', ); return $options; } function project_reward_callback( $post ) { wp_nonce_field( 'project_reward_nonce', 'project_reward_nonce' ); $reward_value = get_post_meta( get_the_ID(), '_project_rewards', true ); $options = project_rewards_select_options(); ?> <script type="text/javascript"> jQuery(document).ready(function( $ ){ $( '#add-row' ).on('click', function() { var row = $( '.empty-row.screen-reader-text' ).clone(true); row.removeClass( 'empty-row screen-reader-text' ); row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' ); return false; }); $( '.remove-row' ).on('click', function() { $(this).parents('tr').remove(); return false; }); }); </script> <table id="repeatable-fieldset-one" width="100%"> <thead> <tr> <th width="15%">Reward Amount</th> <th width="25%">Reward Title</th> <th width="10%">Shipping</th> <th width="45%">Reward Description</th> <th width="5%"></th> </tr> </thead> <tbody> <?php ( $reward_value ); foreach ( $reward_value as $field ) { ?> <tr> <td><input type="text" class="widefat" name="reward[]" value="<?php if ( isset ( $field['reward'] ) ) echo esc_attr( $field['reward'] ); ?>" pattern="[1-9]\d*" /></td> <td><input type="text" class="widefat" name="reward_title[]" value="<?php if ( isset ( $field['reward_title'] ) ) echo esc_attr( $field['reward_title'] ); ?>" /></td> <td> <select class="widefat" name="reward_shipping[]"> <?php foreach ( $options as $label => $value ) : ?> <option value="<?php echo $value; ?>"<?php selected( $field['reward_shipping'], $value ); ?>><?php echo $label; ?></option> <?php endforeach; ?> </select> </td> <td><textarea class="widefat" name="reward_description[]"><?php if ( isset ( $field['reward_description'] ) ) echo esc_attr( $field['reward_description'] ); ?></textarea></td> <td><input type="image" class="remove-row" src="<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png" alt="Submit" width="35" height="35"></td> </tr> <?php } ?> <!-- empty hidden one for jQuery --> <tr class="empty-row screen-reader-text"> <td><input type="text" class="widefat" name="reward[]" /></td> <td><input type="text" class="widefat" name="reward_title[]" /></td> <td> <select class="widefat" name="reward_shipping[]"> <?php foreach ( $options as $label => $value ) : ?> <option value="<?php echo $value; ?>"><?php echo $label; ?></option> <?php endforeach; ?> </select> </td> <td><textarea class="widefat" name="reward_description[]" ></textarea></td> <td><input type="image" class="remove-row" src="<?php bloginfo('template_directory'); ?>/assets/images/remove-icon.png" alt="Submit" width="35" height="35"></td> </tr> </tbody> </table> <p><a id="add-row" class="button" href="#">Add Reward</a></p> <?php } function save_project_reward( $post_id ) { // Check if our nonce is set. if ( ! isset( $_POST['project_reward_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['project_reward_nonce'], 'project_reward_nonce' ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } $reward_data = array(); $options = project_rewards_select_options(); $rewards = $_POST['reward']; $reward_titles = $_POST['reward_title']; $reward_shippings = $_POST['reward_shipping']; $reward_descriptions = $_POST['reward_description']; $count = count( $rewards ); for ( $i = 0; $i < $count; $i++ ) { if ( $rewards[$i] != '' ) : $reward_data[$i]['reward'] = stripslashes( strip_tags( $rewards[$i] ) ); if ( in_array( $reward_shippings[$i], $options ) ) $reward_data[$i]['reward_shipping'] = stripslashes( strip_tags( $reward_shippings[$i] ) ); else $reward_data[$i]['reward_shipping'] = ''; endif; if ( $reward_titles[$i] != '' ) : $reward_data[$i]['reward_title'] = stripslashes( strip_tags( $reward_titles[$i] ) ); endif; if ( $reward_descriptions[$i] != '' ) : $reward_data[$i]['reward_description'] = stripslashes( $reward_descriptions[$i] ); endif; } update_post_meta( $post_id, '_project_rewards', $reward_data ); } add_action( 'save_post', 'save_project_reward' ); ```
Wordpress has the jQuery datepicker already included. So you can enqueue the default WP script. However, as far as I know, WP doesnt include the necessary styling for the datepicker! So try to enqueue the WP script, and for example, styles from external source: ``` function my_datepicker_enqueue() { wp_enqueue_script( 'jquery-ui-datepicker' ); // enqueue datepicker from WP wp_enqueue_style( 'jquery-ui-style', '//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/base/jquery-ui.css', true); } add_action( 'admin_enqueue_scripts', 'my_datepicker_enqueue' ); ``` Create a new HTML input field with atleast with a class and a name. HTML of the input field: (you already have some input fields defined, so jump to the script) ``` <input type="text" name="_custom_datepicker[]" id="_custom_datepicker[]" class="my-custom-datepicker-field" value="<?php echo $your_saved_value; ?>" /> ``` Than add a script to init the datepicker for our new element. Script: (make sure that you target the right input element, we are looking at the defined class here, cause we want to use multiple instances.) ``` jQuery(document).ready(function($){ $('.my-custom-datepicker-field').datepicker({ dateFormat: 'dd-mm-yy', //maybe you want something like this showButtonPanel: true }); }); ``` --- **Update:** I had some problems reading your code at first, and you also have several errors in your code. First I could see the same strange behaviour. I have now setup a testplugin on a dev site, and there it is now working. **1:** You set up your save function so that you cannot just enter a date and save. You will have to either add a amount, title or description also, to be able to save. I think this is intended by you? **2:** In the save function you have the following code: ``` if ( $reward_descriptions[$i] != '' ) : $reward_data[$i]['reward_date'] = stripslashes( $reward_dates[$i] ); endif; ``` So only when the description field is not empty the date will get saved?! Seems this was a typo because the other fields look good. Change to: ``` if ( $reward_data[$i] != '' ) : $reward_data[$i]['reward_date'] = stripslashes( $reward_dates[$i] ); endif; ``` **3:** In your callback code you have these fields as datepicker fields: ``` <td><input type="text" name="_custom_datepicker[]" id="_custom_datepicker[]" class="my-custom-datepicker-field" value="<?php echo esc_attr( $field['reward_date'] ); ?>" /></td> ``` and ``` <td><input type="text" class="my-custom-datepicker-field" name="_custom_datepicker[]" /></td> ``` Both named `_custom_datepicker[]`. But in your save function you try to save fields called `reward_date` instead. Also the `id` should be unique. But you add the same `id` to all datefields. You could just remove the `id` from these fields, its not needed anyway. **4.** If you add fields dynamically like you want to, you need to change the datepicker JS function. And instead of loading the JS code inline (and multiple times like you did), I recommend enqueuing one JS file. So try to replace your JS code with something like this: ``` jQuery(document).ready(function($){ // your default code $( '#add-row' ).on('click', function() { var row = $( '.empty-row.screen-reader-text' ).clone(true); row.removeClass( 'empty-row screen-reader-text' ); row.insertBefore( '#repeatable-fieldset-one tbody>tr:last' ); return false; }); $( '.remove-row' ).on('click', function() { $(this).parents('tr').remove(); return false; }); //changed to be used on dynamic field which gets added and removed from DOM //if the element with the class .my-custom-datepicker-field gets focus, add datepicker $(document).on('focus', '.my-custom-datepicker-field', function(){ $(this).datepicker({ dateFormat: 'dd-mm-yy', //maybe you want something like this showButtonPanel: true }); }); }); ``` After I fixed these things and enqueued the JS file with the code like WordPress wants it to, it is now working.
272,526
<p>Can anybody tell me that how to check if someone created his site using wordpress?</p>
[ { "answer_id": 272527, "author": "Community", "author_id": -1, "author_profile": "https://wordpress.stackexchange.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>Yes Probably.<br>\nJust Type <code>wp-admin</code> at the end of your domain like following:</p>\n\n<pre><code>htt...
2017/07/06
[ "https://wordpress.stackexchange.com/questions/272526", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
Can anybody tell me that how to check if someone created his site using wordpress?
Yes Probably. Just Type `wp-admin` at the end of your domain like following: ``` http://example.com/wp-admin ```
272,552
<p>When a post is protected, its content looks like:</p> <pre><code>// This content is password protected. To view it please enter your password below: // Password: [_______________] [Enter] </code></pre> <p>How do I add a placeholder to that <code>&lt;input&gt;</code> tag?</p>
[ { "answer_id": 272553, "author": "dodov", "author_id": 122905, "author_profile": "https://wordpress.stackexchange.com/users/122905", "pm_score": 1, "selected": false, "text": "<p>This can be achieved via a hook, called <code>the_password_form</code>:</p>\n\n<pre><code>function my_theme_p...
2017/07/06
[ "https://wordpress.stackexchange.com/questions/272552", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122905/" ]
When a post is protected, its content looks like: ``` // This content is password protected. To view it please enter your password below: // Password: [_______________] [Enter] ``` How do I add a placeholder to that `<input>` tag?
This can be achieved via a hook, called `the_password_form`: ``` function my_theme_password_placeholder($output) { $placeholder = 'Hello!'; $search = 'type="password"'; return str_replace($search, $search . " placeholder=\"$placeholder\"", $output); } add_filter('the_password_form', 'my_theme_password_placeholder'); ``` A `str_replace` searches for the string `type="password"` inside the output. This gives an attribute to the `<input>` indicating it's of type `password`. The replacement string contains the searched one *plus* the `placeholder` attribute too.
272,573
<p>I am setting a header image as a background image to the <code>.blog__header</code> block via inline styles in functions.php:</p> <pre><code>$header_image = get_header_image(); if ( $header_image ) { $header_image_css = " .blog__header { background-image: url({$header_image}); }"; wp_add_inline_style( 'theme-styles', $header_image_css ); } </code></pre> <p>now I want to replace this header image with a featured image if set:</p> <pre><code>$header_image = get_header_image(); if ( has_post_thumbnail() ) { $post_thumbnail = get_the_post_thumbnail('full'); } if ( $header_image ) { $header_image_css = " .blog__header { background-image: url({$header_image}); }"; wp_add_inline_style( 'theme-styles', $header_image_css ); } elseif ( has_post_thumbnail() ) { $post_thumbnail_css = " .blog__header { background-image: url({$post_thumbnail}); }"; wp_add_inline_style( 'theme-styles', $post_thumbnail_css ); } </code></pre> <p>however it doesn't work, probaly because I have not set the post ID. Any assistance would be greatly appreciated!</p>
[ { "answer_id": 272603, "author": "Junaid", "author_id": 66571, "author_profile": "https://wordpress.stackexchange.com/users/66571", "pm_score": 3, "selected": true, "text": "<p>You did not mention or shown in the code to which hook are you hooking the above code to, but here's what I thi...
2017/07/06
[ "https://wordpress.stackexchange.com/questions/272573", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/103046/" ]
I am setting a header image as a background image to the `.blog__header` block via inline styles in functions.php: ``` $header_image = get_header_image(); if ( $header_image ) { $header_image_css = " .blog__header { background-image: url({$header_image}); }"; wp_add_inline_style( 'theme-styles', $header_image_css ); } ``` now I want to replace this header image with a featured image if set: ``` $header_image = get_header_image(); if ( has_post_thumbnail() ) { $post_thumbnail = get_the_post_thumbnail('full'); } if ( $header_image ) { $header_image_css = " .blog__header { background-image: url({$header_image}); }"; wp_add_inline_style( 'theme-styles', $header_image_css ); } elseif ( has_post_thumbnail() ) { $post_thumbnail_css = " .blog__header { background-image: url({$post_thumbnail}); }"; wp_add_inline_style( 'theme-styles', $post_thumbnail_css ); } ``` however it doesn't work, probaly because I have not set the post ID. Any assistance would be greatly appreciated!
You did not mention or shown in the code to which hook are you hooking the above code to, but here's what I think should work. NOT TESTED ``` global $post; $header_image = ''; // featured image is first priority, right? if ( has_post_thumbnail( $post->ID ) ) { $header_image = get_the_post_thumbnail_url( $post->ID, 'full' ); } elseif ( !empty( get_header_image() ) ) { $header_image = get_header_image(); } $header_image_css = ".blog__header { background-image: url({$header_image}); }"; wp_add_inline_style( 'theme-styles', $header_image_css ); ```
272,585
<p>I have a custom post type product (wine). Each of the following is a custom taxonomy:</p> <ul> <li>Vintage (Year of harvesting) [only one per wine]</li> <li>Family (Grape variety) [may be more than one]</li> <li>Size (Bottle Size) [only one per product]</li> </ul> <p>In the single product view of a wine I want to do the following queries: </p> <p>1) Find all wines which have the <strong>same family</strong>, <strong>same size</strong> but are from a <strong>different vintage</strong></p> <p>2) Find all wines (post type: product) which are in the <strong>same family</strong> AND have the <strong>same vintage</strong> AND have a <strong>different size</strong>.</p> <p>Now the problem: The <strong>numeric year</strong> is a custom term meta property of the <strong>vintage term</strong>. The <strong>numeric bottle size</strong> is a custom term meta property of the size term.</p> <p>For the first query I have tried the following:</p> <pre><code> $other_years = get_posts(array( 'post_type' =&gt; 'product', 'numberposts' =&gt; -1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'family', 'field' =&gt; 'id', 'terms' =&gt; $family-&gt;term_id, // Where term_id of Term 1 is "1". 'include_children' =&gt; false ), array( 'taxonomy' =&gt; 'size', 'field' =&gt; 'id', 'terms' =&gt; $size-&gt;term_id, // Where term_id of Term 1 is "1". 'include_children' =&gt; false ), array( 'taxonomy' =&gt; 'vintage', 'field' =&gt; 'id', 'terms' =&gt; array($vintage-&gt;term_id), // Where term_id of Term 1 is "1". 'include_children' =&gt; false, 'operator' =&gt; 'NOT IN' ), ) )); </code></pre> <p><strong>It works.</strong> However: Instead of comparing the <strong><em>term_id</em></strong> (here: term id of vintage) I would like to compare if the term custom meta value (year_numeric) is different.</p> <p>Is there any possibility to do such a query?</p>
[ { "answer_id": 272587, "author": "Nick M.", "author_id": 122778, "author_profile": "https://wordpress.stackexchange.com/users/122778", "pm_score": 0, "selected": false, "text": "<p>I believe you are checking for when a meta key does not exist. </p>\n\n<p>Please refer to this similar ques...
2017/07/06
[ "https://wordpress.stackexchange.com/questions/272585", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12035/" ]
I have a custom post type product (wine). Each of the following is a custom taxonomy: * Vintage (Year of harvesting) [only one per wine] * Family (Grape variety) [may be more than one] * Size (Bottle Size) [only one per product] In the single product view of a wine I want to do the following queries: 1) Find all wines which have the **same family**, **same size** but are from a **different vintage** 2) Find all wines (post type: product) which are in the **same family** AND have the **same vintage** AND have a **different size**. Now the problem: The **numeric year** is a custom term meta property of the **vintage term**. The **numeric bottle size** is a custom term meta property of the size term. For the first query I have tried the following: ``` $other_years = get_posts(array( 'post_type' => 'product', 'numberposts' => -1, 'tax_query' => array( array( 'taxonomy' => 'family', 'field' => 'id', 'terms' => $family->term_id, // Where term_id of Term 1 is "1". 'include_children' => false ), array( 'taxonomy' => 'size', 'field' => 'id', 'terms' => $size->term_id, // Where term_id of Term 1 is "1". 'include_children' => false ), array( 'taxonomy' => 'vintage', 'field' => 'id', 'terms' => array($vintage->term_id), // Where term_id of Term 1 is "1". 'include_children' => false, 'operator' => 'NOT IN' ), ) )); ``` **It works.** However: Instead of comparing the ***term\_id*** (here: term id of vintage) I would like to compare if the term custom meta value (year\_numeric) is different. Is there any possibility to do such a query?
AFAIK there's no way to achieve that within a single WP\_Query, so you'll have to first get a list of term\_ids which have a **different year** than the one in question. I think with the following you'll come quite close. (don't have a env to test right away) ``` $other_years_terms = get_terms( 'taxonomy' => 'vintage', 'meta_key' => 'year_numeric', 'meta_value' => $the_current_wine_year, // You'll have to figure that out 'meta_compare' => '!=', 'fields' => 'ids' ); $other_years_posts = get_posts(array( 'post_type' => 'product', 'numberposts' => -1, 'tax_query' => array( array( 'taxonomy' => 'family', 'field' => 'id', 'terms' => $family->term_id, // Where term_id of Term 1 is "1". 'include_children' => false ), array( 'taxonomy' => 'size', 'field' => 'id', 'terms' => $size->term_id, // Where term_id of Term 1 is "1". 'include_children' => false ), array( 'taxonomy' => 'vintage', 'field' => 'term_id', 'terms' => $other_years_terms, ), ) )); ```
272,613
<p>I'm trying to create a page on WordPress with a grid which contains al my posts. </p> <p>The grid works well until when I add the <code>the_excerpt();</code> for my post. The grid became a mess. The rows are not correct anymore. </p> <p>This is what I have without <code>the_excerpt();</code>:</p> <p><a href="https://i.stack.imgur.com/cGyA5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cGyA5.png" alt="enter image description here"></a></p> <p>and this is what happens with <code>the_excerpt();</code>:</p> <p><a href="https://i.stack.imgur.com/WxXGq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WxXGq.png" alt="enter image description here"></a></p> <p>Here my code of page-post.php:</p> <pre><code>&lt;?php /* Template Name: Blog-3 */ ?&gt; &lt;?php get_header(); ?&gt; &lt;div&gt; &lt;div class="container"&gt; &lt;?php query_posts('post_type=post&amp;post_status=publish&amp;posts_per_page=10&amp;paged='. get_query_var('paged')); ?&gt; &lt;div class="row"&gt; &lt;?php if( have_posts() ): ?&gt; &lt;?php while( have_posts() ): the_post(); ?&gt; &lt;div class="col-sm-6" style="margin-bottom: 65px;"&gt; &lt;p&gt; &lt;?php if ( has_post_thumbnail() ) : ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_post_thumbnail( 'large' ); ?&gt;&lt;/a&gt; &lt;?php endif; ?&gt; &lt;/p&gt; &lt;h3&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;p&gt;Posted on &lt;?php echo the_time('F jS, Y');?&gt; by &lt;?php the_author_posts_link(); ?&gt; &lt;/p&gt; &lt;?php the_excerpt(); ?&gt; &lt;/div&gt;&lt;!-- col --&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt;&lt;!-- row --&gt; &lt;/div&gt;&lt;!-- container --&gt; &lt;div&gt; &lt;span&gt;&lt;?php previous_posts_link(__('« Newer','example')) ?&gt;&lt;/span&gt; &lt;span class="older"&gt;&lt;?php next_posts_link(__('Older »','example')) ?&gt;&lt;/span&gt; &lt;/div&gt;&lt;!-- /.navigation --&gt; &lt;?php else: ?&gt; &lt;div id="post-404"&gt; &lt;p&gt;&lt;?php _e('None found.','example'); ?&gt;&lt;/p&gt; &lt;/div&gt;&lt;!-- /#post-404 --&gt; &lt;?php endif; wp_reset_query(); ?&gt; &lt;/div&gt;&lt;!-- /#content --&gt; &lt;?php get_sidebar(); get_footer();?&gt; </code></pre>
[ { "answer_id": 272615, "author": "Kieran McClung", "author_id": 52293, "author_profile": "https://wordpress.stackexchange.com/users/52293", "pm_score": 2, "selected": false, "text": "<p>The way I tackle this issue is by closing the row every <em>nth</em> column, like so. You basically co...
2017/07/07
[ "https://wordpress.stackexchange.com/questions/272613", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107597/" ]
I'm trying to create a page on WordPress with a grid which contains al my posts. The grid works well until when I add the `the_excerpt();` for my post. The grid became a mess. The rows are not correct anymore. This is what I have without `the_excerpt();`: [![enter image description here](https://i.stack.imgur.com/cGyA5.png)](https://i.stack.imgur.com/cGyA5.png) and this is what happens with `the_excerpt();`: [![enter image description here](https://i.stack.imgur.com/WxXGq.png)](https://i.stack.imgur.com/WxXGq.png) Here my code of page-post.php: ``` <?php /* Template Name: Blog-3 */ ?> <?php get_header(); ?> <div> <div class="container"> <?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?> <div class="row"> <?php if( have_posts() ): ?> <?php while( have_posts() ): the_post(); ?> <div class="col-sm-6" style="margin-bottom: 65px;"> <p> <?php if ( has_post_thumbnail() ) : ?> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'large' ); ?></a> <?php endif; ?> </p> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <p>Posted on <?php echo the_time('F jS, Y');?> by <?php the_author_posts_link(); ?> </p> <?php the_excerpt(); ?> </div><!-- col --> <?php endwhile; ?> </div><!-- row --> </div><!-- container --> <div> <span><?php previous_posts_link(__('« Newer','example')) ?></span> <span class="older"><?php next_posts_link(__('Older »','example')) ?></span> </div><!-- /.navigation --> <?php else: ?> <div id="post-404"> <p><?php _e('None found.','example'); ?></p> </div><!-- /#post-404 --> <?php endif; wp_reset_query(); ?> </div><!-- /#content --> <?php get_sidebar(); get_footer();?> ```
The way I tackle this issue is by closing the row every *nth* column, like so. You basically collect the total number of posts in the current loop then at the end of each loop, increment `$i` and check whether it's divisible by two wholly (I'm rubbish at explaining this part). Example: You could tweak this to `if ( $i % 3 == 0 )` if you were wanting rows of 3. The example below can replace your entire container. ``` <div class="container"> <?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?> <?php // Get total posts $total = $wp_query->post_count; // Set indicator to 0; $i = 0; ?> <?php while( have_posts() ): the_post(); ?> <?php if ( $i == 0 ) echo '<div class="row">'; ?> <div class="col-sm-6" style="margin-bottom: 65px;"> <p> <?php if ( has_post_thumbnail() ) : ?> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'large' ); ?></a> <?php endif; ?> </p> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <p>Posted on <?php echo the_time('F jS, Y');?> by <?php the_author_posts_link(); ?> </p> <?php the_excerpt(); ?> </div><!-- col --> <?php $i++; ?> <?php // if we're at the end close the row if ( $i == $total ) { echo '</div>'; } else { /** * Perform modulus calculation to check whether $i / 2 is whole number * if true close row and open a new one */ if ( $i % 2 == 0 ) { echo '</div><div class="row">'; } } ?> <?php endwhile; ?> </div><!-- container --> ```
272,619
<p>I'm trying to get a list/count of products who's has a specific attribute and value. Products are managed and setup using the WooCommerce plugin.</p> <p>Each product has the same variation set, the product is assigned to a category, I need to retrieve only product with a specific attribute i.e "newyork" and the stock quantity that is less than i.e "20"</p> <p>Each product variation is set to Managed stock, but not the product itself hope that makes sense. My issue at the moment is the WordPress query I have is not checking the variation name or stock at all. </p> <p>Any help would be appreciated. </p> <pre><code>&lt;?php $args= array( 'post_type' =&gt; array('product', 'product_variation'), 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'meta_query' =&gt; array( array( 'key' =&gt; '_stock', 'value' =&gt; 20, 'compare' =&gt; '&lt;' ) ), 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'product_cat', 'field' =&gt; 'slug', 'terms' =&gt; array('cat1', 'cat2', 'cat3'), 'operator' =&gt; 'IN', ), array( 'taxonomy' =&gt; 'pa_regions', 'field' =&gt; 'slug', 'terms' =&gt; 'newyork', 'operator' =&gt; 'IN' ), ) ); $loop = new WP_Query($args); $post_count = array(); while($loop-&gt;have_posts()) : $loop-&gt;the_post(); global $product; ?&gt; &lt;pre style="background: #1c1c1b; color: #f7e700"&gt; &lt;?php $post_count[] = $product-&gt;ID ;?&gt; &lt;/pre&gt; &lt;?php endwhile; ?&gt; $total = count($post_count); </code></pre>
[ { "answer_id": 291998, "author": "Minh Dao", "author_id": 135439, "author_profile": "https://wordpress.stackexchange.com/users/135439", "pm_score": -1, "selected": false, "text": "<p>I think you has a proble on 'tax_query'.\nIf you want you query array on 'tax_query', you need flown on f...
2017/07/07
[ "https://wordpress.stackexchange.com/questions/272619", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120173/" ]
I'm trying to get a list/count of products who's has a specific attribute and value. Products are managed and setup using the WooCommerce plugin. Each product has the same variation set, the product is assigned to a category, I need to retrieve only product with a specific attribute i.e "newyork" and the stock quantity that is less than i.e "20" Each product variation is set to Managed stock, but not the product itself hope that makes sense. My issue at the moment is the WordPress query I have is not checking the variation name or stock at all. Any help would be appreciated. ``` <?php $args= array( 'post_type' => array('product', 'product_variation'), 'post_status' => 'publish', 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => '_stock', 'value' => 20, 'compare' => '<' ) ), 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => array('cat1', 'cat2', 'cat3'), 'operator' => 'IN', ), array( 'taxonomy' => 'pa_regions', 'field' => 'slug', 'terms' => 'newyork', 'operator' => 'IN' ), ) ); $loop = new WP_Query($args); $post_count = array(); while($loop->have_posts()) : $loop->the_post(); global $product; ?> <pre style="background: #1c1c1b; color: #f7e700"> <?php $post_count[] = $product->ID ;?> </pre> <?php endwhile; ?> $total = count($post_count); ```
You should use [wc\_get\_products and a custom filter](https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support) for adding your specific query. **Example** I want to find products containing a specific attribute value "table-filter". ``` $args = array( 'table-filter' => array(1,2,3) ); $products = wc_get_products($args); ``` Than I have a filter for this: ``` add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2); function my_handle_custom_query_var($query, $query_vars) { if (!empty($query_vars['table-filter'])) { $query['tax_query'][] = array( 'taxonomy' => 'pa_table-filter', 'field' => 'term_id', //default 'terms' => $query_vars['table-filter'], 'operator' => 'IN', ); } return $query; } ``` **Hint:** The generated attribute taxonomy from WooCommerce is always prefixed with "pa\_", so if you attributes slug is "table-filter", the taxonomy will be "pa\_table-filter".
272,620
<p>I want disable one specific page of the default css, and i want use my css on the specific page. I don't know it is posibble?</p> <p>I use Blank State plugin, for create blank page, but css its on the blank pages, but i want my css use on the specific blank pages.</p> <p><a href="https://wordpress.org/plugins/blank-slate/" rel="nofollow noreferrer">https://wordpress.org/plugins/blank-slate/</a></p> <p>So, i have one page, that name: test-area-7 Code:</p> <pre><code>add_action('wp_enqueue_scripts', 'my_script', 99); function my_script() { if(is_page( 'test-area-7' )){ wp_dequeue_script('fpw_styles_css'); } } </code></pre> <p>EDITED</p> <pre><code> add_action('wp_enqueue_scripts', 'my_script', 99); function my_script() { if(is_page( 'test-area-7' )){ wp_dequeue_script('/wp-content/themes/colormag/style.css'); } } </code></pre>
[ { "answer_id": 291998, "author": "Minh Dao", "author_id": 135439, "author_profile": "https://wordpress.stackexchange.com/users/135439", "pm_score": -1, "selected": false, "text": "<p>I think you has a proble on 'tax_query'.\nIf you want you query array on 'tax_query', you need flown on f...
2017/07/07
[ "https://wordpress.stackexchange.com/questions/272620", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123365/" ]
I want disable one specific page of the default css, and i want use my css on the specific page. I don't know it is posibble? I use Blank State plugin, for create blank page, but css its on the blank pages, but i want my css use on the specific blank pages. <https://wordpress.org/plugins/blank-slate/> So, i have one page, that name: test-area-7 Code: ``` add_action('wp_enqueue_scripts', 'my_script', 99); function my_script() { if(is_page( 'test-area-7' )){ wp_dequeue_script('fpw_styles_css'); } } ``` EDITED ``` add_action('wp_enqueue_scripts', 'my_script', 99); function my_script() { if(is_page( 'test-area-7' )){ wp_dequeue_script('/wp-content/themes/colormag/style.css'); } } ```
You should use [wc\_get\_products and a custom filter](https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support) for adding your specific query. **Example** I want to find products containing a specific attribute value "table-filter". ``` $args = array( 'table-filter' => array(1,2,3) ); $products = wc_get_products($args); ``` Than I have a filter for this: ``` add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2); function my_handle_custom_query_var($query, $query_vars) { if (!empty($query_vars['table-filter'])) { $query['tax_query'][] = array( 'taxonomy' => 'pa_table-filter', 'field' => 'term_id', //default 'terms' => $query_vars['table-filter'], 'operator' => 'IN', ); } return $query; } ``` **Hint:** The generated attribute taxonomy from WooCommerce is always prefixed with "pa\_", so if you attributes slug is "table-filter", the taxonomy will be "pa\_table-filter".
272,659
<p>I am trying to write a simple plugin that fetches some data from an API endpoint. I am planning to read the api key from a shortcode, but didn't get that far yet.</p> <p>I wrote the following piece of code. The noob question I have is how do I even trigger the code so that I could debug it to see what happens ?</p> <p>If that's a simple question, the follow up would be how to read the api key from a shortcode? </p> <pre><code>class DATA_PARSING { private static $instance; /** * Initializes the plugin and read some data * * @access private */ private function __construct() { add_action('data', [$this, 'fetchData']); } /** * Creates an instance of this class * * @access public * @return DATA_PARSING An instance of this class */ public function get_instance() { if (null == self::$instance) { self::$instance = new self; } return self::$instance; } private function fetchData($apiKey) { $url = 'https://api.website.com/data'; $args = [ 'id' =&gt; 1234, 'fields' =&gt; '*' ]; $method = 'GET'; $headers = array( 'Authorization' =&gt; 'Bearer ' . $apiKey, 'Accept' =&gt; 'application/vnd.website.v1+json', 'content-type' =&gt; 'application/json', ); $request = array( 'headers' =&gt; $headers, 'method' =&gt; $method, ); if ($method == 'GET' &amp;&amp; !empty($args) &amp;&amp; is_array($args)) { $url = add_query_arg($args, $url); } else { $request['body'] = json_encode($args); } $response = wp_remote_request($url, $request); try { $json = json_decode($response['body']); } catch (Exception $e) { $json = null; } return $json; } } </code></pre>
[ { "answer_id": 291998, "author": "Minh Dao", "author_id": 135439, "author_profile": "https://wordpress.stackexchange.com/users/135439", "pm_score": -1, "selected": false, "text": "<p>I think you has a proble on 'tax_query'.\nIf you want you query array on 'tax_query', you need flown on f...
2017/07/07
[ "https://wordpress.stackexchange.com/questions/272659", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123390/" ]
I am trying to write a simple plugin that fetches some data from an API endpoint. I am planning to read the api key from a shortcode, but didn't get that far yet. I wrote the following piece of code. The noob question I have is how do I even trigger the code so that I could debug it to see what happens ? If that's a simple question, the follow up would be how to read the api key from a shortcode? ``` class DATA_PARSING { private static $instance; /** * Initializes the plugin and read some data * * @access private */ private function __construct() { add_action('data', [$this, 'fetchData']); } /** * Creates an instance of this class * * @access public * @return DATA_PARSING An instance of this class */ public function get_instance() { if (null == self::$instance) { self::$instance = new self; } return self::$instance; } private function fetchData($apiKey) { $url = 'https://api.website.com/data'; $args = [ 'id' => 1234, 'fields' => '*' ]; $method = 'GET'; $headers = array( 'Authorization' => 'Bearer ' . $apiKey, 'Accept' => 'application/vnd.website.v1+json', 'content-type' => 'application/json', ); $request = array( 'headers' => $headers, 'method' => $method, ); if ($method == 'GET' && !empty($args) && is_array($args)) { $url = add_query_arg($args, $url); } else { $request['body'] = json_encode($args); } $response = wp_remote_request($url, $request); try { $json = json_decode($response['body']); } catch (Exception $e) { $json = null; } return $json; } } ```
You should use [wc\_get\_products and a custom filter](https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support) for adding your specific query. **Example** I want to find products containing a specific attribute value "table-filter". ``` $args = array( 'table-filter' => array(1,2,3) ); $products = wc_get_products($args); ``` Than I have a filter for this: ``` add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2); function my_handle_custom_query_var($query, $query_vars) { if (!empty($query_vars['table-filter'])) { $query['tax_query'][] = array( 'taxonomy' => 'pa_table-filter', 'field' => 'term_id', //default 'terms' => $query_vars['table-filter'], 'operator' => 'IN', ); } return $query; } ``` **Hint:** The generated attribute taxonomy from WooCommerce is always prefixed with "pa\_", so if you attributes slug is "table-filter", the taxonomy will be "pa\_table-filter".
272,675
<p>I am working on a WordPress theme offline in localhost It's a blog theme: <a href="http://preview.themeforest.net/item/paperback-magazine-wordpress-theme/full_screen_preview/13511026" rel="nofollow noreferrer">http://preview.themeforest.net/item/paperback-magazine-wordpress-theme/full_screen_preview/13511026</a> . I need to create a profile header in such a way that these writers would be able to put in their bio, a background picture, profile picture and links to their social networks. Something similar to this:</p> <p><a href="http://thoughtcatalog.com/rania-naim/" rel="nofollow noreferrer">http://thoughtcatalog.com/rania-naim/</a> </p> <p>I am just starting out theme development and don't know my way around this. Will be grateful for any help. Thanks</p>
[ { "answer_id": 291998, "author": "Minh Dao", "author_id": 135439, "author_profile": "https://wordpress.stackexchange.com/users/135439", "pm_score": -1, "selected": false, "text": "<p>I think you has a proble on 'tax_query'.\nIf you want you query array on 'tax_query', you need flown on f...
2017/07/07
[ "https://wordpress.stackexchange.com/questions/272675", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119981/" ]
I am working on a WordPress theme offline in localhost It's a blog theme: <http://preview.themeforest.net/item/paperback-magazine-wordpress-theme/full_screen_preview/13511026> . I need to create a profile header in such a way that these writers would be able to put in their bio, a background picture, profile picture and links to their social networks. Something similar to this: <http://thoughtcatalog.com/rania-naim/> I am just starting out theme development and don't know my way around this. Will be grateful for any help. Thanks
You should use [wc\_get\_products and a custom filter](https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#adding-custom-parameter-support) for adding your specific query. **Example** I want to find products containing a specific attribute value "table-filter". ``` $args = array( 'table-filter' => array(1,2,3) ); $products = wc_get_products($args); ``` Than I have a filter for this: ``` add_filter('woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2); function my_handle_custom_query_var($query, $query_vars) { if (!empty($query_vars['table-filter'])) { $query['tax_query'][] = array( 'taxonomy' => 'pa_table-filter', 'field' => 'term_id', //default 'terms' => $query_vars['table-filter'], 'operator' => 'IN', ); } return $query; } ``` **Hint:** The generated attribute taxonomy from WooCommerce is always prefixed with "pa\_", so if you attributes slug is "table-filter", the taxonomy will be "pa\_table-filter".
272,682
<p>A client is using the WordPress REST JSON API with some WordPress data models. We need to hit the WordPress API from the frontend and retreive a few hundred custom posts.</p> <p>Wordpress has a <a href="https://developer.wordpress.org/reference/classes/wp_rest_controller/get_collection_params/" rel="nofollow noreferrer">hard limit of 100 custom posts</a>.</p> <p>I would like to change this limit to a much higher number for this use case. I read that you cannot monkey patch in PHP. </p> <p>Is there any way to adjust the <code>per_page-&gt;maximum</code> value to, say, 10000?</p>
[ { "answer_id": 272724, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 1, "selected": false, "text": "<p>You cannot get over that limit of 100 posts per requests in WordPress for default requests. One way to still r...
2017/07/07
[ "https://wordpress.stackexchange.com/questions/272682", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/52128/" ]
A client is using the WordPress REST JSON API with some WordPress data models. We need to hit the WordPress API from the frontend and retreive a few hundred custom posts. Wordpress has a [hard limit of 100 custom posts](https://developer.wordpress.org/reference/classes/wp_rest_controller/get_collection_params/). I would like to change this limit to a much higher number for this use case. I read that you cannot monkey patch in PHP. Is there any way to adjust the `per_page->maximum` value to, say, 10000?
You cannot get over that limit of 100 posts per requests in WordPress for default requests. One way to still retrieve all posts would be to query that interface until you have all posts. Another would be a custom endpoint. If you can, I suggest creating your own REST endpoint. This will already work and return all posts ``` add_action('rest_api_init', 'my_more_posts'); function my_more_posts() { register_rest_route('myplugin/v1', '/myposts', array( 'methods' => 'GET', 'callback' => 'my_more_posts_callback', )); } function my_more_posts_callback( WP_REST_Request $request ) { $args = array( 'posts_per_page' => -1, ); return get_posts($args); } ``` More info on [creating your own endpoint can be found here](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/), whereas the [arguments of `get_posts()` are explained here](https://codex.wordpress.org/Template_Tags/get_posts). --- For a pure JavaScript solution in the frontend, you can utilize the `x-wp-totalpages` header which tells the total amount of pages. Unless this page is reached, we know we need to query again. So a basic recursive version like this works: ``` var allPosts = []; function retrievePosts(opt) { if (typeof opt === 'undefined') opt = {}; var options = $.extend({ per_page: 100, page: 1 }, opt); var url = 'https://example.com/wp-json/wp/v2/posts'; var uri = url + '?per_page=' + options.per_page + '&page=' + options.page; $.getJSON(uri, function(data, status, jqXHR) { var totalpages = jqXHR.getResponseHeader('x-wp-totalpages'); allPosts = allPosts.concat( data ); // here the magic happens // if we are not done if (options.page < totalpages) { // request again, but for the next page retrievePosts({ per_page: options.per_page, page: options.page + 1 }); } else { // WE ARE DONE // posts are in allPosts } }); }; retrievePosts(); ```
272,717
<p>I am newbie in wordpress but not very new.</p> <p>When I came to know that wordpress have inbuilt shortcodes like audio, video, gallery, playlist.</p> <p>I have searched for a list of inbuilt shortcodes that WordPress provides but I did not get anything except above can anybody provide me a link which has a list of inbuilt wp shortcodes.</p> <p>And</p> <p>one more thing if WordPress provide more inbuilt shortcodes are they only work in wordpress.com</p> <p>I know that you guys may thing I am a fool or idiot but I want to know.</p>
[ { "answer_id": 272721, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p...
2017/07/08
[ "https://wordpress.stackexchange.com/questions/272717", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123366/" ]
I am newbie in wordpress but not very new. When I came to know that wordpress have inbuilt shortcodes like audio, video, gallery, playlist. I have searched for a list of inbuilt shortcodes that WordPress provides but I did not get anything except above can anybody provide me a link which has a list of inbuilt wp shortcodes. And one more thing if WordPress provide more inbuilt shortcodes are they only work in wordpress.com I know that you guys may thing I am a fool or idiot but I want to know.
You can actually list all of the available shortcodes for your WordPress installation by using the following code: ``` <?php global $shortcode_tags; echo '<pre>'; print_r($shortcode_tags); echo '</pre>'; ?> ``` It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!
272,760
<p>I have done some weird things with a few custom theme pages. Namely, i have bypassed the wp_query and obtained data from a different db. I populate the post object with custom data and then inject this into my theme. Since the toolbar shows up fine normally, there must be some sort of trigger that i am bypassing by not calling the wordpress DB. I am 100% sure the theme is not the cause of the issue here, it is the messing that i have done. However, there are no errors in the code, everything works good. What does the admin toolbar require in order to load? Is there some hook i can call manually in order to make it render?</p> <p>I have tried messing around with the code and info from the wordpress docs <a href="https://codex.wordpress.org/Function_Reference/show_admin_bar" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/show_admin_bar</a></p>
[ { "answer_id": 272721, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p...
2017/07/09
[ "https://wordpress.stackexchange.com/questions/272760", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/190834/" ]
I have done some weird things with a few custom theme pages. Namely, i have bypassed the wp\_query and obtained data from a different db. I populate the post object with custom data and then inject this into my theme. Since the toolbar shows up fine normally, there must be some sort of trigger that i am bypassing by not calling the wordpress DB. I am 100% sure the theme is not the cause of the issue here, it is the messing that i have done. However, there are no errors in the code, everything works good. What does the admin toolbar require in order to load? Is there some hook i can call manually in order to make it render? I have tried messing around with the code and info from the wordpress docs <https://codex.wordpress.org/Function_Reference/show_admin_bar>
You can actually list all of the available shortcodes for your WordPress installation by using the following code: ``` <?php global $shortcode_tags; echo '<pre>'; print_r($shortcode_tags); echo '</pre>'; ?> ``` It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!
272,772
<p>I have a WP installation with 6 categories and I want 3 of them to use a custom Category Archive Page called "category-special.php" (default page is the "category.php"). I found the code below that looks to be close to my query, how can I modify and make it work for me, so categories 31,40 and 55 to load the above specific page?</p> <pre><code>add_filter( 'template_include', 'wpsites_photo_page_template', 99 ); function wpsites_photo_page_template( $template ) { if ( is_category('33') ) { $new_template = locate_template( array( 'photo.php' ) ); if ( '' != $new_template ) { return $new_template ; } } return $template; } </code></pre> <p>Thank you.</p>
[ { "answer_id": 272721, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p...
2017/07/09
[ "https://wordpress.stackexchange.com/questions/272772", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117746/" ]
I have a WP installation with 6 categories and I want 3 of them to use a custom Category Archive Page called "category-special.php" (default page is the "category.php"). I found the code below that looks to be close to my query, how can I modify and make it work for me, so categories 31,40 and 55 to load the above specific page? ``` add_filter( 'template_include', 'wpsites_photo_page_template', 99 ); function wpsites_photo_page_template( $template ) { if ( is_category('33') ) { $new_template = locate_template( array( 'photo.php' ) ); if ( '' != $new_template ) { return $new_template ; } } return $template; } ``` Thank you.
You can actually list all of the available shortcodes for your WordPress installation by using the following code: ``` <?php global $shortcode_tags; echo '<pre>'; print_r($shortcode_tags); echo '</pre>'; ?> ``` It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!
272,787
<p>The permalink structure has changed with old entries as well as any new entry (post, object, etc) from THEN to NOW </p> <p>THEN: </p> <blockquote> <p>constructstudies.com/(page slug or object label)</p> </blockquote> <p>NOW: </p> <blockquote> <p>constructstudies.com/disability-application/disability-benefits-application/disability-application/(page slug or object label)</p> </blockquote> <p>The redundant parent labels cannot be altered under permalinks settings, nor with the 4 custom permalink plugins I have tried. The structure is embedded deeper than these settings allow. </p> <p>It should be noted that in attempts to better my link structure, I have created and subsequently deleted 3 versions of similar parent pages with no more than one present at any given time. Two were labeled disability application and the other disability benefits application. </p> <p>Why have these old titles carried over into the permanent URL structure and how can I fix this? Ive deleted revisions with WP optimize, gone into <code>myphpadmin</code> and deleted old like entries from the <code>wp_febe_posts</code> table, cleared all cache, tried to delete and recreate pages, alter the <code>.htaccess</code> file to reflect a single-label permalink structure, and searched endlessly on forums and google. </p> <p>I'm uncertain whether deleting the old parent page entries and revisions in <code>wp_febe_posts</code> table via <code>myphpadmin</code> is the same as doing so in WP_pages via FTP, as I have searched endlessly for this to no avail so I cannot confirm. </p> <p>My strongest suspicion is something awry in my <code>.htaccess</code> file, as I have made several changes to it over the past couple of weeks and have limited knowledge of the changes beyond what was explained in the articles which accompanied respective modules i copy pasted. </p> <p>Below is the contents of <code>.htaccess files.</code> This file in the root directory is identical to the entry within my <code>public_html--&gt;constructstudies</code> directory</p> <p>-Please help me remedy this befuddlement and get me back to work. Thank you.-</p> <p><strong>EDIT</strong>:I returned to my site to find a fourth /disability-application appended to the permalink structure. As suggested on worpress.org forums, i have deleted my htaccess file as it was indicated there were redundancies within it. Also, I read that my results could be produced by a command but i have no recollection of this nor is it found in any of the basic editor phps within dashboard. just thought it may be worth noting.</p> <p>.htaccess: (any general suggestions welcomed as well)</p> <pre><code> &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteRule ^sitemap(-+([a-zA-Z0-9_-]+))?\.xml(\.gz)?$ /public_html/constructstudies/sitemap$1.xml$2 [L] &lt;/IfModule&gt; # BEGIN W3TC CDN &lt;FilesMatch "\.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|webp|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|_ttf|wav|wma|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|WEBP|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|_OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|_TTF|WAV|WMA|WRI|WOFF|WOFF2|XLA|XLS|XLSX|XLT|XLW|ZIP)$"&gt; &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule .* - [E=CANONICAL:http://www.constructstudies.com%{REQUEST_URI},NE] RewriteCond %{HTTPS} =on RewriteRule .* - [E=CANONICAL:https://www.constructstudies.com%{REQUEST_URI},NE] &lt;/IfModule&gt; &lt;IfModule mod_headers.c&gt; Header set Link "&lt;%{CANONICAL}e&gt;; rel=\"canonical\"" &lt;/IfModule&gt; &lt;/FilesMatch&gt; &lt;FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css)$"&gt; &lt;IfModule mod_headers.c&gt; Header set Access-Control-Allow-Origin "*" &lt;/IfModule&gt; &lt;/FilesMatch&gt; # END W3TC CDN # BEGIN WordPress AddHandler application/x-httpd-php70s .php &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /disability-application RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /disability-application/index.php [L] &lt;/IfModule&gt; # END WordPress AddHandler application/x-httpd-php70s .php &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 # Wordfence WAF &lt;Files ".user.ini"&gt; &lt;IfModule mod_authz_core.c&gt; Require all denied &lt;/IfModule&gt; &lt;IfModule !mod_authz_core.c&gt; Order deny,allow Deny from all &lt;/IfModule&gt; &lt;/Files&gt; # END Wordfence WAF </code></pre>
[ { "answer_id": 272721, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p...
2017/07/09
[ "https://wordpress.stackexchange.com/questions/272787", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123480/" ]
The permalink structure has changed with old entries as well as any new entry (post, object, etc) from THEN to NOW THEN: > > constructstudies.com/(page slug or object label) > > > NOW: > > constructstudies.com/disability-application/disability-benefits-application/disability-application/(page > slug or object label) > > > The redundant parent labels cannot be altered under permalinks settings, nor with the 4 custom permalink plugins I have tried. The structure is embedded deeper than these settings allow. It should be noted that in attempts to better my link structure, I have created and subsequently deleted 3 versions of similar parent pages with no more than one present at any given time. Two were labeled disability application and the other disability benefits application. Why have these old titles carried over into the permanent URL structure and how can I fix this? Ive deleted revisions with WP optimize, gone into `myphpadmin` and deleted old like entries from the `wp_febe_posts` table, cleared all cache, tried to delete and recreate pages, alter the `.htaccess` file to reflect a single-label permalink structure, and searched endlessly on forums and google. I'm uncertain whether deleting the old parent page entries and revisions in `wp_febe_posts` table via `myphpadmin` is the same as doing so in WP\_pages via FTP, as I have searched endlessly for this to no avail so I cannot confirm. My strongest suspicion is something awry in my `.htaccess` file, as I have made several changes to it over the past couple of weeks and have limited knowledge of the changes beyond what was explained in the articles which accompanied respective modules i copy pasted. Below is the contents of `.htaccess files.` This file in the root directory is identical to the entry within my `public_html-->constructstudies` directory -Please help me remedy this befuddlement and get me back to work. Thank you.- **EDIT**:I returned to my site to find a fourth /disability-application appended to the permalink structure. As suggested on worpress.org forums, i have deleted my htaccess file as it was indicated there were redundancies within it. Also, I read that my results could be produced by a command but i have no recollection of this nor is it found in any of the basic editor phps within dashboard. just thought it may be worth noting. .htaccess: (any general suggestions welcomed as well) ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^sitemap(-+([a-zA-Z0-9_-]+))?\.xml(\.gz)?$ /public_html/constructstudies/sitemap$1.xml$2 [L] </IfModule> # BEGIN W3TC CDN <FilesMatch "\.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|webp|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|_otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|_ttf|wav|wma|wri|woff|woff2|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|WEBP|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|_OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|_TTF|WAV|WMA|WRI|WOFF|WOFF2|XLA|XLS|XLSX|XLT|XLW|ZIP)$"> <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule .* - [E=CANONICAL:http://www.constructstudies.com%{REQUEST_URI},NE] RewriteCond %{HTTPS} =on RewriteRule .* - [E=CANONICAL:https://www.constructstudies.com%{REQUEST_URI},NE] </IfModule> <IfModule mod_headers.c> Header set Link "<%{CANONICAL}e>; rel=\"canonical\"" </IfModule> </FilesMatch> <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css)$"> <IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule> </FilesMatch> # END W3TC CDN # BEGIN WordPress AddHandler application/x-httpd-php70s .php <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /disability-application RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /disability-application/index.php [L] </IfModule> # END WordPress AddHandler application/x-httpd-php70s .php <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 # Wordfence WAF <Files ".user.ini"> <IfModule mod_authz_core.c> Require all denied </IfModule> <IfModule !mod_authz_core.c> Order deny,allow Deny from all </IfModule> </Files> # END Wordfence WAF ```
You can actually list all of the available shortcodes for your WordPress installation by using the following code: ``` <?php global $shortcode_tags; echo '<pre>'; print_r($shortcode_tags); echo '</pre>'; ?> ``` It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!
272,797
<p>I have Wordpress menus that is seems are put together in the backend somehow. I used <a href="https://developer.wordpress.org/reference/functions/wp_nav_menu/" rel="nofollow noreferrer">wp_nav_menu()</a> to customize the wrap of the menu items slightly.</p> <p>My issue is I have found no direct access to access the menu items, and add a custom field to them. They are all categories, and I want a specific icon for each category. </p> <p>This is my code in the functions.php to customize the menu:</p> <pre><code>function custom_novice_menu($args) { $args['container'] = false; $args['container_id'] = 'my_primary_menu'; $args['link_before'] = '&lt;div class="topic-card"&gt;&lt;div class="topic-circle"&gt;&lt;/div&gt;&lt;h3&gt;'; $args['link_after'] = '&lt;/h3&gt;&lt;/div&gt;'; return $args; } </code></pre> <p>Does anyone know a way I could add a unique icon to each menu item?</p>
[ { "answer_id": 272721, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p...
2017/07/09
[ "https://wordpress.stackexchange.com/questions/272797", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123346/" ]
I have Wordpress menus that is seems are put together in the backend somehow. I used [wp\_nav\_menu()](https://developer.wordpress.org/reference/functions/wp_nav_menu/) to customize the wrap of the menu items slightly. My issue is I have found no direct access to access the menu items, and add a custom field to them. They are all categories, and I want a specific icon for each category. This is my code in the functions.php to customize the menu: ``` function custom_novice_menu($args) { $args['container'] = false; $args['container_id'] = 'my_primary_menu'; $args['link_before'] = '<div class="topic-card"><div class="topic-circle"></div><h3>'; $args['link_after'] = '</h3></div>'; return $args; } ``` Does anyone know a way I could add a unique icon to each menu item?
You can actually list all of the available shortcodes for your WordPress installation by using the following code: ``` <?php global $shortcode_tags; echo '<pre>'; print_r($shortcode_tags); echo '</pre>'; ?> ``` It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!
272,801
<p>I come from a Laravel background which means I am used to using database migrations and seedings to keep content on dev / staging sites in sync with my local environment.</p> <p>I'm starting my first project in WordPress and was wondering how to go about doing the same. Essentially I'm building the site on my local environment and through the use of plugins such as Advanced Custom Fields I will create the content for the site. I need an easy was of ensuring the dev / staging sites have the same content as my local environment. I only want to sync content such as posts, pages, custom post types, and any associated media.</p> <p>Deployment of code itself is not an issue as the code is kept under version control and I can create a webhook to auto deploy the code.</p> <p>I have read up on plugins such as <a href="https://en-gb.wordpress.org/plugins/wp-migrate-db/" rel="nofollow noreferrer">WP Migrate DB</a> but I'm not sure this is the tool for the job.</p> <p>Can anyone advise the best way to accomplish this?</p>
[ { "answer_id": 272721, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": false, "text": "<p>You got almost all of them:</p>\n\n<pre><code>caption\ngallery\naudio\nvideo\nplaylist\nembed\n</code></pre>\n\n<p...
2017/07/09
[ "https://wordpress.stackexchange.com/questions/272801", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62933/" ]
I come from a Laravel background which means I am used to using database migrations and seedings to keep content on dev / staging sites in sync with my local environment. I'm starting my first project in WordPress and was wondering how to go about doing the same. Essentially I'm building the site on my local environment and through the use of plugins such as Advanced Custom Fields I will create the content for the site. I need an easy was of ensuring the dev / staging sites have the same content as my local environment. I only want to sync content such as posts, pages, custom post types, and any associated media. Deployment of code itself is not an issue as the code is kept under version control and I can create a webhook to auto deploy the code. I have read up on plugins such as [WP Migrate DB](https://en-gb.wordpress.org/plugins/wp-migrate-db/) but I'm not sure this is the tool for the job. Can anyone advise the best way to accomplish this?
You can actually list all of the available shortcodes for your WordPress installation by using the following code: ``` <?php global $shortcode_tags; echo '<pre>'; print_r($shortcode_tags); echo '</pre>'; ?> ``` It will show the main WordPress shortcodes plus any shortcodes for installed plugins which can be handy too!
272,844
<p>I am clicking on the link define in the anchor tag and fetching the url. I want to pass this url in url_to_postid($_POST['url']) which returns me ID.</p> <p>What I have done till far now is everything working except the ajax call on admin-ajax to pass url to fetch ID</p> <p>Step 1 : Created a widget in widget() function</p> <p>Step 2 : Calling get_prev_ajax_handler() function on click and want to get the post ID of that link using url_to_postid($_POST['url']); </p> <pre><code> function Reco_load_widget() { register_widget( 'Reco_Person' ); } add_action( 'widgets_init', 'Reco_load_widget' ); class Reco_Person extends WP_Widget { function __construct() { parent::__construct( 'wpb_widget_per', __('Reco Personalisation','wpb_widget_per_person'), array( 'description' =&gt; __( 'Content widget', 'wpb_widget_per_person' ), ) ); } public function widget( $args, $instance ) { ?&gt; &lt;script&gt; jQuery(function(){ jQuery('a').click(function(){ var url = jQuery(this).attr('href'); jQuery.ajax({ url: '&lt;?php echo admin_url('admin-ajax.php'); ?&gt;', method: "POST", contentType: 'application/json', data: ({ action: "get_prev_ajax_handler", url: url }), success: function (response){ console.log(response); } }); }); }); &lt;/script&gt; &lt;?php } public function get_prev_ajax_handler() { return url_to_postid($_POST["url"]); } } add_action('wp_ajax_get_prev', 'get_prev_ajax_handler'); // add action for logged users add_action( 'wp_ajax_nopriv_get_prev', 'get_prev_ajax_handler' ); </code></pre> <p>But this hook is not working. Did I invoke add_action at wrong place with wrong parameter? </p>
[ { "answer_id": 272883, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 0, "selected": false, "text": "<p>Your <code>action</code> in JQuery and and hook action is not matching.\nIt should be:</p>\n\n<pre...
2017/07/10
[ "https://wordpress.stackexchange.com/questions/272844", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123508/" ]
I am clicking on the link define in the anchor tag and fetching the url. I want to pass this url in url\_to\_postid($\_POST['url']) which returns me ID. What I have done till far now is everything working except the ajax call on admin-ajax to pass url to fetch ID Step 1 : Created a widget in widget() function Step 2 : Calling get\_prev\_ajax\_handler() function on click and want to get the post ID of that link using url\_to\_postid($\_POST['url']); ``` function Reco_load_widget() { register_widget( 'Reco_Person' ); } add_action( 'widgets_init', 'Reco_load_widget' ); class Reco_Person extends WP_Widget { function __construct() { parent::__construct( 'wpb_widget_per', __('Reco Personalisation','wpb_widget_per_person'), array( 'description' => __( 'Content widget', 'wpb_widget_per_person' ), ) ); } public function widget( $args, $instance ) { ?> <script> jQuery(function(){ jQuery('a').click(function(){ var url = jQuery(this).attr('href'); jQuery.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', method: "POST", contentType: 'application/json', data: ({ action: "get_prev_ajax_handler", url: url }), success: function (response){ console.log(response); } }); }); }); </script> <?php } public function get_prev_ajax_handler() { return url_to_postid($_POST["url"]); } } add_action('wp_ajax_get_prev', 'get_prev_ajax_handler'); // add action for logged users add_action( 'wp_ajax_nopriv_get_prev', 'get_prev_ajax_handler' ); ``` But this hook is not working. Did I invoke add\_action at wrong place with wrong parameter?
the another way to get the `post_id` by clicking on the `link` is to add a `data-attribute` to the link. e.g; `data-post-id="'.get_the_ID().'"` your html code should look like ``` <a href="#link" data-post-id="47">Link</a> ``` then in your js code above the ajax call ``` var post_id = jQuery(this).attr('data-post-id'); ``` and pass this in your `data` object to the ajax call. ``` data: ({ action: "get_prev_ajax_handler", url: url, post_id: post_id, }), ``` now you can get the `post_id` with `$_POST['post_id']` or `print_r()` the `$_POST` `array()`
272,858
<p>Can anyone help me how to add custom css file in wordpress.</p> <p>I followed the below link, <a href="https://wordpress.stackexchange.com/questions/258226/where-are-additional-css-files-stored">Where are Additional CSS files stored</a>. But it shows only adding additional css, but i want to add css file and calling,</p> <p>Thanks </p>
[ { "answer_id": 272860, "author": "Jignesh Patel", "author_id": 111556, "author_profile": "https://wordpress.stackexchange.com/users/111556", "pm_score": 2, "selected": false, "text": "<p>Put this code in functions.php file for add new css file (more info <a href=\"https://developer.wordp...
2017/07/10
[ "https://wordpress.stackexchange.com/questions/272858", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122737/" ]
Can anyone help me how to add custom css file in wordpress. I followed the below link, [Where are Additional CSS files stored](https://wordpress.stackexchange.com/questions/258226/where-are-additional-css-files-stored). But it shows only adding additional css, but i want to add css file and calling, Thanks
Put this code in functions.php file for add new css file (more info [here](https://developer.wordpress.org/reference/functions/wp_enqueue_style/)). ``` add_action( 'wp_enqueue_scripts', 'enqueue_my_styles' ); function enqueue_my_styles() { wp_enqueue_style( 'my-theme-ie', get_stylesheet_directory_uri() . "/css/ie.css"); } ``` 1. if using a parent theme then put code in parent theme function.php file and use `get_template_directory_uri()` 2. if using a child theme then put code in child theme function.php file and use `get_stylesheet_directory_uri()` Note: Relative CSS path must be correct.
272,879
<p>I create custom field type select</p> <p><a href="https://i.stack.imgur.com/bofha.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bofha.png" alt="enter image description here"></a> </p> <p>Need display <code>values</code> from custom field outside <code>&lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt;</code> like <a href="https://v4-alpha.getbootstrap.com/components/navs/#tabs" rel="nofollow noreferrer">bootstrap tabs</a>.</p> <p>Code 1:</p> <pre><code>&lt;?php global $wp_query; $postid = $wp_query-&gt;post-&gt;ID; var_dump($postid); echo get_post_meta($postid, 'employee_category', true); wp_reset_query(); ?&gt; </code></pre> <p>return - <code>int(269)</code> - id page.</p> <p>Code 2:</p> <pre><code>&lt;?php $value = get_field( "employee_category" ); if( $value ) { echo $value; } else { echo 'empty'; } ?&gt; </code></pre> <p>return - <code>empty</code>.</p> <p>Code 2 inside loop work correctly.</p> <p>How display values outside loop?</p> <p><strong>UPD</strong></p> <p>Need to display all categorys.</p> <p>This code </p> <pre><code>&lt;?php global $wp_query; $postid = $wp_query-&gt;post-&gt;ID; $value = get_field( "employee_category", 269 ); var_dump($value); if( $value ) { echo $value; } else { echo 'empty'; } wp_reset_query(); ?&gt; </code></pre> <p>return <code>null</code></p>
[ { "answer_id": 272880, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 2, "selected": false, "text": "<p>You need to pass <code>$postid</code> to your <code>get_field</code> function.</p>\n\n<pre><code>&...
2017/07/10
[ "https://wordpress.stackexchange.com/questions/272879", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/120398/" ]
I create custom field type select [![enter image description here](https://i.stack.imgur.com/bofha.png)](https://i.stack.imgur.com/bofha.png) Need display `values` from custom field outside `<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>` like [bootstrap tabs](https://v4-alpha.getbootstrap.com/components/navs/#tabs). Code 1: ``` <?php global $wp_query; $postid = $wp_query->post->ID; var_dump($postid); echo get_post_meta($postid, 'employee_category', true); wp_reset_query(); ?> ``` return - `int(269)` - id page. Code 2: ``` <?php $value = get_field( "employee_category" ); if( $value ) { echo $value; } else { echo 'empty'; } ?> ``` return - `empty`. Code 2 inside loop work correctly. How display values outside loop? **UPD** Need to display all categorys. This code ``` <?php global $wp_query; $postid = $wp_query->post->ID; $value = get_field( "employee_category", 269 ); var_dump($value); if( $value ) { echo $value; } else { echo 'empty'; } wp_reset_query(); ?> ``` return `null`
I make this: ``` <ul class="nav nav-tabs d-flex justify-content-center flex-wrap team-navs"> <?php $loop = new WP_Query( array( 'post_type' => 'employee', 'post_status'=>'publish', 'posts_per_page' => -1 ) ); ?> <?php $counter = 0; while ( $loop->have_posts() ) : $loop->the_post(); $counter++; $value = get_field( "employee_category" ); ?> <li class="nav-item post-<?php the_ID(); ?> <?=($counter == 1) ? 'active' : ''?>"> <a class="nav-link" role="tab" href="#<?php echo $value; ?>" aria-controls="home" role="tab" data-toggle="tab"><?php echo $value; ?></a> </li> <?php endwhile; wp_reset_query(); ?> </ul> ``` This code display category. But at the same time its dublicates tabs, if if there is post of the same category. And need to make switching tabs...
272,887
<p>First apologies if this is a stupid question I can imagine there is an easy way to do this but would like to ask anyhow.</p> <p>I have setup a js framework that I am trying to integrate into a WordPress plugin. Currently if works like this.</p> <pre><code>example("div").media({ plugins: { modal : true }, options : { opts: 1 } }); </code></pre> <p>I am not sure how to set this up with shortcode without having hundreds of params.</p> <pre><code>[example div="div" plugins="???" options="???"] </code></pre> <p>Can't find anything here <a href="https://codex.wordpress.org/Shortcode_API" rel="nofollow noreferrer">https://codex.wordpress.org/Shortcode_API</a></p> <p>Thanks</p>
[ { "answer_id": 272880, "author": "Aniruddha Gawade", "author_id": 101818, "author_profile": "https://wordpress.stackexchange.com/users/101818", "pm_score": 2, "selected": false, "text": "<p>You need to pass <code>$postid</code> to your <code>get_field</code> function.</p>\n\n<pre><code>&...
2017/07/10
[ "https://wordpress.stackexchange.com/questions/272887", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/83641/" ]
First apologies if this is a stupid question I can imagine there is an easy way to do this but would like to ask anyhow. I have setup a js framework that I am trying to integrate into a WordPress plugin. Currently if works like this. ``` example("div").media({ plugins: { modal : true }, options : { opts: 1 } }); ``` I am not sure how to set this up with shortcode without having hundreds of params. ``` [example div="div" plugins="???" options="???"] ``` Can't find anything here <https://codex.wordpress.org/Shortcode_API> Thanks
I make this: ``` <ul class="nav nav-tabs d-flex justify-content-center flex-wrap team-navs"> <?php $loop = new WP_Query( array( 'post_type' => 'employee', 'post_status'=>'publish', 'posts_per_page' => -1 ) ); ?> <?php $counter = 0; while ( $loop->have_posts() ) : $loop->the_post(); $counter++; $value = get_field( "employee_category" ); ?> <li class="nav-item post-<?php the_ID(); ?> <?=($counter == 1) ? 'active' : ''?>"> <a class="nav-link" role="tab" href="#<?php echo $value; ?>" aria-controls="home" role="tab" data-toggle="tab"><?php echo $value; ?></a> </li> <?php endwhile; wp_reset_query(); ?> </ul> ``` This code display category. But at the same time its dublicates tabs, if if there is post of the same category. And need to make switching tabs...
272,902
<p>I am trying to upload many hundreds of images daily from a folder on the server to the media library using the following script that is scheduled via CRON:</p> <pre><code>&lt;?php require_once('../../../../public/wordpress/wp-load.php'); require_once('../../../../public/wordpress/wp-admin/includes/image.php'); function importImage($imagePath, $postId) { $succeededFileCount = 0; $failedFileCount = 0; $files = scandir($imagePath); foreach ($files as $file) { if (in_array($file, ['.', '..'])) { continue; } $newPath = $imagePath . "/" . $file; $filePath = realpath($newPath); if (is_dir($newPath) &amp;&amp; $item != '.' &amp;&amp; $item != '..' &amp;&amp; $item != 'failed_files') { importImage($newPath, $postId); } elseif ($item != '.' &amp;&amp; $item != '..' &amp;&amp; $item != 'failed_files') { $filename = basename($file); $uploadFile = wp_upload_bits($filename, null, file_get_contents($filePath)); $wp_upload_dir = wp_upload_dir(); if (! $uploadFile['error']) { $fileType = wp_check_filetype($filename, null); $attachment = [ 'guid' =&gt; $wp_upload_dir['url'] . '/' . basename( $filename ), 'post_mime_type' =&gt; $fileType['type'], 'post_parent' =&gt; $postId, 'post_title' =&gt; preg_replace('/\.[^.]+$/', '', $filename), 'post_content' =&gt; '', 'post_status' =&gt; 'inherit' ]; $attachmentId = wp_insert_attachment($attachment, $uploadFile['file'], $postId); if (! is_wp_error($attachmentId)) { $attachmentData = wp_generate_attachment_metadata($attachmentId, $uploadFile['file']); wp_update_attachment_metadata($attachmentId, $attachmentData); } } else { echo '&lt;span style="color: red; font-weight: bold;"&gt;Error: ' . $uploadFile['error'] . '&lt;/span&gt;'; } if ($attachmentId &gt; 0) { $succeededFileCount++; echo '&lt;span style="color: green; font-weight: normal;"&gt;File import succeeded: ' . $filePath . "&lt;/span&gt;&lt;br /&gt;"; if (! unlink($filePath)) { echo '&lt;span style="color: red; font-weight: bold;"&gt;Unable to delete file ' . $filePath . " after import.&lt;/span&gt;&lt;br /&gt;"; } $page = get_post($postId); if ($page-&gt;post_content) { $content = $page-&gt;post_content; $start = strpos($content, "[gallery ") + strlen("[gallery "); $end = strpos(substr($content, $start), "]"); $shortcode = substr($content, $start, $end); $attrs = shortcode_parse_atts($shortcode); $attrs["ids"] .= "," . $attachmentId; $tempIds = explode(",", $attrs["ids"]); $tempIds = array_filter($tempIds); rsort($tempIds); $attrs["ids"] = implode(",", $tempIds); $shortcode = ""; foreach ($attrs as $key =&gt; $value) { if (strlen($shortcode) &gt; 0) { $shortcode .= " "; } $shortcode .= $key . "=\"" . $value . "\""; } $newContent = substr($content, 0, $start); $newContent .= $shortcode; $newContent .= substr($content, $start + $end, strlen($content)); $page-&gt;post_content = $newContent; wp_update_post($page); } } } } echo $succeededFileCount . " files uploaded and imported successfully. &lt;br /&gt;"; echo $failedFileCount . " files failed to uploaded or import successfully."; } get_header(); if (get_option('rmm_image_importer_key') != urldecode($_GET['key'])) { echo '&lt;div id="message" class="error"&gt;'; echo "&lt;p&gt;&lt;strong&gt;Incorrect authentication key: you are not allowed to import images into this site.&lt;/strong&gt;&lt;/p&gt;&lt;/div&gt;"; } else { echo '&lt;br /&gt;&lt;br /&gt;'; $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = $mtime[1] + $mtime[0]; $starttime = $mtime; $dataset = get_option('rmm_image_importer_settings'); if (is_array($dataset)) { foreach ($dataset as $data) { if (isset($data['folder']) || isset($data['page'])) { ?&gt; &lt;h2&gt;Import from folder: &lt;?php echo $data['folder']; ?&gt;&lt;/h2&gt; &lt;p&gt; &lt;?php importImage(realpath(str_replace('//', '/', ABSPATH . '../../' . $data['folder'])), $data['page']); ?&gt; &lt;/p&gt; &lt;?php } } } $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = $mtime[1] + $mtime[0]; $endtime = $mtime; $totaltime = ($endtime - $starttime); echo 'Files imported to media library over ' . $totaltime . ' seconds.&lt;br /&gt;&lt;br /&gt;'; } get_footer(); </code></pre> <p>The problem is that no matter what I do, the script fails after just two images with this error:</p> <blockquote> <p>Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 28672 bytes) in /home/forge/morselandcompany.com/public/wordpress/wp-includes/wp-db.php on line 1841</p> </blockquote> <p>I have the memory limit set to 1024M in wordpress, as well as PHP. I don't see why this script should need more than 128M, really. How can this script be optimized to work properly? (Average image size is 800kB.)</p> <p>Some initial debugging with BlackFire.io suggests the following memory hogs: - wpdb->query: 3.2MB, called 31 times - mysqli_fetch_object: 1.89MB, called 595 times - run_init() in wp-settings.php: 5.4MB, called once In total blackfire suggests that over 8MB is required to run this script!</p> <p>I have also tested with all plugins disabled, and that ended with the same result.</p> <p>I am running on - PHP 7.1<br> - Ubuntu 16.04<br> - DigitalOcean VPS (1 CPU, 1GB RAM)<br> - Wordpress 4.8<br> - NGINX 1.11.5 </p> <p>Thanks for any help!</p> <p><strong>Update:</strong> in the interest of completeness so that others may utilize the solution for memory leaks associated with get_post and wp_update_post, I have posted the finalized code that solved the problem above. As you can see, the solution was to write my own queries using $wpdb instead of relying on the two WP methods causing the memory leaks:</p> <pre><code>&lt;?php require_once('../../../../public/wordpress/wp-load.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); function importImage($imagePath, $postId) { $succeededFileCount = 0; $failedFileCount = 0; $files = scandir($imagePath); foreach ($files as $file) { if (in_array($file, ['.', '..'])) { continue; } $newPath = $imagePath . "/" . $file; $filePath = realpath($newPath); if (is_dir($newPath) &amp;&amp; $file != 'failed_files') { importImage($newPath, $postId); } elseif ($file != 'failed_files') { $webPath = str_replace($_SERVER['DOCUMENT_ROOT'], '', $imagePath); $imageUrl = str_replace('/wordpress', '', get_site_url(null, "{$webPath}/" . urlencode($file))); $imageUrl = str_replace(':8000', '', $imageUrl); $attachmentId = media_sideload_image($imageUrl, 0, '', 'id'); if ($attachmentId &gt; 0) { $succeededFileCount++; echo '&lt;span style="color: green; font-weight: normal;"&gt;File import succeeded: ' . $filePath . "&lt;/span&gt;&lt;br /&gt;"; if (! unlink($filePath)) { echo '&lt;span style="color: red; font-weight: bold;"&gt;Unable to delete file ' . $filePath . " after import.&lt;/span&gt;&lt;br /&gt;"; } global $wpdb; $page = $wpdb-&gt;get_results("SELECT * FROM wp_posts WHERE ID = {$postId}")[0]; if (is_array($page)) { $page = $page[0]; } if ($page-&gt;post_content) { $content = $page-&gt;post_content; $start = strpos($content, "[gallery ") + strlen("[gallery "); $end = strpos(substr($content, $start), "]"); $shortcode = substr($content, $start, $end); $attrs = shortcode_parse_atts($shortcode); $attrs["ids"] .= "," . $attachmentId; $tempIds = explode(",", $attrs["ids"]); $tempIds = array_filter($tempIds); rsort($tempIds); $attrs["ids"] = implode(",", $tempIds); $shortcode = ""; foreach ($attrs as $key =&gt; $value) { if (strlen($shortcode) &gt; 0) { $shortcode .= " "; } $shortcode .= $key . "=\"" . $value . "\""; } $newContent = substr($content, 0, $start); $newContent .= $shortcode; $newContent .= substr($content, $start + $end, strlen($content)); $wpdb-&gt;update( 'post_content', ['post_content' =&gt; $newContent], ['ID' =&gt; $postId] ); } } } } echo $succeededFileCount . " files uploaded and imported successfully. &lt;br /&gt;"; echo $failedFileCount . " files failed to uploaded or import successfully."; } get_header(); if (get_option('rmm_image_importer_key') != urldecode($_GET['key'])) { echo '&lt;div id="message" class="error"&gt;'; echo "&lt;p&gt;&lt;strong&gt;Incorrect authentication key: you are not allowed to import images into this site.&lt;/strong&gt;&lt;/p&gt;&lt;/div&gt;"; } else { echo '&lt;br /&gt;&lt;br /&gt;'; $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = $mtime[1] + $mtime[0]; $starttime = $mtime; $dataset = get_option('rmm_image_importer_settings'); if (is_array($dataset)) { foreach ($dataset as $data) { if (isset($data['folder']) || isset($data['page'])) { ?&gt; &lt;h2&gt;Import from folder: &lt;?php echo $data['folder']; ?&gt;&lt;/h2&gt; &lt;p&gt; &lt;?php importImage(realpath(str_replace('//', '/', ABSPATH . '../../' . $data['folder'])), $data['page']); ?&gt; &lt;/p&gt; &lt;?php } } } $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = $mtime[1] + $mtime[0]; $endtime = $mtime; $totaltime = ($endtime - $starttime); echo 'Files imported to media library over ' . $totaltime . ' seconds.&lt;br /&gt;&lt;br /&gt;'; } get_footer(); </code></pre>
[ { "answer_id": 273298, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>There is already a built-in function created just for that purpose. You don't need to write walls of codes ...
2017/07/10
[ "https://wordpress.stackexchange.com/questions/272902", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/87803/" ]
I am trying to upload many hundreds of images daily from a folder on the server to the media library using the following script that is scheduled via CRON: ``` <?php require_once('../../../../public/wordpress/wp-load.php'); require_once('../../../../public/wordpress/wp-admin/includes/image.php'); function importImage($imagePath, $postId) { $succeededFileCount = 0; $failedFileCount = 0; $files = scandir($imagePath); foreach ($files as $file) { if (in_array($file, ['.', '..'])) { continue; } $newPath = $imagePath . "/" . $file; $filePath = realpath($newPath); if (is_dir($newPath) && $item != '.' && $item != '..' && $item != 'failed_files') { importImage($newPath, $postId); } elseif ($item != '.' && $item != '..' && $item != 'failed_files') { $filename = basename($file); $uploadFile = wp_upload_bits($filename, null, file_get_contents($filePath)); $wp_upload_dir = wp_upload_dir(); if (! $uploadFile['error']) { $fileType = wp_check_filetype($filename, null); $attachment = [ 'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), 'post_mime_type' => $fileType['type'], 'post_parent' => $postId, 'post_title' => preg_replace('/\.[^.]+$/', '', $filename), 'post_content' => '', 'post_status' => 'inherit' ]; $attachmentId = wp_insert_attachment($attachment, $uploadFile['file'], $postId); if (! is_wp_error($attachmentId)) { $attachmentData = wp_generate_attachment_metadata($attachmentId, $uploadFile['file']); wp_update_attachment_metadata($attachmentId, $attachmentData); } } else { echo '<span style="color: red; font-weight: bold;">Error: ' . $uploadFile['error'] . '</span>'; } if ($attachmentId > 0) { $succeededFileCount++; echo '<span style="color: green; font-weight: normal;">File import succeeded: ' . $filePath . "</span><br />"; if (! unlink($filePath)) { echo '<span style="color: red; font-weight: bold;">Unable to delete file ' . $filePath . " after import.</span><br />"; } $page = get_post($postId); if ($page->post_content) { $content = $page->post_content; $start = strpos($content, "[gallery ") + strlen("[gallery "); $end = strpos(substr($content, $start), "]"); $shortcode = substr($content, $start, $end); $attrs = shortcode_parse_atts($shortcode); $attrs["ids"] .= "," . $attachmentId; $tempIds = explode(",", $attrs["ids"]); $tempIds = array_filter($tempIds); rsort($tempIds); $attrs["ids"] = implode(",", $tempIds); $shortcode = ""; foreach ($attrs as $key => $value) { if (strlen($shortcode) > 0) { $shortcode .= " "; } $shortcode .= $key . "=\"" . $value . "\""; } $newContent = substr($content, 0, $start); $newContent .= $shortcode; $newContent .= substr($content, $start + $end, strlen($content)); $page->post_content = $newContent; wp_update_post($page); } } } } echo $succeededFileCount . " files uploaded and imported successfully. <br />"; echo $failedFileCount . " files failed to uploaded or import successfully."; } get_header(); if (get_option('rmm_image_importer_key') != urldecode($_GET['key'])) { echo '<div id="message" class="error">'; echo "<p><strong>Incorrect authentication key: you are not allowed to import images into this site.</strong></p></div>"; } else { echo '<br /><br />'; $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = $mtime[1] + $mtime[0]; $starttime = $mtime; $dataset = get_option('rmm_image_importer_settings'); if (is_array($dataset)) { foreach ($dataset as $data) { if (isset($data['folder']) || isset($data['page'])) { ?> <h2>Import from folder: <?php echo $data['folder']; ?></h2> <p> <?php importImage(realpath(str_replace('//', '/', ABSPATH . '../../' . $data['folder'])), $data['page']); ?> </p> <?php } } } $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = $mtime[1] + $mtime[0]; $endtime = $mtime; $totaltime = ($endtime - $starttime); echo 'Files imported to media library over ' . $totaltime . ' seconds.<br /><br />'; } get_footer(); ``` The problem is that no matter what I do, the script fails after just two images with this error: > > Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried > to allocate 28672 bytes) in > /home/forge/morselandcompany.com/public/wordpress/wp-includes/wp-db.php > on line 1841 > > > I have the memory limit set to 1024M in wordpress, as well as PHP. I don't see why this script should need more than 128M, really. How can this script be optimized to work properly? (Average image size is 800kB.) Some initial debugging with BlackFire.io suggests the following memory hogs: - wpdb->query: 3.2MB, called 31 times - mysqli\_fetch\_object: 1.89MB, called 595 times - run\_init() in wp-settings.php: 5.4MB, called once In total blackfire suggests that over 8MB is required to run this script! I have also tested with all plugins disabled, and that ended with the same result. I am running on - PHP 7.1 - Ubuntu 16.04 - DigitalOcean VPS (1 CPU, 1GB RAM) - Wordpress 4.8 - NGINX 1.11.5 Thanks for any help! **Update:** in the interest of completeness so that others may utilize the solution for memory leaks associated with get\_post and wp\_update\_post, I have posted the finalized code that solved the problem above. As you can see, the solution was to write my own queries using $wpdb instead of relying on the two WP methods causing the memory leaks: ``` <?php require_once('../../../../public/wordpress/wp-load.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); function importImage($imagePath, $postId) { $succeededFileCount = 0; $failedFileCount = 0; $files = scandir($imagePath); foreach ($files as $file) { if (in_array($file, ['.', '..'])) { continue; } $newPath = $imagePath . "/" . $file; $filePath = realpath($newPath); if (is_dir($newPath) && $file != 'failed_files') { importImage($newPath, $postId); } elseif ($file != 'failed_files') { $webPath = str_replace($_SERVER['DOCUMENT_ROOT'], '', $imagePath); $imageUrl = str_replace('/wordpress', '', get_site_url(null, "{$webPath}/" . urlencode($file))); $imageUrl = str_replace(':8000', '', $imageUrl); $attachmentId = media_sideload_image($imageUrl, 0, '', 'id'); if ($attachmentId > 0) { $succeededFileCount++; echo '<span style="color: green; font-weight: normal;">File import succeeded: ' . $filePath . "</span><br />"; if (! unlink($filePath)) { echo '<span style="color: red; font-weight: bold;">Unable to delete file ' . $filePath . " after import.</span><br />"; } global $wpdb; $page = $wpdb->get_results("SELECT * FROM wp_posts WHERE ID = {$postId}")[0]; if (is_array($page)) { $page = $page[0]; } if ($page->post_content) { $content = $page->post_content; $start = strpos($content, "[gallery ") + strlen("[gallery "); $end = strpos(substr($content, $start), "]"); $shortcode = substr($content, $start, $end); $attrs = shortcode_parse_atts($shortcode); $attrs["ids"] .= "," . $attachmentId; $tempIds = explode(",", $attrs["ids"]); $tempIds = array_filter($tempIds); rsort($tempIds); $attrs["ids"] = implode(",", $tempIds); $shortcode = ""; foreach ($attrs as $key => $value) { if (strlen($shortcode) > 0) { $shortcode .= " "; } $shortcode .= $key . "=\"" . $value . "\""; } $newContent = substr($content, 0, $start); $newContent .= $shortcode; $newContent .= substr($content, $start + $end, strlen($content)); $wpdb->update( 'post_content', ['post_content' => $newContent], ['ID' => $postId] ); } } } } echo $succeededFileCount . " files uploaded and imported successfully. <br />"; echo $failedFileCount . " files failed to uploaded or import successfully."; } get_header(); if (get_option('rmm_image_importer_key') != urldecode($_GET['key'])) { echo '<div id="message" class="error">'; echo "<p><strong>Incorrect authentication key: you are not allowed to import images into this site.</strong></p></div>"; } else { echo '<br /><br />'; $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = $mtime[1] + $mtime[0]; $starttime = $mtime; $dataset = get_option('rmm_image_importer_settings'); if (is_array($dataset)) { foreach ($dataset as $data) { if (isset($data['folder']) || isset($data['page'])) { ?> <h2>Import from folder: <?php echo $data['folder']; ?></h2> <p> <?php importImage(realpath(str_replace('//', '/', ABSPATH . '../../' . $data['folder'])), $data['page']); ?> </p> <?php } } } $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = $mtime[1] + $mtime[0]; $endtime = $mtime; $totaltime = ($endtime - $starttime); echo 'Files imported to media library over ' . $totaltime . ' seconds.<br /><br />'; } get_footer(); ```
A few things * Use `media_handle_sideload` so that WordPress moves the files to the right location and validates them for you, creates the attachment post etc, none of this manual stuff * Don't run this once and expect it to do everything. You're just going to run into the same problem but further into the import. If you give it infinite memory you'll have a time limit execution problem where the script simply runs out of time * Process 5 files at a time, and repeatedly call run it until nothing is left to process * Use a WP CLI command, don't bootstrap WordPress and call it from the GUI. Call it from Cron directly and skip the pinging a URL business. CLI commands get unlimited time to do their job, and you can't call them from the browser. The GET variable with the key becomes completely unnecessary. * Escape escape escape, you're echoing out these arrays and values, assuming what they contain is safe, but what if I snuck a script tag in there? `Unable to delete file <script>...</script> after import.`. Biggest security step you can take that makes the most difference yet the least used A Prototype WP CLI command -------------------------- Here is a simple WP CLI command that should do the trick. I've not tested it but all the important parts are there, I trust you're not a complete novice when it comes to PHP and can tighten any loose screws or minor mistakes, no additional API knowledge necessary. You'll want to only include it when in a WP CLI context, for example: ``` if ( defined( 'WP_CLI' ) && WP_CLI ) { require_once dirname( __FILE__ ) . '/inc/class-plugin-cli-command.php'; } ``` Modify accordingly, dumping the command in `functions.php` of a theme and expecting it all to work will cause errors as WP CLI classes are only loaded on the command line, never when handling a browser request. Usage: `wp mbimport run` Class: ``` <?php /** * Implements image importer command. */ class MBronner_Import_Images extends WP_CLI_Command { /** * Runs the import script and imports several images * * ## EXAMPLES * * wp mbimport run * * @when after_wp_load */ function run( $args, $assoc_args ) { if ( !function_exists('media_handle_upload') ) { require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); } // Set the directory $dir = ABSPATH .'/wpse'; // Define the file type $images = glob( $dir . "*.jpg" ); if ( empty( $images ) { WP_CLI::success( 'no images to import' ); exit; } // Run a loop and transfer every file to media library // $count = 0; foreach ( $images as $image ) { $file_array = array(); $file_array['name'] = $image; $file_array['tmp_name'] = $image; $id = media_handle_sideload( $file_array, 0 ); if ( is_wp_error( $id ) ) { WP_CLI::error( "failed to sideload ".$image ); exit; } // only do 5 at a time, dont worry we can run this // several times till they're all done $count++; if ( $count === 5 ) { break; } } WP_CLI::success( "import ran" ); } } WP_CLI::add_command( 'mbimport', 'MBronner_Import_Images' ); ``` Call repeatedly from a real cron job. If you can't, then either use WP Cron, or have a hook on `admin_init` that checks for a GET variable. Use the code inside the `run` command with some modifications. When WP CLI Isn't An Option --------------------------- Using a standalone PHP file that bootstraps WP is a security risk and a great target for attackers if they want to exhaust your server resources ( or trigger duplication issues by hitting the URL multiple times all at once ). For example: ``` // example.com/?mbimport=true add_action( 'init', function() { if ( $_GET['action'] !== 'mbimport' ) { return; } if ( $_GET['key'] !== get_option('key thing' ) ) { return; } // the code from the run function in the CLI command, but with the WP_CLI::success bits swapped out // ... exit; } ``` ### Repeated Calling It might be that your external service can't call this repeatedly. To which I say: * Don't rely on the external service, have your own server call it regardless, even if there's no work to do * A standard WP Cron task would also work * Run it every 5 minutes * Make the task call itself if there's still stuff to do, using a nonblocking request. This way it'll keep spawning new instances until it's finished e.g. ``` if ( $count === 5 ) { wp_remote_get( home_url('?mbimport=true&key=abc'), [ 'blocking' => false ]); exit; ) ``` GUI? ---- If you want a progress meter for a UI in the dashboard, just count how many jpeg files are left in the folder to import. If you need to configure it, then build a UI and save the settings in options, then pull from options in the CLI script. Have You Considered Using the REST API? --------------------------------------- Sidestep the entire process and add the files via the REST API. You can do a POST request to `example.com/wp-json/wp/v2/media` to upload the jpegs. No code on your site necessary <https://stackoverflow.com/questions/37432114/wp-rest-api-upload-image>
272,925
<p>I've read a bunch of articles about <a href="https://docs.woocommerce.com/document/template-structure/" rel="nofollow noreferrer">overriding the default /woocommerce/ templates</a> and tried implementing the following (which were the best/most relevant that I could find all to no avail):</p> <ul> <li><a href="https://wordpress.stackexchange.com/questions/110602/load-woocommerce-templates-from-my-plugin-folder-first">Load WooCommerce templates from my plugin folder first</a> </li> <li><a href="https://www.skyverge.com/blog/override-woocommerce-template-file-within-a-plugin/" rel="nofollow noreferrer">Override WooCommerce Template File Within a Plugin</a></li> </ul> <p>Essentially, what I would like to accomplish is: load all template files (for archives and posts not just template parts) from ~/wp-content/my-plugin/templates/woocommerce/* UNLESS the files are in my theme (and I don't have to override each file instance in my function) . For instance:</p> <ul> <li><code>~/wp-content/my-plugin/templates/woocommerce/single-product.php</code> <em>(this seems like it just doesn't want to load via plugin)</em></li> <li><code>~/wp-content/my-plugin/templates/woocommerce/archive-products.php</code> <em>(this seems like it just doesn't want to load via plugin)</em></li> <li><code>~/wp-content/my-plugin/templates/woocommerce-pdf-invoices-packing-slips/*</code> <em>(I also want to be able to <strong>override other plugin extension templates</strong> just like I would be able to in my child theme)</em></li> </ul> <p><strong>EDIT:</strong></p> <p>The friendly folks at <a href="https://www.skyverge.com/blog/override-woocommerce-template-file-within-a-plugin/" rel="nofollow noreferrer">SkyVerge</a> sent me the following code, which I tested and confirm that it works for template <em>parts</em>.</p> <pre><code>// Locate the template in a plugin function myplugin_woocommerce_locate_template( $template, $template_name, $template_path ) { $_template = $template; if ( ! $template_path ) { $template_path = WC()-&gt;template_path(); } $plugin_path = myplugin_plugin_path() . '/templates/'; // Look within passed path within the theme - this is priority $template = locate_template( array( trailingslashit( $template_path ) . $template_name, $template_name ) ); // Modification: Get the template from this plugin, if it exists if ( ! $template &amp;&amp; file_exists( $plugin_path . $template_name ) ) { $template = $plugin_path . $template_name; } // Use default template if ( ! $template ) { $template = $_template; } return $template; } add_filter( 'woocommerce_locate_template', 'myplugin_woocommerce_locate_template', 10, 3 ); // Helper to get the plugin's path on the server function myplugin_plugin_path() { // gets the absolute path to this plugin directory return untrailingslashit( plugin_dir_path( __FILE__ ) ); } </code></pre> <p>The above code works for something like:</p> <ul> <li><code>~/myplugin/templates/single-product/product-image.php</code></li> </ul> <p>But does NOT work for: </p> <ul> <li><code>~/myplugin/templates/single-product.php</code></li> </ul> <p>Where I'm getting stuck:</p> <ul> <li>There are solutions to override bits and pieces of WC templates, but there I've not found / been able to create a solution that does <em>comprehensive</em> overrides (i.e. overriding ability just like a child theme would)</li> <li>I can't seem to find the right combination of filter hooks; single-product.php and archive-product.php seem to be controlled by functions outside the standard WC template functions</li> </ul> <p>Thanks in advance!</p>
[ { "answer_id": 272930, "author": "Syed Abuthahir M", "author_id": 112046, "author_profile": "https://wordpress.stackexchange.com/users/112046", "pm_score": 0, "selected": false, "text": "<p>In this scenario you can use the following filter wc_get_template_part.</p>\n\n<p>Hook reference l...
2017/07/10
[ "https://wordpress.stackexchange.com/questions/272925", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/47880/" ]
I've read a bunch of articles about [overriding the default /woocommerce/ templates](https://docs.woocommerce.com/document/template-structure/) and tried implementing the following (which were the best/most relevant that I could find all to no avail): * [Load WooCommerce templates from my plugin folder first](https://wordpress.stackexchange.com/questions/110602/load-woocommerce-templates-from-my-plugin-folder-first) * [Override WooCommerce Template File Within a Plugin](https://www.skyverge.com/blog/override-woocommerce-template-file-within-a-plugin/) Essentially, what I would like to accomplish is: load all template files (for archives and posts not just template parts) from ~/wp-content/my-plugin/templates/woocommerce/\* UNLESS the files are in my theme (and I don't have to override each file instance in my function) . For instance: * `~/wp-content/my-plugin/templates/woocommerce/single-product.php` *(this seems like it just doesn't want to load via plugin)* * `~/wp-content/my-plugin/templates/woocommerce/archive-products.php` *(this seems like it just doesn't want to load via plugin)* * `~/wp-content/my-plugin/templates/woocommerce-pdf-invoices-packing-slips/*` *(I also want to be able to **override other plugin extension templates** just like I would be able to in my child theme)* **EDIT:** The friendly folks at [SkyVerge](https://www.skyverge.com/blog/override-woocommerce-template-file-within-a-plugin/) sent me the following code, which I tested and confirm that it works for template *parts*. ``` // Locate the template in a plugin function myplugin_woocommerce_locate_template( $template, $template_name, $template_path ) { $_template = $template; if ( ! $template_path ) { $template_path = WC()->template_path(); } $plugin_path = myplugin_plugin_path() . '/templates/'; // Look within passed path within the theme - this is priority $template = locate_template( array( trailingslashit( $template_path ) . $template_name, $template_name ) ); // Modification: Get the template from this plugin, if it exists if ( ! $template && file_exists( $plugin_path . $template_name ) ) { $template = $plugin_path . $template_name; } // Use default template if ( ! $template ) { $template = $_template; } return $template; } add_filter( 'woocommerce_locate_template', 'myplugin_woocommerce_locate_template', 10, 3 ); // Helper to get the plugin's path on the server function myplugin_plugin_path() { // gets the absolute path to this plugin directory return untrailingslashit( plugin_dir_path( __FILE__ ) ); } ``` The above code works for something like: * `~/myplugin/templates/single-product/product-image.php` But does NOT work for: * `~/myplugin/templates/single-product.php` Where I'm getting stuck: * There are solutions to override bits and pieces of WC templates, but there I've not found / been able to create a solution that does *comprehensive* overrides (i.e. overriding ability just like a child theme would) * I can't seem to find the right combination of filter hooks; single-product.php and archive-product.php seem to be controlled by functions outside the standard WC template functions Thanks in advance!
``` function woo_template_replace( $located, $template_name, $args, $template_path, $default_path ) { if( file_exists( plugin_dir_path(__FILE__) . 'templates/' . $template_name ) ) { $located = plugin_dir_path(__FILE__) . 'templates/' . $template_name; } return $located; } function woo_get_template_part( $template , $slug , $name ) { if( empty( $name ) ) { if( file_exists( plugin_dir_path(__FILE__) . "/templates/{$slug}.php" ) ) { $template = plugin_dir_path(__FILE__) . "/templates/{$slug}.php"; } } else { if( file_exists( plugin_dir_path(__FILE__) . "/templates/{$slug}-{$name}.php" ) ) { $template = plugin_dir_path(__FILE__) . "/templates/{$slug}-{$name}.php"; } return $template; } add_filter( 'wc_get_template' , 'woo_template_replace' , 10 , 5 ); add_filter( 'wc_get_template_part' , 'woo_get_template_part' , 10 , 3 ); ``` You can use this snippet in your plugin root file and place your all woocommerce templates file in templates directory. Plugin structure for reference ``` plugins woo-template-replace (plugin root folder) woo-template-replace.php (plugin root file) templates (folder) single-content.php (woocommerce template file) searchform.php (woocommerce template file) ```
272,928
<p>I've managed to get the behaviour I want by modifying some plugin code. However, I would like to move my modifications outside of the plugin code using the provided hook, but I can't seem make it work. The hook uses do_action_ref_array.</p> <p>The situation is not helped by the fact that the only way I can find to access the php vars is by sending error messages to the debug.log file.</p> <p>(like so):</p> <pre><code>function ra_func1($args) { $str = print_r($args, true); error_log($str); } add_action ( 'bookly_validate_custom_field', 'ra_func1', 10, 3); </code></pre> <p>Trouble is there's a mixture of objects and arrays and I'm now really stuck, having spent a lot of time trying to get this working. If anyone could provide a working callback that does what I want I would be very grateful.</p> <p>Original plugin code:</p> <pre><code>public function validateCustomFields( $value, $form_id, $cart_key ) { $decoded_value = json_decode( $value ); $fields = array(); foreach ( json_decode( get_option( 'bookly_custom_fields' ) ) as $field ) { $fields[ $field-&gt;id ] = $field; } foreach ( $decoded_value as $field ) { if ( isset( $fields[ $field-&gt;id ] ) ) { if ( ( $fields[ $field-&gt;id ]-&gt;type == 'captcha' ) &amp;&amp; ! Captcha\Captcha::validate( $form_id, $field-&gt;value ) ) { $this-&gt;errors['custom_fields'][ $cart_key ][ $field-&gt;id ] = __( 'Incorrect code', 'bookly' ); } elseif ( $fields[ $field-&gt;id ]-&gt;required &amp;&amp; empty ( $field-&gt;value ) &amp;&amp; $field-&gt;value != '0' ) { $this-&gt;errors['custom_fields'][ $cart_key ][ $field-&gt;id ] = __( 'Required', 'bookly' ); } else { /** * Custom field validation for a third party, * if the value is not valid then please add an error message like in the above example. * * @param \stdClass * @param ref array * @param string * @param \stdClass */ do_action_ref_array( 'bookly_validate_custom_field', array( $field, &amp;$this-&gt;errors, $cart_key, $fields[ $field-&gt;id ] ) ); } } } } </code></pre> <p>Code with the beginnings of the functionality I want to add via an external callback:</p> <pre><code>public function validateCustomFields( $value, $form_id, $cart_key ) { $decoded_value = json_decode( $value ); $fields = array(); foreach ( json_decode( get_option( 'bookly_custom_fields' ) ) as $field ) { $fields[ $field-&gt;id ] = $field; } foreach ( $decoded_value as $field ) { if ( isset( $fields[ $field-&gt;id ] ) ) { if ( ( $fields[ $field-&gt;id ]-&gt;type == 'captcha' ) &amp;&amp; ! Captcha\Captcha::validate( $form_id, $field-&gt;value ) ) { $this-&gt;errors['custom_fields'][ $cart_key ][ $field-&gt;id ] = __( 'Incorrect code', 'bookly' ); } elseif ( $fields[ $field-&gt;id ]-&gt;required &amp;&amp; empty ( $field-&gt;value ) &amp;&amp; $field-&gt;value != '0' ) { $this-&gt;errors['custom_fields'][ $cart_key ][ $field-&gt;id ] = __( 'Required', 'bookly' ); } else { /** * Custom field validation for a third party, * if the value is not valid then please add an error message like in the above example. * * @param \stdClass * @param ref array * @param string * @param \stdClass */ // if ($fields[$field-&gt;id]-&gt;id == 12372){ $this-&gt;errors['custom_fields'][ $cart_key ][ $field-&gt;id ] = __( 'Post Code Error', 'bookly' ); } } } } } </code></pre>
[ { "answer_id": 272934, "author": "Syed Abuthahir M", "author_id": 112046, "author_profile": "https://wordpress.stackexchange.com/users/112046", "pm_score": 0, "selected": false, "text": "<p>You need to write custom function in functions.php with name of <code>bookly_validate_custom_field...
2017/07/10
[ "https://wordpress.stackexchange.com/questions/272928", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98276/" ]
I've managed to get the behaviour I want by modifying some plugin code. However, I would like to move my modifications outside of the plugin code using the provided hook, but I can't seem make it work. The hook uses do\_action\_ref\_array. The situation is not helped by the fact that the only way I can find to access the php vars is by sending error messages to the debug.log file. (like so): ``` function ra_func1($args) { $str = print_r($args, true); error_log($str); } add_action ( 'bookly_validate_custom_field', 'ra_func1', 10, 3); ``` Trouble is there's a mixture of objects and arrays and I'm now really stuck, having spent a lot of time trying to get this working. If anyone could provide a working callback that does what I want I would be very grateful. Original plugin code: ``` public function validateCustomFields( $value, $form_id, $cart_key ) { $decoded_value = json_decode( $value ); $fields = array(); foreach ( json_decode( get_option( 'bookly_custom_fields' ) ) as $field ) { $fields[ $field->id ] = $field; } foreach ( $decoded_value as $field ) { if ( isset( $fields[ $field->id ] ) ) { if ( ( $fields[ $field->id ]->type == 'captcha' ) && ! Captcha\Captcha::validate( $form_id, $field->value ) ) { $this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Incorrect code', 'bookly' ); } elseif ( $fields[ $field->id ]->required && empty ( $field->value ) && $field->value != '0' ) { $this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Required', 'bookly' ); } else { /** * Custom field validation for a third party, * if the value is not valid then please add an error message like in the above example. * * @param \stdClass * @param ref array * @param string * @param \stdClass */ do_action_ref_array( 'bookly_validate_custom_field', array( $field, &$this->errors, $cart_key, $fields[ $field->id ] ) ); } } } } ``` Code with the beginnings of the functionality I want to add via an external callback: ``` public function validateCustomFields( $value, $form_id, $cart_key ) { $decoded_value = json_decode( $value ); $fields = array(); foreach ( json_decode( get_option( 'bookly_custom_fields' ) ) as $field ) { $fields[ $field->id ] = $field; } foreach ( $decoded_value as $field ) { if ( isset( $fields[ $field->id ] ) ) { if ( ( $fields[ $field->id ]->type == 'captcha' ) && ! Captcha\Captcha::validate( $form_id, $field->value ) ) { $this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Incorrect code', 'bookly' ); } elseif ( $fields[ $field->id ]->required && empty ( $field->value ) && $field->value != '0' ) { $this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Required', 'bookly' ); } else { /** * Custom field validation for a third party, * if the value is not valid then please add an error message like in the above example. * * @param \stdClass * @param ref array * @param string * @param \stdClass */ // if ($fields[$field->id]->id == 12372){ $this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Post Code Error', 'bookly' ); } } } } } ```
That feature exists because I bugged them to implement it :) * <https://support.booking-wp-plugin.com/hc/en-us/community/posts/207263389-Add-a-WordPress-hook-for-custom-validators-on-the-custom-fields?page=1#community_comment_115001021885> Using it confused me as well but somebody finally replied to this just the other day with this snippet: ``` add_action( 'bookly_validate_custom_field', function ( \stdClass $field, &$errors, $cart_key, \stdClass $field_info ) { // Validation by custom_field id switch ( $field->id ) { case 'id_value': if ( /*$invalid == */ true ) { $errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Invalid', 'bookly' ); } break; } }, 10, 4 ); ```
272,936
<p>To avoid image caching issues, I would like to get WordPress to reference my jpeg images with a URL parameter. I know in javascript I can do this: </p> <pre><code>&lt;img id="idSigma" src="#" class="classSigma"&gt; &lt;script&gt; $(document).ready(function() { var d = new Date(); $("#idSigma").attr("src", "images/Sigma.jpeg?t=" + d.getTime()); }); &lt;/script&gt; </code></pre> <p>Is there a way I can get wordpress to do this to all of its internal links. For example, if I right click on an image in a blog post and click on open image it would already be pointing to the link with the URL parameter. This will ensure all the images are fresh since I plan on updating them daily. My first thought was to look for this code in media.php but maybe there is a better way than modifying the source code. </p> <hr> <p>Edit, here is what I have so far, it works in my php emulator when I set the $content variable but not doing anything in wordpress:</p> <pre><code>function add_jpeg_params($content){ preg_match_all("/https?:\/\/[^\/\s]+\/\S+\.(jpg|jpeg)/", $content, $output_array); $items_to_replace = array_unique($output_array[0]); $items_to_replace = array_values($items_to_replace); for ($j = 0; $j &lt; sizeof($items_to_replace); $j++) { $content = preg_replace('~' . $items_to_replace[$j] . '~', $items_to_replace[$j] . '?t=' . time(), $content); } return $content; } add_filter('the_content','add_jpeg_params'); </code></pre> <p>I've added this in functions.php in my wordpress theme. </p> <p>Edit 2: Solution posted below. The hook I needed was 'post_thumbnail_html'. </p>
[ { "answer_id": 272934, "author": "Syed Abuthahir M", "author_id": 112046, "author_profile": "https://wordpress.stackexchange.com/users/112046", "pm_score": 0, "selected": false, "text": "<p>You need to write custom function in functions.php with name of <code>bookly_validate_custom_field...
2017/07/10
[ "https://wordpress.stackexchange.com/questions/272936", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123537/" ]
To avoid image caching issues, I would like to get WordPress to reference my jpeg images with a URL parameter. I know in javascript I can do this: ``` <img id="idSigma" src="#" class="classSigma"> <script> $(document).ready(function() { var d = new Date(); $("#idSigma").attr("src", "images/Sigma.jpeg?t=" + d.getTime()); }); </script> ``` Is there a way I can get wordpress to do this to all of its internal links. For example, if I right click on an image in a blog post and click on open image it would already be pointing to the link with the URL parameter. This will ensure all the images are fresh since I plan on updating them daily. My first thought was to look for this code in media.php but maybe there is a better way than modifying the source code. --- Edit, here is what I have so far, it works in my php emulator when I set the $content variable but not doing anything in wordpress: ``` function add_jpeg_params($content){ preg_match_all("/https?:\/\/[^\/\s]+\/\S+\.(jpg|jpeg)/", $content, $output_array); $items_to_replace = array_unique($output_array[0]); $items_to_replace = array_values($items_to_replace); for ($j = 0; $j < sizeof($items_to_replace); $j++) { $content = preg_replace('~' . $items_to_replace[$j] . '~', $items_to_replace[$j] . '?t=' . time(), $content); } return $content; } add_filter('the_content','add_jpeg_params'); ``` I've added this in functions.php in my wordpress theme. Edit 2: Solution posted below. The hook I needed was 'post\_thumbnail\_html'.
That feature exists because I bugged them to implement it :) * <https://support.booking-wp-plugin.com/hc/en-us/community/posts/207263389-Add-a-WordPress-hook-for-custom-validators-on-the-custom-fields?page=1#community_comment_115001021885> Using it confused me as well but somebody finally replied to this just the other day with this snippet: ``` add_action( 'bookly_validate_custom_field', function ( \stdClass $field, &$errors, $cart_key, \stdClass $field_info ) { // Validation by custom_field id switch ( $field->id ) { case 'id_value': if ( /*$invalid == */ true ) { $errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Invalid', 'bookly' ); } break; } }, 10, 4 ); ```
272,962
<p>I can't find any information anywhere about what data I need to give exactly. When I try to read the data from one of my posts with a thumbnail already I get this but there's not way you have to enter all this info just to add a featured image:</p> <pre><code> thumbnail: { attachment_id: '360', date_created_gmt: 2017-07-11T04:51:15.000Z, parent: 245, link: 'http://xxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery.jpg', title: 'japanese-rice-bowl-pottery.jpg', caption: '', description: '', metadata: [Object], type: 'image/jpg', thumbnail: 'http://xxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery-150x150.jpg' } } </code></pre> <p>An example of code I tried to use to post with Node.js</p> <pre><code>client.editPost(posts[0].id, {thumbnail : { thumbnail : "http://xxxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery-150x150.jpg" } }, function( error ) {}) </code></pre>
[ { "answer_id": 273086, "author": "cooldude101", "author_id": 123580, "author_profile": "https://wordpress.stackexchange.com/users/123580", "pm_score": 1, "selected": false, "text": "<p>I found my problem and just passing it on in case someone googles this.</p>\n\n<p>You need to pass the ...
2017/07/11
[ "https://wordpress.stackexchange.com/questions/272962", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123580/" ]
I can't find any information anywhere about what data I need to give exactly. When I try to read the data from one of my posts with a thumbnail already I get this but there's not way you have to enter all this info just to add a featured image: ``` thumbnail: { attachment_id: '360', date_created_gmt: 2017-07-11T04:51:15.000Z, parent: 245, link: 'http://xxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery.jpg', title: 'japanese-rice-bowl-pottery.jpg', caption: '', description: '', metadata: [Object], type: 'image/jpg', thumbnail: 'http://xxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery-150x150.jpg' } } ``` An example of code I tried to use to post with Node.js ``` client.editPost(posts[0].id, {thumbnail : { thumbnail : "http://xxxxxxxxxxxxx.org/wp-content/uploads/2017/07/japanese-rice-bowl-pottery-150x150.jpg" } }, function( error ) {}) ```
In order to have your post have a default image, you need to set your post thumbnail. In doing this you need to set the ID of the media, which isn't readily apparent. I do most of my work in Python, so for me, the following helps: **Step 1.** Get the list of all your media so you know the IDs ``` ## ## Retrieve a list of media # curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/posts import json import pycurl import re from io import BytesIO import pandas as pd import datetime import urllib3 wpUrl = "https://MyWordPRessSite.COM</wp-json/wp/v2/media?page={}" bContinue = True page=1 while bContinue == True: buffer = BytesIO() c = pycurl.Curl() c.setopt(pycurl.SSL_VERIFYPEER, 0) c.setopt(c.WRITEDATA, buffer) c.setopt(c.HTTPHEADER,['Content-Type: application/json']) myUrl = wpUrl.format(page) #print(myUrl) c.setopt(c.URL,myUrl) c.perform() page+= 1 if buffer != None: myData = json.loads(buffer.getvalue()) for foo in myData: print("MediaID ={}, caption = {}, alt_text={}".format(foo["id"], foo["caption"], foo['alt_text'])) #print(foo) if len(myData) <= 0: bContinue = False else: bContinue = False c.close() ``` **Step 2.** Create the post with the correct media ID ``` ###################################################### # Create A Post ###################################################### from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods.posts import NewPost #authenticate wp_url = "https://info-qa.cloudquant.com/xmlrpc.php" wp_username = "My_User_ID_on_WP" wp_password = "My_PWD_on_WP" wp = Client(wp_url, wp_username, wp_password) #post and activate new post post = WordPressPost() post.title = '3 Post' post.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.' post.post_status = 'draft' post.thumbnail = 50 # The ID of the image determined in Step 1 post.slug = "123abc" post.terms_names = { 'post_tag': ['MyTag'], 'category': ['Category'] } wp.call(NewPost(post)) ```
272,968
<p>I am running some calculations on custom field data using wp_query on a large number of posts and it is taking a long time to load the result. I was advised by a user here to take advantage of wp cron to run these calculations once daily.</p> <p>What I've been unable to wrap my head around is - if I create an action which contains all of this code, set it to run once daily, and call this action in a template file, won't those queries then recalculate every time that template is loaded?</p> <p>My intended result is for the result of the queries to display on a template, but only actually recalculate when initiated by cron.</p> <p>I feel I'm missing something simple here but all examples of wp cron I can find don't appear to cover my use case.</p>
[ { "answer_id": 273086, "author": "cooldude101", "author_id": 123580, "author_profile": "https://wordpress.stackexchange.com/users/123580", "pm_score": 1, "selected": false, "text": "<p>I found my problem and just passing it on in case someone googles this.</p>\n\n<p>You need to pass the ...
2017/07/11
[ "https://wordpress.stackexchange.com/questions/272968", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105873/" ]
I am running some calculations on custom field data using wp\_query on a large number of posts and it is taking a long time to load the result. I was advised by a user here to take advantage of wp cron to run these calculations once daily. What I've been unable to wrap my head around is - if I create an action which contains all of this code, set it to run once daily, and call this action in a template file, won't those queries then recalculate every time that template is loaded? My intended result is for the result of the queries to display on a template, but only actually recalculate when initiated by cron. I feel I'm missing something simple here but all examples of wp cron I can find don't appear to cover my use case.
In order to have your post have a default image, you need to set your post thumbnail. In doing this you need to set the ID of the media, which isn't readily apparent. I do most of my work in Python, so for me, the following helps: **Step 1.** Get the list of all your media so you know the IDs ``` ## ## Retrieve a list of media # curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/posts import json import pycurl import re from io import BytesIO import pandas as pd import datetime import urllib3 wpUrl = "https://MyWordPRessSite.COM</wp-json/wp/v2/media?page={}" bContinue = True page=1 while bContinue == True: buffer = BytesIO() c = pycurl.Curl() c.setopt(pycurl.SSL_VERIFYPEER, 0) c.setopt(c.WRITEDATA, buffer) c.setopt(c.HTTPHEADER,['Content-Type: application/json']) myUrl = wpUrl.format(page) #print(myUrl) c.setopt(c.URL,myUrl) c.perform() page+= 1 if buffer != None: myData = json.loads(buffer.getvalue()) for foo in myData: print("MediaID ={}, caption = {}, alt_text={}".format(foo["id"], foo["caption"], foo['alt_text'])) #print(foo) if len(myData) <= 0: bContinue = False else: bContinue = False c.close() ``` **Step 2.** Create the post with the correct media ID ``` ###################################################### # Create A Post ###################################################### from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods.posts import NewPost #authenticate wp_url = "https://info-qa.cloudquant.com/xmlrpc.php" wp_username = "My_User_ID_on_WP" wp_password = "My_PWD_on_WP" wp = Client(wp_url, wp_username, wp_password) #post and activate new post post = WordPressPost() post.title = '3 Post' post.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.' post.post_status = 'draft' post.thumbnail = 50 # The ID of the image determined in Step 1 post.slug = "123abc" post.terms_names = { 'post_tag': ['MyTag'], 'category': ['Category'] } wp.call(NewPost(post)) ```
272,997
<p>I'm trying to achieve simple result. Run main loop 2 times, but first time for the one post with different layout, and second time for the rest posts with different layout. I found that condition <strong>1 > $wp_query->current_post</strong> can show only the first post in my loop. But when I run loop again it starts with 3rd post and skipping the 2nd.</p> <p>Here is the code:</p> <pre><code>&lt;!-- Full Post --&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); // first post if( 1 &gt; $wp_query-&gt;current_post ): get_template_part( 'template-parts/content', get_post_format() ); else : break; endif; endwhile; ?&gt; &lt;!-- Small Posts --&gt; &lt;div class="row"&gt; &lt;?php while( have_posts() ) : the_post(); get_template_part( 'template-parts/post-small', get_post_format() ); endwhile; ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 273086, "author": "cooldude101", "author_id": 123580, "author_profile": "https://wordpress.stackexchange.com/users/123580", "pm_score": 1, "selected": false, "text": "<p>I found my problem and just passing it on in case someone googles this.</p>\n\n<p>You need to pass the ...
2017/07/11
[ "https://wordpress.stackexchange.com/questions/272997", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112255/" ]
I'm trying to achieve simple result. Run main loop 2 times, but first time for the one post with different layout, and second time for the rest posts with different layout. I found that condition **1 > $wp\_query->current\_post** can show only the first post in my loop. But when I run loop again it starts with 3rd post and skipping the 2nd. Here is the code: ``` <!-- Full Post --> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); // first post if( 1 > $wp_query->current_post ): get_template_part( 'template-parts/content', get_post_format() ); else : break; endif; endwhile; ?> <!-- Small Posts --> <div class="row"> <?php while( have_posts() ) : the_post(); get_template_part( 'template-parts/post-small', get_post_format() ); endwhile; ?> </div> ```
In order to have your post have a default image, you need to set your post thumbnail. In doing this you need to set the ID of the media, which isn't readily apparent. I do most of my work in Python, so for me, the following helps: **Step 1.** Get the list of all your media so you know the IDs ``` ## ## Retrieve a list of media # curl -X OPTIONS -i http://demo.wp-api.org/wp-json/wp/v2/posts import json import pycurl import re from io import BytesIO import pandas as pd import datetime import urllib3 wpUrl = "https://MyWordPRessSite.COM</wp-json/wp/v2/media?page={}" bContinue = True page=1 while bContinue == True: buffer = BytesIO() c = pycurl.Curl() c.setopt(pycurl.SSL_VERIFYPEER, 0) c.setopt(c.WRITEDATA, buffer) c.setopt(c.HTTPHEADER,['Content-Type: application/json']) myUrl = wpUrl.format(page) #print(myUrl) c.setopt(c.URL,myUrl) c.perform() page+= 1 if buffer != None: myData = json.loads(buffer.getvalue()) for foo in myData: print("MediaID ={}, caption = {}, alt_text={}".format(foo["id"], foo["caption"], foo['alt_text'])) #print(foo) if len(myData) <= 0: bContinue = False else: bContinue = False c.close() ``` **Step 2.** Create the post with the correct media ID ``` ###################################################### # Create A Post ###################################################### from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods.posts import NewPost #authenticate wp_url = "https://info-qa.cloudquant.com/xmlrpc.php" wp_username = "My_User_ID_on_WP" wp_password = "My_PWD_on_WP" wp = Client(wp_url, wp_username, wp_password) #post and activate new post post = WordPressPost() post.title = '3 Post' post.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.' post.post_status = 'draft' post.thumbnail = 50 # The ID of the image determined in Step 1 post.slug = "123abc" post.terms_names = { 'post_tag': ['MyTag'], 'category': ['Category'] } wp.call(NewPost(post)) ```
273,063
<p>I don't know exactly how is the correct name, but i want to create my own table like the default wordpress table : </p> <p><a href="https://i.stack.imgur.com/WCgaY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WCgaY.png" alt="enter image description here"></a></p> <p>I wanted to ask, does the WordPress provide some API to create it?</p>
[ { "answer_id": 273068, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>Did you already create your custom post type? Or were you trying to modify what appears on that page? </p>\n\n...
2017/07/11
[ "https://wordpress.stackexchange.com/questions/273063", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121651/" ]
I don't know exactly how is the correct name, but i want to create my own table like the default wordpress table : [![enter image description here](https://i.stack.imgur.com/WCgaY.png)](https://i.stack.imgur.com/WCgaY.png) I wanted to ask, does the WordPress provide some API to create it?
I'm not an expert on this but I did get into it a little recently. Take a look at this tutorial: <http://wpengineer.com/2426/wp_list_table-a-step-by-step-guide/> Basically, you'll want to create a class that extends `WP_List_Table`: ``` class My_List_Table extends WP_List_Table { // what your table is all about } $myListTable = new My__List_Table(); ``` It is an involved process, but that tutorial seems pretty good. Good luck!
273,078
<p>I'm trying to add a link to each item of the Users table in the WP Admin area and use that link to send that specific user an email. I'm most of the way there but I'm having some odd behavior that I can't figure out. Here's my code: (I describe my issues below that)</p> <pre><code>// Adds "Send rejection email" action to Users page function jm_send_rejection_link($actions, $user_object) { if( ($_POST['send']) &amp;&amp; ($_POST['email-address'] == $user_object-&gt;user_email) ) { $sendto = $_POST['email-address']; $sendsub = "Your registration has been rejected."; $sendmess = "Sorry! Your registration has been rejected. I guess someone doesn't like you."; $headers = array('From: The Company &lt;email@sample.com&gt;'); wp_mail($sendto, $sendsub, $sendmess, $headers); echo '&lt;div class="updated notice"&gt;&lt;p&gt;Success! The rejection email has been sent to ' . $_POST['email-address'] . '.&lt;/p&gt;&lt;/div&gt;'; } $actions['send_rejection'] = "&lt;form method='post' action=''&gt; &lt;input type='hidden' name='email-address' value='" . $user_object-&gt;user_email . "' /&gt; &lt;input type='submit' name='send' value='Send Rejection' /&gt; &lt;/form&gt;"; return $actions; } add_filter('user_row_actions', 'jm_send_rejection_link', 10, 2); </code></pre> <p>So this code adds the action link "Send Rejection Email" to each user in the table. It also successfully sends out the email... sometimes. For the first user in the table, it seems to fail and also it appends some unexpected stuff to the URL:</p> <pre><code>http://sampledomain.org/wp-admin/users.php?s&amp;action=-1&amp;new_role&amp;paged=1&amp;email-address=emailaddress%sampledomain.com&amp;send=Send+Rejection&amp;action2=-1&amp;new_role2 </code></pre> <p>It also does not display the success message in this case.</p> <p>For a number of the other users it does successfully display the success message and send the email. However, not for all other users. The other users display the success message but do not receive the email. It is possible that these accounts are just catching the email in a firewall or something, although it does not appear in spam. </p> <p>I am most concerned about whatever I'm doing wrong that is causing the issue with the first user. Any ideas?</p> <p>PS - I do recognize that my IF statement in there is a little weird. I guess because I'm adding this to <code>user_row_actions</code> it is running for every user on the table, which is why I am making that email send only for the user whose email matches the posted address. A little backwards I know. If I should break those into two different functions, any advice as to how to make that second function run on the user page without running for each user would be much appreciated.</p>
[ { "answer_id": 273068, "author": "rudtek", "author_id": 77767, "author_profile": "https://wordpress.stackexchange.com/users/77767", "pm_score": 0, "selected": false, "text": "<p>Did you already create your custom post type? Or were you trying to modify what appears on that page? </p>\n\n...
2017/07/11
[ "https://wordpress.stackexchange.com/questions/273078", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/117675/" ]
I'm trying to add a link to each item of the Users table in the WP Admin area and use that link to send that specific user an email. I'm most of the way there but I'm having some odd behavior that I can't figure out. Here's my code: (I describe my issues below that) ``` // Adds "Send rejection email" action to Users page function jm_send_rejection_link($actions, $user_object) { if( ($_POST['send']) && ($_POST['email-address'] == $user_object->user_email) ) { $sendto = $_POST['email-address']; $sendsub = "Your registration has been rejected."; $sendmess = "Sorry! Your registration has been rejected. I guess someone doesn't like you."; $headers = array('From: The Company <email@sample.com>'); wp_mail($sendto, $sendsub, $sendmess, $headers); echo '<div class="updated notice"><p>Success! The rejection email has been sent to ' . $_POST['email-address'] . '.</p></div>'; } $actions['send_rejection'] = "<form method='post' action=''> <input type='hidden' name='email-address' value='" . $user_object->user_email . "' /> <input type='submit' name='send' value='Send Rejection' /> </form>"; return $actions; } add_filter('user_row_actions', 'jm_send_rejection_link', 10, 2); ``` So this code adds the action link "Send Rejection Email" to each user in the table. It also successfully sends out the email... sometimes. For the first user in the table, it seems to fail and also it appends some unexpected stuff to the URL: ``` http://sampledomain.org/wp-admin/users.php?s&action=-1&new_role&paged=1&email-address=emailaddress%sampledomain.com&send=Send+Rejection&action2=-1&new_role2 ``` It also does not display the success message in this case. For a number of the other users it does successfully display the success message and send the email. However, not for all other users. The other users display the success message but do not receive the email. It is possible that these accounts are just catching the email in a firewall or something, although it does not appear in spam. I am most concerned about whatever I'm doing wrong that is causing the issue with the first user. Any ideas? PS - I do recognize that my IF statement in there is a little weird. I guess because I'm adding this to `user_row_actions` it is running for every user on the table, which is why I am making that email send only for the user whose email matches the posted address. A little backwards I know. If I should break those into two different functions, any advice as to how to make that second function run on the user page without running for each user would be much appreciated.
I'm not an expert on this but I did get into it a little recently. Take a look at this tutorial: <http://wpengineer.com/2426/wp_list_table-a-step-by-step-guide/> Basically, you'll want to create a class that extends `WP_List_Table`: ``` class My_List_Table extends WP_List_Table { // what your table is all about } $myListTable = new My__List_Table(); ``` It is an involved process, but that tutorial seems pretty good. Good luck!
273,084
<p>I have a situation where my search is working but the client just came with a request I hadn't considered. If you search by first name (eg. john) or last name (eg. doe), this will absolutely bring your result. But if you search for their full name (eg. john doe), you get 0 results.</p> <p>I've looked around but I can't seem to find a way to compare the search to "first_name last_name".</p> <p>I've scanned through the similar questions on the forum but they aren't helping / seem to go in a different direction entirely. If anyone has any knowledge, or can point me to the right thread, I'd be grateful.</p> <p>Here's the summary of my code:</p> <pre><code>$args = array( 'role' =&gt; 'Subscriber', 'meta_query' =&gt; array( array( 'key' =&gt; 'membership_class', 'value' =&gt; 'Full', 'compare' =&gt; '=', 'type' =&gt; 'CHAR', ), array( 'relation' =&gt; 'OR', array( 'key' =&gt; 'first_name', 'value' =&gt; $usersearch, 'compare' =&gt; 'LIKE' ), array( 'key' =&gt; 'last_name', 'value' =&gt; $usersearch, 'compare' =&gt; 'LIKE' ), array( 'key' =&gt; 'personal_city', 'value' =&gt; $usersearch, 'compare' =&gt; 'LIKE', 'type' =&gt; 'CHAR', ), array( 'key' =&gt; 'personal_province', 'value' =&gt; $usersearch, 'compare' =&gt; 'LIKE', 'type' =&gt; 'CHAR', ), array( 'key' =&gt; 'treatments', 'value' =&gt; $usersearch, 'compare' =&gt; 'LIKE', ), ), ), ); </code></pre>
[ { "answer_id": 273173, "author": "dbeja", "author_id": 9585, "author_profile": "https://wordpress.stackexchange.com/users/9585", "pm_score": 3, "selected": true, "text": "<p>What if you use IN operator and split the search term in a words array:</p>\n\n<pre><code>$args = array(\n 'rol...
2017/07/11
[ "https://wordpress.stackexchange.com/questions/273084", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76600/" ]
I have a situation where my search is working but the client just came with a request I hadn't considered. If you search by first name (eg. john) or last name (eg. doe), this will absolutely bring your result. But if you search for their full name (eg. john doe), you get 0 results. I've looked around but I can't seem to find a way to compare the search to "first\_name last\_name". I've scanned through the similar questions on the forum but they aren't helping / seem to go in a different direction entirely. If anyone has any knowledge, or can point me to the right thread, I'd be grateful. Here's the summary of my code: ``` $args = array( 'role' => 'Subscriber', 'meta_query' => array( array( 'key' => 'membership_class', 'value' => 'Full', 'compare' => '=', 'type' => 'CHAR', ), array( 'relation' => 'OR', array( 'key' => 'first_name', 'value' => $usersearch, 'compare' => 'LIKE' ), array( 'key' => 'last_name', 'value' => $usersearch, 'compare' => 'LIKE' ), array( 'key' => 'personal_city', 'value' => $usersearch, 'compare' => 'LIKE', 'type' => 'CHAR', ), array( 'key' => 'personal_province', 'value' => $usersearch, 'compare' => 'LIKE', 'type' => 'CHAR', ), array( 'key' => 'treatments', 'value' => $usersearch, 'compare' => 'LIKE', ), ), ), ); ```
What if you use IN operator and split the search term in a words array: ``` $args = array( 'role' => 'Subscriber', 'meta_query' => array( array( 'key' => 'membership_class', 'value' => 'Full', 'compare' => '=', 'type' => 'CHAR', ), array( 'relation' => 'OR', array( 'key' => 'first_name', 'value' => explode( ' ', $usersearch ), 'compare' => 'IN' ), array( 'key' => 'last_name', 'value' => explode( ' ', $usersearch ), 'compare' => 'IN' ), array( 'key' => 'personal_city', 'value' => $usersearch, 'compare' => 'LIKE', 'type' => 'CHAR', ), array( 'key' => 'personal_province', 'value' => $usersearch, 'compare' => 'LIKE', 'type' => 'CHAR', ), array( 'key' => 'treatments', 'value' => $usersearch, 'compare' => 'LIKE', ), ), ), ); ```
273,094
<p>I'm trying to register a new shortcode on my custom theme. </p> <p>In functions.php I have created a basic test function as follows</p> <pre><code>function get_second_image($atts) { echo ‘test’; } </code></pre> <p>And registered it right underneath</p> <pre><code>add_shortcode( ‘case_study_second_image_sc’, ‘get_second_image’ ); </code></pre> <p>Using the WYSIWYG editor I insert the shortcode [case_study_second_image_sc] but it just displays as the raw code on the page. </p> <p>I'm calling the page content using</p> <pre><code>&lt;?php the_content(); ?&gt; </code></pre> <p>in the template file.</p> <p>Based on info from another SE question I have searched my theme's files for any add or remove filter functions but there don't appear to be any that would be getting in the way. </p>
[ { "answer_id": 273096, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>See the documentation here <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow norefe...
2017/07/12
[ "https://wordpress.stackexchange.com/questions/273094", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123673/" ]
I'm trying to register a new shortcode on my custom theme. In functions.php I have created a basic test function as follows ``` function get_second_image($atts) { echo ‘test’; } ``` And registered it right underneath ``` add_shortcode( ‘case_study_second_image_sc’, ‘get_second_image’ ); ``` Using the WYSIWYG editor I insert the shortcode [case\_study\_second\_image\_sc] but it just displays as the raw code on the page. I'm calling the page content using ``` <?php the_content(); ?> ``` in the template file. Based on info from another SE question I have searched my theme's files for any add or remove filter functions but there don't appear to be any that would be getting in the way.
Make sure to use straight quotes, e.g. `'` or `"` and not curly quotes `‘`, `’`, `“`, or `”` for strings. Also, shortcodes should return their output, not echo it. When WordPress finds a shortcode without a callback, it displays the shortcode tag just as it was entered e.g. `[case_study_second_image_sc]`. The shortcode tag `‘case_study_second_image_sc’` and the associated [callback](https://codex.wordpress.org/How_to_Pass_Tag_Parameters#Callable) `‘get_second_image’` will be parsed as constants by PHP. This means we won't have a valid shortcode tag or callback function for our shortcode and WP will just output the shortcode as it was entered by the user. Turning on error reporting helps to find these tricky errors (sometimes curly quotes appear in copy/pasted code and it can be difficult to differentiate quotes in some editors). > > > ``` > Use of undefined constant ‘case_study_second_image_sc’ - assumed '‘case_study_second_image_sc’' > > Use of undefined constant ‘get_second_image’ - assumed '‘get_second_image’' > > ``` > >
273,112
<p>I have been working on trying to get data to store and display on a CPT field. The code I have is here:</p> <pre><code>function fhaac_subject_box_callback( $post ){ wp_nonce_field( basename(__FILE__ ), 'fhacc_subject_nounce'); $fhaac_stored_subject_meta = get_post_meta( '$post-&gt;ID' ); ?&gt; &lt;div&gt;Subject name: &lt;input type="text" name="fhaac_subject_name" id="fhaac_ subject_name" value="&lt;?php if ( ! empty ( $fhaac_stored_subject_meta ['fhaac_subject_name']) ) echo esc_attr ( $fhaac_stored_subject_meta ['fhaac_subject_name'][0] ); ?&gt;"/&gt;&lt;/div&gt; </code></pre> <p>I have set the <code>save_post</code> into a function below: </p> <pre><code>function fhaac_save_subject_meta( $post_id ){ //Checking save status $is_autosave = wp_is_post_autosave( $post_id ); $is_revision = wp_is_post_revision( $post_id ); $is_valid_nonce = ( isset( $_POST[ 'fhacc_subject_nounce' ] ) &amp;&amp; wp_verify_nonce( $_POST[ 'fhacc_subject_nounce' ], basename(__FILE__ )))?'true' : 'false'; //Exit scripts depending on save status if ( $is_autosave || $is_revision || !$is_valid_nonce){ return; } if ( isset( $_POST['fhaac_subject_name'])){ update_post_meta( $post_id, 'fhaac_subject_name', sanitize_text_field($_POST['fhaac_subject_name'])); } </code></pre> <p>But either the data isn't saving, or being returned. The issue is, I have this working on a <code>wp_editor</code> field. I'm still fairly new to this, so any help would be really appreciated. </p> <p>Thanks in advance!</p>
[ { "answer_id": 273096, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>See the documentation here <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow norefe...
2017/07/12
[ "https://wordpress.stackexchange.com/questions/273112", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/58313/" ]
I have been working on trying to get data to store and display on a CPT field. The code I have is here: ``` function fhaac_subject_box_callback( $post ){ wp_nonce_field( basename(__FILE__ ), 'fhacc_subject_nounce'); $fhaac_stored_subject_meta = get_post_meta( '$post->ID' ); ?> <div>Subject name: <input type="text" name="fhaac_subject_name" id="fhaac_ subject_name" value="<?php if ( ! empty ( $fhaac_stored_subject_meta ['fhaac_subject_name']) ) echo esc_attr ( $fhaac_stored_subject_meta ['fhaac_subject_name'][0] ); ?>"/></div> ``` I have set the `save_post` into a function below: ``` function fhaac_save_subject_meta( $post_id ){ //Checking save status $is_autosave = wp_is_post_autosave( $post_id ); $is_revision = wp_is_post_revision( $post_id ); $is_valid_nonce = ( isset( $_POST[ 'fhacc_subject_nounce' ] ) && wp_verify_nonce( $_POST[ 'fhacc_subject_nounce' ], basename(__FILE__ )))?'true' : 'false'; //Exit scripts depending on save status if ( $is_autosave || $is_revision || !$is_valid_nonce){ return; } if ( isset( $_POST['fhaac_subject_name'])){ update_post_meta( $post_id, 'fhaac_subject_name', sanitize_text_field($_POST['fhaac_subject_name'])); } ``` But either the data isn't saving, or being returned. The issue is, I have this working on a `wp_editor` field. I'm still fairly new to this, so any help would be really appreciated. Thanks in advance!
Make sure to use straight quotes, e.g. `'` or `"` and not curly quotes `‘`, `’`, `“`, or `”` for strings. Also, shortcodes should return their output, not echo it. When WordPress finds a shortcode without a callback, it displays the shortcode tag just as it was entered e.g. `[case_study_second_image_sc]`. The shortcode tag `‘case_study_second_image_sc’` and the associated [callback](https://codex.wordpress.org/How_to_Pass_Tag_Parameters#Callable) `‘get_second_image’` will be parsed as constants by PHP. This means we won't have a valid shortcode tag or callback function for our shortcode and WP will just output the shortcode as it was entered by the user. Turning on error reporting helps to find these tricky errors (sometimes curly quotes appear in copy/pasted code and it can be difficult to differentiate quotes in some editors). > > > ``` > Use of undefined constant ‘case_study_second_image_sc’ - assumed '‘case_study_second_image_sc’' > > Use of undefined constant ‘get_second_image’ - assumed '‘get_second_image’' > > ``` > >
273,144
<p>Recently all of my REST-API requests suddenly turned to return a 404 error, Every request (no matter custom endpoint or built-in).</p> <p>Then I figured it's because of permalink's structure. <code>/wp-json/</code> is not accessible under plain permalink, since there is simply no redirect rule available at the moment.</p> <p>Is it possible to use the REST endpoints in this situation? Both custom and built-in.</p>
[ { "answer_id": 273147, "author": "kraftner", "author_id": 47733, "author_profile": "https://wordpress.stackexchange.com/users/47733", "pm_score": 5, "selected": true, "text": "<p>Yes you can. Just add the <code>rest_route</code> query parameter.</p>\n\n<p>So</p>\n\n<p><a href=\"https://w...
2017/07/12
[ "https://wordpress.stackexchange.com/questions/273144", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94498/" ]
Recently all of my REST-API requests suddenly turned to return a 404 error, Every request (no matter custom endpoint or built-in). Then I figured it's because of permalink's structure. `/wp-json/` is not accessible under plain permalink, since there is simply no redirect rule available at the moment. Is it possible to use the REST endpoints in this situation? Both custom and built-in.
Yes you can. Just add the `rest_route` query parameter. So <https://wordpress.org/wp-json/> would become <https://wordpress.org/?rest_route=/> Or `https://wordpress.org/wp-json/wp/v2/` would become `https://wordpress.org/?rest_route=/wp/v2` to give you a more complete example. So you're wondering how to decide which one to use? Worry no more, there's a function for that: [`get_rest_url()`](https://developer.wordpress.org/reference/functions/get_rest_url/) Another option is the fact that by default there is a `<link>` in the header that gives you the API root. ``` <link rel='https://api.w.org/' href='https://wordpress.org/wp-json/' /> ``` So in case you need to figure that out from client side JS just use something along the lines of ``` document.querySelectorAll('link[rel="https://api.w.org/"]')[0].getAttribute('href'); ``` --- So basically you shouldn't take the `wp-json` part as given (and hardcode it) but always build it dynamically either using `get_rest_url()` or the JS approach mentioned above.
273,165
<p>I am trying to display a taxonomy term's image and need the term's ID. For some reason I am having trouble getting the ID. If I hard-code the ID in place of <code>$term_id</code> everything works as expected, but of course that doesn't help in a template.</p> <p>For reference, my taxonomy is <code>Organizations</code> and each entry is the name of an organization.</p> <p>This is the first time I've really gotten into WordPress functions and templates.</p> <p>Here's what I have:</p> <pre><code> &lt;?php $terms = get_field('listing_organization'); $term_id = get_queried_object_id(); if( $terms ): ?&gt; &lt;ul&gt; &lt;?php foreach( $terms as $term ): ?&gt; &lt;img src="&lt;?php echo z_taxonomy_image_url($term_id, thumbnail); ?&gt;" /&gt; &lt;h2&gt;&lt;a href="&lt;?php echo get_term_link( $term ); ?&gt;"&gt;&lt;?php echo $term-&gt;name; ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;&lt;?php echo $term-&gt;description; ?&gt;&lt;/p&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 273168, "author": "dbeja", "author_id": 9585, "author_profile": "https://wordpress.stackexchange.com/users/9585", "pm_score": 0, "selected": false, "text": "<p>Are you using this on an archive page?</p>\n\n<p>Try to get the term ID with this instead:</p>\n\n<pre><code>$que...
2017/07/12
[ "https://wordpress.stackexchange.com/questions/273165", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123721/" ]
I am trying to display a taxonomy term's image and need the term's ID. For some reason I am having trouble getting the ID. If I hard-code the ID in place of `$term_id` everything works as expected, but of course that doesn't help in a template. For reference, my taxonomy is `Organizations` and each entry is the name of an organization. This is the first time I've really gotten into WordPress functions and templates. Here's what I have: ``` <?php $terms = get_field('listing_organization'); $term_id = get_queried_object_id(); if( $terms ): ?> <ul> <?php foreach( $terms as $term ): ?> <img src="<?php echo z_taxonomy_image_url($term_id, thumbnail); ?>" /> <h2><a href="<?php echo get_term_link( $term ); ?>"><?php echo $term->name; ?></a></h2> <p><?php echo $term->description; ?></p> <?php endforeach; ?> </ul> <?php endif; ?> ```
The term ID is contained within the term object you are already using in your loop: ``` echo z_taxonomy_image_url( $term->term_id, 'thumbnail' ); ```
273,194
<p>I want to prevent posts that dont have thumbnails from showing on the homepage, category page, archive, etc.</p> <p>Using something like </p> <pre><code>if (get_the_post_thumbnail_url() != "") { //don't insert post } </code></pre> <p>What filter / hook should I use?</p>
[ { "answer_id": 273206, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>What you asked for can be expensive. You can not check if a post has thumbnail or not unless the query is r...
2017/07/12
[ "https://wordpress.stackexchange.com/questions/273194", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123742/" ]
I want to prevent posts that dont have thumbnails from showing on the homepage, category page, archive, etc. Using something like ``` if (get_the_post_thumbnail_url() != "") { //don't insert post } ``` What filter / hook should I use?
> > What filter / hook should I use? > > > You can use the `pre_get_posts` action hook. Following [Tom's](https://wordpress.stackexchange.com/users/736/tom-j-nowell) comment on the question about querying for what you want, maybe set `meta_query` to `_thumbnail_id`. I would also `(` group `)` the conditionals to read: "Is *both* not admin and is main query, AND is either home, category, or archive." ``` add_action( 'pre_get_posts', 'thumbnails_only' ); function thumbnails_only( $query ) { if ( ( ! $query->is_admin && $query->is_main_query() ) && ( $query->is_home() || $query->is_category() || $query->is_archive() ) ) { $meta_query = array( array( 'key' => '_thumbnail_id', ) ); $query->set( 'meta_query', $meta_query ); } } ``` may want to replace `is_home()` with `is_front_page()` [depending on your site settings.](https://developer.wordpress.org/reference/functions/is_home/#usage)
273,239
<p><strong>Set-up</strong></p> <p>I have the following standard Adsense script inserted in my <code>header.php</code> file, </p> <pre><code>&lt;script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"&gt; &lt;/script&gt; &lt;script&gt; (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-********", enable_page_level_ads: true }); &lt;/script&gt; </code></pre> <p>This allows me to display ads on all pages instantly without too much hassle.</p> <p><hr> <strong>Problem</strong></p> <p>I'd like to prevent display of all adsense ads on specific pages of my website. </p> <p>I'm looking for some 'if' function to stop the display. Anyone knows of such a function?</p>
[ { "answer_id": 273247, "author": "SleepyAsh", "author_id": 123718, "author_profile": "https://wordpress.stackexchange.com/users/123718", "pm_score": 3, "selected": true, "text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/is_page/\" rel=\"nofollow norefe...
2017/07/13
[ "https://wordpress.stackexchange.com/questions/273239", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123057/" ]
**Set-up** I have the following standard Adsense script inserted in my `header.php` file, ``` <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"> </script> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-********", enable_page_level_ads: true }); </script> ``` This allows me to display ads on all pages instantly without too much hassle. --- **Problem** I'd like to prevent display of all adsense ads on specific pages of my website. I'm looking for some 'if' function to stop the display. Anyone knows of such a function?
You can use [this](https://developer.wordpress.org/reference/functions/is_page/ "this") function: ``` <?php if(is_page('your-page-slug')): ?> //do nothing on selected pages <?php else: ?> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" /> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-********", enable_page_level_ads: true }); </script> <?php endif; ?> ``` If you want to disable this on more than one page, just add them like this: ``` <?php if(is_page('your-page-slug1') || is_page('your-page-slug2')): ?> ``` Wordpress Developer Resources are very useful (more than codex), so i recommend checking them out first if you don't know how to do something
273,242
<p>So im currently developing a plugin, this plugin has a new CPT that i would like to exclude its menu from the admin page of the first site. Im using a multi-site installation. The menu has to only be visible to the other site admins but not the first one.</p> <p>The Link where i want to remove the menu from is www.example.com/wp-admin</p> <p>Thank you!</p>
[ { "answer_id": 273245, "author": "TMA", "author_id": 91044, "author_profile": "https://wordpress.stackexchange.com/users/91044", "pm_score": 0, "selected": false, "text": "<p>Wordpress <a href=\"https://codex.wordpress.org/WPMU_Functions/switch_to_blog\" rel=\"nofollow noreferrer\"><code...
2017/07/13
[ "https://wordpress.stackexchange.com/questions/273242", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121367/" ]
So im currently developing a plugin, this plugin has a new CPT that i would like to exclude its menu from the admin page of the first site. Im using a multi-site installation. The menu has to only be visible to the other site admins but not the first one. The Link where i want to remove the menu from is www.example.com/wp-admin Thank you!
When you register the custom post type, you can control whether the menu item appears with the `show_in_menu` arg. You could do something like the following ( this has not been tested ): ``` // create a constant to store the ID of the blog where the menu should be hidden. define('HIDDEN_MENU_BLOG_ID', 1 ); function codex_custom_init() { $show_in_menus = ( HIDDEN_MENU_BLOG_ID === get_current_blog_id() ) ? false : true; $args = array( 'public' => true, 'label' => 'Books' 'show_in_menu' => $show_in_menus, ); register_post_type( 'book', $args ); } add_action( 'init', 'codex_custom_init' ); ``` This is not very scalable however, you may want to couple this with an admin screen where a super-admin can choose which blogs to hide the menu from. Hope this helps!
273,264
<p>I am developing theme to sell on themefores. I want to get option values in the head. but as the checkoptions would not be called yet i need to call wp-load.php. but the reviewer from themeforest said wp-load.php should not be called in any case. so can you please guide me how can i do the same without requiring wp-load.php ? </p> <p>Here is my coede </p> <pre><code>&lt;?php $root = dirname(dirname(dirname(dirname(dirname(__FILE__))))); if ( file_exists( $root.'/wp-load.php' ) ) { require_once( $root.'/wp-load.php' ); } else { $root = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))); if ( file_exists( $root.'/wp-load.php' ) ) { require_once( $root.'/wp-load.php' ); } } $checkOpt = get_option('Bethaven'); header( "Content-type: text/css; charset: UTF-8" ); global $post; //Footer font color if (get_post_meta($post-&gt;ID, 'oebryn_footer_font_color', true) != '' ) { $footer_font_color = get_post_meta($post-&gt;ID, 'oebryn_footer_font_color', true); } elseif ( $checkOpt['oebryn_footer_font_color'] != '' ) { $footer_font_color = $checkOpt['oebryn_footer_font_color']; } // Footer link color if (get_post_meta($post-&gt;ID, 'oebryn_footer_link_color', true) != '' ) { $footer_font_color = get_post_meta($post-&gt;ID, 'oebryn_footer_link_color', true); } elseif ( $checkOpt['oebryn_footer_link_color'] != '' ) { $footer_font_color = $checkOpt['oebryn_footer_link_color']; } // Footer hovered color if (get_post_meta($post-&gt;ID, 'oebryn_footer_link_hover', true) != '' ) { $footer_hovered = get_post_meta($post-&gt;ID, 'oebryn_footer_link_hover', true); } elseif ( $checkOpt['oebryn_footer_link_hover'] != '' ) { $footer_hovered = $checkOpt['oebryn_footer_link_hover']; } // Widget title color if (get_post_meta($post-&gt;ID, 'oebryn_footer_widget_title', true) != '' ) { $footer_title = get_post_meta($post-&gt;ID, 'oebryn_footer_widget_title', true); } elseif ( $checkOpt['oebryn_footer_widget_title'] != '' ) { $footer_title = $checkOpt['oebryn_footer_widget_title']; } ?&gt; #header-bar nav ul#oebryn-navigation &gt; li &gt;a { color: &lt;?php echo esc_attr($checkOpt['oebryn_header_color'] );?&gt; !important; } #oebryn-navigation ul.sub-menu { background-color: &lt;?php echo esc_attr($checkOpt['oebryn_submenu_background']); ?&gt; !important; } #header-bar ul#oebryn-navigation li ul.sub-menu li ul.sub-menu a, #header-bar ul#oebryn-navigation li ul.sub-menu li a { color: &lt;?php echo esc_attr($checkOpt['oebryn_submenu_color'] );?&gt; !important; } ul#oebryn-navigation li ul.sub-menu li ul.sub-menu li:hover, #header-bar ul#oebryn-navigation li ul.sub-menu li:hover { border-bottom: 1px &lt;?php echo esc_attr($checkOpt['oebryn_submenu_hover_color'] );?&gt; solid !important; } #header-bar ul#oebryn-navigation li.megamenu ul.sub-menu li &gt;a { color: &lt;?php echo esc_attr($checkOpt['oebryn_megamenu_titles'] );?&gt; !important; } .sticky { background-color: &lt;?php echo esc_attr($checkOpt['oebryn_sticky_background']['rgba'] );?&gt; !important; line-height: &lt;?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?&gt; !important; height: &lt;?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?&gt; !important; border-bottom: &lt;?php echo esc_attr($checkOpt['oebryn_sticky_border']); ?&gt; solid &lt;?php echo esc_attr($checkOpt['oebryn_sticky_border_color']['rgba']); ?&gt; !important; } #header-bar.sticky ul#oebryn-navigation li a { color: &lt;?php echo esc_attr($checkOpt['oebryn_sticky_font_color']['rgba']); ?&gt; !important; } #header-bar.sticky ul.second-menu li.header-cart { border-bottom: &lt;?php echo esc_attr($checkOpt['oebryn_sticky_border']); ?&gt; solid &lt;?php echo esc_attr($checkOpt['oebryn_sticky_border_color']['rgba']); ?&gt; !important; line-height: &lt;?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?&gt; !important; height: &lt;?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?&gt; !important; } .widget li, .widget li a , .contact-info-widget ul li &gt; i { color: &lt;?php echo esc_attr($footer_font_color); ?&gt;; } .widget li a:hover { color: &lt;?php echo esc_attr($footer_hovered); ?&gt;; } footer .widget h6 { color: &lt;?php echo esc_attr($footer_title); ?&gt;; } .mobile-menu-logo-wrapper { background-image: url('&lt;?php echo esc_url($checkOpt['oebryn_mobile_menu_background_image']['url']) ?&gt;'); background-color: &lt;?php echo esc_url($checkOpt['oebryn_mobile_menu_background']); ?&gt;; } .mobile-menu-logo-inner { background-color: &lt;?php echo esc_attr($checkOpt['oebryn_mobile_menu_background_overlay']['rgba']); ?&gt;; } .menu-parent, .mobile-menu-cart .mobile-menu-meta &gt; p &gt; a.menu-checkout { background-color: &lt;?php echo esc_attr($checkOpt['oebryn_mobile_menu_background'] );?&gt; !important; } .ul.mobile-menu-cart-items li, .oebryn-mobile-menuwrapper li a, .mobile-menu-cart .mobile-menu-meta &gt; p &gt; a.menu-checkout { color: &lt;?php echo esc_attr($checkOpt['oebryn_mobile_menu_fontcolor']) ;?&gt; !important; } </code></pre>
[ { "answer_id": 273252, "author": "satibel", "author_id": 123782, "author_profile": "https://wordpress.stackexchange.com/users/123782", "pm_score": 2, "selected": false, "text": "<p>Disclaimer: I haven't used this, but from the description it looks like a good fit.</p>\n\n<hr>\n\n<p>The <...
2017/07/13
[ "https://wordpress.stackexchange.com/questions/273264", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123788/" ]
I am developing theme to sell on themefores. I want to get option values in the head. but as the checkoptions would not be called yet i need to call wp-load.php. but the reviewer from themeforest said wp-load.php should not be called in any case. so can you please guide me how can i do the same without requiring wp-load.php ? Here is my coede ``` <?php $root = dirname(dirname(dirname(dirname(dirname(__FILE__))))); if ( file_exists( $root.'/wp-load.php' ) ) { require_once( $root.'/wp-load.php' ); } else { $root = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))); if ( file_exists( $root.'/wp-load.php' ) ) { require_once( $root.'/wp-load.php' ); } } $checkOpt = get_option('Bethaven'); header( "Content-type: text/css; charset: UTF-8" ); global $post; //Footer font color if (get_post_meta($post->ID, 'oebryn_footer_font_color', true) != '' ) { $footer_font_color = get_post_meta($post->ID, 'oebryn_footer_font_color', true); } elseif ( $checkOpt['oebryn_footer_font_color'] != '' ) { $footer_font_color = $checkOpt['oebryn_footer_font_color']; } // Footer link color if (get_post_meta($post->ID, 'oebryn_footer_link_color', true) != '' ) { $footer_font_color = get_post_meta($post->ID, 'oebryn_footer_link_color', true); } elseif ( $checkOpt['oebryn_footer_link_color'] != '' ) { $footer_font_color = $checkOpt['oebryn_footer_link_color']; } // Footer hovered color if (get_post_meta($post->ID, 'oebryn_footer_link_hover', true) != '' ) { $footer_hovered = get_post_meta($post->ID, 'oebryn_footer_link_hover', true); } elseif ( $checkOpt['oebryn_footer_link_hover'] != '' ) { $footer_hovered = $checkOpt['oebryn_footer_link_hover']; } // Widget title color if (get_post_meta($post->ID, 'oebryn_footer_widget_title', true) != '' ) { $footer_title = get_post_meta($post->ID, 'oebryn_footer_widget_title', true); } elseif ( $checkOpt['oebryn_footer_widget_title'] != '' ) { $footer_title = $checkOpt['oebryn_footer_widget_title']; } ?> #header-bar nav ul#oebryn-navigation > li >a { color: <?php echo esc_attr($checkOpt['oebryn_header_color'] );?> !important; } #oebryn-navigation ul.sub-menu { background-color: <?php echo esc_attr($checkOpt['oebryn_submenu_background']); ?> !important; } #header-bar ul#oebryn-navigation li ul.sub-menu li ul.sub-menu a, #header-bar ul#oebryn-navigation li ul.sub-menu li a { color: <?php echo esc_attr($checkOpt['oebryn_submenu_color'] );?> !important; } ul#oebryn-navigation li ul.sub-menu li ul.sub-menu li:hover, #header-bar ul#oebryn-navigation li ul.sub-menu li:hover { border-bottom: 1px <?php echo esc_attr($checkOpt['oebryn_submenu_hover_color'] );?> solid !important; } #header-bar ul#oebryn-navigation li.megamenu ul.sub-menu li >a { color: <?php echo esc_attr($checkOpt['oebryn_megamenu_titles'] );?> !important; } .sticky { background-color: <?php echo esc_attr($checkOpt['oebryn_sticky_background']['rgba'] );?> !important; line-height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important; height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important; border-bottom: <?php echo esc_attr($checkOpt['oebryn_sticky_border']); ?> solid <?php echo esc_attr($checkOpt['oebryn_sticky_border_color']['rgba']); ?> !important; } #header-bar.sticky ul#oebryn-navigation li a { color: <?php echo esc_attr($checkOpt['oebryn_sticky_font_color']['rgba']); ?> !important; } #header-bar.sticky ul.second-menu li.header-cart { border-bottom: <?php echo esc_attr($checkOpt['oebryn_sticky_border']); ?> solid <?php echo esc_attr($checkOpt['oebryn_sticky_border_color']['rgba']); ?> !important; line-height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important; height: <?php echo esc_attr($checkOpt['oebryn_sticky_height']); ?> !important; } .widget li, .widget li a , .contact-info-widget ul li > i { color: <?php echo esc_attr($footer_font_color); ?>; } .widget li a:hover { color: <?php echo esc_attr($footer_hovered); ?>; } footer .widget h6 { color: <?php echo esc_attr($footer_title); ?>; } .mobile-menu-logo-wrapper { background-image: url('<?php echo esc_url($checkOpt['oebryn_mobile_menu_background_image']['url']) ?>'); background-color: <?php echo esc_url($checkOpt['oebryn_mobile_menu_background']); ?>; } .mobile-menu-logo-inner { background-color: <?php echo esc_attr($checkOpt['oebryn_mobile_menu_background_overlay']['rgba']); ?>; } .menu-parent, .mobile-menu-cart .mobile-menu-meta > p > a.menu-checkout { background-color: <?php echo esc_attr($checkOpt['oebryn_mobile_menu_background'] );?> !important; } .ul.mobile-menu-cart-items li, .oebryn-mobile-menuwrapper li a, .mobile-menu-cart .mobile-menu-meta > p > a.menu-checkout { color: <?php echo esc_attr($checkOpt['oebryn_mobile_menu_fontcolor']) ;?> !important; } ```
There is actually a plugin that offers this exact functionality: [Polylang User Manager](http://wooexperts.com/plugins/polylang-user-manager/): > > Polylang User Manager will work with Polylang WordPress multilingual Plugin, it will allow you to restrict access for editors/shop\_manager or other user role based on languages they’re not assigned as Translators or editor. > > >
273,289
<p>Using the plugin "Advanced Custom Fields": <a href="https://wordpress.org/plugins/advanced-custom-fields/" rel="nofollow noreferrer">https://wordpress.org/plugins/advanced-custom-fields/</a> I am able to add my custom fields to profile.php.</p> <p><strong>But how do I remove the default elements from profile.php (Personal Options, Name, etc.)?</strong></p> <p>I know I can create new template files in my child theme to override how pages look, but I can't find how to do this with profile.php.</p> <p>I started using CSS to hide the elements, this works except for the titles which have no class or ID, and I can't simply hide the entire form because Advanced Custom Fields places the new elements in this same form.</p> <p>I would prefer to stay away from large plugins that create front end user accounts on top of the existing system just so I can get a customized profile editing page.</p> <p>Thanks for any help.</p>
[ { "answer_id": 273304, "author": "Charles", "author_id": 15605, "author_profile": "https://wordpress.stackexchange.com/users/15605", "pm_score": 2, "selected": true, "text": "<p>There are probably several options to achieve your goal, below is one of the options shown by me.<br />\n<em>(...
2017/07/13
[ "https://wordpress.stackexchange.com/questions/273289", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123624/" ]
Using the plugin "Advanced Custom Fields": <https://wordpress.org/plugins/advanced-custom-fields/> I am able to add my custom fields to profile.php. **But how do I remove the default elements from profile.php (Personal Options, Name, etc.)?** I know I can create new template files in my child theme to override how pages look, but I can't find how to do this with profile.php. I started using CSS to hide the elements, this works except for the titles which have no class or ID, and I can't simply hide the entire form because Advanced Custom Fields places the new elements in this same form. I would prefer to stay away from large plugins that create front end user accounts on top of the existing system just so I can get a customized profile editing page. Thanks for any help.
There are probably several options to achieve your goal, below is one of the options shown by me. *(these 2 functions belong to each other)* > > Please make always a copy of `functions.php` before you start to edit/add a plugin or other code snippet. > > > ``` /** * Remove fields from an user profile page for all except Administrator * * FYI {@link https://codex.wordpress.org/Function_Reference/current_user_can} * {@link https://codex.wordpress.org/Roles_and_Capabilities} * {@link https://codex.wordpress.org/Plugin_API/Action_Reference/admin_footer} * {@link https://developer.wordpress.org/reference/hooks/load-pagenow/} * * Checked with @version WordPress 4.8 */ add_action('admin_init', 'wpse273289_remove_profile_fields' ); function wpse273289_remove_profile_fields() { global $pagenow; // apply only to user profile or user edit pages if( $pagenow !=='profile.php' && $pagenow !=='user-edit.php' ) { return; } // Make it happen for all except Administrators if( current_user_can( 'manage_options' ) ) { return; } add_action( 'admin_footer', 'wpse273289_remove_profile_fields_js' ); } /** * Remove (below)selected fields on user profile * This function belongs to the wpse273289_remove_profile_fields function! * */ function wpse273289_remove_profile_fields_js() { ?> <script> jQuery(document).ready( function($) { $('input#user_login').closest('tr').remove(); // Username $('input#first_name').closest('tr').remove(); // First Name $('input#nickname').closest('tr').remove(); // Nickname (required) $('input#email').closest('tr').remove(); // Email (required) }); </script> <?php } ``` > > The fields above in the script are just examples so please adjust to your own preference. > Both functions are checked in a local sandbox and working for me. > > > > > > > > Note: above is NOT tested with ACF plugin but that should not be a problem. > > > > > > > > >
273,302
<p>I'm getting an error on the admin screen for the custom post type. I've searched lots of other answers but see nothing in my code that could be causing it. Here's my code. Any help would be greatly appreciated.</p> <pre><code>// Register the post types and taxonomys add_action('init', 'register_post_types'); function register_post_types(){ // Property Post Type $labels = array( 'name' =&gt; __('Properties'), 'singular_name' =&gt; __('Property'), 'add_new' =&gt; __('Add New'), 'add_new_item' =&gt; __('Add New Property'), 'edit_item' =&gt; __('Edit Property'), 'new_item' =&gt; __('New Property'), 'view_item' =&gt; __('View Property'), 'search_items' =&gt; __('Search Properties'), 'not_found' =&gt; __('Nothing found'), 'not_found_in_trash' =&gt; __('Nothing found in Trash'), 'parent_item_colon' =&gt; '', ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'register_meta_box_cb' =&gt; 'custom_meta_boxes', 'query_var' =&gt; true, 'menu_icon' =&gt; null, 'rewrite' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; false, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title', 'editor', 'genesis-seo', 'thumbnail','genesis-cpt-archives-settings' ), 'has_archive' =&gt; true, ); register_post_type('property' , $args); // Property Taxonomy $taxononmy_args = array( 'hierarchical' =&gt; true, 'label' =&gt; "Categories", 'singular_label' =&gt; "Category", 'rewrite' =&gt; true, 'show_admin_column' =&gt; TRUE ); register_taxonomy("property_categories", array("property"), $taxononmy_args); } </code></pre>
[ { "answer_id": 273325, "author": "Sddarter", "author_id": 62082, "author_profile": "https://wordpress.stackexchange.com/users/62082", "pm_score": 1, "selected": false, "text": "<p>I've removed the custom_meta_boxes. I don't have to have them and it solves the problem. I still don't under...
2017/07/13
[ "https://wordpress.stackexchange.com/questions/273302", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/62082/" ]
I'm getting an error on the admin screen for the custom post type. I've searched lots of other answers but see nothing in my code that could be causing it. Here's my code. Any help would be greatly appreciated. ``` // Register the post types and taxonomys add_action('init', 'register_post_types'); function register_post_types(){ // Property Post Type $labels = array( 'name' => __('Properties'), 'singular_name' => __('Property'), 'add_new' => __('Add New'), 'add_new_item' => __('Add New Property'), 'edit_item' => __('Edit Property'), 'new_item' => __('New Property'), 'view_item' => __('View Property'), 'search_items' => __('Search Properties'), 'not_found' => __('Nothing found'), 'not_found_in_trash' => __('Nothing found in Trash'), 'parent_item_colon' => '', ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'register_meta_box_cb' => 'custom_meta_boxes', 'query_var' => true, 'menu_icon' => null, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'genesis-seo', 'thumbnail','genesis-cpt-archives-settings' ), 'has_archive' => true, ); register_post_type('property' , $args); // Property Taxonomy $taxononmy_args = array( 'hierarchical' => true, 'label' => "Categories", 'singular_label' => "Category", 'rewrite' => true, 'show_admin_column' => TRUE ); register_taxonomy("property_categories", array("property"), $taxononmy_args); } ```
I've removed the custom\_meta\_boxes. I don't have to have them and it solves the problem. I still don't understand why they were a problem, but if I can do without them I will. I appreciate everyone's efforts. Note: rolling back to 4.7 made no difference.
273,322
<p>Right now I've got future posts displayed on my site, and I was using this code on each post to show when it was published.</p> <pre><code>&lt;?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?&gt; </code></pre> <p>Naturally it shows a post 2 days from now as 2 days ago. How might I fix it so it says "ago" and maybe "from now" where applicable?</p>
[ { "answer_id": 273326, "author": "mwz", "author_id": 121004, "author_profile": "https://wordpress.stackexchange.com/users/121004", "pm_score": 1, "selected": true, "text": "<p>I managed to figure it out</p>\n\n<pre><code>&lt;?php\n if ( get_post_status ( $ID ) == 'future' ) { \necho huma...
2017/07/13
[ "https://wordpress.stackexchange.com/questions/273322", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121004/" ]
Right now I've got future posts displayed on my site, and I was using this code on each post to show when it was published. ``` <?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?> ``` Naturally it shows a post 2 days from now as 2 days ago. How might I fix it so it says "ago" and maybe "from now" where applicable?
I managed to figure it out ``` <?php if ( get_post_status ( $ID ) == 'future' ) { echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' from now'; } else { echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?> ```
273,333
<p>The Admin Bar has a menu with shortcuts for adding new content.</p> <p>By default, it shows "Post", "Media", "Page" and "User".</p> <p><a href="https://i.stack.imgur.com/0ydcC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0ydcC.png" alt="enter image description here"></a></p> <p>I'm using <code>register_post_type</code> to register a new custom post type. I can use its <code>menu_position</code> property to change the position in the dashboard menu, but how can I reorder the shortcut link so it will show higher, instead of just above "User"?</p>
[ { "answer_id": 273388, "author": "Kudratullah", "author_id": 62726, "author_profile": "https://wordpress.stackexchange.com/users/62726", "pm_score": 0, "selected": false, "text": "<p>This section rendered via <code>wp_admin_bar_new_content_menu</code> (admin-bar.php <a href=\"https://cor...
2017/07/13
[ "https://wordpress.stackexchange.com/questions/273333", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22510/" ]
The Admin Bar has a menu with shortcuts for adding new content. By default, it shows "Post", "Media", "Page" and "User". [![enter image description here](https://i.stack.imgur.com/0ydcC.png)](https://i.stack.imgur.com/0ydcC.png) I'm using `register_post_type` to register a new custom post type. I can use its `menu_position` property to change the position in the dashboard menu, but how can I reorder the shortcut link so it will show higher, instead of just above "User"?
I had a similar situation. My custom post type showed up under the Admin Bar as **Artifact**, but my clients preferred it to be at the top of the list. Plus, the items for **Media** and **User** were not really needed. [![WordPress New menu before](https://i.stack.imgur.com/pI5kR.jpg)](https://i.stack.imgur.com/pI5kR.jpg) My approach was first to user [remove\_node](https://codex.wordpress.org/Function_Reference/remove_node) to take away all the ones except my custom post-type and then put back the ones I want with [add\_node](https://codex.wordpress.org/Function_Reference/remove_node) ``` add_action( 'wp_before_admin_bar_render', 'portfolio_adminbar' ); function portfolio_adminbar() { global $wp_admin_bar; // get node for New + menu node $new_content_node = $wp_admin_bar->get_node('new-content'); // change URL for node, edit for prefered link $new_content_node->href = admin_url( 'post-new.php?post_type=portfolio' ); // Update New + menu node $wp_admin_bar->add_node($new_content_node); // remove all items from New Content menu $wp_admin_bar->remove_node('new-post'); $wp_admin_bar->remove_node('new-media'); $wp_admin_bar->remove_node('new-page'); $wp_admin_bar->remove_node('new-user'); // add back the new Post link $args = array( 'id' => 'new-post', 'title' => 'Blog Post', 'parent' => 'new-content', 'href' => admin_url( 'post-new.php' ), 'meta' => array( 'class' => 'ab-item' ) ); $wp_admin_bar->add_node( $args ); // add back the new Page $args = array( 'id' => 'new-page', 'title' => 'Page', 'parent' => 'new-content', 'href' => admin_url( 'post-new.php?post_type=page' ), 'meta' => array( 'class' => 'ab-item' ) ); $wp_admin_bar->add_node( $args ); } ``` Here is my menu after: [![enter image description here](https://i.stack.imgur.com/du4kU.jpg)](https://i.stack.imgur.com/du4kU.jpg)
273,367
<p>Im trying to remove the editor from the homepage using the following functions however I am struggling to achieve this?</p> <pre><code>function hide_homepage_editor() { if ( is_admin() ) { if (is_front_page()) { remove_post_type_support('page', 'editor'); } } } add_action( 'admin_init', 'hide_homepage_editor' ); </code></pre> <p>another try:</p> <pre><code>function hide_homepage_editor() { if ( is_admin() ) { $post_id = 0; if(isset($_GET['post'])) $post_id = $_GET['post']; $template_file = get_post_meta($post_id, '_wp_page_template', TRUE); if ($template_file == 'front-page.php') { remove_post_type_support('page', 'editor'); } } } add_action( 'admin_init', 'hide_homepage_editor' ); </code></pre> <p>Anyone know why these are not working and how I can remove the page editor from the page set as frontpage?</p>
[ { "answer_id": 273371, "author": "Andrew M", "author_id": 89356, "author_profile": "https://wordpress.stackexchange.com/users/89356", "pm_score": 5, "selected": true, "text": "<p>There are a couple of issues with your approach</p>\n\n<p>By using the <strong>admin_init</strong> hook you w...
2017/07/14
[ "https://wordpress.stackexchange.com/questions/273367", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102937/" ]
Im trying to remove the editor from the homepage using the following functions however I am struggling to achieve this? ``` function hide_homepage_editor() { if ( is_admin() ) { if (is_front_page()) { remove_post_type_support('page', 'editor'); } } } add_action( 'admin_init', 'hide_homepage_editor' ); ``` another try: ``` function hide_homepage_editor() { if ( is_admin() ) { $post_id = 0; if(isset($_GET['post'])) $post_id = $_GET['post']; $template_file = get_post_meta($post_id, '_wp_page_template', TRUE); if ($template_file == 'front-page.php') { remove_post_type_support('page', 'editor'); } } } add_action( 'admin_init', 'hide_homepage_editor' ); ``` Anyone know why these are not working and how I can remove the page editor from the page set as frontpage?
There are a couple of issues with your approach By using the **admin\_init** hook you won't have any reference to the post object. This means you won't be able to get the post ID or use anything like get\_the\_ID because the post won't actually be loaded. You can see that in the order here <https://codex.wordpress.org/Plugin_API/Action_Reference> So if you run the action hook after the wp action you'll have the post object. For example ``` add_action('admin_head', 'remove_content_editor'); /** * Remove the content editor from ALL pages */ function remove_content_editor() { remove_post_type_support('page', 'editor'); } ``` Now this snippet will remove the editor from all pages. The problem is that **is\_home** and **is\_front\_page** won't work on the admin side so you'll need to add some meta data to distinguish whether you're on the home page. There's a very comprehensive discussion of approaches for that on this page: [Best way to present options for home page in admin?](https://wordpress.stackexchange.com/questions/103433/best-way-to-present-options-for-home-page-in-admin) So, if you used some extra meta data, you can then check this like ``` add_action('admin_head', 'remove_content_editor'); /** * Remove the content editor from ALL pages */ function remove_content_editor() { //Check against your meta data here if(get_post_meta( get_the_ID(), 'is_home_page' )){ remove_post_type_support('page', 'editor'); } } ``` Hopefully that will help you out \*\*\*\*\*\*\* Update \*\*\*\*\*\*\*\*\*\*\*\* Actually, I've just looked into this again and realised that there is an easier way. If you have set the front page to be a static page in the Reading settings, you can check against the **page\_on\_front** option value. In that case, the following will work ``` add_action('admin_head', 'remove_content_editor'); /** * Remove the content editor from pages as all content is handled through Panels */ function remove_content_editor() { if((int) get_option('page_on_front')==get_the_ID()) { remove_post_type_support('page', 'editor'); } } ```
273,394
<p>I'm trying to make simple about me widget with WordPress media uploader. When I click the button <strong>Upload</strong> it opens media uploader, but after I hit <strong>save</strong>, the button doesn't work anymore, the same behavior if I have one active widget and then I add another, media upload button doesn't work in second widget. No JS errors in console. Can someone point me, where I'm wrong?</p> <p><strong>PHP</strong></p> <pre><code>class Inka_Profile_Widget extends WP_Widget { // setup the widget name, description etc. function __construct() { $widget_options = array( 'classname' =&gt; esc_attr( "inka_profile_widget", 'inka' ), 'description' =&gt; esc_html__( 'Custom Profile Widget', 'inka' ), 'customize_selective_refresh' =&gt; true ); parent::__construct( 'inka_profile', 'Inka Profile', $widget_options); } // back-end display of widget function form( $instance ) { $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'About Me', 'inka' ); $image = ! empty( $instance['image'] ) ? $instance['image'] : ''; ?&gt; &lt;p&gt; &lt;label for="&lt;?php echo esc_attr( $this-&gt;get_field_id('title') ); ?&gt;"&gt;&lt;?php esc_attr_e( 'Title', 'inka' ); ?&gt;&lt;/label&gt; &lt;input class="widefat" id="&lt;?php echo esc_attr( $this-&gt;get_field_id( 'title' ) ); ?&gt;" name="&lt;?php echo esc_attr( $this-&gt;get_field_name( 'title' ) ); ?&gt;" type="text" value="&lt;?php echo esc_attr( $title ); ?&gt;"&gt; &lt;/p&gt; &lt;p&gt; &lt;img src="&lt;?php echo esc_attr( $image ); ?&gt;" alt="" class="deo-image-holder" style="width: 100%;"&gt; &lt;/p&gt; &lt;p&gt; &lt;input type="hidden" class="deo-image-hidden-field" name="&lt;?php echo $this-&gt;get_field_name( 'image' ); ?&gt;" id="&lt;?php echo $this-&gt;get_field_id( 'image' ); ?&gt;" value="&lt;?php echo esc_attr( $image ); ?&gt;"/&gt; &lt;input type="button" class="deo-image-upload-button button button-primary" value="Upload"&gt; &lt;input type="button" class="deo-image-delete-button button" value="Remove Image"&gt; &lt;/p&gt; &lt;?php } // front-end display of widget function widget( $args, $instance ) { echo "Hey"; } // update of the widget function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; $instance['image'] = ( ! empty( $new_instance['image'] ) ) ? strip_tags( $new_instance['image'] ) : ''; return $instance; } } add_action( 'widgets_init', function() { register_widget( 'Inka_Profile_Widget' ); }); </code></pre> <p><strong>JS</strong></p> <pre><code>(function($){ /* WordPress Media Uploader -------------------------------------------------------*/ var addButton = $('.deo-image-upload-button'); var deleteButton = $('.deo-image-delete-button'); var hiddenField = $('.deo-image-hidden-field'); var imageHolder = $('.deo-image-holder'); var mediaUploader; addButton.on('click', function(e) { e.preventDefault(); if ( mediaUploader ) { mediaUploader.open(); return; } mediaUploader = wp.media.frames.file_frame = wp.media({ title: 'Select an Image', button: { text: 'Use This Image' }, multiple: false }); mediaUploader.on('select', function() { var attachment = mediaUploader.state().get('selection').first().toJSON(); hiddenField.val(attachment.url); imageHolder.attr('src', attachment.url); }); mediaUploader.open(); }); })(jQuery); </code></pre>
[ { "answer_id": 273371, "author": "Andrew M", "author_id": 89356, "author_profile": "https://wordpress.stackexchange.com/users/89356", "pm_score": 5, "selected": true, "text": "<p>There are a couple of issues with your approach</p>\n\n<p>By using the <strong>admin_init</strong> hook you w...
2017/07/14
[ "https://wordpress.stackexchange.com/questions/273394", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112255/" ]
I'm trying to make simple about me widget with WordPress media uploader. When I click the button **Upload** it opens media uploader, but after I hit **save**, the button doesn't work anymore, the same behavior if I have one active widget and then I add another, media upload button doesn't work in second widget. No JS errors in console. Can someone point me, where I'm wrong? **PHP** ``` class Inka_Profile_Widget extends WP_Widget { // setup the widget name, description etc. function __construct() { $widget_options = array( 'classname' => esc_attr( "inka_profile_widget", 'inka' ), 'description' => esc_html__( 'Custom Profile Widget', 'inka' ), 'customize_selective_refresh' => true ); parent::__construct( 'inka_profile', 'Inka Profile', $widget_options); } // back-end display of widget function form( $instance ) { $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'About Me', 'inka' ); $image = ! empty( $instance['image'] ) ? $instance['image'] : ''; ?> <p> <label for="<?php echo esc_attr( $this->get_field_id('title') ); ?>"><?php esc_attr_e( 'Title', 'inka' ); ?></label> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>"> </p> <p> <img src="<?php echo esc_attr( $image ); ?>" alt="" class="deo-image-holder" style="width: 100%;"> </p> <p> <input type="hidden" class="deo-image-hidden-field" name="<?php echo $this->get_field_name( 'image' ); ?>" id="<?php echo $this->get_field_id( 'image' ); ?>" value="<?php echo esc_attr( $image ); ?>"/> <input type="button" class="deo-image-upload-button button button-primary" value="Upload"> <input type="button" class="deo-image-delete-button button" value="Remove Image"> </p> <?php } // front-end display of widget function widget( $args, $instance ) { echo "Hey"; } // update of the widget function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; $instance['image'] = ( ! empty( $new_instance['image'] ) ) ? strip_tags( $new_instance['image'] ) : ''; return $instance; } } add_action( 'widgets_init', function() { register_widget( 'Inka_Profile_Widget' ); }); ``` **JS** ``` (function($){ /* WordPress Media Uploader -------------------------------------------------------*/ var addButton = $('.deo-image-upload-button'); var deleteButton = $('.deo-image-delete-button'); var hiddenField = $('.deo-image-hidden-field'); var imageHolder = $('.deo-image-holder'); var mediaUploader; addButton.on('click', function(e) { e.preventDefault(); if ( mediaUploader ) { mediaUploader.open(); return; } mediaUploader = wp.media.frames.file_frame = wp.media({ title: 'Select an Image', button: { text: 'Use This Image' }, multiple: false }); mediaUploader.on('select', function() { var attachment = mediaUploader.state().get('selection').first().toJSON(); hiddenField.val(attachment.url); imageHolder.attr('src', attachment.url); }); mediaUploader.open(); }); })(jQuery); ```
There are a couple of issues with your approach By using the **admin\_init** hook you won't have any reference to the post object. This means you won't be able to get the post ID or use anything like get\_the\_ID because the post won't actually be loaded. You can see that in the order here <https://codex.wordpress.org/Plugin_API/Action_Reference> So if you run the action hook after the wp action you'll have the post object. For example ``` add_action('admin_head', 'remove_content_editor'); /** * Remove the content editor from ALL pages */ function remove_content_editor() { remove_post_type_support('page', 'editor'); } ``` Now this snippet will remove the editor from all pages. The problem is that **is\_home** and **is\_front\_page** won't work on the admin side so you'll need to add some meta data to distinguish whether you're on the home page. There's a very comprehensive discussion of approaches for that on this page: [Best way to present options for home page in admin?](https://wordpress.stackexchange.com/questions/103433/best-way-to-present-options-for-home-page-in-admin) So, if you used some extra meta data, you can then check this like ``` add_action('admin_head', 'remove_content_editor'); /** * Remove the content editor from ALL pages */ function remove_content_editor() { //Check against your meta data here if(get_post_meta( get_the_ID(), 'is_home_page' )){ remove_post_type_support('page', 'editor'); } } ``` Hopefully that will help you out \*\*\*\*\*\*\* Update \*\*\*\*\*\*\*\*\*\*\*\* Actually, I've just looked into this again and realised that there is an easier way. If you have set the front page to be a static page in the Reading settings, you can check against the **page\_on\_front** option value. In that case, the following will work ``` add_action('admin_head', 'remove_content_editor'); /** * Remove the content editor from pages as all content is handled through Panels */ function remove_content_editor() { if((int) get_option('page_on_front')==get_the_ID()) { remove_post_type_support('page', 'editor'); } } ```
273,403
<p>I've been pulling my hair over this strange issue for several hours now and need some help figuring out what's going on. Allow me to explain my setup followed by the behavior and question.</p> <p>Setup:</p> <ol> <li><p>I've set my 'posts page' to domain.com/search/ where I intend to list all my posts. </p></li> <li><p>Since I need a custom layout for displaying my posts, I've the following redirect in 'template_include' hook:</p> <pre><code>/*Use custom template to render posts on /search/ */ if ( is_home() ) { return plugin_dir_path( __FILE__ ) . 'partials/display-speaker-list.php'; } </code></pre></li> <li><p>My posts list also displays tags associated with each post. I want these tags to be clickable. When user clicks on any tag, I want to filter the posts using the clicked tag as keyword. The HTML for my displaying tags for each post looks like this:</p> <pre><code> &lt;a href="&lt;?php echo esc_url( home_url('/') . 'search/?tag=' . str_replace(' ', '+', $topic ) ); ?&gt;" class="btn btn-outline-primary" role="button"&gt;&lt;?php echo esc_html( $topic ); ?&gt;&lt;/a&gt; </code></pre></li> </ol> <p>In order to make the search work, I decided to make use of 'pre_get_posts' hook. This is where the strange things began to happen. Look at the code I execute with <code>pre_get_posts</code> : </p> <pre><code>/* Filter posts using the tag public function io_speakers_pre_get_posts( $query ) { if ( $query-&gt;is_main_query() &amp;&amp; $query-&gt;is_home() ) { $query-&gt;set('tag', $_GET['tag']); return $query; } return $query; } </code></pre> <p>Here's the Odd behavior:</p> <p>If I remove the <code>$query-&gt;set('query_var', 'value');</code> statement from the condition, WordPress returns all posts, completely ignoring the <code>search/?tag=xyz</code> query. But it works even if I set it to something random or even empty. That is, WordPress correctly filters the posts if I change that line to <code>$query-&gt;set('', '');</code> </p> <p>In short, WordPress expects me to have a <code>$query-&gt;set(WHATEVER);</code> in that condition for it to acknowledge existence of 'tag' parameter. Otherwise it just returns all the posts. </p> <p>My questions are: </p> <ol> <li>What's really happening with <code>$query-&gt;set()</code>? </li> <li>Why does it require me to set any random stuff in <code>$query-&gt;(blah, blah)</code> in order to work properly?</li> <li>What if I want to search by <code>/search/?topic=someTopic</code> instead of <code>/search/?tag=someTopic</code>? </li> </ol> <p>I hope I've explained my question properly. It's a pretty long explanation and I look forward to your help. Would really appreciate it. Thank you in advance for your time.</p> <p>-K</p>
[ { "answer_id": 273371, "author": "Andrew M", "author_id": 89356, "author_profile": "https://wordpress.stackexchange.com/users/89356", "pm_score": 5, "selected": true, "text": "<p>There are a couple of issues with your approach</p>\n\n<p>By using the <strong>admin_init</strong> hook you w...
2017/07/14
[ "https://wordpress.stackexchange.com/questions/273403", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/21100/" ]
I've been pulling my hair over this strange issue for several hours now and need some help figuring out what's going on. Allow me to explain my setup followed by the behavior and question. Setup: 1. I've set my 'posts page' to domain.com/search/ where I intend to list all my posts. 2. Since I need a custom layout for displaying my posts, I've the following redirect in 'template\_include' hook: ``` /*Use custom template to render posts on /search/ */ if ( is_home() ) { return plugin_dir_path( __FILE__ ) . 'partials/display-speaker-list.php'; } ``` 3. My posts list also displays tags associated with each post. I want these tags to be clickable. When user clicks on any tag, I want to filter the posts using the clicked tag as keyword. The HTML for my displaying tags for each post looks like this: ``` <a href="<?php echo esc_url( home_url('/') . 'search/?tag=' . str_replace(' ', '+', $topic ) ); ?>" class="btn btn-outline-primary" role="button"><?php echo esc_html( $topic ); ?></a> ``` In order to make the search work, I decided to make use of 'pre\_get\_posts' hook. This is where the strange things began to happen. Look at the code I execute with `pre_get_posts` : ``` /* Filter posts using the tag public function io_speakers_pre_get_posts( $query ) { if ( $query->is_main_query() && $query->is_home() ) { $query->set('tag', $_GET['tag']); return $query; } return $query; } ``` Here's the Odd behavior: If I remove the `$query->set('query_var', 'value');` statement from the condition, WordPress returns all posts, completely ignoring the `search/?tag=xyz` query. But it works even if I set it to something random or even empty. That is, WordPress correctly filters the posts if I change that line to `$query->set('', '');` In short, WordPress expects me to have a `$query->set(WHATEVER);` in that condition for it to acknowledge existence of 'tag' parameter. Otherwise it just returns all the posts. My questions are: 1. What's really happening with `$query->set()`? 2. Why does it require me to set any random stuff in `$query->(blah, blah)` in order to work properly? 3. What if I want to search by `/search/?topic=someTopic` instead of `/search/?tag=someTopic`? I hope I've explained my question properly. It's a pretty long explanation and I look forward to your help. Would really appreciate it. Thank you in advance for your time. -K
There are a couple of issues with your approach By using the **admin\_init** hook you won't have any reference to the post object. This means you won't be able to get the post ID or use anything like get\_the\_ID because the post won't actually be loaded. You can see that in the order here <https://codex.wordpress.org/Plugin_API/Action_Reference> So if you run the action hook after the wp action you'll have the post object. For example ``` add_action('admin_head', 'remove_content_editor'); /** * Remove the content editor from ALL pages */ function remove_content_editor() { remove_post_type_support('page', 'editor'); } ``` Now this snippet will remove the editor from all pages. The problem is that **is\_home** and **is\_front\_page** won't work on the admin side so you'll need to add some meta data to distinguish whether you're on the home page. There's a very comprehensive discussion of approaches for that on this page: [Best way to present options for home page in admin?](https://wordpress.stackexchange.com/questions/103433/best-way-to-present-options-for-home-page-in-admin) So, if you used some extra meta data, you can then check this like ``` add_action('admin_head', 'remove_content_editor'); /** * Remove the content editor from ALL pages */ function remove_content_editor() { //Check against your meta data here if(get_post_meta( get_the_ID(), 'is_home_page' )){ remove_post_type_support('page', 'editor'); } } ``` Hopefully that will help you out \*\*\*\*\*\*\* Update \*\*\*\*\*\*\*\*\*\*\*\* Actually, I've just looked into this again and realised that there is an easier way. If you have set the front page to be a static page in the Reading settings, you can check against the **page\_on\_front** option value. In that case, the following will work ``` add_action('admin_head', 'remove_content_editor'); /** * Remove the content editor from pages as all content is handled through Panels */ function remove_content_editor() { if((int) get_option('page_on_front')==get_the_ID()) { remove_post_type_support('page', 'editor'); } } ```
273,419
<p>The following bit of code was used in my fictitious plugin to redirect the non-logged-in users from page <code>173</code> (ID) to <code>sample-page</code> (slug). The code's working well. But just today, I figured out that the code is causing Notices <del>in Firefox</del>.</p> <p>The issue happened when I tried setting a Static Page as the front page from Settings » Reading.</p> <blockquote> <p><strong>Notice:</strong> Trying to get property of non-object in <code>/wp-includes/class-wp-query.php</code> on line 3760 <strong>Notice:</strong> Trying to get property of non-object in <code>/wp-includes/class-wp-query.php</code> on line 3762 <strong>Notice:</strong> Trying to get property of non-object in <code>/wp-includes/class-wp-query.php</code> on line 3764</p> </blockquote> <p>With several inspection, I figured out that, the following bit of code is causing the issue. And to be specific the issue is with the <code>is_page(173)</code>.</p> <pre><code>add_action('pre_get_posts', function($query) { if( $query-&gt;is_main_query() &amp;&amp; ! is_admin() &amp;&amp; ! is_user_logged_in() &amp;&amp; $query-&gt;is_page(173) ) { wp_redirect(home_url('/sample-page')); exit(); } }); </code></pre> <p>I tried changing from <code>$query-&gt;is_page(173)</code> to <code>is_page(173)</code> - the result is same.</p> <p>To test in a blank installation, I tried disabling all the plugins and set the default theme TwentySixteen, and re-installed WordPress to get a fresh install. I put the following code in TwentySixteen's <code>functions.php</code>, and with DEBUG <em>on</em>, <a href="http://dev.nanodesignsbd.com/" rel="nofollow noreferrer">here's what I got</a>. (The notice is under the black area of header, just hit <kbd>Ctrl</kbd> + <kbd>A</kbd> to see 'em) <del>You can check the redirection is working from <a href="http://dev.nanodesignsbd.com/level-2/" rel="nofollow noreferrer">this page</a> (<code>173</code>) to <a href="http://dev.nanodesignsbd.com/sample-page/" rel="nofollow noreferrer">this page</a> without any notice.</del></p> <p>What's the problem with my code?</p>
[ { "answer_id": 344086, "author": "Tom", "author_id": 172789, "author_profile": "https://wordpress.stackexchange.com/users/172789", "pm_score": 0, "selected": false, "text": "<p>Turn off debug mode and it will be gone, at least worked for me. \nI know it's an old post but just want to hel...
2017/07/14
[ "https://wordpress.stackexchange.com/questions/273419", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/22728/" ]
The following bit of code was used in my fictitious plugin to redirect the non-logged-in users from page `173` (ID) to `sample-page` (slug). The code's working well. But just today, I figured out that the code is causing Notices ~~in Firefox~~. The issue happened when I tried setting a Static Page as the front page from Settings » Reading. > > **Notice:** Trying to get property of non-object in > `/wp-includes/class-wp-query.php` on line 3760 > **Notice:** Trying to get property of non-object in > `/wp-includes/class-wp-query.php` on line 3762 > **Notice:** Trying to get property of non-object in > `/wp-includes/class-wp-query.php` on line 3764 > > > With several inspection, I figured out that, the following bit of code is causing the issue. And to be specific the issue is with the `is_page(173)`. ``` add_action('pre_get_posts', function($query) { if( $query->is_main_query() && ! is_admin() && ! is_user_logged_in() && $query->is_page(173) ) { wp_redirect(home_url('/sample-page')); exit(); } }); ``` I tried changing from `$query->is_page(173)` to `is_page(173)` - the result is same. To test in a blank installation, I tried disabling all the plugins and set the default theme TwentySixteen, and re-installed WordPress to get a fresh install. I put the following code in TwentySixteen's `functions.php`, and with DEBUG *on*, [here's what I got](http://dev.nanodesignsbd.com/). (The notice is under the black area of header, just hit `Ctrl` + `A` to see 'em) ~~You can check the redirection is working from [this page](http://dev.nanodesignsbd.com/level-2/) (`173`) to [this page](http://dev.nanodesignsbd.com/sample-page/) without any notice.~~ What's the problem with my code?
`pre_get_posts` is innapropriate for this use, instead you should use the `template_redirect` filter, e.g. ```php add_action( 'template_redirect', funnction() { if ( ! is_user_logged_in() && is_page( 123 ) ) { wp_safe_redirect( home_url( '/sample-page' ) ); exit; } } ); ```
273,438
<p>I want to show random posts from a custom post type in my page. For example, I have 10 posts, but I want to show 5 post in page which will change randomly.</p> <p>How can I do this?</p> <p>Regards.</p>
[ { "answer_id": 273439, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>A quick 'googles' turns up several possibilities (the googles are your friend to get answers for most ...
2017/07/14
[ "https://wordpress.stackexchange.com/questions/273438", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123903/" ]
I want to show random posts from a custom post type in my page. For example, I have 10 posts, but I want to show 5 post in page which will change randomly. How can I do this? Regards.
You can write a custom query to get some random posts for your template. The simplest possible solution will be this query: ``` <?php // Set the post type here, and sort them randomly $args = array( 'post_type' => 'YOUR-POST-TYPE', 'posts_per_page'=> 5, 'order_by' => 'rand', ); // Initiate a custom query $my_query = new WP_Query($args); // If the query has any post, start the loop if($my_query->have_posts()){ while($my_query->have_posts()){ // Output a link and a thumbnail of the post $my_query->the_post(); ?> <div class="random-post"> <img src="<?php the_post_thumbnail_url();?>"/> <a href="<?php the_permalink();?>"><?php the_title();?></a> </div><?php } } ?> ``` Replace `YOUR-POST-TYPE` with your actual post type's name, then paste this code wherever you wish in your template. You can add or remove any element that you wish, if you are familiar with WordPress's functions.
273,442
<p>I will post the entire plugin code below.. here is the problem that I am having with it. I am using the values that are imported to custom fields in a custom post type to construct the URLs. On the edit post page it shows the permalink as I wish it to be..</p> <blockquote> <p>site.com/real-estate/%postname%-%field_City%-%field_State%-%field_Zip_Code%/</p> </blockquote> <p>as</p> <blockquote> <p>site.com/real-estate/51-main-st-<strong>port-jefferson</strong>-ny-11777/</p> </blockquote> <p>The permalink however is 404.. although if I remove the hyphens in the city name and search..</p> <blockquote> <p>site.com/real-estate/51-main-st-<strong>portjefferson</strong>-ny-11777/</p> </blockquote> <p>than the url works..</p> <p>So I imagine the plugin is missing something with respects to fields with spaces.. strange that it shows properly in the permalink field within the post editor though.. any help will be much appreciated..</p> <pre><code> &lt;?php /* Plugin Name: Custom Fields Permalink 2 Plugin URI: http://athlan.pl/wordpress-custom-fields-permalink-plugin Description: Plugin allows to use post's custom fields values in permalink structure by adding %field_fieldname%, for posts, pages and custom post types. Author: Piotr Pelczar Version: 2.0 Author URI: http://athlan.pl/ */ class CustomFieldsPermalink { const PARAM_CUSTOMFIELD_KEY = 'custom_field_key'; const PARAM_CUSTOMFIELD_VALUE = 'custom_field_value'; public static $checkCustomFieldValue = false; public static function linkPost($permalink, $post, $leavename) { return self::linkRewriteFields($permalink, $post); } public static function linkPostType($permalink, $post, $leavename, $sample) { return self::linkRewriteFields($permalink, $post); } protected static function linkRewriteFields($permalink, $post) { $replaceCallback = function($matches) use (&amp;$post) { return CustomFieldsPermalink::linkRewriteFieldsExtract($post, $matches[2]); }; return preg_replace_callback('#(%field_(.*?)%)#', $replaceCallback, $permalink); } public static function linkRewriteFieldsExtract($post, $fieldName) { $postMeta = get_post_meta($post-&gt;ID); if(!isset($postMeta[$fieldName])) return ''; $value = implode('', $postMeta[$fieldName]); $value = sanitize_title($value); return $value; } public static function registerExtraQueryVars($value) { array_push($value, self::PARAM_CUSTOMFIELD_KEY, self::PARAM_CUSTOMFIELD_VALUE); return $value; } public static function processRequest($value) { // additional parameters added to Wordpress // Main Loop query if(array_key_exists(self::PARAM_CUSTOMFIELD_KEY, $value)) { $value['meta_key'] = $value[self::PARAM_CUSTOMFIELD_KEY]; // remove temporary injected parameter unset($value[self::PARAM_CUSTOMFIELD_KEY]); // do not check field's value for this moment if(true === self::$checkCustomFieldValue) { if(array_key_exists(self::PARAM_CUSTOMFIELD_VALUE, $value)) { $value['meta_value'] = $value[self::PARAM_CUSTOMFIELD_VALUE]; // remove temporary injected parameter unset($value[self::PARAM_CUSTOMFIELD_VALUE]); } } } return $value; } public static function rewriteRulesArrayFilter($rules) { $keys = array_keys($rules); $tmp = $rules; $rules = array(); for($i = 0, $j = sizeof($keys); $i &lt; $j; ++$i) { $key = $keys[$i]; if (preg_match('/%field_([^%]*?)%/', $key)) { $keyNew = preg_replace( '/%field_([^%]*?)%/', '([^/]+)', // you can simply add next group to the url, because WordPress // detect them automatically and add next $matches indiceis $key ); $rules[$keyNew] = preg_replace( '/%field_([^%]*?)%/', sprintf('%s=$1&amp;%s=', self::PARAM_CUSTOMFIELD_KEY, self::PARAM_CUSTOMFIELD_VALUE), // here on the end will be pasted $matches[$i] from $keyNew, so we can // grab it it the future in self::PARAM_CUSTOMFIELD_VALUE parameter $tmp[$key] ); } else { $rules[$key] = $tmp[$key]; } } return $rules; } } add_filter('pre_post_link', array('CustomFieldsPermalink', 'linkPost'), 100, 3); add_filter('post_type_link', array('CustomFieldsPermalink', 'linkPostType'), 100, 4); add_filter('rewrite_rules_array', array('CustomFieldsPermalink', 'rewriteRulesArrayFilter')); add_filter('query_vars', array('CustomFieldsPermalink', 'registerExtraQueryVars'), 10, 1); add_filter('request', array('CustomFieldsPermalink', 'processRequest'), 10, 1); </code></pre> <p>I THOUGHT I FIGURED OUT A SOLUTION.. BUT... I thought that using the hex code for hyphen (%2D) in permalink settings was a solution.. but it turns out this only works in the chrome browser.. not in IE or Edge.. so I am still without a solution unfortunately :(</p>
[ { "answer_id": 273439, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>A quick 'googles' turns up several possibilities (the googles are your friend to get answers for most ...
2017/07/14
[ "https://wordpress.stackexchange.com/questions/273442", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123857/" ]
I will post the entire plugin code below.. here is the problem that I am having with it. I am using the values that are imported to custom fields in a custom post type to construct the URLs. On the edit post page it shows the permalink as I wish it to be.. > > site.com/real-estate/%postname%-%field\_City%-%field\_State%-%field\_Zip\_Code%/ > > > as > > site.com/real-estate/51-main-st-**port-jefferson**-ny-11777/ > > > The permalink however is 404.. although if I remove the hyphens in the city name and search.. > > site.com/real-estate/51-main-st-**portjefferson**-ny-11777/ > > > than the url works.. So I imagine the plugin is missing something with respects to fields with spaces.. strange that it shows properly in the permalink field within the post editor though.. any help will be much appreciated.. ``` <?php /* Plugin Name: Custom Fields Permalink 2 Plugin URI: http://athlan.pl/wordpress-custom-fields-permalink-plugin Description: Plugin allows to use post's custom fields values in permalink structure by adding %field_fieldname%, for posts, pages and custom post types. Author: Piotr Pelczar Version: 2.0 Author URI: http://athlan.pl/ */ class CustomFieldsPermalink { const PARAM_CUSTOMFIELD_KEY = 'custom_field_key'; const PARAM_CUSTOMFIELD_VALUE = 'custom_field_value'; public static $checkCustomFieldValue = false; public static function linkPost($permalink, $post, $leavename) { return self::linkRewriteFields($permalink, $post); } public static function linkPostType($permalink, $post, $leavename, $sample) { return self::linkRewriteFields($permalink, $post); } protected static function linkRewriteFields($permalink, $post) { $replaceCallback = function($matches) use (&$post) { return CustomFieldsPermalink::linkRewriteFieldsExtract($post, $matches[2]); }; return preg_replace_callback('#(%field_(.*?)%)#', $replaceCallback, $permalink); } public static function linkRewriteFieldsExtract($post, $fieldName) { $postMeta = get_post_meta($post->ID); if(!isset($postMeta[$fieldName])) return ''; $value = implode('', $postMeta[$fieldName]); $value = sanitize_title($value); return $value; } public static function registerExtraQueryVars($value) { array_push($value, self::PARAM_CUSTOMFIELD_KEY, self::PARAM_CUSTOMFIELD_VALUE); return $value; } public static function processRequest($value) { // additional parameters added to Wordpress // Main Loop query if(array_key_exists(self::PARAM_CUSTOMFIELD_KEY, $value)) { $value['meta_key'] = $value[self::PARAM_CUSTOMFIELD_KEY]; // remove temporary injected parameter unset($value[self::PARAM_CUSTOMFIELD_KEY]); // do not check field's value for this moment if(true === self::$checkCustomFieldValue) { if(array_key_exists(self::PARAM_CUSTOMFIELD_VALUE, $value)) { $value['meta_value'] = $value[self::PARAM_CUSTOMFIELD_VALUE]; // remove temporary injected parameter unset($value[self::PARAM_CUSTOMFIELD_VALUE]); } } } return $value; } public static function rewriteRulesArrayFilter($rules) { $keys = array_keys($rules); $tmp = $rules; $rules = array(); for($i = 0, $j = sizeof($keys); $i < $j; ++$i) { $key = $keys[$i]; if (preg_match('/%field_([^%]*?)%/', $key)) { $keyNew = preg_replace( '/%field_([^%]*?)%/', '([^/]+)', // you can simply add next group to the url, because WordPress // detect them automatically and add next $matches indiceis $key ); $rules[$keyNew] = preg_replace( '/%field_([^%]*?)%/', sprintf('%s=$1&%s=', self::PARAM_CUSTOMFIELD_KEY, self::PARAM_CUSTOMFIELD_VALUE), // here on the end will be pasted $matches[$i] from $keyNew, so we can // grab it it the future in self::PARAM_CUSTOMFIELD_VALUE parameter $tmp[$key] ); } else { $rules[$key] = $tmp[$key]; } } return $rules; } } add_filter('pre_post_link', array('CustomFieldsPermalink', 'linkPost'), 100, 3); add_filter('post_type_link', array('CustomFieldsPermalink', 'linkPostType'), 100, 4); add_filter('rewrite_rules_array', array('CustomFieldsPermalink', 'rewriteRulesArrayFilter')); add_filter('query_vars', array('CustomFieldsPermalink', 'registerExtraQueryVars'), 10, 1); add_filter('request', array('CustomFieldsPermalink', 'processRequest'), 10, 1); ``` I THOUGHT I FIGURED OUT A SOLUTION.. BUT... I thought that using the hex code for hyphen (%2D) in permalink settings was a solution.. but it turns out this only works in the chrome browser.. not in IE or Edge.. so I am still without a solution unfortunately :(
You can write a custom query to get some random posts for your template. The simplest possible solution will be this query: ``` <?php // Set the post type here, and sort them randomly $args = array( 'post_type' => 'YOUR-POST-TYPE', 'posts_per_page'=> 5, 'order_by' => 'rand', ); // Initiate a custom query $my_query = new WP_Query($args); // If the query has any post, start the loop if($my_query->have_posts()){ while($my_query->have_posts()){ // Output a link and a thumbnail of the post $my_query->the_post(); ?> <div class="random-post"> <img src="<?php the_post_thumbnail_url();?>"/> <a href="<?php the_permalink();?>"><?php the_title();?></a> </div><?php } } ?> ``` Replace `YOUR-POST-TYPE` with your actual post type's name, then paste this code wherever you wish in your template. You can add or remove any element that you wish, if you are familiar with WordPress's functions.
273,459
<p>In the navigation menu creation page, when you are trying to add a category to the menu, if the category is empty, it won't show up in the search results. However, if the category itself is empty but has a child that is not empty, it will still be shown.</p> <p>I have a blog with over 500 categories, and I'm trying to add some of them to the menu but they have no posts yet. Navigating through category list is going to take time, and is also frustrating.</p> <p>Now I've tracked down the issue to <code>/wp-admin/includes/nav-menu.php</code>, ( starting at line 588 ) but can't find a filter or hook to do so.</p> <p>This line (109) seems to be responsible for doing the search:</p> <pre><code>$terms = get_terms( $matches[2], array( 'name__like' =&gt; $query, 'number' =&gt; 10, )); </code></pre> <p>According to the <a href="https://developer.wordpress.org/reference/functions/get_terms/" rel="nofollow noreferrer">documentations</a>, this function accepts an argument for showing empty terms <code>'hide_empty' =&gt; false</code>, but I can't see such option in this part of core's code. I've added this option to the core (temporarily) to see if it solves the issue, and it does.</p> <p>Can this be a bug? And is it possible to enable the search to return the result no matter the category has a post or not?</p>
[ { "answer_id": 273812, "author": "Worduoso", "author_id": 101425, "author_profile": "https://wordpress.stackexchange.com/users/101425", "pm_score": 2, "selected": true, "text": "<p>You can modify this behaviour by adding a custom filter to your functions.php or as a plugin:</p>\n\n<pre><...
2017/07/15
[ "https://wordpress.stackexchange.com/questions/273459", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94498/" ]
In the navigation menu creation page, when you are trying to add a category to the menu, if the category is empty, it won't show up in the search results. However, if the category itself is empty but has a child that is not empty, it will still be shown. I have a blog with over 500 categories, and I'm trying to add some of them to the menu but they have no posts yet. Navigating through category list is going to take time, and is also frustrating. Now I've tracked down the issue to `/wp-admin/includes/nav-menu.php`, ( starting at line 588 ) but can't find a filter or hook to do so. This line (109) seems to be responsible for doing the search: ``` $terms = get_terms( $matches[2], array( 'name__like' => $query, 'number' => 10, )); ``` According to the [documentations](https://developer.wordpress.org/reference/functions/get_terms/), this function accepts an argument for showing empty terms `'hide_empty' => false`, but I can't see such option in this part of core's code. I've added this option to the core (temporarily) to see if it solves the issue, and it does. Can this be a bug? And is it possible to enable the search to return the result no matter the category has a post or not?
You can modify this behaviour by adding a custom filter to your functions.php or as a plugin: ``` add_filter('get_terms_args', 'wodruoso_terms_args', 10, 1); function wodruoso_terms_args($args) { /* note: I am checking here that we are in WP Admin area and that it's * search by category name to minimize impact on other areas */ if(is_admin() && isset($args["name__like"]) && !empty($args["name__like"])) { $args["hide_empty"] = false; } return $args; } ```
273,500
<p>I have just followed <a href="http://www.wpbeginner.com/wp-tutorials/how-to-move-live-wordpress-site-to-local-server/" rel="nofollow noreferrer">this guide</a> on manually migrating a WordPress site to localhost.</p> <p>I have followed all of the steps: downloading files using FTP, exporting database, importing to localhost database, changing URL links to localhost and finally updating wp-config.</p> <p>I tried this on two of my sites and came across different problems:</p> <ol> <li>Safari cannot connect to the server' error message</li> <li>The following text displayed on the screen:</li> </ol> <blockquote> <p>"Front to the WordPress application. This file doesn't do anything, but loads wp-blog-header.php which does and tells WordPress to load the theme.</p> </blockquote> <pre><code> * @package WordPress */ /** * Tells WordPress to load the WordPress theme and output it. * * @var bool */ define('WP_USE_THEMES', true); /** Loads the WordPress Environment and Template */ require( dirname( FILE ) . '/wp-blog-header.php' );" </code></pre> <p>Can anyone advise as to how I can make my website display?</p>
[ { "answer_id": 273496, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>You can't find it because it doesn't exist. There is no page at that location.</p>\n\n<p>In WordPress everyt...
2017/07/15
[ "https://wordpress.stackexchange.com/questions/273500", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123633/" ]
I have just followed [this guide](http://www.wpbeginner.com/wp-tutorials/how-to-move-live-wordpress-site-to-local-server/) on manually migrating a WordPress site to localhost. I have followed all of the steps: downloading files using FTP, exporting database, importing to localhost database, changing URL links to localhost and finally updating wp-config. I tried this on two of my sites and came across different problems: 1. Safari cannot connect to the server' error message 2. The following text displayed on the screen: > > "Front to the WordPress application. This file doesn't do anything, > but loads wp-blog-header.php which does and tells WordPress to load > the theme. > > > ``` * @package WordPress */ /** * Tells WordPress to load the WordPress theme and output it. * * @var bool */ define('WP_USE_THEMES', true); /** Loads the WordPress Environment and Template */ require( dirname( FILE ) . '/wp-blog-header.php' );" ``` Can anyone advise as to how I can make my website display?
You can't find it because it doesn't exist. There is no page at that location. In WordPress everything is either an archive of posts or a post of some type. Pages are posts of type `page` etc. Date archives are archives of posts So if you went to `/category` what would it show? For this reason there is nothing there to show. You would need to write a rewrite rule, manually load a template, and that's assuming it doesn't interfere with other rewrite rules
273,523
<p>I cannot successfully filter posts from some categories and exclude at the same time from others. The code is working perfectly when used to include only posts from a given category. Categories to be included are subcategories and the excluded categories are main categories (they're not parents to the included subcategories)</p> <p>Examples:</p> <p>1) Use both <code>category__in</code> and <code>category__not_in</code> at the same time</p> <pre><code>$wpid = get_category_id($_REQUEST['param']); $cat_arr = array($wpid); $args = array( 'category__in' =&gt; $cat_arr, 'category__not_in' =&gt; array(350,351), 'posts_per_page' =&gt; 10, 'post_status' =&gt; 'publish', 'suppress_filters' =&gt; 0 ); $the_query = new WP_Query( $args ); while ($the_query -&gt; have_posts()){ . . } </code></pre> <p>2) Use only <code>category__in</code> with negative values:</p> <pre><code>$wpid = get_category_id($_REQUEST['param']); $cat_arr = array($wpid); array_push($cat_arr, -350, -351); $args = array( 'category__in' =&gt; $cat_arr, 'posts_per_page' =&gt; 10, 'post_status' =&gt; 'publish', 'suppress_filters' =&gt; 0 ); $the_query = new WP_Query( $args ); while ($the_query -&gt; have_posts()){ . . } </code></pre>
[ { "answer_id": 273496, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 1, "selected": false, "text": "<p>You can't find it because it doesn't exist. There is no page at that location.</p>\n\n<p>In WordPress everyt...
2017/07/16
[ "https://wordpress.stackexchange.com/questions/273523", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1210/" ]
I cannot successfully filter posts from some categories and exclude at the same time from others. The code is working perfectly when used to include only posts from a given category. Categories to be included are subcategories and the excluded categories are main categories (they're not parents to the included subcategories) Examples: 1) Use both `category__in` and `category__not_in` at the same time ``` $wpid = get_category_id($_REQUEST['param']); $cat_arr = array($wpid); $args = array( 'category__in' => $cat_arr, 'category__not_in' => array(350,351), 'posts_per_page' => 10, 'post_status' => 'publish', 'suppress_filters' => 0 ); $the_query = new WP_Query( $args ); while ($the_query -> have_posts()){ . . } ``` 2) Use only `category__in` with negative values: ``` $wpid = get_category_id($_REQUEST['param']); $cat_arr = array($wpid); array_push($cat_arr, -350, -351); $args = array( 'category__in' => $cat_arr, 'posts_per_page' => 10, 'post_status' => 'publish', 'suppress_filters' => 0 ); $the_query = new WP_Query( $args ); while ($the_query -> have_posts()){ . . } ```
You can't find it because it doesn't exist. There is no page at that location. In WordPress everything is either an archive of posts or a post of some type. Pages are posts of type `page` etc. Date archives are archives of posts So if you went to `/category` what would it show? For this reason there is nothing there to show. You would need to write a rewrite rule, manually load a template, and that's assuming it doesn't interfere with other rewrite rules
273,545
<p>I am attempting to import several users, who each should have a connection with a term in a taxonomy named "firm" - but I don't know how to make the connection...</p> <p><strong>Background:</strong></p> <p>FYI, I have already enabled WordPress taxonomy support for Users using plugin <a href="https://wordpress.org/plugins/lh-user-taxonomies/" rel="nofollow noreferrer">LH User Taxonomies</a>, and taxonomy "firm" has already been registered. I am importing using plugin <a href="http://www.wpallimport.com/" rel="nofollow noreferrer">WPAllImport</a>.</p> <p>65 "firms" terms have been created via prior WPAllImport import. Term slugs underwent text processing on inbound company name field <code>$company</code> to <a href="https://stackoverflow.com/questions/40641973/php-to-convert-string-to-slug">strip spaces and convert to lowercase</a>, in order to create a clean term slug.</p> <p>All this is set up, and the question is not about enabling taxonomy support for Users.</p> <p><strong>The problem:</strong></p> <p>I am now importing many Users, and need to connect them to an existing "firm" term (ie. the company they work for). Unfortunately, WPAllImport does not support import to taxonomy terms for Users - but it does support PHP functions executed upon each user import, and actions like pmxi_after_xml_import, which fires after import.</p> <p>The best way to match seems to be via slug - that is, matching inbound User field <code>$company</code>, after stripping spaces, against a "firm" term with matching unique slug. But how do I do this, and then how do we make the association in the database?</p> <p>On each individual User import, logic may look something like this:</p> <ul> <li>Identify inbound string <code>$company</code></li> <li>Strip spaces and make <code>$company</code> lowercase using my <code>convert_company_name()</code> function.</li> <li>Identify taxonomy "firms".</li> <li>Step through "firms" taxonomy to find a term whose slug matches our processed <code>$company</code> string (eg. "widgetsinc" for User's processed <code>$company</code>, matching "widgetsinc" term slug)</li> <li>Associate this User with that slug, ie. set the term.</li> <li>Any appropriate fallback.</li> </ul> <p>I'm not sure how any of the code would be written for this.</p> <p><code>wp set object terms</code> seems like it might be involved?</p> <p><strong>Edit (2):</strong></p> <p>I think I have learned how to do a lot here. This seems to work, to a point...</p> <pre><code>// Relate user to "firm" taxonomy terms function relate_user_to_firm($company, $username){ // convert company name to slug format $company_slug = lowercase_and_strip($company); // use slug to find corresponding taxonomy term $term = get_term_by('slug', $company_slug, 'firm'); // get the object id of this term $mytermid = $term-&gt;term_id; // get user's ID $user = get_user_by('login', $username); $user_id = $user-&gt;ID; // *** relate user to this term *** wp_set_object_terms( $user_id, $mytermid, 'firm' ); } </code></pre> <p>The trouble is, whilst the correct terms show under the "Firms" column on my Users listing page, the Users count against the actual term on the Firms listing page is not updated, it still shows 0. What's going on there?</p>
[ { "answer_id": 273590, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>users are humans (or extensions of humans) that have some level of admin access, taxonomies are for \"cat...
2017/07/16
[ "https://wordpress.stackexchange.com/questions/273545", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/39300/" ]
I am attempting to import several users, who each should have a connection with a term in a taxonomy named "firm" - but I don't know how to make the connection... **Background:** FYI, I have already enabled WordPress taxonomy support for Users using plugin [LH User Taxonomies](https://wordpress.org/plugins/lh-user-taxonomies/), and taxonomy "firm" has already been registered. I am importing using plugin [WPAllImport](http://www.wpallimport.com/). 65 "firms" terms have been created via prior WPAllImport import. Term slugs underwent text processing on inbound company name field `$company` to [strip spaces and convert to lowercase](https://stackoverflow.com/questions/40641973/php-to-convert-string-to-slug), in order to create a clean term slug. All this is set up, and the question is not about enabling taxonomy support for Users. **The problem:** I am now importing many Users, and need to connect them to an existing "firm" term (ie. the company they work for). Unfortunately, WPAllImport does not support import to taxonomy terms for Users - but it does support PHP functions executed upon each user import, and actions like pmxi\_after\_xml\_import, which fires after import. The best way to match seems to be via slug - that is, matching inbound User field `$company`, after stripping spaces, against a "firm" term with matching unique slug. But how do I do this, and then how do we make the association in the database? On each individual User import, logic may look something like this: * Identify inbound string `$company` * Strip spaces and make `$company` lowercase using my `convert_company_name()` function. * Identify taxonomy "firms". * Step through "firms" taxonomy to find a term whose slug matches our processed `$company` string (eg. "widgetsinc" for User's processed `$company`, matching "widgetsinc" term slug) * Associate this User with that slug, ie. set the term. * Any appropriate fallback. I'm not sure how any of the code would be written for this. `wp set object terms` seems like it might be involved? **Edit (2):** I think I have learned how to do a lot here. This seems to work, to a point... ``` // Relate user to "firm" taxonomy terms function relate_user_to_firm($company, $username){ // convert company name to slug format $company_slug = lowercase_and_strip($company); // use slug to find corresponding taxonomy term $term = get_term_by('slug', $company_slug, 'firm'); // get the object id of this term $mytermid = $term->term_id; // get user's ID $user = get_user_by('login', $username); $user_id = $user->ID; // *** relate user to this term *** wp_set_object_terms( $user_id, $mytermid, 'firm' ); } ``` The trouble is, whilst the correct terms show under the "Firms" column on my Users listing page, the Users count against the actual term on the Firms listing page is not updated, it still shows 0. What's going on there?
The function wp\_set\_object\_terms relates to objects (posts, page, etc). You better use usermeta - update\_usermeta. E.g `update_usermeta( $user_id, 'company', $company_id );` Wordpress is built by two major database tables (wp\_posts and wp\_users) and two (meta tables wp\_postmeta and wp\_usermeta). It seems that the term tables (wp\_terms and others) relates to wp\_posts. I dealing with the same need (relate user to a company). I thought to use terms, but I will use usermeta.
273,558
<p>So I made a couple of custom taxonomies to add multiple categories to a page/project. (single-work.php) The default one (built in category) being <code>project type</code>, and the two new ones being <code>client</code> and <code>agency</code>.</p> <p>Basically I use the same code for all three, but I just noticed that what it's doing for the two custom categories is basically reading out EVERY tag I've added to different projects, instead of only showing the tag that's selected for that specific page.</p> <p>In other words, it's basically just showing every tag that can be found under the "Choose from the most used tags" area. Despite only a single tag being selected for each project.</p> <p>I hope that was somewhat clear :)</p> <p>Here's the code I'm using:</p> <pre><code>&lt;?php $terms = get_terms( 'portfolio_tags_client' ); foreach ( $terms as $term ) { $term_link = get_term_link( $term ); if ( is_wp_error( $term_link ) ) { continue; } echo 'Client: &lt;a href="' . esc_url( $term_link ) . '"&gt;' . $term-&gt;name . '&lt;/a&gt;&amp;nbsp;&lt;br /&gt;'; } ?&gt; </code></pre> <p>And here's the taxonomy it's coming out of, if that helps:</p> <pre><code>register_taxonomy( 'portfolio_tags_client', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces). 'work', // Post type name array( 'hierarchical' =&gt; false, 'label' =&gt; 'Clients', // Display name 'singular_name' =&gt; 'Client', 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'client', // This controls the base slug that will display before each term 'with_front' =&gt; false // Don't display the category base before ) ) ); </code></pre> <p>Does anyone know what it could be? I've spent way more time than I'd like to admit trying to fix this :)</p> <p><strong>UPDATE</strong> Fixed! Thanks so much for the help guys. I really appreciate it. Here's the final code:</p> <pre><code>&lt;?php $post_tags = get_the_terms(get_the_ID(), 'portfolio_tags_client'); if ($post_tags) { foreach($post_tags as $tag) { echo 'Client: &lt;a href="'.get_tag_link($tag-&gt;term_id).'" title="'.$tag-&gt;name.'"&gt;'. $tag-&gt;name .'&lt;/a&gt;&amp;nbsp;&lt;br /&gt;'; } } ?&gt; </code></pre>
[ { "answer_id": 273561, "author": "montrealist", "author_id": 8105, "author_profile": "https://wordpress.stackexchange.com/users/8105", "pm_score": 0, "selected": false, "text": "<p>You can set the post status to <code>trash</code>.</p>\n\n<pre><code>$post_id = 1; // change this to your p...
2017/07/16
[ "https://wordpress.stackexchange.com/questions/273558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123968/" ]
So I made a couple of custom taxonomies to add multiple categories to a page/project. (single-work.php) The default one (built in category) being `project type`, and the two new ones being `client` and `agency`. Basically I use the same code for all three, but I just noticed that what it's doing for the two custom categories is basically reading out EVERY tag I've added to different projects, instead of only showing the tag that's selected for that specific page. In other words, it's basically just showing every tag that can be found under the "Choose from the most used tags" area. Despite only a single tag being selected for each project. I hope that was somewhat clear :) Here's the code I'm using: ``` <?php $terms = get_terms( 'portfolio_tags_client' ); foreach ( $terms as $term ) { $term_link = get_term_link( $term ); if ( is_wp_error( $term_link ) ) { continue; } echo 'Client: <a href="' . esc_url( $term_link ) . '">' . $term->name . '</a>&nbsp;<br />'; } ?> ``` And here's the taxonomy it's coming out of, if that helps: ``` register_taxonomy( 'portfolio_tags_client', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces). 'work', // Post type name array( 'hierarchical' => false, 'label' => 'Clients', // Display name 'singular_name' => 'Client', 'query_var' => true, 'rewrite' => array( 'slug' => 'client', // This controls the base slug that will display before each term 'with_front' => false // Don't display the category base before ) ) ); ``` Does anyone know what it could be? I've spent way more time than I'd like to admit trying to fix this :) **UPDATE** Fixed! Thanks so much for the help guys. I really appreciate it. Here's the final code: ``` <?php $post_tags = get_the_terms(get_the_ID(), 'portfolio_tags_client'); if ($post_tags) { foreach($post_tags as $tag) { echo 'Client: <a href="'.get_tag_link($tag->term_id).'" title="'.$tag->name.'">'. $tag->name .'</a>&nbsp;<br />'; } } ?> ```
You can move the post to Trash before you save it or publish: [![enter image description here](https://i.stack.imgur.com/olHzC.png)](https://i.stack.imgur.com/olHzC.png) Or you can do it later, from the post list: [![enter image description here](https://i.stack.imgur.com/Ng1mh.png)](https://i.stack.imgur.com/Ng1mh.png) Later you can empty Trash or it will automatically delete everything from Trash what is older than a month.
273,572
<p>I am using WordPress to develop a picture gallery website. I have albums and galleries, with different permalinks...<code>http://url.com/albums</code> and <code>http://url.com/gallery</code>, but only the albums appear in the main navigation.</p> <p>The code for my navigation looks like:</p> <pre><code>&lt;div id="nav"&gt; &lt;ul&gt; &lt;?php wp_list_pages("title_li="); ?&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Because I am using the <code>wp_list_pages()</code> function, the current page that you're on gets a <code>current_page_item</code> class added to the <code>li</code> tag.</p> <p>The gallery page is not part of the main navigation, so when someone is viewing one of the gallery pages, nothing is highlighted in the main navigation.</p> <p>I'd like to highlight the album page in the main navigation when someone is viewing a gallery page. Because each gallery is in album, it makes sense to highlight that page.</p> <p>Can anyone point me in the right direction?</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 273653, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 2, "selected": true, "text": "<p>The <a href=\"https://developer.wordpress.org/reference/hooks/page_css_class/\" rel=\"nofollow noreferrer\"><code>p...
2017/07/17
[ "https://wordpress.stackexchange.com/questions/273572", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I am using WordPress to develop a picture gallery website. I have albums and galleries, with different permalinks...`http://url.com/albums` and `http://url.com/gallery`, but only the albums appear in the main navigation. The code for my navigation looks like: ``` <div id="nav"> <ul> <?php wp_list_pages("title_li="); ?> </ul> </div> ``` Because I am using the `wp_list_pages()` function, the current page that you're on gets a `current_page_item` class added to the `li` tag. The gallery page is not part of the main navigation, so when someone is viewing one of the gallery pages, nothing is highlighted in the main navigation. I'd like to highlight the album page in the main navigation when someone is viewing a gallery page. Because each gallery is in album, it makes sense to highlight that page. Can anyone point me in the right direction? Thanks, Josh
The [`page_css_class` filter](https://developer.wordpress.org/reference/hooks/page_css_class/) lets you modify the classes each menu item gets. Here we check if we are currently viewing a singular `envira` post type and the menu item slug is `gallery`. In that case we add a class to the array of default classes passed to the function. ``` function wpd_page_css_class( $css_class, $page ){ if( is_singular( 'envira' ) && 'albums' == $page->post_name ){ $css_class[] = 'current_page_item'; } return $css_class; } add_filter( 'page_css_class', 'wpd_page_css_class', 10, 2 ); ```
273,582
<p>Let suppose I have made a file in my theme folder (with the name c.php) and I want it to link it with a custom button (that I have made in post/page) in admin using GET action. How can I achieve that</p>
[ { "answer_id": 273623, "author": "lky", "author_id": 102937, "author_profile": "https://wordpress.stackexchange.com/users/102937", "pm_score": 0, "selected": false, "text": "<p>Im a little unsure what you are trying to achieve but can't you link the button like:</p>\n\n<pre><code>href=\"...
2017/07/17
[ "https://wordpress.stackexchange.com/questions/273582", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108146/" ]
Let suppose I have made a file in my theme folder (with the name c.php) and I want it to link it with a custom button (that I have made in post/page) in admin using GET action. How can I achieve that
Finally, I make it, the way without losing the access to WordPress environment: ``` add_action( 'edit_form_after_title', 'custom_button' ); function custom_button() { $button = sprintf('<a href="%1$s" class="button button-primary button-large">%2$s</a>', esc_url( add_query_arg( 'link' , true, get_the_permalink() ) ), 'Custom Button' ); print_r($button); } ``` **Update:** ***Hint***: Please make a function for validation the url for ssl and wrap get\_the\_permalink() inside it.
273,597
<p>I need an extra pair of eyes on this. I have customized a block of code in a function of a commercial theme, which is the following code: </p> <pre><code> &lt;div class="author-description"&gt; &lt;h5&gt;&lt;span class="fn"&gt;&lt;?php the_author_link(); ?&gt;&lt;/span&gt;&lt;/h5&gt; &lt;p class="note"&gt;&lt;?php the_author_meta( 'description', $id ); ?&gt;&lt;/p&gt; &lt;?php csco_post_author_social_accounts( $id ); ?&gt; &lt;/div&gt; </code></pre> <p>There's <code>the_author_link()</code> in it, which states either the name of the user, or the link to the website of the user, which can be filled in the admin users profile. The <code>the_author_link()</code> does not accept any parameters, according to the Codex. </p> <p>I would like this function to open the link in a new window. Do I need to break the function down?</p>
[ { "answer_id": 273623, "author": "lky", "author_id": 102937, "author_profile": "https://wordpress.stackexchange.com/users/102937", "pm_score": 0, "selected": false, "text": "<p>Im a little unsure what you are trying to achieve but can't you link the button like:</p>\n\n<pre><code>href=\"...
2017/07/17
[ "https://wordpress.stackexchange.com/questions/273597", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60297/" ]
I need an extra pair of eyes on this. I have customized a block of code in a function of a commercial theme, which is the following code: ``` <div class="author-description"> <h5><span class="fn"><?php the_author_link(); ?></span></h5> <p class="note"><?php the_author_meta( 'description', $id ); ?></p> <?php csco_post_author_social_accounts( $id ); ?> </div> ``` There's `the_author_link()` in it, which states either the name of the user, or the link to the website of the user, which can be filled in the admin users profile. The `the_author_link()` does not accept any parameters, according to the Codex. I would like this function to open the link in a new window. Do I need to break the function down?
Finally, I make it, the way without losing the access to WordPress environment: ``` add_action( 'edit_form_after_title', 'custom_button' ); function custom_button() { $button = sprintf('<a href="%1$s" class="button button-primary button-large">%2$s</a>', esc_url( add_query_arg( 'link' , true, get_the_permalink() ) ), 'Custom Button' ); print_r($button); } ``` **Update:** ***Hint***: Please make a function for validation the url for ssl and wrap get\_the\_permalink() inside it.
273,654
<p>I can't access the dashboard of the second site. When I go to the second site, I only see the HTML page without the style (css).</p> <p>When I try to access the dashboard (from Safari), I get this message from the browser: "too many redirects occurred trying to open".</p> <p>Subsite set-up</p> <p>example.com (works)</p> <p>example.com/secondary (doesn't work)</p> <p>I tried disabling all plugins and change to the default theme. It still doesn't work. Here's what in my .htaccess file:</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre>
[ { "answer_id": 273619, "author": "Chris Cox", "author_id": 1718, "author_profile": "https://wordpress.stackexchange.com/users/1718", "pm_score": 1, "selected": false, "text": "<p>It's in the filename. single-$posttype.php, archive-$posttype.php</p>\n" }, { "answer_id": 273622, ...
2017/07/17
[ "https://wordpress.stackexchange.com/questions/273654", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123998/" ]
I can't access the dashboard of the second site. When I go to the second site, I only see the HTML page without the style (css). When I try to access the dashboard (from Safari), I get this message from the browser: "too many redirects occurred trying to open". Subsite set-up example.com (works) example.com/secondary (doesn't work) I tried disabling all plugins and change to the default theme. It still doesn't work. Here's what in my .htaccess file: ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] </IfModule> # END WordPress ```
You need to create the template files within your theme using the correct naming. Please see: <https://developer.wordpress.org/themes/template-files-section/page-template-files/#creating-page-templates-for-specific-post-types>
273,678
<p>I am sending php array using serialise but the response is different. Here is my attempt</p> <pre><code>$array = serialize($out); var_dump(serialize($array)); //string(58) "s:50:"a:2:{s:9:"sidebar-1";i:5;s:12:"footer-insta";i:2;}";" </code></pre> <p>The way I am sending this value, </p> <pre><code>echo '&lt;div data-ad = '.$array.' class="ash_loadmore"&gt;&lt;span&gt;LOAD MORE&lt;/span&gt;&lt;/div&gt;'; </code></pre> <p>As I am sending the serialised value using ajax, the value that ajax response give me,</p> <pre><code>string(54) "a:2:{s:9:\"sidebar-1\";i:5;s:12:\"footer-insta\";i:2;}" </code></pre> <p>I need the exact value as I have unserialise again to make it array. Why there is extra <code>\</code> and output is different. </p>
[ { "answer_id": 273680, "author": "CodeMascot", "author_id": 44192, "author_profile": "https://wordpress.stackexchange.com/users/44192", "pm_score": 0, "selected": false, "text": "<p>Well, this <code>\\</code> is getting added to escape the <code>\"</code>. For example you are storing the...
2017/07/17
[ "https://wordpress.stackexchange.com/questions/273678", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48294/" ]
I am sending php array using serialise but the response is different. Here is my attempt ``` $array = serialize($out); var_dump(serialize($array)); //string(58) "s:50:"a:2:{s:9:"sidebar-1";i:5;s:12:"footer-insta";i:2;}";" ``` The way I am sending this value, ``` echo '<div data-ad = '.$array.' class="ash_loadmore"><span>LOAD MORE</span></div>'; ``` As I am sending the serialised value using ajax, the value that ajax response give me, ``` string(54) "a:2:{s:9:\"sidebar-1\";i:5;s:12:\"footer-insta\";i:2;}" ``` I need the exact value as I have unserialise again to make it array. Why there is extra `\` and output is different.
Well it seems @JacobPeattie mentioned to use json, I just echoing that. 1. First json encode the variable `$array = json_encode($out);` 2. Then send this value `echo '<div data-ad = '.$array.' class="ash_loadmore"><span>LOAD MORE</span></div>';` 3. To get that `echo json_encode($_POST['ad'])` I think that's it.BTW you don't have now that string problem as the output will be like this `{"footer-insta":2,"sidebar-1":3}` you see it is wrapped by `{}`
273,695
<p>I have two meta_keys on a custom post type. I want to be able to query all of these posts, and order them by the two <code>meta_key</code>, one taking precedence over the other.</p> <p>I.e. I have one <code>meta_key</code> called <code>stickied</code>, these should always appear first. The second <code>meta_key</code> is <code>popularity</code>, which is a basic hit count for that post.</p> <p>When I use <code>meta_query</code>, it seems that posts <em>without</em> the meta keys initialized will not appear in the result set. I want <em>all</em> posts regardless of whether they have the <code>meta_key</code> initialized or not, and <em>then</em> order them based on those <code>meta_key</code>.</p> <p>Is this possible?</p>
[ { "answer_id": 273697, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>As I understand, you are trying to sort the post by meta values. In such cases, you can use <code>'orderby ...
2017/07/18
[ "https://wordpress.stackexchange.com/questions/273695", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124056/" ]
I have two meta\_keys on a custom post type. I want to be able to query all of these posts, and order them by the two `meta_key`, one taking precedence over the other. I.e. I have one `meta_key` called `stickied`, these should always appear first. The second `meta_key` is `popularity`, which is a basic hit count for that post. When I use `meta_query`, it seems that posts *without* the meta keys initialized will not appear in the result set. I want *all* posts regardless of whether they have the `meta_key` initialized or not, and *then* order them based on those `meta_key`. Is this possible?
I had a similar issue but couldn't solved with the snippets on this thread. I had to order a query by: 1. all 'featured' posts first (***is\_it\_a\_featured\_etf***) and 2. by a numeric field (***etf\_aum***) in DESC order after the featured ones. My solution: ``` 'meta_query' => [ 'relation' => 'OR', 'etf_aum' => array( 'key' => 'etf_aum', 'type' => 'NUMERIC', 'compare' => 'EXISTS', ), 'is_it_a_featured_etf' => array( 'key' => 'is_it_a_featured_etf', 'compare' => 'EXISTS', 'value' => '1', 'operator' => '=', ), ], 'orderby' => [ 'is_it_a_featured_etf' => 'ASC', 'etf_aum' => 'DESC', ] ```
273,704
<p>Since some updates of WooCommerce, Wordpress, Theme etc. on our product pages in the product-tab "additional information" some attributes are now linkable (to some automatic created pages). I cant find the setting how to disable it and even so no php solution for functions.php. I neither want that automatic pages then the links.</p> <p><a href="https://i.stack.imgur.com/0o8AT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0o8AT.png" alt="enter image description here"></a></p> <p>Do you know how to fix that?</p>
[ { "answer_id": 276255, "author": "Krystian", "author_id": 122426, "author_profile": "https://wordpress.stackexchange.com/users/122426", "pm_score": 1, "selected": true, "text": "<p>I couldnt find a real Solution, but I used CSS to visually hide the link, but actually the link still exist...
2017/07/18
[ "https://wordpress.stackexchange.com/questions/273704", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122426/" ]
Since some updates of WooCommerce, Wordpress, Theme etc. on our product pages in the product-tab "additional information" some attributes are now linkable (to some automatic created pages). I cant find the setting how to disable it and even so no php solution for functions.php. I neither want that automatic pages then the links. [![enter image description here](https://i.stack.imgur.com/0o8AT.png)](https://i.stack.imgur.com/0o8AT.png) Do you know how to fix that?
I couldnt find a real Solution, but I used CSS to visually hide the link, but actually the link still exists, but its not clickable anymore. Note: change this CSS to your font-color: ``` .shop_attributes a[rel="tag"] { pointer-events: none; cursor: default; color: #888; } ```
273,720
<p>I want to apply my valid custom admin bar color scheme to front-end toolbar.</p> <p>I am using this code to do it:</p> <pre><code>add_action( 'wp_enqueue_scripts', function () { wp_enqueue_style( 'color-admin-bar', PATH_TO_CSS, array( 'admin-bar' ) ); } ); </code></pre> <p>However it causes some strange bugs.</p> <p>For example, when I hover a button it is colored with deep blue which is ok. But when it loses hover for 1 second it changes back to original color cheme (black background and blue text color).</p> <p><a href="https://i.stack.imgur.com/VxiZy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VxiZy.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/zfLAo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zfLAo.png" alt="enter image description here"></a></p> <p>I guess this is happening because of the default admin bar stylesheet:</p> <pre><code>&lt;link rel='stylesheet' id='admin-bar-css' href='http://neuralnet.info.loc/wp-includes/css/admin-bar.min.css?ver=4.8' type='text/css' media='all' /&gt; </code></pre> <p>But I can't turn it off because whole toolbar layout gets broken.</p> <p>So how to properly replace admin bar color scheme in front-end?</p> <p><strong>UPD</strong></p> <p>I did look in admin-bar.css and it seems that it is a bit different from back-end admin bar...</p>
[ { "answer_id": 273724, "author": "Chris Cox", "author_id": 1718, "author_profile": "https://wordpress.stackexchange.com/users/1718", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://css-tricks.com/forums/topic/styling-wordpress-admin-bar/\" rel=\"nofollow noreferrer\">Thi...
2017/07/18
[ "https://wordpress.stackexchange.com/questions/273720", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109919/" ]
I want to apply my valid custom admin bar color scheme to front-end toolbar. I am using this code to do it: ``` add_action( 'wp_enqueue_scripts', function () { wp_enqueue_style( 'color-admin-bar', PATH_TO_CSS, array( 'admin-bar' ) ); } ); ``` However it causes some strange bugs. For example, when I hover a button it is colored with deep blue which is ok. But when it loses hover for 1 second it changes back to original color cheme (black background and blue text color). [![enter image description here](https://i.stack.imgur.com/VxiZy.png)](https://i.stack.imgur.com/VxiZy.png) [![enter image description here](https://i.stack.imgur.com/zfLAo.png)](https://i.stack.imgur.com/zfLAo.png) I guess this is happening because of the default admin bar stylesheet: ``` <link rel='stylesheet' id='admin-bar-css' href='http://neuralnet.info.loc/wp-includes/css/admin-bar.min.css?ver=4.8' type='text/css' media='all' /> ``` But I can't turn it off because whole toolbar layout gets broken. So how to properly replace admin bar color scheme in front-end? **UPD** I did look in admin-bar.css and it seems that it is a bit different from back-end admin bar...
You make it the wrong way. First, you do double work. Enqueue inside enqueue. You don't need `wp_enqueue_scripts()`: ``` wp_enqueue_style( 'color-admin-bar', PATH_TO_CSS, array( 'admin-bar' ) ); ``` Second. Don't use anonymous functions with WordPress Actions. Once-for-all-time is OK, but while the project is growing up you can collide with the inability to dequeue that style when you'll want to. The solution. Make a copy of the `admin-bar.css` and correct it to fit your needs. Then minimize it using any tool you can google for (optionally). Dequeue the original admin bar: ``` <?php add_action('admin_init', 'my_remove_admin_bar'); function my_remove_admin_bar() { wp_dequeue_style('admin-bar') } ``` And enqueue your new-laid `my-admin-bar.css` Slight hitch. You can face the problem when the whole admin bar gets updated to the new look with the new WordPress version.
273,734
<p>When I change <code>WP_PLUGIN_DIR</code> example:</p> <pre><code>define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/../wp-content/renamefolder' ); </code></pre> <p>All plugins are shown and I can activate them. <a href="https://i.stack.imgur.com/z4naU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z4naU.png" alt="enter image description here"></a> </p> <p>But with TinyMCE Advanced when I wrote post, alert message shows <a href="https://i.stack.imgur.com/vEV1Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vEV1Q.png" alt="enter image description here"></a></p> <blockquote> <p>Failed to load plugin: insertdatetime from url ../../wp-content/plugins/tinymce-advanced/mce/insertdatetime/plugin.min.js</p> </blockquote> <p>How to change code in <code>tinymce-advanced.php</code> or how to fix it?</p>
[ { "answer_id": 273751, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 1, "selected": true, "text": "<p><code>WP_PLUGIN_DIR</code> customizes the location of files in filesystem.</p>\n\n<p>Most likely you <em>also</em> n...
2017/07/18
[ "https://wordpress.stackexchange.com/questions/273734", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123978/" ]
When I change `WP_PLUGIN_DIR` example: ``` define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/../wp-content/renamefolder' ); ``` All plugins are shown and I can activate them. [![enter image description here](https://i.stack.imgur.com/z4naU.png)](https://i.stack.imgur.com/z4naU.png) But with TinyMCE Advanced when I wrote post, alert message shows [![enter image description here](https://i.stack.imgur.com/vEV1Q.png)](https://i.stack.imgur.com/vEV1Q.png) > > Failed to load plugin: insertdatetime from url ../../wp-content/plugins/tinymce-advanced/mce/insertdatetime/plugin.min.js > > > How to change code in `tinymce-advanced.php` or how to fix it?
`WP_PLUGIN_DIR` customizes the location of files in filesystem. Most likely you *also* need to customize `WP_PLUGIN_URL`, which customizes client–facing URL location. If you omit this one, WP will decide it based on `WP_CONTENT_URL`, which might not at all point to your new location. Another possibility is that plugin/code in question simply *cannot* handle a custom location. Generally this shouldn't happen under a normal WP API usage and such should be reported to developers as a possible bug.
273,765
<p>I made a large-scale research. But there are no anything what I want. I want to style my options page in a static style file. How can I do that?</p> <p><strong>Sources</strong></p> <pre><code>/* *Create A Simple Theme Options Panel *Exit if accessed directly */ if (!defined('ABSPATH')){ exit; } // Start Class if ( ! class_exists('Azura_Theme_Options')){ class Azura_Theme_Options{ public function __construct(){ // We only need to register the admin panel on the back-end if (is_admin()){ add_action('admin_menu', array( 'Azura_Theme_Options', 'add_admin_menu')); add_action('admin_init', array( 'Azura_Theme_Options', 'register_settings')); } } public static function get_theme_options() { return get_option('theme_options'); } public static function get_theme_option($id) { $options = self::get_theme_options(); if (isset($options[$id])){ return $options[$id]; } } // Add sub menu page public static function add_admin_menu(){ add_menu_page( esc_html__('Azura Panel', 'text-domain'), esc_html__('Azura Panel', 'text-domain'), 'manage_options', 'azura-panel', array('Azura_Theme_Options', 'create_admin_page') ); } /** * Register a setting and its sanitization callback. * We are only registering 1 setting so we can store all options in a single option as * an array. You could, however, register a new setting for each option */ public static function register_settings(){ register_setting('theme_options', 'theme_options', array( 'Azura_Theme_Options', 'sanitize')); } // Sanitization callback public static function sanitize($options){ // If we have options lets sanitize them if ($options){ // Input if (!empty($options['site_name'])){ $options['site_name'] = sanitize_text_field( $options['site_name'] ); }else{ unset($options['site_name']); // Remove from options if empty } // Select if (!empty($options['select_example'])){ $options['select_example'] = sanitize_text_field( $options['select_example'] ); } } // Return sanitized options return $options; } /** * Settings page output */ public static function create_admin_page(){ ?&gt; &lt;div class="wrap"&gt; &lt;h1&gt;&lt;?php esc_html_e('Tema Ayarları', 'text-domain'); ?&gt;&lt;/h1&gt; &lt;form method="post" action="options.php"&gt; &lt;?php settings_fields('theme_options'); ?&gt; &lt;table class="form-table wpex-custom-admin-login-table"&gt; &lt;?php // Text input example ?&gt; &lt;tr valign="top"&gt; &lt;th scope="row"&gt;&lt;?php esc_html_e('Başlık', 'text-domain'); ?&gt;&lt;/th&gt; &lt;td&gt; &lt;?php $value = self::get_theme_option('site_name'); ?&gt; &lt;input type="text" name="theme_options[site_name]" value="&lt;?php echo esc_attr($value); ?&gt;"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr valign="top"&gt; &lt;th scope="row"&gt;&lt;?php esc_html_e('Açıklama', 'text-domain'); ?&gt;&lt;/th&gt; &lt;td&gt; &lt;?php $value = self::get_theme_option('site_desc'); ?&gt; &lt;input type="text" name="theme_options[site_desc]" value="&lt;?php echo esc_attr($value); ?&gt;"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr valign="top"&gt; &lt;th scope="row"&gt;&lt;?php esc_html_e('Buton', 'text-domain'); ?&gt;&lt;/th&gt; &lt;td&gt; &lt;?php $value = self::get_theme_option('top_header_btn'); ?&gt; &lt;input type="text" name="theme_options[top_header_btn]" value="&lt;?php echo esc_attr($value); ?&gt;"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr valign="top"&gt; &lt;th scope="row"&gt;&lt;?php esc_html_e('Buton Link', 'text-domain'); ?&gt;&lt;/th&gt; &lt;td&gt; &lt;?php $value = self::get_theme_option('top_header_btn_link'); ?&gt; &lt;input type="text" name="theme_options[top_header_btn_link]" value="&lt;?php echo esc_attr($value); ?&gt;"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;?php submit_button(); ?&gt; &lt;/form&gt; &lt;/div&gt;&lt;!-- .wrap --&gt; &lt;?php } } } new Azura_Theme_Options(); // Helper function to use in your theme to return a theme option value function myprefix_get_theme_option( $id = '' ) { return Azura_Theme_Options::get_theme_option( $id ); } </code></pre>
[ { "answer_id": 273767, "author": "Chris Cox", "author_id": 1718, "author_profile": "https://wordpress.stackexchange.com/users/1718", "pm_score": -1, "selected": false, "text": "<p>Give your HTML elements existing classes from the WP admin CSS and they'll inherit styles consistent with th...
2017/07/18
[ "https://wordpress.stackexchange.com/questions/273765", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124103/" ]
I made a large-scale research. But there are no anything what I want. I want to style my options page in a static style file. How can I do that? **Sources** ``` /* *Create A Simple Theme Options Panel *Exit if accessed directly */ if (!defined('ABSPATH')){ exit; } // Start Class if ( ! class_exists('Azura_Theme_Options')){ class Azura_Theme_Options{ public function __construct(){ // We only need to register the admin panel on the back-end if (is_admin()){ add_action('admin_menu', array( 'Azura_Theme_Options', 'add_admin_menu')); add_action('admin_init', array( 'Azura_Theme_Options', 'register_settings')); } } public static function get_theme_options() { return get_option('theme_options'); } public static function get_theme_option($id) { $options = self::get_theme_options(); if (isset($options[$id])){ return $options[$id]; } } // Add sub menu page public static function add_admin_menu(){ add_menu_page( esc_html__('Azura Panel', 'text-domain'), esc_html__('Azura Panel', 'text-domain'), 'manage_options', 'azura-panel', array('Azura_Theme_Options', 'create_admin_page') ); } /** * Register a setting and its sanitization callback. * We are only registering 1 setting so we can store all options in a single option as * an array. You could, however, register a new setting for each option */ public static function register_settings(){ register_setting('theme_options', 'theme_options', array( 'Azura_Theme_Options', 'sanitize')); } // Sanitization callback public static function sanitize($options){ // If we have options lets sanitize them if ($options){ // Input if (!empty($options['site_name'])){ $options['site_name'] = sanitize_text_field( $options['site_name'] ); }else{ unset($options['site_name']); // Remove from options if empty } // Select if (!empty($options['select_example'])){ $options['select_example'] = sanitize_text_field( $options['select_example'] ); } } // Return sanitized options return $options; } /** * Settings page output */ public static function create_admin_page(){ ?> <div class="wrap"> <h1><?php esc_html_e('Tema Ayarları', 'text-domain'); ?></h1> <form method="post" action="options.php"> <?php settings_fields('theme_options'); ?> <table class="form-table wpex-custom-admin-login-table"> <?php // Text input example ?> <tr valign="top"> <th scope="row"><?php esc_html_e('Başlık', 'text-domain'); ?></th> <td> <?php $value = self::get_theme_option('site_name'); ?> <input type="text" name="theme_options[site_name]" value="<?php echo esc_attr($value); ?>"> </td> </tr> <tr valign="top"> <th scope="row"><?php esc_html_e('Açıklama', 'text-domain'); ?></th> <td> <?php $value = self::get_theme_option('site_desc'); ?> <input type="text" name="theme_options[site_desc]" value="<?php echo esc_attr($value); ?>"> </td> </tr> <tr valign="top"> <th scope="row"><?php esc_html_e('Buton', 'text-domain'); ?></th> <td> <?php $value = self::get_theme_option('top_header_btn'); ?> <input type="text" name="theme_options[top_header_btn]" value="<?php echo esc_attr($value); ?>"> </td> </tr> <tr valign="top"> <th scope="row"><?php esc_html_e('Buton Link', 'text-domain'); ?></th> <td> <?php $value = self::get_theme_option('top_header_btn_link'); ?> <input type="text" name="theme_options[top_header_btn_link]" value="<?php echo esc_attr($value); ?>"> </td> </tr> </table> <?php submit_button(); ?> </form> </div><!-- .wrap --> <?php } } } new Azura_Theme_Options(); // Helper function to use in your theme to return a theme option value function myprefix_get_theme_option( $id = '' ) { return Azura_Theme_Options::get_theme_option( $id ); } ```
In your construct function you also need to enqueue a custom stylesheet that will house the CSS to style up your theme options. A simplified example would look like this: ``` function admin_style() { wp_enqueue_style( 'theme-options-style', get_template_directory_uri().'styles/theme-options-style.css'); } add_action('admin_enqueue_scripts', 'admin_style'); ```
273,773
<p>How add, update and retrieve user meta fields with the wp api? I added a function to add a meta field phonenumber to a user. Is a function like this necessary to add meta values to the meta object? The function doesn't add the field to the meta object in the API response but adds it as a new field.</p> <p>The function i have right now:</p> <pre><code>&lt;?php function portal_add_user_field() { register_rest_field( 'user', 'phonenumber', array( 'get_callback' =&gt; function( $user, $field_name, $request ) { return get_user_meta( $user[ 'id' ], $field_name, true ); }, 'update_callback' =&gt; function( $user, $meta_key, $meta_value, $prev_value ) { $ret = update_user_meta( array( $user, $meta_key, $meta_value ); return true; }, 'schema' =&gt; array( 'description' =&gt; __( 'user phonenumber' ), 'type' =&gt; 'string' ), ) ); } add_action( 'rest_api_init', 'portal_add_user_field' ); </code></pre> <p>I also tried to add the phone number field to the user meta with ajax without a extra function like this: (this doesn't save the phone number field)</p> <pre><code>updateUser: function () { var data = { username: this.username, email: this.email, first_name: this.firstname, last_name: this.lastname, meta: { phonenumber: this.phonenumber } }; console.log(data); $.ajax({ method: "POST", url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID, data: data, beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); } }) .done( $.proxy( function() { alert('Account saved'); }, this )) .fail( $.proxy( function( response ) { alert('something went wrong'); }, this )); </code></pre>
[ { "answer_id": 273875, "author": "Maarten Heideman", "author_id": 54693, "author_profile": "https://wordpress.stackexchange.com/users/54693", "pm_score": 2, "selected": true, "text": "<p>found it, first yes for meta data on a user you'll need a custom function like this:</p>\n\n<pre><cod...
2017/07/18
[ "https://wordpress.stackexchange.com/questions/273773", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/54693/" ]
How add, update and retrieve user meta fields with the wp api? I added a function to add a meta field phonenumber to a user. Is a function like this necessary to add meta values to the meta object? The function doesn't add the field to the meta object in the API response but adds it as a new field. The function i have right now: ``` <?php function portal_add_user_field() { register_rest_field( 'user', 'phonenumber', array( 'get_callback' => function( $user, $field_name, $request ) { return get_user_meta( $user[ 'id' ], $field_name, true ); }, 'update_callback' => function( $user, $meta_key, $meta_value, $prev_value ) { $ret = update_user_meta( array( $user, $meta_key, $meta_value ); return true; }, 'schema' => array( 'description' => __( 'user phonenumber' ), 'type' => 'string' ), ) ); } add_action( 'rest_api_init', 'portal_add_user_field' ); ``` I also tried to add the phone number field to the user meta with ajax without a extra function like this: (this doesn't save the phone number field) ``` updateUser: function () { var data = { username: this.username, email: this.email, first_name: this.firstname, last_name: this.lastname, meta: { phonenumber: this.phonenumber } }; console.log(data); $.ajax({ method: "POST", url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID, data: data, beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); } }) .done( $.proxy( function() { alert('Account saved'); }, this )) .fail( $.proxy( function( response ) { alert('something went wrong'); }, this )); ```
found it, first yes for meta data on a user you'll need a custom function like this: ``` <?php function portal_add_user_field() { register_rest_field( 'user', 'userfields', array( 'get_callback' => function( $user, $field_name, $request ) { return get_user_meta( $user[ 'id' ], $field_name, true ); }, 'update_callback' => function($meta_value ) { $havemetafield = get_user_meta(1, 'userfields', false); if ($havemetafield) { $ret = update_user_meta(1, 'userfields', $meta_value ); return true; } else { $ret = add_user_meta( 1, 'userfields', $meta_value ,true ); return true; } }, 'schema' => null ) ); } add_action( 'rest_api_init', 'portal_add_user_field', 10, 2 ); ``` ?> after that with ajax send it like this: ``` updateUser: function () { var data = { userfields: { somefield: this.somefield, somefield2: this.somefield2 } }; console.log(data); $.ajax({ method: "POST", url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID, data: data, beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); } }) .done( $.proxy( function() { alert('Account saved'); }, this )) .fail( $.proxy( function( response ) { alert('something went wrong'); }, this )); } ```
273,790
<p>I am trying to use $wpdb object to get results from a custom table and I get an error when I echo the result:</p> <pre><code>Notice: Undefined property: stdClass::$category in... </code></pre> <p>Here is the PHP code:</p> <pre><code>global $wpdb; $prodCat = $wpdb-&gt;get_results( "SELECT * FROM product_category" , OBJECT_K); foreach ( $prodCat as $row ){ echo $row-&gt;category-name; } </code></pre> <p>Any help is appreciated.</p>
[ { "answer_id": 273875, "author": "Maarten Heideman", "author_id": 54693, "author_profile": "https://wordpress.stackexchange.com/users/54693", "pm_score": 2, "selected": true, "text": "<p>found it, first yes for meta data on a user you'll need a custom function like this:</p>\n\n<pre><cod...
2017/07/18
[ "https://wordpress.stackexchange.com/questions/273790", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45250/" ]
I am trying to use $wpdb object to get results from a custom table and I get an error when I echo the result: ``` Notice: Undefined property: stdClass::$category in... ``` Here is the PHP code: ``` global $wpdb; $prodCat = $wpdb->get_results( "SELECT * FROM product_category" , OBJECT_K); foreach ( $prodCat as $row ){ echo $row->category-name; } ``` Any help is appreciated.
found it, first yes for meta data on a user you'll need a custom function like this: ``` <?php function portal_add_user_field() { register_rest_field( 'user', 'userfields', array( 'get_callback' => function( $user, $field_name, $request ) { return get_user_meta( $user[ 'id' ], $field_name, true ); }, 'update_callback' => function($meta_value ) { $havemetafield = get_user_meta(1, 'userfields', false); if ($havemetafield) { $ret = update_user_meta(1, 'userfields', $meta_value ); return true; } else { $ret = add_user_meta( 1, 'userfields', $meta_value ,true ); return true; } }, 'schema' => null ) ); } add_action( 'rest_api_init', 'portal_add_user_field', 10, 2 ); ``` ?> after that with ajax send it like this: ``` updateUser: function () { var data = { userfields: { somefield: this.somefield, somefield2: this.somefield2 } }; console.log(data); $.ajax({ method: "POST", url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID, data: data, beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); } }) .done( $.proxy( function() { alert('Account saved'); }, this )) .fail( $.proxy( function( response ) { alert('something went wrong'); }, this )); } ```
273,801
<p>I've got a local install of WP and I've copied my live site's uploads dir to the proper spot in wp-content, but Media Library isn't showing a single image.</p> <p>I've recursively set uploads and subsequent dirs to 755, that didn't fix it. I checked the upload_path in wp_options and it's blank like it is on the live server.</p> <p>FYI, the import of posts I did came from a multi-site install where the live site is.</p> <p>I'm at a loss as to where I can fix this missing link to the uploads folder. Posts are seeing the images in the uploads and rendering fine with the local dev url path in the images.</p> <p>Thanks for any guidance!</p> <p><a href="https://i.stack.imgur.com/ifxLM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ifxLM.png" alt="my empty media library on local"></a></p> <p><a href="https://i.stack.imgur.com/icQFi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/icQFi.png" alt="my folder structure for the local install"></a></p>
[ { "answer_id": 273875, "author": "Maarten Heideman", "author_id": 54693, "author_profile": "https://wordpress.stackexchange.com/users/54693", "pm_score": 2, "selected": true, "text": "<p>found it, first yes for meta data on a user you'll need a custom function like this:</p>\n\n<pre><cod...
2017/07/18
[ "https://wordpress.stackexchange.com/questions/273801", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124126/" ]
I've got a local install of WP and I've copied my live site's uploads dir to the proper spot in wp-content, but Media Library isn't showing a single image. I've recursively set uploads and subsequent dirs to 755, that didn't fix it. I checked the upload\_path in wp\_options and it's blank like it is on the live server. FYI, the import of posts I did came from a multi-site install where the live site is. I'm at a loss as to where I can fix this missing link to the uploads folder. Posts are seeing the images in the uploads and rendering fine with the local dev url path in the images. Thanks for any guidance! [![my empty media library on local](https://i.stack.imgur.com/ifxLM.png)](https://i.stack.imgur.com/ifxLM.png) [![my folder structure for the local install](https://i.stack.imgur.com/icQFi.png)](https://i.stack.imgur.com/icQFi.png)
found it, first yes for meta data on a user you'll need a custom function like this: ``` <?php function portal_add_user_field() { register_rest_field( 'user', 'userfields', array( 'get_callback' => function( $user, $field_name, $request ) { return get_user_meta( $user[ 'id' ], $field_name, true ); }, 'update_callback' => function($meta_value ) { $havemetafield = get_user_meta(1, 'userfields', false); if ($havemetafield) { $ret = update_user_meta(1, 'userfields', $meta_value ); return true; } else { $ret = add_user_meta( 1, 'userfields', $meta_value ,true ); return true; } }, 'schema' => null ) ); } add_action( 'rest_api_init', 'portal_add_user_field', 10, 2 ); ``` ?> after that with ajax send it like this: ``` updateUser: function () { var data = { userfields: { somefield: this.somefield, somefield2: this.somefield2 } }; console.log(data); $.ajax({ method: "POST", url: wpApiSettings.current_domain + '/wp-json/wp/v2/users/' + wpApiSettings.current_user.ID, data: data, beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); } }) .done( $.proxy( function() { alert('Account saved'); }, this )) .fail( $.proxy( function( response ) { alert('something went wrong'); }, this )); } ```
273,805
<p>When I write answers for questions on WPSE, or when I want to try a piece of short and simple code, I need a place to quickly test the results without actually doing permanent change to any file. </p> <p>For example, let's say I want to test this:</p> <pre><code>&lt;?php echo get_post_meta(); ?&gt; </code></pre> <p>I can put this at the end of my <code>single.php</code> and open a single post to check the results, but then each time I need to modify my templates and then revert the changes.</p> <p>Is there any way to test WordPress codes quickly? </p> <p>A method that crossed my mind was to create a php file and then load WordPress by using <code>require_once( dirname(__FILE__) . '/wp-load.php' );</code> for development purposes. However I'm not sure if it's the best way to do this.</p>
[ { "answer_id": 273807, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 1, "selected": false, "text": "<p>The answer is quite simple: test your code in WordPress environment.</p>\n\n<p>I have a standard WordPress ins...
2017/07/18
[ "https://wordpress.stackexchange.com/questions/273805", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94498/" ]
When I write answers for questions on WPSE, or when I want to try a piece of short and simple code, I need a place to quickly test the results without actually doing permanent change to any file. For example, let's say I want to test this: ``` <?php echo get_post_meta(); ?> ``` I can put this at the end of my `single.php` and open a single post to check the results, but then each time I need to modify my templates and then revert the changes. Is there any way to test WordPress codes quickly? A method that crossed my mind was to create a php file and then load WordPress by using `require_once( dirname(__FILE__) . '/wp-load.php' );` for development purposes. However I'm not sure if it's the best way to do this.
I actually use free online development environments to test, such as [c9](http://c9.io). It allows very quick installation and setup of wordpress. You can easily try different plugins/codes without endangering your files. Moreover, if you mess any thing up you can always delete that installation and create a new one. Another great feature is the cloning of the environment. So if you are about to work on something dangerous. You can clone your environment prior to it and work freely on the new plugins/themes you are working on. It provides a very nice text editor with similar functions to sublime and great test environment. You can use command line just like any normal server. The only thing to keep in mind is that it is only a development environment. It does not support Production. Besides wordpress, it also provides other dev environment for many other languages. **Edit** Additional Tip: I keep a separate Wordpress installation in c9 with the [unit test data](https://wpcom-themes.svn.automattic.com/demo/theme-unit-test-data.xml) imported. Follow [here](https://codex.wordpress.org/Theme_Unit_Test) for more instructions and the benefit for having test data. This allows me to quickly test someone's code or a new plugin without having to mess with my actual project. This is especially beneficial for [stack](https://wordpress.stackexchange.com) members. [![Image is from their official website](https://i.stack.imgur.com/zpy5V.png)](https://i.stack.imgur.com/zpy5V.png) **Edit 5/9/2018** As of July 14, 2016, Cloud9 is part of Amazon AWS. you can read the announcement of the c9's acquisition by AWS [here](https://c9.io/announcement). Some of the benefits listed on the [official AWS Cloud9](https://aws.amazon.com/cloud9/?origin=c9io) are: * **CODE WITH JUST A BROWSER** *AWS Cloud9 gives you the flexibility to run your development environment on a managed Amazon EC2 instance or any existing Linux server that supports SSH* * **CODE TOGETHER IN REAL TIME** *AWS Cloud9 makes collaborating on code easy. You can share your development environment with your team in just a few clicks and pair program together. While collaborating, your team members can see each other type in real time, and instantly chat with one another from within the IDE.* * **BUILD SERVERLESS APPLICATIONS WITH EASE** *AWS Cloud9 makes it easy to write, run, and debug serverless application* * **DIRECT TERMINAL ACCESS TO AWS** *AWS Cloud9 comes with a terminal that includes sudo privileges to the managed Amazon EC2 instance that is hosting your development environment and a preauthenticated AWS Command Line Interface.* * **START NEW PROJECTS QUICKLY** *AWS Cloud9 makes it easy for you to start new projects. Cloud9’s development environment comes prepackaged with tooling for over 40 programming languages, including Node.js, JavaScript, Python, PHP, Ruby, Go, and C++.*
273,806
<p>In my WordPress site, I created a <code>Singleton</code> inside a custom plugin I have, like this:</p> <pre><code>class VBWpdb { private $trace = array(); public static function get_instance() { static $instance = null; if(null === $instance) { $instance = new static(); } return $instance; } //... </code></pre> <p>So, I'm using <code>VBWpdb::get_instance()</code> in a lot of places of my code to populate <code>$trace</code> array (first var of the class). It works for the purpose of having a trace along my code and this static class is being the only instance during the plugin execution. I tested with arbitrary <code>var_dump</code>'s...</p> <p>The problem is... I want to print that trace once my page is loaded and I'm doing this:</p> <pre><code>add_action('wp_loaded', 'vb_dump_wpdb_trace'); function vb_dump_wpdb_trace() { VBWpdb::get_instance()-&gt;dump(); } </code></pre> <p>It seems that this instance is not being created again, but <code>$trace</code> is <code>NULL</code>.</p> <p>Am I missing something related to object living span on WordPress layers?</p>
[ { "answer_id": 273828, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 0, "selected": false, "text": "<p>Your function <code>get_instance</code> will never create an instance of the class because of ...
2017/07/18
[ "https://wordpress.stackexchange.com/questions/273806", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/77513/" ]
In my WordPress site, I created a `Singleton` inside a custom plugin I have, like this: ``` class VBWpdb { private $trace = array(); public static function get_instance() { static $instance = null; if(null === $instance) { $instance = new static(); } return $instance; } //... ``` So, I'm using `VBWpdb::get_instance()` in a lot of places of my code to populate `$trace` array (first var of the class). It works for the purpose of having a trace along my code and this static class is being the only instance during the plugin execution. I tested with arbitrary `var_dump`'s... The problem is... I want to print that trace once my page is loaded and I'm doing this: ``` add_action('wp_loaded', 'vb_dump_wpdb_trace'); function vb_dump_wpdb_trace() { VBWpdb::get_instance()->dump(); } ``` It seems that this instance is not being created again, but `$trace` is `NULL`. Am I missing something related to object living span on WordPress layers?
You are just doing it wrong. The problem starts with using a singleton, just never do it. You have a class of loggers which logs into some internal buffer. All loggers log into the same buffer, therefor the buffer (`trace` in your case) a static array in the class. No more `get_intance`, just instantiate a new logger and log. This gives you the added flexibility of having several classes of loggers that "output" to the same buffer. We are left with a question of how to inspect the log, and this you do with a static method. I am sure this scheme can be improved by people that are more hard core OOP than me, using singleton is equivalent to using a `namespace` and code written under a namespace is easier to read and use than the singleton, just call a function directly with no need to handle the complications of getting an object first, it is easier to use a function in a hook, etc.