INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Show comments menu in dashboard only if the site has comment I would like to hide "Comments" menu in Dashboard until the site doesn't have any comments. I tried to do this with this below code, but doesn't works: function remove_mainmenu_pages() { global $user_ID; if ( 1 > wp_count_comments( get_the_ID() )->all ) { remove_menu_page( 'edit-comments.php' ); } } add_action( 'admin_menu', 'remove_mainmenu_pages' ); Thanks!
Okay, the solution is this below to hide Comments menu if the site doesn't have any comments (approved, pending, trash or spam). function remove_commentsmenu() { global $user_ID; if ( 1 > wp_count_comments( get_the_ID() )->total_comments && 1 > wp_count_comments( get_the_ID() )->trash ) { remove_menu_page( 'edit-comments.php' ); } } add_action( 'admin_menu', 'remove_commentsmenu' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, menus, comments, dashboard" }
How to subscribe free subscription on user registration in woocommerce subscription plugin? I am using Woocommerce Subscription plugin. I have two types of Subscription plans right now. 1. Premium Subscription 2. Free Subscription When any user registers on my site, I want every user to show default free subsciption subscribed to that account in beginning until it upgrades manually later. Is there any Hook which I can use? I have tried checking in Plugin settings but I didn't find anywhere if I can set a subscription plan 'as default'.
The solution is to create an order, then create a subscription, link the order to the subscription using WooCommerce classes. Below is the link where I found my answer: wordpress.stackexchange.com/questions/202873/ The response given by Jeremy Warne worked for my website's logical flow.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic, hooks, subscription" }
How to translate text in function.php with WPML I added this function to add cash on delivery price and I want to translate the text (cash on delivery) using WPML plugin add_action( 'woocommerce_cart_calculate_fees', 'custom_handling_fee', 10, 1 ); function custom_handling_fee ( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; if ( 'cod' === WC()->session->get('chosen_payment_method') ) { $fee = 10; $cart->add_fee( 'Cash On Delivery', $fee, true ); } }
It should suffice to add a `__()` around your translatable text: add_action( 'woocommerce_cart_calculate_fees', 'custom_handling_fee', 10, 1 ); function custom_handling_fee ( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; if ( 'cod' === WC()->session->get('chosen_payment_method') ) { $fee = 10; $cart->add_fee( __('Cash On Delivery'), $fee, true ); } } You can then scan your theme or plugin for strings in WPML: < and then use the WPML string translation.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, plugin wpml" }
Wordpress Automatic Plugin Update Renames Plugin Directory So I have hooked the wordpress plugin auto updated to effectively redirect my plugin to autoupdate from my own site rather than wordpress.com. The updating process works seemlessly aside from one wierd hitch - the wordpress updater downloads the `my_plugin.zip` file from my server, saves it in a temp directory as `my_plugin-3sd123.tmp` (where the random string is generated by the wp updater to avoid file conflicts) and unzips it to `wp-content/upgrades` which leaves a directory `my_plugin-3sd123` in updates and then it copies this directory to `plugins` and removes the old directory BUT never renames the new one to the old plugin slug.. Should I be writing my plugins to expect this? because I dont see it happening with other plugin updates?
It turns out the answer was simple I didnt have my plugins content in a subdirectory slug inside the zip file eg. I had : my_plugin.zip |- my_plugin.php |- admin |-admin.php I should have had my_plugin.zip |-my_plugin |-my-plugin.php |-admin |-admin.php Once you add that sub directory the auto updated will work as expected
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, plugin development" }
WordPress 5.3 update causes media library file upload to break - Cannot convert undefined or null to object So after updating to WP 5.3 I can no longer use the file upload to choose files to add. I get the following error: Uncaught TypeError: Cannot convert undefined or null to object at g.cleanup (backbone.min.js:1) Error in console: ![enter image description here]( How it shows when I try to choose an image: ![enter image description here]( I have the Classic Editor plugin installed so I can use it the classic way. I have disabled all other unnecessary plugins but the problem still persists. It's only happened since the new WP core update to 5.3 yesterday. Any ideas what's going on here?
Right, so what worked for me was upgrading my PHP version to 7.2 and that did the job. I was using 7.0 before.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 11, "tags": "plugins, media library, core" }
WC_Customer delete function returns error Here is my code: function woo_delete_customer(){ $customer = new WC_Customer(get_current_user_id()); $val = $customer -> delete(); if($val){ $customer -> save(); $data = []; $data['Status'] = 'Customer was successfully deleted'; return new WP_REST_Response( $data, 200 ); } else{ new WP_Error( 'woo_deleting_problems', 'Can\'t delete customer!', array( 'status' => 403, ) ); } } And here is my logs: 2019-11-16T05:29:23+00:00 CRITICAL Call to undefined function wp_delete_user() in /home/test.com/public_html/wp-content/plugins/woocommerce/includes/data-stores/class-wc-customer-data-store.php on line 235 Please help me!((
Welcome! You need to include `'wp-admin/includes/user.php'` before calling `wp_delete_user` function. The reason is, it is an admin functionality and it is not available everywhere in code. In Your case, just put the following line of code at the very beginning of the function. require_once ABSPATH . 'wp-admin/includes/user.php';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, woocommerce offtopic, rest api" }
hover image appears below placeholder instead of overlayed I used padding-bottom calc to stop my text jumping around while the placeholder loaded. This worked, however the hover image which is supposed to display over the top of the placeholder, now appears below it. Ive tried many things and keep messing it up further. Here is a fiddle showing the issue JSFiddle Im not sure why the placeholder is so small in this demo but it appears fine on my page. I am also trying to make the hover image remain as the active image until the next category link is hovered.
I solved this by removing the figure element around the image and applying `style="padding-bottom: calc((height/width)*100%); position: relative"` to the `<div class="img_container"` instead, which contains both the placeholder and the hover image.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, categories, images, jquery, thumbnails" }
Replace "WordPress" word in title of Dashboard I would like to replace the `WordPress` word in title of Dashboard. ![enter image description here]( Original title: Dashboard < Site Title - WordPress Expected result: Dashboard < Site Title - foobar I tried to do this with this below code, but it doesn't do what I expected. add_filter('admin_title', 'my_admin_title', 10, 2); function my_admin_title($admin_title, $title) { return get_bloginfo('name').' &bull; '.$title; }
You've tried correct filter - just needs to update return: function my_admin_title ( $admin_title, $title ) { return $title . ' ‹ ' . get_bloginfo( 'name' ) . ' — ' . 'foobar'; } add_filter( 'admin_title', 'my_admin_title', 10, 2 ); Btw, filter above works only for logged pages, for login page needs to add another filter: add_filter( 'login_title', 'my_admin_title', 10, 2 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "customization, title, dashboard" }
Create cron job for update translations automatically I would like to set cron job in WordPress with WP Crontrol for update translations automatically. If I saw it right I have to create a PHP code (simple plugin) and then schedule it with mentioned plugin. How is it possible?
I found wp cli based solution. These below commands are useful for update translate files for core, themes and plugins: wp language core update wp language theme update --all wp language plugin update --all To schedule these commands, insert this line in crontab: 30 0 * * * wp language core update ; wp language theme update --all ; wp language plugin update --all It will update all translate files once a day. Shorter version of cron job: 30 0 * * * for i in "core update" "theme update --all" "plugin update --all"; do sudo wp language $i; done
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions, translation, wp cron, automatic updates" }
My wordpress site was hacked - is my htaccess file compromised? My Wordpress site (on a shared server) was compromised. It's full of spam links when I do a google site: check. I removed a re-direct through cpanel so at least now the spam pages do not re-direct anymore. The re-direct had a name that was similar to a line in my htaccess file: RewriteRule ^neabsmoiea.md$ "https\:\/\/post.ristourne.co\/Paket_ch\/" [R=301,L] ~ I assume this means the htaccess file was compromised as well? My site's name is in no way related to the words "neabsmoiea" or "ristourne" if that is relevant. Naturally I changed all passwords, but I have no idea how to fix this.
Looks similar to a search redirect. You'll see the results when all of your search results go to someplace else. Lots of ways for it to get in there. But, fix the htaccess. Get a standard one from WP here: < Then, you should change all credentials: hosting, ftp, database, MySQL, and WP admin credentials. Look for unknown WP admin accounts (and extra FTP accounts). Check you wp-settings.php and wp-config.php. Look at the index file to ensure no extra code. Look at all files (via your hosting File Manager) to ensure no extra code. Look for hidden ICO files that contain code. Look at the wp-posts and wp-options tables for extra records that contain just numbers/characters. Cleanup is hard - my process is here < . But even then that process is not perfect. I've got one client with a shared hosting and multiple WP and non-WP sites that keeps getting reinfected. And I've done all of the above stuff. Still haven't figured out where it's coming from.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "hacked" }
Remove all users from site except one using WP CLI I would like to remove all users from WordPress site using WP CLI except one (me, as administrator). This command remove every user: wp user delete $(wp user list --field=ID --number=10) Unfortunately (or not), nobody have any role except the administrator. So I cannot filter based on this information.
Found out you can pass the `--exclude` option to `wp user list` to exclude a user by their ID from the list. So let's assume your user ID is `2` then you could do the following: wp user delete $(wp user list --field=ID --exclude=2) And just to be sure all content gets reassigned to you that would be the following command. wp user delete $(wp user list --field=ID --exclude=2) --reassign=2
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "users, wp cli" }
Can't delete a category in Wordpress I can't delete the Gallon Tanks category from my site, and I have no idea why. My site isn't using the Gallon Tanks category at all in the navmenu. ![enter image description here]( ![enter image description here](
One of the categories is always set as the default category, which will be used for an article, if no other category is selected when the post is created. In your case it looks like Gallon tanks is the default one. You can change the default category from Dashboard > Settings > Writing > Default Post Category. After you've changed the default category, you should be able to delete the unneeded category. <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories" }
Is it possible to publish multiple versions of a single post? I'm assessing WordPress for a short story blog. The blog is to chart my journey as a writer. To this end, I'm looking to post a short story and then, perhaps months/years later, post a revision that (hopefully) will be better. When a reader views a short story post, they should see the latest version but then also have access to previous published versions. Having done some searching, I have become aware of revisions. From what I understand, these are created via clicking 'Save as Draft' or Publishing. I've seen this question: How can we publish revisions of a post, in addition to showing the latest post? I have two considerations: 1. It seems if I 'Save as Draft' too many times, I could push out previously Published versions? 2. Is there a way to identify just Published versions and show them only? Any guidance would be greatly appreciated. Thanks in advance.
I would not recommend the Save as Draft approach as I don't believe it will help you accomplish your ultimate goal. WordPress is saving revisions in a non-public Post Type (more info here). I found a "Changelog" plugin, which may help track changes to existing blog posts. You can see that here < Finally, a stock WordPress approach may be the following: Publish a blog post and create a unique tag. For example, if your blog post is called "Hello World," then name the tag `hello_world_revisions`. Then, when you are ready to revise the post, create a new post, and call it "Hello World." Tag it with the same `hello_world_revisions` tag, and that way, all of your revised blog posts are tagged the same, and you can direct your users to that tag when you want them to explore older versions. There are also other ways to accomplish your goals, but they would require custom code and custom theming. The items noted above are a quick, non-programming way to get started.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "revisions" }
change in form-checkout.php by using code in functions.php Specific, how do i remove "Your order" or the full function? By using a code snippet in functions.php (child-theme) It can be found by: <h3 id="order_review_heading"><?php esc_html_e( 'Your order', 'woocommerce' ); ?></h3> in form-checkout.php. I would prefer some code instead of coping the file to child-theme and alter the file.
By injecting CSS (not optimal): function remove_message_text() { echo '<style type="text/css">#order_review_heading { display: none; } </style>'; // Remove original text "Your Order" } add_action( 'woocommerce_checkout_before_order_review', 'remove_message_text');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, woocommerce offtopic" }
PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback Error without any function name I am getting the following php error: PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, function '' not found or invalid function name in /home/example/public_html/wp-includes/class-wp-hook.php on line 286 The issue is that there is no function name mentioned, how can I identify which function is causing this error?
There was a filter in the child theme causing the issue: add_action('excerpt_length','')
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, php" }
How can i edit all posts slug in bulk keeping WP native redirect? When i edit a single post slug the old url redirects to the new one automatically. I need to do this in bulk. There is a text that appears on thousands of permalinks and i want to remove it from them all and keep wp native redirect, because this text appears in random places i cannot make an htaccess rule for all posts. So for example: Should become: If someone access the old url redirect to the new one.
This is what worked for me: function remove_false_words($slug) { if(!is_page()) if (!is_admin()) return $slug; $keys_false = array('unwanted','word'); $slug = explode ('-', $slug); $slug = array_diff($slug,$keys_false); return implode ('-', $slug); } add_filter ('sanitize_title', 'remove_false_words'); Then you can use wordpress dashboard to select all posts, bulk edit, Update. And the words will be removed from slugs with native redirect.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "permalinks, slug, bulk" }
WordPress URL redirect and replace ? question mark Following is example of what we are looking for. We're trying this in wordpress and we require all parameters as a variable * * * Example 1 : < Need this : < * * * Example 2 : Need this : < * * * **funtion.php** code OR **.htaccess** rule any suggestion. Thanks in advance
Into wordpress function file add following code and check it. add_filter('query_vars', function( $vars ){ $vars[] = 'parent'; return $vars; }); function archive_rewrite_rules() { add_rewrite_rule( '^(.*)/(.*)/?$', 'index.php?post_type=client&name=$matches[1]&parent=$matches[2]', 'top' ); add_rewrite_rule( '^(.*)/?$', 'index.php?post_type=client&name=$matches[1]', 'top' ); //flush_rewrite_rules(); // use only once } add_action( 'init', 'archive_rewrite_rules' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, htaccess" }
How to use offset in WP_Query Where do I put the offset function? <?php $args = array( 'post_type' => 'post', 'category_name' => 'category', 'orderby' => 'date', 'order' => 'DESC', 'showposts' => 4); $wp_query = new WP_Query($args); if($wp_query->have_posts()) : while($wp_query->have_posts()) : $wp_query->the_post(); ?>
`offset` is one of the arguments that you can pass to `WP_Query`, so it belongs in the `$args` array: $args = array( 'post_type' => 'post', 'category_name' => 'category', 'orderby' => 'date', 'order' => 'DESC', 'showposts' => 4, 'offset' => 4, ); * * * PS: `$wp_query` is a reserved variable used by the main query. When creating your own `WP_Query` instance you should use a different variable name.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, loop, offsets" }
How to show all taxonomies within custom post type loop I am trying to show all records for a particular custom post type and I want a list of all taxonomies in a dropdown. Here is the query for the CPT: <?php $articles = new WP_Query(array( 'posts_per_page' => -1, 'post_type' => 'stories', )); ?> And getting the terms <?php $terms = get_terms( array( 'taxonomy' => 'topic', 'hide_empty' => false, ) ); ?> Then the loop <?php if ($articles->have_posts() ): while ($articles->have_posts() ): $articles->the_post(); ?> // this is where I want to echo all taxonomy names <div class="masonry__item col-lg-3 col-md-6" data-masonry-filter="<?php //echo tax names here ?>"> <?php endwhile; ?> <?php wp_reset_postdata(); ?> <?php endif; ?>
I'm answering the `<?php //echo tax names here ?>`: 1. In the loop, you can get the post terms using `wp_get_post_terms()`: while ($articles->have_posts() ): $articles->the_post(); $terms = wp_get_post_terms( get_the_ID(), 'topic', [ 'fields' => 'names' ] ); 2. Then you can do something like `echo implode( ' ', $terms );` inside the `<div>` tag: <div class="masonry__item col-lg-3 col-md-6" data-masonry-filter="<?php echo implode( ' ', $terms ); ?>"> But are you very sure you want to use the term _name_ and not _slug_? If you want the term slug, then you'd use `'fields' => 'id=>slug'` and not `'fields' => 'names'`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, wp query, custom taxonomy" }
Send emails with wp_mail() using SMTP configured in plugin I have the plugin Easy WP SMTP installed and there I have configured sending my WordPress mails with SMTP. I send emails with a cronjob to my users with the `wp_mail()` function. I was asking myself, if the emails are sent with SMTP or do I need to add this functionality to `wp_mail()`? If yes, how can I achieve this?
When you're using something like Easy WP SMTP, what you're doing is configuring things so that `wp_mail()` sends using your validated SMTP account rather than the generic mailer on the web server. The a common confusion and misconception is that you are using SMTP **_OR_** `wp_mail()`. Actually what you're doing is changing what `wp_mail()` is **using** to send. So you're still using `wp_mail()`. Properly configured, anything going through `wp_mail()` will be going through your SMTP account.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins, wp mail, smtp" }
Wordpress website Thumbnails not showing on Facebook Share When i am sharing my articles, it isn't showing featured image as a thumbnail. After using Facebook debugger, it is showing me this; ![enter image description here]( I also tried changing wordpress plugin settings as well as changed the featured image size, but still unable to fix it.
Solved! This issue was caused by two things; 1\. Hotlink enable in Cpanel. 2\. SEO Plugin What i did; 1\. Disabled "Hotlink Protection" from cPanel. 2\. I changed my SEO Plugin. I was using SEOPress which caused issues and then i was shifted to Yoast SEO.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "facebook" }
Where can I find a single item template I want to sell just one item on my store. I am looking for something that resembles < . I also don't want the product bar since it's just one item.
The WC single item template is located at: `yoursite.com/wp-content/plugins/woocommerce/templates/single-product.php` See this documentation: < So, you would want to move any of those templates to your child theme under `/wp-content/themes/your-child-theme/woocommerce/[any_template_you_want]` So, for example, if you wanted to edit the single-product.php but safe from WC updates, you would put the file in this directory and do your mods: `www.yoursite.com/wp-content/themes/your_child_theme/woocommerce/single-product.php` Last thing to mention here is keep the directory structure as well. So, if you want to edit something in the 'emails' folder, it would be like this: `www.yoursite.com/wp-content/themes/your_child_theme/woocommerce/emails/admin-new-order.php` (just for example sake) So, copy any templates you want to modify using that documentation above and you will be safe from any updates over time.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "woocommerce offtopic" }
Check if current user has a post and that post has any term/s from a specific custom taxonomy outside the loop I'm looking for a way to check if (whilst outside the loop) the current user.. 1\. is logged in 2\. has a post published 3\. their post has any term/terms from a custom taxonomy I have this so far... <?php if (( 1 == count_user_posts( get_current_user_id(), "post" ) && is_user_logged_in() ) { ?> blah blah <?php } ?> I'm just wildly guessing here but could I use `if( has_term( '', 'custom-taxonomy' ) )`? but that's for use inside the loop.
This can be done using WP_Query using author and tax_query. Something like this: $args = array( 'post_type' => 'post', 'author' => get_current_user_id(), 'tax_query' => array( array( 'taxonomy' => 'custom-taxonomy', 'operator' => 'EXISTS' ), ), ); $query = new WP_Query( $args ); And then check if posts are returned through this query. Please note that this code is not tried or tested and may contain syntax errors.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, custom taxonomy, users, terms" }
List all posts in a particular page I have a small wordpress blog. There are around 50 posts in the blog. I want to create a page which will enlist all the post titles. I have used "W4 Post List" wordpress plugin but that doesn't solve my issue. Please suggest me any alternative wordpress plugin or code.
first, create a custom page template and paste the code <?php // the query $wpb_all_query = new WP_Query(array('post_type'=>'post', 'post_status'=>'publish', 'posts_per_page'=>-1)); ?> <?php if ( $wpb_all_query->have_posts() ) : ?> <ul> <!-- the loop --> <?php while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> <!-- end of the loop --> </ul> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> for custom page template visit this link and for WP_Query visit this link
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "plugins, wp admin" }
Create a shortcode for native WooCommerce search form How can I create a shortcode for the native WooCommerce search form, so that it can be used elsewhere? In the secondary menu, for example.
Add this code to functions.php. You can then use the shortcode [search_form], or whatever you choose to name it, in a menu. I used it in the navigation label field of a custom link. function search_form_shortcode() { return get_product_search_form(false); } add_shortcode('search_form', 'search_form_shortcode');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, shortcode, search" }
Rename WooCommerce sorting dropdown options How to rename the WooCommerce sorting dropdown options and customise the wording? For example, change "Popularity" to "Best Selling" or "Price: Low to High" to just "Price Low to High" without the colon.
Add this code to functions.php and rename the relevant option. Here I have renamed the 'Popularity' option to 'Best Selling'. add_filter( 'woocommerce_catalog_orderby', 'rename_sorting_option_woocommerce_shop' ); function rename_sorting_option_woocommerce_shop( $options ) { $options['popularity'] = __( 'Best Selling', 'woocommerce' ); $options['date'] = __( 'Newest', 'woocommerce' ); $options['price'] = __( 'Price: Low to High', 'woocommerce' ); $options['price-desc'] = __( 'Price: High to Low', 'woocommerce' ); return $options; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, woocommerce offtopic, sort" }
Individual months in WP Query I would like to create `WP_Query` query and I am using date parameters. How should I should write my query if I want to get all posts from: January 2019 and May 2019 (there is not range).
It's possible to pass multiple sets of arguments to `date_query`, so if you set `relation` to `OR` for them, you should get posts that match either, meaning that you could get the posts you want like this: 'date_query' => [ 'relation' => 'OR', [ 'month' => 1, 'year' => 2019, ], [ 'month' => 5, 'year' => 2019, ], ],
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query" }
Is saving data to WordPress options as array bad thing to do? With a form I am saving the data to WordPress options, it's a big multidimensional array. The problem that I am facing is sometimes it misses a value in the array. I am not sure how to debug that as it works 80% of time. Can this be related as I am saving it as an array?
It depends, if you use the data, only as a whole. Lets say for configuration settings or something, then I would say, it's not a problem. But if you are doing queries on the data, like searching or fetching only 1 or 2 fields from that array.. you should use other solutions. If you are missing some values from your array, are you sure these values are submitted from your form? (Are the fields not "disabled", or are these fields unchecked checkboxes?)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "options" }
Write text below a specific part of a sentence I'm looking for to obtain this effect ![enter image description here]( that is to place a bracket under a piece of text and then to write text below the said bracket. Is it possible to obtain such an effect using HTML and CSS? A "primitive" bracket can be obtained by simply adding a bottom-border to the selected text, such as `The quick <span style="bottom-border: 1px solid">brown fox jumps over the</span> lazy dog.` But how to add text below the border?
This code does the job, moreover it is also possible to put HTML code below the selected text, an example here .above { position: relative; display: inline-block; margin-bottom: 1.5em; } .above::before { position: absolute; top: 90%; height: 6px; width: 100%; border: 1.5px currentcolor solid; border-top: 0; content: ""; } .above .below { position: absolute; width: 100%; left: 0; top: 140%; font-size: 0.75em; text-align: center; } <p>The product <span class="above">2 · 2 · 2 <span class="below">2<sup>3</sup></span></span> can be written as power.</p> ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "css, javascript, html" }
Does wp post delete also delete metadata associated with posts? say this: wp post delete --force $(wp post list --post_type=product --format=ids) I found out that it's far more fast and performant than deleting posts from admin. But I was wandering: any differences between the cli and admin ways? For example, will that cli command also delete metadata associated with deleted posts?
In short, yes. However, if you run into an issue like custom fields or media hanging around, you could use: wp post meta delete
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "wp cli" }
Woo API REST : product variation price is read-only? I see `price string Current variation price. [read-only]` on this documentation (official api rest doc from WooCommerce). Does it mean that it's impossible to make an app to update a product variation price ?
After some research, i found this example : `PUT /wp-json/wc/v3/products/<product_id>/variations/<id>` So in javascript we could do : const data = { regular_price: "10.00" }; WooCommerce.put("products/22/variations/733", data) .then((response) => { console.log(response.data); }) .catch((error) => { console.log(error.response.data); }); And the JSON API Response : { "id": 733, "date_created": "2017-03-23T00:53:11", "date_created_gmt": "2017-03-23T03:53:11", "date_modified": "2017-03-23T00:53:11", "date_modified_gmt": "2017-03-23T03:53:11", "description": "", "permalink": " "sku": "", "price": "10.00", "regular_price": "10.00", "sale_price": "", ... } I'll do some test, but i think it's possible to update a product variation price with WooCommerce API/REST.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic, rest api" }
Wordpress 5: including larger thumbnail image sizes in srcset than I have set I have set image sizes in my functions.php, such as add_image_size( 'article-lede', 500, 600 ); It shows up in Regenerate Thumbnails, and I regenerated them. So I upload an image to the media library which is 934x1200. My template code is set to use the "article-lede"image: <?php the_post_thumbnail('artcle-lede', ['class' => 'featured-image img-fluid']);?> But the page shows a full-size image. And the img tag in the resulting HTML has the height and width set to the large size, and an SRCSET of sizes, none being the article-lede size I specified: <img src=" class="featured-image img-fluid wp-post-image" alt="" srcset=" 934w, 234w, 797w, 768w, 467w, 311w" sizes="(max-width: 934px) 100vw, 934px"> How I do get it to display the 500x600 version?
Good question as I know that this can be a pain in the butthole. Please see this page; < From the docs: get_the_post_thumbnail_url($id, 'image-size') So in your case: $img = get_the_post_thumbnail_url($post, 'article-lede'); echo "<img src='{$img}' class='featured-image img-fluid' />";
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, images, post thumbnails, responsive" }
Linking products to categories I want my WooCommerce products to be linked to proper categories. I already have categories and products. These needs to shuffle to the new linking. Please suggest the detail steps.
You can try using csv product import plugins like < . The best way is to write a custom script as per your requirements.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, woocommerce offtopic, link category" }
Custom Post Type "MUST NOT" be able to search via URL Hello good day everyone, Guys any idea how to hide permalinks from custom post types and should not be able to access via url. By the way, Im using Pods framework for my CPT's Example: www.example.com/this-is-a-custom-post-type Any suggestions, recommendation will be appreaciated. Thanks!
Welcome! After creating a post type using pods, You can navigate to Advanced options and uncheck Public and Publicly Queryable. Note: There are parameters like `exclude_from_search`, `publicly_queryable`, `show_ui`, and `show_in_nav_menus` that are inheriting value from `public`. You need to set them manually if you want to use them. More info: < ![Advanced options of pod's custom post type](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, permalinks, pods framework" }
Exclude read more in the_excerpt I want to remove "read more" in the next code: <?php the_excerpt(); ?> Is it possible to do in the PHP line directly or I need a filter in funtions.php? I am want to do one by one in PHP query not for all.
I asked to author theme. It was by filter from functions.php
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development, excerpt, read more" }
How to call a function from inside class to outside class i want to call myfunction() inside the myfunction2() how can i achieve that. can you give me an example. class myclass(){ function myfunction(){ #my code here } } function myfunction2(){ # how can i get the function myfunction() here. }
Remove the () after myclass. Then in your myfunction2: $obj = new myclass(); $obj->myfunction();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development" }
What is the latest WordPress that will work on PHP 5.2.17? I have an old server that runs important PHP aplication that required PHP 5.2.17. What is the newest WordPress that I can install on it?
I think you're looking at this the wrong way. Having an old application that requires such a archaic PHP version is bad enough. That does not mean, your new WordPress installation needs to use that same old version though. Instead, I would suggest to **keep PHP 5.2.17 for the legacy application and use the latest PHP version for WordPress**. There are various ways to do this, it all depends on how exactly your server is set up. * Check this answer from StackOverflow for an Apache way. It generally boils down to `AddHandler` and `SetHandler`. * This answer from ServerFault explains how to solve it via NGINX. The main idea it seems is to access other ports via `fastcgi_pass`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Gutenberg: Restrict Top Level Blocks, But Not Child Blocks # Background I've created a custom top level "page section" block, to work with my existing theme. I've like to restrict top level blocks to ONLY that one block. However, I don't want to disable all blocks completely, because I want all blocks available to use as innerBlocks. # Question How can I restrict top level blocks, without restricting child level blocks?
The short answer is you can’t. But you can accomplish this by using a block template that only contains your block and is locked. If your block has an InnerBlocks instance, you can add any of the registered blocks to it. add_action( 'init', 'insert_template' ); function insert_template() { $post_type_object = get_post_type_object( 'post' ); $post_type_object->template =[ [ 'your-custom-block-name'] ]; $post_type_object->template_lock = 'all'; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "block editor" }
Where do the files of a custom WP CLI Command reside? I want to create a custom WP CLI command and I have read the documentation but I just don't understand for the life of me how this works. Do I need to declare it before in my config file where they are gonna go? Is it a PHP file? If so, I need to declare it put it anywhere inside my theme? Thank you in advance.
You can put the PHP anywhere in your plugin, or a file that's included into your plugin, the same as you would any other code for extending any part of WordPress in a plugin. The only thing you need to do is check that `WP_CLI` exists before using any of the WP CLI API: if ( defined( 'WP_CLI' ) && WP_CLI ) { // WP_CLI::add_command etc. }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp cli" }
How can i show specific Category List? By this code ,it shows all the category.but i want to show specific some category(like-Officer,Training) Thanks in Advance <?php // change category to your custom page slug $categories = get_categories(); foreach ($categories as $category) { $option .= '<option value="'.get_option('home').'/category/'.$category->slug.'">'; $option .= $category->cat_name; $option .= ' ('.$category->category_count.')'; $option .= '</option>'; } echo $option; ?> </select>
<?php // change category to your custom page slug $categories = get_categories( array( 'include' => array(1, 2, 3) ) ); foreach ($categories as $category) { $option .= '<option value="'.get_option('home').'/category/'.$category->slug.'">'; $option .= $category->cat_name; $option .= ' ('.$category->category_count.')'; $option .= '</option>'; } echo $option; ?> **array(1, 2, 3)** is category ids.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, categories, javascript" }
Product Tags in Add New product as checkbox list Id like to use product tags as a second classification for products from the Add New Product menu, however the product tag option in its default state is not reliable. Id like to customise it so that I could select from a complete list with checkboxes as is done with categories. The product tags populate one of my dropdown menus, so they need to be consistent, created in the Tag menu, much like Categories and not created on the fly, duplicated, or be similar to others, as is the case with Tags currently. I have used some code previously which created a tag cloud to choose from, but it was never a complete list and not ideal. Can this be done? And is it the best option for achieving a second product classification from the product page. Im trying to avoid plugins.
That's only one way to achieve that, but it's the easiest, I guess. The taxonomy UI is displayed as list of checkboxes, if given taxonomy is hierarchical. So if you change the product tags to hierarchical, it will solve your problem. And it's pretty easy to change, because there's a hook for that: function my_woocommerce_make_tags_hierarchical( $args ) { $args['hierarchical'] = true; return $args; }; add_filter( 'woocommerce_taxonomy_args_product_tag', 'my_woocommerce_make_tags_hierarchical' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, woocommerce offtopic, tags" }
Not able to show the favicon to the uploads URL in WordPress I am working on my client WordPress project and I have uploaded the PDF in the media. When I open the PDF URL, it is not showing the favicon. My client wants to show the favicon in the PDF url. I have added the favicon.ico in the directory where the wp-config is there but after that it is not showing the favicon. Any help is much appreciated.
I have just implemented this solution to my own website. I copied my site-icon.png file (the favicon that I inserted via the wordpress dashboard) to my root directory (public_html folder) and renamed it favicon.ico. To test that it was placed correctly I typed in the following www.mywebsite.co.za/favicon.ico and the favicon displayed. I then went and checked a pdf file and it worked.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "favicon" }
If you add a shortcode programmatically, but the code isn't viewed on that request, is it still executed? Is it expected behavior that the callback of a shortcode is executed even if the result isn't returned, or do shortcodes only execute when they are displayed?
Shortcode callbacks are not executed unless the shortcode is parsed and executed. So if a shortcode has been added, its callback will not run unless the shortcode has been used somewhere on the page, or executed manually in a function or template that has been used, and it will only be run at the moment that the shortcode is parsed. So the act of registering a shortcode with `add_sortcode()` alone will not execute the callback function.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "shortcode" }
My #id is not showing in the url when the user clicks on the anchor tag I am working on my WordPress website and when the user clicks on the `<a href="#id">` tag, the #id is not showing in the URL and because of that, when the user clicks on the back button, it is taking me to the back not on the top of the page. I want that, when the user click on the `<a href="#id">` tag and it moves to that id but when the user clicks on the back button, it should take me to the top of the page. Now, it is taking me to the back page. Any help is much appreciated.
The solution is: Just add the page scroll id plugin. After installing the plugin, Go to the `Links behavior` section: Check this option: Append the clicked link’s hash value (e.g. #id) to browser’s URL/address bar. By doing this, id shows in the URL and when you click the back button after going to the id, the page will come to the own page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls" }
How to allow data:image attribute in src tag during post insert? I'm inserting a post using `wp_post_insert()`. And my post's content looks like this: <img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAN4AAAB6CA { ... } but on the insert process, Wordpress `removes` the data attribute. So above code becomes this: <img src="image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAN4AAAB6CA { ... } I've tried something like this but no luck: function my_filter_allowed_html($allowed, $context){ if (is_array($context)) { return $allowed; } if ($context === 'post') { $allowed['img']['data'] = true; $allowed['src']['data'] = true; } return $allowed; } add_filter('wp_kses_allowed_html', 'my_filter_allowed_html', 10, 2); How can I avoid this?
Thanks to naththedeveloper from StackOverflow. His answer worked for me. > Well, this was a nightmare to find, but I think I've resolved it after digging through the WordPress code which hooks in through `wp_insert_post`. Please add this to your `functions.php` file and check it works: add_filter('kses_allowed_protocols', function ($protocols) { $protocols[] = 'data'; return $protocols; }); > Essentially internally in WordPress, there's a filter that checks the protocol of any URL's in the content and strips any which it doesn't like. By default, the supported list doesn't support the data protocol. The above function just adds it to the list of supported protocols. > This filter does not run if you're an administrator, which is probably why you're seeing this issue only when logged out. Thank you for your research.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "wp insert post, wp kses, allowedtags" }
change hover color of specific menu link I'm trying to change a hover color of a menu link element. Normally this is really easy, but on this projet i'm not able to do it. _remove url_ I need to change the hover color of "RESERVER" button ( pink button in right header menu ) to another color. I have tryed tons of CSS edit, no one works... I'll really apreciate any help for this ! Thanks in advance for your help.
Here you go - .book-now-link span:hover { background-color: #ffffff; padding: 5px 10px 5px 10px; } Tested and it works.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, css" }
Block search SQL from happening I need to block some accesses to search _results_ not the whole page, just the results. The problem is, I need the search SQL query to not happen AT ALL. (I can conditionaly hide the output loop template very easily, I'm just not sure SQL is not happening). Where would I prevent such thing (I assume some filter/action hook I just could not find the right one)? **EDIT:** Please note, that the page needs to be loaded and displayed, otherwise I would proceed with request blocking approach like `template_redirect`
It's possible to avoid SQL execution in `WP_Query` with the `posts_pre_query` filter. It's e.g. used by plugins to outsource the default search to 3rd party search engines. Here's an example how we can override the main search query on the front-end, with an empty posts array and avoid running the SQL search query: add_filter( 'posts_pre_query', function( $posts, \WP_Query $query ){ if( $query->is_search() && $query->is_main_query() && ! is_admin() ) { return array(); } return $posts; }, 10, 2 ); Since we're returning an empty array, I don't think we need to adjust the `$query->found_posts` or `$query->max_num_pages` as they are zero by default.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "database, hooks, search, sql" }
On the .org repo, can your plugin name/slug contain "WooCommerce" I know they won't let you call a plugin **WordPress-xxx** , but they will allow **WP-xxx**. What are the rules surrounding **WooCommerce**?
I'm posting this answer because the accepted answer is slightly misleading, as it implies that you cannot use the trademarked name at all. While not 100% wrong, it's also not 100% right. It is correct that unless **you** are WooCommerce, you can't call your plugin "WooCommerce Cool Add-on". But you **_can_** call it "Cool Add-on for WooCommerce." See "Why can’t I use someone’s trademark/brand as my plugin name?" Also, if you're submitting to the .org repo and you are concerned about making sure your naming convention is correct/acceptable/valid, just submit it the way you interpret the rules. If it's unacceptable, _they **will** tell you_ and then you adjust it to be approved. OR, just get on the #PluginReview Slack channel and ask up front. @Ipstenu and @otto42 can give you a solid thumbs up/down on whether your name will pass muster.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugin development" }
wp_query get the 2nd post How could I get only the 2nd product in this query? $loop = new WP_Query( [ 'post_type' => 'product', 'posts_per_page' => 1, 'meta_key' => 'total_sales', 'orderby' => 'meta_value_num', ), ), ] );
I figured out you can use `'offset' => 1,` to skip 1 post and get the 2nd. Change the number to however many posts you want to skip. ie. set it to 2 to get the 3rd. $loop = new WP_Query( [ 'post_type' => 'product', 'posts_per_page' => 1, 'offset' => 1, 'meta_key' => 'total_sales', 'orderby' => 'meta_value_num', ] );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, wp query, loop" }
How to import posts correctly? There are 2 tasks, there is a site X on which there are 1,500 posts, each entry has a title, a thumbnail and 3 metadata. You need to export these entries to other sites. Those. first you need to write a microapi that will generate json for example, and on the side of other sites (where you need to parse these same entries) a plugin that will receive the same json in the url and create entries. The option of exporting xml and importing to other sites is not suitable, you just need to make a script. I made json generation, it remains to do import of records on the basis of json. The main question is how to make imports. so that it works stably, because running **foreach** from 1500 **wp_insert_post** is not a good option, right? Please tell me in which direction to look at the implementation of such a task. Thanks!
You could always give it a try, i've imported around 300 posts at the same time before so, it shouldn't be that big of a deal. You could try the following methods if you have problems with importing them all at once. * Try re-defining WP_MEMORY_LIMIT and increase it to i.e. 1024MB * Try increasing the max_execution_time (Check this link for more information) * Try to split/chunk the array in a few different arrays and add a `usleep` after every iteration Please note that within the `foreach` `$id = wp_insert_post()` will set `$id` to the `ID` of the Post/Page that is being added. If desired you can use this variable to add i.e. meta_values, thumbnails, etc. Good luck!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "import" }
Get ALL post ID's export list (Only id's. Php or sql not important ) please help me. I dont know How can I do. I need list all posts IDs. export need 1 3 5 6 7 8 9 . . . . Please help
There are lots of ways to get all IDs. Assuming you do want all posts - which include Posts, Pages, Media, Menu Items, custom post types, etc.: phpMyAdmin: Run a SQL query: `SELECT ID FROM wp_posts` then export the results to whatever file type you prefer.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, sql, id, export" }
Why does my caroussel gallery do this in responsive? [CSS] I do have a photo Gallery on my site, on laptop it works perfectly, but on mobile view, the pictures 1st display well, and after a scroll, becomes very big & blur. you can see on : [hidden link] A working demo can be find also on : < I've search for hours but I can not get rid of this bug. Any help will be much appreciate :* EDIT : If i activate the original child theme, it works well. So it comes from my custom dev, need to find the one that create this troubles. EDIT2 : After more investigation, the issue comes from < If i set back to empty style.css the issue disapear. Please fill free to inform me if you see anything wrong in it. ![enter image description here]( ![enter image description here](
ok, i find the solution !!! it was this line that makes trouble ! .vc_column_container>.vc_column-inner { width:unset !important; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "css, gallery, responsive" }
Does costum code in the root folder get lost when wordpress is updated? I have added costum JS and CSS in the root folder of the WordPress installation. If I update Wordpress, does this costum code get lost? See picture: `smardigo` is my webspace root folder and in the folder `costum` is my costum js and css. ![enter image description here](
No, WordPress won't overwrite or delete files in your custom folder. The only places that are normally overwritten in a Core update are Core files themselves, like the ones inside `wp-admin` and `wp-includes`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "css, javascript" }
create bootstrap columns inside editor group block According to this answer I'm trying to use the new default block editor of wordpress to set the bootstrap classes on the content of the blocks. I'm using the group block to set the container and another group block to set the row that are required from the grid of bootstrap. My question is how I can set the columns inside the second block group that will contain the columns? If I use paragraph the result isn't what I expect, and I have no idea of how to create columns inside a group block. If you look at the screen you can see that the columns classes are set on the tag `<p>`, I need instead to add two divs with the classes. NB: I was using the anchor field of the block editor to set the classes, but I've fixed this using the class field instead. Thanks for the help. ![enter image description here](
Inside your `.row` container choose a "Columns Block" instead of a paragraph block. Each column can be assigned the desired bootstrap CSS class. It will look like this: <div class="wp-block-group container"> <div class="wp-block-group__inner-container"> <div class="wp-block-group row"> <div class="wp-block-group__inner-container"> <div class="wp-block-columns"> <div class="wp-block-column col-sm-12 col-md-6 col-lg-6"> <p>Text Here</p> </div> <div class="wp-block-column col-sm-12 col-md-6 col-lg-6"> <p>More Text</p> </div> </div> </div> </div> </div> </div> The "Columns Block" is already a flex container by default, so in this case you may not even need the `.row` container. Or you could give the `.row` class to the "Columns Block" itself.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "css, block editor, twitter bootstrap" }
Ask WP-CLI latest core WordPress version released I'm trying to make a script (bash) that examines all WordPress installations on my server and returns a set of information. I would need to know the latest known version of WordPress (official repository), can you do it via WP-CLI? or is there another way (API...)? (I'm looking for a WP-CLI solution)
`wp core version` displays your current WordPress version. $ wp core version 5.2.4 Adding `--extra` shows extended version information. $ wp core version --extra WordPress version: 5.2.4 Database revision: 44719 TinyMCE version: 4.940 (4940-20190515) Package language: en_US `wp core check-update` lists the most recent versions when there are updates available, or success message when up to date. $ wp core check-update --field=version 5.3
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "wp cli" }
js file in root loading without <script src= This is my first time using a js file. It controls the hover and display of images in a php menu file. They are both in the root directory. I have not referenced the file in the menu.php file at all as I have only learnt of this now, and yet somehow it works. Do js files just load automatically all the time?
WordPress has no mechanism to load custom js files automatically. If your theme need that js file, then place it inside your theme folder. and link it in your template file. for example, <script src="<?php echo get_template_directory_uri(); ?>/assets/bootstrap.min.js"></script> In the above example, "bootstrap.min.js" file is located in my theme's "assets" folder. the function get_template_directory_uri() return the url to your theme folder. In this way you can link your custom js files to your template file. > ... and yet somehow it works." As per my experience, this doesn't mean WordPress loading your js file, as @Kaperto said, Wordpress uses a lot of JavaScript libraries by default. Coincidently your expected js file is one of them.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, jquery, javascript" }
Bulk edit existing shortcode within custom field I have a very similar question to this: Custom Fields Bulk Edit I would like to edit ALL of the data inside a custom field but instead of replacing values I would like to instead add an attribute to the custom field on each page. Example: This is an existing shortcode `[idx-listings linkid="387056" count="6"]` I now want to add an attribute to look like this: `[idx-listings linkid="387056" count="6" showlargerphotos="true"]` Is there a way of bulk apending the `showlargerphotos` attribute inside the existing shortcode without affecting the rest of the string? Here is the custom field in the `wp_postmeta` table ![enter image description here](
In phpMyAdmin: update wp_postmeta set meta_value = replace(meta_value,'[idx-listings','[idx-listings showlargerphotos="true"'); As long as you've always typed the shortcode starting with `[idx-listings` and not, say, `[ idx-listings`, this will add your new attribute everywhere the shortcode has been used.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, mysql" }
Is there a simpler version of WP Media? I'm developing a plugin where users need to be able to upload an image (a payment receipt) to a custom user field. At the time, I'm using a code I found here Extra User Profile Field Upload File / Image and it is working. The problem is I don't want WP Media to show a lot of things, I just want the user to be able to upload a single image without seeing private site information or media and without being able to create something like a gallery. Please, answer if you have any idea about how doing it. Thank you!
You can use ACF to do this. 1. Set up your custom field for the user profile. 2. Use the acf_form() to produce a form containing the field on your front end for the user to interact with. 3. Customise your acf_form() arguments to use a "simple" uploader (this will not expose WP Media Library to users then) Example: $field_arguments = array( 'post_id' => 'user_'.$current_user->ID, 'field_groups' => array(111), // Replace with ACF Group you created 'form' => true, 'uploader' => 'basic', // This is what hides the WP Media Library to the user 'submit_value' => 'Submit' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom field, uploads" }
Prevent update check for specific theme I'm working on a custom theme that lives in `/var/www/html/wp-content/themes/custom/`. It's for internal use, so it doesn't matter if there's a theme with the same name on the wordpress site. But wordpress performs an update check, finds a theme with the same name, which has a newer version number, and so asks me to upgrade. Is there a way to suppress this behavior without renaming my theme and without fiddling with version numbers? I don't want the check to be performed at all. (BTW `define('AUTOMATIC_UPDATER_DISABLED', true)` doesn't help.)
Yes, you can disable auto update by adding this line of code in your wp-config.php file: define( 'WP_AUTO_UPDATE_CORE', false ); OR Disable automatic WordPress theme updates by adding the following filters in your functions.php add_filter( 'auto_update_theme', '__return_false' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "theme development, themes, updates" }
Create role that can edit some user details, but not the role I want to create custom role ('sales') that can edit user profiles of 'subscribers' but can not change the role of that user. The user details that would be editable by the 'sales' role would be resetting password and interacting with some custom user-meta fields. Is it possible to edit capabilities at that level of granularity?
I am not sure if there is something native. However you could get really hacky if you wanted to if no other option. You could create a css class to be inserted based on the current user role that is logged in. Then target that role (being sales for example) and hide that form field. You could use something like this: function sales_role_admin_body_class( $classes ) { global $current_user; foreach( $current_user->roles as $role ) $classes .= ' role-' . $role; return trim( $classes ); } add_filter( 'admin_body_class', 'sales_role_admin_body_class' ); Then you could target it something like this in your css: .role-sales #form_field_id_you_want_to_hide{ display: none !important; } Purely an example and very hacky. However it would work if no other option.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles, capabilities" }
Wordpress WebSite is jumps while scrolling bottom my following wordpress pages are jumps while scolling down 1.< 2.<
You have some css that is conflicting and causing the issue when the top menu sticks absolute on scroll down and the header hides. In your media.css on line 340 you have: @media (min-width: 768px){ .main-navigation { clear: both; display: block; float: left; width: 100%; } } Changing that in live dev tools to: @media (min-width: 768px){ .main-navigation { clear: both; display: block; float: none !important; width: 100%; } } Seems to fix the issue and make it smooth again.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "gallery" }
Template for landing pages I'm using WP for a business site (not a blog) with landing pages. So there are no posts, only pages (actually, "landing pages") which I create with the Elementor page builder. Since a typical theme has lots of unnecessary stuff for a landing page business site, I decided to create a lightweiht custom theme. I have a `header.php`, `footer.php` and basic css/js enqueued via `functions.php`. I want to create each page's content using a page builder. I don't know what to put in `index.php`. This is something typical: <?php get_header(); ?> // ....the wp loop goes here <?php get_footer(); ?> Of course in my case there is no loop - but that is where the main content goes. When I create a new page with Elementor (or other page builder, or Gutenberg), I want my custom per-page content to go in there, where the loop usually goes. What markup do I place there, so the page builder knows where to insert each page's content?
in your theme folder. create a new php file. For example call it: landingpage.php in the php file you could have something as basic as: <?php /* Template Name: Landing Page */ get_header(); while ( have_posts() ) : the_post(); the_content(); endwhile; get_footer(); ?> Elementor will be called / inserted where it says the_content(); Included out of the box with elementor you should have a blank elementor template to choose from and using the built in elementor theme builder options create exactly what you are after also choosing conditions of when that page template gets used?
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, themes, pages, templates" }
Remove clickable Link of Wordpress Site Logo from Woocommerce Single Product page I need help to remove clickable Link of Wordpress Site Logo from Woocommerce Single Product page. i tried following css code .home .site-logo a { pointer-events: none; } and it works for Homepage. But i need to avoid users going to home page when they come to woocommerce single product page.
Each product should have a unique class identifier in the body. Compare two product pages and depending on the theme you are using. Allot of them have a unique css identify. Look for something like: postid- followed my numbers for example. If you had something like: <body class="product-template-default single single-product postid-3592 wp-custom-logo woocommerce woocommerce-page woocommerce-no-js shop-buttons-is-sticky"> Then you could target it using the postid-3592 class as its unique to that product page. So you could do: .postid-3592 .site-logo a { pointer-events: none !important; } **or for all products using a single product template you could use:** .single-product .site-logo a { pointer-events: none !important; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, woocommerce offtopic, css" }
Bulk actions redirects to "options.php" page when clicked (WP_List_Table) I'm having a problem with WP_List_Table. I'm following a tutorial on internet (< because I need to display an table on my plugin page. The problem is that the Bulk Actions are not working, I already tried to use the original code provided by the link I just mentioned and I tried to follow another tutorial too. But, when I press the Bulk Action button, wordpress redirect me to wp-admin/options.php page, no matter which action bulk I press. I don't have any idea why is this happening.
Apparently, this error was occurring because I created this admin page in a wrong way. I just moved eveything related to this table to my main plugin php file and it is working now.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "table, wp list table" }
Missing 'Page Attributes' I'm building my own theme and so far so good. I created a template and named it correctly but it doesn't appear in any drop-down or indeed there's even no page attribute option at all. Do I need to add something to the functions file? There is nothing either in 'screen options' Thanks for all help
This works: <?php /* * Template Name: Top Ten * Template Post Type: post, page, product */ get_header(); ?> I was missing the `Template Post Type`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "templates, page template" }
create category on theme setup Is possible to create some default categories when a custom theme is activated? I mean, when I activate a custom theme, I want that some predefined category are created, for example news or info, this because using this way I can load the post directly on the template parts of the theme. Otherwise, if I want to add a custom widget plugin, how I can achieve this? I see many website that are using widgets in footer or in other part of the pages, but I've never used them so I don't know thhe correct way to add this feature on my page or post php files that have this structure: <?php if( have_posts() ): while( have_posts() ): the_post(); the_title(); the_content(); endwhile; endif; ?> All the markup are added using shortcodes except for the title or sometimes for the post thumbnail.
You can use the `after_setup_theme` for this eg: add_action( 'after_setup_theme', 'custom_add_cat' ); function custom_add_cat() { //Create Custom Category wp_insert_term( 'Custom Category', 'category', array('slug' => 'custom-category') ); } Read here for more info: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development, themes" }
Woocommerce SKU on ALL products page Woocommerce on wordpress When i List ALL the products using a Product catergory of ALL Products and every product is listed OR i use any of the categorys I get a thumbnail picture Title Price I would ike to add the SKU number to this list SkU works fine on the product page itself , and i have modified the code to show after the tilte on a single product display But its when i have a page full of products - that i would like the SKU to show Fenori.co.uk choose - Products Then any category Thanks
Hope this code will helpful for you, the sku will be displayed at the end of shop loop function shop_display_skus() { global $product; if ( $product->get_sku() ) { echo '<div class="product-meta">SKU: ' . $product->get_sku() . '</div>'; } } add_action( 'woocommerce_after_shop_loop_item', 'shop_display_skus', 9 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "woocommerce offtopic" }
impreza portfolio display/view blank page I have a strange problem. My site is in development currently. I have taken over from the previous developer, and I believe this was working for him (I think/hope). We have a few portfolio pages, but I cannot view/display any of them. If I click on Preview for example, I get a blank page. Browser console shows no errors. Pages and blog posts work perfectly. I have enabled debugging, deleted cache, deactivated all plugins - still the same. And there is nothing in the log. I am at lost of where to look next. Any pointer to what I should control or test will be very useful. Thanks
Now it works: 1. Uninstalled all plugins 2. ReUpdated Theme 3. Reinstalled plugins It was obviously some incompatibility issue that only deactivating plugins did not solve.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts" }
Suddenly all emails in User have [email protected] I don't know what happened but suddenly all emails under "User" are changed to `[email protected]` \- see the below picture. Of course, my first thought was a plugin problem, but when I disable **ALL** plugins then nothing changes. Any idea what happened? The site is running under Cloudflare for months but this issue does exist since few days. I am not aware of anything I could have changed. I am viewing the users as administrator. ![enter image description here](
This is coming from cloudflare's Email Address Obfuscation. 1. Login to Cloudflare. 2. Click on your domain name. 3. Navigate to Scrape Shield 4. Turn off Email Address Obfuscation. 5. Purge Cloudflare Cache ![](
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "users, email" }
How to display post view count by date, week and month? I am using the below code to display post views. How can I get the data for every day, week and month? function gt_get_post_view() { $count = get_post_meta( get_the_ID(), 'post_views_count', true ); return "$count views"; } function gt_set_post_view() { $key = 'post_views_count'; $post_id = get_the_ID(); $count = (int) get_post_meta( $post_id, $key, true ); $count++; update_post_meta( $post_id, $key, $count ); } function gt_posts_column_views( $columns ) { $columns['post_views'] = 'Views'; return $columns; } function gt_posts_custom_column_views( $column ) { if ( $column === 'post_views') { echo gt_get_post_view(); } } add_filter( 'manage_posts_columns', 'gt_posts_column_views' ); add_action( 'manage_posts_custom_column', 'gt_posts_custom_column_views' );
As you are doing `update_post_meta( $post_id, $key, $count );` for which `$key` is `'post_views_count'`, you can't. You are updating the meta key as is. You could however change how you are saving the meta key. You could add a prefix to the meta key you're using to differentiate the day, week, and month. example for month: function gt_set_post_view_by_month() { $prefix = date('mY') // 122019 $key = $prefix . '_post_views_count'; // `122019_post_views_count` $post_id = get_the_ID(); $count = (int) get_post_meta( $post_id, $key, true ); $count++; update_post_meta( $post_id, $key, $count ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "post meta, views" }
Updating Existed RocketTheme Theme on Wordpress I have a legal RocketTheme theme for Wordpress. I installed it while it on version 1.5. Now, version 1.6 released. How can I update theme without corrupt my theme customizations ? Thanks.
You can click update by going to themes or dashboard > update. Changes made using the theme-options or customizer will stay intact after the update but if you have modified the theme core files or added additional codes to theme files then you will lose them with the update. In that case, the solution will be to create a child theme and move the custom code added by you to the child theme. You can create the child theme using a plugin or manually create one. There are many plugins available. Note creating the child theme at this stage does not move your custom code automatically to the child theme. To know more <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, themes, updates, automatic updates" }
WooCommerce shop, my account, cart every page redirect to home page Here is my website: smitafashions.com Whenever I click on any page from the menu or the products in the home page, every link redirects me back to the home page I tried clearing cache Save permalinks Delete .htacccess Disable sg optimizer plugin I had created a single product page using Elementor Pro
I found the solution that Go to Settings --> Permalinks --> I have used custom permalinks So change it to another default permalink and save Solves the problem
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "woocommerce offtopic, redirect" }
How to add a blog filter bar without paying money. (example inside) ![blogfilter]( Hello, I saw this type of blog filter on a website and I really liked it. I was hoping I could add something similar on my site but I haven't found a way to do so without a plugin. If anyone has experience in this, please share, thanks! :^)
The filter that you see is not really a filter, it's just menu links. Each menu item such as the link that says "Support" will show posts that are in the "Support" category. First go to WP > Posts > Categories and create a category called "Support". Then add posts to that category. Go to WP > Appearance > Menus and add the category called "Support" into your menu. Users will now see all posts of "Support" when they click that menu link.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, blog page" }
How to get random posts and order them by date I need to get some random posts and order them by date. To get random posts I used the following: $query = new WP_Query( [ 'post__in' => $post_id_array, 'posts_per_page' => $number, 'orderby' => 'rand' ] ); To order by date I tried this: 'orderby' => ['rand' => 'ASC', 'date' => 'DESC'] But it does not work correctly. How can I do this?
Unfortunately, that will never work. 'rand' is a random order, so you always end up with a randomized order, no matter what you put for the date. In order to do something like what you're describing, you have to use `'orderby'=>'rand'`. Then you can sort the result by date. $query = new WP_Query( [ 'post__in' => $post_id_array, 'posts_per_page' => $number, 'orderby' => 'rand' ] ); // Sort the resulting posts array by date usort( $query->posts, function( $a, $b ) { $t1 = strtotime( $a->post_date ); $t2 = strtotime( $b->post_date ); return $t1 - $t2; }); // $query->posts is now sorted and in order by date.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "wp query" }
Making a list of post tags in string I am trying to push post tags to the search index of the WPFTS plugin in order to search my posts by tag names. To achieve this, I have to generate a string with all tags. Here is what I tried: add_filter('wpfts_index_post', function($index, $post) { global $wpdb; $data = get_the_tags($post->ID); $index['post_tag'] = implode(' ', $data); return $index; }, 3, 2); The problem is I see this new search cluster 'post_tag' in the list, but all data there is empty. What did I do wrong?
You're using `get_the_tags()` incorrectly. It **does not** return an array of tag _names_. It returns an array of tag **objects**. Each tag object does contain the tag's name (along with other data), but you can't use `implode()` on that result. I used your original code just adding a step to put the tag object's name into an array. Then your code picks up with the implode from there. add_filter('wpfts_index_post', function($index, $post) { global $wpdb; $data = get_the_tags($post->ID); $tag_array = array(); foreach( $data as $tag_object ) { $tag_array[] = $tag_object->name; } $index['post_tag'] = implode(' ', $tag_array); return $index; }, 3, 2); Always check the documentation for a function to make sure you are getting the expected result (in this case an object instead of an array). See `get_the_tags()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "search, tags" }
How to add a custom taxonomy to a custom post type's document tab I created a custom taxonomy and wanted to add it to the side-menu of my portfolio custom post type (in the admin area). My custom taxonomy is not loading, but the default one ('category') does. What did I miss? add_action( 'init', 'add_taxonomies' ); function add_taxonomies() { register_taxonomy( 'related_service', 'portfolio', array( 'label' => 'Related Services', 'public' => true ) ); } add_action( 'init', 'register' ); function register() { register_post_type( 'portfolio', array( 'label' => 'Portfolio', 'public' => true, 'show_in_rest' => true, 'taxonomies' => array( 'category', 'related_service' ) ) ); }
If you're using the Block Editor you also need to add `'show_in_rest' => true` for the taxonomy. You only have it for the CPT currently.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "custom post types, custom taxonomy" }
register_activation_hook in mu-plugin not triggering I have a class setup to run some database scripts on my mu-plugin. function activate_mjmc_core() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core-activator.php'; Mjmc_Core_Activator::activate(); Mjmc_Core_Activator::mjmc_database_version(); Mjmc_Core_Activator::mjmc_companies_table(); Mjmc_Core_Activator::mjmc_locations_table(); Mjmc_Core_Activator::mjmc_companies_insert(); } register_activation_hook( __FILE__, 'activate_mjmc_core' ); Now these work just fine when i use this as a normal plugin where i have to activate it. But when i use this in my mu-plugins, all the other plugin functions work, it just doenst run the database functions listed above on activate. Is there something else i need to do on these database functions? or run this on another wordpress hook? thanks
MU plugins don't 'activate', or 'deactivate'. They're just present or not present. So you'll need a different approach. One option would be to just perform your activation functions on `init`, and store a record in the database to say whether or not it's already been done: function activate_mjmc_core() { if ( '1' === get_option( 'mjmc_activated' ) ) { return; } require_once plugin_dir_path( __FILE__ ) . 'includes/class-mjmc-core-activator.php'; Mjmc_Core_Activator::activate(); Mjmc_Core_Activator::mjmc_database_version(); Mjmc_Core_Activator::mjmc_companies_table(); Mjmc_Core_Activator::mjmc_locations_table(); Mjmc_Core_Activator::mjmc_companies_insert(); update_option( 'mjmc_activated', '1' ); } add_action( 'init', 'activate_mjmc_core' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugins, mu plugins" }
Is there a way to convert shortcodes to html content? There's this plugin called media downloader, it works awesome, but I like my WordPress site to be less dependent on dynamic content. I want the shortcode's dynamic content to be converted to html code programmatically. I know I can copy paste the HTML code using page source. But I need it to be done automatically.
This is what WP shortcode gives you. Short code basically generate HTML/Content automatically for you. A WP shortcode might be using some logic in order to generate the right HTML. What you are wanting does not seem to be the right way.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, php, shortcode, html" }
Set image size on media and text block with a function I'm using the Media & Text block within Gutenberg. You can adjust the size of the image by dragging the small blue circle: ![WordPress Media & Text Block]( Looking at the Media & Text settings on the right, it doesn't look possible to select the image size. When using the stand alone image block, you can adjust the image size, like so: ![Media Size]( Is it possible to set an image size using a function for this block type? I need the design to be consistent on the front-end.
The image size dropdown was added in PR #24795 which was included in Gutenberg v9.1 and then included in WordPress 5.6.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "functions, images, block editor" }
Save User Meta Email Address in Lowercase I'm looking for a way to save all email addresses to user meta as lowercase, ideally without validating and asking the user to change it but instead just saving it as lowercase. I've got as far as the following but can't get it to work: add_action( 'update_user_meta', 'meta_email_tolowercase', 10, 4 ); function meta_email_tolowercase( $meta_id, $object_id, $meta_key, $_meta_value ) { if( strpos( $_meta_value, '@' ) !== false && ! ctype_lower( $_meta_value ) ): $result = update_user_meta( get_current_user_id(), $meta_key, strtolower( $_meta_value ) ); endif; }
you can use this filter to do that add_filter("sanitize_email", function ($sanitized_email, $email, $message) { $sanitized_email = strtolower($sanitized_email); return $sanitized_email; }, 10, 3); but I am not sure if using "strtolower" is a good idea, does another readers know if it's better to use "mb_strtolower" to handle multibyte characters ? <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "hooks, actions, user meta" }
Woocommerce - Shop page repeat the products with filters I have a website with shop page < and tried to recreate the shop page using the shortcode but failed You can see after 3 products it shows a filter bar and then repeat the products so how to remove that filter bar and repeated products Thanks in Advance
`/shop` is a default woocommerce shop page. Adding shortcode to the content of that page simply prepends it before the actual shop page. Read more about it here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
How to put an "include" inside a "do_shortcode"? I need to put an include inside a shortcode. Can any one help me to do it, please? Example: echo do_shortcode( '[student]' . include 'incMac.php' . '[/student]' );
You won't be able to concatenate an include as it doesn't return a string. What you could do is store that include content in a variable, and then concatenate. ob_start(); include 'incMac.php'; $include_content = ob_get_clean(); echo do_shortcode( '[student]' . $include_content . '[/student]' ); `ob_start` tells php to store the output from the script in an internal buffer, instead of printing it. `ob_get_clean` returns the content of the buffer at the moment and deletes it, turning off the output buffering. We store this content in the `$include_content` variable, which can be concatenated.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "shortcode" }
Uploading picture via REST API I have picture URL like ` I'm trying make product with that pic, but REST API say it's the wrong format and it's not acceptable due to security. What can I do? Reformat it via PHP?
I did that by downloading first those picture via exec(wget).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rest api" }
How to move top widget to the left - Responsive Theme WordPress I have WordPress, responsive theme and whenever I upload a **top widget** , it stays a bit to the left from the header. How can I move the top widget to go close to the header image as in the picture? ![]( The header image is simply an image and the top widget image is a Google content matched ad.
Add this CSS to your theme's CSS: #top-widget { float: left; } If that fails you may try this: #top-widget { float: left !important; } Once you add your CSS ensure that you have cleared your cache.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets" }
How to add no follow to specific links? I have some cloaking affiliate links to which I would like to add the attributes of **nofollow**. However, I'm looking for a way in coding that will allow me to target links that contain specific string, like **/go/brand**. While searching, I found this code somewhere, but it didn't work for me in functions.php, so I was hoping someone might provide me with something that may do the job for me. Thank you so much in advance! add_filter( 'the_content', 'my_string_replacements'); function my_string_replacements ( $content ) { if ( ! is_admin() && is_main_query() ) { return preg_replace('/<a(.*href=".*\/go\/pluto\/?".*)>/', '<a$1 rel="nofollow">', $content ); } return $content; }
The replace code is replacing the whole a element content with `<a rel="nofollow">`. Here's the correction: I used `(.+?)` between `<a and href"` and before and after `/go/pluto/` to the closing `>`. Then in the replace, we put `$1 $2 $3` etc. to keep them and add `rel="nofollow"`. You can check in this test, and here's explanation about the replace. return preg_replace('/<a(.+?)href="(.+?)\/go\/pluto\/(.+?)"(.+?)>/', '<a$1href="$2/go/pluto/$3" rel="nofollow"$4>', $content ); **Edit:** Considering there are links that contains rel attribute already, we will run regex that searches for links that does have rel but doesn't contain nofollow and add nofollow: return preg_replace('/<a(.+?)href="(.+?)\/go\/pluto\/(.+?)"(.+?)rel="((?!nofollow).)*(?=")/', '$0 nofollow', $content); I'm still figuring out the appropriate code to insert rel if the a element doesn't contain it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, seo, regex" }
How to display the category id along with category name on categories list? I have a categories and I have to display all categories id along with categories name. Something like Accessories(id=1) featured(id=1) OR id Name 1 Accessories 2 featured ![enter image description here]( Is it possible to display without a plugin?
You can add new column using below code. replace `(your-texanomy)` with your taxonomy slug. I have tested and its working fine. < #add header before category name function taxonomy_custom_column_header( $columns ){ $columns = array_slice($columns, 0, 1, true) + array("cat_id" => "ID") + array_slice($columns, 1, count($columns) - 1, true) ; return $columns; } add_filter( "manage_edit-(your-texanomy)_columns", 'taxonomy_custom_column_header', 10); # add value to newly added column function taxonomy_custom_column_content( $value, $column_name, $tax_id ){ if ( 'cat_id' == $column_name ) { $content = $tax_id; } return $content; } add_action( "manage_(your-texanomy)_custom_column", 'taxonomy_custom_column_content', 10, 3);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, categories" }
How to nest a list inside a blockquote using the Gutenberg block-editor? WordPress Gutenberg block-editor don't allow to paste an HTML list inside a blockquote. It transforms it arbitrarily in a series of `<p>` tags, which is not semantically what I want. I've found that the issue I'm facing has been already reported on Github, but no solution has been implemented since. Has anybody here found any way to handle this situation before the problem will be solved ?
Create blockquote and edit it as HTML using right-click (some accuracy required as everywhere in Gutenberg). The result of quick tryout: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "block editor" }
Prevent third party plugin's admin page access based on user type Am using a third party plugin(eg. ABC Plugin). And their code doesn't have any hooks or filters. And they don't provide customization based on our requirements. So if I modify the plugin code, I would have to duplicate the changes each time when an update is available for that plugin. Hence I decided to create a plugin, that will work along with the other plugin, and make the necessary modifications. Right now, I want to limit the access to a specific url of the plugin page (in admin panel), only to a specific user type. And the url is like ` Am thinking to use the `admin_init` hook to check whether the current requested url is the above, by simply doing `if( $_GET['page']=='abcplugin') && $_GET['route_name']=='customers__index')` But am not sure how to show the `You do not have permission to access this page` error message. Any inputs?
It's done with `wp_die()`. Something along these lines: ` if ( $no_user_access ) { wp_die( 'You do not have permission to access this page' ); }` See: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugin development, wp admin, user roles" }
Show template part if part of term I'm not an educated programmer, but usually i can put existing code together so it works the way i want it to. But this time i'm lost, i feel like i've tried everything. I'm trying to only show a template part if the product is part of a specific term. This is one of the numerous code snippets i've tried. I hope it makes sense to what i'm trying if not i'll answer any questions :) $taxonomy = taxonomy_exists( 'produkttype' ); if ( $term = 'pude' && $term = 'senge' ) { echo get_template_part( 'partials/sections/section', 'trustpilot' ); }
Try this if( has_term('pude', 'produkttype') || has_term('senge', 'produkttype')) { get_template_part( 'partials/sections/section', 'trustpilot' ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, taxonomy, terms" }
Cannon see subcategory in permalink There are a lot of articles (old one, though because I use new WordPress 5.3.1) about how to include category and subcategory in WordPress URLs. I followed those articles (pretty much are the same), but something is wrong. I checked Settings > Permalinks > Custom Structure and added `/%category%/%postname%/`, and all I can see is parent category, not child category. It's the same issue whatever template I use, so I guess template is not a problem. What is wrong?
Good question. WordPress determines the permalink by finding the category closest to the root. * If the parent category is selected (or if both the parent category and the child category are selected), then the permalink will only include the parent category. * If only the child category is selected, then the permalink will include the parent category followed by the child category. So, for your case, be sure to select only the child category.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, permalinks" }
Filter posts in pre_get_posts order by meta value date (desc or asc) I am trying to order the post by a meta value but it is not working the right way. I store the date in the post meta value like this `01 December 2019 10:00`. Now I want to sort the posts `desc` or `asc` like the `date`. I tried the following code: $orderby = $query->get( 'orderby' ); $sorting = $query->get( 'order' ); if ('month' == $orderby ) { $query->set( 'meta_key', 'preferred_date' ); $query->set( 'orderby', 'meta_value'); $query->set( 'order', $sorting ); } I use the code in the action `pre_get_posts`. Did anyone have some suggestions?
The problem was that I have not stored the date values in the right way. I had to save it like `Y-m-d` or `Y-m-d H:i`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development" }
Execute a piece of code also when the cached version of a page is served How can I be sure that a piece of code is executed also for the cached page of the website?
You call it asynchronously via the REST API. In a best case scenario, you want the entire HTML of a page cached (full page cache). Executing PHP inside that is not easily possible and that's exactly the idea behind it So what you want is some JavaScript that talks to the REST API. The JavaScript code (your " **logic** ") must be written in a way that it does not need to change, so it can be embedded within the cached HTML. Your **data** that comes from the endpoint can change, because the endpoint is not cached in the same way as a site is.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "cache" }
Does the debug.log do log rotation? This is more like of an inquiry. So I enabled my WP_DEBUG_LOG to true. It does work though, debug.log is in my wp-content's directory. But does it also do log rotation like different file for each day? Example: Today's file - debug.log Yesterday's - 2019-12-18-101010-debug.log Does it work like this? Or just debug.log all through out?
No, it creates only one file. There is no log rotation involved. But... Sometimes “but” can be a good thing ;) WP uses error_log for its debug log, so you can change its location using: ini_set( 'error_log', WP_CONTENT_DIR . '/debug-' . date('Y-m-d') . '.log' );
stackexchange-wordpress
{ "answer_score": 11, "question_score": 4, "tags": "php, debug, apache, logging" }
How to integrate JSS to WordPress WordPress is all about PHP and JSS is... Js. And I want to use JSS but I got trouble in interacting between generated HTML by PHP and CSS from JSS. Like in the official example (< JSS generate a version of CSS classes. This means I cannot set fixed classes in WordPress. What should I do?
JSS is designed for dynamically generated HTML rendered by JS. It's purpose is to generate unique identifiers for class names to prevent collisions in naming. If you want to have static CSS generated it's easier to look at LESS\SASS\SCSS and build them with gulp, or with Less straight(< **Here's heavily modified example which does what you might want**. < All is done using `jss-plugin-global` Compare it to initial code in how CSS rules are defined with `@global` to make them rendered without enhancing class names with dynamic parts. Also look at < docs and nested plugin docs < as it's useful. And probably you'll find it useful to use JSS-CLI < So with JSS CLI you'll be able to complile JSS into static CSS and serve it via `wp_enqueue_style()` as normal css file. Or you can build your JS with JSS file from ES6 syntax with webpack+babel and then use `wp_enqueue_script()` and your built JS will compile inner JSS and inject into page just like in example.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, css" }
Save html content of a widget textarea I have a textarea inside a custom widget that needs to hold some html tags. I've noticed that if I use the `esc_html` or `esc_attr` or `strip_tags` to take the things secure, I will lost all the html I use. How I can keep the html tags in place, I just need to add an `<i>` tag and `<p>` or `<h>`, `<a>` tags. Any suggestion?
Use `wp_kses_post` instead! It will keep all the tags allowed in a post, you can also use `wp_kses` and provide a list of tags and attributes
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, plugin development" }
Index of row in WP_List_Table In `WP_List_Table`, the method `column_$custom( $item )`, if implemented, is called once for each row of data that is being displayed in the list table. So, if my list table has three rows of data, then the method `column_$custom( $item )` will be called three times, once for each row In addition to displaying the data, I need to know the "row index" of the data being displayed. In the above example, I like to extract `0` because it is the first row, `1` for the second, and `2` for the third. Is there a way of knowing the row index?
That should be possible, but it looks pretty complicated. As you have undoubtedly seen, the `display_rows` method just passes a single line and there's no counter. This means that the row number must be in the `$item` variable for you to extract it. Since it is not there natively, you must insert it before you start displaying the table. Luckily, there is a method expressly designed to do this, `prepare_items`. This is an abstract class, meaning it must be filled in by child classes that use this class. Take, for instance, a look at the way it is implemented in `WP_Posts_List_Table`. So what you'll have to is override the existing `prepare_items` of the child class you are working with, and loop through the rows to add a new property `$row_count` to each one of them. Then, when you implement column_$custom( $item ) you can extract `$row_count`. Disclaimer: obviously I didn't test this myself, it's just a concept I think should work.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp list table" }
Setting color of specific menu items depending on page or post tag I have a website that uses a plugin that lets me add categories and tags to pages. Is there a way of automatically changing the color of a menu item linked to all pages with a particular tag or category? Specifically, I want to add the class "unwatched" to the menu item of any page that has been tagged with the "unwatched" tag. I have tried the following code but I'm sure I've got it wrong: (it didn't work) add_filter('nav_menu_css_class', 'custom_nav_menu_css_class', 10, 2 ); function custom_nav_menu_css_class( $classes, $item ) { if( 'tag' === $item->object ){ array_push( $classes, 'unwatched' ); } return $classes; }
OK, got it :-) add_filter( 'wp_nav_menu_objects', 'add_nav_menu_item_class' ); function add_nav_menu_item_class( $items ) { foreach ( $items as $item ) { $post_id = get_post_meta( $item->ID, '_menu_item_object_id', true ); $post_tags = get_the_tags( $post_id ); if ( $post_tags ) { foreach( $post_tags as $tag ) { if ( $tag->name == 'unwatched' ) { $item->classes[] = 'unwatched'; } } } } return $items; } The associated CSS, which changes the color of all menu items tagged with the 'unwatched' class, is li.unwatched > a { color: FORESTGREEN; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, tags" }
how to redirect 301 my old search query string to wordpress search query string? How to redirect 301: /cgi-bin/mt/mt-search.cgi?search=WORDS to in `.htaccess` file?
Try something like the following at the top of your root `.htaccess` file ( _before_ the WordPress block): RewriteCond %{QUERY_STRING} ^search=([^&]*) RewriteRule ^cgi-bin/mt/mt-search\.cgi$ /?s=%1 [R=301,L] `%1` in the `RewriteRule` _substitution_ is a backreference to the captured group in the preceding _CondPattern_ (ie. the value of the _search_ URL parameter - "WORDS"). Clear your browser cache before testing. It is preferable to first test with a 302 (temporary) redirect to avoid caching issues. Reference: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "htaccess" }
How to access repeater field of a custom field? I have a custom post type called `donation_group` it has a custom_field called `donate_pages` which is a repeater field. This `donate_pages` has again fields called `donation_object` and `amount_received`. I want to access these custom fields in my controller ie php file. This is the code I have tried so far $donation_group_posts = Timber::get_posts(array( 'post_type' => 'donation_group' )); foreach ( $donation_group_posts as $dg_post ) { $dg_donate_pages = $dg_post -> donate_pages; echo "dg_donate_pages", $dg_donate_pages; } When I echo dg_donate_pages, I am only getting the number of rows that repeater field has. How can I get its values?
Try this: foreach ( $donation_group_posts as $dg_post ) { $dg_id = $dg_post->ID; if(have_rows('YOUR_REPEATER_SLUG', $dg_id)){ while(have_rows('YOUR_REPEATER_SLUG', $dg_id)) : the_row(); echo get_sub_field('YOUR_FIELD_SLUG'); endwhile; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, advanced custom fields" }
How can I figure out where memory is being used? I've got a WordPress site that's using too much memory, and I'm having problems with it on my shared hosting site. So, to try to figure out where it's coming from without wrecking my live site, I cloned the site and installed into a local VM, where I deleted all plugins except Query Monitor. That clone is still using 157M of memory with no other plugins installed. On the other hand, I've got a fresh WordPress install that I installed Query Monitor into, and it's using only 4M of memory. So clearly, there's something in my clone that's burning memory. It's not the plugins -- they're gone. It's not the theme -- I switched it to the same theme as the fresh install (stock 2017 theme). I've looked through the output from Query Monitor, and I can't see a difference of substance. What can I look for to try to figure out why my clone is consuming so much memory?
I found it: it was a massive set of WordPress cron jobs that I had inadvertently accumulated. The technique I used was to keep removing things from the database in the clone that weren't in the blank install, watching the memory in query monitor to see what dropped it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "memory" }