INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Show metabox only for homepage I'll try to add metabox to homepage with setting fields, but something went wrong, help me please. The metabox don't appear in page editor, when i remove `if statement` it shows on all pages. add_action('add_meta_boxes', 'metabox_homepage_videos'); function metabox_homepage_videos($post) { if (is_front_page()): add_meta_box('metabox-homepage-videos', __("Homepage Videos"), 'metabox_homepage_videos_callback', 'page', 'side', 'low'); endif; }
`is_front_page()` is only for use on the front-end to tell if the 'main query' is for the front page. In a back end context you need to check if the current post ID (which is in the `$post` passed to your callback function) is the same ID that's set to be the front page. So the if statement would look like this: if ( $post->ID == get_option( 'page_on_front' ) ) : endif;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, metabox" }
WooCommerce Shop Page Not Found 404 I added WooCommerce to my WordPress site and the Shop page is giving a 404. This seems weird because the page is listed in my "Pages" area like this "Shop - Shop Page", but when I try to preview it is not found. I tried uninstalling and reinstalling WooCommerce and also deleted the Shop page and recreated one using the WooCommerce tools. I also fiddled with the permalinks page (screenshot below), but no luck. --Also the Cart Page and other woocommerce pages are not working. Thanks for any guidance you can give on this. ![enter image description here](
What you've done here is changing slug for products. For example : < as explained in WP, but not your Woocommerce home. Change the base to base default in permalinks settings. Then read after :) If you want to change your "Shop Homepage" go to That's the good way to do it !
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "woocommerce offtopic" }
Redirect users on specific post category or category page im trying to redirect users on specific categry with this hook: // Show app-data posts only to app users function user_redirect() { if ( is_category( 'app-data' ) ) { $url = site_url(); wp_redirect( $url ); exit(); } } add_action( 'the_post', 'user_redirect' ); But its not working and i dont know why. it redirect if the user if browsing the category. i want to redirect if the user is browsing the category or a post of that category
## Why it's not working? There is one major problem with your code... You can't redirect after any html content was already sent... Such redirect will be ignored... So why is your code incorrect? Because of `the_post` hook. This hook is fired up when the object of post is set up. So usually it's in the loop, which is much too late to do redirects... ## So how to fix your code? Use another hook. Here is the list of available hooks fired up during typical request. One of the best hooks for doing redirects (and commonly used for that) is `template_redirect`. As you can see it's fired up just before getting header, so everything is already set up. function redirect_not_app_users_if_app_data_category() { if ( (is_category( 'app-data' ) || in_category('app-data'))&& ! is_user_logged_in() ) { wp_redirect( home_url() ); die; } } add_action( 'template_redirect', 'redirect_not_app_users_if_app_data_category');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "hooks, redirect, actions, wp redirect" }
Show Featured Post Only On The Homepage Before the content/loop I have this featured post on the top. The problem is that it shows up in the other pages besides the home. I tried several solutions, but I am unable to hide it. Any help would be great. <?php $args = array( 'posts_per_page' => 1, 'meta_key' => 'meta-checkbox', 'meta_value' => 'yes' ); $featured = new WP_Query($args); if ($featured->have_posts()): while($featured->have_posts()): $featured->the_post(); ?> <h3><a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a></h3> <?php if (has_post_thumbnail()) : ?> <figure> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> </figure> <p><?php the_excerpt();?></p> <?php endif; endwhile; else: endif; ?>
With the help of Castiblanco I solved this! <?php if( !is_paged() ) { // Your code! }; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "customization, homepage, featured post" }
Display post metadata: "title, category, author, date" with shortcode How to create shortcodes to the standard post-metadata "title, author, category and date" in order to display it in post-content? E.g. post-content including shorcodes: Lorem ipsum dolor **[post_title]** sit amet, **[post_category]** consectetur adipiscing elit **[post_author]**.. Followed this guide and it worked for the title but can't make it work on the other metadata: category, author name and date. The code is the following: function myshortcode_title( ){ return get_the_title(); } add_shortcode( 'page_title', 'myshortcode_title' );
If you are outside the loop then you can use to get them by post id, you can play around with these snippet: shortcode for author's name: function author_name_shortcode(){ global $post; $post_id = $post->ID; $author = get_the_author($post_id); return $author; } add_shortcode('post_author','author_name_shortcode'); shortcode for categories name: function category_name_shortcode(){ global $post; $post_id = $post->ID; $catName = ""; foreach((get_the_category($post_id)) as $category){ $catName .= $category->name . " ,"; } return $catName; } add_shortcode('post_category','category_name_shortcode');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "shortcode, post meta" }
Hiding products with a specific tag from WooCommerce main shop page I want to hide products with a specific tag from WooCommerce main shop page but not from this same tag dedicated page. To be clearer, see https//www.popito.fr. I would like to remove products tagged "pré-commande" from here: < but not from here: < Is it doable? If yes, how? Thanks a lot!
You can paste the following snippet in your child theme's functions.php function exclude_specific_tag( $q ) { if (is_shop()){ $tax_query = (array) $q->get( 'tax_query' ); $tax_query[] = array( 'taxonomy' => 'product_tag', 'field' => 'slug', 'terms' => array( 'pré-commande' ), // write the tag name to remove in between the '' 'operator' => 'NOT IN' ); $q->set( 'tax_query', $tax_query ); } } add_action( 'woocommerce_product_query', 'exclude_specific_tag' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic" }
Way to redirect all Product Sub Category to its Main category Page? How to redirect all Product Sub Categories to its Main category Page respectively. This is a question to find a way.
You will have to use JS for the redirection since header is already sent before we can check the category, following snippet would do the work: add_action('woocommerce_before_main_content','redirect_to_top_level_parent',1); function redirect_to_top_level_parent(){ if (is_product_category()){ $cate = get_queried_object(); $cateID = $cate->term_id; $parentcats = get_ancestors($cateID, 'product_cat'); $count = count($parentcats); if ($count > 0){ $count = $count-1; $link = get_term_link( $parentcats[$count], 'product_cat' ); $redirect = "<script>"; $redirect .= "window.location.replace('{$link}');"; $redirect .= "</script>"; echo $redirect; } } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, woocommerce offtopic" }
Create new multisite from existing and keep domain? Apologies if this is too basic a question, but I have an existing multisite installation and would like to move one of the subdirectory websites "out" and create a new multisite with it due to size and technical considerations. The catch is I'd like to keep the current domain and not use a subdomain. So lets say my current multisite is mapped to example.com and has directories: * example.com/apples * example.com/bananas * example.com/cherries Is is possible to take create a new folder in public_html for 'bananas' and make example.com/bananas a new multisite installation? Or will this not work because there's already an existing installation at the root and in the database, and its DNS is mapped to _example.com_? Thanks!
Yes, you can set up multiple installs. You do need to be careful that you don't ever create anything in the "parent" multisite (at `example.com`) that has the same slug as the folder you place the "child" multisite (at `example.com/bananas`) - so in the bananas example, never create a Post, Page, Category, Tag, etc. with the slug `bananas` in the parent site. You could also consider a Multi-Network - which is basically a MultiSite of MultiSites. Most plugins aren't compatible with these, so if you rely on a lot of plugins that may not be the way you want to go, but it can help ensure you don't have conflicting slugs that cause the "Do I show the actual folder, or the content at this slug?" conundrum.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, domain" }
New custom PHP pages are getting 404s When I create new php pages and try to visit them I am receiving a 404. For example, I have created the file `page-tacos.php` (stored in my child theme directory) but when I try to visit the URL at `localhost:8888/tacos` I am getting a 404. I have added several custom pages in the past and whenever I was having this issue I would follow the advice from this question and it would fix my problem. However, now flushing my rewrite rules is not fixing it. I have tried renaming my file to not include the 'page-' prefix, resaving my permalinks, and running `flush_rewrite_rules( false );` to no avail. My .htaccess file has not changed. Does anyone have any other suggestions?
Per the Template Hierarchy, creating the file `page-tacos.php` in your active theme will create the template that would be used to view the page with slug `tacos`, but it _doesn't create the page_. You also need to add the page in WordPress's backend.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks" }
Do I have to have a nonce for a custom comment field? im working on my comment section and I have added a custom field <input type="hidden" name="be_user_star_rating" id="be_user_star_rating" value="" /> Its value is beign set by Javascript. Validating it with something like this: add_action( 'comment_post', 'be_comment_rating_insert_comment', 10, 1 ); function be_comment_rating_insert_comment( $comment_id ) { if( isset( $_POST['be_user_star_rating'] ) && $_POST['be_user_star_rating'] > 0 && $_POST['be_user_star_rating'] <= 5 && is_numeric($_POST['be_user_star_rating']) ) { $val = (int) $_POST['be_user_star_rating']; update_comment_meta( $comment_id, 'be_user_star_rating', esc_attr( $val ) ); } } Since this is hooked into `comment_post`, do I have to worry about checking custom nonces - beyond my validation? Or will Worpdress take care of it?
A WordPress Nonce, while not a _true_ nonce, functions similarly in that it exists to secure a form or page from unauthorized access and abuse. By default, the WordPress Comment Form only displays a nonce field if the current user has the `unfiltered_html` capability. So, if the form is implemented with standard procedures, all you have to do is validate your own input, and you don't have to mess with nonces. From **comment-template.php** : /** * Display form token for unfiltered comments. * * Will only display nonce token if the current user has permissions for * unfiltered html. Won't display the token for other users. * * The function was backported to 2.0.10 and was added to versions 2.1.3 and * above. Does not exist in versions prior to 2.0.10 in the 2.0 branch and in * the 2.1 branch, prior to 2.1.3. Technically added in 2.2.0. * * Backported to 2.0.10. * * @since 2.1.3 */
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "comments, validation" }
How to add and SQL query of posts only published I have a notification on a menu item and need to change the number on the notification. I'm missing an argument of show only "Published" posts. Right now it's pulling in everything in draft too. Here's what I have now. Need to add the Published part to it. $prepare_string = "SELECT DISTINCT ID FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id ) LEFT JOIN $wpdb->postmeta AS mt1 ON ( $wpdb->posts.ID = mt1.post_id ) WHERE ( ( $wpdb->postmeta.meta_key = 'event_date' AND $wpdb->postmeta.meta_value >= %d ) OR ( ( $wpdb->postmeta.meta_key = 'event_date' AND $wpdb->postmeta.meta_value < %d ) AND ( mt1.meta_key = 'end_date' AND mt1.meta_value >= %d ) ) OR ( $wpdb->postmeta.meta_key = 'event_date' AND $wpdb->postmeta.meta_value = '' ) )";
You should be able to get away with just adding `AND $wpdb->posts.post_status = 'publish'` at the end. $prepare_string = " SELECT DISTINCT ID FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id ) LEFT JOIN $wpdb->postmeta AS mt1 ON ( $wpdb->posts.ID = mt1.post_id ) WHERE ( ( $wpdb->postmeta.meta_key = 'event_date' AND $wpdb->postmeta.meta_value >= %d ) OR ( ( $wpdb->postmeta.meta_key = 'event_date' AND $wpdb->postmeta.meta_value < %d ) AND ( mt1.meta_key = 'end_date' AND mt1.meta_value >= %d ) ) OR ( $wpdb->postmeta.meta_key = 'event_date' AND $wpdb->postmeta.meta_value = '' ) ) AND $wpdb->posts.post_status = 'publish' ";
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "mysql" }
htaccess redirect invoice.php to /client/invoice.php I am looking at installing Wordpress into my WHMCS website and I would like to make it so any old invoices or support tickets go to the new subfolder. Current links will look like this What should I put in `.htaccess` so anyone who goes to those links will be redirected to:
So, you just want to inject a `/client` subdirectory, for specific URLs, from the document root. You can do this using mod_rewrite, at the top of your `.htaccess` file ( _before_ the WordPress front-controller). For example: RewriteRule ^view(invoice|ticket)\.php$ /client/$0 [R=302,L] This will redirect either `/viewinvoice.php` or `/viewticket.php` to `/client/viewinvoice.php` and `/client/viewticket.php` respectively. The query string is passed through to the target unaltered. The `$0` backreference in the _substitution_ refers to the URL-path that matches the entire `RewriteRule` _pattern_. Note that this is currently a _temporary_ (302) redirect. Change the 302 to 301 if this is intended to be permanent, but only once you have confirmed it works OK (to avoid caching issues). Make sure your browser cache is cleared before testing.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "redirect, htaccess" }
Login page so wide Please i need help, i have been battling with this for hours now and i still cant get it right, please help me, the login page is so wide i cant get it to be normal. This is the user login page on my wordpress and this is the screenshot attached below, please help me anyone if you can ![wordpress user login error](
I think that you would need to understand how to ask question in here. Why login page is wide, these would be for some below reasons. * When you install wordpress plugins, it changed default wordpress style * You could solve these problems by making input fields responsive using css * Don't forget to read documentation of plugins that you used in your website
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "woocommerce offtopic, login, account" }
How to make a wordpress blog in two different languages? I have a news blog and i am posting news in English. Now I want to make another section where I want to display news only in Urdu language. I also want to keep both languages separate that when I am on English news, no Urdu news should be shown anywhere and when I click on Urdu news page, no post from English section should be shown. Should I use two different wordpress installations on same domain to achieve this thing ? For example, my website is www.mywebsite.com and have another wordpress installation www.mywebsite.com/urdu-news/ and I make a custom link in www.mywebsite.com for www.mywebsite.com/urdu-news/. If yes, what about google ads I am gonna show on my pages. Will these ads are considered as in one website or I need to register www.mywebsite.com/urdu-news/ with google adsense separately ? Regards.
You shouldn't create two wordpress installation because it is wasting resources. I think you should use wordpress translation plugins. Just google it. As for me, I use polylang. You could use **News** with category based or you could also create custom template and make query for that.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multi language" }
Uploading dwg files to wordpress I'm trying to upload files with dwg extension to media but when I do that I get an error telling me that uploading files with this extension is not allowed. I tried to upload them via ftp but I cannot see them in my panel afterwards. I've looked for a solution online and tried adding this to my `functions.php`: function custom_upload_mimes ( $existing_mimes=array() ) { $existing_mimes[‘dwg’] = ‘application/dwg’; return $existing_mimes; } add_filter(‘upload_mimes’,’custom_upload_mimes’); But it didn't change anything. Is there any other way to bypass this file restriction?
Your code should work just fine. The only problem in there is that you’ve set incorrect mime type, I guess... It should be `image/vnd.dwg`. So this one should work: function custom_upload_mimes ( $existing_mimes=array() ) { $existing_mimes['dwg'] = 'image/vnd.dwg'; return $existing_mimes; } add_filter('upload_mimes', 'custom_upload_mimes');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "uploads, media" }
Trying to get property of non-object in Wordpress Breadcrumbs I have this error in my custom breadcrumbs : Notice: Trying to get property of non-object. This is the code : $taxonomy_exists = taxonomy_exists($custom_taxonomy); if(empty($last_category) && !empty($custom_taxonomy) && $taxonomy_exists) { $taxonomy_terms = get_the_terms( $post, $custom_taxonomy ); $cat_id = $taxonomy_terms[0]->term_id; // ERROR LINE $cat_nicename = $taxonomy_terms[0]->slug; // ERROR LINE $cat_link = get_term_link($taxonomy_terms[0]->term_id, $custom_taxonomy); // ERROR LINE $cat_name = $taxonomy_terms[0]->name; } How i can solve this problem ?
You need to check if `get_the_terms()` is actually returning anything. If a post doesn't have terms in that taxonomy, then `$taxonomy_terms` won't actually have any terms in it. If `$taxonomy_terms` is empty then `$taxonomy_terms[0]` won't actually be a term object so trying to access a property on it (`->term_id`) will throw an error: $taxonomy_exists = taxonomy_exists($custom_taxonomy); if(empty($last_category) && !empty($custom_taxonomy) && $taxonomy_exists) { $taxonomy_terms = get_the_terms( $post, $custom_taxonomy ); if ( ! empty( $taxonomy_terms ) ) { $cat_id = $taxonomy_terms[0]->term_id; // ERROR LINE $cat_nicename = $taxonomy_terms[0]->slug; // ERROR LINE $cat_link = get_term_link($taxonomy_terms[0]->term_id, $custom_taxonomy); // ERROR LINE $cat_name = $taxonomy_terms[0]->name; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Woocommerce order empty items array I call `$order = new WC_Order(52);` and I get a correct order object but the Items array is empty. I 've tried `select * from wp_woocommerce_order_items where order_id=52;` and I got the line item. Any ideas whats going wrong ? I am using WooCommerce 3.4.3.
To fetch the order items you can use the method get_items() I am doing something similar to you and i am doing it like this $order = wc_get_order($order_id); $line_items = $order->get_items(); In WooCommerce 3.0, CRUD objects were added so all the data can be accessed using getters and set using setters. Line items are the same so when you have your line items you should loop them and access the data using getters. For more information about the available getters and setters for these objects you can use this for reference < for the order object and for the product line items you can check < Hope this helps!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, woocommerce offtopic" }
How to customize the WordPress 2014 theme, to have page using less horizontal margin? How do I customize the WordPress 2014 theme, to have a single pages content use less horizontal margin? Do I need to create a custom theme? Or is there a simple way to modify or customize the theme that I missed? Below, I have a large image left aligned which does not leave too much horizontal space for the image. It's a requirement that the the image be the size that currently is. ![enter image description here](
This can be done with some Customized CSS, which you an insert via the Theme Customization, Additional CSS area. Use developer tools (press F12, or right-click the area and use Inspect Element) to see the CSS class used for the area you want to modify. Then use different `margin` or `padding` to position things.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, themes, css, child theme" }
Is it possible to keep all special letters for foreign languages in slug as in title? Is it possible to keep special letters in slug for foreign languages as in title? When you visit < you can see that the url contains a special letter. Is it possible to have the same functionality in WordPress for foreign languages? ![enter image description here](
Any decent theme or plugin will run URLs through the `esc_url` function to ensure the string is a decent URL. As you can see, there is a filter at the end of that function which allows you to change the outcome. You could use that to put special characters in the URL or even undo the whole escaping process. Please beware that escaping is not done for nothing. Apart from preventing invalid URLs it also solves security issues with code injected through a URL.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, url rewriting" }
Wordpress Search matching hyphenated words I've got a custom post type for comic books. The post type is called Comics (comics). I've implemented the WordPress search and I'm able to search the custom post type fine with the standard search form using the `post_type` hidden field. I've come across an issue where some people may search for Spider-Man but instead of typing Spider-Man they will type Spiderman or possibly even Spider man. My comic book titles are stored as Spider-Man and they don't return in the results if the hyphen isn't in place. Do I need to implement some sort of custom WordPress search functionality? Any pointers would be great.
It is possible to filter search terms before they are submitted to the actual query using the `query_vars` hook. So in your case you would do something like this: add_filter ('query_vars', 'wpse307005_filter_search', 10, 1); function wpse307005_filter_search ($args) { preg_replace ('Spiderman','Spider-Man',$args[s]); preg_replace ('Spider man','Spider-Man',$args[s]); return $args; } Where `$args[s]` holds the search string.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "search" }
user_id error: Only variables should be passed by reference Getting the error in my functions file that I cannot figure out how to fix. The error is: > Only variables should be passed by reference for the line of: $user_id = get_comment(get_comment_ID())->user_id; The whole of the code is: $user_id = get_comment(get_comment_ID())->user_id; $user = new WP_User( $user_id ); $user_roles = $user->roles; $user_role = array_shift($user_roles); if ($user_role == 'administrator') { echo '<div class="comment-tag admin-comment-tag">Admin</div><br>'; } elseif ($user_role == 'contributor') { echo '<div class="comment-tag contributor-comment-tag">Contributor</div><br>'; } else { echo ' '; }
There is an answer for your question right in the Codex: The first parameter of `get_comment` function is: > **$comment** \- (integer) (required) > > The ID of the comment you'd like to fetch. **You must pass a variable containing an integer (e.g. $id). A literal integer (e.g. 7) will cause a fatal error (Only variables can be passed for reference or Cannot pass parameter 1 by reference).** > > Default: None In your code, you're passing a function result as this param, so it's not a variable, so you get this error. How to fix this? It's pretty simple... Just use a variable in there: $comment_id = get_comment_ID(); $user_id = get_comment( $comment_id )->user_id; Or use a dummy variable (as shown in Codex): $user_id = get_comment( $dummy = get_comment_ID() )->user_id;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php" }
Query for post term that matches user ID I'm trying to set up something to decide wether the current post has a custom taxonomy term that matches the current users ID. So far I set up a variable that stores the taxonomy terms of the given post with $terms = get_terms( array( 'taxonomy' => 'list' )); But now I don't know how to loop through that list of terms in order to match one of the terms names with the user ID. Also, is there a way to do this without running into troubles when for example the user ID is 3 and the post has a term with the name of 30. In this case I do not want this to be a match. Any guidance is appreciated.
Try this code it will surely work, before testing this code make sure you have added the categories title as numbers. $terms = get_terms( array( 'taxonomy' => 'list', 'hide_empty' => false )); $user = wp_get_current_user(); if(!empty($terms)){ foreach ( $terms as $term ) { if($term->name == $user->ID){ // Do something } } } This code will works only for post which id you gave. $args = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all'); // You need to add Current Post ID here. $get_terms = wp_get_post_terms($post_id,'list',$args); //Get Current User Info $user = wp_get_current_user(); //Check array is not empty if(!empty($get_terms)){ foreach ( $get_terms as $term ) { if($term->name == $user->ID){ // Do something } } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, terms" }
Download any file after submitting a form I wanted to know if you know of a plugin, or a method so that when the user fills in and sends it to the form, they automatically download a file. I currently use the plugin contact form 7 Thanks.
You can use "actions". More info: < Put this code in your functions.php: function action_wpcf7_mail_sent( $contact_form ) { // here your file redirect header("Location: }; add_action( 'wpcf7_mail_sent', 'action_wpcf7_mail_sent', 10, 1 ); let me you if it is working i cannot test right now.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, php, plugin contact form 7, contact" }
Limit RSS feed to previous calendar month I want to filter my RSS feed to only show posts in the previous calendar month. I have this code in my theme functions file but it is not working? // filter the RSS feeds to show only the last calendar month $lastMonthNumber = date( 'n', current_time( 'timestamp' ) ) - 1; // work out the previous month number function feedFilter($query) { if ($query->is_feed) { $query->set('date_query', array( array( 'month' => $lastMonthNumber //'month' => 5 ) )); } return $query; } add_filter('pre_get_posts','feedFilter');`
This approach doesn't work for January: $lastMonthNumber = date( 'n', current_time( 'timestamp' ) ) - 1; as it would give `1 - 1 = 0`. Here's another suggestion, using the _string to time_ support of the date query: $query->set( 'date_query', [ [ 'after' => 'midnight first day of last month', 'inclusive' => true, ], [ 'before' => 'midnight first day of this month', 'inclusive' => false, ] ] ); For example this should generate: wp_posts.post_date >= '2018-05-01 00:00:00' AND wp_posts.post_date < '2018-06-01 00:00:00' if the current day is _27th of June 2018_. Note that `pre_get_posts` is an _action_ , not a _filter_.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "filters, rss, date query" }
Related post based on content I saw a lot of ways about related post but it's based on taxonomies. I need help to display related post based on content in the single.php Thanks
I'm too low level to comment but maybe this WP guide can help you. I didn't want to copy and paste their answer in case it was against WPSE.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query" }
How do I display SQL query on a specific page of my wordpress site this is the query i want to display **SELECT** `account_number`, `consumer_name`, `bill_amount`, `due_date`, `disco_date`, `bill_status` **FROM** `wp_bill_inquiry` **WHERE** `account_number` = _input_ **AND** `pin_number` = _input_ by inputting the data in a form like this ![enter image description here]( I hope to get this display as a result ![enter image description here](
$result = $wpdb->get_results( "SELECT `account_number`,`consumer_name`,`bill_amount`,`due_date`,`disco_date`,`bill_status` FROM {$wpdb->prefix}_bill_inquiry where `account_number` = '$inputnumber' AND `pin_number` = '$inputpin'", OBJECT ); `$wpdb->prefix` will automatically print the prefix, then to convert the result in array form you can use the following snippet: $result = json_decode(json_encode($result),true); You can either place it in a template or you can create a shortcode in functions.php, you can refer shortcode docs.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sql" }
Additional conditions tags to work Im trying to get this simple condition tag to work . Im having no luck // If we are logged in, and NOT an admin and NOT on specific page... if ( is_user_logged_in() & !is_admin() ) & !is_page('account') ) {
if(strpos($_SERVER['REQUEST_URI'], '/account/') === FALSE AND strpos($_SERVER['REQUEST_URI'], '/wp-admin/') === FALSE AND ! is_user_logged_in() === FALSE) {
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "conditional tags" }
CSS not loaded when omitting www. part of URL I have the following website: www.bibaboegifts.be. * When giving in the URL < the CSS is loaded. * However, when giving in the URL < ( **without the www. part** ), the CSS is not loaded. Only the content is displayed, but my lay-out is not applied. Any idea why this is the case & how this can be resolved?
This can happen for several reasons - in your case, it looks like you are using a caching plugin that only recognizes `www` links. I suspect if you turned off caching you would not have that problem, but then you'd lose the benefits of caching. It's best practice (with or without caching) to add redirects so only the www or non-www version of your website can be seen. You can add a line or two in your `.htaccess` file to enforce whichever you prefer - which in your case is probably `www`. RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteCond %{HTTP_HOST} ^(.*)$ [NC] RewriteRule ^(.*)$ [R=301,L] These 3 lines say, if someone tries to access your site without "www." in the URL, the server should always redirect them to the "www." version of that URL. This helps search engines know which version of your site you want indexed, and if you use SEO plugins that add canonical URLs, will help reinforce the 1 and only 1 version of each page that should be recognized.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, css, urls" }
Breadcrumbs on Product Page Always Show Wrong Product If I visit a product page, for example: < And look at the breadcrumbs, they show the wrong product. It turns out the product that the breadcrumbs show is the last updated product in my backend… How do I get my breadcrumbs working again and showing the current product that I am visiting?
The problem was a custom plugin I made was globally looping through some proucts with a WP_Query. This meant that the breadcrumbs were being set to the last product in that loop, not the product on that page... the solution was to reset the query in my plugin using `wp_reset_query();`. Always reset your queries!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic, breadcrumb" }
Output Post with ACF Fields into other Post I got a post that should be embeded, included or outputted - however you call it - into another post. I prefer a solo code variant. So far I have tested various shortcode plugins - but they don't seem to catch the attached acf fields of my post. The embedded post is a wall of several elements that should be attached now to other posts. Is this possible in Wordpress? In Drupal you can easily load a node content (page content) into the template of another. How to achieve this in WP? Is there a way to import a **RENDERED** version of a post with all of its contents (also acf fields)? Thanks?
To not duplicate code you could make a file in your theme/child-theme for the html of the post which you intend to embed, let's say `x_cpt_render_html.php`: function get_x_cpt_html(){ ?> <div class="x-cpt"> <h2> <?php the_title(); ?> </h2> <div class="content"> <?php the_content(); ?></div> <div class="custom"> <?php the_field('custom'); ?> </div> </div><?php } Then you could embed this file in the `single.php` or wherever it's needed anyway for display for that particular custom post type: get_template_part('x_cpt_render_html'); while ( have_posts() ) : the_post(); get_x_cpt_html(); endwhile; Somewhat similar where you want to embed it: $loop = new WP_Query( array( 'post_type' => 'that_post_type', 'posts_per_page' => -1,); get_template_part('x_cpt_render_html'); while ( $loop->have_posts() ) : $loop->the_post(); get_x_cpt_html(); endwhile; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, custom field, pages, import, embed" }
Insert Sponsor logo in custom own theme I'm new to wordpress. I'm creating my own theme. There is a sponsor logo area in my theme. For that case I'm going to use cr3ativ sponsor plugin. I have installed the plugin and added the sponsors logo. How I have to insert the PHP code for that sponsor plugin. I read the documentation and found like below. [sponsor_level category="all" orderby="menu_order" columns="4" image="yes" title="no" link="yes" bio="yes" show="9999999"] Do I need to insert into my php code?
That's a shortcode, it's meant to go in content. If you want to output it in a template but don't know the underlying function then you can use `do_shortcode()`: <?php echo do_shortcode( '[sponsor_level category="all" orderby="menu_order" columns="4" image="yes" title="no" link="yes" bio="yes" show="9999999"]' ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, images" }
Current category link filter In my theme I have an archive template for a taxonomy (taxonomy-cat_projet.php). In this template I have a list of this taxonomies' links to allow users to select a taxonomy. Here is the code I'm using to list the categories links: <ul> <?php $args = array( 'title_li' => '', 'taxonomy' => 'cat_projet', 'hide_empty' => false, ); wp_list_categories( $args ); ?> </ul> Is there a way (once a category is selected) it's link could change so that if it's clicked it lists posts from all categories. Like, first click makes that category active, and the second time it's clicked it becomes inactive. I know I could do it in javascript, but i prefer doing it in php, like using some "current taxonomy link" filter if it exists.
Internally `wp_list_categories()` uses `get_term_link()` for the URL of the terms. That function can be filtered using the `term_link` filter, so you could filter any links to the current term and replace them with links to the post type archive: function wpse_307202_term_link( $termlink, $term, $taxonomy ) { if ( is_tax( 'cat_projet' ) ) { if ( get_queried_object_id() === $term->term_id ) { $termlink = get_post_type_archive_link( 'post_type_name' ); } } return $termlink; } add_filter( 'term_link', 'wpse_307202_term_link', 10, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy, theme development, filters, taxonomy, link category" }
Creating User Profiles using author.php I am trying to create a user profile template using author.php. However, the template remains blank if I try to see the profile of a user that has not created any posts. www.website.com/author/user1 -> Has written Posts -> Template shows User info www.website.com/author/user2 -> Subscriber account -> template remains empty How can I tell Wordpress to fill in the information for every user? Edit: My Code so far: <?php get_header(); $userID = get_the_author_meta('ID'); $user = get_userdata($userID); ?> <div class="profile-wrapper"> <div class="row justify-content-center user-info"> <div class="col-lg-5 text-center"> <span><?php echo get_avatar($user->ID, 150) ?></span> <h2 class="heading-semibig"><?php echo $user->display_name ?></h2> </div> </div> </div>
`get_the_author_meta( 'ID' )` gets the ID of the author of the current post. If there's no post there's no author. Use `get_queried_object_id()` instead. When used on author archives (i.e. author.php) it will be the ID of the author, regardless of whether or not they have posts.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, author, profiles" }
How to move a WordPress Localhost straight to an online site? I have read several guides including this one which talk about creating a live server which is hosted. I don't require a custom domain and are happy having it named `mysite.wordpress.com.` If I am moving it from localhost how can I upload this using the WordPress online editor so that my site can be live? I would like to do this for free, which is why I am not going with a custom domain. Is it possible, or do I have to hos the site under a custom domain? If this is the case do I have to copy and paste all content individually to my WordPress online editor from the installed localhost?
You're confusing WordPress.com and WordPress.org. The .org is what is used for hosting your own WordPress website on your hosting provider. The .com is hosting your website using WordPress.com's systems. There are some major differences between the two and it's critical that you understand them. First and foremost hosting on .com has severe restrictions on the themes and plugins that you can use. Ultimately you are limited to what is approved by WordPress.com. Hosting your own domain allows you much more control over your website, the themes, and plugins you can use. To my knowledge, there is no way to upload your locally developed website to WordPress.com. You can however deploy it to your own hosting provider.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "localhost, hosting" }
Prevent wordpress autoredirect I've got a problem. My client has taken ads with ex.com/helloworld as the short URL to their new page. No problem, I'll do a htaccess redirect on it, redirect the shorturl to the right page (which is ex.com/careers/helloworld-recruiting) But theres a page on my site which is ex.com/services/helloworld, and for some reason, the htaccess redirect is bypassed in favor of the automatic wordpress URL recognition redirect. So how can I ask Wordpress to kindly fuck off so I can use my own redirect instead of his? Here's the line in my htaccess, tested with < it should go through as expected. `RewriteRule ^helloworld/$ //careers/helloworld-recruiting/ [L,R=301]`
Not really a WP-specific question, but I'll help you out. That regex will match `ex.com/helloworld/` but not `ex.com/helloworld`. To handle both you'd want `RewriteRule ^helloworld/?$ /careers/helloworld-recruiting/ [L,R=301]` The question mark makes the preceding token optional and the single slash rather than double in the rewritten URL makes it relative to the root.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "redirect, htaccess" }
woocomrce pay here button help I am beginner in WordPress.I am using woocommrce plugin. What i am trying to implement is when i click the item (add to cart) after product checkout to showing order details and payment option and pay here button. My issue is i want to hide this time payment option and pay here button to send to invoice for customer . after 2nd time admin send to shipping cost with total payment details. and payment option with pay here button . i tried to find any plugin this type . i dont seen any plugging . please help me to fix this thanks
I just found a free WooCommerce extension for Quote implementation. REQUEST FOR QUOTE PLUGIN: < 1. Customer adds products to the Quote from website. All products will be displayed in Quote List and customer sends the quote request to the website Admin. 2. Website admin views the quote and creates the proposal as shown in below screenshot from orders screen. ![enter image description here]( 3. Customer sees proposal and accepts or rejects proposal from Quotes detail page in My Account. ![enter image description here]( This plugin brief doc for installation and how it works...Hope this helps..!!
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "woocommerce offtopic" }
How to I prevent WordPress from switching external HTTP links to HTTPS? The website has an SSL certificate and uses but when I link to a website using a text link pointing to < and then preview it the link is updated to < What causes this and how can I prevent this from happening?
I suspect a bad plugin, but you didn't provide enough information. But it could be a directive in your htaccess file that is not correct. Take a look at this question/answer for a comprehensive discussion about it: < . If that doesn't help, provide more information about plugins and your htaccess file contents.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks, links" }
Translate a Constant while appeasing WordPress PHPCS The following _works_ but isn't up to snuff with PHP Code Sniffer WordPress coding standards <?php esc_html_e( ADDRESS, 'wprig' ); ?> Linter yells at me with: > [WordPress.WP.I18n.NonSingularStringLiteralText] The $text arg must be a single string literal, not "ADDRESS". The following, for aforementioned error, also don't work: <?php esc_html_e( (string)ADDRESS, 'wprig' ); ?> <?php esc_html_e( strval(ADDRESS), 'wprig' ); ?> <?php esc_attr_e( ADDRESS, 'wprig' ); ?> I know constants can be exploited so it is needed. Any way to make this work besides `//phpcs:ignore`, or is this not good practice and I should redo my use of constants?
You cannot use constants or anything other than actual strings with translation functions. This is because the code that reads your code, and produces the translatable strings does not actually _run_ your code, it is _reading_ your code. Here is a more detailed post on the topic: < But the short version is this: This is wrong: <?php esc_html_e( ADDRESS, 'wprig' ); ?> Nothing will make that right except this: <?php esc_html_e( 'Actual String here', 'wprig' ); ?>
stackexchange-wordpress
{ "answer_score": 11, "question_score": 1, "tags": "escaping, coding standards" }
Hide empty custom field I've created a custom field in Woocommerce to link to games that have the same title but are on different platforms. It basically shows **Also available on:** XBox One or PS4. It works well but when the field is empty it shows only **Also available on:** which looks sloppy and is confusing. How can I hide the custom field when it's empty? The code is below and the custom field is also_available. I've placed it in my functions.php add_action( 'woocommerce_single_product_summary', 'also_available_on_ps4', 38 ); function also_available_on_ps4() { global $product; if ( has_term( 'ps4-games', 'product_cat' ) ) { echo '<b>Also available on:</b>' . get_post_meta( get_the_ID(), 'also_available', true ); } } I hope someone can help me. TIA
I'm assuming what you want is to hide the text when meta is empty. You can put a conditional check for meta before print: add_action( 'woocommerce_single_product_summary', 'also_available_on_ps4', 38 ); function also_available_on_ps4() { global $product; if ( has_term( 'ps4-games', 'product_cat' ) ) { if(get_post_meta( get_the_ID(), 'also_available', true )){ echo '<b>Also available on:</b>' . get_post_meta( get_the_ID(), 'also_available', true ); } } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, custom field" }
Add count for new registered user in Users tab Is there a way or hooks that I can use to add counter in Users tab for new registered users like this?. <
Yes, there is. You can use `admin_menu` hook to loop through menu items and add span with notification. There are two classes that WP uses for these notifications `update-plugins` and `awaiting-mod`. The second one looks more appropriate in this case, I guess... Here's some code: function add_user_menu_notification() { global $menu; $user_count = count_users(); // get whatever count you need $user_count = $user_count['avail_roles']['administrator']; if ( $user_count ) { foreach ( $menu as $key => $value ) { if ( $menu[$key][2] == 'users.php' ) { $menu[$key][0] .= ' <span class="awaiting-mod">' . $user_count . '</span>'; return; } } } } add_action( 'admin_menu', 'add_user_menu_notification' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp admin, users" }
How to enable shortcodes in a custom post type? How can I enable shortcodes on a custom post type that doesn't use `the_content()` or `get_the_content()`? In the template file it uses <?php echo nl2br( $post->post_content ); ?> to get the content from the backend like any other post or page would. I have tried using <?php echo do_shortcode(get_post_field('post_content', $postid)); ?> which works but the shortcode itself is still displaying for example: [gallery columns="4" link="file" ids="1,2,3,4"] displays above the gallery photos.
For my particular situation the answer was to replace `<?php echo nl2br( $post->post_content ); ?>` with `<?php echo $content; ?>` which allowed all shortcodes to work as expected.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "custom post types, shortcode" }
Complex List Field - Gravity Forms So I am using this Complex List instruction from LINK and it works, but it is changing all my lists. I've tried a few things but am missing something... .gform_wrapper ul.gform_fields.form_sublabel_above table.gfield_list td::before, .gform_wrapper ul.gform_fields.form_sublabel_below table.gfield_list td::after { content: attr(data-label); font-size: 14px; letter-spacing: .5pt; white-space: nowrap; display: block; clear: both; I've tried adding `#field_35_53` to the front of it so it would target just that field, but to no avail. Anyone got any bright ideas?
Never mind... got it and feel stupid. This did the trick: #field_35_53 td::after { content: attr(data-label); font-size: 14px; letter-spacing: .5pt; white-space: nowrap; display: block; clear: both; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, forms, list, plugin gravity forms" }
Userless db-only wordpress instalation Hello how I can perform a wordpress installation without the need to create users. I want to just run a command and just install the database. I want the user to get installed via gui when cli install has been completed. The reason I am asking is because I developed a docker based wordpress solution (< and performs a wordpress installation via wp-cli. But with that requires to provide user credentials for the first wordpress admin user. Not only that also there is somewhere stored in the server the password as plaintext as well (possible security vunlerability) Not only that when I use this solution usually I create a personal user account with admin rights so that results the user that is created during installation to be actually useless. So I want to perform all the installation steps via wp-cli EXCEPT the one that creates any user. What I actually want is to setup the database schema.
It is not possible to install WordPress without creating a user. However, you could immediately remove that user with a second wp-cli command like yes | wp user delete 1 Note: this will also delete any posts and pages associated with that user. You can normally re-assign them to a different user but in this case, there won't be one.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp cli" }
How to skip woocommerce checkout after payment page? I use woocommerce plugin for my shop. I want to skip the checkout after payment page where users give order details . So the system will be when they select a checkout after go to the payment page . i want to skip it this time. but i want to send email to client pay for my order . Any idea how i can build this, Please help me
This is actually a legal requirement, until any payments CAN be made online, else all details etc have to be told in the email supposed you live in the USA or EU, else research with your local government. As guidelines, you can add a javascript that fills in any forms (subject to PHP session), then toggles (clicks) the payment-by-email button and then continue button after `document.ready`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How do I get the Payzone WooCommerce payment gateway plugin to show up in the settings? We have a multi-site set up, but for some reason Payzone will not show up as a payment method. It seems to affect only multi-sites because if I install it onto a regulard WordPress/WooCommerce site it shows up perfectly fine. So does anyone know how do I go about fixing this, or at least figuring out why it won't work on a multi-site? Is there something I am missing?
As Rustom mentioned, the plugin isn't checking if this Multisite is activated - you can add a check in for multisite, add the below in the plugin registration file, just below the existing active check functions. if(!function_exists('is_plugin_active_for_network')){ require_once(ABSPATH .'/wp-admin/includes/plugin.php'); if(is_multisite() && is_plugin_active_for_network('woocommerce/woocommerce.php')){//check if multisite and check /** add in the functions from inside the current active check. **/ } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, multisite, woocommerce offtopic" }
Wordpress plugin enqueue scripts working for js, but not css files I am trying to load custom css specifically relevant to the plugin. The js is working perfectly fine, but the css just refuses to get loaded in. Here is the code: function admin_plugin_scripts(){ wp_enqueue_style('arena', plugin_dir_url(__FILE__) . 'css/arena.css', array(), filemtime( WP_PLUGIN_DIR . '/PluginName/css/arena.css'), true ); wp_enqueue_script('admin', plugin_dir_url(__FILE__) . 'js/admin.js', array('jquery'), filemtime( WP_PLUGIN_DIR . '/PluginName/js/admin.js' ), true); wp_localize_script( 'admin', 'ajaxobj', array('ajax_url' =>admin_url('admin-ajax.php'))); } add_action('admin_enqueue_scripts', 'admin_plugin_scripts'); Thanks in advance for any help offered!
The function `wp_enqueue_style` last argument is the `$media` and you set it to true so its mean you are doing <link rel='stylesheet' ... media='1' /> > $media (string) (Optional) The media for which this stylesheet has been defined. Accepts media types like **'all', 'print' and 'screen', or media queries like '(orientation: portrait)' and '(max-width: 640px)'**. > > Default value: 'all' So you should or remove the last argument so it will be the default **all** or just set some other media type. wp_enqueue_style('arena', plugin_dir_url(__FILE__) . 'css/arena.css', array(), filemtime( WP_PLUGIN_DIR . '/PluginName/css/arena.css') );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, wp enqueue style" }
Is is safe to edit language files from wp-content/languages/plugins/woocommerce-ro_RO? Is is safe to edit language files from wp-content/languages/plugins/woocommerce-ro_RO.mo(.po) ? I'm asking this because I don't want them to be overriden on plugin update. Sorry if dumb question.
**No** , this is not safe. You shouldn't make any changes to files within a plugin's directory, all of those changes may be overridden. If you want to change a translation, you can use a plugin such as Loco Translate or use the `gettext` filter.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "woocommerce offtopic, translation" }
Remove link preview in discussion dashboard It can be sometimes bothersome when, in the Discussion (Comments) dashboard, where the admin can see a list of comments, moving the mouse over a link will cause a preview of that link. Sometimes the preview gets in the way of looking at the comment. This is especially true with spam comments. And I am also concerned that a link to a page/site that had some 'bad' code would cause a compromise of my site. Is there a way to disable this 'feature'? Not sure where it is coming from.
Since version 4.1.6, Akismet has a filter which allows you to disable these "mShots" (the site preview popups): <?php function disable_akismet_mshots( $value ) { return false; } add_filter( 'akismet_enable_mshots', 'disable_akismet_mshots' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "comments, links" }
Why is my upload / Select media library button empty? The button seems to exist but the content of the button is empty. I have tried: * Disabling all the plugins * Downloading again wordpress and overwriting wp-includes and wp-admin with the original files. * Clearing the Browser cache * Clearing the Wordpress cache Still doesn't work. ![enter image description here](
I have found out that you can't defer the javascript loading on the whole site or it will mess up some contents on the backend. I have to check if the page is the backend or the frontend and block the function just for backend with `if (!(is_admin() ))`. if (!(is_admin() )) { function defer_parsing_of_js ( $url ) { if ( FALSE === strpos( $url, '.js' ) ) return $url; if ( strpos( $url, 'jquery.js' ) ) return $url; // return "$url' defer "; return "$url' defer onload='"; } add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "media library" }
Is there an event or an other method that tells me the preview is loaded? I'm working on a Plugin for the WordPress Customizer and need to call a function when the previewer has loaded. Is there an event or an other method that tells me the preview is loaded? If have tried: jQuery(window).load (function() { // Customizer loaded... wp.customize.previewer.bind( 'refresh', function() { // doesn't seem to work ?! alert ('Previewer has loaded'); } } I've also tried `wp.customizer.bind('refresh', function (){` Is there no event that gets fired when the preview is loaded? The refresh event gets fired when the previewer gets refreshed. Any ideas?
Yes, this is the way to detect when the preview has loaded: wp.customize.bind( 'ready', function() { wp.customize.previewer.bind( 'ready', function( message ) { console.info( 'Preview is loaded' ); } ); } ); This JS code should be enqueued at the `customize_controls_enqueue_scripts` action with `customize-controls` script as its dependency.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugin development, jquery, javascript, theme customizer" }
Changing the_posts_navigation() html output I'm using underscores which uses the_posts_navigation(); in the archive. Any way to change this language? Thanks!
This function use the `get_the_posts_navigation()` to change the text **Older posts** and **Newer posts** you can pass array with the args. See this example with the default values: the_posts_navigation( array( 'prev_text' => __('Older posts', 'theme_textdomain'), 'next_text' => __('Newer posts', 'theme_textdomain'), 'screen_reader_text' => __('Posts navigation', 'theme_textdomain') ) );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, loop" }
How to load a template-part based on a url wildcard? I'm trying to create a agenda in a custom Wordpress theme. On the agenda page there is a simple page-agenda.php template that will include some code that handles the index of the agenda. Quite simple. But now I would like to 'listen' to the URL that contains a detail page of an agenda item. For example /agenda/1/event-name. When I visit the above URL I get an page not found error. And when I try to load a template file based on the init hook of wordpress, no content seems to be added to the page and I keep getting the page-not-found page. SO. How would I load a .php template file base on a URL wildcard like /agenda/1/event-name? So I can show the event data and not get a 404 message. Thanks!
I ended up with this solution in `functions.php`, thanks to the offical Wordpress documentation at: < First added a custom rewrite rule like so: function custom_rewrite_rule() { add_rewrite_rule( '^agenda/([^/]*)/([^/]*)/?', 'index.php?page_id=10&agenda_id=$matches[1]&agenda_name=$matches[2]', 'top' ); } add_action( 'init', 'custom_rewrite_rule', 10, 0 ); Then this needed to be added: function prefix_register_query_var( $vars ) { $vars[] = 'agenda_id'; $vars[] = 'agenda_name'; return $vars; } add_filter( 'query_vars', 'prefix_register_query_var' ); Now URL's such as /agenda/1/event-title work like a charm! And passes the variables needed. **PS: Remember to save the permalinks settings in the backend once again, or this code won't work!**
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, theme development, hooks" }
Extending WP_UnitTestCase without any Tests I want to add some logging to an extension of WP_UnitTestCase. Like this: class MZMBO_UnitTestCase extends WP_UnitTestCase { public function el($message){ file_put_contents('./log_'.date("j.n.Y").'.log', $message, FILE_APPEND); } } And include('class-mzmbo-wpunittestcase.php'); class Tests_Session extends MZMBO_UnitTestCase { /** some tests **\ $this->el('some data'); } Then there's a warning: 1) Warning No tests found in class "MZMBO_UnitTestCase". So I add a useless method and the warning goes away. public function test_nothing() { $this->assertEquals( true, true ); } There must be a better way.
You just need to define the `MZMBO_UnitTestCase` class as `abstract`: abstract class MZMBO_UnitTestCase extends WP_UnitTestCase { public function el($message){ file_put_contents('./log_'.date("j.n.Y").'.log', $message, FILE_APPEND); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "unit tests" }
SQL query to set posts in bulk based on the post content I have thousands of offline links in my posts, and I'd like to set them all to draft. I know the links are in the format example.com/fileX. So I needed a SQL query to search the post content and whatever post that contain that url will be set to draft. I think this might be a good start: UPDATE tb_posts SET post_status = 'draft' WHERE But I don't know to do the search inside the WHERE clause. I intend to use ARI Adminer Plugin to edit the database.
Look into MySQL Wildcards. The correct MySQL Query for your search should be WHERE tb_posts.post_content LIKE "%example.com%" You should also be sure that you only target published posts (in contrast to nav_menu_items, revisions etc). Expand your WHERE with this: AND tb_posts.post_type IN ('post','page',*All Posttypes you use additionally*) AND tb_posts.post_status = 'publish' So your complete Query should look like this (assuming that you only use posts and pages): UPDATE tb_posts SET post_status = 'draft' WHERE post_content LIKE "%example.com%" AND post_type IN ('post','page') AND post_status = 'publish' Happy Coding!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, query, mysql, sql" }
Fatal error: Out of memory with the Duplicator plugin When i try to install a website that i got as an duplicator archive i get the following error at the very last step of the installation: ![enter image description here]( I am using the latest version of xampp on my local machine which has 16GB of DDR4. These are the relevant values in my PHP.INI memory_limit=1024M max_execution_time=300 post_max_size=32M
I found a solution that worked for me. I downgraded my PHP-Version from 7.2.5 to 5.6.36 and that fixed it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, xampp" }
Multiple Permalinks for custom post type post is there a way to have multiple permalinks for a custom post type post? For example: The normal permalink url is called: I also want the post is reachable under the following urls: I know that I can manual add in the .htaccess, but I add the post inside my plugin. So what is the best method to add these urls to a post and make them accessable? I need some suggestions, not code solution.
Yes this is possible using `add_rewrite_rule()`, something along the lines of add_rewrite_rule( 'test-subject/(\d+)/?', 'index.php?post_type=CPT_slug&post_id=$matches[1]' ); add_rewrite_rule( 'ts/(\d+)/?', 'index.php?post_type=CPT_slug&post_id=$matches[1]' ); It might be a bit trickier though, since `test-subject/test-title` and `test-subject/post_id` are quite similar. Adding the `post_id`-rule with the 3rd argument as `'top'` might help.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, plugin development, url rewriting" }
Question on templates I'm using a free theme called Ocean WP that has a folder called 'templates' I thought I could just save over one of the templates and rename it and construct a template (which I need for custom post types/ Advanced Custom Fields). However when I tried the above it threw an error. My question is - what should I be looking for with regards to building templates. Of course the easiest way to build a template is to just copy the page.php and give it a new name but that seems to be the wrong approach given that there is a folder called 'templates' Thanks for all direction
The folder is just where Ocean WP's developers chose to store its templates. It's not something for you to do anything with. If you want to create your own custom template you need to create a Child Theme and create the template there. If you create or modify files in a theme they will be erased if/when the theme is updated. Creating a Child Theme avoids this issue. Regarding the error, putting a file into a theme wouldn't throw an error on its own. You likely had a syntax error in the code of the template.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, templates, page template" }
Modify automatically generation of slug when term is created I need modify the sanitize of slug when a **term** is created. For example I'm creating a term with name 0,5 and the slug automatically generated is 05. I need to add a dash in the position of the comma, the spected slug will be 0-5. It's possible to do it overridind the code in theme functions.php? SOLVED: add_action('wp_insert_term_data', 'slug_save_term_callback', 10, 3 ); function slug_save_term_callback($data, $taxonomy, $args) { $name = $data['name']; $name = str_replace(',', '-', $name); $data['slug'] = $name; return $data; } Thanks
You will have bugs like this. because you are not sanitizing the title with `sanitize_title()`. And you are not checking for duplications with `wp_unique_term_slug()` Bugs tests: 1. Add spaces in the name and see the slug with spaces. 2. After you add the `sanitize_title()` add term with comma 5,5 add term with space 5 5 results with duplications. So just fix this like this: add_action('wp_insert_term_data', 'slug_save_term_callback', 10, 3 ); function slug_save_term_callback($data, $taxonomy, $args) { $name = $data['name']; $name = wp_unique_term_slug(sanitize_title(str_replace(',', '-', $name)), (object) $args); $data['slug'] = $name; return $data; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "terms, sanitization" }
Hide Visibility Option From WordPress Publish Metabox I want to hide visibility option on publishbox for PAGE post_type like you see in red square on the below picture. ![enter image description here]( Thanks.
Add this code: function wpseNoVisibility() { echo '<style>div#visibility.misc-pub-section.misc-pub-visibility{display:none}</style>'; } add_action('admin_head', 'wpseNoVisibility'); to `functions.php` of your active theme. Needless to say, the preferred method, would be to add above code to `functions.php` of the child theme. **Update** Unfortunately, the above solution will not limit this change to pages only. We'll have to determine, if we add, or edit page, first. The following code will fix it: function wpseNoVisibility() { echo '<style>div#visibility.misc-pub-section.misc-pub-visibility{display:none}</style>'; } function wpseCurrentScreenAction($current_screen) { if ('page' == $current_screen->post_type && 'post' == $current_screen->base) { add_action('admin_head', 'wpseNoVisibility'); } } add_action('current_screen', 'wpseCurrentScreenAction');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, wp admin" }
Allow users from my ASP.Net MVC site to access my private WordPress site I have an ASP .Net MVC site and I would like users who are logged in to my site to be able to access a separate WordPress site which I also own. Otherwise, if a user is not logged into my ASP .Net site, the WordPress site should remain private. What is the easiest way to implement this? I thought about SSO but it seems like overkill for this simple scenario. I don't need users identified on the WordPress site; they won't be allowed to post or anything, all they can do is just read my posts there.
I ended up making the whole WP site private except to logged in users by using a plugin (Ultimate Member). Then I created a single login which would be used from the .Net site. The way it works is: 1. User clicks on link within .Net site to access WordPress site 2. Server-side: performs POST to /wp-login.php with credentials for single WP user 3. Server-side: retrieve cookies from wp-login.php response 4. Client-side: call to custom PHP page on WP site: /setcookies.php and set user’s session cookies for WP site domain using cookies from previous step 5. Client-side: open WP site in iframe using session cookies
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "password, single sign on" }
Hide icon and rating when there is no rating entered Some newbie question regarding PHP. I need to hide star icon when there is no rating for the post: <span class="js-average-rating"><i class="star"></i> <?php echo get_average_listing_rating( $post->ID, 1 ); ?></span> So I need to hide when no rating is inserted. Thanks!
Simply check that the rating is not empty before printing the markup you wish to make conditional: <?php $rating = get_average_listing_rating( $post->ID, 1 ); if ( ! empty( $rating ) ) { ?> <span class="js-average-rating"><i class="star"></i> <?php echo $rating; ?></span> <?php } ?> Without seeing this in context, it's possible you need the outer span to maintain alignment or something else. If so, just move what you need outside of the condition test.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "icon" }
Error in Validate Field with ACF plugin in Wordpress I have the following problem when I am validating a field with the Advanced Custom Fields plugin in wordpress. What happens is that the field is validated correctly but the error appears on a new page instead of going out on the same page above the field to which I am validating. The code to validate is the following: function validate_fields_contact() { add_filter('acf/validate_value/name=phone_contact', 'validate_phone_number', 10, 4); } function validate_phone_number($valid, $value, $field, $input) { if (!$valid) { return $valid; } if(!preg_match("/^\+XX(\s|\d){8,12}$/", $value)) { return __('Incorrect Format.'); } return true; } **It should be like that:** ![enter image description here]( **This is what happens** ![enter image description here](
I did have the same issue. And I wasted enough time for the answer. At first be sure that: The ajax request isn't failed and happens. So, check: 1. Is acf_form_head() before get_header() and run before any html is output? 2. Does your theme contain call to wp_head()? 3. Does your theme contain call to wp_foot()? 4. Are your deferring the loading of JavaScript or otherwise altering the way that JavaScript is loaded on the page? (Look at this ACF support topic too. If you use acf_form() for creating new user look at this topic). But in my case the root was is_admin() in this line into the 'acf/validate_value' hook: if ( ! $valid || is_admin() ) { return $valid; } **Because is_admin() returns 'true' by AJAX requests**. As a result, the validate function didn't work. Hope it will helpfully for somebody.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "advanced custom fields, validation, 500 internal error" }
Styling the website via the customizer - do the changes stay after theme update? If I customize a theme via the Customizer, do these changes get over-written with the theme update? I have tested it on TwentySeventeen as well as on the free version of the Agama theme, and the changes stayed. But I want to understand why these changes stay when changes done directly to the theme files get over-written. Where does the customizer save the changes? Thank you.
It's not really the Customizer that stores the changes, sort of. All changes to a theme's settings are done by the theme settings code, and are stored (usually) in the wp-options table (although a theme might have it's own table where it stores settings). So, if you make changes via the theme's Customizer interface, the theme stores that in the database. If you change to a new theme, there will be settings for that theme that are stored in another spot in the database. Then if you change back to the first theme, it should read the settings that you set before. Depending on the theme, uninstalling/deleting the theme might remove all the settings for that theme, so if you reinstall that theme again, you'll have to start all over. Some themes may 'share' settings between themes, but again this is all the responsibility of the theme's code, which uses the Customizer API to display and save settings.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, theme customizer" }
Using custom php file for ajax url inside plugin Inside a subdirectory of my plugin I have a file called insertproducts.php and I need to call that through an Ajax request. I have something like this: $.ajax({ url: "insertproducts.php", }).done(function(data) { console.log(data); }); But the script cannot find the file and tries to look for: Looking around to find out the problem and I read that WP points all the ajax requests to admin-ajax.php. How do I run my custom url now?
Read more about AJAX in Plugins. How to use Ajax in WP: 1\. Register file contain functions, event of javascript or jquery. All data will be submit by events js add_action( 'wp_enqueue_scripts', 'ajax_scripts' ); function ajax_scripts() { wp_register_script( 'main-ajax', get_template_directory_uri() . '/assets/js/main-ajax.js', array(), '', true ); $arr = array( 'ajaxurl' => admin_url('admin-ajax.php') ); wp_localize_script('main-ajax','obj',$arr ); wp_enqueue_script('main-ajax'); } inside main-ajax.js (data will be process through by admin-ajax.php) : $.ajax({ url: obj.ajaxurl, }).done(function(data) { console.log(data); }); 2\. File PHP to process functions (insertproducts.php) after submit data by ajax. Use below action for your function. add_action('wp_ajax_my_action', 'my_action'); add_action('wp_ajax_nopriv_my_action', 'my_action');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, ajax" }
add_menu_page() for more than one user role If I add a custom page to the wordpress backend menu via add_menu_page('My Custom Page', 'My Custom page', 'editor', 'custom_page','add_custom_page','dashicons-admin-comments',8); only a user with editor privileges can see the page in its menu. How can I make this menu entry also available for users with administrator privileges? Have I to use _add_menu_page()_ for every user role seperately?
Let's take a look at Codex page for `add_menu_page`... Third param is: > **$capability** _(string)_ (Required) The capability required for this menu to be displayed to the user. And later on in Notes section: > This function takes a ‘capability’ (see Roles and Capabilities) which will be used to determine whether or not a page is included in the menu. The function which is hooked in to handle the output of the page must check that the user has the required ‘capability’ as well. As you can see, you should use capability (for example `manage_options`, `publish_posts`) and not user role (`editor`, `subscriber`) as that param. So if you'll pass `publish_pages` as third param, only Editor, Administrator, and Super Admin will get access to that page. Here you can find list of default capabilities for default user roles.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "user roles, capabilities, add menu page" }
How to display partial values of JSON Encode values I want to display partial values of JSON Encode values. Following is the code. <?php global $wpdb; $project_member_details = $wpdb->get_var( $wpdb->prepare( "SELECT project_members FROM wpxa_project_members WHERE project_id = 603" ) ); echo $project_member_details; ?> I get following result... {"member_image":["21604_1530889966_1408904487.png","21604_1530889966_1590217155.jpg","21604_1530889966_1179667677.png"],"member_name":["Test","Best","Guest"],"member_role":["Test1","Best1","Guest1"],"member_email":["[email protected]","[email protected]","[email protected]"],"member_facebook_id":["Test3","Best3","Guest3"]} But I want only this... How to do... {"member_image":["21604_1530889966_1408904487.png","21604_1530889966_1590217155.jpg","21604_1530889966_1179667677.png"] Plz help...
Use `json_decode`: global $wpdb; $project_member_details = $wpdb->get_var( $wpdb->prepare( "SELECT project_members FROM wpxa_orocox_project_members WHERE project_id = 603" ) ); $project_member_details = json_decode( $project_member_details, true ); print_r( $project_member_details['member_image'] ); If you still want the output to be JSON encoded at the end of it, you could then do something like: $member_images = $project_member_details['member_image']; echo wp_json_encode( [ 'member_image' => $member_images ] );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "json" }
WordPress Multisite subdirectories not allowed on new install? I've just installed a fresh install of WordPress and before doing anything else I've tried to setup a multisite, which I would like to do with subdirectories. But when I click on Network Setup I get the notification: > Because your installation is not new, the sites in your WordPress network must use sub-domains. The main site in a sub-directory installation will need to use a modified permalink structure, potentially breaking existing links. Can anyone tell me what I'm doing wrong, or what I need to change to allow subdirectories?
You don't need to do anything just past this code in your activated theme's `functions.php` add_filter( 'allow_subdirectory_install', '__return_true' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "multisite" }
Conditionally change Wordpress core language I need to change the wordpress language conditionally. So I use the code: //Change Site Locale function wpsx89972_redefine_locale($locale) { if .....my condition exists... { $locale = 'en_US'; } else { $locale = 'fr_FR'; } return $locale; } add_filter('locale','wpsx89972_redefine_locale',10); This way I can use my translations but the core's and the theme's language does not change. For example "Leave a Comment" or the month of the published date remain in English. The solution used to be to call conditionally the function define ('WPLANG', 'fr_FR'); but now that is deprecated how could I change the core's translation?
You must define this filter as early as you can, before it is used anywhere. Best way to do it is to create must-use plugin. I find the concept incredibly usefull since this scripts don't require any setup like plugins do, and can stage environment for both your plugins and theme. Also they can't be deactivated
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, translation, multi language, language" }
how can I change the read more link destinations and direct all to the same page? I have 4 read more urls in my woocommerce product listing and i would like all to be directed to a custom page instead of the product info page - preferably using functions.php
You could use the post_link filter to rewrite the permalinks for those selected products. function redirect_products( $url, $post ) { if ( in_array($post->ID, array(1,2,3,4) ) { //1,2,3,4 = your product IDs $url = get_permalink(123); //the ID of the redirect page } return $url; } add_filter( 'post_link', 'redirect_products', 10, 2 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, woocommerce offtopic, read more" }
Posts page only shows one post I have an old blog that I have kept up to date with the latest Wordpress version, plugins and theme updates over the years. But somewhere along the way the posts page stopped working properly. It presently only shows a link for one post. Furthermore, it is just the link, no graphic or summary is displayed. I disabled the theme and all the plugins as a test but the result is the same. I recreated the page that is named as the posts page too, all to get the same result. This is a link to the page. What am I missing?
As noted in a comment above, apparently the theme I use in one of its updates required the Options Framework plugin. Without it, a certain function was undefined. Thus the error and the breaking of the posts page. Installing the plugin solved the issue.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts" }
wp_get_nav_menu_items vs wp_nav_menu I'm a novice WordPress developer and I'm looking for best way to build custom WordPress menu. I have found two server side ways to do that, but i don't understand deeper difference of them The menu might build with the wp_nav_menu function and for that need crate extends class of Walker_Nav_Menu. For that need have a copy of the main class in your theme and change more code as well Or we can use wp_get_nav_menu_items function, by giving it the menu location to get the array of all items to build html output. It will be more simple and easy and no need to understand complicated Walker class So, what the best way to build the menu or what the main difference of these functions. Thanks
`wp_get_nav_menu_items` function retrieves an array of menu items for given menu. But the menu is a hierarchy, so there is a need of creating some mechanism that will create that hierarchy based on list of menu items. On the other hand there already is `wp_nav_menu`, that will get items for that menu (using `wp_get_nav_menu_items`) and then it will pass it to Walker class that will generate HTML code for this menu. This function will also take care of cases when given menu doesn't exist and so on. It is the recommended way to display menu in themes. PS. I don't get why you think that you "have to" write your own Walker class. You certainly don't. WP will use it's own Walker class as default. And if you want to customize the HTML code for that menu, you can write filters and it will be enough most of the times...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "menus" }
Wordpress returns a wrong date I am trying to get the todays date , day and time . **Today is : 10th july 2018,tuesday and time is 3.23am** For time the below code works fine: $wpplcurrenttime = current_time( 'g:i a', $gmt = 0 ); echo $wpplcurrenttime; and out put is: 3.23 am which is correct But strangely the date is not getting correct : the **returned date is 9th july 2018,Monday** These are the codes i tried : $dw = date('l'); echo $dw; echo date(get_option('date_format')); echo date('l jS F Y'); echo gmdate('w'); All of above codes gives a wrong date and day. I have double checked the WordPress general setting it is showing the date and time correctly. Really appreciate the help Thanks
As mmm said, wp stores all dates&times in gmt, but will show times as per the setting timezone. So you can cgange the timezone without the history needing to be updated. I prefer to use the php datetime when working with time. Gives better control and flexibility, eg if you want to show events in different users timezones, let the system deal with daylight saving etc. To Fetch the wp timezone and create tz object, then use $tzs = get_option('timezone_string'); $tzobj = timezone_open($tzs); To create datetime object for 'now' in a particular timezone $now = date_create('now',$tzobj ); to format dates & times, use any format accepted by `date()` echo date_format($now, 'Y-m-d H:i:s');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, date, date time" }
How can I copy all users to newly created site on a multisite network in Wordpress? As when I create a new site on multisite wordpress network, then only admin user gets created. I want all users which are present on my first site to be present here too. I have tried several import and export csv plugins, but nothing is working right. Is there any other plugin?
I guess I have found perfect solution for it. There is a plugin called **_Multisite User Management_**. It easily does the task. Just Activate it and go to Network Admin -> Settings -> Network Settings Then there will be section called **Multisite User Management**. Just assign the role (which is to be given to users) for that particular site. And Save it, automatically all users will be copied to the new site.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, multisite, users, bulk import" }
Custom menus displaying all pages instead of set pages Edit, complete function - function themename_setup() { // WordPress Menu Locations register_nav_menus(array( 'primary' => esc_html__( 'Primary', 'themename' ), 'footer ' => esc_html__( 'Footer', 'themename' ), )); } add_action( 'after_setup_theme', themename_setup' ); The primary menu works exactly as expected I've set up a foot menu location in my `functions.php` file; register_nav_menus(array( 'primary' => esc_html__( 'Primary', 'themename' ), 'footer ' => esc_html__( 'Footer', 'themename' ), )); In the admin, I've created a new menu and assigned it to this new location. However, when I output this menu the menu items retrieved are all of the pages from the admin. `<?php wp_nav_menu(array('theme_location' => 'footer')); ?>` I only want the pages that have been assigned to this menu
It's pretty easy then... And it works exactly how it should... You register menu `'footer '` \- there's a space at the end (so you have two locations defined `'primary'` and `'footer '`). And then you use it as `'footer'` \- without that space. There is no such location defined anywhere ;)
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "functions, menus" }
How to get WordPress Username in Array format I want to create an Autocomplete function in WordPress. I want a search field from where **username** can be searched. I am using following JQuery UI. <label>Users</label> <input type="text" name="user_name" id="user-name" /> <?php $get_arr_user = array('John', 'Rogers', 'Paul', 'Amanda', 'Peter'); ?> <script> jQuery(document).ready(function($) { var availableTags = <?php echo json_encode($get_arr_user); ?>; $( "#user-name" ).autocomplete({ source: availableTags }); }); </script> My problem is that I am not able to get the list of **Usernames** in this format - `array('John', 'Rogers', 'Paul', 'Amanda', 'Peter');` How do I get that?
The other answers are correct, but it's possible to achive the same thing with less code using `wp_list_pluck()`: $users = get_users(); $user_names = wp_list_pluck( $users, 'display_name' ); `wp_list_pluck()` used that way will get the `display_name` field of all the users in an array without needing to do a loop.
stackexchange-wordpress
{ "answer_score": 16, "question_score": 11, "tags": "users" }
Exact Hook to payment methods I'm using this hook `woocommerce_order_status_processing` to check if an order is payed and update the user with a memberplan. The problem is that manual update, acessing _woocommerce menu > orders > change status_ from any to processing works, but when the online payment returns and change the status programatically appears that the hook `woocommerce_order_status_processing` is not being used and my client's status is not being changed. How I can find which hook I need to use? Someone have a tip?
Like I said before change manually the data through admin works well with the `woocommerce_order_status_processing` hook. But the gateway I'm using was using other method and consequently other hook. The right hook is `woocommerce_update_order`. Inside this hook was needed to use a conditional check if the `status` change to processing. public function create_memberplan_after_update_order($order){ $order = wc_get_order($order); if ($order->data['status'] == 'processing') { //update user when status is changed to processing } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, woocommerce offtopic" }
Force the “Choose from the most used tags” meta box section to always be expanded I'm looking to have the "most used tags" link within the tag meta box on the post page always be expanded. Couldn't find any helpful plugins to use. I did find this previous post but the function doesn't seem to be working anymore - I'm wondering if something has changed since that was in 2012.
You can do this using jQuery. First of all, you need to add your script into your `functions.php` function my_theme_scripts() { wp_enqueue_script( 'expand-tags', get_site_url() . '/js/expand-tags.js', array( 'jquery' ), '1.0.0', true ); } add_action( 'admin_enqueue_scripts', 'my_theme_scripts' ); Then, in your file (`expand-tags.js`) which is located on, for example, `public_html/mysite/js/`, you will have to have something like this: $(document).ready(function() { $("#link-post_tag").trigger("click"); }); **link-post_tag** is the ID of the _Choose from the most used tags_ button, so when the page is loaded, a button click will be triggered.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, functions, taxonomy, post meta" }
Unfamiliar query string in Google Search Console URL not found An old client site was hacked. After deleting the old site and rebuilding a new site, the Google Search Console has quite a few (50 or so) URL not found with this address pattern. > /category/business/%3C?php%20bloginfo('rss2_url');%20?%3E I understand that it may reference the default rss function in WordPress, but some of the characters seem suspicious. Are these addresses that are standard to WordPress? Are these addresses possible caused by the compromised code? If so, what are the indicators?
It's not a standar URL for sure. That kind of URLs are most likely due to the compromised code, so there is no need to do anything with then but remove every trace it left. Since the site is clean now, you should just remove those URLs from the Google Search Console. 1. Log into the Google Search Console and select the desired website 2. Click on **Google Index** in the left-hand navigation 3. Click on **Remove URL** in the sub-menu 4. Click on the button **Temporarily Hide** on this page ![enter image description here]( You will now be asked to type in the URL of the page that you want to be removed and confirm your choice by clicking on **continue**. ![enter image description here]( Done. Now you have to wait some time until the desired URL is removed from Google’s index.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "rss, hacked, google" }
How can I display all post IDs from the taxonomy? I try echo on any page (I mean page on my site) all post IDs what I have in my taxonomy. I found this: get a list of posts from Custom Taxonomy But I could not handle with it. I want to echo all currently published post IDs what the taxonomy contains. Name taxonomy = 'agency' Post type = 'job_listing' <input value="<?php echo $idsTaxonomy"?> And I would see output example: 420, 16, 5 Somone could help me? **Thank you for help.**
Just some code to get started. This will get you all the IDs for job_listings that are assigned to term 4 in your taxonomy. <?php $posts = get_posts( array( 'posts_per_page' => -1, 'fields' => 'ids', 'post_type' => 'job_listing', 'tax_query' => array( array( 'taxonomy' => 'agency', 'field' => 'term_id', 'terms' => 4 ) ) ) ); echo implode( ', ', $posts ); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom taxonomy, advanced taxonomy queries" }
Displaying Posts by tag dynamically in Wordpress How do I come about to display posts related to a random tag? When I click a tag and directed to tag.php page I want all posts related to the previously clicked tag to be displayed. I have seen a lot of example like this: <?php $args = array( 'numberposts' => 3, 'post_status' => 'publish', 'tag' => 'travel' //how to give a dynamic value ); but I would want 'tag' to be assign dynamically as to whatever tag I click.
The tag.php template shouldn't use a custom query for its posts at all. When you visit the link to a tag the main query is automatically populated with posts that have that tag. In the template you output the main query with the standard loop. <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> ... Display post content <?php endwhile; ?> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "tags" }
Remove WordPress theme from a specific page There is a site with WordPress installed and a theme selected. I have created an HTML page for the site, but it wasn't looking well with the theme. So, I want to put the page on the site without any theme, and just the way I wrote the code, without disabling the theme from any other pages. Is there an easy way to do it without messing with the theme? And if there isn't, then I am willing to modify theme files, but how should I go about it?
There is, in fact, a way to do it without messing with the theme, let's say your WordPress is on `public_html/your_site`, now you want to create an HTML page that is on `your_site.com/mypage`, so instead of creating a page or post called `mypage` on your WordPress dashboard you are going to create a **mypage.html** and upload it to `public_html/your_site`, in case you want to get rid of the .html you can simply hide it from your **.htaccess** doing something like: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+)$ $1.html [NC,L] Keep in mind any tracking code you have on your WordPress, for example, Google Analytics, if you are using things like that you will have to add those codes to your HTML page as well.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 7, "tags": "customization, child pages" }
Function to activate WordPress theme inside a plugin I am creating a plugin that generates a theme, and so I want to have a checkbox at the end of the theme generation process that gives the possibility to activate the freshly created theme without having to do it manually. Is there any function that can do that?
Of course there’s a function for that (Codex): switch_theme( $stylesheet ) It: > Switches current theme to new template and stylesheet names. Accepts one argument: $stylesheet of the theme. ($stylesheet is the name of your folder slug. It's the same value that you'd use for a child theme, something like `twentythirteen`.) It also accepts an additional function signature of two arguments: $template then $stylesheet. This is for backwards compatibility. And why is that any better? WordPress uses filters and actions for many things. For example, when you switch the theme, the unused widgets will get saved, so you can restore them in new sidebars... All of that won’t be done, if you switch the theme directly in DB.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "plugins, plugin development, theme development, child theme, activation" }
Problem with $wpdb I was trying to learn to use $wpdb but I don't know why it's not working. <?php /* Plugin Name: TEST */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } function ctz_show(){ global $wpdb; $table = "${$wpdb->prefix}postmeta"; $query = "SELECT * FROM $table"; $results = $wpdb->get_results($query); var_dump($results); } add_shortcode( 'cotizador', 'ctz_show' ); The output is always > array(0) { } Even if I change the name of the table.
Try this, it should work much better ;) $table = "{$wpdb->prefix}postmeta"; $query = "SELECT * FROM {$table}";
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins" }
WordPress search and date filter not working with custom post type I have a custom post type registered in my WordPress. Everything is working fine except Search and Filter functions are not working in admin. For example, I have posts from 2013 but when I select 2013 from filter drop-down, I get nothing.
Are you using any `pre_get_posts` hooks in your theme that might be affecting things? I've found that when the listing in the admin is screwed up, it's usually some other code snippet or plugin that is causing the issue.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, search" }
Adding a title below the logo I need to add a site title as a text below the logo for a site. The title should be `<h2>` tag. The theme allows either image or text, but not both.
You will have to customize the `header.php` of your theme (from **Appearancece > Editor** ), I recommend you create a child theme first and then find **#logo** within the header.php and add the title below the logo. I cannot show you exactly how since I don't know the `header.php` of your theme, but after you find the where the logo is generated **#logo** you will know where to place your title. <h2>Your title</h2>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "child theme, title" }
Is it possible to duplicate users on a new Wordpress install? I have a running site (Site A). I want to re-write the site fully to improve everything but, when I'm finished, I don't want to have to get everyone to sign up to the new site. I wondered if I could create an entirely new site on a different domain (Site B) with a clean install of Wordpress - and then when I'm finished developing the site copy over the following tables from Site A to Site B: wp_options wp_users wp_usermeta And would all my existing users then have full access to Site B (the new site) ? Or is there more to it than this? Thanks
Migrate DB Pro can help with this, make sure to migrate any plugin tables and the WP_Users and WP_Usermeta tables if your users make posts and you want that content to remain assigned an available make sure to keep WP_Posts and WP_Postmeta table as well. < Also keep in mind that WP uses an EAV (Entity Attribute Value) architecture for pretty much everything User and Content related so if you have a ton of users it will take time or possibly crash. I run a site with 100K registered users and I have no problems with this process using MigrateDBPro but I know that larger sites would have problems.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "users, domain" }
force customers to add only single item to card per purchase EDD Is there any way to force Easy Digital Downloads customers to add only single item to card per purchase? In other words, disable shopping card "completely", So that when a customer touches the download button of an item, if he returns to the download archive page, it will be deleted from his shopping cart. Thanks!
I searched a lot and find a way to do it. add following to theme functions.php file: add_filter( 'edd_pre_add_to_cart_contents', '__return_false' ); Source: < Thanks!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, php, customization" }
get user id in a plugin without a function I have an admin page, in the callback of this admin page, i need to query into current user's posts. So let's assume this is my function to add menu page: add_menu_page( 'My billings ', 'Billings', 'manage_options', 'billings', 'billings_html', 'dashicons-analytics' ); And this is the callback function : function billings_html() { $user_id = get_current_user_id(); $barbershops = new WP_Query( array( 'author' => $user_id, 'post_type' => 'barbershop' ) ); print_r( $barbershops ); } I need to mention that my code is in plugin. I can't wrap my code to get the ID in a function and run it with an action. As you know, this is the error i get: Uncaught Error: Call to undefined function wp_get_current_user() ... I don't know how to get the user id in this plugin.
i think it's correct. just add add_action('init','billings_html');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users" }
Use the wordpress admin table I want to create a custom page, which uses the GUI from wordpress, so I don't have to use my own. I want to take the table from wordpress posts and using to display my own information (hidden custom post or any other database) ![Example](
Include and extend the WP_List_Table class `class Example_List_Table extends WP_List_Table` Best way to learn this is to modify the custom list table plugin: < For a full tutorial check this out: < And read the codex here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "admin" }
How can I pick a single post from the latest 3? I'm looking to display a single featured post from my latest 3 posts at random. I've managed to get it up and running picking any post at random just fine, but I want to filter it down to only the latest 3. <?php $args = array( 'post_type' => 'post', 'orderby' => 'rand', 'posts_per_page' => 1, 'post_status' => 'publish' ); $rand_query = new WP_Query( $args ); if ( $rand_query->have_posts() ) : while ( $rand_query->have_posts() ) : $rand_query->the_post(); ?> // DIV FOR SINGLE FEATURED POST HERE // etc... Obviously, if I change the posts_per_page to 3 I then get 3 divs containing featured post previews. I only want the one post that is picked at random from those last 3. A date query won't work as the posts aren't regular.
Here's my approach... First you have to select 3 latest posts, then you have to pick random one of them... But it's easier to shuffle selected posts than picking only one of them - that way you can still use normal loop: <?php $args = array( 'post_type' => 'post', 'posts_per_page' => 3, 'post_status' => 'publish' ); $rand_query = new WP_Query( $args ); shuffle( $rand_query->posts ); if ( $rand_query->have_posts() ) : while ( $rand_query->have_posts() ) : $rand_query->the_post(); ?> // HERE GOES THE DIV WITH POST <?php break; // we want only one post to be shown, so we break the loop endwhile; endif; ?>
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "wp query, query posts, order, array, post type" }
How to add custom classes to the customizer panels, sections or controls? I must add custom classes to the customizer panels, sections and controls. I checked the WP Codex, but I didn't find any information. How to do it?
The customizer is rendered by several classes. Let's look, for instance, at panels, which are generated by a function called `render_template` in the file WordPress Customize Panel class. As you can see the function hardcodes the `html`. You might be able to manipulate the json object from which a part of the class variables is taken, but I wouldn't count on it. In any case you're not supposed to mess with this, as indicated by the function being 'protected', and doing so might lead to unexpected results. So, there is no native way to do what you want. That said, you can of course go around this by adding a script file to the customizer, which adds classes to certain panels/sections/controls on the user end.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme customizer" }
Override Admin menu icon I have created set of icons that I want to replace Wordpress admin menu icons. I am wondering what is the best approach to force Wordpress to use my icons instead of the default?
One way is to use the admin_menu hook to insert CSS with your selection of menu icons (which use the DashIcons). The googles show this recent result: < . Here's some code from there; you'll just need to figure out the CSS for each menu item - use your Developer inspection tools (F12, usually) to inspect each element to find it's CSS class: function replace_admin_menu_icons_css() { ?> <style> /* CSS code goes here */ </style> <?php } add_action( 'admin_head', 'replace_admin_menu_icons_css' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, wp admin, templates, admin css" }
How to change menu labels What is the best approach to changing admin menu labels? As part of my first step in modifying the admin area, I would like to know how I can change **WooCommerce** label to **Shop**?
In order to change the menu labels you will have to go to add this code into your `functions.php`: add_filter( 'gettext', 'change_woocommerce_text' ); function change_woocommerce_text( $translated ) { $translated = str_replace( 'WooCommerce', 'Store', $translated ); return $translated; } Tested.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, functions, wp admin, wp enqueue style" }
How to display only first value of database column in WordPress I have following foreach loop code... <?php $usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" ); foreach ( $usernames as $username ) { echo $username->user_name; } ?> When I use `echo $username->user_name;` it displays all the usernames from the `user_name` column of database. I want to display only the first username from the list. How to do... Pl help... Thanks...
I have found the solution... Here it is... <?php $usernames = $wpdb->get_results( "SELECT user_name FROM wpxa_project_members WHERE project_id = 698" ); foreach ( $usernames as $username ) { $member_username[] = $username->user_name; } echo $member_username[0]; ?> Hope it may help other users.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "php, wpdb" }
how to get woocommerce product attribute slug I am trying to get product attribute slug. I have used below code but it display name. echo $_product->get_attribute( 'pa_color' ); I am working on woocommerce/cart/cart.php file in theme folder. Also I checked this is coming in anchor url of product image in cart page but not getting it **anchor url** : I am working on this from today morning but I have not get success. Please guide. ![enter image description here](
I got this.... To get slug use: $attributes = $_product->get_attributes(); $pa_color = $attributes["pa_color"]; Thanks to all for helping me.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "woocommerce offtopic" }
WP Cli - post add meta in xargs after wp post generate - add multiple fields This command will generate posts and create a field with key "bar" and value "foo" wp post generate --format=ids --count=10 | xargs -d ' ' -I % wp post meta add % foo bar This does not seem to work: wp post generate --format=ids --count=10 | xargs -d ' ' -I % wp post meta add % foo bar ; wp post meta add % key_2 value_2 How could create 2 meta fields and values after the wp post generate command?
You just need to change the syntax of `xargs` to run multiple commands using the same placeholder: `wp post generate --format=ids --count=10 | sed -e "s/ /\n/g" | xargs -n1 -I % sh -c 'echo "Adding fields for %"; wp post meta add % foo bar; wp post meta add % key_2 value_2'; ` **Update** : The output of `wp post generate` is post ids with spaces for the delimiter. I'm sure there is a better way for xargs to process spaces but I'm using `sed` to replace the spaces with newlines. Reference: * < * < * <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, wp cli, automation" }
How to display certain category in the loop from WordPress default post type? I want to display a certain category from WordPress post type, but it is not showing... Here is my quote. it displays all posts instead of "wedding venue" category post. <?php $args = array( 'post_type' => 'post', 'category_name' => 'wedding-venue', 'posts_per_page' => 8, 'facetwp' => true, ); $query = new WP_Query( $args ); ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> //loop content here <?php endwhile; endif; ?> <?php wp_reset_postdata(); ?>
Of course it displays all posts... You create your own custom WP_Query, but then you ignore it and use global one ;) Here’s the correct code: <?php $args = array( 'post_type' => 'post', 'category_name' => 'wedding-venue', 'posts_per_page' => 8, 'facetwp' => true, ); $query = new WP_Query( $args ); ?> <?php if ( $query->have_posts() ) : while ( $query-> have_posts() ) : $query-> the_post(); ?> //loop content here <?php endwhile; wp_reset_postdata(); // this should be inside if - there is no need to rested postdata if the_post hasn’t been called. endif; ?> PS. Remember, that if you want to modify posts that are displayed in main loop, you should use pre_get_posts action - creating your own query is redundant...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "query posts" }
How to remove howdy dropdown menu content ![enter image description here]( I would like to know how I can remove content inside .ab-sub-wrapper but keep Log Out and Edit My Profile links? Just want to keep thing nice and tidy
You can use wordpress nodes to customize profile menu. **Add this in`functions.php`** add_action( 'admin_bar_menu', 'remove_my_account', 999 ); function remove_my_account( $wp_admin_bar ) { $wp_admin_bar->remove_node( 'my-account' ); } add_action( 'admin_bar_menu', 'add_logout', 999 ); function add_logout( $wp_admin_bar ) { $args = array( 'id' => 'logout', // id of the existing child node (New > Post) 'title' => 'Logout', // alter the title of existing node 'parent' => 'top-secondary', // set parent ); $wp_admin_bar->add_node( $args ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, themes, wp admin, templates" }
Why does WordPress hide the reset password key from the URL? I'm currently working on a WordPress plugin of my own that involves a custom login interface. I'm wondering, why is it that when you reset your password on WP-Admin, WordPress stores the reset password key in a cookie rather retrieve it from the URL through `$_GET`? For example, if your reset link is ` the link will store `$_GET['key']` and `$_GET['login']` in a cookie and serve you this page using the cookie: ` Are there any security reasons for doing that?
To be honest? It's a little bit hard to say... This behavior was introduced in 3.9.2 (which is security release). Here's the bug in Trac: 29060: Don't pass around the resetpass key, but there isn't much info on why was it introduced in the bug report. Is it for security reasons? Most probably. But does it really make the process more secure? It's a little bit hard to say... Both GET params and Cookies are sent in every request - so attacker still can intercept them. It just makes such attempts a little bit harder (since you have to get pass_key and it's hashed value).
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "login" }
Show all tags within a category? How can I display a list of tags within a category page? So my **_URL_** would look something like this. Then it would display only posts from that category, and that tag on the page?
The best way to do that would be to create a custom page template, and make a custom loop that would only display the posts in you specific category and tag. For example: global $wp_query; $args = array( 'category__and' => 'category', 'tag__in' => 'post_tag', //Enter tag id for this field (not tah name) 'posts_per_page' => -1); //Gets all posts $posts = get_posts($args); foreach ($posts as $post) : endforeach;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, categories" }