INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How can I make my custom shortcode work in a Custom HTML Widget? I created a plugin and tried to use its shortcode in a Custom HTML Widget, but for some reason it's outputting `[my_shortcode_name]` instead of executing the shortcode. The shortcode works fine if I place it on the page or in a Text Widget. How can I make it work in a Custom HTML Widget?
I was able to make it work by adding these two lines to my theme's `functions.php` file: add_filter( 'widget_text', 'shortcode_unautop'); add_filter( 'widget_text', 'do_shortcode'); The Custom HTML Widget now correctly executes the shortcode function and outputs the result.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 4, "tags": "plugins, php, plugin development, widgets, html" }
get_terms() - unexpected '=>' (T_DOUBLE_ARROW) error I am trying to get the terms from all the taxonomies in an array. but this throws an error like this ..not sure why. Is it the wrong method?: > Fatal error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ',' or ')' public function pggggo_list_of_terms(){ $terms = get_terms( 'taxonomy' => array( 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras') ); return $terms; }
This is a PHP syntax error. You're attempting to pass an array to `get_terms()` but haven't used `array()` or `[]` to make it an array. This means that `=>` is invalid here. The code should be: public function pggggo_list_of_terms() { $terms = get_terms( [ 'taxonomy' => [ 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras', ], ] ); return $terms; } or public function pggggo_list_of_terms() { $terms = get_terms( array( 'taxonomy' => array( 'vehicle_safely_features', 'vehicle_exterior_features', 'vehicle_interior_features', 'vehicle_extras', ), ) ); return $terms; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "custom taxonomy, taxonomy, terms" }
How can I show a custom WordPress menu anywhere I want on my website? I went into Appearances > Menus and created my own menu called "default menu." Then I tried to include it in my WordPress theme, but was unsuccessful. I am trying to include it just before the footer. When I tried with this code: <?php wp_nav_menu('theme_location=header-menu&container=false&menu_id='); ?> it just gave me a list of all the pages I've created. So then I tried with: <?php echo do_shortcode('[listmenu menu="default menu"]'); ?> and then it just echoed what was in the PHP tag. Please tell me what I should be doing differently. Thank you.
`wp_nav_menu()` is the correct function to display a menu. Is the default menu assigned to the location you've specified and if so, are there any items assigned to that menu? Menus without any items assign will display pages by default. You could try adding the `menu` param with a value of the name of your default menu.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, menus, navigation" }
Restricting users to a specific front end page I am looking for a way to restrict users of a certain role to only be able to access one page on my wordpress site. When a user of the role logs in they should be redirected to the page and they should not be able to access any other pages. I have tried multiple plugins that can restrict pages to users, but I have not found one that can restrict users to pages. Does this functionality exist within Wordpress and how would I implement it if it does?
You'd have to add a function during the `init` action of WP. There you'll get the `current user` and check whether they have a specific `role` assigned to them and `redirect` to the page when they do. add_action('init', function () { $user = wp_get_current_user(); $role = 'your role'; if (in_array($role, $user->roles)) { wp_redirect('url'); } }); WordPress Function References: * < * < * < Relevant SE posts: * <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, user roles" }
How to remove recurring totals information for a particular subscription product? I have a subscription product in which I have customized checkout page for this particular product. I want to remove "Recurring Totals" row from checkout and cart page. Here is my code: function cart_subtotal_func_unset( $total ) { print_r($total); unset($totals['cart_subtotal']); return $totals; } add_filter('woocommerce_cart_item_subtotal', 'cart_subtotal_func_unset', 10, 2); And here is my screenshot for checkout page. ![enter image description here](
Try filtering the hook woocommerce_cart_calculate_fees. Use this code. it might work for you. add_filter( 'woocommerce_cart_calculate_fees', 'add_recurring_postage_fees', 10, 1 ); function add_recurring_postage_fees( $cart ) { if ( ! empty( $cart->recurring_cart_key ) ) { remove_action( 'woocommerce_cart_totals_after_order_total', array( 'WC_Subscriptions_Cart', 'display_recurring_totals' ), 10 ); remove_action( 'woocommerce_review_order_after_order_total', array( 'WC_Subscriptions_Cart', 'display_recurring_totals' ), 10 ); } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "woocommerce offtopic" }
Save button is not working on custom widget I created a custom widget according to Widget API and it seems to work until I make changes. The save button is not triggered, this problem is only affecting this new widget. Ps. The custom widget is also part of a `dynamic_sidebar` but every other widget works fine. The button is enabled but not triggered. ![Save Button issue]( Edit. Widget code
I have checked code of codeshare.io/2jJLDK and found the issue. Please follow below instructions for fix this issue. > In the form function, you have used input type as "url" for Link and as per rule of input type "url", it can't take "#" so you must use actual url with http/https like < for saving/updating widget link data.* * * * > If you want to save/update widget link data with "#" then you need to change input type as "text" like below **From:** <input type="url" name="<?php echo esc_attr( $this->get_field_name( 'link' ) ); ?>" id="<?php echo esc_attr( $this->get_field_id( 'link' ) ); ?>" class="widefat" value="<?php echo esc_attr( $link ) ?>"> **To:** <input type="text" name="<?php echo esc_attr( $this->get_field_name( 'link' ) ); ?>" id="<?php echo esc_attr( $this->get_field_id( 'link' ) ); ?>" class="widefat" value="<?php echo esc_attr( $link ) ?>">
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets, register sidebar, customization" }
remove string: 'custom content...' from every page I'm not quite sure how this came about, but every page on my site has the text 'custom content...' appended to the end of the body. The string appears within `<p>` tags on the frontend. I've searched in ubuntu for that string in the directory but none of the results seem to be the explanation. I've also opened and scanned files like `page.php`,`footer.php`, `header.php` but it doesn't seem to be in there. How might I remove this (without hiding via css)? it also does not appear in the wordpress html editor.
It ended up being a custom plug-in that I was following in a tutorial but abandoned a long time ago and left active. Thanks for the tips!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "html, content" }
Trouble running $wpdb->query() with last_insert_id I am trying to get a primary key from a coupon table to put it in my target table as a foreign key. In between I would like to run a query to get the last insert id. I can't get the syntax right though $couponId = $wpdb->query("select last_insert_id() from frequentVisitorCoupons_coupons"); var_dump($couponId); // false $couponId = $wpdb->query("select * from frequentVisitorCoupons_coupons where last_insert_id()"); var_dump($couponId); // false What is the correct syntax for this query?
You can get the last inserted ID from `$wpdb` with the `insert_id` property: $wpdb->insert( ... ); $couponId = $wpdb->insert_id
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, mysql, wpdb" }
Shortcode from a function not working I am trying to create a shortcode from a custom function in WP but it seems like I'm doing something wrong. I have a function in child's theme function.php and add_shortcode code: function uniquetestfunction() { echo '<div class="my_class">Test Element</div>'; } add_shortcode(‘uniqueshortcodename’,’uniquetestfunction’); Which should generate a shortcode [uniqueshortcodename]. I have done this with existing functions in different plugins and it worked fine. But when added to a page, it's not rendering the function, just showing the shortcode as a text. Any ideas what I'm doing wrong? I'm very new to PHP :) Thanks
If you refer to the documentation for add_shortcode, you need your function to return the content: function uniquetestfunction($attributes) { return '<div class="my_class">Test Element</div>'; } add_shortcode('uniqueshortcodename','uniquetestfunction'); You also used the wrong quotes in your add_shortcode line - stick with single `'` or double `"` quotes.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, functions, shortcode" }
how to display a specific wordpress menu? Below is my code: wp_nav_menu( array( 'menu', _('My Custom Header Menu'), 'theme_location' => 'my_custom_location', ) ); * * * And as result, I obtain all Wordpress page's menu link instead of the menu of My Custom Header Menu.
**Register your navigation menu** Add this code to your functions.php file. function my_custom_new_menu() { register_nav_menu('my-custom-menu',__( 'My Custom Menu' )); } add_action( 'init', 'my_custom_new_menu' ); **Create new menu** You can now go to Appearance » Menus page in your WordPress admin and try to create or edit a new menu. You will see ‘My Custom Menu’ as theme location option. **Display new menu** wp_nav_menu( array( 'theme_location' => 'my-custom-menu') );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "customization, menus" }
Inserting post content into pages when using custom taxonomies I am inserting a snippet of text into posts when posts have a certain taxonomy. I want this text to be editable by WP users n the admin area. The following doesn't seem to want to do anything for me, admittedly I copied pasted and amended from another thread on here. <?php if ( has_term( 'ART', 'product_relevance' ) ) { ?> <div class="row"> <div class="notification col-lg-9 order-1"> <?php $my_id = 927; $post_id_927 = get_post($my_id, ARRAY_A); $title = $post_id_927['post_content']; ?> </div> </div> <?php } ?> The if statement works fine, it is just the block calling the post by ID.
That code never outputs anything to the page: <?php if(has_term('ART', 'product_relevance')): $my_post = get_post(927); if(isset($my_post->post_content)): ?> <div class="row"> <div class="notification col-lg-9 order-1"> <?php echo $my_post->post_content; ?> </div> </div> <?php endif; ?> <?php endif; ?> Untested, but in essence you need to do something with the post content.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "get posts" }
Add the Name of Products Ordered to Admin New Order Email WooCommerce I am trying to get the names of all the products ordered separated by a comma and added into the subject line of the new order email sent to the admin. Here's some code I have but it's only adding in the first product name, not all of them: add_filter('woocommerce_email_subject_new_order', 'change_admin_email_subject', 1, 2); function change_admin_email_subject( $subject, $order ) { global $woocommerce; $items = $order->get_items(); foreach ( $items as $item ) { $product_name = $item->get_name(); } $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); $subject = sprintf( '[%s] New Customer Order (#%s) of '.$product_name.' from %s %s', $blogname, $order->id, $order->billing_first_name, $order->billing_last_name); return $subject; }
Since Woocommerce 3 your actual code is a bit outdated. In the following you will get all products names _(coma separated)_ in the email subject. add_filter('woocommerce_email_subject_new_order', 'change_admin_email_subject', 10, 2); function change_admin_email_subject( $subject, $order ) { $products_names = array(); foreach ( $order->get_items() as $item ) { $products_names[] = $item->get_name(); } return sprintf( '[%s] New Customer Order (#%s) of %s from %s %s', wp_specialchars_decode(get_option('blogname'), ENT_QUOTES), $order->get_id(), implode(', ', $products_names), $order->get_billing_first_name(), $order->get_billing_last_name() ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, woocommerce offtopic" }
Warning: require_once(/home/onetwo/public_html/wp-config.php): after changing php version on godaddy it started giving these error on wordpress any help highly appriciated. < > Warning: require_once(/home/onetwo/public_html/wp-config.php): failed to open stream: Permission denied in /home/onetwo/public_html/wp-load.php on line 37 > > Fatal error: require_once(): Failed opening required '/home/onetwo/public_html/wp-config.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/onetwo/public_html/wp-load.php on line 37
Contact GoDaddy customer support and ask them to check file permissions for your site.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "errors" }
Having Issues with in_category , need help I used this code to display content from my custom fields only where post category id is 5, but all data from the custom fields show above the table in a straight line like a paragraph. <?php $post = $wp_query->post; if ( in_category('5') ) { echo "<table><tr><td> ".the_field('song_title')."</td></td> <tr><td> <b>Artist: </b> ".the_field('artist')."</td></tr> <tr><td> <b >Song Title:</b> ".the_field('song_title')."</td></tr> <tr><td> <b>Song Lenght:</b> ".the_field('song_lenght')."</td></tr></table> "; } ?>
Welcome to this community Prezido. `the_field()` function has echo in it. There is no problem with `in_category()` function. You need to use `get_field()` function when you echo the values of fields. I've updated your code. This version should work as expected. <?php $post = $wp_query->post; if ( in_category( '5' ) ) { echo '<table> <tr><td> ' . get_field( 'song_title' ) . '</td></tr> <tr><td><b>Artist: </b> ' . get_field( 'artist' ) . '</td></tr> <tr><td><b >Song Title:</b> ' . get_field( 'song_title' ) . '</td></tr> <tr><td><b>Song Lenght:</b> ' . get_field( 'song_lenght' ) . '</td></tr> </table> '; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "posts" }
Stop WooCommerce from updating user/user meta after checkout Customers have billing/shipping addresses saved to their account and when they checkout they are presented with the billing/shipping address fields. If they update them in the checkout and confirm their order, this also updates their addresses on their account. I understand this is the expected behaviour but not what our site requires. I want to still show the address fields on the checkout but don't want it to update their account once it is being processed, but I also need the addresses they enter during checkout to be attached to the order meta, so the addresses on the order/order meta match those that they entered during checkout. Is this possible? I've tried looking for hooks or how to programatically approach this but all I can find is how to add additional meta fields to an order which is not what I want.
To avoid user registration data to be updated each time an order is placed use the following: add_filter( 'woocommerce_checkout_update_customer_data', '__return_false' ); Code goes in function.php file of your active child theme (or active theme). Tested and works.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "woocommerce offtopic" }
Slider with two images at a time I need an images slider that supports adding two images next to each other and to show them at the same time with prev & next option, I need to be able to change to the next two images when a user clicks on next & prev , I will use this to display two images of [before and after hair cut].
Slick slider handles displaying multiple slides at once nicely. You can also set it to display different number of slides at different breakpoints for responsive layouts. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
PHP error when using newer PHP versions When enabling PHP version 7.2.17 or newer on my site, I get a PHP-related error message on some pages. **Warning:** Use of undefined constant comment_notes_before - assumed 'comment_notes_before' (this will throw an Error in a future version of PHP) in **/home/(username)/public_html/(domain name).com/wp-content/themes/Divi-child/comments.php** on line **68** Here is the code on line 68 of the comments.php file: comment_form( array( 'fields' => $fields, 'label_submit' => esc_attr__( 'Submit', 'Divi' ), 'title_reply' => '<span>' . esc_attr__( 'Leave a comment', 'Divi' ) . '</span>', 'title_reply_to' => esc_attr__( 'Leave a Reply to %s', 'Divi' ), 'class_submit' => 'submit et_pb_button', comment_notes_before And here is line 69: =>'<p class="comment-notes">' . __( '' ) . '</p>' ) ); ?> Any ideas what could be causing this and what adjustments I need to make to the PHP source code?
Please try to change that line to comment_form( array( 'fields' => $fields, 'label_submit' => esc_attr__( 'Submit', 'Divi' ), 'title_reply' => '<span>' . esc_attr__( 'Leave a comment', 'Divi' ) . '</span>', 'title_reply_to' => esc_attr__( 'Leave a Reply to %s', 'Divi' ), 'class_submit' => 'submit et_pb_button', 'comment_notes_before'
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Print WordPress username id inside JavaScript Hello am trying to print the user id inside an JavaScript <script type="text/javascript"> Li.re('ab12','$user_id'); </script> i wanna output like <script type="text/javascript"> Li.re('ab12','12'); </script> 12 is the number of the login in user. Is possible inside shortcode? <?php echo do_shortcode('[mycred_link href="'.get_field('incentivised_url', $taxonomy . '_' . $termId).'subid1='.$get_current_user_id.'[/mycred_link]'); ?> The `.$get_current_user_id.` inside the shortcode not works. Any help?
You can use `get_current_user_id()` to get the ID of the current user, and in your case, you can do so to print the user ID in the JavaScript `Li.re()` call: <script type="text/javascript"> Li.re( 'ab12','<?php echo get_current_user_id(); ?>' ); </script> And yes, you can include the user ID as part of a shortcode: (note that I omitted the `href` parameter for simplicity) <?php echo do_shortcode( '[mycred_link subid1="' . get_current_user_id() . '"][/mycred_link]' ); ?> PS: Your shortcode was missing the closing `]` tag, so I added it above. All shortcode parameter values should also be wrapped in single/double quotes.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugin development, javascript, users" }
CSS - Initial HTML Margin Issue On WordPress Site This is a WordPress site and I'm using bootstrap. Site is < Basically I'm just trying to get rid of the initial top margin. So instead of this: ![enter image description here]( It should look like this: ![enter image description here]( I've tried adding styles to the html element in my stylesheet, but nothing has worked. I.e. html { margin-top: 0px!important; } So then I'm wondering if the issue is WordPress related? There is not any top margin when I place relevant code in a Codepen. Any ideas?
That looks like the margin added by the WP admin bar when you are logged into the site. WP adds an inline style tag which sets the margin on the html element with an !important flag. Since it typically comes after any of your own styles it overrides them even if you also use !important. Since it only displays when you are logged in it shouldn't matter much, but if you really want to remove the admin bar you can change that in the settings Users->Your Profile then uncheck "Show Toolbar when viewing site". Or add the following to your functions file. add_filter(‘show_admin_bar’, ‘__return_false’);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, html, twitter bootstrap" }
CF7 Custom Recipient - Changing the text I'm using the CF7 Custom Recipient plugin and i need to change some text on it. ![enter image description here]( In that red square i just want to change "CF7 Custom Recipient" to "Enter mail for inquiries" or something like that. How can i do it?
You can put this below code into theme's `functions.php` file and check it. see this screenshot function add_wpcf7_custom_recipient_meta_box_changed() { add_meta_box( 'wpcf7_custom_recipient_meta_box', 'Enter mail for inquiries', //just here to change text you want 'show_wpcf7_custom_recipient_meta_box', get_post_types(array('public' => true), 'names'), 'side', 'high' ); } add_action( 'add_meta_boxes', 'add_wpcf7_custom_recipient_meta_box_changed' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin contact form 7" }
correct validate and sql query Is this method of operation on the database is safe and correct? if(isset($_POST['name'])){ $table = $wpdb->prefix.'_my_table'; $post = trim(sanitize_user($_POST['name'], true)); $part = $this->wpdb->prepare("WHERE name = %s", $post) $results = $this->wpdb->get_results("SELECT * FROM {$table} $part", ARRAY_A) }
What you're doing is safe. However, some notes: 1. See the `WP_User_Query` class in the Codex. This is the, "official," way to do something like this, although you'll get an integer-indexed array of `WP_User` objects. Instead of the `ARRAY_A` that you've specified. 2. You probably don't want `_my_table`, unless your table is called something like `wp__my_table` (note the double underscore after `wp`). The prefix returned from `$wpdb->prefix` includes the underscore that many installations use after the prefix. 3. The `trim()` call after `sanitize_user()` is superfluous. It doesn't hurt anything but it's also a waste of compute cycles. 4. You may be able to write this in one line: `$results = $wpdb->get_results($wpdb->prepare("select * from {$wpdb->prefix}my_table where name = %s", sanitize_user($_POST['name'])), ARRAY_A);` This may be better or worse for you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, query, sql" }
WordPress User ID as Shortcode I want to use this as a shortcode to show in any post/page <?php $user_id = get_current_user_id(); if ($user_id == 0) { echo 'You are currently not logged in.'; } else { echo 'You are logged in as user '.$user_id; } ?> when I do this // Add Shortcode function uniqueID_shortcode() { $user_id = get_current_user_id(); if ($user_id == 0) { echo 'You are currently not logged in.'; } else { echo 'You are logged in as user '.$user_id; } } add_shortcode( 'naveen', 'uniqueID_shortcode' ); Gutenberg through an error of Updating failed, how to solve this? Thank you in advance.
From `add_shortcode` > ...Note that the function called by the shortcode should never produce output of any kind. Shortcode functions should return the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results... Try changing the `echo`s in your callback to `return`s and see, if that helps.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode" }
How to get category name or ID by post? I'm trying to display category name inside a foreach post .. <?php $recent_posts = wp_get_recent_posts(array( 'post_status' => 'publish', 'cat' => '', )); foreach($recent_posts as $post) : ?> <div class="card"> <div class="card-bg"> <div class="card-cat"> <?php foreach((get_the_category()) as $category) { echo $category->name.''; } ?> </div> <img class="card-img" src="<?php echo get_the_post_thumbnail_url( $post['ID'] ); ?>"> </div> <div class="card-body"> <div class="card-title"> <?php echo $post['post_title'] ?> </div> </div> </div> <?php endforeach; wp_reset_query(); ?> Does not work !
Please try below updated code <?php $recent_posts = wp_get_recent_posts(array( 'post_status' => 'publish', 'cat' => '', )); foreach($recent_posts as $post) : ?> <div class="card"> <div class="card-bg"> <div class="card-cat"> <?php $category_detail=get_the_category($post['ID']);//Pass POST ID foreach($category_detail as $cd){ echo $cd->cat_name.''; } ?> </div> <img class="card-img" src="<?php echo get_the_post_thumbnail_url( $post['ID'] ); ?>"> </div> <div class="card-body"> <div class="card-title"> <?php echo $post['post_title'] ?> </div> </div> </div> <?php endforeach; wp_reset_query(); ?> Try and let me know if any query. Hope it will help!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, categories" }
What is the criteria for pluggable functions? Why are certain functions pluggable (overrideable) in WordPress core and others not? (I note on the Codex page regarding Pluggable Functions no more are to be added in favour of filter usage.) But theoretically, would there be any security implications or other concerns for having them all pluggable - or is it simply so less pluggable code becomes incompatible with core updates?
Pluggable functions are less elastic than filters/actions. You can have only one pluggable function “active” - so only one plugin can override the core function. And you don’t have much control over which plugin will it be (WP will use the pluggable function that gets defined first). So it won’t be very useful if all actions were replaced by pluggable functions. On the other hand, there are some cases that using pluggable functions may have some sense. wp_mail is great example, I guess. If you want to change the way the emails are sent - you can. But you still want only one such function (otherwise, if you install two plugins that are changing it, you can end with multiple emails sent for every wp_email call). So it makes sense to use pluggable, whenever it is critical to perform an action only once, but you still want to be able to modify what action is performed exactly.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "functions, core, pluggable" }
Wordpress plugins for database queries I have a handful of custom database commands that my admin users need to execute on an adhoc basis - it's some business logic that was unavailable in a normal plugin. The commands are all procedures that either execute successfully, or return a record set. I want to be able to make these commands available through the Wordpress admin interface, ideally saving each query with a friendly name (eg Process1 - start of day) so that it is easier to execute but I haven't been able to find a solution. The admin users are slightly horrified by the likes of PHPMyAdmin for Wordpress, or even using SSH to get to a Bash menu script which executes database commands when options are selected.
I don't know of a plugin that allows you to do this out of the box, but as you are (/seem to be) comfortable with database manipulation, I've outlined below how you can achieve what you want using custom coding. You can run custom queries using the `wpdb`-class. There are a few posts on WPSE/SO that treat this. Once you've set those up, you can run them on, for example, a custom admin page (a new page in the Wordpress Dashboard). There are various tutorials available online (such as this one) that show how that can be done.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "mysql" }
How to keep close a sub-menu under homepage? I am facing an issue in the Avada vertical menu when the homepage is opened. Please note that all "Home", "Company profile" and "Servizi" link to the same page (the homepage). The sub-menu under "Servizi" is already opened while I would prefer it was closed by default, and that it could be opened simply by hovering "servizi", as it works properly when you try hovering "Servizi" from both "Clienti" and "Contatti". I am pretty sure there is an option in Avada/WP to do that, or otherwise by adding some JS code, but I really have no idea how to do it!
To do that, you have to set `hidden` attribute to the sub menu. **CSS** #wrapper .fusion-vertical-menu-widget.left .menu .sub-menu { display: none; } to toggle display on the menu on hover over servizi, you can add jQuery hover to the menu item. **jQuery** var subMenu = jQuery("#wrapper .fusion-vertical-menu-widget.left .menu .sub-menu"); jQuery("#menu-item-12049").hover(function(){ subMenu.show(); }, function(){ subMenu.hide(); }); **Note:** You should change the class values to more appropriate values, these are just extracted from what I saw, but probably a good idea to get better css selectors
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "javascript, css, sub menu" }
How to make default "Privacy Policy Page" a normal page? When you install WordPress it creates a default Privacy Policy page. I would like to make this page be a normal page, but I can't see where to "unset" the Privacy Policy page. I named this page "Company" but as you can see it still says it's the Privacy Policy page. How can I change this? (I want to repurpose this existing page in order to keep the page IDs sequential and logical for my site.) ![privacy-policy-screenshot](
Log into your wordpress admin area. Go to Settings-> Privacy ![enter image description here]( From there, you can either select a different(unsued) page for default privacy policy page or you can create a new one within same page. So change your current privacy page to a different one and you can use it as you wish
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, pages" }
Unit Test in Wordpress I work in wordpress with a lot of classes that use wordpress functions and I'd like make unit tests for them. The problem I found is that phpunit doesn't recognize wordpress functions and the tests don't work. I tried to include in the test class the index.php, wp-load.php and when they are included, phpunit doesn't work and exits through "exit code 0" without do anything -the error is shown in the PhpStorm Terminal. If I execute the command in the cmd, the cmd doesn't throw any information, just a blank line. Php Version: 7.3.3 PhpUnit Version: 7.5.9 Wordpress Version: 4.9.1 An example of an error is to test for a class with "add_action" in their constructor and the error is: "Call to undefined function add_action()". I don't know what file I have to include for doing work this test or what is the method to test the class correctly.
Take a look at the WordPress core setup with PHPUnit: < Using this process rather than rolling your own allows you to leverage the boostrapping (and other customization) specific for WordPress. From the Codex: > When `phpunit` is invoked, the test suite runs a script that sets up a default installation of WordPress, with a configuration similar to what you get with the GUI install. Before any tests are run, the following steps take place: > > * WordPress is bootstrapped (by including `wp-settings.php`). This means that all tests run after the entire WP bootstrap (through `wp_loaded`). > * All default content is deleted. This includes sample posts and pages, but does not include the default user or the ‘Uncategorized’ category. > Hope that helps!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, unit tests" }
Display description on cart page How to display main product description on the cart page? I tried this but it works only for variation description. $_product->description I want to display the main description which is the same for all variations.
$_product object is product variation object. You have to first get the parent product id and then get the description of parent product. $parent_product_id =$_product->get_parent_id(); $parent_product = get_post($parent_product_id); echo $content = $parent_product->post_content; Or echo $_product->parent->description;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic" }
Seeking Hook Whenever a Custom Taxonomy Term Has Been Added I'm looking for a hook that fires whenever a new term is added to a custom taxonomy. I tried `set_object_terms` and `create_category` but I can't get them to work it seems. I need a hook that will fire whenever someone adds a term when creating a new Post.
`create_category` runs when a new _category_ is created, in turn `set_object_terms` fires after a terms have been _set_ to object. The hooks you are looking for are: * create_{$taxonomy} \- new term in a specific taxonomy is created * created_{$taxonomy} \- new term created, term cache has been cleaned * create_term * created_term
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "hooks" }
Display sorting options dropdown when using WooCommerce product category shortcode I have a WordPress site, with WooCommerce. The WooCommerce archives pages as shop display a dropdown sorting filter like in this screenshot: ![enter image description here]( Now in another page let's say `example.com/foo` On that page I use a WooCommerce shortcode: [product_category per_page="90" columns="3" orderby="" order="ASC" category="foo" prdctfltr="yes" pagination="yes"] But the sorting dropdown is not shown. What I am doing wrong? How can I display the sorting dropdown?
Since WooCommerce 3.2, Woocommerce shortcodes and their available attributes have changed. So try the following shortcode instead _(for "foo" product category)_ : [product_category limit="90" columns="3" category="foo" paginate="true"] or inside php code: echo do_shortcode( '[product_category limit="90" columns="3" category="foo" paginate="true"]' ); Now you will see that the sorting options dropdown appear. **Note:** `orderby` argument with an empty value **has no effect**. `order` argument is **`ASC` by default**.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "php, woocommerce offtopic, shortcode, sort" }
How I shift me website from WordPress managed to linux hosting? I am now hosting my website on GoDaddy managed hosting (basic plan). Here the hosting provider company did not allow me to install third party plugins like cache plugins, etc. There are other limitations too. Now I want to shift my website to Linux hosting. Please help me to backup my website because it automatically backs ups under GoDaddy basic plan.
You could use a plugin like Duplicator to download a copy of your website and database. Then you could set up a new clean WordPress install on the new server and import your Duplicator-export. That way you are able to test everything before canceling the GoDaddy-plan. Duplicator Plugin
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "migration" }
is_page(id) not working for blog page I am trying to add a css file specific to 3 pages using the `is_page(postid)` for a WordPress website in the `functions.php` if (is_page(1) || is_page(2) || is_page(3) ) { echo "<script>console.log('insideIf');</script>"; wp_enqueue_style( 'custom_css', get_template_directory_child() . path); } So considering 1,2 and 3 are the ids of the pages, the pages with the ids 2 and 3 are logging the message in the console and loading the css file whereas `is_page(1)` does not respond. I tried changing it to `is_page('1')` or `is_single()` or `is_single(1)`. The page that is not getting detected is a blog page and i even tried with the title `is_page('blog')`. Ps. Cross checked the id many times, so I am definitely not using the wrong id.
If the page you’re trying to check is set as Page for posts, then `is_page` conditional won’t be true. In such case you should check if `is_home`. Why? All these conditional tags are based on global `wp_query`. For page that is set as page for posts (home of your blog), the global query doesn’t contain singular page - it contains list of blog posts.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, blog page" }
Do I need normalize.css when developing my own Wordpress-theme? I'm developing my own Wordpress theme and I'm trying to make it as light as possible. I started from the Underscores starter theme, but they use normalize.css to reset the styles. Is it necessary to include it in my theme or is there a better method?
Web standards are pretty good these days and IMO I don't think things like normalize are nearly as necessary as years ago. I would recommend having a look through the CSS file and deciding for yourself. You can always just grab what styles you think are relevant and include them in your own CSS. This will cut down on a dependency and make you more aware of what code you are including in your own theme. Quick note: You can use caniuse.com to look up specific styles or tags you might have questions about. For Example, normalize includes this CSS... main { display: block; } If you look up main HERE, you will see it was added to the spec late and could cause bugs in IE if you don't apply `block` to it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "theme development, css" }
Set fullscreen mode by default The block editor has a `Fullscreen mode` which you can access via the tools options on the top-right: ![enter image description here]( Is there a PHP approach to enable the `Fullscreen mode` by default? As in, force this mode for all users. Alternatively, a javascript solution.
Switching Gutenberg to fullscreen mode requires setting to TRUE `fullscreenMode` from the `core/edit-post` package. To enqueue appropriate script, you use `enqueue_block_editor_assets` action hook. function se337302_fullscreen_editor() { $js_code = "jQuery(document).ready(function(){" . " var isFullScreenMode = wp.data.select('core/edit-post').isFeatureActive('fullscreenMode');" . " if ( !isFullScreenMode )" . " wp.data.dispatch('core/edit-post').toggleFeature('fullscreenMode');" . "});"; wp_add_inline_script( 'wp-blocks', $js_code ); } add_action( 'enqueue_block_editor_assets', 'se337302_fullscreen_editor' );
stackexchange-wordpress
{ "answer_score": 8, "question_score": 5, "tags": "block editor" }
Append a term to WooCommerce product existing product category terms I have a form which makes people decide about the sub-categories of their product and the form gets submitted on user post method **Im trying to add the parent category to it as well** Now I tested couple of way to adding the `$term` but each time it just get replaced not added add_action('transition_post_status', 'new_product_add', 10, 3); function new_product_add($new_status, $old_status, $post) { if( $old_status != 'publish' && $new_status == 'pending' && !empty($post->ID) && in_array( $post->post_type, array( 'product') ) ) { $term = get_term_by('name', 'parent_category', 'product_cat'); wp_set_object_terms($post->ID, $term->term_id, 'product_cat'); } }
You just need to add a missing boolean argument in `wp_set_object_terms()` function like: wp_set_object_terms($post->ID, $term->term_id, 'product_cat', true); This time the term will be **appended** and not replaced. You should check that the term doesn't exist yet on the product, before appending it like: add_action( 'transition_post_status', 'new_product_add', 10, 3 ); function new_product_add( $new_status, $old_status, $post ) { if( $old_status !== 'publish' && $new_status === 'pending' && ! empty($post->ID) && $post->post_type === 'product' ) { $taxonomy = 'product_cat'; $term_id = get_term_by( 'name', 'parent_category', $taxonomy )->term_id; if( ! has_term( $term_id, $taxonomy ) ) { wp_set_object_terms( $post->ID, $term_id, $taxonomy ); } } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, woocommerce offtopic, terms" }
Conditional tag doesn't work in WordPress plugin I'm developing a plugin which can change the whole content of a special page in WordPress with an image. My plugin's code is here: <?php /** * Plugin Name: Test1234 */ function set_header_page(){ if( is_page('img') ){ header("Content-Type: image/jpg"); } } add_action('init', 'set_header_page'); function replace_image_content(){ if( is_page('img') ){ $image = plugin_dir_url(__FILE__).'1404-1.jpg'; readfile($image); } } add_action('wp_loaded', 'replace_image_content'); My problem is here: In both functions when I add `if( is_page('img') )` nothing happens. Without `if( is_page('img') )` I see my image in all pages. This shows me in my code everything depends on 'if(is_page( 'pagename' ) )'. How can I solve it? Note that I tried it by `if( $post->ID == 11 )`, too. Thank you in advance.
Both those hooks are too early to use `is_page()`. WordPress hasn't determined which page is being loaded yet, so it can't check the current page. Try `template_redirect` for both: /** * Plugin Name: Test1234 */ function replace_image_content(){ if ( is_page( 'img' ) ) { header( 'Content-Type: image/jpg' ); $image = plugin_dir_url(__FILE__) . '1404-1.jpg'; readfile( $image ); exit; } } add_action( 'template_redirect', 'replace_image_content' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, php, conditional tags" }
How to deregister a jquery version for a specific page? in the effort to fix an issue with my website, I needed to include a specific jQuery version through functions.php in my theme folder, but this leads to some compatibility problem with avada portfolios and other builder elements in some pages. How could I deregister a php script located in functions.php for 5 specific pages? If I delete the script, the portfolios and the other builder element come back to work. I am sorry but I have a poor knowledge of php... This below is the code added to functions.php: function add_jq_theme() { wp_enqueue_script( 'script-name', ' array(), '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'add_jq_theme' ); Thank you a lot for your help, Tommaso
Haven't tested it but this should work with small tweaks: function deregister_script_page_createit() { if( is_page( 42 ) ) { wp_deregister_script('jquery'); } } add_action( 'wp_enqueue_scripts', 'deregister_script_page_createit' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "jquery" }
I can't choose the custom taxonomy in my custom post type on Gutenberg I'm new here and in Wordpress Development. I have a custom post type that works with a custom taxonomy. In the classic editor, I can choose the category or add new if I want, but when I'm on Gutenberg the option doesn't show it. Thanks!!\[Custom Post Type]1 ![Custom Taxonomy](
As Gutenberg does nearly everything over REST-API, you will have to update your `register_taxonomy` to be shown in REST, as the default value for `show_in_rest` in `register_taxonomy` is `false`. So, you update your `$args` array in the `function custom_taxonomy` and add 'show_in_rest' => true and you should be fine. Happy Coding!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, custom taxonomy, block editor" }
How to get "Additional CSS Class" for ACF Gutenberg block I have registered a custom block with ACFs `acf_register_block`. I have set a `render_callback` to load a php template but would like to access any extra CSS classes which the user may have set in the admin. ![enter image description here]( Does WordPress provide a global like `$block` (similar to `$post`) or would I need to raise a question on the ACF support forums?
_Note that I don't have ACF PRO 5.8 which comes with the Block features, but I hope this answer helps._ If you look at the example here, you can retrieve the additional/custom CSS classes using `props.attributes.className`; i.e. the classes are saved as an _attribute_ named `className`. So with that in mind and based on `acf_register_block()` (which as of writing, it redirects to `acf_register_block_type()`), your `render_callback` function would receive a `$block` array (the block settings and attributes) as the first argument, and therefore you should be able to retrieve the additional CSS class(es) via `$block['className']` as shown here -- see the example under " _Registering a block with callback_ ".
stackexchange-wordpress
{ "answer_score": 8, "question_score": 6, "tags": "advanced custom fields, block editor" }
Auto Sorting List Alphabetically I'm trying to simply sort unordered lists when they have the following ID. The code works in a fiddle perfectly < but when i try to run it on my site it doesn't work or give me any errors. any ideas? function sortUL(selector) { var unsortedList = jQuery(selector); unsortedList.find('li').sort(function (a, b) { var upA = jQuery(a).text().toUpperCase(); var upB = jQuery(b).text().toUpperCase(); return (upA < upB) ? -1 : (upA > upB) ? 1 : 0; }).appendTo(selector); }; jQuery(document).ready(function () { sortUL("#sortList"); });
I was able to fix this by adjust my call slightly. instead of using jQuery(document).ready(function () { sortUL("#sortList"); }); I used jQuery(window).on("load", function() { sortUL("#sortList"); }); seems that either SHOULD have worked, but this worked for me nonetheless
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "jquery" }
how to loop through blog posts in php I need help looping through a simple php code. What I'm trying to achieve is the following: Start Loop Look for all the posts Add the author first & last name as a tag (links to /tag/firstName-lastName) Once clicked on the tag, take me to the author page with all their posts end loop I'm writing all this in single.php (I'm aware it only effects the page I open and doesn't effect all the blogs) My Code so far; <?php $post_id = get_the_ID(); $queried_post = get_post($post_id); $user_info = get_userdata($post->the_author); $first = $user_info->last_name; wp_set_post_tags( $post_id, $first, true ); ?>
$args = array( 'posts_per_page' => -1, 'post_type' => 'post', ); $the_query = new WP_Query( $args ); If you set the posts_per_page to -1 it will return all posts. Then you can loop through and do what you want with the single post. while ( $the_query->have_posts() ) { echo get_the_author_meta( );//I have NOT used this so you should look into it. } Theses links will help you understand the attributes on the_post. < <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "php, functions, tags" }
12 column grid layout I'm Looking for a way to create the grid as on the pictures. A 12 columns based layout with a simple way to add text, images, video etc. etc. Tried the **Bootstrap way** without success. I’m up for everything. Anyone? !enter image description here!enter image description here
Depending upon the css framework you can use grids, menus, lists to create your layout. You should not use grids for all of your elements. ### Example For the top `logo-menu`, you should use a `row` then inside the row `4col` for logo and `8col` for the menu. And then for creating the menu you will use `ul > li`. Adjust the spacing with paddings and margins. ### Basic Structure using Bootstrap 4 I have created a basic structure for your understanding. Please see this pen <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, templates" }
How to order WordPress Rest API data I am pulling in some data via the Rest API: The data loads fine, but the order is out of whack. I was expecting the first result to be ID '3116' as that's the first included id in my URL. How do I pull in data orderd by the URL id? ![enter image description here](
Add `orderby=include` to your GET request. See the docs here: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "rest api, order, json" }
get author_name from queried post All I'm trying to do is, get the author name of the current post and set it's name as a tag. I tried changing author_id to author_name but didn't really get anything back. wp_set_post_tags should return **'user_nicename' (nickname) instead of 'hey'**
The problem with your code lies in these three lines: $queried_post = get_post($post_id); $author_id = $queried_post->post_author; $first = $user_info->user_nicename; You correctly get authors ID, but then you try to get some field of `user_info` variable, which is not defined anywhere in your code. One way to fix it is to get user info (using `get_userdata`) before trying to access it: $author_id = $queried_post->post_author; $user_info = get_userdata( $author_id ); $first = $user_info->user_nicename; You can also use `get_the_author_meta` to obtain only the field you need: $author_id = $queried_post->post_author; $first = get_the_author_meta( 'user_nicename', $author_id );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, functions, loop" }
Show only one post on custom post type archive First of all thanks for your time! Im trying to show only the last element of my Custom post type (CPT) in the archive page, I tried it but it is showing the las Post, not the last CPT element, I dont know what im doing wrong but I think is this line: <?php $the_query = new WP_Query('showposts=1'); ?> here you can see my code. Would you be able to help me? Thanks in advance. <
Please thoroughly read the `WP_Query` docs, especially that part about post types. Means you need to pass the query the post type you want to query: $args = array( 'post_type' => 'my_custom_post_type', 'posts_per_page' => 1, ); $query = new WP_Query( $args ); * * * Even better it would be to simply override the existing query for that archive page by hooking into `pre_get_posts`. This will for example also adjust the pagination accordingly. Place this in your `functions.php`: /** * Override the main query on a custom post type archive. * * @param \WP_Query $wp_query */ function wpse_337567( WP_Query $wp_query ) { // Only check this on the main query. if ( $wp_query->is_main_query() && is_post_type_archive( 'my_custom_post_type' ) && !is_admin() ) { $query->set( 'posts_per_page', 1 ); } } add_action( 'pre_get_posts', 'wpse_337567' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, wp query" }
How to point menu to my homepage So basicially i have a long-long homepage where you can scroll down and find a services section, if you scroll down more you see important informations and etc. but i have a menu. I want to make the buttons on the menu to scroll me down to that section so for example if i click sercives it scrolls me down to services on my main page
You will need to add "Custom Links" to your menu to point to the homepage + the specific anchor on the page. For example, your `services` section may have the markup: <section id="services"> <h2>Services</h2> <p>Some text</p> </section> So your custom menu link would need to have a URL of `/#services`. You need the `/` slash at the start so that if someone clicks the menu from elsewhere in the site, it will first go to the homepage and then link to services, rather than trying to look for that ID on the current page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, widgets" }
How to (correctly) embed a Facebook video? I'm trying to embed a Facebook video in my site using the snippets generated by the Facebook Embedded videos page. Having done so, I add this function to a custom, site specific plugin so as to load the FB javascript API: add_action('wp_head', 'js_sdk_wp_head'); function js_sdk_wp_head(){ ?> <div id="fb-root"></div> <script async defer crossorigin="anonymous" src=" <?php } I then use the code editor to add the following to the page: <!-- wp:html /--> <div class="fb-video" data-href=" data-width="500" data-show-text="false"> </div> And when I do so, nothing happens, (apart from a blank line being inserted into the WP post). What am I doing wrong?
It worked correctly for me, however I used the wp_enqueue_scripts hook to add the JavaScript. function mytheme_enqueue_scripts() { wp_register_script('facebook-video', ' '', ''); wp_enqueue_script('facebook-video'); } add_action('wp_enqueue_scripts', 'mytheme_enqueue_scripts'); * Do you see any errors in your browser console or network tab? * Do you see the JS added to your page if you inspect?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "facebook, embed, videos" }
Can i Remove copyright text wordpress.org theme Hope you're doing great. i am using a theme wordpress.org that's shopstore ( < ) Can i remove the copyright text from the theme for my own usess? ![enter image description here]( Thanks
If the theme license allows, you can remove the footer text and link.
stackexchange-wordpress
{ "answer_score": -2, "question_score": -2, "tags": "themes, copyright" }
wordpress redirect error in xampp i had a wordpress website on xampp let's say in "localhost/listing" and it was working perfectly then i installed another copy of this website on "localhost/mylisting" now the problem is that when i type "localhost/listing/wp-admin" the site redirects itself to "localhost/mylisting/wp-admin" i dont know how to solve this problem. i tried making another directory and copying all contents on listing in it and the problem was same.
It's because your new copy of the site `localhost/mylisting` is still hooked into same database as `localhost/listing`. So to avoid that, you have to point your new installation to a different database. to do that, goto your phpmyadmin and export your current db, then create new empty db and import into it. then goto newly imported db's wp-options table. change siteURL and homepage URL to `localhost/mylisting` from `localhost/listing`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, xampp" }
wp-cli create post and media import I would like to create a post and insert a url as an image, right now I have this, it works but creates a gallery block, instead I would just like to create a simple image block . What is the correct syntax to post just an image in "post_content" ? wp post create --post_title="test" --post_content="[gallery ids='$(wp media import --porcelain)']" Thanks !
There is just `[gallery]` to display images BUT you can specify in which size the image(s) will be displayed. By default it's `size='thumbnail'`. Simply set it to `size='full'` to just get one full-sized image: $ wp post create --post_title="Foobar" --post_content="[gallery ids='$(wp media import --porcelain)' size='full']" More gallery shortcode options can be found on wordpress.com: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "wp cli" }
sidebar navigation problem with child pages not all display.? Corsetería is parant pages and 25 sub pages. but display only 17 pages ![enter image description here](
I don't know of a specific limit, but if you have a lot of pages I have either had to page through them - i.e. if you scroll down there may be (1 2 3 4 ->) pagination so you need to go to the next page - or else it may be easier to search for the specific page instead.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
How to include custom PHP file both in header and footer files I have created a custom file that both the header and the footer needs to render certain content. If I only do `include($_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/myTheme/myCustomFile.php');` in the `header.php` file it works as expected BUT only in the header. Likewise with the footer, If I only do `include($_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/myTheme/myCustomFile.php');` in the `footer.php` file it works as expected BUT only in the footer. The moment I have the include on both files, the page renders up until the footer starts and then stops rendering. How can I include this file so it can be accessed from anywhere in the theme? I also tried the other import methods in PHP - require, require_once, and include_once – same deal. Thank you in advance.
You wrote that you have a function definition in file that you include. I suspect that the reason is the function redeclaration error. You should move the function definition from `myCustomFile.php` to `functions.php`. You can also before each function definition in `myCustomFile.php` check whether there is already a function of the same name. if ( ! function_exists('you_function_name') ) { function you_function_name() { // ... } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, customization, include" }
How to exclude children categories of parent category I want to list only certain categories and exclude a particular parent and all its children. The reason is so that if a new child category is added, it won't show up by default. With wp_list_categories you also get an active class but with get_categories you don't. I would also like to somehow get an active class from it if possible. I tried this: $categories = get_categories(array( 'exclude' => array(40) )); But it still shows the children of category with ID 40. The below code hides all the children but is a pain to try and style it whereas if I run my own loop with get_categories I can style the output much easier. <?php wp_list_categories( array( 'orderby' => 'name', 'show_count' => false, 'exclude' => array( 40 ) ) ); ?>
$categories = get_categories( array( 'exclude_tree' => array(40) )); In both `get_categories()` and `wp_list_categories()` you can use the `exclude_tree` parameter instead of `exclude`. > * **exclude_tree** > (array|string) Array or comma/space-separated string of term ids to exclude along with all of their descendant terms. If _$include_ is non-empty, $exclude_tree is ignored. > Default empty array. >
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories" }
Extract url of every image in library? I'd like to make a PHP script to output the full-size URL of every image on the WordPress library. How can i make a foreach of all images in the site?
First you have to get all attachments. You can use `get_posts` function for this: $attachments = get_posts( array( 'post_type' => 'attachment', 'posts_per_page' => -1, ) ); Then you have to loop through them and get their urls using `wp_get_attachment_url`: foreach ( $attachments as $att ) { echo wp_get_attachment_url( $att->ID ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "media library" }
Query WooCommerce orders where meta data does not exist I'm trying to fetch all my WooCommerce orders where some additional metadata is equal to not empty. $orders = wc_get_orders( array( 'orderby' => 'date', 'order' => 'DESC', 'meta_query' => array( array( 'key' => 'var_rate', 'compare' => 'NOT EXISTS', ) ) )); So if the `var_rate` is empty or doesn't exist then do not return that record. At the moment all orders are returned using those arguments. Example of empty record - object(WC_Meta_Data)#2344 (2) { ["current_data":protected]=> array(3) { ["id"]=> int(6471) ["key"]=> string(15) "var_rate" ["value"]=> NULL } ["data":protected]=> array(3) { ["id"]=> int(6471) ["key"]=> string(15) "var_rate" ["value"]=> NULL } }
The `meta_query` argument _(that you can use in a`WP_Query`)_ is not enabled by default when using a `WC_Order_Query` through `wc_get_orders()` WooCommerce function. But for you can use the undocumented Custom Field Parameters _(just like in a`WP_Query`)_: * `meta_key` * `meta_value` * `meta_value_num` * `meta_compare` So in your case you can use the following instead: $orders = wc_get_orders( array( 'limit' => -1, // Query all orders 'orderby' => 'date', 'order' => 'DESC', 'meta_key' => 'var_rate', // The postmeta key field 'meta_compare' => 'NOT EXISTS', // The comparison argument )); This time it works nicely (Tested on WooCommerce 3.5.8 and 3.6.2).
stackexchange-wordpress
{ "answer_score": 14, "question_score": 5, "tags": "wp query, woocommerce offtopic, query, meta query" }
wp_insert_post with data from graph api inside a plugin I'm creating a plugin that creates a post in a CPT for every Facebook page post (using fb graph api). When should I fire the function that gets the data? using an action? Also if I understood the docs correctly, the `wp_insert_post` takes ID as an argument, which if doesn't exist, sets the newly created post id to that value?
There's no way to get notifications from Facebook for a new post. You have to check **by hand**. Just set a transient with the desired expire time for the data so you don't make a request on each reload, maybe check hourly for new data or every 30 mins, up to you. As for your second question, read the docs: < It automatically assigns an ID unless provided by you (which is auto-incremented by the system) but you still need to provide more things in the array, even if some are default, you might not want it like that.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, wp insert post" }
the correct order of manual install WP and SSL on server I am wundering what the correct order of these next things is when you want to manually install Wordpress and have SSL installed on your server and website. Is this the correct order to do that in? 1. Install SSL certificate for the site on the server 2. Manually install WordPress 3. Go to your website and do all the WP settings for SSL And what if you don't do it in this order?
There's not a correct order. Either way will work and results in a WordPress install that is secured with SSL. What makes sense in a situation, depends on the setup and workflow. If you can plan ahead, it's optimal to set up the SSL on your server first. Because doing so, you don't have to go back through WordPress, and change settings and the database. In short, you're saving yourself work and avoid potential sources of errors.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "installation, ssl" }
Proper way to use apply_filters() with class functions? I want to allow my user to override a function. It's a plugin. I believe that apply_filters() can be used for this. this can be overridden by add_filter(). I am confused about how to use it. Say if i have a class like this class Example{ public function hello(){ $title = the_title_attribute(); return $title; } } What change should I make to allow that $title to be modified? where to place the apply filter? Thanks
It depends on you where you want to call `apply_filters()`. It can be right when you defined the `$title`: $title = apply_filters( 'my_hook', the_title_attribute( 'echo=0' ) ); // set echo to false return $title; Or in the `return` call: $title = the_title_attribute( 'echo=0' ); // set echo to false return apply_filters( 'my_hook', $title ); Then one can hook to the filter like so: add_filter( 'my_hook', 'some_function' ); PS: As @birgire pointed, `the_title_attribute()` will echo output, unless the `echo` argument is set to `false`. So be sure to use the function with the proper parameters.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "plugin development, filters" }
Extra Text in Home URL When I try to access my main URL when just typing it in the address bar, the URL has this appended to the end: `?route=common%2Fhome` I've asked my host, WP Engine, and they don't have anything that would have caused this. I'm not sure what plugin would cause this, and I don't know where it's coming from. Any ideas? Thanks
Thanks for the above responses. I did not have opencart installed, and those were the only similar answers I could find. I ended up just installing the "Redirection" plugin which seemed to solve my problem. I added a simple redirect which redirected the target URL back to the homepage. I could have eventually found a way to fix it with .htaccess but I was not having much luck and this was a quick and effective solution.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, themes" }
Need to show post summary in sidebar I need to show a summary of each post in the sidebar. Is there any way to do this?
Easy way is use - `excerpt()` else you can also use `wp_trim_words( get_the_content(), 40, '...' );` In a `excerpt()`, You have to add content on excerpt in backend. While `wp_trim_words` will trim words from content. In sidebar case you have to add shortcode into functions.php file which uses in sidebar widget(if you are using widgets). function test_short(){ ob_start(); global $post; echo wp_trim_words( get_the_content($post->ID), 40, '...' ); return ob_get_clean(); } add_shortcode('test_short', 'test_short');
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "excerpt" }
Rewrite rules in multisite I've been trying to set up different rewrite rules on my multisite installation, but as of now, nothing is working. Even the simple `add_rewrite_rule('^welcome$', 'index.php?p=1', 'top');` isn't working. Is there anything to do when setting up rewrite rules using the Rewrite API that needs to be done that isn't explicitity defined in the codex? This problem led me to wonder: are rewrite rules written using the API supposed to be written in .htaccess or not? Thank you in advance. PS. If I'm duplicating, I am sorry, but I haven't been able to find a well written answer yet.
Found the answers: 1. There is nothing to do when using the Rewrite API that isn't written in the Codex. 2. Rules written using `add_rewrite_rule` are not added to `.htaccess`. WP adds them to its database under `rewrite_rules` in the `_options` table. It's important not to forget to: * Filter the rewritten permalinks; call the functions on the `post_type_link` hook and/or the `term_link` hook depending on the situation. * Remove default rules to avoid conflict and call the function/s on the `rewrite_rules_array` hook. * Flush and rewrite the rules using `flush_rewrite_rules();` on plugin activation and/or deactivation.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, url rewriting, rewrite rules" }
Delete option of a Plugin ![enter image description here]( I am getting below error while I click on `Delete` word under name of a plugin. ![enter image description here](
Wordpress will popup for FTP credentials if it does not have permission to write the files it needs to. Am assuming your WordPress website is hosted on Linux OS. And also if you connected to your server using SSH (i.e., putty, etc.). Please try to run the below command: sudo chown -R www-data:www-data /var/www/html **Alternate Method:** Try to define below the line in wp-config.php. But this could create security issues. define('FS_METHOD', 'direct');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development" }
Intercept page request and add value to it I am trying to intercept the GET request of a post and add a value to it. function foo($request) { $request['vid'] = wp_generate_uuid4(); return $request; } add_filter( 'request', 'foo' ); and hope that it would be available later with $_REQUEST['vid'] but no access so far any ideas?
WordPress doesn't add the `vid` to the `$_REQUEST` array. Instead, it's saved in a class property — see `WP::$query_vars` which is an array. And to access the value of items in that array, use `get_query_var()` like so in your case: $vid = get_query_var( 'vid' ); echo "vid value is $vid";
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, pages, request filter" }
Adding query string to multiple page urls in a Wordpress function I have a wordpress function that adds a query string `'nocfcache=1'` to a single page url. function nocfcache_query_string( $url, $id ) { if( 42 == $id ) { $url = add_query_arg( 'nocfcache', 1, $url ); } return $url; } add_filter( 'page_link', 'nocfcache_query_string', 10, 2 ); > **Issue:** How to use multiple page ids in the function so as to make sure they will all have the query string appended to the url. **What I have tried so far:** function nocfcache_query_string( $url, $id ) { $id = array (399, 523, 400, 634, 636, 638); if(in_array($post->ID, $id)) { $url = add_query_arg( 'nocfcache', true, get_permalink( $post->ID )); return $url; exit; } } add_filter( 'page_link', 'nocfcache_query_string', 10, 2 );
In your second code you use undefined `$post` variable. Probably you meant a global `$post`, but as the second parameter to the filter is passed the ID of the post for which the link is created, and this does not necessarily have to be the current post of the loop. Try this: add_filter( 'page_link', 'nocfcache_query_string', 10, 2 ); function nocfcache_query_string( $url, $id ) { $ids = array (399, 523, 400, 634, 636, 638); if( in_array($id, $ids) ) { $url = add_query_arg( 'nocfcache', 1, $url ); } return $url; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, urls" }
Advice on redirect to lock site from unauthorized users Looking for some advice on the below function. I have a web app type site built in WP. There is nothing on the site relevant to non-users, apart from the login form on the homepage. I've got some membership plugins that lock content, but as an added layer of security I was thinking of adding the following: function lock_non_users_to_front() { if( !is_user_logged_in() && !is_front_page() ) { wp_redirect( home_url() ); } } add_action( 'template_redirect', 'lock_non_users_to_front' ); Essentially, if anyone tries to access a url that isn't the homepage, and they aren't logged in, it'll just kick them back to the homepage. Any thoughts/improvements?
The comment by 'warm_tape' is correct. Use home_url(), then put a die() after the wp_redirect to ensure that the accessed page will 'die' and not interfere with your main page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "login, security, membership" }
Load template file without a post type Is there a way of loading a template file without having a post? I'm loading set of data via an API. Set up my index page but having a brain freeze with single template files as these posts are not in the WP registry/database. // Template files events-index.php events-single.php Events index: <?php $events = $api_data // Data retrieved from API if ( $upcoming_events->have_posts() ) : while ( $upcoming_events->have_posts() ) : $upcoming_events->the_post(); $custom_link = sanitize_title( get_the_title() ); $custom_link = rtrim($custom_link, '/'); $custom_link .= '?' . get_the_ID(); ?> <a href="<?php echo $custom_link; ?>"> // This link to a custom template file <?php } ?>
You could setup a custom rewrite rule using add_rewrite_rule and send these requests to a custom page. Your URL structure could be `/index-page/single-event-slug` The rule would point all of the single events to a separate page where you can then set your template `events-single.php`. Another option is to pass the events in as a query `/index-page?event=single-event-slug` or `/index-page?event=123`. You'd need to register this parameter with add_query_arg and then change your index template to use the event template via the template_include hook.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "templates, template hierarchy" }
Don't replace "|" with Empty String ("") when generating slugs from title I work for an architecture company and our project names mostly go like this: `house|something`, `bridge|somewhere`, `building|whatever`. Now, when I want to add a new project named like that, WordPress automatically converts it to `housesomething`, `bridgesomewhere` and puts that as the slug. I'd much prefer to keep some kind of separator, e.g. `house-something`, `bridge-somewhere` instead. So, how to make WordPress convert `|` to `-` and not `Empty String` (`""`)? I'm obviously tired of doing that manually all the time. It seems to me that it's very simple to do. It takes just a simple search and replace kind of thing if one knows where to look (in the WP core or wherever), but I haven't the slightest idea where to look, or what code to execute.
When WordPress inserts a post, it runs the title through a filter called `sanitize_title` to get the slug. By default there is a function called `santize_title_with_dashes` attached to this filter with priority 10. This function simply strips out the `|`. If it is surrounded by spaces those spaces will be converted to hyphens. So your task is to run a filter on the same hook before (say, priority 9) the default one and replace the `|` with `-` before it gets stripped away. Like this: add_filter( 'sanitize_title', function ( $title ) { return str_replace( '|', '-', $title ); }, 9 );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "filters, slug, title" }
REST API GET users when I do < I get: "code": "rest_user_cannot_view", "message": "Sorry, you are not allowed to list users.", "data": { "status": 401 } I am using Postman... please help
Read the docs: you need to add a Header named `X-WP-Nonce` to your requests to the API that require authentication, as you can see in the jQuery example. However the catch is getting that nonce in the first place. WordPress inject that token itself in the post editing screens. Type `wpApiSettings` in the developer console and you can get the nonce. You will need to send your `wordpress_logged_in` cookie too, that can be retrieved from the request headers in the Network tab of your browser dev tools. I'm sharing an example of how you put that headers in your Postman request: ![Postman example of Authenticated request to WordPress REST API]( However making it for an app that is not coupled to the WP backend itself can be cumbersome, that´s why there are other options, like Basic authentication that I´m not a big fan, and JWT authentication plugin. Both are linked in the documentation page that I linked.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "rest api, users" }
Running CRON on Server with WP Function How can I run a WP function on server cron? Background: I can't run it on wp_cron because the website is not published and will not be, so there will be no visitors. Tested cron job without wp function, it is working properly (like sending email every 30 minutes). //RemoteCoins() and LoadRemoteCoins() that include wp functions like wp_remote_get() function runthe_func() { //some code here } runthe_func(); I kept on getting errors like: "Fatal error: Call to undefined function wp_remote_get() in /home/path/path2/testing.php on line 91" How can I make it run with the server recognizing wp functions?
We need to include `wp-load.php` in order to bootstrap WordPress in our custom PHP code. So, the modified code would look something like this... include '/path/to/wp-load.php'; //RemoteCoins() and LoadRemoteCoins() that include wp functions like wp_remote_get() function runthe_func() { //some code here } runthe_func(); Now, if we run this file on server cron, it wouldn't throw errors. Oh, btw, similar questions have been asked and answered multiple times here in WPSE. For example, How to load WordPress on non WP page? .
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, server" }
Add slug to default post permalinks ONLY I've been browsing and reading and testing and can't seem to find a clean solution for my problem. A solution that doesn't affect all other post types, categories, custom taxonomies, etc. :( Is there anyway to modify the default post permastructure only programmatically by prepending an hardcoded slug to it? As of now, I've tried using `$wp_rewrite`, `add_permastruct`, `set_permalink_structure`... Thank you in advance for your help.
Literally found the answer 10 minutes after posting this question and spending a couple of hours on it before asking. Simply hook your function to `post_link`! public function __construct() { add_action('post_link', [$this, 'post_links'], 10, 2); } public function post_links($link, $post) { if ($post->post_type === 'post') { return site_url('slug/'. $post->post_name .'-'. $post->ID); } else { return $link; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, url rewriting, rewrite rules" }
Include future posts in tags and in search I am using something like this to query and display future or scheduled posts on my homepage: <?php query_posts('post_status=future&posts_per_page=10&order=ASC'); while ( have_posts() ) : the_post(); ?> //doing stuff <?php endwhile; ?> <?php wp_reset_query(); ?> This is working with great success. Although, these `scheduled` or `future` posts don't want to show up in a search or tag search. I would like to get the future posts searchable and the tags contained within them clickable. They (the tags) are currently clickable but throw an error on click. Takes me to the dreaded "Sorry No posts matched your criteria". So, how to enable WP search for and to include future posts and tags from future posts?
To achieve the intended result you will have to modify the query by adding the `future` value to the `post_status` parameter via the `pre_get_posts` filter hook. add_action( 'pre_get_posts', 'se338152_future_post_tag_and_search' ); function se338152_future_post_tag_and_search( $query ) { // apply changes only for search and tag archive if ( ! ( $query->is_main_query() && (is_tag() || is_search()) ) ) return; $status = $query->get('post_status'); if ( empty($status) ) $status = ['publish']; if ( !is_array($status) ) $status = (array)$status; $status[] = 'future'; $query->set('post_status', $status); } Conditional tags `is_search()` and `is_tax()` will allow you to modify the query only on the search page or the tag archive.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, search, tags, post status, scheduled posts" }
How safe is current_user_can()? I'm saving sensitive data via JSON ajax request, it is not sanitized, literally anything can be passed. I need to make sure that only admins with `edit_options` permission can save it. So I do: function received_ajax_request() { if ( !current_user_can('edit_options') ) { return; } save_to_database( $_POST['something']) ); } My question is how safe it is? Do I need to check for anything else besides `current_user_can`? For example, I saw some other plugins check also for nonce, but when rest API is used - nonces are generally not used.
`current_user_can` checks whether current user has a specific capability. And only that... **It won’t protect you from XSS attacks** \- so it would be a good idea to check some _nonces_ too - this way you can be certain that user wants to perform given action. _Let’s say there’s a link to delete a post. Of course you will check if user can delete posts. But what if a user is logged in and I make him click the link? He doesn’t have to know - it can be a shortened link or an image._ **It also won’t check if the current user is owner of given object.** _Let’s day I’m a customer in shop. Of course I can add comments to orders. But only for my orders._ So you should always check full access rights and not only roles and capabilities. **And of course it won’t make the action safe.** So you still have to sanitize, and escape, and so on...
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "security" }
Why doesn't media(max-width) work on h2 title? I am trying to style posts on my website, but when I try to change font size with media function in CSS I can't seem to change font size for h2. When I go to "inspect element" and navigate to "style" section I see that my styling for fon-size is crossed. What does that mean?![enter image description here](
It's being overwritten by the line at the top. You can see from the bit on the end of the filename that the your media query CSS is on line 133, but the CSS that's overwriting it is on line 182. Because they use the same selector (`.posts h2`) the last one will take precedence, according to the rules of specificity. You either need to remove the line on 182, or move your new CSS below it.
stackexchange-wordpress
{ "answer_score": -1, "question_score": -2, "tags": "css" }
How to create more templates to the same theme? Some theme contains more than one templates to chose in Page editor. ![enter image description here]( What is this called? How can I register more templates to my theme?
Create .php file with name like `template-blogs.php`, inside file write a `Template Name` in php comment, include header & footer. here is the sample of test template <?php /* * Template Name: Test Template */ get_header(); ?> <div class="content_area"> <!---Write Your PHP Code Here---> </div> <?php get_footer();
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "theme development" }
Mu-plugin causes entire site to crash I think i'm probably doing something daft here. Every time i try to include this as a mu-plugin it takes down the test site though. <?php if( is_plugin_active( '/public_html/wp-content/plugins/wordfence.php' ) ) { require_once('wp-load.php'); $to = ‘[email protected]’; $subject = ‘Wordfence is down’; $message = ‘Wordfence is not active’; $headers = array('Content-Type: text/html; charset=UTF-8'); wp_mail( $to, $subject, $message, $headers ); } Any ideas where i'm going wrong would be very much appreciated :)
`is_plugin_active` isn't available for mu-plugins to use. The codex says: > NOTE: defined in wp-admin/includes/plugin.php, so this is only available from within the admin pages, and any references to this function must be hooked to admin_init or a later action. If you want to use this function from within a template or a must-use plugin, you will need to manually require plugin.php, an example is below. And I think there must be better ways to solve this anyway: your code will try and send you an email for every non-static HTTP request to the site, and you probably meant `!is_plugin_active` or `is_plugin_inactive`, and in any case these accept relative paths to the plugin files not absolute paths.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "mu plugins" }
Category list with postcount Im total noob with wordpress, and would like to get some help with following problem. I Would like to make list of all categories and postcounts in category, something like this: category1(2), category2(4), category3(7) with hyperlinks to the category page. If someone could help me with this one with noob friendly answer i would appreciate it so much.
You just need to use wp_list_categories function with param show_count set to true < wp_list_categories( array( 'show_count' => true, 'title_li' => '<h2>' . __( 'Categories', 'textdomain' ) . '</h2>') );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, list" }
Download Themes From LocalHost WordPress Site I am wanting to download themes from my localhost install of Wordpress. My issue is that anytime I click download, I get a pop-up asking me for Connection Information. I tried to input localhost and my Wordpress username and password, but it will not download. What step have I missed here? **edit** And I am running localhost on a Ubuntu laptop with LAMP installed. **edit 2** This is an image of the request screen that I get, where I input localhost and my valid username and password ![Image1]( And this is an image of the error I receive when I try those reds ![Image 2](
Probably your local FTP service is not running. You can verify this by trying to connect to the local FTP server at the command prompt: ftp localserver and it will ask for your credentials. Also possible is that 'localserver' is not being resolved locally. You can check that with a command nslookup localserver And seeing if it gives you your servers' IP address. But this is not a WP Development question. Ask the googles/bings/ducks for help with enabling/starting your local FTP service.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes" }
Where in code to replace content before display of page? I wish to make a replacement in all pages of a WordPress installation, after the page content has been read from the database and before it is displayed on visitor screen (of course). _Where_ in the code do I insert the following statement that will make the replacement? $page = str_replace($target, $replace, $page); I run an updated WordPress using 2016 child theme. Among others I have a dedicated single.php and a functions.php Thank you
If you use native editor (and not some PageBuilder that stores data in its way), then you should be able to use `the_content` filter to do that: add_filter( 'the_content', 'my_the_content_filter' ); function my_the_content_filter( $content ) { $content = str_replace(...); return $content; } You might put some conditions in there, to check if you modify only pages or only on single page and so on...
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "customization" }
How can I delete the word `Category:` from page titles? If I installed a new WordPress with twentysixteen theme and went to uncategorized page, I will see at the title something like Category: Uncategorized how can I remove the **category:** word from pages titles?
For achieve this title you need to extend get_the_archive_title . here is how or check the official doc function wpse64458_get_the_archive_title($title){ if ( is_category() ) { $title = single_cat_title( '', false ); } elseif ( is_tag() ) { $title = single_tag_title( '', false ); } return $title; } add_filter( 'get_the_archive_title', 'wpse64458_get_the_archive_title');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, css, templates" }
How to remove WooCommerce Plugin some specific features I need to know how I can remove some features in WooCommerce Plugin, I mean Add to Cart Button, My Account page, Cart page, Checkout Options, etc? I only need to show the Shop page in my project and all other stuff needs to be hidden in the theme. How I can archive this?
**Disable Membership:** Uncheck box under 'Wordpress - Settings - General ~ Membership'. Uncheck boxes under 'WooCommerce - Settings - Accounts & Privacy'. **Add the following code to your`functions.php` file to remove the 'Add to Cart' button:** remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' ); remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 ); **To redirect away from the cart or checkout page:** Select a page for the Cart and Checkout pages under 'WooCommerce - Settings - Advanced ~ Page Setup'.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
How to display quote format by preg_match function? I have defined `quote` post format for the theme: // Add post-formats for theme add_theme_support( 'post-formats', array( 'quote', ) ); After it, I want to display quote from the content. For that, I want to use `preg_match_all` function to search for `<blockquote>Hello World.</blockquote>` if( $format == 'quote' ) { $content = apply_filters( 'the_content', get_the_content() ); preg_match( '/<blockquote.*?>/', $content, $matches ); } But it is not working. I want to find blockquote tag and display content inside this tag.
Meta-character `.` match any character except newline. If you have new lines inside quote, try this: preg_match_all( '#<blockquote.*?>([\s\S]*?)</blockquote>#', $content, $matches ); > **Escape sequences:** > > `\s` \- any whitespace character > `\S` \- any character that is not a whitespace character
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post formats" }
Is it possible to remove editor from a custom product type? I want to remove the editor and set up only the excerpt to a custom product type (WooCommerce) in my theme, is this possible? This is how i add my custom product type to the WooCommerce product type selector <?php defined('ABSPATH') || exit; class Custom_Product_Type(){ public function __construct() { add_filter('product_type_selector', array($this, 'product_type_selector')); } function product_type_selector($types) { $types['custom_product_type'] = 'Custom product type'; return $types; } } new Custom_Product_Type();
I've figured how to hide the editor only when the product type is selected because if i remove the support: 1) The product type is the hidden and then change the product type to another the editor doesn't appear back 2) The product type is not the hidden and then change the product type to hidden the editor dont dissappear function admin_footer() { if ( 'product' !== get_post_type() ) : return; endif; ?><script type='text/javascript'> jQuery( document ).ready( function() { $("#postdivrich").addClass('hide_if_custom_product_type'); $("#product-type").trigger('change'); }); </script><?php } add_action( 'admin_footer', array($this, 'admin_footer')); This way, every time it selects or deselects the product type, it will hide or show using WooCommerce methods
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, editor" }
How to create a page with a form programmatically in WP? I made some research and found a way how to create custom pages using content (post) types. However, I do not want to create a new post type, I just want to create a page having a certain URL (`/form`) with a form on it. I was not able to find how to do it without custom post types. Can someone show me the correct direction? Thanks a lot.
You can use **wp_insert_post()** function with ' **after_theme_setup** ' action hook to programatically create pages. Here is a short example, add_action( 'after_setup_theme', 'create_form_page' ); function create_form_page(){ $title = 'Form'; $slug = 'form'; $page_content = ''; // your page content here $post_type = 'page'; $page_args = array( 'post_type' => $post_type, 'post_title' => $title, 'post_content' => $page_content, 'post_status' => 'publish', 'post_author' => 1, 'post_slug' => $slug ); if(post_exists($title) === 0){ $page_id = wp_insert_post($page_args); } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development" }
I'm using rtMedia and Youzer. Can Shortcodes be used to display a video gallery? Please be patient if This doesn't make sense. I'm using Youzer which adds advanced social networking features to BuddyPress. I also added rtmedia to allow users to upload videos. How do I use the shortcodes to show a video album of whatever users page I click on? Example - Bob visits the site to look up Bill, once he is on bills profile I would like the videos that Bill uploaded to appear under a new tab. Could I create my own string to get the user id or do I have to manually add the album to each new member?![enter image description here]( That image is the tab I want to tell Wordpress to display the users' videos.
I'm not too familiar with BuddyPress and a total stranger to rtmedia. But out of curiosity I had a brief look at their documentations. Perhaps you could add a custom shortcode to your `functions.php`, which gets the current profile ID and uses it with the rtmedia gallery shortcode to display videos from the profile. Something along these lines, function my_profile_videos_shortocde( $atts ) { $profile_id = bp_displayed_user_id(); // not sure if this is the right function if ( ! $profile_id ) { return; } return do_shortode( '[rtmedia_gallery media_type="video" media_author="' . $profile_id . '"]' ); // add parameters to the shortcode as needed } add_shortcode( 'profile_videos', 'my_profile_videos_shortocde' ); You should then be able to use `[profile_videos]` on the Tab content field.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode" }
How to 301 redirect from url with post id to permalink with post name (slug)? my posts have urls of two different types: one with post id and other with post slug: /post/789 /post/my-post-slug i'm doing this using: add_rewrite_rule( 'post/(\d+)/?', 'index.php?p=$matches[1]', 'top' ); and setting up permalinks using %post_name%. both `/post/123` and `/post/my-post-slug` open the same html page. is it possible to make wordpress return the 301 redirect to `/post/my-post-slug` when accessing `/post/123`?
yes, it is possible. add a `template_redirect` hook handler: add_filter('template_redirect', 'redirect_post_to_canonical_url'); function redirect_post_to_canonical_url(): void { if (!is_single()) { // do not redirect nothing else except posts return; } $canonicalLocation = get_permalink(); $requestUri = $_SERVER['REQUEST_URI']; $currentLocation = home_url('/') . substr($requestUri, 1); if ($currentLocation === $canonicalLocation) { // prevent from infinite redirect loop return; } wp_redirect($canonicalLocation, 301); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories, permalinks, redirect, slug" }
Where can I save plugin data? I created a plugin which has a shortcode that displays a button in a form. I would like to track the button clicks with an onclick() script and save the amount of clicks to a meta field. I am just not sure where to save this data. I don't want this data to be saved to a posts meta field, as this isn't post specific. Should such data be saved to the wp-options table? What's the best way to do this? Thanks!
If it's not post specific then it should be saved as an option in `wp_options` with `add_option()` or `update_option()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development" }
Add admin page to the top of the admin panel I want to add a page to the admin panel of wordpress. If I want to link it into the menu on the left, I can use add_menu_page. But I want to add it to the top of the admin panel. How can I do this?
Try this code: add_action('admin_bar_menu', 'wp_toolbar_custom_menu', 100); function wp_toolbar_custom_menu($admin_bar){ $admin_bar->add_menu( array( 'id' => 'menu-item', 'title' => 'Menu Item', 'href' => '#', 'meta' => array( 'title' => __('Menu Item'), ), )); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin" }
Wordpress check box unchecked on null value ternary operator [plugin development] I'm trying to use wordpress plugin development, without a checked checkbox getting an error. <?php global $options; ?> <input name="settings[enable]" type="checkbox" id="" value="1" <?php checked( $options['enable'], 1 ); ?> />
`checked()` only checks if the passed first and second parameters match. It doesn't do any array key checking, so you need to do it yourself before using the function to avoid errors. <?php global $options; $enabled = ( isset( $options['enable'] ) ) ? $options['enable']: ''; ?> <input name="settings['enable']" type="checkbox" id="" value="1" <?php checked( $enabled, 1 ); ?>>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, plugin development" }
How to create a post template with two sidebars I'm looking for a way to have a post template that has two sidebars, one on the right side, the other on the left side, with always the same content on each one of them. I defined that left sidebar as "sidebaraleatorio", and right sidebar as "sidebarrecomenda", and created for each one of them a .php file, then I registered them in my functions.php of child theme. After that, I created a template trying to call the two sidebars php files: `<?php get_sidebaraleatorio(); ?> <?php get_sidebarrecomenda(); ?>` But when I tested, there were several bugs, so I guess something is wrong in my way of doing it... Shouldn't I create different sidebar php files? If the problem is not that, I can include the other code I'm using on these files Thanks a lot for any help
If you add `sidebar-sidebaraleatorio.php` and `sidebar-sidebarrecomenda.php` sidebar templates to your (child) theme directory, you can then call them with `get_sidebar()` function. Like so `get_sidebar('sidebaraleatorio);` and `get_sidebar('sidebarrecomenda);`. You can read more about sidebars from the Developer Handbook > Sidebars.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "templates, sidebar" }
Plugin for an interactive image? I'd like to make an interactive image like this one, so when a visitor hovers over that circle, some text dialog pops up. Does anybody know any WordPress plugin that could do that or atleast something close to that? Thanks! ![enter image description here](
Image Hotspot by DevVN and Interactive Maps might have what you're looking for!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, images" }
Create Add New button How to create Add New button in WP_List_Table Class ? ![enter image description here](
Regarding the "Add new" part, here's an example that I assume will help you. I haven't used WP_List_Table so unfortunately I can't comment much on that. But based on the class reference I'd guess you'd need to use the `get_columns()` method. Using the code below you should be able to generate an url that you can use as `href` for an `a` tag. You can then render the `a` wherever you need it to be. admin_url('post-new.php?post_type={post_type}'); When clicked, the genereated url should take the user to "Add new {post_type}" editing view. Example copied from, How to get new post URL?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp list table" }
load CSS only for administrators on backend I am trying to load a custom styles sheet but only for administrators My code works fine by itself: function admin_style() { wp_enqueue_style('admin-styles', get_template_directory_uri().'/admin.css'); } add_action('admin_enqueue_scripts', 'admin_style'); However, when I try to create a conditional based on the role, it can not get it to fire: function role_exists( $role ) { if( ! empty( $role ) ) { return $GLOBALS['wp_roles']->administrator( $role ); } return false; } function admin_style() { wp_enqueue_style('admin-styles', get_template_directory_uri().'/admin.css'); } if( role_exists( 'administrator' ) ) { return add_action('admin_enqueue_scripts', 'admin_style'); }
This is what I use, tested and works... function wpse_admin_styles(){ $user = wp_get_current_user(); if( !empty($user) && count(array_intersect(["administrator"], (array) $user->roles ))) { wp_enqueue_style( 'admin_css', get_stylesheet_directory_uri() . '/css/admin-styles.css', array(), filemtime( get_stylesheet_directory() . '/css/admin-styles.css') ); } } add_action('admin_enqueue_scripts', 'wpse_admin_styles');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, user roles" }
How to remove the sub-category from Woocommerce product URL In permalinks settings the 'Shop Base with Category' `/shop/%product_cat%/` permalink setting puts all the hierarchical categories in the url, for example: http:// mystore.com/shop/ **parent-category** /child-category/ **product** I want to remove anything between parent-category and product so my urls look like: http:// mystore.com/shop/ **parent-category/product** I am pretty sure that setting up urls like this does not cause problems, because I can manually type the shortened url into an address bar and it goes to the same place as the longer one. Thanks.
It's actually quite simple. Use the `woocommerce_product_post_type_link_parent_category_only` filter: add_filter( 'woocommerce_product_post_type_link_parent_category_only', '__return_true' ); Tried and tested working. PS: The code would go into the theme functions file and `__return_true()` is a WordPress function.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "woocommerce offtopic, permalinks" }
Array ids post to function have_post I get as result of a main sql an array of post IDs, now what I need that Array of ids post to obtain the information and be presented in the following way: <?php $ids = [1,2,3,4,5]; // Here is some execution or process // then I need to present the post as a normal loop if ( have_posts() ) : while ( have_posts() ) : the_post(); echo get_the_title(); endwhile; endif; wp_reset_query(); How can I run the ids and then display it in a loop?
If I understand it properly, You can use the `post__in` parameter to query for specific posts where the post ID is in that parameter: $ids = [ 1, 2, 3, 4, 5 ]; $query = new WP_Query( array( 'post__in' => $ids, // ... other args, if any. ) ); // Then loop through the posts. if ( $query->have_posts() ) { while ( $query->have_posts() ) : $query->the_post(); the_title(); // ... your code here. endwhile; wp_reset_postdata(); } Alternatively, use `foreach` with `setup_postdata()` without having to do the `new WP_Query()`: global $post; $ids = [ 1, 2, 3, 4, 5 ]; foreach ( $ids as $id ) { $post = get_post( $id ); setup_postdata( $post ); the_title(); // ... your code here. } wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "loop, array" }
Hide admin bar on all pages except homepage I am trying to hide WordPress admin bar from all pages except the home page. I added the following CODE in the theme's `functions.php` file, but it hides the admin bar on all pages: if ( ! is_single() ) { add_filter( 'show_admin_bar', '__return_false' ); } I want it to appear only on the homepage and to be hidden everywhere else.
You should use conditional tag inside function hooked to `show_admin_bar` filter. add_filter( 'show_admin_bar', 'show_adminbar_on_homepage_only', 20 ); function show_adminbar_on_homepage_only() { return is_user_logged_in() && is_front_page(); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "admin bar" }
Multiple plugins linked to same settings page I have **several custom plugins** that do very different things but I use on each of them (or almost) the Jenkins and Mantis Rest APIs. For the moment, the API settings (as URL or tokens) are hard coded in the plugin codes, but I would like to centralize this information on a **settings page**. I found a good tutorial to add a plugin settings page but it would require a settings page for each plugin when the information would be the same... Would anyone have a solution?
Perhaps you could create a dedicated settings plugin, which you would use to add single settings page and register separate section and setting for each token/url/etc. As the settings are saved to the database you can get them with `get_option( 'setting_name' )` in any other plugin whenever you need.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "settings api" }
Internal forward link with add_rewrite_rule I want to forward a link to another link but internally. I've set up the wordpress to show post links like this - < which only throws 404 error. However If you visit < (location instead of medical), it works. So I want to forward any url containing `medical` to `location`. Thanks in advance for your help
The code below should work for you as long as: 1. Your CPT slug is `location`. 2. You don't have a custom `query_var` registered for your CPT `location`. You probably don't have. Refer to < for more information, it's very usefull, btw. And I'm assuming the string `nyc` is the slug of your single custom post. function rewrite_medical_url() { add_rewrite_rule( '^medical/[^/]+/([^/]+)/?', 'index.php?location=$matches[1]', 'top' ); } add_action( 'init', 'rewrite_medical_url' ); Put the code in your **functions.php** file. In order for the rewrite rule start taking effect you should visit **Settings** > **Permalinks** to flush your permalinks.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks" }
How to stop EU users from accessing my website? I have a website using self-hosted WordPress. I am pretty confused with the GDPR law by EU. So, I want to block EU users from accessing my websites. How i can do that? Please help!
I would use .htaccess. To do so you can: 1. Login via FTP, sFTP or SSH to your WordPress root installation. Find and open .htaccess file. 2. Visit this website and choose the countries you want to block. It will generate a list of IPs ready to copy and paste on your .htaccess. 3. Paste the list. If you don't know how to access search for a plugin in the repository like < The proper way is to take the time to read about cookies and privacy and implement it. Some basics are: 1. Ensure you block cookies until they are accepted. 2. Ensure you ask for permission in your forms to process the data. 3. Ensure you don't keep european users data outside EU servers.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "content restriction" }
Why should I escape translatable strings? and how shall i do that? Is it really need to escape translatable strings? ![enter image description here](
> Is it really need to escape translatable strings? Yes. If a string is translatable then that means its value can be changed from an external source. This means it's not safe. > and how shall i do that? See the documentation on how to escape with WordPress. When it comes to translatable strings, there are two main functions to use: `esc_html__()`, `esc_attr__()`, `esc_html_e()`, and `esc_attr_e()`. These functions are essentially just `esc_html()` and `esc_attr()` combined with the `__()` or `_e()` translation functions. The thing you need to be aware of is that escaping should happen as late as possible. Ideally the last thing that happens before output. In your screenshot you appear to be just defining strings for later use. In that case you wouldn't use `esc_html__()` at this point. Instead you'd just use `__()` and then use `esc_html()` whenever you actually output the string. Here's a couple of good resources on the topic: * < * <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "translation, escaping" }