INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
WOOCommerce redirect after registration to account details I want to redirect users to account details after registering, by default it is redirecting to my account dashboard. This is where I want users to be redirected > mydomain.com/my-account/edit-account/ I found something like this, but I think it won't work function iconic_register_redirect( $redirect ) { return wc_get_page_permalink( '' ); } add_filter( 'woocommerce_registration_redirect', 'iconic_register_redirect' );
To get " _Account details_ " permalink (endpoint `edit-account`) you need to use function `wc_get_account_endpoint_url`. function wc_redirect_to_account_details( $redirect ) { $redirect = wc_get_account_endpoint_url('edit-account'); return $redirect; } add_filter( 'woocommerce_registration_redirect', 'wc_redirect_to_account_details' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic" }
What does selecting a page for GDPR privacy actually do? I get that you can generate a sample privacy page with the new GDPR update. I don't understand what it actually does? Is there an API endpoint or something? When you "select an existing page" what happens?
It will add a link to the selected page to wp-login.php and a link to it is included in the Erase Personal Data confirmation email. It also makes it easy for themes and plugins to link to it using the `the_privacy_policy_link()` function. The default themes all use this to add a link to the selected page to the footer.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "privacy" }
How to pass page as an argument like post in WordPress? I am using this code to pass arguments in posts: $args_automobile_just_launched_bike = array( 'posts_per_page' => 3, 'post_type' => 'post', 'order' => 'DESC', 'meta_query' => array( array( 'key' => 'wpcf-new-launch-bikes', 'value' => '1', ), ), ); This is the format of getting posts dynamically. How can I do the same for Page?
Pages are posts, you just need to change the `post_type` to `page`: $args_automobile_just_launched_bike = array( 'posts_per_page' => 3, 'post_type' => 'page', 'order' => 'DESC', 'meta_query' => array( array( 'key' => 'wpcf-new-launch-bikes', 'value' => '1', ), ), );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom field, pages" }
How to fix this warning:call_user_func_array() expects exactly 2 parameters, 1 given in D:\wamp\www\.......\wp-includes\class-wp-hook.php on line 286 I am creating Wordpress Dashboard Menu: add_action('admin_menu', 'personalised_menu'); function personalised_menu() { add_menu_page( 'Page Title' , 'Blog' , 'edit_posts' , 'menu_slug' , 'call_user_func_array' , 'dashicons-welcome-write-blog' ); add_submenu_page( 'menu_slug' , 'Add New Page' , 'Add New' , 'edit_posts' , 'add_new_page' , 'call_user_func_array' ); }
Replace `'call_user_func_array'` with name of the function to be called to output the page content. add_action('admin_menu', 'personalised_menu'); function personalised_menu() { add_menu_page( 'Page Title', 'Blog', 'edit_posts', 'menu_slug', 'display_main_page', 'dashicons-welcome-write-blog' ); add_submenu_page( 'menu_slug', 'Add New Page', 'Add New', 'edit_posts','add_new_page', 'display_secondary_page' ); } function display_main_page() { echo 'Content of "Page Title"'; } function display_secondary_page() { echo 'Content of subpage'; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, functions, array, warnings" }
Custom Avatars for Wordpress Comments VIA Website URL? I've tried a couple different wordpress plugins and solutions but nothing is quite what I'm looking for. I want to adjust my theme/wordpress so that avatars for my Wordpress commenters are grabbed from the "website URL" that people fill in. Does anyone know how I would go about doing this?
By default most of the time WordPress comments will include a "gravatar" (linked to the user's email address) when displaying comments, using WordPress built-in function `get_avatar()`. You can hook a custom function to the `get_avatar` filter to return another image. Something like this should do the trick for your use case: it filters `'get_avatar'` and returns an image with the comment author's website URL if it is set. Add this to your theme (or child theme) functions.php: add_filter( 'get_avatar', 'wpse310726_custom_avatar', 1, 5 ); function wpse310726_custom_avatar( $avatar, $id_or_email, $size, $default, $alt = null ) { $comment_author_url = get_comment_author_url(); if ( '' !== $comment_author_url ) { $avatar = "<img alt='{$alt}' src='{$comment_author_url}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />"; } return $avatar; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, comments, avatar" }
Redirect to https not working with .htaccess I have the following setup in my `.htaccess` file, but I am still able to go to my site via `http:` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # Rewrite HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^(.*) [R,L] </IfModule> # END WordPress Any idea what I could be doing wrong?
You've put the code in the wrong place. The HTTP to HTTPS directives must go _before_ the WordPress front-controller, otherwise it's simply never going to get processed for anything other than direct file requests. Your custom directives should also be outside the `# BEGIN WordPress` block, otherwise WordPress itself is likely to override your directives in a future update. For example: # Redirect HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule (.*) [R,L] # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress It is a "redirect", not a "rewrite". Change the `R` to `R=301` when you are sure it's working OK (as this should ultimately be a _permanent_ redirect).
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "redirect, htaccess, https" }
Query Post Based of Yoast Primary Category Class I can pull the terms from a post to return only the Primary Category that Yoast SEO plugin provides. But what I'd like to do is the following: Query latest 1 post from category "x". But, the post returned has to have that category set as the Primary. It can't return the latest if that post has not marked that cat as primary.
Yoast SEO stores the primary term ID as the post meta field `_yoast_wpseo_primary_{taxonomy}`. Knowing this you can use a meta query to get all posts with primary category ID `X`: $query = new WP_Query([ 'cat' => 'X', // Just in case Yoast data corrupted & post no longer attached to X term but primary meta remains 'meta_query' => [ [ 'key' => '_yoast_wpseo_primary_category', 'value' => 'X', ] ], ]);
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugin wp seo yoast" }
Custom Post Type slug same as page name causing a conflict I have a Custom Post Type all set up. I would like the slug to be the same as a page name, because all of these CPT's will be queried on that particular page (/team-members). If I set the Custom Post Type slug to the page URL, that particular page doesn't load the page template anymore. It loads a broken post template. My Custom Post Type rewrite: $rewrite = array( 'slug' => 'team-members', 'with_front' => false, 'pages' => false, 'feeds' => false, ); This allows me to generate the **proper URL** of: < The problem now is when I try to access the page: < it does not render the correct page template file (aptly titled `page-team-members.php`). Saving permalink settings didn't work. **How can I create the URL slug of my Custom Post Type to not interfere with a page titled the exact same thing?**
What is appearing at < is the 'post type archive' for your post type. It's the automatically generated list of posts created by WordPress. If you don't want the post type to have an archive you can disable the archive by setting the `has_archive` argument to false: register_post_type( 'post_type_name', array( 'has_archive' => false, ) ); Now you can create a page at /team-members without a conflict.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom post types, permalinks, url rewriting, page template" }
How to handle security on a wordpress site? I'm doing a draft of a WordPress site on localhost. If I am using PHP snippets to do the sort of `back-end` functionality. How do I know that, when this goes to a real platform, the `php` code cannot be tampered with? How can I ensure that login information (password especially) is secure? Should I be doing password validation in the PHP snippets, or is there a more secure way?
You cannot be 100% sure you are safe. Check this Security reading from WordPress. That been said, there are some things you can do. * Keeping WordPress Updated * Keeping theme and plugins Updated * Use Strong Passwords * You can use a Security Plugin, although it's arguable. When a client request it I use Sucuri. * Change the Default “admin” username * Limit Login Attempts * Change WordPress Database Prefix * Use double authentication All that won't be enough but it will give intruders a hard time trying to get in.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "customization, security" }
Function to allow "Anyone can register"? I'd been crawling the codex but can't seem to find a function that will allow me to programmatically enable the User registration system. Hopefully, I can make a custom plugin that will enable User registration system by default.
You can do it by using this code: add_action('init', 'update_anyone_can_register'); function update_anyone_can_register() { update_option('users_can_register', true); } I tested on my `functions.php` file and it worked as expected.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, users, user registration" }
Logs to check when the plugin was first installed for the first time Is there a way to check when for the first time a particular plugin was installed in the WordPress? I need this information to prove my integrity somewhere.
When plugins were activated is not logged by WordPress. If the plugin hasn't been updated then the file modified time in the file system might be useful for telling you when the plugin was at least uploaded. If you have regular database backups then you could look at `active_plugins` in `wp_options` to get an idea of when plugins were activated based on which backup the plugin first appears in.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "plugins, plugin development" }
Apply text based styling done for a single post in WPBakery to all posts / create a template out of it I work on a project with several custom post types. One of these post types is called BSP. For one single specific BSP (called test BSP) I created a whole design with WPBakery, as shown on this image: Showing the WPBakery elements ![]( The same template as plain text ![enter image description here]( **Question:** I have several other BSP custom posts. While I can just copy the plain text of this test BSP and paste it to the other custom posts of type BSP, how can I make this the default template? I'm more specifically looking for a way to have this template automatically being applied to any new post of type BSP I create.
I have found a solution to my problem. It is very easy and rather obvious. **To save the template:** First click on the template icon above the edit page of the blog post you want to copy the template from. ![enter image description here]( Next: go to the my templates tab and save the template as a custom template ![enter image description here]( **To make the saved template the default template:** Click on the WPBakery tab and select the template for that specific post. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "custom post types, posts, templates" }
how can remove this element to avoid having two menu buttons with one that shows unnecessary pages I like the menu buttons when the website is viewed in the desktop view but I don't like it whenever it is viewed in the mobile view. it brings two menu buttons and one of the buttons shows unnecessary pages while the other one just works fine bellow is the inspected element that I thought has to be removed to avoid this menu button but I don't know how to go about it or you can visit my website Here and try to minimize the browser to mobile ratio to see what exactly I have to do to work out this issue. <button class="menu-toggle" aria-controls="site-navigation" aria-expanded="true"><span>Menu</span></button>
You can add this CSS code to hide that menu: .secondary-navigation, .menu-toggle { display: none; } Of course, that option doesn't remove it but just hide it. To try to remove it, since I think you don't want to get rid of the `Max Mega Menu` you can try to go to **Appearance > Menus** and find the menu on top and check if it has any **Display location** checkbox marked so you can uncheck it. I didn't find any options for a Secondary menu on its documentation so it's kind of weird.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "menus" }
Where to put coding a validation script for store? I am pretty new using WordPress and was asked to validate the number of items in the cart for an eCommerce site that lets you "make a pack" in which you have several steps, step 1 is a page in which you select the box, this doesn't need validation but the next 4 steps do, each step is a new page and each has a different amount of the item that you need to select, what I need is to either disable the hyperlink that says "Next step" until you select the correct amount of items for each step or just display a message when you click with the incorrect amount Now my question is not code itself but where to put it in WordPress, I checked everything in the WordPress admin part of the site and on the hosting site but can't find where I am supposed to code the validation for each page.
Normally on WordPress you use Your Theme `Functions.php` to put that code. But in this case we are talking about a WordPress with WooCommerce (I'd think), so if you add custom code to your theme as I told you normally is the case, it will be gone if you change your theme, for that reason and if you aren’t sure where to place the code, choose one of the following options to add the code to your site. ## PHP Use the Code Snippets plugin or similar. ## JavaScript Use Simple Custom CSS and JS.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, javascript" }
Clients with empty username are not receiving request new password email I am looking after a old site from a client and a lot of users dont have username. I had setup in woocommerce "When creating an account, automatically generate a username from the customer's email address", but for some reason it is not creating username for the new user, so I unticked that and left the field mandatory. Now, If an user with blank username request a new password, wordpress doesnt send an email. Only if I go manually to the phpmyadmin and included it. However there are more than 500 users without username. Is there a way to automatically get the user email for example and include in the username field? Or make wordpress send email even with no username? Thank you,
WordPress functions doesn't allow to modify user login then you need to change directly the database. make a backup of you database and try this to fill login with something like `user4589` UPDATE `wp_users` SET `user_login` = CONCAT("user", ID) WHERE `user_login` = ""
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, user registration, password, phpmyadmin" }
is singular and is home not working I am creating a theme and i have added custom hooks to make the developement easier. when using the code in functions it works in all pages. the code is below add_action('before_footer','post_prev_nex'); function post_prev_nex(){ the_post_navigation(); } But when i try to put a conditional, it doesnt work. if (is_singular()) { add_action('before_footer','post_prev_nex'); function post_prev_nex(){ the_post_navigation(); } } what is the problem here. Thanks in advance
Put condition inside your function: add_action('before_footer','post_prev_nex'); function post_prev_nex() { if (is_singular()) the_post_navigation(); } In your version `is_singular()` is executed when `functions.php` file is loaded, not while displaying the page.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "conditional tags" }
How to narrow the area between buttons on Helium theme sidebar? I have WordPress based site. I used Helium theme and added a sidebar. On this sidebar, I added a few buttons from SiteOrigin widgets plugin. The buttons are being spaced between them automatically, and I would like to narrow this spacing between them. How can I do that?
Use this CSS code. .sidebar .widget { margin-bottom: 40px; } Keep in mind currently it has 80px, so change it for what looks best for you. In case you don't know how to add CSS, check this out.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, themes, widgets, sidebar" }
WP Site Hacked, Serp Google Spam It all began when Google Ads suspended my ads because they found a malware in my WP site. I tried to do scan with some free plugins: Wordefence, anti-malware and Securi, or online tool like: sitecheck.sucuri.net and transparencyreport.google.com, but I didn't find any malware though the SERP has been compromised!!there are about 100 fake url like these: * ` * ` I'm at my wit's end!! Is there someone that can help me? Thanks
I've cleaned up a few hacked sites, and have developed my own personal procedure here. But there are many googles on how to clean up. The basics are change the passwords of everything (hosting, database, FTP, users), reinstall WP and all themes/plugins from a known good source (WP repository), and manual inspection for bad files. It's a bit of work, but I've been successful. The link in the comments is also a good place to start.
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "hacked" }
How to display line breaked meta values in table? I have meta_key 'oyuncular' and it has meta values with line breaks. I want to get them and display in table with two column. Name and Role Name ![enter image description here]( $names = get_post_meta( get_the_ID(), 'oyuncular', true ); $namesArray = explode( '\n', $names); <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr class="table-success"> <th>#</th> <th>Name</th> <th>Role Name</th> </tr> </thead> <tbody> <?php foreach( $namesArray as $key => $name ) { ?> <tr> <th scope="row">1</th> <td>Name</td> <td>Role Name</td> </tr> <?php } ?> </tbody> </table> </div>
You can use `explode()` or `preg_split()`, like this: $i = 0; foreach( $namesArray as $key => $name ) { $arr = explode( ' -', $name, 2 ); //$arr = preg_split( '/\s+\-/', $name, 2 ); $name2 = isset( $arr[0] ) ? trim( $arr[0] ) : ''; $role_name = isset( $arr[1] ) ? trim( $arr[1] ) : ''; if ( $name2 || $role_name ) : $i++; ?> <tr> <th scope="row"><?php echo $i; ?></th> <td><?php echo $name2; ?></td> <td><?php echo $role_name; ?></td> </tr> <?php endif; } Also, you need to wrap the `\n` in double-quotes: $namesArray = explode( "\n", $names); // not '\n' Otherwise, the `\n` will not be evaluated as "new line".
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "array" }
Page navigation doesn't seem to work when I add offset? I am trying to get a simple navigation to work, it works when I don't use offset in the arguments. but I like to do something special with the first post $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $args = array( 'posts_per_page' => '6', 'cat' => 5, 'orderby' => 'date', 'order' => 'DESC', 'paged' => $paged );` So for these I add $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $args = array( 'offset' => 1, //<--- 'posts_per_page' => '6', 'cat' => 5, 'orderby' => 'date', 'order' => 'DESC', 'paged' => $paged ); But with offset the post are not returning correctly just the first 6???
If you sets a manual offset value, pagination will not function because that value will override WordPress's automatic adjustment of the offset for a given page. In order to use an offset in WordPress queries without losing WordPress's pagination features, you will need to manually handle some basic pagination calculations. For example you can use this bellow code $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $offset = 1; $ppp = 6; $page_offset = $offset + ( ($paged-1) * $ppp ); $args = array( 'offset' => $page_offset, 'posts_per_page' => $ppp, 'cat' => 5, 'orderby' => 'date', 'order' => 'DESC', 'paged' => $paged ); Try that, then let me know the result. **Note:** Follow this <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, pagination, offsets" }
How to check whether Gutenberg editor is installed or not i want to ask a simple question that what to do if i have to check whether a pliugin is installed. for example i want to run a code, which says, if Gutenberg is installed, then run the following code else not. i have created this code, but not sure will this work or not if(defined('Gutenberg')) { } is this the right way or is there any other way to that. thanks in advance
Checking if a plugin is installed is always a bad idea as plugins might be installed but for whatever reason not function, or function in different way than you might expect. Specifically for gutenberg as it stands right now for example, post types that are not exposed in the REST API can not be edited by gutenberg. As always, if you have a functionality that depends on a plugin you should hook to its actions and filters to avoid the need to guess if it is active or not (the fact that the action is "called" is the best indication for activity), or ask the plugin author to add the kind of action/filter you might find useful.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "block editor" }
Assign all Post in Wp to a specific Category I Cleared off all data in wordpress wp_postmeta, wp_terms, wp_term_relationship, wp_term_taxonomy. I have post content of 50k. Is there any way I can assign all the 50 posts to a new Category I just created, I will recommend using.?
1. Find out the ID of the category that you want to assign. You'll see it in the URL when editing the category (URL will be something like `?taxonomy=category&tag_ID=3&post_type=post`, here **3** is the ID) 2. Assuming that the ID is 3, you can now run this query in your database (eg via PHPMyAdmin) INSERT IGNORE INTO wp_term_relationships (object_id, term_taxonomy_id) ( SELECT DISTINCT ID, 3 FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' ); If you use a different prefix than `wp_`, be sure to change it. Also change the **3** to the ID you want.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, database" }
How to create User friendly URL in WordPress? I need to create a custom URL for all users to view user details. My user information page URL is: ` I need to create a URL like this: ` Is it possible with WordPress?
There is a simple solution for this. Add this code to your theme's `functions.php`. After that you need to re-save your permalinks from `Settings->Permalinks` in WordPress dashboard. function remove_author_base() { /** * Remove Author base from Wp Links * Serkan Algur */ global $wp_rewrite; $wp_rewrite->author_base = ''; } add_action('init', 'remove_author_base', 1); I tested this code on my localhost (apache server with htaccess enabled). Please comment if code works or not.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "url rewriting" }
How to update serialized post meta? I have serialized post meta. And i want to update single meta key. It looks like this: ![enter image description here]( In array: $kisiArray = array( 'option1' => 'foo', 'option2' => 'bar', 'option3' => 'apple', 'option4' => 'orange' ); I want to update only `'option3'` to `'peach'` so i am using update_post_meta function. update_post_meta( $post_id, 'themeOps', ??? ); But i don't know what i must put the `meta_value` section. When i pust **peach** , it changes all meta keys to **peach**.
You must read custom field `themeOps` first, update index `option3` in array and then save/update whole array. $kisiArray = get_post_meta( $post_id, 'themeOps' ); $kisiArray['option3'] = 'peach'; update_post_meta( $post_id, 'themeOps', $kisiArray ); * * * **Update** (sort by custom field) $args = array( 'post_type' => 'post', 'meta_key' => 'themeOps_option3', 'orderby' => 'meta_value_num', 'order' => 'ASC', ); $query = new WP_Query( $args ); More examples you find in Codex
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "posts, array" }
Private member page I need to make a private page for subscribers in my Wordpress website I don’t want to use plugins so I’m asking what is better, add the capability to subscribers to read private pages or maybe create a custom page template with conditions?
You can do it without plugins, you just have to allow `subscribers` to see Private posts and pages, depending on what you want, so you have to put this code in your **functions.php** $subRole = get_role( 'subscriber' ); $subRole->add_cap( 'read_private_posts' ); $subRole->add_cap( 'read_private_pages' ); And then simply create a private post or page and it will works as expected. Tested.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "customization, membership, members" }
How can i force Display names to be the same as Usernames? i need help. My users register to the website. They type their username **user_login** (see chello) but the Display name (see chello04) is not the same. It has a random two digits at the end. Is there a way to force Display names to be the same as usernames? ![enter image description here]( ![enter image description here](
You can use the `wp_pre_insert_user_data` filter. function wpse_filter_user_data( $data, $update, $id) { if( isset( $data[ 'user_login' ] ) ) { $data[ 'display_name' ] = $data[ 'user_login' ]; return $data; } $user = get_user_by( 'email', $data[ 'user_email' ] ); $data[ 'display_name' ] = $user->user_login; return $data; } add_filter( 'wp_pre_insert_user_data', 'wpse_filter_user_data', 10, 3 ); You'll probably want to use Javascript and/or CSS to hide the field too for a better user experience. $( '.user-display-name-wrap' ).remove(); .user-display-name-wrap { display:none; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "plugins, custom field, users, user registration, username" }
Can't get JS code to work with shortcode I am trying to create a plugin and I've got stuck. I am trying to register and enqueue a script from a shortcode: This is my shortcode: add_shortcode( 'gear-guide', 'gg_product_front_end' ); This is the function it calls to: function gg_product_front_end() { echo '<p id="test">Test!</p>'; wp_register_script( 'gg_loadProducts_frontEnd', plugins_url( 'js/front_end.js', __FILE__ ), array( 'jquery' )); wp_enqueue_script( 'gg_loadProducts_frontEnd' ); } And this is the JavaScript: function gg_loadProducts_frontEnd() { console.log( 'Test!' ); } JavaScript doesn't work, but I am not getting any error, neither php nor js.
You need to return the Shortcode generated string, not `echo`, like this: function gg_product_front_end() { wp_register_script( 'gg_loadProducts_frontEnd', plugins_url( 'js/front_end.js', __FILE__ ), array( 'jquery' )); wp_enqueue_script( 'gg_loadProducts_frontEnd' ); return '<p id="test">Test!</p>'; } Also, you need to call the JavaScript function, like this: function gg_loadProducts_frontEnd() { console.log( 'Test!' ); } gg_loadProducts_frontEnd(); Otherwise `Test!` will not be logged in Browser Console. Also, check This Post to enqueue Scripts / styles when shortcode is present.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugin development, shortcode, javascript, wp enqueue script, wp register script" }
How to load terms of a custom taxonomy of a product in woocommerce cart page I have created a custom taxonomy called "job_orders" to a products in woocommerce. I want to edit cart page and show then terms of job_orders inside cart table. currently I'm using the below script which echo all the terms , I want to show only the categories select in back end.I appreciate if anybody can help on this. $terms = get_terms('job_orders','hide-empty=0&orderby;=id'); //shuffle($terms); // dlete this line if you don't want it random. $sep = ''; foreach ( $terms as $term ) { if( ++$count > 60 ) break; // number of tags here. //echo $sep . ''.$term->name.''; echo $sep . $term->name; $sep = ', '; // Put your separator here. } Above goes inside below woocommerce loop in cart.php foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { }
found the code that do the trick $terms = get_the_terms( $product_id, 'my_taxo' ); foreach ($terms as $term) { $product_cat = $term->name; } echo $product_cat ; from below discussion < Thanks for the authors
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, custom taxonomy, woocommerce offtopic" }
Theme menu in Admin Panel I am new in WordPress Development. How can I get `Menus` in Admin Panel like below ? ![enter image description here]( I am trying to develop a theme. But I couldn't display that. ![enter image description here](
You need to register custom menus in your theme - < You first need to register your menu in functions.php like so: add_action( 'after_setup_theme', 'register_my_menu' ); function register_my_menu() { register_nav_menu( 'primary', __( 'Primary Menu', 'theme-slug' ) ); } Then, where you want your menu to appear - usually header.php - you call the function: wp_nav_menu()
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "menus, wp admin, admin menu" }
Making a custom help center page I am working now on a new WordPress theme and I want to make a help center system to allow users that will buy my theme do add helper articles. So my plan is: 1- Make a normal new page and create the page-help.php file. 2- Create two post types first named sections and the second article. 3- Add the sections posts and articles inside the page-help file. The problem now that I don't need the link of sections and articles be directly like this: I want to make a rewrite rule to add help beside the section and article post type to be the final link like that: Really this is very important for me and I hope anyone helps me to make this or at least something like that I want. Thanks in advance.
You can achieve this when you register your post types. The `slug` can be a path: $section_args = array( 'rewrite' => array( 'slug' => 'help/section' ), // your other args... ); $article_args = array( 'rewrite' => array( 'slug' => 'help/article' ), // your other args... );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, permalinks, pages, url rewriting, rewrite rules" }
Adding Age Based Wordpress Category I want to create a WordPress blog that shows public profile. I have added a category for that "Age" because i want to show the list of all the people who have same "Age". Now the problem is with age. I don't want to update every individual's age again and again. A person's age will change as per their DOB. How to create the age-based custom taxonomy that changes automatically for an individual post?
You might like to: * Use a custom field as @Fayaz mentions above. Advanced Custom Fields will be the best for this (and you have it already). * Add a new field (and I'd call it 'Year of birth') using Range. You could use a datepicker, but this way it's cleaner and less intrusive: ![Year of birth]( * This will then give you nice stable meta data for each post ('stable' as in their 'year of birth' doesn't change; age does!). * You can then 'call' that meta data depending on what you want. * If you wish to reference posts that are of a certain age range, you can do this with a WP_query using meta_query. * If you want to show someone's age on a post, you could use **current_year** minus **Year-of-birth**. Note that this requires some level of development. This is Wordpress development after all..!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy" }
Apply Wordpress function on specific woocommerce product categories only I have the following function which I need to apply on a particular category only: function ChangeSelectTitle($woocommerce_product_categories_widget_args){ $woocommerce_product_categories_widget_args['show_option_none'] = __('Select your Device/Brand'); return $woocommerce_product_categories_widget_args; } if( $product_cat_id == 6 ) { add_filter('woocommerce_product_categories_widget_dropdown_args', 'ChangeSelectTitle'); } The category ID is 6. I have tried putting `$product_cat_id == 6`to identify the category page but it's not working. How to make it work?
You're trying to use `$product_cat_id` even though it isn't defined anywhere. If you want to know the current category being viewed you need to use `is_product_category(6)`, but you need to use that _inside_ the callback function (`ChangeSelectTitle()`), because WordPress hasn't determined whether it's a category archive yet when it runs functions.php. function ChangeSelectTitle($woocommerce_product_categories_widget_args) { if ( is_product_category(6) ) { $woocommerce_product_categories_widget_args['show_option_none'] = __('Select your Device/Brand'); } return $woocommerce_product_categories_widget_args; } add_filter('woocommerce_product_categories_widget_dropdown_args', 'ChangeSelectTitle');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, woocommerce offtopic" }
How can I create this type of table/catalog? ![SCREENSHOT]( Hello there! I am a WP Beginner and I am banging my head on how to recreate this table/catalog. I went through a couple of plugins like Ultimate Product catalog, MyListing (paid) and most of the WP Table creators. The point is I want it as close as the one on the screenshot. So before I take any action I would like to hear your opinions. Thank you and have a productive week!
1. You should create custom post type - you can do it with code in functions.php or using a plugin 2. Create basic page template to loop through new post type 3. Add custom fields to store extra data as in tour screenshot. I usually use acf plugin for it 4. Fine tune your new page template with the display of custom fields. That’s it
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "table" }
I'd like to add a button under the "Add to Cart" button which says "Buy on Amazon" and links to my Amazon product page I'm hoping for some "additional CSS" I can add to my WordPress customization to get this extra button on my product page!
You can copy this code to your `functions.php` and you will add a button under Add to Cart Button. add_action( 'woocommerce_after_add_to_cart_button', 'content_after_addtocart_button' ); function content_after_addtocart_button() { echo '<div class="content-section"><br><br><a href=" id="amazonBtn" type="button" value="Buy on Amazon"/></a></div>'; } Change the Google link for your Amazon link.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "woocommerce offtopic" }
Wordpress Editor completely blank Although the classic editor works, I am unable to use Gutenberg. When I disable plugins in wp-content (by changing plugins to pluginsOLD), I can edit everything just fine. How can I restore the new editor's functionality?
You already know it's a plugin problem, so now it's time to find which is the plugin that is doing it but deactivating each plugin one by one and checking to find the one, once you find the faulty plugin you will have to: * Replace it with a similar one * Trying to debug it to find it's problem But to be honest, normally it's better to use another plugin that does the same or code the functionality of the faulty plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, block editor" }
Getting an array out of WPQuery I have a query like this i will get the id's for product. This works fine: function ids(){ $args = array( 'numberposts' => -1, 'post_type' => 'product', 'meta_key' => 'wppl_is_dax', 'meta_value' => '1' ); // query $the_query = new WP_Query( $args ); if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post(); global $product; return $product->get_id(); endwhile; endif; wp_reset_query(); } But now i want to use the output from the above query in the below function tester2(){ $targetted_products = array(/* the ids from above function- ids()*/); } I am only getting one id if i use $targetted_products =array(ids());
Your function returns `$product->get_id();`, instead of that, you should save those values into an array and at the end return that array. function ids(){ $args = array( 'numberposts' => -1, 'post_type' => 'product', 'meta_key' => 'wppl_is_dax', 'meta_value' => '1' ); // query $the_query = new WP_Query( $args ); $allIds = array(); if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post(); global $product; array_push($allIds,$product->get_id()); endwhile; endif; wp_reset_query(); return $allIds; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "wp query, array" }
Firstname and lastname greyout or hidden Billing details at next checkout like username is hidden I have a woocommerce site designed for max and min quantity and price range pick like donation. I want something like, if I am registering at checkout, filling username, password, firstname, lastname, email and phone no., I don't want the fields in my next checkout. Same like username and password are hidden in the checkout, if you are already registered. I just want these fields to be hidden: firstname, lastname and email id if possible.
Use filter `woocommerce_checkout_fields`: add_filter( 'woocommerce_checkout_fields' , 'checkout_change_fields' ); function checkout_change_fields( $fields ) { return $fields; } more samples <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Multiple non-hierarchical custom taxonomies frequently used terms showing up in first selected taxonomy box I'm using WordPress 4.9.8, and I'm declaring multiple non-hierarchical custom taxonomies to use on a post type called "inventory". The non-hierarchical custom post types use the tag cloud style interface in the Wordpress backend for content editors to categorize inventory. When I click on "Choose from the most used tags" in one of the custom taxonomy boxes it loads the tag cloud as expected. But when I click on "Choose from the most used tags" in a second custom taxonomy box, the tag cloud loads in the first custom taxonomy box. Is there a way to fix this? Or, is there another interface I can use to access the custom taxonomy terms other than the tag cloud? I want to keep the taxonomies non-hierarchical. Thanks and regards
I found a solution that serves my purposes. I found this plugin (< that will allow me to use Radio Buttons for taxonomies instead of the tag cloud, so I avoid the bug with the tag cloud by using this interface instead. It only allows posts to be tagged with one term from each taxonomy at a time but that is fine for my case.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy" }
How do I edit the php/html for a particular post? I am new to Wordpress but I am comfortable coding in html/php and want to create custom forms on some of my posts. My site is currently running on localhost. I feel very silly because I have been searching through my `/var/html` folder for an embarrassingly long time trying to find out where I can edit a page called "My Profile". I was expecting to see some kind of auto-generated `my_profile.php` file or something. The page itself is identified with `page_id=10` , but I don't see anything about `page_id` within the file structure either. Where does the "My Profile" code live?
It's useful to understand how things work in WP. Content (pages, posts) are stored in the WP database. The 'style' of the site - how it works, how pages are built, how it looks - are in the theme of the site. Within the theme are templates - that defines how a post is displayed to the end user. To understand templates - and themes - check out my answer to this question: Need help on Wordpress and php . This page is a good place to start learning about how WP works: < . Look at themes, templates, template hierarchy, etc. Find a basic theme, then make a Child Theme to 'mess' with. (The above link will get you to Child Themes info.) Edit a template. Pages and Posts are edited via the Admin pages. Log into admin, then look at the Pages or Posts items. Edit a page, and see the changes. But the "Where to Start" is a good place to start learning. Have fun. WP is great to modify, frustrating at times, but will give you a sense of accomplishment.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, html, filesystem, wp filesystem" }
Is it possible to register a new template file? I'm trying to create a custom user dashboard on the front end using a rewrite rule to `/dashboard/` and a custom theme file `dashboard.php`. I notice that when loading in `dashboard.php`, I have to manually include `wp-blog-header.php` or the WordPress functions don't work, and that `get_page_template()` returns `page.php` instead of `dashboard.php`. Is there a proper way to register `dashboard.php` as a custom template in the same manner that, for example, the 404 page is registered? I'd like this page to operate independently of any page in the back-end, and just utilize my custom code.
I would strongly suggest you use a WordPress page template. At the top of `dashboard.php`: <?php /** * Template Name: Dashboard */ Now create a page called "Dashboard" and assign it the dashboard template. This way you're not loading WordPress yourself (nearly always bad) & WordPress & all your plugins will function as normal (creating custom endpoints in WordPress that don't ultimately map to a loop/post object can hit a lot of problems as vast swathes of the frontend assume they do).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "templates, rewrite rules" }
How to reset the post ID increment So, after working on a script that imports tons of data from another API, and doing lots of testing, all new posts I make have a post ID above 10,000,000. Thing is, now that I'm done, all my test data is gone, and my last "real" post has the ID 88. Is there a method to "reset" my post ID's, so that the next one I make has the ID 89? I know that there's no real need to do this, but I plan on maintaining this site for many years and it'll be annoying. Worst case, I can just reinstall and export/import.
I also happened to me once, I only had like 10 real post, so what I did was to go to **phpMyAdmin** , make sure your that on my `wp_posts` and `wp_posts_meta` tables are only information about the 10 real posts IDs, from the `mysite/wp-admin/export.php` I exported all the posts (10 of them), I run the following SQL query on **phpMyAdmin**. DELETE FROM wp_posts; DELETE FROM wp_post_meta; TRUNCATE TABLE wp_posts; TRUNCATE TABLE wp_post_meta; And finally, I import again the 10 posts, after that the ID was bad to normally, mine was only around 10000 tho, but it should work nonetheless.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "database" }
Need to display author's email id in the "Edit post" field in wp dashboard. How do I do this? I have created a custom post type & have enabled frontend posting for the same. I need the Edit post page to display the original author's email id. I already have "post author" displayed, but that just gives the name & username of the author. How do I go about doing this?
Probably you use `get_post` on edit page with query object. You can simply use `$post->post_author` on edit page. For example; $editableid = get_query_var('id'); $postedit = get_post($editableid); $author_id = $postedit->post_author; //Always return author ID value. <input type="hidden" name="post_author" value="<?php echo $author_id;?>" /> I hope this code piece helps you. EDIT : For email you use the_author_meta with your `$author_id` value.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts, author" }
Editing Header with a Page Builder Is it possible to edit my site's header with a page-builder plugin, such as Page Builder, Elementor, or Gutenberg? I don't want to be stuck in the constraints of the theme and/or Wordpress's idea of how a header should be structured. I essentially just want to define a block section either above and/or below the menu that appears on every site page.
It seems that this isn't possible without additional plugins/development. For instance, Beaver Builder Header Footer is a plugin that accomplishes this for the Beaver Builder page builder. And the pro version of Elementor allows this. They both require compatible themes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "headers, custom header" }
Add rewrite rule to call front-page.php? I am trying to create a multilanguage website. And I have set my home page to a **static page** in my WP admin area. This **home page ID is 2** and it calls `front-page.php` template when I am on the home page at this address, for example, ` So for a french version, I have added a new rewrite rule so I have this url, ` and its call the same home page which is ID 2. add_rewrite_rule( '^fr/?$', 'index.php?&p=2&lang=fr', 'top' ) But why it calls `index.php` template instead but **not** `front-page.php`? How can I make ` to call `front-page.php`?
As I pointed in my comment, in the rewrite rule there, change `?&p=2` to `?page_id=2`. Because `p` is used for querying a Post (i.e. post of the `post` type). So for Pages (i.e. post of the `page` type), use `page_id`. To prevent ` from being redirected to ` you can cancel (the) canonical redirect, like this: add_action( 'template_redirect', function(){ if ( is_front_page() ) { remove_action( 'template_redirect', 'redirect_canonical' ); } }, 0 );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "url rewriting, rewrite rules, frontpage" }
Change header.php of a specific Wordpress Multisite I wish to change to change the header.php of child theme and add `<meta name="theme-color" content="#ff6600" />` into it. However when using the editor under 'Network Admin', changes are reflected across all the wordpress multisites. How can I access change the header.php of a specific multisite, as the editor is not available in the multisite's dashboard. Thanks!
From what I understand you're using one theme across multiple blogs inside your network? If that's the case, you could edit the `header.php` to add a bit of php logic into it to check on what blog your header is currently loaded. To make it work, you'll need to get the ID of a blog you want to apply the change to (check for it in your network admin on a screen that lists all the blogs). Then edit the `header.php` and add something like this: <?php // 6 in my example is the blog ID that I want to apply the change to if ( 6 === get_current_blog_id() ) { echo `<meta name="theme-color" content="#ff6600" />`; } ?> The other way would be to create a new child theme with a header.php file that has the additional meta tag and activate it only on a particular blog. Hope that helps!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, child theme, headers, network admin" }
WordPress Global Redirect I need to expand on this discussion Redirect entire website to a single page to include two pages rather than one. On this site, I need two pages to be live and all others to redirect to the home page. < This is the code I'm trying and I get a perpetual redirect. add_action( 'template_redirect', 'wpse_76802_goodbye_redirect' ); function wpse_76802_goodbye_redirect() { if (( ! is_page( 16372 ) ) || ( ! is_page( 16384 ) )) { wp_redirect( esc_url_raw( home_url( 'index.php?page_id=16372' ), 301 ) ); exit; } }
`is_page()` supports array too, so you could do something like this. add_action( 'template_redirect', 'wpse_76802_goodbye_redirect' ); function wpse_76802_goodbye_redirect() { if ( !is_page( array( 16372, 16384 ))) { wp_redirect( esc_url_raw( home_url( 'index.php?page_id=16372' ), 301 ) ); exit; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "redirect, wp redirect" }
Display Random Post in Author Page By default when we open any author's page, WordPress displays latest posts from that author first. What I want: If anyone opens any author's page, it will display _random_ posts from that author. I have searched everywhere but I couldn't find any solution.
use this query in themes `functions.php` function ng_author_query( $query ) { if ( $query->is_author() && $query->is_main_query() ) { // your code to set $current_user_name here $query->set( 'orderby', 'rand' ); } } add_action( 'pre_get_posts', 'ng_author_query' ); Let me know if you have any problem?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "author" }
Custom column into custom taxonomy (img tag with slug-name as file name) How to add $term->name (slug) into custom column cells as the file name? $columns = '<img src="SLUG_NAME.jpg">'; function custom_column_header( $columns ){ $columns['image'] = 'Image'; return $columns; } add_filter( "manage_edit-genre_columns", 'custom_column_header', 10); function custom_column_content( $value, $column_name, $term_id ){ if ($column_name === 'image') { $columns = '<img src="SLUG_NAME.jpg">'; } return $columns; } add_action( "manage_genre_custom_column", 'custom_column_content', 10, 3);
You can use `get_term_field()` like this: if ($column_name === 'image') { $slug = get_term_field( 'slug', $term_id ); $columns = '<img src="' . $slug . '.jpg">'; } Or `get_term()`: if ($column_name === 'image') { $term = get_term( $term_id ); $columns = '<img src="' . $term->slug . '.jpg">'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, columns" }
How can I use get_bloginfo('admin_email') in a custom PHP file? How can I use **get_bloginfo('admin_email')** in a custom PHP file located in the parent theme root directory? I've built a custom form and a PHP mail script separately, but now I'd like to send the form data to the WP Admin email address with Bcc. $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= 'From: <[email protected]>' . "\r\n"; $headers .= 'Bcc: <'. get_bloginfo('admin_email');'>'. "\r\n"; mail("[email protected]","Form Application",$admin_email_body,$headers); Do I need to include Wordpress functions in the PHP file? Thanks
You can include the `wp-load.php` in your PHP file, but, I do not recommend this method. It's better you use the `wp_enqueue_script()`. See this article to get more information. <?php include "../../../wp-load.php"; $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= 'From: <[email protected]>' . "\r\n"; $headers .= 'Bcc: <'. get_bloginfo('admin_email') . '>'. "\r\n"; mail("[email protected]","Form Application",$admin_email_body,$headers);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "customization, bloginfo, phpmailer" }
Sent comments notifications to multiple users I am new to wordpress I want to send email notifications for commenting in blogs. Currently it is going to only one user. I tried 'comment notifier' plugin but got negative result. I tried the below code add_filter('comment_notification_recipients', 'override_comment_notice_repicient', 10, 2); function override_comment_notice_repicient($emails, $comment_id) { $comment = get_comment( $comment_id ); if ( empty( $comment ) ) return $emails; $post = get_post( $comment->comment_post_ID ); return array('[email protected]'); } but it isn't working. I googled it but couldn't get anything. Please help me solve it.
Something like this should work: add_filter('comment_notification_recipients', 'override_comment_notice_repicient', 10, 2); function override_comment_notice_repicient($emails, $comment_id) { $admins = get_users( array( 'role__in' => array('administrator'), ) ); foreach ( $admins as $user ) { $emails[] = $user->user_email; } return ($emails); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, email" }
Plugin activation error due to unexpected output I am getting the following error when I activate my plugin: > The plugin generated 22 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin. And here's my plugin code: <?php /* Plugin Name: Hello World */ echo "<h1>Hello, world!</h1>"; ?> I know we get this error usually when there's some syntax error in the code. I have checked, there are no blank spaces, `\n`, `\t`, `\r` or any kind of special characters at the starting or ending of the file. I don't understand, this is the most minimalist plugin one could ever create, what's wrong? * * * **EDIT 1:** I don't get the error if I remove the `echo "<h1>Hello, world!</h1>";` line.
Plugins are loaded before headers are sent. The reason is that you should be able to send your own headers per plugin. And that's why a main plugin file must not create direct output. Wrap your `echo` code into a function and register that function as a callback for an action that happens later, after the headers are sent.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugin development, activation" }
Change Responsive Images Maximum Width of 1600px Sorry for my English first. Just started with responsive Images and read < So according to this post, there is a maximum width of 1.600px. I wonder how to increase this value to 1800px? And if it's possible... . Many thanks in advance.
You can simply remove that limit, go to your `functions.php` and add this code. function remove_max_srcset_image_width( $max_width ) { return false; } add_filter( 'max_srcset_image_width', 'remove_max_srcset_image_width' ); If you want to increase, go to your `functions.php` and add this code. function custom_max_srcset_image_width( $max_width, $size_array ) { $max_width = 1800; return $max_width; } add_filter( 'max_srcset_image_width', 'custom_max_srcset_image_width');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, responsive, images" }
WooCommerce set default product sort to product description (content) I am trying have the default product sort to be by product description (content). Right now I can make it by sku or other meta keys, but not by post content (description). Here is what I have so far by adding this to the function.php file: add_filter('woocommerce_get_catalog_ordering_args', 'am_woocommerce_catalog_orderby'); function am_woocommerce_catalog_orderby( $args ) { $args['meta_key'] = '_sku'; $args['orderby'] = 'meta_value'; $args['order'] = 'asc'; return $args; }
Sorting by content is not very efficient, as content can be long strings which take time to sort through. However, if your description is actually very short and you want to order your results by this very short string, then you could simply store your short description in a custom meta-field and use that field to order your results.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Woocommerce customer role doesn't change if user is already a subscriber I noticed the following behavior on woocommerce : I have a user on my website who is already registered with 'subscriber' role. When I login and checkout on my woocommerce shop, user role still remains on 'subscriber' and role is not updated to 'customer'. Problem is on admin page (Users > All users) : when I use the filter to show all customers, users who were already subscribers and have made orders don't appear on search results. I use Wordpress 4.9.6 et Woocommerce 3.3.3. Can anybody explain to me if this behavior is all right ? Thank you.
While WC is off topic, and I am not going to dig into how it explicitly works, in general wordpress roles are just a semantic way to call a class of permissions and users probably can not belong to two roles at once (this is an observation based on user management UI, not on whether it is possible to somehow hack something in the DB or via code), therefor if the user already exists it is just not obvious what to do if it might be better assigned to some other role. Not surprising that if a customer of a shop is already a user on the site, WC does not modify it in any way. So this is not so much about wrong and right but more about you looking for information about customers in an admin screen that is meant to manage user permissions and other non shopping related attributes
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, users, user roles" }
Get a specific size from wp_get_attachment_image_src I have this section in my website where i use `wp_get_attachment_image_src()` to get all the images associated with the post, but now you want to get a certain size (size: listing_grid): <?php $args = array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'numberposts' => 15, // -1, show all 'post_status' => 'any', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC' ); $images = get_posts($args); if($images) { ?> <images> <?php foreach($images as $image) { ?> <image><![CDATA[<?php echo wp_get_attachment_url($image->ID); ?>]]></image> <?php } ?> </images> <?php } ?>
Thanks maverick, your solution works <?php $args = array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'numberposts' => 15, // -1, show all 'post_status' => 'any', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC' ); $images = get_posts($args); if($images) { ?> <images> <?php foreach($images as $image) { ?> <image><![CDATA[<?php echo wp_get_attachment_image_src( $image->ID, 'listing_gallery_2x')[0]; ?>]]></image> <?php } ?> </images> <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, images" }
How to make a custom redirect in WooCommerce? An unregistered user buys a product from a certain category (take into account the ID), adds it to the cart and goes to the order processing. If it is registered, it makes out an order. If not, redirecting it for registration and back for ordering. After making an order, if user bought a product of a certain category, redirecting it to the custom page "Thank You", or immediately to the edit page of the account "edit-account" in the personal account. ![Illustration of the desired actions of the user.]( In principle, for an unregistered user, it is possible to enable the automatic creation of an account when buying products. It is necessary to add the condition of buying products from a certain category. And need to make a redirect after placing an order. I shall be very glad to your help!
add_action('template_redirect', 'woo_custom_redirect'); function woo_custom_redirect($redirect) { // HERE set your product category (can be term IDs, slugs or names) $category = 'subscription'; $found = false; // CHECK CART ITEMS: search for items from our product category foreach(WC() - > cart - > get_cart() as $cart_item) { if (has_term($category, 'product_cat', $cart_item['product_id'])) { $found = true; break; } } if (!is_user_logged_in() && is_checkout() && $found) { wp_redirect(get_permalink(get_option('woocommerce_myaccount_page_id'))); exit(); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How do I create a Shortcode that returns text if domain is .com, not .co.uk I am trying to create a shortcode to see if the url matches with the attribute, then return the content. So far I have: add_shortcode( 'ifurl', 'ifurl' ); function ifurl( $atts, $content = null ) { $url = ' . $_SERVER['SERVER_NAME']; $current_tld = end( explode( ".", parse_url( $url, PHP_URL_HOST ) ) ); $country_select = // Something to get attribute 'country' if( $current_tld == $country_select ) { return $content } } But as you can see, I haven't been able to get the attributes to work correctly, and the if statement. I would like to use it like this: [ifurl country="com"] Show only if .com [/ifurl] [ifurl country="uk"] Show only if .co.uk [/ifurl]
to read the attribut `country`, you just need to read it in `$atts` add_shortcode( 'ifurl', 'ifurl' ); function ifurl($atts, $content = null) { $url = ' . $_SERVER['SERVER_NAME']; $current_tld = end(explode(".", parse_url($url, PHP_URL_HOST))); if ($current_tld === $atts["country"]) { return $content; } };
stackexchange-wordpress
{ "answer_score": 3, "question_score": 6, "tags": "shortcode" }
Why my CSS file is not being registered in functions.php? I want to enqueue the stylesheet in `functions.php`, but it's not loading. What can be problem in my code? function my_theme_sty() { wp_enqueue_style( 'bootstrap', get_template_directory_uri().'/assets/css/bootstrap.css'); } add_action( 'admin_enqueue_s', 'my_theme_sty' );
Your function should be: function my_theme_sty() { wp_enqueue_style( 'bootstrap', get_template_directory_uri().'/assets/css/bootstrap.css'); } add_action( 'wp_enqueue_scripts', 'my_theme_sty' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "wp enqueue style" }
Wordpress Template Engine? I'm in a need to convert an existent design into wordpress and before starting I was curious to know: Is it correct to use pure "naked" PHP when adding logic to templates in wordpress? Wordpress uses no template engine like Twig or Blade by default? I'm pretty suprised, so before starting to work on that project and doing everything in pure PHP (with the opening `<?php` and closing hassle `?>`) I wanted to ask here. This way of doing things seems very outdated to me.
Correct, there is no PHP templating engine built into WordPress. This does however give you the flexibility to use a templating engine such as Twig or Blade (and I have worked on sites using each of those), or even completely headless using the REST API.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "php, templates" }
Add CSS class to PHP Statement A newbie question, I have been trying to style certain PHP code and I keep hitting the wall. I need to add CSS class to the **No results found** text bellow: <?php } else{ esc_html_e('No results found','ThemeName'); } ?> Thanks!
You need to wrap it in an HTML element that has a class. Doing it with your code will require changes. You can either do it outside the PHP, which will require changing where you open and close the PHP tags: <?php } else { ?> <span class="classname"> <?php esc_html_e('No results found','ThemeName'); ?> </span> <?php } ?> You can do it inside the PHP by concatenating a string, which means you'll need to use `esc_html__()` instead of `esc_html_e()` (which echoes the result, which you shouldn't do in the middle of a concatenation): <?php } else { echo '<span class="classname">' . esc_html__('No results found','ThemeName') . '</span>'; } ?> Or use `printf()` to put the string together, also using `esc_html__()`: <?php } else { printf( '<span class="classname">%s</span>', esc_html__( 'No results found', 'ThemeName' ) ); } ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "php, theme development, css" }
prevent showing posts of an specific category in admin posts section For some purposes I made a plugin that automatically makes posts with a specific category. Now in admin posts section, posts with that specific category have been too plentyfull and finding other posts has been difficult. For this I wrote another plugin and want to prevent showing posts of that specific category id or slug in admin posts section without using any third party plugin. And I want to make a menu in admin section to show posts of that specific category in that. My target category slug is 'eventscat' . But I don't know how do it, what hook must I use?
You can use the `pre_get_posts` action to affect any queries, both in frontend and admin. In your case you should make sure you affect only admin queries and you can even use `get_current_screen` to narrow it down further. Here's an example that would modify the query only on the regular posts page: add_action ('pre_get_posts', 'wpse311946_restrict_cats'); function wpse311946_restrict_cats ($query) { // retrieve the id of the category to be excluded $idObj = get_category_by_slug ('eventscat'); $id = $idObj->term_id; // find current admin page $current_screen = get_current_screen (); // conditionally exclude category if (is_admin() && $current_screen->id == "edit-post" ) { $query->set ('cat', -$id); } } You can use the same filter, slightly modified, to make sure only posts of this category are shown on the other posts page you want to create (this will have another screen id).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, plugin development, wp query, categories, admin" }
Shortcode attribute value with dash (hyphen) Is it safe to use hyphen in shortcode attribute value? For example: [foo something="fo-bar"]
It's safe, you won't have any problem using it, the only caution about **Hyphens** and **Shortcodes** comes from the Codex. > Take caution when using hyphens in the name of your shortcodes. In the following instance WordPress may see the second opening shortcode as equivalent to the first (basically WordPress sees the first part before the hyphen): [tag] [tag-a] > It all depends on which shortcode is defined first. If you are going to use hyphens then define the shortest shortcode first. > > To avoid this, use an underscore or simply no separator: [tag_a]
stackexchange-wordpress
{ "answer_score": -2, "question_score": 3, "tags": "shortcode" }
Notice: Undefined index: mtral_field_subscriber > Notice: Undefined index: mtral_field_subscriber in /wp-content/plugins/redirect-after-login/redirect-after-login.php on line 54 > > Warning: Cannot modify header information - headers already sent by (output started at /wp-content/plugins/redirect-after-login/redirect-after-login.php:54) in wp-includes/pluggable.php on line 1219 I get the above error and the error occurs specifically after I login since I am using Redirect After Login plugin in wordpress How can I debug and fix it ?
You can simply remove that plugin, and create that redirection youself. You can use the `login_redirect` hook, add this into your theme's `functions.php` function redirect_admin( $redirect_to, $request, $user ){ //is there a user to check? if ( isset( $user->roles ) && is_array( $user->roles ) ) { //check for admins if ( in_array( 'administrator', $user->roles ) ) { $redirect_to = get_site_url().'/a-page/'; // Your redirect URL } } return $redirect_to; } add_filter( 'login_redirect', 'redirect_admin', 10, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, wp redirect" }
Adding Custom Link anchors in the top menu that points to specific sections of the site home page My site is using a nav menu in my custom theme. I want to add navigation links to anchored links that points to specific sections of the site home page using a `Custom Link` in the nav menu. I want to use the equivalent of: <?php echo get_home_url(); ?>/#xxxx in the URL field. If I use just the anchored link `#xxx` as the `Custom Link`, it will work fine on the home page, but it will not link from another page (as that anchor section is not on that page). There has to be a clean way to do this. When I insert the php code as well, it appears to work on the home page, but not from another page. I've gone through all the other related posts, but none seem to address this issue.
If all you want is to go to a specific section of the home page, then the easiest way is to use the **relative URL** mark `/` and then use the anchor `#xxx`. So the custom link for the menu will be: `/#xxx`. > **Note the difference between`#xxx` and `/#xxx`** as custom link. The best thing about this approach is that you'll not have to bother changing the link after you go live, and additionally, this needs no programming.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "customization, menus, urls" }
Woocommerce checkout fields on the same line I'm trying to customize Woocommerce checkout page text boxes. Specifically I want to make some text boxes on the same line instead of separate. I've tried only with css messing around with float property but I can't figure out what I'm missing. This is what I'm trying to do.. * City and Zip Code on the same line * Telephone and Email Address on the same line * Text boxes should be the same size as First Name and Last Name text boxes
Add custom CSS using custom style editor, for below classes and IDs .woocommerce-billing-fields__field-wrapper { display: flex; flex-wrap: wrap; } .woocommerce form .form-row { display: inline-block; } .woocommerce form .form-row input.input-text { max-width: 252px; } #billing_first_name_field { order: 1; } #billing_last_name_field { order: 2; } #billing_company_field { order: 3; } #billing_country_field { order: 4; } #billing_address_1_field { order: 5; } #billing_address_2_field { order: 6; width: 100%; } #billing_city_field { order: 7; } #billing_postcode_field { order: 8; } #billing_state_field { order: 9; width:100%; } #billing_phone_field { order: 10; } #billing_email_field { order: 11; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "woocommerce offtopic, css" }
Extra items added to cart on refresh, woocommerce I have a client site, < where there are **AJAX** 'add to cart' buttons auto-generated by WooCommerce. If I visit the page with an empty cart and click **ADD** it adds a single item to the cart as expected. The page is reloaded and a popup cart slides into the window. If I refresh the browser a second item is added to the cart without clicking the **ADD** button. **How to prevent such bug?** * This is not a query param problem, there url is clean * I had a second product on the same page, clicking **ADD** (p1) and then after the reload clicking **ADD** (p2), p1 gets added a second time so I have a total of 3 items in the cart after two clicks
If you look on the network tab of the developer tools from your browser, you will see that the product is NOT added by AJAX. ![Chrome network tab]( Yes, there is an AJAX-Request but that sends a nonce to "woosb_custom_data" and adds no product to your cart. (blue cross on the screenshot) Normaly the "add to cart" AJAX-Request should go to an address like "example.com/?wc-ajax=add_to_cart". The product is add via a normal POST-Request. (red cross on the screenshot) If you reload the page the browser will send the POST-Request again. Try the reload test with an firefox browser and the browser will ask you if you want to send the POST-Request again. By the way there is an problem with your cart page. < If you remove all item from the cart (hit the red cross for every item) the cart-view will be white and there is no navigation back to your shop.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "woocommerce offtopic" }
<small> tag is being auto inserted The tag is being automatically inserted in my HTML document. It is only being applied in my home page. I've already disabled all plugins but it is still there. My website is < This is the part where `<small>` tags are being weirdly inserted. ![enter image description here]( These tags should not be in here. ![enter image description here]( Anyone has an idea what's going on? * * * ## UPDATE I restored from a backup so the issue with the columns was solved. But now it inserts small tags in the bottom part of my home page. ![enter image description here]( These small tags should not be here ![enter image description here](
this has been solved. In my grid, I'm only showing 30 characters of excerpt in my cards. I use this line of code: $post_excerpt = ( get_the_excerpt() ) ? mb_substr( get_the_excerpt(), 0, 30 ) . '...' : ''; In one of my post's excerpt, there's an html code written and with the code above the html code is being cut. I still don't know why there are small html tags being added when an html code is being cut. To solve the issue I added the code below: $post_excerpt = wp_strip_all_tags( $post_excerpt ); Thanks!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development" }
Comment form on custom page template I have created a custom page template, but I don't know how to add the WordPress comment form to my `<body>` tag. I tried to include the following in my `template.php` file in the body tag, but the form won't show up: <?php $comments_args = array('label_submit' => __( 'Send', 'textdomain' ), 'title_reply' => __( 'Write a Reply or Comment', 'textdomain' ), 'comment_notes_after' => '', 'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label><br /><textarea id="comment" name="comment" aria-required="true"></textarea></p>', ); comment_form( $comments_args ); ?> I am using the child theme of twenty seventeen themes.
If you want to display default Wordpress comment form then you need to call `comments_template()` in your template. Make sure that `comment_status` should be `open` for the particular post that you want to display the comment form. <?php comments_template(); ?> Read more here <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, comment form" }
Getting custom posts by post id from cutomizer text input I want's to show custom posts in a page by using post id which is taken from customizer text input my code is here <?php $query = new WP_Query( array( 'post_type' => 'post', 'post__in' => array( get_theme_mod('fp_post') ) ) ); while ($query -> have_posts()) : $query -> the_post(); the_title(); endwhile; ?> where **fp_post** is the customizer setting name. when use this code its show only one post but when use **179,182,185** (post id number) in place of **get_theme_mod('fp_post')** its show all of posts when print the value of **fp_post** it show **179,182,185**
The `post__in` parameter needs an array, see the WP_Query docs. With your customizer field you are not saving an array, you are saving a comma separated string. So try something like this: $my_field = get_theme_mod('fp_post'); // create an array from comma separated values $the_post_id_array = explode(',', $my_field); $query = new WP_Query( array( 'post_type' => 'post', 'post__in' => $the_post_id_array ) ); while ($query -> have_posts()) : $query -> the_post(); the_title(); endwhile; See in the docs: 'post__not_in' => array( '1,2,3' ) // <--- this wont work
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development, customization" }
Replacing words in Wordpress or theme (not in content) I am struggling to find some words that are appearing in the Wordpress (or theme). In particular I cannot find where the word 'by' is, as I need to replcae this word. This is the word 'by' that appears in the posts at the top of each post "date BY author". I need to replace the word 'by' for another word, but cannot find its location. I have tried the following in settings.php of the theme, but it does not work: function hpm_replace_text($translated_text) { switch ($translated_text) { case 'by' : // write the original string here $translated_text = 'por'; // make a change to it break; } return $translated_text; } add_filter('gettext', 'hpm_replace_text'); There are also other words, such as 'Categories', 'Replies' which I need to replace but cannot find where they are located. Can anyone help? Thanks.
These would be in your template. The Template File Hierarchy can be found here, and can help locate the specific template for the page you are looking at: < The plugin, Show Current Plugin, can also help: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization" }
Activate Gutenberg in category-descriptions I'm trying to convert my sites to Gutenberg. I like it!! But how do I make it possible to make category-descriptions using the new editor? ![Gutenberg editor in category description](
This isn't possible at the moment, Gutenberg is a post editor that relies on REST API endpoints, it's not an arbitrary content area editor as TinyMCE is. Given some modification though it could be made to work with a custom data model and be a replacement, but it's not a trivial task, and what's involved is in flux. It would be best to ask over on the Gutenberg GitHub issue tracker
stackexchange-wordpress
{ "answer_score": 3, "question_score": 6, "tags": "categories, block editor" }
Enqueue Script with data attributes I am looking to enqueue this script on the header of a wordpress page <script src=" data-cb-site="mydomainame" ></script> I know how to use function wp_mk_scripts() { if( is_page(11) ){ wp_enqueue_script( 'chargebee', ' array(), '2', false ); } } add_action( 'wp_enqueue_scripts', 'wp_mk_scripts' ); but how do I add the parameter `data-cb-site="mydomainame"` ?
Please try code given below: function add_data_attribute($tag, $handle) { if ( 'chargebee' !== $handle ) return $tag; return str_replace( ' src', ' data-cb-site="mydomainame" src', $tag ); } add_filter('script_loader_tag', 'add_data_attribute', 10, 2);
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "functions, wp enqueue script" }
Overriding core functions in child theme Is it good practice to use children functions.php to override parent core functions? Example in Storefront theme : **Core function** if ( ! function_exists( 'storefront_primary_navigation_wrapper' ) ) { /** * The primary navigation wrapper */ function storefront_primary_navigation_wrapper() { echo '<div class="storefront-primary-navigation"><div class="col-full">'; } } **children functions.php** function storefront_primary_navigation_wrapper() { // modified content; }
Basically, that is what `Child Themes` are meant to be, you have the need to modify the theme, but you shouldn't do it directly on the theme since the updates will mess you up, instead, you do all your customizations and new features on your Child Theme so you will be alright. From codex. > If you modify a theme directly and it is updated, then your modifications may be lost. By using a child theme you will ensure that your modifications are preserved. It's a good practice, to sum up.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "functions, theme development, child theme" }
Remove the last character from tag name in tag archive page I would remove the last character from tag name in tag archive page, I tried: <?php echo substr(<?php single_tag_title(); ?>, 0, -1); ?> but won't work.
Two things here, one is wrong syntax because you're opening and closing PHP tags twice. The second problem is the wrong usage of `single_tag_title()`. If you want this function to return value instead of outputting it (and you need that because you want to manipulate the string), you need to set the second parameter to false. (see the second example: < ) Also it's a good idea to check if you didn't get an empty result. So your code should look like this: <?php $tag_title = single_tag_title( '', false ); if ( ! empty( $tag_title ) ) { echo substr( $tag_title, 0, -1 ); } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "tags" }
Twenty Seventeen - Navigation bar, logo, header size I'm new here, like 3 days learning about WordPress, I think is very good, have some problems to understand the CSS, I think I'll get over it with time. I have a problem maybe someone can help me. Problem: ![Actually]( I want it like this. ![Want it]( Thanks in advanced. GitHub Regards!
Add the following to your `style.css`. Using Flex to align and space the items in the header. #masthead .wrap { display: flex; justify-content: space-between; } .navigation-top a { width:100%; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "child theme, navigation, theme twenty seventeen" }
MariaDB as a backend database I know WordPress expects to use MySQL as it's database backend, but can I switch to using MariaDB instead? MariaDB is a fork of MySQL that includes a bunch of really nice improvements for management and has some great SQL language improvements.
Yes, you can use MariaDB. MariaDB is a drop-in replacement for MYSQL so compatibility is not an issue. WordPress even lists MariaDB as an option within the requirements on their website: > We recommend servers running version 7.2 or greater of PHP and MySQL version 5.6 OR MariaDB version 10.0 or greater. Here is a resource from MariaDB on this topic <
stackexchange-wordpress
{ "answer_score": 11, "question_score": 10, "tags": "database" }
Register a menu - Error Header Could someone have the same error when im trying to register a menu? function.php function register_my_menu() { register_nav_menu('header-menu',__( 'Header Menu' )); } add_action( 'init', 'register_my_menu' ); error > function register_my_menu() { register_nav_menu('header-menu',__( 'Header Menu' )); } add_action( 'init', 'register_my_menu' ); Warning: Cannot modify header information - headers already sent by (output started at /home/milibyte/public_html/wp-content/themes/test/functions.php:4) in /home/milibyte/public_html/wp-admin/includes/misc.php on line 1126 GitHub Regards!
<?php function register_my_menu() { register_nav_menu( 'header-menu',__( 'Header Menu' ) ); } add_action( 'after_setup_theme', 'register_my_menu' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, menus" }
How to echo all the_title() without text after last "-" I am trying to do something but I have problem... I wont show the list of my post, but from all titles I want remove text after last "-" (dash) My list of posts: > 1. My experience - this boy - first day - meet > 2. My love - i do not know - second day > 3. My first time - auuu - third time > I would like to return this: > 1. My experience - this boy - first day > 2. My love - i do not know > 3. My first time > I tried this: <?php $stringx = get_the_title(); echo preg_replace('/-[^-]*$/', '', $stringx); ?> But this return whole text... with the dashes.... also I tried this: < Somone could help me how to output titles of post withoust text after last '-'?
This is really a PHP question not so much a WP question -- but: echo substr($stringx,0,strrpos($stringx,'-')); Also I think your example #3 is wrong unless there are some cases where you want to exclude more than simply after the final dash character. Note - if you want to exclude both that final blank space along with the final dash that immediately follows it, then change the substr length by -1 to avoid the final blank space: echo substr($stringx,0,strrpos($stringx,'-')-1);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "title" }
Wordpress content shows this character ​​ In my website this characters ​​ showing up on everywhere in blog content and title, after many hours of searching and googling cant find any useful answer i tried this meta but no luck header("Content-Type: text/html; charset=ISO-8859-1"); <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> Is there any way to rid-off this `​​` And many other characters: `‘` `â` `` Also tried Plugin search and replace but the character is not searchable.
Found the answer after little bit search on google & < , After a long time answered my own question thought maybe it will help someone. htmlspecialchars_decode(utf8_decode(htmlentities(YOUR_STRING, ENT_COMPAT, 'utf-8', false)));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "encoding" }
How to direct user after comment save I've been trying to direct the user to the specific page after they posted the comment, but that not luck for me. Here is the my code blocks My first try: add_action('wp_insert_comment', array($this, 'redirectAfterCommented')); public function redirectAfterCommented() { //some bussines logics wp_redirect(' } Also, I've try with another with the following code add_action('comment_post', array($this, 'redirectAfterCommented '), 10, 2); public function redirectAfterCommented () { // some business logic wp_redirect(' } Do hooked in the wrong place? if so, where should I hook to redirect the commentator?
Use the filter `comment_post_redirect`: add_filter( 'comment_post_redirect', 'comment_redirect' ); function comment_redirect( $location ) { $location = ' // or: // $location = get_page_link( page_ID ); // $location = get_page_link( get_page_by_path( 'sample-page' )->ID ) return $location; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "comments, hooks, actions, troubleshooting" }
Correct way to register custom post type from external php file? I have a class file and I have separated out my custom post types into their own files in a sub-folder for neatness, readability, etc. I want to init the CPT now in my plugin's `index.php` class. My class is initialised on the `plugins_loaded` action and in my construct I have the following: public function __construct() { add_action('admin_enqueue_scripts', array($this,'init_admin_scripts')); add_action('wp_enqueue_scripts', array($this,'init_frontend_scripts')); } The above actions refer to functions that are in the `index.php` file itself. My CPTs are in a subfolder called `cpt`. What is the correct way to add the action for the functions in a subfolder?
Adding an action doesn't do anything except putting the callback function in the queue of the corresponding hook. It doesn't check if the function exists, let alone load a file where the function is resident. Only when the corresponding hook is fired PHP looks for the function. If it is not loaded by then it simply throws an error: > **Warning** : call_user_func_array() expects parameter 1 to be a valid callback, function 'yada_yada' not found or invalid function name in **/../wp-includes/class-wp-hook.php** on line **286** > So, you are yourself responsible for loading the file where the function resides using `include` or `require` **before** the `admin_enqueue_scripts` hook is fired. Refer to the hook order list to check if you're hooking timely. If you're hooking everything into `plugins_loaded` you should be fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugin development, hooks" }
Rewrite URL with category and tag combined using WP_Rewrite I know how to query posts with my custom query var, but I am trying to rewrite the following URL from this... < to this... < I can't seem to combine the pre-existing category/subcategory with the tag. Here's some code I started with function myplugin_rewrite_tag_rule() { add_rewrite_tag( '%tag%', '([^&]+)' ); add_rewrite_rule( '^tag/([^/]*)/?', 'index.php?tag=$matches[1]','top' ); } add_action('init', 'myplugin_rewrite_tag_rule', 10, 0); I know this won't work because I need the category parameter as a query var.
These should work for you: function myplugin_rewrite_tag_rule() { add_rewrite_rule( 'category/(.+?)/tag/([^/]+)/?$', 'index.php?category_name=$matches[1]&tag=$matches[2]', 'top' ); add_rewrite_rule( 'category/(.+?)/tag/([^/]+)/page/?([0-9]{1,})/?$', 'index.php?category_name=$matches[1]&tag=$matches[2]&paged=$matches[3]', 'top' ); } add_action('init', 'myplugin_rewrite_tag_rule', 10, 0); The second rule is to support pagination so you can have: as well as: Note that you don't need to add a rewrite tag, as it's already added by core.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "categories, tags" }
Get ONLY the count from wp_query without fetching posts This is potentially a duplicate but what was listed on the following link didn't work for me : Return only Count from a wp_query request? I can't get the count using the query below. If I set `posts_per_page = -1` it renders a blank page, if I set it to something like 10, it returns 10 found_posts.. There's 190k results with "special_key", so maybe something to do with it..? // There are 190k records with post_meta "special_key" on each coupon/post. $query = array( 'post_type' => 'shop_coupon', 'meta_key' => 'special_key', 'fields' => 'ids', 'no_found_rows' => true, ); $results = new WP_Query($query); echo $results->found_posts; //// This is 0... echo $results->count_posts; //// This is 0... wp_reset_postdata(); If it helps, I'm running the query from inside a plugin.
The `found_posts` property of the `WP_Query` class is what you're looking for, which is the amount of found posts for the _current_ query. However, you got a `0` because you set `no_found_rows` (in the `$query` array) to `true`, which means the amount there will not be calculated. I.e. * WordPress will not append `SQL_CALC_FOUND_ROWS` to the SQL command for querying the posts. Otherwise, the command would be something like: `SELECT SQL_CALC_FOUND_ROWS {the rest of the query}` * WordPress will not execute `SELECT FOUND_ROWS()` _after_ the posts query is complete. And when it's not executed, the value of the `found_posts` property would be a zero (`0`). So remove the `no_found_rows` from the `$query` array, and the `$results->found_posts` would have the proper value: $query = array( 'post_type' => 'shop_coupon', 'meta_key' => 'special_key', 'fields' => 'ids', );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wp query" }
shortcode display metainformation as linked image I am trying to make this shortcode to display a self made meta field called `qrbase_code_pass_url` as a linked image. The image should be static, but should get the dynamic URL from the meta field of the current user. This is what I've got so far. function get_qr_image() { global $current_user; // get current user's information get_currentuserinfo(); $qr_url = get_currentuserinfo($current_user->qrbase_code_pass_url,24 ); return '<a href="'. $qr_url . '"><img src=" } add_shortcode('get_user_qr', 'get_qr_image'); This shortcode only break the page. Thank you for all input!
@WebElaine is correct. I had to use the `wp_get_current_user();` and remove `global`. This is what worked for me function download_to_wallet() { $current_user = wp_get_current_user(); // get current user's information $qr_url = $current_user->qrbase_code_pass_url; return '<a href="'. $qr_url . '"><img class="qr_download" src=" style="width:200px;"></a>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, user meta" }
Retrieving data about comments and likes What's the easiest way to fetch the number of comments and the number of likes a post has? I don't see any usefull field when fetching a post (with a request like < I'm currently using javascript issuing direct requests with axios.
You can get the comments by checking: Where `post=150`, is the ID of the post. I don't really know what do you mean by `likes`, but there are not `likes` WordPressPres natively.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, rest api" }
Notify admin when Custom post meta data gets updated or deletet I am trying to email admin when an single custom post meta gets updated or deleted. This does not work with post save or post delete. All i need is to detect when this post meta gets updated or deleted and email admin. so far i have tried to use this action but does not work: function detect_post_meta_update($meta_id, $post_id, $meta_key, $meta_value) { //code to email admin goes here } add_action( 'updated_post_meta', 'detect_post_meta_update', 10, 4 ); This was working but it was detecting all post meta changes including post view ... But currently is not working at all. Any better way for building this notification system ?
Actually this is the right way of doing that and proper hook to work with in my opinion. All you need to do is check if the updated meta key is the one you want to detect (that's why there are 4 arguments passed to the hook!). So let's say your post meta is called `'email_triggering_meta'`: function detect_post_meta_update($meta_id, $post_id, $meta_key, $meta_value) { // ignore every meta update apart from `email_triggering_meta` if ( 'email_triggering_meta' !== $meta_key ) { return; } // code to email admin goes here } add_action( 'updated_post_meta', 'detect_post_meta_update', 10, 4 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, actions" }
Multisite installation but do plugins always have to be multisite compatible? I have a multisite installtion and I have a question about using plugins in my multisite network. If I plan to activate this plugin only in one of my subsites, is it necessary for this plugin to be multisite compatible?
They shouldn't have to be multisite compatible. Also remember that, there are two kinds of * Passive compatibility: doing nothing multisite specific, just works without breaking anything. * Active compatibility: changing or extending multisite specific behavior. In case the plugin you want to use doesn't say anything about its compatibility on multisites, you just have to try them out, they may break things but they also can work without problem, it depends on what is their purpose.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, multisite" }
How to bulk Edit Dates in Media Library? I can't seem to find this option, but is there a way to bulk edit the dates of media items? I'm trying to go through my media and clean it up and I'd like to batch edit the dates of images (they'd be the same date for each batch), but can't seem to find a reference at all to this issue.
You can use a plugin called Media Library Assistant. 1. After you install it go to your **Media > Assitant** (`wp-admin/upload.php?page=mla-menu`). 2. Select all the images or the ones you want to edit. 3. Click on **Bulk Actions**. 4. Click on **Edit** and then **Apply**. 5. Then you will see **Uploaded on** and use the date you wish. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "media, media library, bulk" }
Multisite Installation: how do I setup global search? I run a multisite installation and my sites are bilingual. I would like to find out how I can setup global search. Are there decent plugins available that do this? Cos I'm a wordpress noob and am deathly afraid of doing stuff like changing/editing php files because I worry that a single error may cause my entire site to breakdown... I did a search and saw this: < But it is an old plugin and hasn't been updated for a couple of years. Plus, reviews are mixed so I'm wondering if there's a better solution/plugin that I haven't found yet.. Would really appreciate your advice and help! Thank you!
I think the best way to do it is to index all the posts and search through them in database. This method should be the fastest when you perform a search because you can filter posts, create the pagination etc. Check this tutorial < Another way is to to something with `switch_to_blog()` function – I mean to search each site individually and then to rearrange the results, but I suppose it would be a very slow code. Especially if you have a lot of site in your network.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "multisite, search, globals" }
How to show posts with multiple tags on tag.php? On my tag.php page, I want to show posts with multiple tags... I have something like this: mypage.com/tag/ **tag1+tag2+tag3** / $tags = get_queried_object()->slug; //returns only 'tag1' !! $args = array( 'tag' => $tags //need to get 'tag1+tag2+tag3' here ); $loop = new WP_Query($args); Is there any other way how to show posts with multiple tags?
`get_query_var( 'tag' )` will return you `'tag1+tag2+tag3'` string. `get_query_var( 'tag_slug__and' )` will return you the array of tags. So, there are two ways to achieve the goal: $args = array( 'tag' => get_query_var( 'tag' ), // string ); or $args = array( 'tag__and' => get_query_var( 'tag_slug__and' ), // array ); It remains to be seen how do you plan to create `tag1+tag2+tag3` slug.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "loop, tags, slug" }
Wordpress error after installing plugin "Internal Server Error" So after I press "Install" on a plugin that I want to install to my page I get "Internal Server Error" and message, that the plugin already exists. (Even I am installing a plugin for the first time, there is no folder in wp_content and plugin.) Even, that there was an error message, the plugin is installed and all I have to do in "Activate" it in plugins tab. So, I can install any plugin anyway but is it annoying, that I have error message every time. Can I fix that somehow? Thank you for your answer.
Could you please try to deactivate all other plugins, revert to a default theme like `TwentySeventeeen` and test once more? If this resolves the error, it should be a conflict with some theme and/or plugin(s). Simply activate them back one-by-one checking each time the installation process until you get the error again. Also, check that you are running the last version of WordPress.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, errors, 500 internal error" }
How to register a widget when saving a post? I've tried to solve my problem in the simplest way, but it doesn't work: why? function createNewWidgetSavingAPost($post_id) { add_action( 'widgets_init', function(){ $new_widget = new myWdgetClass("widget_id"); register_widget( $new_widget ); }); } add_action('save_post', 'createNewWidgetSavingAPost', 10);
As you can see from the hook order, `widget_init` is a hook that is quite early in the page execution order. So, by the time `save_post` is fired `widget_init` has already passed. If you add an action to a hook that has already passed, nothing will happen.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets, hooks, save post" }
css media query question I guess this is a novice question but here it is. I have been editing a child theme CSS and trying to change this specific code @media (min-width: 769px) #carousel-hestia-generic span.sub-title { font-size: 24px; } Which I see from the inspect in Chrome. When I add it to my style.css in my child theme and make the font size let's say 36px, it doesn't change. Actually, Chrome shows a strikethrough... **the element I want to change** < **the CSS file in my child theme** <
You have to put it like this: @media only screen and (min-width: 769px) { #carousel-hestia-generic span.sub-title { font-size: 24px; } } Notice how **@media** has a block `{}` which contains the CSS selector you want to work with.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, css, child theme" }
Get all posts as an array ID => Name I need to query all of my posts as an array in example: 'options' => [ 'Post ID' => __('Post Name'), 'Post ID' => __('Post Name'), ], How can i do it? tried this but it gives me only the ID's: function query_posts_as_array(){ $args = array( 'post_status' => 'publish', 'fields' => 'ids', ); $result_query = new WP_Query( $args ); $ID_array = $result_query->posts; wp_reset_postdata(); return $ID_array;
You're trying to make `WP_Query` give you everything in a single API call, but that won't work. Instead, break it down into multiple steps, e.g.: * Create an empty list * fetch all the posts * foreach post: * add its ID and name to the list * you now have alist of ID's and names
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, wp query, theme development, loop, array" }
Templates to use multiple time within page? New to WP, so this may be a newbie question. My page will consist of structured data: Movie title, Movie release date, Movie Poster Image filename. On mediawiki, my page might look something like this: {{movie-template|Gone With the Wind|1939|gwtw.jpg}} {{movie-template|Citizen Kane|1941|ck.jpg}} {{movie-template|Star Wars|1977|sw.jpg}} How do I do this in wordpress?
If you are trying to do this within a page or post, you could make a shortcode out of it. ` [movie-template title="Gone With the Wind" date="1939" image="gwtw.jpg"] [movie-template title="Citizen Kane" date="1941" image="ck.jpg"] [movie-template title="Star Wars" date="1977" image="sw.jpg"]` Then you need a little code, in your template's functions.php, or in a custom plugin: ` add_shortcode( 'movie-template', 'my_movie_listings' ); function my_movie_listings( $atts ) { $atts = shortcode_atts( array( 'foo_title' => 'title', 'foo_date' => 'date', 'foo_image' => 'image', ), $atts ); // $atts['foo_title'] is your movie title // $atts['foo_date'] is your movie date // $atts['foo_image'] is your movie image $ret = "do something here with {$atts['foo_title']}"; return $ret; }`
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "templates" }
Replace "http://localhost:8888/" by website URL in Wordpress Due to some recent security breach, I had to replace my website on the server with all the new local files. **Question** : Now I see " **` " string in my blog posts ( e.g. image sources and everywhere else) due to which the website is not working properly. I have already generated fresh permalinks `Settings->Permanlinks->Save` How can I replace " **` " with " **`mysiteurl.com`** ". Is there any script?
You'll need to fix the URLs in the database. Although you can do it with MySQL commands, the easiest way I've found is with the "Better Search and Replace" plugin. Easy to use, and works. < Of course, backup your database first. But it works quite well.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "url rewriting, localhost, site url" }
How to disable click thumbnail product on archives product i want to disable click our product image on archives product page. so, user only can click from the button. ![enter image description here](
In your functions.php remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 ); remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "woocommerce offtopic" }
What's the difference between admin_url() and get_admin_url() functions? Except for the `$blog_id` parameter (which is only allowed in the `get_admin_url` function), what is the difference between `admin_url` and `get_admin_url`?
The `admin_url()` function retrieves the URL to the admin area for your current site. You needn't give the blog id for your current site. You can use this function if you aren't running WordPress multisite. And use the `get_admin_url()` function to get a specific site URL in the multisite admin.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 7, "tags": "functions, wp admin" }
Stop WordPress From Removing HTML Comments In Content Whenever I switch from the visual editor to the text (HTML) editor and put an HTML comment in the code, e.g. `<!-- this is a comment-->`, WordPress removes it, either after saving the change or switching back and forth between editing modes. Is this a quirk of WordPress or TinyMCE and more importantly, how do I stop this so I can keep the comments in the content?
Looks like it's TinyMCE that's doing this, and it can be fixed by either modifying the `valid_elements` or `extend_valid_elements` options. I'm using the Advanced TinyMCE Configuration plugin which makes this very easy. The value for either option above to use is `--[*]'` For example: `valid_elements: 'strong,em,--[*]'`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 5, "tags": "tags, html editor" }
When using global $post in blog index file (home.php) it returns the latest blog post instead of current page In my `home.php` file I have only this code: <?php global $post; print_r($post->ID); die(); ?> This is printing the ID of the latest blog post, but what I want is to get the ID of the current page (the page I set as the Posts Page in Settings). It seems that I am already in "The Loop". How can I get the global `$post` object for the current page rather than the first post in the loop?
¿How about getting the ID from de configuration? <?php $page_for_posts = get_option( 'page_for_posts' ); ?> As the page you are looking for now displays the posts, you are in the loop for posts, not the loop for the page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "blog page" }