INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
HOW do you Redirect buddypress login to EDIT tab not PROFILE tab on profile page? HOW do you Redirect buddypress login to EDIT tab not PROFILE tab on profile page?
You could try... function admin_default_page() { global $user; return bp_core_get_user_domain( $user->ID ).'/groups/'; } add_filter('login_redirect', 'admin_default_page'); Or a plugin... BuddyPress Login Redirect to Profile
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, login, buddypress" }
Homepage not loading correctly, but then loads when refreshing When going to our homepage (www.whiteskitchen.co.uk). We seem to have lost the styling on the homepage. I checked the source code and it’s not fully loading the page. When you refresh the page or click on a link, the page reverts to the correct theme styling and loads correctly. The stylings are very different and you’ll notice the difference Any ideas what it could be? It only started happening a couple of days ago and no updates or changes have been made before or after the issue cropped up The site I need help with is <
I think that there is a problem with the cache. Try clearing the cache with plugins, like WP Super Cache. Follow these steps: 1. Install and activate WP Super Cache. 2. Head to **Settings > WP Super Cache**. 3. Click on **Delete Cache** button under **Delete Cached Pages**. It should fix your issue. However, if you are still experiencing the styling problem in your homepage, there must be an issue with the theme.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp enqueue style, css" }
Trigger action when submitting form with WPForms A customer of mine uses the WPForms plugin to create a front-end form. When the form is submitted the entry goes in de database (in a separate table wp_wpform_entries or something like that, all handled by the plugin). But they also want to post all data to another website in JSON format. Is there a way to know the form is submitted or is the best way to use the `add_filter('wp_insert_post)?`
I would suggest you to use the action `wpforms_process_entry_save`. add_action('wpforms_process_entry_save', 'your_submit_json_function', 10, 4); Check the `actions` list here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "forms, json" }
Are gutenberg blocks ideally supposed to look the same in both back-end and front-end? This appears to be the case with built in blocks at the moment. If you use them with default Twenty Nineteen theme you get the same look in both backend and frontend When building custom theme, should we make sure blocks are identical in both cases? It seems that this requires loading the same CSS frameworks and JS in back-end and front-end
Ideally, yes. Blocks are supposed to be WYSIWYG. See the Editor Styles section of the Gutenberg Handbook for how to load theme styles in the editor. You need to add an editor stylesheet with `add_editor_style()`, the same way you did with the previous editor, but to support the block editor you need to declare theme support for editor styles: add_theme_support( 'editor-styles' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "block editor" }
unordered list loop not showing up in sidebar I have a custom sidebar named "sidebar-events" that should only display posts in the "Events" category. I placed the following code in the sidebar. The header appears, but not the unordered list. In the source code there's nothing - no ul, no li. What am I doing wrong? <div id="sidebar" class="widgets-area"> <h2>What's Going On</h2> <?php //what I will be looking for $args = array( "type" => post, "posts_per_page" => 5, "category_name" => "Events" ); //create new query and pass the arguments $recentEvents = new WP_Query($args); if( $recentEvents->have_posts() ): ?> <ul> <?php while( $recentEvents->have_posts() ): $recentEvents->the_post(); ?> <li><?php the_title(); ?></li> <?php endwhile; ?> </ul> <?php endif; wp_reset_postdata(); ?>
You want to use post_type instead of just type and put apostrophes around your post type itself. Instead of this: $args = array( "type" => post, "posts_per_page" => 5, "category_name" => "Events" ); I would do this: $args = array( 'post_type' => 'post', 'posts_per_page' => 5, 'category_name' => 'Events', );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sidebar" }
Fatal error: Call to undefined method WooCommerce::nonce_field() I am getting an error on the cart page " **Call to undefined method WooCommerce::nonce_field()** ". **Fatal error: Call to undefined method WooCommerce::nonce_field() in C:\xampp\htdocs\stemorg\wp-content\themes\breeze-child\woocommerce\cart\cart.php on line 120** cart.php on line 120 here is the code: **$woocommerce->nonce_field('cart');** I am very tired of this error. Please, anyone, help me how to fix this error. Thanks in advance
The Products section in wp-admin panel doesn’t depend on the theme. If you select default WordPress theme you’ll see the same issue. This is WordPress configuration. To fix the errors you need edit files via FTP, open the file wp-content/themes/your_theme/woocommerce/cart/shipping-calculator.php on line 67 and replace $woocommerce->nonce_field with wp_nonce_field and the file wp-content/themes/your_theme/woocommerce/checkout/form-checkout.php on line 3 and replace $woocommerce->show_messages(); with wc_print_notices();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic" }
Whether an <html >tag is required in header? can i have a structure like below? <div> <head> </head> <html> <body> <body </html> <footer> </footer> </div> I am asking this because elementor theme editor when ever some content is placed it creates `<html><body>`...if i put `<html>`in header.php this results in validation failure in validator.w3.org
**Can you have such structure?** Yes, you can have such structure. **Is it valid HTML code?** No, it is not. **Will the browser render it correctly?** Most of the browsers deal with code errors pretty well. So yes - I guess it will render correctly, but it's hard to say what errors will it cause later on. It may cause some JS libraries to work incorrectly, and so on. **Should you write such code?** No, definitely not. It's invalid, so it's an error and should be fixed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, html" }
Sidebar by Category Conditional Statement not functioning I have two categories for my posts, "event" and "long-term-leasing." I have sidebar-events.php and sidebar-long-term.php. I wrote a conditional statement in single.php, but when I view a post it only shows me the generic sidebar. I did a copy/paste of the categories to avoid typos. Where is my mistake? <?php if (is_category("event")) { get_sidebar('events'); } elseif (is_category('long-term-leasing')) { get_sidebar('long-term'); } else { get_sidebar(); } ?>
Try `has_category`, instead; `is_category` is used for archive pages, not single posts.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, sidebar, conditional tags" }
How to check, if user commented before, on comment_post action? I want check, if user commented post, in comment_post action. So i make this: function checkUserComment( $comment_ID ) { $comment = get_comment( $comment_ID ); $postID = $comment->comment_post_ID; $authorID = $comment->user_id; // If user commented this post already, don't update post meta. if( get_comments( array( 'post_id' => $postID, 'user_id' => $authorID ) ) ) return; update_post_meta($postID, 'testMeta', 'testValue'); } add_action( 'comment_post', 'checkUserComment', 10, 2 ); It must doesn't update post_meta if user comments first time. But it updates post_meta anyway.
From the WordPress Codex: comment_post is an action triggered immediately after a comment is inserted into the database. Instead, I think what you want to try is to hook into preprocess_comment and not comment_post.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, actions" }
Handling Body class based on Template Through a **PHP function** , I think I can handle body class, but I think **WordPress** would have some specific way to handle it. If `Home.php` then class in the body should be `wbody` else it should be `bgody`. As I said I can write **PHP functions** to print class based on the template, but Is there a more precise way to do this in the case of **WordPress**?
I'm not sure if I understand your question correctly, but... If you want to set body classes based on current page, then you can use this code function my_body_class( $classes ) { if ( is_home() ) { $classes[] = 'wbody'; } else { $classes[] = 'gbody'; } return $classes; } add_filter( 'body_class', 'my_body_class' ); Of course you can use other conditions in there and the list of Conditional Tags might come in handy to.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, functions, filters, hooks, body class" }
How to get URL for the first page of post archive I would like to get the first page of an archive. I have an archive with events. /events display events, which are not finished yet. /events?past display past events. I use `get/remove_query_arg` to generate an URL for a link, so that users can switch between past and future events. The problem is, if user is at page x in past events and try to switch to future events. Future events may not have the page x. This results in an error. URL is generated like this: esc_url(remove_query_arg('past')) esc_url(add_query_arg('past', '')) This method preserves the page number within the URL: at `/events/page/88?past` URL for future events becomes `/events/page/88`, which doesn't exist. I was wondering if there is a "WordPress way" of doing this?
You can get link to post type archive using... ‘get_post_type_archive_link’ function: esc_url(add_query_arg('past', '', get_post_type_archive_link('events')));
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "urls, paginate links" }
How to render core component inside edit() within custom registered block in Gutenberg? How to render core block such as `core/columns` inside custom registered block in Gutenberg? I found this as an example, but I don't really understand how to render it inside my own block with `edit()`. I thought of using something like `createBlock('core/columns')`, but it gives an error on render.
You can make use of components inside your block. However, to insert a block inside your block you need to make use of the editor component **Innerblocks**. Using it you can set a predefined template which includes certain blocks in a specific order. Or you can set allowed blocks that can be added by the user. For example, the `columns block` uses Innerblocks component and includes the `column block` using the template prop, which uses again Innerblocks to allow any kind of block to be added inside each column.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "block editor" }
Wordpress: How to create custom REST API route? How can we create custom REST API route for sending specific data format to **Android** or **IOS** app ?
We can create route using `rest_api_init` action like : Simply add below code to your theme `functions.php` file. add_action( 'rest_api_init', function () { register_rest_route('wp/v2', 'forgot_password', array( 'methods' => array('GET', 'POST'), 'callback' => 'forgot_password' )); } ); function forgot_password(){ // YOUR CALLBACK FUNCTION STUFF HERE } **forgot_password** will define route URL address. **methods** will define which method u want get request parameters like **GET** or **POST**. **callback** will define callback function which is call when rest api will fire.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "rest api" }
Looking for a simple tool to update a table What I would like. A server generates row entries every now and then. I want this entry to be sent to my WordPress site and inserted as a row in a table. How would I accomplish this as simply and securely as possible. My knowledge of WordPress development is in its infancy stage. Thanks.
WordPress has an API available to allow external scripts to get data from your website and to add (POST) data to your website. You can create a custom API endpoint where you receive the data from the other server and in a simple function create a new record in the WordPress database: 1. Create a function in your functions.php to create a new record in the tablet. 2. Add the new API endpoint in your functions.php I know this is a very summarized explanation, but I hope this gets you in the right direction?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "table" }
Wordpress navbar with logo in middle I was searching for something that could help me with query but could not find a understandable solution. What I am trying to do is show the site logo in the center of menu. I have checked the split option and others but they all lack the responsiveness or we need to setup 2 menus (left and right sides of logo) to get 1 final menu. Is there any better solution out there? An example will be appreciated...
You should use Walker to make it easier. Please read more detail to know it and try to research again :D Link: < Tut: < And this is my website, I completed it using Menu Walker. The link below :D Link: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, menus, logo" }
How to exclude posts for current user How can I hide posts that are in an array of ids in the `usermeta` for the current user in the `main query`. I can use `post__not_in` in `meta_query` but I do not know which option to use for only a specific user. I think should use `posts_where`?
I'm not entirely sure what the problem is, because you've already mentioned all the tools that you need to solve it... Just use `pre_get_posts` filter, check if the user is logged in, get the IDs of posts he should not see and exclude them in query: function remove_some_posts_for_user( $query ) { if ( ! is_admin() && is_user_logged_in() && $query->is_main_query() ) { $posts_to_remove_for_current_user = get_user_meta( get_current_user_id(), 'posts_to_remove', true ); if ( ! empty($posts_to_remove_for_current_user) is_array($posts_to_remove_for_current_user) ) { $query->set( 'post__not_in', $posts_to_remove_for_current_user ); } } } add_action( 'pre_get_posts', 'remove_some_posts_for_user' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query, user meta, posts where" }
Should I manually resolve WP Core File security issues or await a subsequent WP release? Using the Google Developer Tools, I can see that some of WordPress' JavaScript Libraries contain known security vulnerabilities; some a few months old. With this in mind, should I consider addressing these issues myself or could this result in unexpected results across the WordPress powered website? Given its notification on Google's Developer Tools, I would suspect it would be something that WordPress would be aware of. That being said, is there a way to see if WordPress are aware of certain security issues and whether they will be addressed in subsequent WordPress releases?
Most of the time you should not modify core by yourself - it will get overwritten after update and it may cause some conflicts. Of course, if you know what you're doing and the vulnerability is really serious, then you can update given library and test everything by yourself. As for awareness. Most of the times WP is very aware of vulnerabilities in its code and fixes them with minor releases. You can check if the problem is known and if it has a ticket in Trac: * < And if you can't find anything, you can always report it: * < * <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, security, front end, library" }
Using concatenate with WordPress Thumbnail Hi can someone explain me why the thumbnail is showing outside from the div? am i using the function correctly to concatenate the thumbnail inside the $list. BTW im running this code inside a shortcode that's why i use a concatenate function. $list = ""; $list = " <div class='box'> ". the_post_thumbnail('post-thumbnail') . "</div>";
`the_post_thumbnail` function echoes the result and does not return anything. If you want to concatenate it this way, you should use `wp_get_attachment_image` instead. $list .= '<div>'. wp_get_attachment_image( get_post_thumbnail_id(), 'post-thumbnail' ) . '</div>';
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "post thumbnails" }
Why 2 home pages? All my site in WP have to 2 home pages in jet pack stats, any idea why ? < <
**"Home"** and **"Home page / archives"** are not the same thing. Instead, they are different. If you have a static front page on your site, the **“Home page / Archives”** item in your stats can refer to a couple things: * Your blog (posts) page, if you have one for your site * Any blog archives page, such as posts from a particular month, in a particular category, or by a particular author
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "homepage, plugin jetpack" }
How to make Media Library use HTTPS? I'm redesigning a site that originally didn't have a SSL. I copied the uploads directory, then did regular expressions on the `wp db export` file from the original site. In the Media Library, none of the thumbnails are showing up. ![ ]( ![ ]( In the developer console it is showing a bunch of requests to the root of the domain, rather than having the image names. ![ ]( If I go to the URL that shows up in the inspector and use the `https` version, the image appears. ![ ]( I've already tried `wp media regenerate`, but they still are not showing up. Where do I need to go to change the protocol the media library is using?
Okay, the issue was my last regular expression that changed the `http:` to `https:` did not save. I reran the expression again and refreshed the page and it worked. Here's the gist of how to do this (with wp cli) for anyone who comes across this. In the original site directory: wp db export This should create a `.sql` file with the original database name and a hash, like `db_name-324ddsx9.sql`. FTP that file to your new server/install directory. Then edit it with vi and perform the search and replace. You want to replace all instances of the original domain with the new one. sudo vi db_name-324ddsx9.sql :%s/oldsite_name.com/newsite_name.com/g :%s/http\:\/\/newsite/https\:\/\/newsite/g :wq If you haven't already, create the mysql database. Then from the command line - import the sql. mysql -u root -p database_name < db_name-324ddsx9.sql And that should have you set to go.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, media library, import, migration" }
All content is HTTPS, but browsers warn of HTTP mixed content Previously Chrome, Firefox, Edge, and other browsers showed our site as fully SSL/HTTPS secure. For some reason, they now warn about mixed content. But the content in question seems to be secure. This only affects a subset of the images on each page. Here's one example--a footer image. The image is entered like this on the WP back-end: <img src=" /> Firebug > Inspect Element shows: <img src=" Firefox > View Source shows: <img src=" /> But Firebug > Network tab > Protocol column reports the image as: HTTP/1.1 Chrome developer tools show the same results. What could cause this problem?
You have "www.wisconsinwetlands.org" URLs redirecting to insecure "< The cases you have used these is in the images on the page. Every image that is set as "< redirects to the insecure version. So while you do need to fix that and correctly configure your setup so that both "www" and non-www URLs are secure, you could quickly solve the problem by removing the www from your image URLs.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "ssl, https, http" }
Add classname to Gutenberg block wrapper in the editor? I'm trying to create custom columns block in Gutenberg. Is it possible to add class to the wrapper of the element in the editor based on the attributes? I'd like to switch `???` to class based e.g. `columns-4`. Otherwise it's not possible to use `flex`. <div id="..." class="wp-block editor-block-list__block ???" data-type="my-blocks/column" tabindex="0" aria-label="Block: Single Column"> <div> <div class="this-can-be-set-in-edit-or-attributes"> ... </div> </div> </div>
Actually it can be done with the filter: const { createHigherOrderComponent } = wp.compose; const withCustomClassName = createHigherOrderComponent( ( BlockListBlock ) => { return ( props ) => { if(props.attributes.size) { return <BlockListBlock { ...props } className={ "block-" + props.attributes.size } />; } else { return <BlockListBlock {...props} /> } }; }, 'withClientIdClassName' ); wp.hooks.addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withCustomClassName );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "block editor" }
Why does AWStats show /wp-json* as Viewed URLs Generally, I track site resource usage using Google Analytics. Recently, I needed to check a clients site stats through AWStats instead. I noticed a number of URLs starting with /wp-json ... My client uses FTP for a few web tasks and will not see those files in the directory structure. The fact that these record start with wp- is likely to be a source of confusion. While I understand that this is tied to the REST API in /wp-includes, I need to give my client a better explanation because I will be sharing those stats with her.
I'm not entirely sure what will be better explanation, or why this one (the real one) is not enough. In your stats you see URLs of requests and not paths to files. URL has nothing to do with files on server. Yes - if the requests targets physical file, then that file exists, but... There are plenty URLs that are not connected to any file - mod_rewrite takes care of them. For example there is no directory like `/rss/` anywhere in your WP installation directory. There is no directory like `/category/uncaregorized/`, and yet - both of these URLs work and you can find them in stats... I don't see anything wrong in explaining, that your client sees HTTP requests and not file paths. And these `/wp-json/*` requests are requests to WP REST API. PS. You don't see them in Google Analytics, because there is no tracking code in REST API, so there requests are not logged to GA. But AWStats are more like server logs, so all requests get logged.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "rest api, json" }
How to create 450 categories in wp I am having trouble to find a way for how to add categories for all the products. I have Apple, Samsung, Sony, Xiaomi, Huawei categories and each of there needs subcategories which will stand for models, and also specific part. example of category tree: Apple>Iphone 6s>Iphone 6s battery Apple>Iphone 6s>Iphone 6s replacement screen> Apple>Iphone 8>Iphone 8 battery etc All the products needs to be in separated category so I can show correct item under correct menu item and no other Iphone stuff, only the battery for example. How do I create 500+ categories which will represent all the items we have got? I was thinking to export existing database and edit in text editor and write all the categories there as it would be simpler then using category manager inside WordPress cpanel which is very bad for this, as I am getting lost of what is in there and what isn't. Do you think it will work this way? Or what do you suggest? Thanks!
You can try using BulkPress. It allows you to create hundreds of categories very easily. Follow these steps: 1. Install and activate the plugin. 2. In the left side bar, hover your cursor on **Bulkpress**. Then click on **Terms**. 3. A new page will appear. In **Taxonomy** field, choose **Category**. 4. Insert your **Categories** in the **Terms** field. 5. Choose your desired **Parent** , if required. 6. Finally, click on the **Add Terms** button.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "categories, mysql" }
Created blank theme for REST API, featured image not appearing on admin side I have a blank theme purely to redirect to my custom front-end. I created a `functions.php` and put `add_theme_support()` inside it and to no avail. index.php: <meta content="0; URL=' http-equiv"refresh"> <!-- just in case the meta tag is not read properly, here is plan B: a JS redirect --> <script type="text/javascript"> window.location = ' </script> functions.php add_action( 'after_setup_theme', 'headless_theme_setup' ); function headless_theme_setup() { add_theme_support( 'post-thumbnails'); } // Also tried these and still didn't show //add_theme_support('post-thumbnails', array( // 'post', // 'page', //)); //add_theme_support( 'post-thumbnails' ); I refreshed the admin panel and checked under `screen options` and did not see it. I'm using WP 5.0.2.
The issue was the symbolic link between my Wordpress install in my public/ and build/ directory was out of sync. I forgot to run `yarn build` after adding the function. My directory structure is like this: site/ |__build/ |_wp/ | |__/src/ |_wp/ So the changes I made in src/ were not being compiled off the build.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, post thumbnails" }
Why activated plugin does not appearing in left side menu bar of WordPress admin area? can anyone help me i am trying to create a plugin for gallery but at the initiating a problem occurred,when i activate the plugin it activating but problem is that it does not appearing at left menu , `this is my code of plugin startup:|` <?php /* Plugin Name:JaissGallery Plugin URI:WWW.GOOGLE.COM description: >-Jaiss gallery plugin Version: 0.1 Author: Mr. Tahrid abbas Author URI: */ function doctors_gallery(){ add_menu_page( "doctorsGallery", "Doctors Gallery", "Manage_options", "DoctorsGallery", "Doc_gallery_view" ); } add_action('admin_menu','doctors_gallery'); function Doc_gallery_view(){ echo "ghfhgfgh"; } can somebody tell me please what i am missing there ?
For Menu and Submenu, ![enter image description here]( function doctors_gallery(){ add_menu_page( __( 'Doctors Gallery', 'textdomain' ), 'Doctors Gallery', 'manage_options', // The capability required for this menu to be displayed to the user. 'DoctorsGallery', 'doc_gallery_view' ); add_submenu_page( 'DoctorsGallery', __( 'Doctors Submenu Page', 'textdomain' ), __( 'Doctors Submenu', 'textdomain' ), 'manage_options', 'DoctorsSubGallery', 'doctor_submenu_callback' ); } add_action( 'admin_menu','doctors_gallery' ); function doc_gallery_view(){ echo "ghfhgfgh"; } function doctor_submenu_callback(){ echo "Sub Menu section"; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
How to replace WordPress sidebars (widget areas) with Gutenberg I'm trying to build my first Gutenberg theme, and I want to build a page template with the layout as shown below: ![template wireframe]( Pre-Gutenberg I would have built widget areas into the page template to create the layout. i.e. widget areas for the sidebar, and widget area 1 + 2. I'm trying to do this now with _blocks_ , and **I want to know what correct approach or best practise is for replacing widget areas in Gutenberg when developing themes** , could this be achieved with _InnerBlocks_ , or _NestedBlocks_? Or some other means? Can anyone point me to examples?
Like @Alvaro said, You should start building blocks for widget areas. Once Phase 2 hit the core you can just simply show the blocks in other areas. Don't bother developing for Pre-Gutenberg widgets, You will double your work load.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "templates, sidebar, block editor" }
Get Database Credentials from within the themes file I have a freelancer working on a program for me. I gave him access to the theme folder via FTP. He uploaded phpMiniAdmin to that folder and, somehow, obtained the database credentials, which he then used to sign in. How did he manage to obtain those credentials? Is there a vulnerability that can be used once you can upload files to the server?
All he needed to do is to put this PHP code in any template file and run it: var_dump(DB_NAME, DB_USER, DB_PASSWORD, DB_HOST); One line and it will print all the DB credentials. As you can see - no vulnerabilities are needed. All PHP code has access to these credentials. And it has to - otherwise it wouldn’t be able to access DB...
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "database, uploads" }
How To Pass Current Post Type ID from Single Template To Custom Page Template Having a Custoom Post Type called `movies`, I am able to get the current Post ID in my `single-movies.php` template. Now can you please let me know how I can pass this post ID from the single template to a custom page template like `page-postDetail.php` basically what I want to do is adding some more details to the post in the custom page (Like having multi single template foe one custom post type)
First of all, (you probably know this but..) you are fighting how WP is intended to work. You can not get the post ID directly in your custom page template because it is not displaying the post. So you will have to, as you said, send the post ID to the page template. The best way I can think of, to do it this way, is to send it to the new page via `GET` or `POST`. The most simple way would be to add a query string to whatever link goes to the sub-page containing the ID, which might look like this `?post_id=123`. Then, you can parse the URL query string to get the ID and use it as needed. Alternatively, you could make your CPT (Custom Post Type) structure hierarchical and set your permalink structure to `example.com/%postname%/`, then you can just add the pages as sub pages of your posts. More details here.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "single, template hierarchy" }
How to access deleted term inside delete_product_cat action I want to run some code after a product category is deleted, in that function I want to access the name of the deleted category, and according to their docs I could do this: add_action('delete_product_cat', 'sync_cat_delete', 10, 1); function sync_cat_delete($term, $tt_id, $deleted_term, $object_ids){ var_dump($deleted_term); } But when I do it, I get 500 internal server error So what could be the issue? Thanks
You get 500 error, because you’ve added your filter incorrectly... It takes 4 params, but you register it as it was using only one. add_action('delete_product_cat', 'sync_cat_delete', 10, 1); // 10 is priority, 1 is number of params to take function sync_cat_delete($term, $tt_id, $deleted_term, $object_ids){ var_dump($deleted_term); } So if you change that 1 to 4, it should be OK.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, woocommerce offtopic, hooks, actions" }
Get posts only from current calendar week I'm building a weekly leaderboard and trying to display posts from on the current calendar week Monday to Sunday. I've tried the code below, but it's only retrieving a post from today (Tuesday 1st January) and no posts from the day before (Monday 31st December). Any ideas? Thanks! $args = array( 'date_query' => array( array( 'year' => date( 'Y' ), 'week' => date( 'W' ), ), ), 'post_type' => 'ride', 'posts_per_page' => 99, 'order' => 'DEC', ); $leaders = new WP_Query( $args );
I think I know what happens here... Most probably that Monday is another week - last one in 2018, and it makes sense. Last day of 2018 can’t be the first week of 2019 ;) So I would query it in a different way: 'date_query' => array( 'after' => '-' . (intval(date('N')) - 1) . 'days', 'inclusive' => true ) What it does is takes all posts published after given date. And to compute that date we take current day and substract the current day of the week - so we get last Monday...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "date query" }
load_plugin_textdomain in `plugins_loaded` or `init`? Which is the best/recommended way to hook `load_plugin_textdomain` within - `plugins_loaded` or `init`? and what are drawbacks using either.
Load translation files as late as possible for your plugin's use-case. This allows other plugins as much time as possible to fully initialise. Why should you care about other plugins? Because they may be involved in the localisation process too. For example, changing the site language or filtering translation file paths. They can't do those things if you beat them to it. From your two examples: `plugins_loaded` fires first, so `init` is the better of the two in most cases. However, it still runs the risk that your _init_ code fires before another plugin's _init_ code, so set a low priority in your add_action call. (larger number = lower priority). If your translations are _needed_ earlier then you'll have to load them earlier. However, if you need them earlier than _init_ then your whole setup might be firing too early.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "translation, textdomain" }
How use custom image size + ACF + background image How to get the URL from an image with custom image size to use as a background-image from AFC? Register size in functions.php: add_theme_support( 'post-thumbnails' ); add_image_size( 'homepage-thumb', 220, 180 ); // Soft Crop Display image with custom size (named: customsize) on page with ACF: <?php $image = get_field('image_field'); ?> <img src="<?php echo $image['sizes']['customsize']; ?> /> But how to display image as background image with ACF?: <?php $image = get_field('image_field'); ?> <div style="background-image: url(<?php $image['url'] ?>)" /></div>
First off, this code... <img src="<?php echo $image['sizes']['customsize']; ?> /> is missing the end quote, it should be... <img src="<?php echo $image['sizes']['customsize']; ?>" /> You can use that same php to output the URL for the background size. <div style="height: 300px; width: 300px; background-image: url(<?php echo $company_logo['sizes']['customsize']; ?>)" /></div> Tested and works.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "advanced custom fields, images" }
How do action and filter hooks understand where to look for the core function that we hooked our function to them I want to know how does WordPress core files handle the relationship between module and core of the WordPress? We all know it uses `add_action()` and `add_filter()` to manipulate data according to our will in our plugin and there is a `$tag` parameter that is the function name that we want to hook our action and filter to core function of the WordPress. But how does the action and filter know where is the location of the $tag parameter (function) is in the WordPress core? I start to the reading the WordPress file and yet I have didn't find my answer.
I read the whole core files in wordpress. And it is split multiple file across the core folders actually it is very smart of them to do such a thing
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, filters, hooks, actions, core" }
What javascript libs & frameworks are integrated in WordPress vanilla? I am wondering what JavaScript libraries and frameworks are integrated in WordPress, which I could use out of the box? Also wondering if I can see which versions of the libs and frameworks are used per WordPress version? Is there any good documentation to it?
You can find the list of scripts and their registered handles here: Default Scripts Included and Registered by WordPress You can also search in `wp-includes/js` and `wp-admin/js` directories.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "javascript" }
explanation for activate_plugin function in wordpress core This function is in plugin.php file in wordpress core. I read the code and didn't get quietly what does it do. Can anyone give some explanation for this function?
Sometimes the easiest way is to go to docs... > Attempts activation of plugin in a "sandbox" and redirects on success. > > A plugin that is already activated will not attempt to be activated again. > > The way it works is by setting the redirection to the error before trying to include the plugin file. If the plugin fails, then the redirection will not be overwritten with the success message. Also, the options will not be updated and the activation hook will not be called on plugin error. > > It should be noted that in no way the below code will actually prevent errors within the file. The code should not be used elsewhere to replicate the "sandbox", which uses redirection to work. > > If any errors are found or text is outputted, then it will be captured to ensure that the success redirection will update the error redirection.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, php, core, activation" }
get selected categories or tags (using javascript) in GutenBerg? I was still unable to find out that in Gutenberg. Specifically, i used: wp.data.select("core/editor").getPostEdits(); to find out how many categories were checked. But it missed already checked categories... So, which function should I use to access in sum, how many categories are select at this moment? where is that data stored?
To get the categories from inside the editor of a post you can make use of the following selectors: The categories the post has in the published version: `wp.data.select("core/editor").getCurrentPostAttribute("categories")` The current categories of the edit (for example if the user has selected a new category but hasn't saved the post it will appear with this selector but not with the former): `wp.data.select("core/editor").getEditedPostAttribute("categories")` This will give you an array with the `id` of each category.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "block editor" }
Changing Post Tag Color Based On Post Count I have post tags that must always display. I want to change the color of the tag if there are no posts. I am looking for guidance on how to find the count and change the color of the post tag link depending on the post number. If the number is zero I'd like to change the tag link to be gray. <div class="container"> <?php $tags = get_tags(array( 'hide_empty' => false, 'count' => true )); foreach ($tags as $tag) :?> <a href="<?php echo esc_url( get_tag_link( $tag->term_id ) ); ?>" title="<?php echo esc_attr( $tag->name ); ?>"><?php echo esc_html( $tag->name ); ?></a> <!-- Ideally I could add a class to that <a> tag if the post count equals zero. Open to other solutions --> <?php endforeach; ?> </div><!-- END CONTAINER -->
Here you go. I just added a class using $tag->count. Tested and works. <div class="container"> <?php $tags = get_tags(array( 'hide_empty' => false, 'count' => true )); foreach ($tags as $tag) :?> <a class="count-<?php echo $tag->count; ?>" href="<?php echo esc_url( get_tag_link( $tag->term_id ) ); ?>" title="<?php echo esc_attr( $tag->name ); ?>"><?php echo esc_html( $tag->name ); ?></a> <?php endforeach; ?> </div><!-- END CONTAINER --> This will add the class count-0 if there are no posts. so just add something similar to this CSS. .count-0 { color: grey; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, tags, conditional tags" }
Delete Title Bar I am new in WordPress and web development. Starting to learn. I have browsed through this site but couldn't find any way to solve my problem. ![enter image description here]( This is my homepage on the website that currently I'm building. I want to delete this brick picture. I tried to install a hide title plugin, but still unsuccessful. This website link is nurulsazlinprubsntakaful.com. Hope someone can help me. Appreciate a lot. tq
Go into the admin. Click on Appearance > Customize > Additional CSS and paste in the following CSS. .home .page_header { display: none !important; } This will hide the entire header area. You could remove the image and add a color by adding something like this. .home .page_header { background-color: red; background-image: none !important; } Note: the .home before each selector will only apply these to the homepage, because the body on the homepage has class .home. If you want to apply these on all pages just remove the .home, like this... .page_header { display: none !important; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "homepage" }
Delete Title and Icone in Homepage ![enter image description here]( Hi, my website im doing now is nurulsazlinprubsntakaful.com i want to delete home ---> Home as per pic i attach. i read its about breadcrumbs. i also use inspect function in web browser.i get code like this from some discussion in other forum. .title-box { display: none; } i put in additional css. still not solve. im very new in wordpress. hope someone can help me...tq2. other than that, i also awant to delete icon share.
First, check your theme's settings, if breadcrumbs can be turned on/off. If not, the following CSS will hide breadcrumbs: nav.breadcrumbs { display: none; } Put the above lines, into Customize -> Additional CSS, or into your theme's `style.css`. To remove sharing buttons, use the following CSS: div.share.js-share { display: none; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "homepage" }
How to remove fresh posts (latest news) on the main page? How to remove fresh posts (latest news) on the main page? I can't find how to remove the "fresh posts"(latest news), I don't need it. Themes the Virtue. Tell me please. Thank you in advance. See below pictures. * * * ![enter image description here](
Solution to the problem. Very simple! Go to admin panel `yoursite/wp-admin` > Appearance > Theme Settings > Homepage Layout > The Layout Manager homepage > all Enabled to Disabled. Done! Now your Homepage is clean. Here is a screenshot, I hope you understand. Have a nice day :) ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, remote, newsletter" }
"You have the latest version of WordPress. Future security updates will be applied automatically." Today I've manually updated my website Wordpress version from 5.0.0 to 5.0.2. Since these updates are not automatic, I'm puzzled by the meaning of this message that appears now at the top of my dashboard (please check attached screenshot): "You have the latest version of WordPress. Future security updates will be applied automatically." So, since I haven't changed any setting, what's the meaning of this message? Updates will still be applied manually or can occur automatically? Thanks. ![enter image description here](
Since version 3.7 WordPress has automatic background updates. By default, only minor releases – such as for maintenance and security purposes – and translation file updates are enabled on most sites. In special cases, plugins and themes may be updated. Of course, as with many things in WP, you can modify that behavior with config or filters. So to disable these automatic updates, you can: 1. Add this to your `wp-config.php` file: `define( 'AUTOMATIC_UPDATER_DISABLED', true );` 2. Or disable only core updates (also in `wp-config.php`): `define( 'WP_AUTO_UPDATE_CORE', false );` 3. Or use one of these filters: `add_filter( 'automatic_updater_disabled', '__return_true' );` `add_filter( 'auto_update_core', '__return_false' );` So check your site for any of these... You can read more on that subject here: Configuring Automatic Background Updates
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "updates, dashboard, automatic updates" }
Gutenberg withInstanceId. When to use it? The WordPress block API for Gutenberg has a `withInstanceId` package. They say, > Some components need to generate a unique id for each instance. This could serve as suffixes to element ID's for example. Wrapping a component with withInstanceId provides a unique instanceId to serve this purpose. and show an example: /** * WordPress dependencies */ import { withInstanceId } from '@wordpress/compose'; function MyCustomElement( { instanceId } ) { return ( <div id={ `my-custom-element-${ instanceId }` }> content </div> ); } export default withInstanceId( MyCustomElement ); It seems like it is just being used for html ids? As to not have duplicate id names? Is there any other usage for it? If i just export my component using `export default withInstanceId( MyCustomElement )` will the entire component have a unique id?
The generated `id` is added to the component's props. So it can be accessed through `this.props.instanceId` inside the component. In the example you posted it is being used to assign a unique id attribute to the html element. However it can be used for custom logic inside react. Just as an example, you can assign each component an `id` and then save its data to the redux store, that way when you need to access the data from an element inside the store you can use its `id` to find it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "block editor" }
I need a custom permalink for my website I have following scenario: my-domain-name.com/google.com my-domain-name.com/twitter.com I need a custom permalink structure to pass `google.com` or `twitter.com` to `domain_name` query variable. I have tried following code: add_rewrite_tag('%domain_name%', '([^&]+)'); add_rewrite_rule('^/([^/]*)/?','index.php?domain_name=$matches[1]','top'); But not working For better example Check this site: ` I am trying to do the similar
The problem was solved by just one line of code. I am thankful to @rifi2k for long discussion and proposing different solutions. Here is the solutions: Add following code to functions.php function custom_rewrite_basic() { add_rewrite_tag('%domain_name%', '([a-z]{1,60}\.[a-z]{2,})'); } add_action('init', 'custom_rewrite_basic'); Then from permalink settings, select `Custom Structure` and add newly created tag by only in our case its `/%domain_name%/` save settings.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, url rewriting, rewrite rules" }
Wordpress functions.php shortcode is not working I have new WordPress (5.0.2) install with the code added to the end of functions.php file: function testsc(){ return "It is working!"; } function testsc2(){ return "It is working!"; } add_shortcode('testshortcode', testsc); add_shortcode('testshortcode2', 'testsc2'); With Debug Objects plugin installed i can see that short codes are added: Shortcode: testshortcode Function: testsc Shortcode: testshortcode2 Function: testsc2 But when i put testshortcode or testshortcode2 in a page it is treated as text. I use default theme: Twenty Sixteen.
Finally it worked. To ensure that, all following conditions must be met: * declarations must be in lowercase * do not use echo but return the content * square brackets are required even in the shortcode block.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "shortcode" }
How to create editable sections in wordpress? I am making a website for a friend and he doesn't know how to code so I decided to make him a WordPress website which is new to me. I wanna make a homepage that has different sections (About us section, photo gallery section, etc). he might want to change the about us section later in the future or add pictures in the galley. whats the best way to do this? I have thought about making posts for each section (an about us post and he could just edit it whenever he wants to change the about us section) does that work?
Here is what I would recommend. Use a plugin called Advanced Custom Fields. This will allow you to build out the admin and have different fields for each section. You could have an editable area with a editor for the about us section. You could use a Repeater Field for the gallery, and much more. Once you have all the fields in the admin, you just need to pull all the data into your homepage template. This is pretty straight forward and there is good documentation with examples. This is one of the few plugins I recommend, but when it comes adding custom fields it doesn't make sense to not use it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts" }
When will the 4.3 branch become EOL I have a wordpress setup which is v4.3.18. When will this branch (4.3) become End Of Life and stop receiving updates? I can't find anything offical
It _is_ EOL. WordPress will backport security fixes when it can, but makes no promises for updates for anything except the latest version. You should have updated 3 years ago. > WordPress will be backported security updates when possible, but there are no guarantee and no timeframe for older releases. There are no fixed period of support nor Long Term Support (LTS) version such as Ubuntu's. None of these are safe to use, except the latest series, which is actively maintained. <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wordpress version" }
I need https::/mysite.com instead of https::/mysite.com/wordpress Now my site is like https::/mysite.com/wordpress If I go to https::/mysite.com I get 403 Forbidden How to fix that?
The reason of such behavior is that you’ve installed your WP in `/wordpress` subdirectory, so that’s exactly where it works. And since the root directory is empty (no index.php nor .htaccess files are in there) you get 403 error, when requesting domain root. **So how to fix it?** 1. Connect to your ftp server and move files from subdirectory to domain root. So all files from `/WordPress` subdirectory should be moved to its parent directory. When `wordpress` directory is empty, remove it. 2. Edit `.htaccess` file and remove `wordpress` part in rewrite rules. 3. Change all paths/URLs in database. You can use this tool to do it: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "errors" }
Gutenberg extend core blocks How do I modify a core block, in my case gallery block to add extra markup to can fire some lightbox on created gallery. Is there a way to hook in on render of gallery on frontpage to adjust markup?
You need to use Block Filters to modify existing blocks. There are couple of handy hooks you need to use in place of **edit** and **save** function to wrap around core blocks into your desirable block structure. For your purpose I guess, you need to use - blocks.getSaveElement and editor.BlockEdit
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "block editor, customization" }
Display all page which have not a certain template I'm trying to display all pages of my website which have not the following template: `template-rubrique.php`. It works great but it doesn't output the blog page as well, since it doesn't have a template at all. How should I proceed? $args = array( 'post_type' => 'page', 'posts_per_page' => -1, 'order' => 'ASC', 'orderby' => 'title', 'meta_query' => array( array( 'key' => '_wp_page_template', 'value' => 'template-rubrique.php', 'compare' => '!=', ) ) );
You can add an `OR` relation to the meta query and also get pages with no `_wp_page_template` meta key: $args = array( 'post_type' => 'page', 'posts_per_page' => -1, 'order' => 'ASC', 'orderby' => 'title', 'meta_query' => array( 'relation' => 'OR', array( 'key' => '_wp_page_template', 'value' => 'template-rubrique.php', 'compare' => '!=', ), array( 'key' => '_wp_page_template', 'compare' => 'NOT EXISTS', ) ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates" }
CSS change in woo commerce Place Order Text add_filter( 'woocommerce_order_button_text', 'woo_custom_order_button_text' ); function woo_custom_order_button_text() { return __( 'Your new button text here', 'woocommerce' ); } Above is the example how we can change the woocommerce "Place order" Text, but what if we want to change the CSS also how can we have the whole button customized along with our own button classes and CSS.
I will try to answer your question. since you know how the text can be changed - let me take it for CSS. View in the browser - The browser is rendering the button like this → <button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Confirm order" data-value="Confirm order">Confirm order</button> ![enter image description here]( Now create a folder by the name of "woocommerce" in your child theme/theme and create a folder by the name of checkout, and in that folder put payment.php from woo commerce template. (Look for the latest template) and change the button class there with class that you want. You are all done.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, woocommerce offtopic, css" }
WP_Query meta_query >= date I have been trying for hours, I don't get my query to work: **display only posts (from custom post type) with a field (Advanced Custom Fields date picker) value that is more than today**. `echo date('d-m-Y');` prints the same date format as the posts output `the_field('datum_event');` : 06-01-2019 $args = array( 'post_type' => 'agenda', 'meta_query' => array( array( 'key' => 'datum_event', 'value' => '06-01-2019', 'compare' => '>=' ) ), ); $loop = new WP_Query( $args ); What is missing?
What is missing? One tiny detail... And it's easy to overlook... the_field('datum_event'); Prints the field using the format you've defined in field settings. But... It has nothing to do with how the value of that field is stored in DB. ACF uses `YYYYMMDD` format when storing date values in DB. And WP_Query doesn't use field format, since it looks directly in DB. So you have to use other/raw format in your WP_Query: $args = array( 'post_type' => 'agenda', 'meta_query' => array( array( 'key' => 'datum_event', 'value' => '20190106', 'compare' => '>=' ) ), ); $loop = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query, advanced custom fields, meta query, date" }
Redirect 301 of old urls to wordpress urls I am migrating a website from vivvo cms to wordpress. Vivvo is using category pages like index. **numberofthepage**.html I want to redirect urls like using regex: to mycats could be more than one category ex cat1/cat2... and the 200 could be any number. I used : ^/index.(.*?)\.html to ^/page/$1/ But not redirecting. Thanks
Since category and page number is dynamic, you can use htaccess and use this sample rewrite rule below: RewriteRule (.*?)/index.(.*?)\.html $1/page/$2/ You can test the regex here - < and I can see that it is working as far as I have tested it. PS: URL Redirections are **cached aggresively** , you need to clear you browser cache completely to make sure that you are testing it properly. Hope this helps!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, regex" }
Return category name with & Ampersand doesnt work I have a category named: `This & That` However, for some strange reason my `switch` code doesn't pick it up. When I output `$firstcat` it does return `This & That` which makes it even more cumbersome. The code works fine for other categories not containing the ampersand &. function posend_text_shortcode() { $mycategory = get_the_category(); $firstcat = $mycategory[0]->name; switch($firstcat){ case "This & That": include(get_stylesheet_directory() . '/inc/style/check.php'); break; default: include(get_stylesheet_directory() . '/inc/style/default.php'); break; } }
Using titles in such comparisons is always a little bit risky - you have to deal with encodings and so on. Much safer way is using of slugs in code, because they are url-safe. So your code could look like this: function posend_text_shortcode() { $mycategory = get_the_category(); $slug = ''; if ( ! empty($mycategory) ) { // you have to check, if any category is assigned $slug = $mycategory[0]->slug; } switch($slug){ case 'this-that': // change to real slug get_template_part('/inc/style/check.php'); // you should use get_template_part instead of including template parts break; default: get_template_part('/inc/style/default.php'); break; } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, categories" }
Add WooCommerce vendor slug to auto-generated SKU I would like to rewrite SKUs generated by WooCommerce Product SKU Generator and prefix them with the vendor slug from WooCommerce Product Vendors into the following format: [Vendor Slug][Generated SKU]. E.g. 'GT1234', 'JD1235', etc... If the product author is not a vendor or the order is not associated with a vendor, the prefix should default to 'XX'. Main difficulty for me is retrieving the vendor slug for the user adding the new product. How would I go about doing that? Anything to get me going is appreciated! function filter_wc_sku_generator_sku( $product_sku, $product ) { $vendor_slug = '???' if (!$vendor_slug) { $product_sku = 'XX' . $product_sku; } else { $product_sku = $vendor_slug . $product_sku; } return $product_sku; }; add_filter( 'wc_sku_generator_sku', 'filter_wc_sku_generator_sku', 10, 2 );
There's a class `WC_Product_Vendors_Utils` that you can use e.g. $vendor = WC_Product_Vendors_Utils::is_vendor_product( $item["product_vendors_product_id"] ); //replace this with the product ID if ( ! empty( $vendor[0] ) ) { $vendor_data = WC_Product_Vendors_Utils::get_vendor_data_by_id( $vendor[0]->term_id ); if ( ! empty( $vendor_data ) ) { $vendor_slug = $vendor_data['slug']; // I am not sure of the correct value here but you can var_dump() just to make sure } } Hope that will help you start generating the SKU properly :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, woocommerce offtopic" }
How to create mass 301 redirects with PHP in Nginx server without using a WP plugin New on Nginx based web server setup and finding a way to create mass 301 redirects in a WP site without using any plugins. It is fairly easy in Apache based web server as you only need to put this at the end of your `.htaccess` file but this won't work in Nginx: `Redirect 301 /old-url /new-url`
Seems the easiest way to do it is via PHP without changing any Nginx server config by adding this at the start of the `wp-config.php` file: // Trailing slashes matters here so /old1 is different from /old1/ $redirect_targets = array( '/old-url' => '/new-url', '/old-url2' => '/new-url2', '/old-url3' => '/new-url3', ); // Added a way not to accidentally break wp-cli if ( (isset($redirect_targets[ $_SERVER['REQUEST_URI'] ] ) ) && (php_sapi_name() != "cli") ) { header('HTTP/1.0 301 Moved Permanently'); header('Location: $_SERVER['HTTP_HOST'] . $redirect_targets[ $_SERVER['REQUEST_URI'] ]); exit(); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect" }
Is there a way of registering a default logo image for custom-logo? Similair to custom-header with **register_default_headers()** in version 4.5 and above.
No, there isn't. Given that a logo is typically unique for each site and brand, it doesn't really make much sense to offer a default logo, except as a placeholder. If you want to have a default logo as a placeholder in your theme, then in the template you could check if a custom value is set, and if not, display your own logo: <?php if ( get_custom_logo() ) { the_custom_logo(); } else { printf( '<a href="%1$s" class="custom-logo-link" rel="home" itemprop="url"><img src="%2$s" class="custom-logo" itemprop="logo" alt="%3$s"></a>', esc_url( home_url( '/' ) ), esc_url( get_theme_file_uri( 'images/default-logo.png' ) ), get_bloginfo( 'name', 'display' ) ); } ?> The markup in this example will match the markup output of `the_custom_logo()`. The logo itself would be `default-logo.png` in the `images/` directory of your theme.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom header, logo" }
Appearance -> Menus doesn't show Ony of my colleges started with the implementation of a new theme, I'm trying to add Menus but the option doesn't show. anyone know how to bring that back? thx. ![enter image description here](
Please add following code into your theme **functions.php** file function pietergoosen_theme_setup() { register_nav_menus( array( 'header' => 'Header menu', 'footer' => 'Footer menu' ) ); } add_action( 'after_setup_theme', 'pietergoosen_theme_setup' ); Please check at your end and let me know if any query. Hope it will help you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, admin menu, theme options" }
Remove category number fill I need create menu but my category list is a 2 page. I want remove this number and show all category in 1 page. ![enter image description here]( ![enter image description here](
In order to override the default of per page, you can set the number to '' to instruct the query to return all categories. Add the following code to your functions.php file. add_filter( 'get_terms_args', 'show_all_categories_admin_nav_menu', 10, 2); function show_all_categories_admin_nav_menu( $args, $taxonomies ) { if( reset($taxonomies) === 'category' ) { $args['number'] = ''; } return $args; } If you set the number to blank it will still shows the numbers of page even though it's showing all the categories. Hope this will help you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "categories, wp admin" }
Allow admins to login as other users My question is about WordPress in general. How can I give admins the ability to log in and do things that other users can do? My specific use-case for this is, in WooCommerce, when an admin creates an order via the "Add New Order" page and assigns it to a user the admin can not view the order or complete checkout. If the admin tries to view the page he gets this error - "This order cannot be paid for. Please contact us if you need assistance." Is there a way to work around this? I would prefer not to use a plugin.
You'll need to find out what specific capabilities Admin users are missing. Once you know the full list, you can use `add_cap()` to add those capabilities to the Admin users and enable them to do whatever the other roles are doing. From Shold I manually add 'cap' to admin role ? - $role = get_role( 'administrator' ); $role->add_cap( 'cap' ); Replace `cap` with one of the capabilities you need to add to admin users. Copy and paste that second line, and add each additional capability separately.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users, admin, user roles, user access" }
Woocommerce cart is not clear after logout I am implementing an LMS using one plus theme,learndash and woocommerce plugins. Currently when a user log out, his cart persist and the item in his cart can be edited by a guest user.I want to clear the cart after a user logout from his account.I tried the answer, given in this link for fixing the issue < I tried putting this code in my themes function.php,but it is not working. function your_function() { if( function_exists('WC') ){ WC()->cart->empty_cart(); } } add_action('wp_logout', 'your_function');
Try this code by using global `$woocommerce` add_action( 'wp_logout', 'force_clear_woocommerce_cart' ); function force_clear_woocommerce_cart() { error_log("Clearing cart"); global $woocommerce; $woocommerce->cart->empty_cart(); } hope this will help you
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
How to reference argument data for wp_nav_menu() from functions.php I would really like to keep my template files as clean as possible, without including too much argument data. Is it possible with the following example... $args = array( 'theme_location' => 'main-menu', 'menu_class' => 'list-inline', 'add_li_class' => 'list-inline-item' ); wp_nav_menu($args); ...that I can store my array of arguments in a function within my functions.php file, and then simply call the argument data onto my header.php where my wp_nav_menu() lives? Please feel free to correct me if I am wrong, but is this a good time for me to use a add_action/do_action for this specific case? I want to use my functions.php file as a one-stop-shop to (i.e. register the nav, add basic or advanced argument data to the same nav, etc..). This is the first time I'm thinking about this, so I'm all for any best practices. Many thanks!
a function like this: function get_nav_args($overrides = array()) { $defaults = array( 'theme_location' => 'main-menu', 'menu_class' => 'list-inline', 'add_li_class' => 'list-inline-item', ); return shortcode_atts($defaults, apply_filters('some_custom_identifier_nav_menu_args', $overrides, $defaults) ); } would be callable like `wp_nav_menu(get_nav_args())` using shortcode atts and allowing an overrides array to be passed in would allow you to change the values if necessary without duplicating the whole thing. As for your put everything in functions.php I would avoid that if possible. Use `include` or `require` to include files that contain your functions. this way you can sort them out by type, use, location, or whatever else you'd like and won't end up digging through a single massive file looking for something down the road.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
How to prevent resized featured images? The theme has set thumbnail sizes for featured images: add_theme_support( 'post-thumbnails' ); add_image_size( 'hitmag-landscape', 1120, 450, true ); add_image_size( 'hitmag-featured', 735, 400, true ); add_image_size( 'hitmag-grid', 348, 215, true ); add_image_size( 'hitmag-list', 290, 220, true ); add_image_size( 'hitmag-thumbnail', 135, 93, true ); How do I set the "featured" image one so that the image size is just whatever image I upload (for height - I want to be able to set width to 735 still)
Featured image sizes are mostly likely controlled by your theme, so I would look there. Maybe there is a theme setting for it. You can also check the following setting to see if it us using one of those sizes. ![enter image description here]( * * * You can change the featured image size by adding this code into your functions.php file. More info on set_post_thumbnail_size. set_post_thumbnail_size( 500, 500 ); * * * You can also add a new image size and then use it in your template by doing something like this... add_image_size( 'featured-image-size', 800, 9999 ); // Add to functions.php php the_post_thumbnail( 'featured-image-size' ); // Template usage More info on add_image_size & the_post_thumbnail * * * **Edit:** Since you updated your question, here is an updated answer. You can set the height to be unlimited like this... add_image_size( 'hitmag-featured', 735, 9999 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "images" }
Can't add or delete plugins - but I'm an admin as the title says, I have Administrator privileges but I don't have the permission to add or delete plug-ins. (Button/Links just aren't on the page) If I go to `.../wp-admin/plugin-install.php` I get the message: `Sorry, you are not allowed to access this page.` **Edit:** And it is not a multisite and they did not have this problem a few days ago. Also, I undertand the Yoast SEO plugin did not update properly - it threw an error (I don't know what unfortunately) and they replaced it via ftp Any ideas? TIA
Fixed - I replaced the `wp-includes` folder with a fresh one, guest something funky was going down in there!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, permissions" }
Getting the selected terms for custom taxonomies in the editor After reading this answer here, I can get the currently selected/checked terms for categories using this code: wp.data.select("core/editor").getCurrentPostAttribute("categories") However, this doesn't seem to work with custom taxonomies created with register_taxonomy(). Is there any other way to do this? This merge seems like it might be relevant, but it's kind of hard for me to understand what's being implemented there.
When you register a custom taxonomy make sure to set `show_in_rest` to `true`. This way the taxonomy will show in the REST API which is what Gutenberg uses to get the data. Then you can use the selector: `wp.data.select("core/editor").getCurrentPostAttribute("my_taxonomy");`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom taxonomy, block editor" }
WordPress Admin Dashboard Does Not Display Correctly I download the wordpress files via ftp software ,after that I install the wordpress , then when I try to access the dashboard display doesn't work correctly , it is shown as links without css so can anyone help me please ![enter image description here](
Seems a duplicate. < Try to find that error with Google as there are a lot of results You can also try editing your wp-config.php file ( it is located on the root folder of your installation ) and right before the lines that say: /* That's all, stop editing! Happy blogging. */ and add this define('CONCATENATE_SCRIPTS', false); This will tell WordPress to load each script on it’s own instead of combining them. This might be caused due to some faulty or outdated plugin .js that overrides something else when it is concatenated. Source: < If that doesn't fix your problem, try to deactivate all plugins moving them to a temp folder via FTP or renaming the plugins folder to sth like plugins_old. Maybe one of them is causing the issue here...
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "errors" }
The editor has encountered an unexpected error. // TypeError: Cannot read property 'prefix' of null when I tried to edit a post of a custom post type, I experienced this error. ![enter image description here]( When I press "Copy Error" I am getting this: TypeError: Cannot read property 'prefix' of null at at ph ( at eg ( at fg ( at wc ( at fa ( at gg ( at Ca ( at Object.enqueueSetState ( at r.q.setState (
So, I was researching this topic a bit deeper. All answers found on this SE suggested disabling Gutenberg with a plugin. This couldn't be a valid "fix" in my oppinion. After researching and browsing through the git issues of `WordPress/gutenberg` I've found a pretty easy solution for this problem. The user `joshuafredrickson` on the git suggested changing the args of the custom post type array from `'public' => false,` to **true**. I have checked that fix on multiple of my clients projects and it has worked every single time. **Credits:** * <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "custom post types, errors, block editor" }
Hestia Child theme creation I'm working on creating a child theme of Hestia for my own website but I'm just not getting where the code is supposed to go in my child theme coding. I know how to design websites and I'm familiar enough with code to make the changes if I know where to look to do it. I know what file I need to edit (hestia\inc\views\main\class-hestia-footer.php) in my main file, but when I updated Hestia it was all lost. Also, I had to edit the main file of my Hestia template to get it to even show up. Plus in all actuality, I don't even want to have the main template of Hestia I just want to have the one that I'm working on be the one that I utilize. It's for my website only, I'm not distributing it or anything.
Yeah, as you found out you don't want to edit files directly in your theme because you will lose the changes when the theme updates. Here is some info on child themes, if you haven't you should read it. For your particular theme, it appears the developer offers a pre-made child theme, you just need to download it and install/activate like any other theme. Here are the docs, you may want to look them over.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, child theme" }
Remove dashicons.min.css conditionally Trying to remove dashicons for non-logged in users excluding specific pages and specific categories with the following: add_action( 'wp_enqueue_scripts', 'go_dequeue_dashicons' ); function go_dequeue_dashicons() { if ( ! is_user_logged_in() ) { if ( !is_page( array( 9, 10 ) ) || !in_category( array( 29, 2 ) ) ) { wp_deregister_style( 'dashicons' ); } } } The code works if I do not use the OR condition. In other words it works if I apply a sole IF statement either for the specific pages or for the specific categories. It doesn’t work if I use both IF statements under the OR condition. Which is the correction needed?
Try this. add_action( 'wp_enqueue_scripts', 'go_dequeue_dashicons' ); function go_dequeue_dashicons() { if ( ! is_user_logged_in() && !is_page( array( 9, 10 ) ) && !in_category( array( 29, 2 ) ) ) { wp_deregister_style( 'dashicons' ); } } I basically just combined the IF statements and changed || to &&.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Hwo to turn off "get_parent_theme_file_path" in child-theme? I have the Twenty Seventeen theme and I would like to turn off generate SVG (social icons menu) in DOM. < How can I turn off it? I do not use the social icons, but it is g In function.php my parent theme i see it: require get_parent_theme_file_path( '/inc/icon-functions.php' ); How can I override it in my child-theme to avoid generate it? Thank you in advance.
If you look at `get_parent_theme_file_path()` it returns `apply_filters( 'parent_theme_file_path', $path, $file );` You need to add a filter here to override the location to something in your child theme, like so. add_filter('parent_theme_file_path', function($path, $file) { if ($file !== '/inc/icon-functions.php') { return $path; } $path = get_stylesheet_directory() . '/' . $file; return $path; }, 10, 2); You will still need to have a file for it to find at that location in your child theme, but you can put whatever you want in there.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "child theme" }
Do i need escaping get_the_passsword_form function? I saw themeforest/WordPress.org has said all WordPress default get functions need to be escaped output for security region for WordPress Theme or Plugin development, Now I want to show password form if a post has password protected. So now I'm using get_the_password_form () function. Now I need to know this function do I need escaping? If answer Yes, Please help me, How can I escape this function? Like esc_html (), or esc_url () etc. Which function do i need to use for escaping ? Here is Themeforest Requirements And Here is my code <div class="single-blog-content"> <?php if(post_password_required()) { echo get_the_password_form( ); }else { the_excerpt(); } ?> </div>
There is nothing to escape in your code. Let’s say given function should return only plain text and no HTML entities should be allowed. For example you want to display the search query string. In such case you should use `esc_html`. This way, if user puts `<b>ala</b>` as search string, your site will print exactly that. If you won’t escape that string before printing it, it will be treated as HTML code and you’ll see bold word `ala` only. But... You have to escape with proper function depending on context. So: <h1>You’re looking for: <?php echo esc_html( get_query_var( 's' ) ); ?></h1> But: <input name="s" value="<?php echo esc_arg( get_query_var( 's' ) ); ?>"/> So, let’s get back to your code... get_the_password_form() should display HTML tags and they should be processed as HTML code by browser - so you can’t escape it. If you will, you’ll see a string containing HTML tags instead of form.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, password" }
how to remove a rel="nofollow" using call to action plugin I need to remove a specific link.`<a href="xyz.com" **rel="nofollow"**>`remove a nofollow link using call to action plugin . may i know how to know the rel="nofollow". i checked in plugin file but. I can't change it. so if you have any suggestion give me fast.
i hope its help you i'm doing use of jquery $("a").each(function(){ if($(this).attr("rel")){ $(this).removeAttr("rel"); } }); it will remove all nofollow link from all anchor tag even plugin link too.
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "plugins, plugin development" }
Move Jquery.js to Footer I want to move jquery.js from header to footer. I have tried following code: //Remove jQuery Default function replace_jquery() { if (!is_admin()) { wp_deregister_script('jquery'); } } add_action('init', 'replace_jquery'); //Load on Footer add_action('wp_footer', 'jquery_code'); function jquery_code(){ ?> <script type='text/javascript' src=' <?php }; The issue is that If I run first piece of above code, js files of my theme are removed with jquery.js. Because theme's static js files is calling via `array( 'jquery' )` attributes. I just want to move jquery only from header to footer. **NOTE:** I have tried other suggestions on Stackexchange but none of them didn't work on my blog. (Such us: Enqueue core jQuery in the footer?) How can I do it?
When you deregister `jQuery`, you have to register it again. Try this code **UPDATE:** You have to deregister `jQuery` first (first part of your code), so the final code should be: //Load on Footer add_action('wp_enqueue_scripts', 'register_jquery'); function register_jquery() { wp_deregister_script('jquery'); // remove original jQuery wp_register_script( // add custom jQuery in footer 'jquery', ' array(), // dependencies null, // version true); // load in footer? wp_enqueue_script('jquery'); } But it's NOT RECOMMENDED to load custom jquery in wordpress.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, jquery, javascript" }
Retrieve Woocommerce Cart Url with javascript/jquery Is it possible to retrive woocommerce cart url using javascript or jquery? Are there native functions or do I have to perform an ajax call to retrieve it?
You can pass it to the script via the functions.php file or a plugin using the wp_localize_script function. <?php function my_load_scripts() { wp_enqueue_script('my-script', plugin_dir_url( __FILE__ ) . 'js/my-script.js'); wp_localize_script('my-script', 'my_script_vars', array( 'woo_cart_url' => get_permalink( wc_get_page_id( 'cart' ) ) ) ); } add_action('wp_enqueue_scripts', 'my_load_scripts'); Then it will be available in your script ( in the example: **my_script_vars.woo_cart_url** ) <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, jquery, javascript" }
Can a manually uploaded plugin be made to track updates from the WordPress.org plugin directory? I've made a plugin which I will give to some users to test by manually uploading the zip file. I later on want to host the plugin in the WordPress.org plugin directory, but I want to avoid users having to uninstall my plugin to install the directory-hosted one because I have code in my uninstaller that deletes all of the terms, etc. that my plugin adds. Is there a way to make WordPress track a plugin in the official directory instead of a locally uploaded zip?
As long as everything was made according to WP best practices all your manually installed versions will update the same as the ones installed from `wordpress.org`. The updater looks at many things to identify your plugin. However, the most important is the plugin URI (you can change the directory of many plugins and they will still work), but the name and slug are also checked. After WP detects that it has a matching plugin it will check the version and send out update information as needed. **Edit 1** Based on a little more research, I see that the update check seems to be done by `wordpress.org` at this url: ` to see how the call is structured you can look at the core code for `wp_update_plugins()`. The reason your manually installed plugin will update is the same as the reason you can manually download and install a plugin from `wordpress.org` and see it recieve updates in the `wp-admin`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, automatic updates, wordpress.org, ziparchive" }
Is there a way to get dynamic data into a Slider Revolution slide from a PHP script? I have a PHP class that I'm using to make requests to an external API for data like view/follower counts. I want to show a couple pieces of that data on my homepage in a Slider Revolution slide. There aren't any default layers that I can put in to execute PHP code or anything like that that I have found. I know that there is a custom JS area, where I could potentially make an AJAX request to a script that instantiates the class and returns data from it. But I'm not sure how I would implement that data within the slide.
Was easier than I thought, didn't know that you could execute shortcodes in the text/html block. function twitch_api_client_views_shortcode() { $twitch = twitch_api_client(); return $twitch->getViewCount(); } add_shortcode( 'twitch-views', 'twitch_api_client_views_shortcode' ); And then `[twitch-views]` in Slider Revolution `text/html` layer.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins" }
Lost password link redirects to my-account/lost-password/,how to fix it back to default lost password My lost password option in the wp login page redirect to woocommerce lost password page.How to set it back to the standard wp lost password option.?I want it to redirect to "wp-login.php?action=lostpassword". I am using,woocommerce,paid membership pro,buddypress plugins. I found this Lost password link is redirecting to /shop/my-account/lost-password/, but I couldn't understand it. Thanks.
Try to put below code into your theme **functions.php** file remove_filter( 'lostpassword_url', 'wc_lostpassword_url', 10 ); OR function reset_pass_url() { $siteURL = get_option('siteurl'); return "{$siteURL}/wp-login.php?action=lostpassword"; } add_filter( 'lostpassword_url', 'reset_pass_url', 10, 2 ); Please let me know if any query. Hope it will help you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "password" }
Remove Font-Awesome MaxCDN Link & Load Locally MaxCDN is slowing down my site so I want to load font-awesome locally but I can't seem to write the correct function to remove it. function remove_unwanted_css(){ wp_dequeue_style(‘font-awesome’, ‘ } add_filter(‘wp_print_styles’, ‘remove_unwanted_css’);
You must find the name of the enqueued stylesheet in your theme and use it to dequeue a style - wp_dequeue_style. URL is unnecessary. Example: function remove_unwanted_css() { wp_dequeue_style( 'font-awesome' ); } add_action( 'wp_print_styles', 'remove_unwanted_css', 100 ); Or another solution wp_deregister_style/: add_action( 'wp_enqueue_scripts', 'remove_default_stylesheet', 20 ); function remove_default_stylesheet() { wp_dequeue_style( 'font-awesome' ); wp_deregister_style( 'font-awesome' ); wp_register_style( 'new-font-awesome', get_stylesheet_directory_uri() . '/new.css', false, '1.0.0' ); wp_enqueue_style( 'new-font-awesome' ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, fonts" }
Allow excerpt for pages in Gutenberg? I'd like to utilize excerpt field on pages. How do I enable it? Currently `excerpt` block only shows on posts in sidebar. But on pages it’s missing.
It's nothing new with the block editor, it's the same age-old way by putting the following code into your theme's `functions.php`: add_action( 'init', 'wpse325327_add_excerpts_to_pages' ); function wpse325327_add_excerpts_to_pages() { add_post_type_support( 'page', 'excerpt' ); } Here's my screenshot in a fresh WordPress 5.0.3 install: ![Excerpt for Pages in the WordPress Block Editor](
stackexchange-wordpress
{ "answer_score": 18, "question_score": 5, "tags": "block editor" }
How do I get the user ID of the user that was updated in WordPress? I want to run a custom function in my plugin that notifies me of the user that's email has been updated in wordpress backend. But i am not sure how do I get the user ID of that user, since this action hook `add_action( 'update_user', 'when_update_user' );` requires me to pass an user ID to run `when_update_user()` function when an administrator updates the user data. Does anyone have any idea regarding it?
You're looking for `profile_update` & `user_register`. `user_register` is called after a user is created. add_action( 'user_register', 'myplugin_registration_save', 10, 1 ); function myplugin_registration_save( $user_id ) { // Do stuff with $user_id } `profile_update` is called after a user is updated. add_action( 'profile_update', 'my_profile_update', 10, 2 ); function my_profile_update( $user_id, $old_user_data ) { // Do stuff with $user_id }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, users, updates" }
tracking number field in Woocommerce order I am creating a custom field `Tracking_ID` on Woocommerce, where the admin will enter the tracking ID as value. How can i get the value of the created custom field and display it inside the `customer-completed-order.php` Also (Optional) i want to show the tracking ID field in the user's `track-order` order page in his/her my-account. **Woocommerce>order field:** ![enter image description here]( **oceanwp-child/woocommerce/emails/customer-completed-order.php** <?php /* translators: %s: Customer first name */ ?> <p><?php printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $order->get_billing_first_name() ) ); ?></p> <?php /* translators: %s: Site title */ ?> <p><?php printf( esc_html__( 'Your %s order is completed. Your tracking number is: {$fld}', 'woocommerce' ), esc_html( wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) ) ); ?></p>
Based on Melissa's answer, here is what i did and it worked for me. <?php #Tracking ID $tracking_id = get_post_meta($order->get_order_number(), 'Tracking_ID', true); if( ! empty($tracking_id) ) { ?> <p> <?php printf( esc_html__( 'Your tracking number is: %s', 'woocommerce' ), esc_html($tracking_id) );?> </p> <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, custom field, woocommerce offtopic" }
Page and Post return 404 with custom taxonomy I have registered a custom taxonomy on "post" named "cat_modules" with this args: 'rewrite' => array( 'hierarchical' => true, 'slug' => '/', 'with_front' => false ) I used `'hierarchical' => true` to have the url structure like 'category/subcateogry' and I used `'slug' => '/'` to remove the "cat_modules" from the slug. These work well on the archive pages but all posts and pages return a 404 error. If I remove `'slug' => '/'` from the args everything work well. P.S In this web site is installed WPML.
OK, so you've used `/` as you taxonomy slug. It means that URL for your term is: And for pages it will be: As you can see, there is no way to guess, what type of post should WP search for. WordPress processes the URLs looping through registered Rewrite Rules and matching given URL against regular expression assigned to current rule. That means that in your case WP will take first rule that will match correctly and try to display that type of object. And because there are two different objects registering rules that are in conflict, then you'll get 404 errors for some of them.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom taxonomy, url rewriting, plugin wpml" }
get_post_gallery with Gutenberg I have a site where I created a page that takes the gallery images from a post and puts them into a slider. I used the following code: // gets the gallery info $gallery = get_post_gallery( $post->ID, false ); // makes an array of image ids $ids = explode ( ",", $gallery['ids'] ); Then I inserted the images using wp_get_attachment_image(). Unfortunately, with WP 5.0 and Gutenberg, get_post_gallery no longer works with newly added content. It seems that get_post_gallery used a shortcode that no longer works with Gutenberg. I am still getting up to speed on Gutenberg and the block system. Until I understand that all better, I was wondering if anyone has any advice on how to get the image ids from a gallery in Gutenberg?
Using birgire's suggestions, I came up with the following solution that is working well with both the old pre-WP 4.x data and the newer posts that have been added under 5.0. // if there is a gallery block do this if (has_block('gallery', $post->post_content)) { $post_blocks = parse_blocks($post->post_content); $ids = $post_blocks[0][attrs][ids]; } // if there is not a gallery block do this else { // gets the gallery info $gallery = get_post_gallery( $post->ID, false ); // makes an array of image ids $ids = explode ( ",", $gallery['ids'] ); }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 8, "tags": "images, gallery, block editor" }
WP + MySql db / PHP I have a website running WP connected to a MySql db, where the latter uses PHP. I did not make the site and have only small experience with WP. This may be a simple question. The WP also uses Elementor. I interact with the db via phpMyAdmin. I have this page = < It accepts input data that does into the db. See the labels ('First Name' etc). I can't seem to find them defined in WP. So they are in the db? I looked in the various db tables. But still can't seem to find these labels. Can you suggest what tables I might focus on?
Following on from Scott and Milo's answers, you should take a look in the theme directory. If you browse the website file directory: /wp-content/themes/generatepress/ Look for a filename like page-template-signup.php That said, since GeneratePress is a premium theme, you need to keep in mind if you make changes to that file, you will lose them when you update the theme. The standard WordPress way around this problem is to use a child theme, which you can Google to find out more.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, mysql" }
Only allow the post author and admin to comment on a post I've searched the interweb and stackexchange high and low and found nothing on how to restrict comment submissions to 1. the post author and 2. the admin.
Depending on how your theme is set up, `comments_open` might be the filter you want. (in functions.php) add_filter( 'comments_open', 'block_comments_for_others', 10, 2 ); function block_comments_for_others( $is_open, $post_id ) { $is_open = false; $post_author_id = get_post_field( 'post_author', $post_id ); if ( get_current_user_id() == $post_author_id || current_user_can('administrator') ) $is_open = true; return $is_open; } Or possibly something like this right in your theme where you display comments: if ( get_current_user_id() == get_the_author_meta( 'ID' ) || current_user_can('administrator') ) { comments_template(); } else { echo "No commenting for you"; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "comments" }
wp query template tags not working I create a page : contact-us then I specify a template for this page and this is the template code: <?php /* Template Name: Template wp_query */ ?> <?php $arg = array ( 'post_type' => 'post', 'post_per_page' => -1 , ); $test = new WP_Query($arg); var_dump($test); if ($test->have_posts()) { while ($test-> have_posts()) : $test-> the_post(); echo $test->get_the_title(); echo $test->get_the_content; endwhile; } wp_reset_query(); ?> the result page is blanck even if the var_dump($test) return the list of post with the information. for your information i tried query_post() and it works fine. please help me.
Template tags are not methods of `WP_Query` object. They are functions. On the other hand `have_posts` and `the_post` are methods of `WP_Query`. So in your code you should use: while ($test->have_posts()) : $test->the_post(); as you do, but then: echo get_the_title(); echo get_the_content(); Also... if you want to echo these values, it would be much better to use `the_title` and `the_content` instead - there are some additional filters and actions fired up.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query" }
update_option returns false in AJAX, how to debug? I tried debug plugins for WordPress, but they only show the current page SQL queries. How to debug if `update_option` returns false? I am updating an object decoded from AJAX request with `json_decode` although I doubt it has anything to do with it.
I found out that my settings where filtered by validation function registered by `register_setting`. Somehow I thought that it would only affect settings that where going through wordpress's own settings fields and not a custom AJAX function (the way I have it setup). To the point of the question: I used `php` `exit` to debug the AJAX. `update_option` returned false because the options fields where the same after validation (I was missing out one particular setting)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mysql, sql, json, options" }
Get thumbnails with array sizes parameter I am trying to get both `full` and `thumbnail` images from post with `wp_get_attachment_image_url`: wp_get_attachment_image_url( get_the_ID(), array('thumbnail, full')); I know that by default `size` is `thumbnail` and I read from documentation that I can pass and array of sizes, but with above example, I am getting an error: > A non-numeric value encountered The documentation is not clear about how to pass an array of sizes as parameter.
You’re almost correct. You really can pass an array as size parameter for that function, but... > **$size** (string|array) (Optional) Image size to retrieve. Accepts any valid image size, or an array of width and height values in pixels (in that order). Default value: 'thumbnail' So you can’t use it in the way you wanted to... You have to pass name of the size or an array that will define the size in pixels (width and height). You can get only one size with one call of that function (as it returns only one value - url of image in given size). But that’s not a problem, just call it twice: $thumb_url = wp_get_attachment_image_url( get_the_ID(), 'thumbnail'); $full_url = wp_get_attachment_image_url( get_the_ID(), 'full');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, post thumbnails, thumbnails" }
While loop shortcode problem I have created a shortcode using the while loop, which is going to break the loop when used with the page builder. How to solve it. Here may custom shortcode ![enter image description here]( here my showing part ![enter image description here](
You don't use global `$wp_query` object anywhere in your code, so there is no point in calling `wp_reset_query()`. On the other hand, you do use global `$post` variable, so after your code you should restore it's original value with `wp_reset_postdata();`. So change `wp_reset_query()` to `wp_reset_postdata()` and it should be OK. ## And one more thing... Shortcodes should return their values and they should not display anything. So you can't use `the_title()` inside of it - this template tags echoes its value and doesn't return anything. You should change it to `get_the_title()`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "shortcode" }
How to add multiple custom widget areas I'm looking to add multiple widget areas to a page in my theme as id like to have widgets within certain pages. I can add one using this code, I'm just struggling with a second. function new_sidebar_widget_init() { register_sidebar( array( 'name' => 'new-sidebar', 'id' => 'new-sidebar', 'before_widget' => '<div id="new-sidebar">', 'after_widget' => '</div>', 'before_title' => '', 'after_title' => '', ) ); } add_action( 'widgets_init', 'new_sidebar_widget_init' ); Then to place it in on my page: <?php dynamic_sidebar( 'new-sidebar' ); ?>
You have to register multiple areas: function new_sidebar_widget_init() { register_sidebar( array( 'name' => 'new-sidebar', 'id' => 'new-sidebar', 'before_widget' => '<div id="new-sidebar">', 'after_widget' => '</div>', 'before_title' => '', 'after_title' => '', ) ); register_sidebar( array( 'name' => 'new-sidebar-1', 'id' => 'new-sidebar-1', 'before_widget' => '<div id="new-sidebar">', 'after_widget' => '</div>', 'before_title' => '', 'after_title' => '', ) ); } add_action( 'widgets_init', 'new_sidebar_widget_init' ); And then you can use them based on their ID: <?php dynamic_sidebar( 'new-sidebar' ); ?> <?php dynamic_sidebar( 'new-sidebar-1' ); ?>
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "theme development, widgets, register sidebar" }
Manually mark imported photo as selected in media library Using image/attachment ID I want to manually set image to be selected in media library in javascript. ![enter image description here]( What's the simplest way to do this?
var selection = wp.media.frame.state().get('selection'); var attachment = wp.media.attachment(image.ID); selection.add(attachment);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "javascript, media library" }
How to add meta tags inside single image page? Hello im trying to add custom meta tags from facebook share button inside image.php file , and i dont know why they dont display, this is how my code looks: function add_facebook_image_code(){ ?> <meta property="og:url" content=" ?>/" /> <meta property="og:type" content="website" /> <meta property="og:title" content="example.com - <?=$post->post_title ?>" /> <meta property="og:image" content="<?=$post->guid ?>" /> <?php } add_action('wp_head', 'add_facebook_image_code'); I add this code inside image.php, is it possible to do it only inside that file ? Thanks and best regards.
Probably because when the execution is hitting your code is already too late to hook on `wp_head`. If you want to have your code in image.php, make sure you place it before `get_header()`. In any case, I would move the code to functions.php or dedicated file and maybe use `is_attachment()` to conditionally print the meta tags.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp head" }
add_rewrite_rule on default post type I need to add some rewrite rules on my posts in order to have one or more urls for the same post. E.g `/foo/post-name` and `bar/post-name` should lead the same post. I'm using this function: function addRewritePost() { add_rewrite_rule( '^foo/([^/]+)/?', 'index.php?name=$matches[1]', 'top' ); add_rewrite_rule( '^bar/([^/]+)/?', 'index.php?name=$matches[1]', 'top' ); } add_action('init','addRewritePost'); This code redirects from `foo/post-name` to `/post-name` and I don't want this kind of behaivor. How can I solve this issue?
This would be bad practice, since WordPress already has a functionality to do this built in. Rewriting the built in functionality is never a good idea. To achieve this the best way is to use Taxonomies. Lets say you create two categories: 1. Foo 2. Bar Now select the categories for the post in question and setup your permalinks structure to be `/%category%/%postname%/` and you will get: * foo/post-name * bar/post-name Hope this helps.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, rewrite rules" }
Display Current Time using shortcode I am using the below code to display current time in php supported time zones: <?php date_default_timezone_set('Asia/Kolkata'); $currentTime = date( 'd-m-Y h:i:s A', time () ); echo $currentTime; ?> We need to create few different pages in wordpress to display current time in different supported cities / timezones in wordpress pages through shortcodes in following format: [current_time timezone="Africa/Accra"] Please help us to write this function.
Add this code in Theme function file functions.php function timeZone_funch( $atts ) { extract(shortcode_atts(array('timezone' => 'Asia/Kolkata'), $atts)); /* Asia/Kolkata is default Timezone */ $output = ''; if (in_array($timezone, DateTimeZone::listIdentifiers())) { date_default_timezone_set($timezone); $currentTime = date( 'd-m-Y h:i:s A'); $output = $currentTime; } else { $output = "Invalid Timezone"; } return $output; } add_shortcode( 'current_time', 'timeZone_funch' ); USAGE: **[current_time timezone="Africa/Accra"]**
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "php, shortcode, date time" }
get_terms only show term if there is a post using it I have a custom post type called `user_images`. I would like to create some filters and populate the dropdowns dynamically. I am using the follow code: $post_type = 'user_images'; $taxonomies = get_object_taxonomies((object) array('post_type' => $post_type)); $terms = get_terms('image_categories'); foreach( $terms as $term ){ echo $term->name; } This is correctly listing my custom taxonomy `Image Categories` but it is showing terms even if none of the posts have that term assigned to it. How can I only list out the terms which are associated with posts and within this specific custom post type?
`get_terms` should hide empty terms by default, but you can force it to setting `hide_empty` argument to true: $terms = get_terms( array( 'taxonomy' => 'image_categories', 'hide_empty' => false, ) );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "terms" }
How to change WordPress theme outside of admin? Can't access dashboard I have extracted my theme via File Manager but it somehow crashed. I activated the theme and now I can not access my admin at /my-web/wp-admin/. Is there another way to change my theme since I cannot access the admin? Thanks.
There are a couple things you can do. **Option 1 - FTP** Easiest would be to FTP into your site and change the name of the currently active theme. Your themes are located in `\wp-content\themes\`. Temporarily changing the name will disable the theme. This should give you back access to the admin. **Option 2 - Database / PhpMyAdmin** You can also change the theme through the database, mostly likely via PhpMyAdmin. There are 3 option rows in wp-options that you need to change. Once you change these it will change your theme. * template – the “Theme Name” as defined in style.css * stylesheet – the actual name of your theme folder * current_theme - the actual name of your theme folder FYI - You can run the following SQL to narrow down just those 3 rows SELECT * FROM wp_options WHERE option_name = 'template' OR option_name = 'stylesheet' OR option_name = 'current_theme';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, wp admin, wp config" }
While Ajax is working well, media upload isn't showing the imagines Look at the image below, it has no javascript errors, and media upload still spinning forever :( I tried to install new Wordpress, also disabled all plugins, googled several times, I tried to do it all and still haven't fixed this error. Any other way to debug this issue? ![What are you waiting for????](
adding the following code to your .htaccess can resolve! PHP_value default_charset none PHP_value output_handler none Note: comment out the others code having utf-8
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "ajax, media" }
Update media library attachments I import image to wordpress via `wp_insert_attachment`. On frontend wordpress media library still don't know that image is imported. I need a way to update attachments in media library without refreshing page. I found partial solution: wp.media.frame.on('open', function() { if (wp.media.frame.content.get() !== null) { wp.media.frame.content.get().collection.props.set({ignore: (+ new Date())}); wp.media.frame.content.get().options.selection.reset(); } else { wp.media.frame.library.props.set({ignore: (+ new Date())}); } }, this); Problem with this part of code is that now when I try to upload photo using Media Library uploader, image is uploaded correctly but it's not displayed.
edit: ok after working on this for the last hour ive finally found a solution that works without affecting uploading and without messing with ignore or reset wp.media.frame.on('open', function() { if (wp.media.frame.content.get() !== null) { // this forces a refresh of the content wp.media.frame.content.get().collection._requery(true); // optional: reset selection wp.media.frame.content.get().options.selection.reset(); } }, this);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, media library" }
WordPress Link To Image Missing Dropdown I am on the latest version of WordPress. When adding/editing a image in Wordpress there's the **Link To Image** which normally provides a dropdown menu. For me it's a blank text box and I don't know how to fix it. I have uninstalled plugins with no luck. It's cross-browser on both Chrome and Firefox. Screenshot attached. **Screenshot** ![enter image description here](
This is what that section looks like to me. ![enter image description here]( Are you sure your not adding custom fields some where? Are you trying to use the "Link To" setting for an image block? See below. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, wp admin, media library" }
Setup a multisite to a running website I am trying to add a multisite to add another website in a diferent language. I followed the codex guide to config the multisite feature with subdomain. I enabled the multisite network on my main website (< added subdomain (< pointing to another directory. I got confused after this step. I installed a new wordpress on this directory with new database, enabled the multisite on wp-config.php but the new site do not have the sites network enabled, instead is asking for a new install of multisite feature in where should be my new website like < but I already have this feature enabled on the main website (< I tried to point to different paths but got 404 errors. What I am missing here?
> I enabled the multisite network on my main website (< added subdomain (< pointing to another directory. I got confused after this step. I installed a new wordpress on this directory with new database A multisite WordPress installation shares a single copy of the WordPress files, and a single database. Each site within the network gets a separate set of tables in the database, but it's the same WordPress installation. You should **not** create a separate folder and reinstall WordPress as you did. You should create the new "site" on the main WordPress installation and configure it (as it sounds like you did), then point your DNS for the subdomain to the same host (or virtual host) as your main WordPress installation.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "multisite" }