INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Two e-commerce in two different folders of the same domain I need to create two e-commerce with woocommerce, one in the main directory of my site in Italian and English for online sales in Europe, and one in a subfolder or subdirectory exclusive for Switzerland in CHF with differentiated prices. I would like to know if you have to install wordpress also in the subfolder, so a wordpress installation for each woocommerce plug or can you manage the two online shops even with a single installation? And in any case, what do you recommend for a better performance? Thanks in advance.
> I would like to know if you have to install wordpress also in the subfolder, so a wordpress installation for each woocommerce plug or can you manage the two online shops even with a single installation? Both options work, either 2 installations of WordPress with WooCommerce installed, or a single installation of WordPress set up as a multisite. Neither will give a performance benefit over the other, but the multisite install will be simpler to maintain
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, multisite, add submenu page" }
Extend meta query arguments I have this meta query: $args = array( 'post_type' => 'events', 'meta_query' => array( array( 'key' => 'fl_type', 'value' => 'Awards' ) ), 'posts_per_page' => -1, 'meta_key' => 'fl_order', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'fields' => 'ids' ); However I need to extend this by another 2 numeric variables `fl_expire = 0` and `fl_global = 1` and I can't figure out the correct syntax for this.
Try this $args = array( 'post_type' => 'events', 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'fl_type', 'value' => 'Awards' ), array( 'key' => 'fl_expire', 'value' => 0, 'type' => 'NUMERIC', ), array( 'key' => 'fl_global', 'value' => 1, 'type' => 'NUMERIC', ), ), 'posts_per_page' => -1, 'meta_key' => 'fl_order', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'fields' => 'ids' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "meta query" }
How to dynamically set a background image with the customizer without putting the css as an inline-style Here is what I am using currently, `<div class="home-header" style="background-image:url('<?php echo get_theme_mod( 'home-header-img' ); ?>'); height: 500px; width: 100%; display: flex; justify-content: center; align-items: center; background-repeat: no-repeat">` I have the background-image being set by the customizer and it's working great however I am unable to have inline styles due to the ThemeForest theme standards. What should I be doing here? or is there a better way to go out this? thanks
I would recommend changing it to this: <div class="home-header" style="background-image:url('<?php echo get_theme_mod( 'home-header-img' ); ?>')"> and adding this to style.css or an other stylesheet: .home-header { height: 500px; width: 100%; display: flex; justify-content: center; align-items: center; background-repeat: no-repeat; } In general, inline styles are not allowed, but Themeforest makes an exception for background-images. So by moving the remaining code in a CSS-file and only leaving the image, you're fully compliant with Themeforest's requirements. The exception for images is mentioned in this article. Let me know how it goes! PS: If you want to add the code using `wp_add_inline_styles()`, but don't know how it works, I can also give an example of that.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, theme customizer" }
How can I add more "filters" to my products? (Categories, attributes, etc.) I want to make a shop that sells car parts. In order to do so I need additional categories such as make, model, year and so on. The reason why I don't want to put everything in the "categories" section is that I will want to implement a "search by car model" feature, like this: ![Car parameters]( My worry is that if I put all the information in the "categories" section of the product, then the user will not only see BWM, Audi, etc. but will also see other names of the categories such as "Make" and "Year" in the dropdown menu. How should I go about solving this problem? For refference, this is my 1st time using wordpress and my experience is not that vast (2nd year of CS)
I presume here that you're using a shopping cart system such as WooCommerce?? If that's the case, you could create new taxonomy terms for the products cut that WooCommerce creates using something like the below: // Create custom taxonomy for parts CPT add_action( 'init', 'create_vehmake_taxonomy' ); function create_vehmake_taxonomy() { register_taxonomy( 'veh-make', 'product', // CPT slug here array( 'label' => __( 'Vehicle Make' ), 'rewrite' => array( 'slug' => 'make' ), // Tax Term Slug (URL) 'hierarchical' => true, ) ); } You could in theory create multiple of these to cater for your needs. However, for ease of use, I'd probably be more inclined to use the Advanced Custom Fields plugin to create new meta fields on your product CPT that you can then use as select fields or text inputs to populate the data you need on a per-product basis.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories" }
WP Multisite - domain mapping to domain.com and separate site to domain.com/help I'm considering setting up a WP multisite network. It would seem to fit my situation perfectly. There's one thing I still need to find out about domain mapping. Say I have the multisite installed on the following example root domain: `multisiteroot.com`. Each subsite is installed on a subdomain. Further, I also registered a domain: `businessdomain.com`. I now want to have two separate WP websites and map them to respectively `businessdomain.com` and `businessdomain.com/help` (or sth like that). Is it possible to install WP Multisite on a root domain with subsites on subdomains, and map two of those subsites to `businessdomain.com` and `businessdomain.com/help`?
Yes, this is possible (see < For sub-domains you'll need to confirm that your DNS has a wildcard entry for your domain. So, based on your root domain, this would work for: mysub1.multisiteroot.com, mysub2.multisiteroot.com, etc. If you wanted to us different domain names for subsites, then you'd need to have those domain names point to your IP, and then, in the Network Admin "Edit Site" page for your new subsite (Network Admin path: All Sites > Edit (site site to be modified): 1. Info tab - Change "Site Address (URL)" to the URL to name of your subsite (e.g. " then click "Save Changes"; 2. "Settings" tab - change the "Siteurl" and "Home" values to the URL for your subsite, then click "Save Changes". As for "businessdomain.com/help", this is a subfolder. I recommend using a subdomin "help.businessdomain.com", using the website I listed above and mu notes. I hope I didn't miss a step, or two. Good luck.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "multisite, subdomains, domain, domain mapping, network admin" }
WooCommerce: Force coupon for existing/registered customers I have some specific regular customers for which I have particular coupons, like 10%, 15% etc. I want the coupon codes to be fixed in their useraccounts so that they do NOT need to enter it during ordering-process. Is it possible? Thanks!
there is a simple plugin if you want to use called Woocommerce Extended Coupon Features Free. This is a freemium plugin but adds enough options to be able to do what you want. Link for the plugin <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, woocommerce offtopic, order" }
How to deal with logo color on dark mode? I'm trying to add a dark mode on my website via prefers-color-scheme webkit. However, my logo is all black, while my header is white. On dark mode it should be the other way around. My logo is in PNG and I thought it wouldn't be a bad idea to somehow upload two logos with different selectors and hide one via CSS on light mode, and the other one on dark mode. My question is: is there any way to do it? If no, does anyone have any other ideas how could I achieve what I need? EDIT: I'm trying to do exactly the same thing as this guy: However, his logo is a simple text so he can easily change its color via CSS. Mine is in PNG and I'm not able to do this.
1. Apply `filter: invert(1)` in dark mode if your logo is simple enough (in shades of grey). 2. Overlay your dark mode logo on top of your normal logo and change the opacity. This is what we do. Our logo consists of two lines of text, one of them is black and the other is colored. We have the same logo in two containers overlaid one above the other (`position: absolute`), but one container is half the height of the logo to only cover the first line of text and it has the `invert` filter applied. When switching to dark mode (with a cool transition), the inverted logo (one white line of text) is revealed. 3. Use SVG.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, headers, logo" }
Loading and Referencing Images I'm slowly writing a page to manage an asset database; effectively, writing a very basic plugin. I want to import photos and found some excellent examples of how to do this and, made it work! My problem then was to display the images in the page. Although I know the uploaded image filename, there seems to be no way to use it. The image will be put into the current 'date' folder and could well be renamed on the way. I've ended up querying the last post ID just before I import the image and adding 1 to it to reference the image. With the post ID I can then use `wp_get_attachment_image_src` to get a url for the (resized) image: wp_get_attachment_image_src( $result->PostNum, 'medium_large' ); It works but it is very clunky. Is there a better way of doing this?
Could be the piece you're missing here is that after you upload photos if you want to get to that item again to do anything with it, including get its URL, the thing you need to keep is not the filename but the ID that you get back. You can then call e.g. `wp_get_attachment_image_src` directly with that ID to get the URL for that image. If you don't have a way to store that ID in a useful place and recall it when you need it, you may need to resort to some other way to figure it out, such as what you're doing. Does that help?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, uploads" }
Woocommerce, finding the ordinal number of a purchase for a certain product we are developing a complex Woocommerce website and an app which uses V3 API. Being sold products very valuable, we need to know the ordinal number of a purchase for each product. For example, we'd like to know that Alice was the third to buy that product and Bob the fifth and so on. What I can think of is to get the total sales through Woocommerce API for that product, then loop every order containing that product and order them by date. The problem is that this way is very time and resources consuming, especially having to loop through all the orders. Does anybody know a better approach. I don't ask for the code, but I'd be glad if someone could have a brilliant approach to share. Thanks! Fabio
Assuming you are not allowed guest checkout what you can try is * add a custom field to your WooCommerce products in which you would save the history of purchases as an array like `[<user_id_1>, <user_id_2>, ...]`; * write a custom function and use a `woocommerce_order_status_completed` hook to update this field according to products within the order (see this question for information on how to get user ID from the WooCommerce order); * write a function which will do a loop through all already placed orders and initialize that field value for each of your products. This can be done as a plugin where initialization of this custom field will occur during plugin activation. And with the same plugin you could register an additional REST API endpoint.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, api" }
Permalinks by page/post name returning 404 All my content is currently setup as pages. I want to setup permalinks with page names. I read some posts online that said choosing %postname% path should render the content. But this does not work. When I access a page, I can see that the link is being updated with the page name, but it returns a 404. I checked the .htaccess file and httpd.conf. mod_rewrite is loaded and access is setup with the right permissions. My site is being hosted on ec2 aws. Update: I just created a post and tested permalinks with it, the post also returns a 404.
I was able to find the answer here: I had to create a custom permalink with the following value: /index.php/%postname%/
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, pages, 404 error" }
Shorter admin url for options page Is it possible to create a short admin url for options page? The default admin url is: domain.com/wp-admin/admin.php?page=options-page-slug And i want it to be: domain/wp-admin/options-page-slug
You mean, `wp-admin/ _admin.php_?page=options-page-slug`? But yes, you can use the rewrite API: add_action( 'init', function () { // The following adds the rule into the database. add_rewrite_rule( 'wp-admin/options-page-slug(/|$)', 'wp-admin/admin.php?page=options-page-slug', 'top' ); } ); Or alternatively, just add this before the WordPress rules in your `.htaccess` file: RewriteRule ^wp-admin/options-page-slug(/|$) /wp-admin/admin.php?page=options-page-slug [QSA,L]
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme options" }
How can I display Only the first Array/Object? **By using Wordpress REST Api** ./wp/v2/users/?_fields=id&orderby=id&order=desc Result [{"id":13},{"id":12},{"id":11},{"id":10},{"id":9},{"id":8},{"id":6},{"id":5},{"id":4},{"id":3}] **What I want?** I just want to display [{"id":13}, Means, I want to limit it to only 1 array Using REST API. Any one have solution on this?
The docs show that you can do paging with `page` and `per_page`, so looks like you should be able to set `per_page` to `1` and leave `page` unset to get a single result. i.e.: ./wp/v2/users/?_fields=id&orderby=id&order=desc&per_page=1 Does that help?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, rest api, array, api" }
I would like to hear recommendation for a plugin to charge exams Hello and a good day to all of you. I need to ask a suggestion about a feature. One of my clients is planning to charge exams.Which module/plugins would you like to recommend. i.e Customers need to pay for exams. Regards
I have used School Management System for Wordpress which you can find it on CodeCanyon. This premium plugin comes with handy features and one of them is paying for Courses or Exams.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins" }
Add instructions to featured image How do you add instructions to the featured image field (see attached screenshot) - something like: "recommended dimensions - H980px by W450px"..? ![screenshot of featured image without instructions](
Wordpress has a hook for that. Here is a sample code: function featured_image_dimensions( $content, $post_id, $thumbnail_id ){ $help_text = '<p>' . __( 'recommended dimensions - H980px by W450px', 'my_domain' ) . '</p>'; return $help_text . $content; } add_filter( 'admin_post_thumbnail_html', 'featured_image_dimensions', 10, 3 ); Add this code to your functions.php and you should be good to go.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "images, post thumbnails" }
Theme support title tag - how to replace the default WP separator (with a filter)? I'm developing a theme for Themeforest and one of their requirements is about the tag. Themeforest states their requirement as follows: _The theme must let WordPress add and manage the title. This is done by adding`add_theme_support( 'title-tag' );` to functions.php instead of using `wp_title()` in the document head._ The current output is on the home page: '`Site title - Site tagline`'. On other pages it is '`Post or page title - Site tagline`'. The separator is '-'. Can anyone give an example of a filter for this, so that I can change the separator to '|' or a character of my choice? Many thanks in advance!
You use the document_title_separator filter. So in your case: <?php function theme_prefix_filter_document_title_separator() { return '|'; } add_filter( 'document_title_separator', 'theme_prefix_filter_document_title_separator' ); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, title, wp title, add theme support" }
Conditional to determine if search.php page is the current template I have a specific CSS-file for my search results, so the search.php template. I want a PHP if-condition to determine if the current template is the search.php template, so that I can load that CSS-file with `wp_enqueue`. The condition should work in the functions.php file. I'm not entirely sure if I can use `is_search()` for this. Can anyone confirm I can use `is_search()` and, if that's not the case, provide an alternative? Many thanks in advance!
WordPress conditional functions will not tell you which template _file_ is used. They tell you what the current request is for. Which file is loaded for that type of request is determined by the template hierarchy. So, `is_search()` will tell you if search.php is being used if the current request is a search, and the current theme includes a search.php. If the theme does not include search.php, `is_search()` will still return `true` if index.php is used, as per the template hierarchy. That's the long way of saying that if your theme has search.php, then yes, use `is_search()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, search, conditional tags" }
Redirect Single Post CPT (Custom Post Type) to a specific URL I have a domain `domain.com` and subdomain `materials.domain.com` At the `domain.com` scope, I created a custom post type called `resources` and a portfolio grid (using Elementor) to display it's featured image with the title. When clicking on the grid item, the **single** post is shown for example: `domain.com/resources/resource-title` I'd like to remove the **single** post from the domain and redirect on click to `materials.domain.com/resource-title`. I already have this page on the `materials`subdomain). How can I achieve that?
Sometimes this would be achievable with `add_rewrite_url` but it looks like in this case it's not as you need to redirect to a different domain. In this case you need .htaccess or nginx rules to do this, so you need to add something like this to your nginx config **for domain.com only** , in order to rewrite those URLs: `rewrite ^/resources/(.+) permanent;` You'll likely need to restart nginx after you add this to the config file. Happy to help if this doesn't do exactly what you want. There's more examples of nginx rewrite rules here: <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "custom post types, multisite, single" }
Modify a Filters Second Parameter I have this filter: $post_arr = apply_filters('insert_product_post_data', $post_arr, $data); add_filter('insert_product_post_data', 'my_filter', 10, 2); function my_filter($post_arr, $data) { //change $data here return $post_arr; } I need to change the value of $data is any way to do this ?
No this isn't possible without changing the original code. Filters work on the very first parameter, the other parameters are provided for context. You will need too either get the author to add a filter for the data variable, fork the plugin, or use a competitor. The only exception, is if `$data` is an `object` not an `array` and you want to modify it. However, it cannot be replaced, and it cannot be done with an array or any other data type.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "filters, references" }
Woocommerce posts and products links works only once and then get 404 error Permalink to products and post of my website getting 404 error. after saving the permalink type in Setting -> Permalink page they will work correctly. But if I refresh the links they get 404 error again. Actually the links work only once. this is my .htaccess file: <IfModule mod_rewrite.c> Options +FollowSymLinks RewriteEngine on RewriteRule ^.*-(\d+)/$ securityl/index\.php?id=$1&%{QUERY_STRING} [L] RewriteRule ^.*-y(\d+)/$ securityl/index\.php?cat=$1&%{QUERY_STRING} [L] RewriteRule ^.*(website[a-z]+map\.xml)$ websiteguide/$1 [L] RewriteBase / </IfModule> I have changed the theme to store front and it's not working.
I realized that some php code changes the content of `.htaccess` file. The php folder was in a directory named 'securityl'. I've been removed that directory but whenever the website was refreshing the directory and also the php files inside it was recreating. In the end I discovered that some code in `wp-include/load.php` is creating the directory and I re-downloaded the wordpress and replaced the clean wp-include, then the problem solved and there was no code for creating securityl folder! . I don't know how and why the contents of that files were changed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, permalinks, htaccess, 404 error" }
Display a custom name when the user has no name settle in his account I'm creating a code that shows the First Name for logged in users, using a shortcode, but I noticed that if the user has no name settle, it will display a blank space. How can I set a custom name to show up instead of the blank space? Something like this "Hi >No Name<, please settle your name in your account." Display first name: // show first name if logged in function colaborador_nome($atts) { if (is_user_logged_in() && !is_feed()) { return '&nbsp;'. get_user_meta( get_current_user_id(), 'first_name', true ); } } add_shortcode('colaborador_nome', 'colaborador_nome');
Use PHP ternary comparsion operator to check if `get_user_meta()` function returns blank or non-blank result: function colaborador_nome($atts) { if (is_user_logged_in() && !is_feed()) { return '&nbsp;'. (get_user_meta( get_current_user_id(), 'first_name', true ) ?: "Hi >No Name<, please settle your name in your account."); } } add_shortcode('colaborador_nome', 'colaborador_nome');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, plugin development, functions, shortcode, username" }
When Wordpress Default table, Echo Success. When Plugin Table, Echo Blank When I used this code, the result/echo display as I wanted. <?php $user_checks = $wpdb->get_results( " SELECT ID, user_nicename FROM $wpdb->users " ); foreach ( $user_checks as $user_check ) { echo $user_check->ID; echo $user_check->user_nicename; } ?> But when I choose table other then what wordpress provide e.g: <?php $user_checks = $wpdb->get_results( " SELECT id, name FROM $wpdb->uap_banners " ); foreach ( $user_checks as $user_check ) { echo $user_check->id; echo $user_check->name; } ?> The Result is blank... Did I miss something? (I'm new on wordpress)
`$wpdb` does not contain any reference to custom tables. So the `uap_banners` property doesn't exist. You need to write in the table name the say way it was written when creating the table. So in your case that would probably be (assuming you included the database prefix): $user_checks = $wpdb->get_results( " SELECT id, name FROM {$wpdb->prefix}uap_banners " );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "mysql, wpdb" }
How to change the background color that appears at top when we pull down a website on mobile device? The website is < ![enter image description here]( In the top there is a bluish rectangle, that comes when we pull the site down to refresh. How can that color be changed?
This is simply the background colour of the `body` element. On your site it's currently set as this: body { background-color: #c1e7e7; } This appears to be being added by your theme, probably based on a customisation option somewhere. You'd be able to overwrite it by adding matching CSS in _Appearance > Customize > Addition CSS_, if you can't find it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom background" }
Trying to add some custom text into Wordpress Post title via function.php I need to add a custom text in wordpress Post title dynamically which I'm trying to add via this code in function.php Following code is not working add_filter('the_title', 'new_title', 10, 2); function new_title($title, $id) { if('babysitters' == get_post_type($id)){ $exclusive = get_field('exclusive', $id); // pass the id into get_field $title = $title .', ' .$exclusive->y; } return $title; }
The first thing that i am not getting is $exclusive->y ? can you please share custom field settings that you have created? And the second thing that i have found, you must have to put global $post; in the first line of the function : add_filter( 'the_title', 'wpb_new_title', 10, 2 ); function wpb_new_title( $title, $id ) { global $post; if('post' == get_post_type($id)){ $exclusive = get_field('exclusive', $id); // pass the id into get_field $title = $title .', ' . $exclusive; } return $title; } I have added a title on the default post. see the screenshot of the settings and the view page. in viewpage my post name is Hello World and i am adding ",test additional title" from the filter hook. ![settings image]( ![output Image]( Please check, If it works for you. also please share the details that i have mentioned. Thanks!:)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, javascript, variables, wp title" }
Empty taxonomy items for CPT in admin grid In admin grid for post taxonomy, if I'll click on "Items" link, I'll get all post, associated with this taxonomy `/wp-admin/edit.php?category_name=test`. But this won't work for taxonomy for Custom Post Type. For example, `/wp-admin/edit.php?cpt=test&post_type=cpt` displaying 0 items.
The correct link should look like this: /wp-admin/edit.php?{taxonomy_slug}={term_slug}&post_type={cpt_slug} **For example**. If you have taxonomy `brand` and it has term (category) `test`, your link will be: /wp-admin/edit.php?brand=test&post_type=CPT
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy" }
500 error after upgrading from 5.0 to 5.4 and adding empty functions.php I've finally managed to upgrade a WP site from v5.0 to v5.4. The only issue left is when I create an empty `functions.php` file I get 500 error. Does someone have an idea why is that? Thanks. Update: My goal is to place the following into `functions.php`: function my_acf_init() { acf_update_setting('google_api_key', $_ENV['GOOGLE_MAPS_API_KEY']); } add_action('acf/init', 'my_acf_init');
I've managed to print the error message by adding the following to the `functions.php`: function exception_handler($exception) { echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); For some reason logs did not include the error details before. The error is `call to undefined function is_blog_installed()` which I have no idea why's that. :D
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "functions, 500 internal error" }
Randomizing wp_tag_cloud() in child theme I'm trying to write a wordpress function code in my child theme that randomizes the words in the word cloud where previously it was alphabetized. The code Im using is below, which doesn't work. // add_filter('wp_tag_cloud_args', 'my_wp_tag_cloud_args_filter'); function my_wp_nav_menu_args_filter($args) { $args['order'] = 'RAND'; // do something return $args; } // I'm able to update the wp_tag_cloud()'s default ('Order' = 'RAND') args in wp-includes/category-template.php but I know that any changes will get replaced. The change work when in that file. How can I move those set of changes to my wordpress child theme?
Try the `tag_cloud_sort` hook: add_filter( 'tag_cloud_sort', 'shuffle_tags', 10, 2 ); function shuffle_tags( $tags, $args ) { shuffle( $tags ); return $tags; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, customization, categories, tags, child theme" }
Assign custom class to post content images Is possible to assign a default class to the images that are part of a post content? I have a problem with teh layout, this because the attached images insetred inside a post will break my bootstrap layout. I want to assign a default class so the user when add an image into the content will have the class assigned and the layout will not break.
As you are using bootstrap you can add `img-fluid` helper class to images like this. function example_add_img_class( $class ) { return $class . ' img-fluid'; } add_filter( 'get_image_tag_class', 'example_add_img_class' ); `get_image_tag_class` filter allows to add custom css class along side WordPress default classes. Read more about the filter here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, images, the content" }
How to assign a specific service to a specific provider based on location I’m looking for a way to assign a specific service to a specific provider based on location. I’m currently developing a website with various service providers providing the same service. Do we have a way to achieve this using woocommerce? Thanks
From what we have to go on, it sounds as though your locations will become WooCommerce product categories (or tags). You can also create new categories if you're already using WooCommerce's default category.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, functions, customization, woocommerce offtopic" }
On the Blogpost I have categories showing, is there a way to exclude a catgegory like 'Media'? This is the code I have in a include file on single template file. Is it possible to exclude 'Media' showing as a category. So for example if I have the following categories on a post - 'Test Test1 Media' then it should show on the blog post 'Test Test1' ONLY. <?php $categories = get_the_category(); foreach($categories as $cat): ?> <a href="<?php echo get_category_link($cat->term_id); ?>"> <?php echo $cat->name; ?> </a> <?php endforeach; ?>
Add this simple check to your `foreach` loop: <?php $categories = get_the_category(); foreach($categories as $cat): if ( $cat->name == 'Media' ) continue; ?> <a href="<?php echo get_category_link($cat->term_id); ?>"> <?php echo $cat->name; ?> </a> <?php endforeach; ?> You can check the category name against the list of categories: <?php $categories = get_the_category(); foreach($categories as $cat): if ( in_array( $cat->name, array( 'Media', 'Other Category 1', 'Other Category 2' ) ) ) continue; ?> <a href="<?php echo get_category_link($cat->term_id); ?>"> <?php echo $cat->name; ?> </a> <?php endforeach; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
customizer not working when ever i activate ssl when ever i activate my free ssl from cloudflare my websites customizer not working it is showing me blank page. please help. screen shot ![enter image description here]( Console Screen shot: ![enter image description here](
If you're using Cloudflare's flexible SSL then you will run in to issues with WordPress. From my basic understanding, this is because Cloudflare's flexible SSL doesn't offer end-to-end encryption, it essentially encrypts items between the client and Cloudflare, but not from Cloudflare to your server. Because of this, WordPress won't always serve up the files in https:// format, so I have simply used a plugin in the past... If you search `Cloudflare Flexible SSL` in WordPress plugins then you should find a plugin that, once activated, will fix those issues that you're getting.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme customizer, ssl" }
How to customize the critical error message? How to customize the critical error message saying: > There has been a critical error on your website. > > Learn more about debugging in WordPress. Instead of using CSS to hide the message it would be interesting to be able to point the link to another source than the community article.
You can use the `wp_php_error_message` filter to customise this message: add_filter( 'wp_php_error_message', function( $message, $error ) { return 'My custom message.'; }, 10, 2 ); I haven't tested to be sure, but I would assume that if the critical error that causes this message happens to be in the code of same theme or plugin that this filter is used in, or a theme or plugin loaded before it, then this filter would likely not apply. If you want to change this message independently of your theme and plugins, this might be a good use case for a Must Use Plugin.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "fatal error, errors, wp error" }
get_header() on new page fatal error I'm building theme and using this link in navigation bar to `about.php` page. <li><a href="<?php echo get_template_directory_uri(); ?>/about.php">אודות</a></li> Now I can't understand why but when I enter `about.php` I get the following error: > Fatal error: Uncaught Error: Call to undefined function get_header() in D:\XAMPP\htdocs\wordpress\wp-content\themes\photography\about.php:2 Stack trace: #0 {main} thrown in D:\XAMPP\htdocs\wordpress\wp-content\themes\photography\about.php on line 2 About.php page <?php get_header(); ?> <?php get_footer(); ?> I'm not sure if I need to define something in my functions.php file. How can I load properly `get_header();` function in about.php?
Look into the theme template hierarchy. There is no "about.php" file and you should not link to any of the theme (PHP) files directly. Instead, you would create a theme file such as "page-about.php" and create its content in wp-admin as a Page with the slug "about," and WordPress will process that Editor content within the PHP file to create the final visible page. If you have pretty permalinks enabled you will want to link to "/about/" instead of the theme file, but because you have named the PHP file "page-about," WP will apply it to a Page with the slug "about."
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development" }
Move static site to WordPress I want to move my website < to a simpler platform like WordPress so I can make small changes myself and don't be dependant on developers (e.g. title meta changes for SEO, posting blogs) the problem is I don't have a clue how to do, this can someone help me understand the process.
There are many sites that can help you become more familiar with how WordPress works. The WPBeginner site (search for it) is one of them. There are tons of end-user-level tutorials. You don't have to be a developer to use WordPress. You can use the default theme to get started. Or look for a theme that might be to your needs - there are tons of free ones. There are tutorials for developing themes, but you don't need those (for now). And you don't need to know programming to create a site. Tons of plugins are available for you to find one that meets a specific need. This place is for developer-type questions. And the more details you can provide on what you are asking will give you better answers. For now, ask the googles/bings/ducks for some beginning WordPress tutorials. That should get you started.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "static website" }
Redirection from a specific page for users logged in but not with membership I am trying to redirect logged in user but not with a membership, from a specific page to product page. But it is showing error if I land on that page. Let's say join is the page with id 1867. Here is my code: function redirect_member_to_product(){ if (is_page(1867)){ if (is_user_logged_in() && !wc_memberships_is_user_active_member('channel-mcgilchrist')){ template_redirect('/product/channel-mcgilchrist'); exit; } } } add_action('template_redirect', 'redirect_member_to_product'); What I am doing wrong here?
Your code is fine to me, except you made a mistake here: template_redirect('/product/channel-mcgilchrist'); WordPress does not have a function named `template_redirect`, only a hook with that name. So you should have used either `wp_redirect()` or `wp_safe_redirect()` which are valid functions to perform URL/page redirections in WordPress. wp_safe_redirect( '/product/channel-mcgilchrist' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, functions, theme development, redirect" }
Check $post->ID against multiple values i have the following snippet on the site which is working perfectly fine but sometimes I have multiple pages where I want to trigger the event snippet from google, my questions can I add multiple ids using comma? this is the code I am using which is working fine. <?php if( $post->ID == 13052) { ?> <!-- Event snippet for thank-you page --><script> gtag('event', 'conversion', {'send_to': 'AW-105871269/5v9gsts6dbdsJ-Kl'});</script> <?php } ?>
This is more of a PHP question than specifically Wordpress, but you can use PHP's `in_array` to test if `$post->ID` is in a bunch of values, like this: <?php if( in_array($post->ID, [13052, 1234, 4242]) ) { ?> <!-- Event snippet for thank-you page --><script> gtag('event', 'conversion', {'send_to': 'AW-105871269/5v9gsts6dbdsJ-Kl'});</script> <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, posts" }
get_next_posts_link() returns no result despite available posts I am developing a custom theme based on the Genesis framework. I want to display a 'previous post | next post' navigation below any article in the single post view. However, neither get_next_posts_link() nor get_previous_posts_link() return any value. All output I can see is | Of course, there are adjacent posts available. My code looks something like this single.php <?php function myslug_render_post_navigation(){ echo get_next_posts_link( __( 'Previous post' ) ) . ' | ' . get_previous_posts_link( __( 'Next post' ) ); } add_action( 'genesis_after_entry', 'myslug_render_post_navigation' ); genesis(); Can anyone point me in the right direction?
`get_next_posts_link()` and `get_previous_posts_link()` are for linking between pages of a paginated post archive. For navigation between individual posts you want `get_next_post_link()` and `get_previous_post_link()`. Note the singular "post". function myslug_render_post_navigation(){ echo get_next_post_link( __( 'Previous post' ) ) . ' | ' . get_previous_post_link( __( 'Next post' ) ); } add_action( 'genesis_after_entry', 'myslug_render_post_navigation' ); genesis(); I've noticed that you've got `get_next_posts_link()` and `get_previous_posts_link()` backwards relative to their labels, but I haven't changed this in my example in case that was intentional.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, theme development, genesis theme framework" }
How to grab posts in Gutenberg Block? Trying to get latest 10 posts to display in a Gutenberg plugin, but I can't figure out how to access the latest posts from the block.js. I know how to do it from PHP and it's easy, but this is new to me. Do I have to make a request to the REST API or is there a better practice?
You'll need to use the REST API. You can access the latest posts by calling: wp.apiFetch( { path: '/wp/v2/posts' } ).then( posts => { console.log( posts ); } ); Here is some more information on using the package - <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "block editor" }
Parent comment's author display_name Parent comment's author name I found this code and would like to modify it as follows: if someone changes the display_name, the name in the comments should also change. I was able to achieve this with the following code in the comments: $usermeta = get_userdata($comment->user_id); <?php echo $usermeta->display_name?> However, I don't know how to change the code below to show display_name here as well. if( $comment->comment_parent ) comment_author( $comment->comment_parent ); I appreciate any help.
Oh, I got it! if( $comment->comment_parent ) { $parent_ID = $comment->comment_parent; $parent_comment = get_comment($parent_ID); $parent_usermeta = get_userdata($parent_comment->user_id); echo $parent_usermeta->display_name; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments" }
Is there a way to display a custom post type menu item as "users" submenu? "client" is a custom post type because I have to add several metaboxes. For a better ergonomy on admin side, I would like to add my custom post type "client" as "users" submenu. I understand to display a custom post type, normally urls are : 1. < 2. < When I add "client" inside users menu, I got this url : < So, that does not work. How can I get the client edition with list/post-new/edit-new based on the last url ?
Solution 1 (not a good idea): add_users_page( _x( $this->page_title, "page_title", $this->text_domain ), _x( $this->menu_title, "menu_title", $this->text_domain ), $this->capability, "edit.php?post_type=my-post-type" ); _Notice : This code is used in a class._ > When you are on the page, it can have some bugs with the menu, it´s a good idea for specific page Solution 2 : register_post_type( 'my-post-type', array( 'show_in_menu' => "users.php" ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, admin menu" }
I am trying to match the wpallimport using the Xpath Filter While Matching the Xpath Filter to set not to import properties having the city Gandia , this works but some properties are having Gandía , Jávea. So it is not matching. Issue seems to be with this í , á characters. /property[price[1] > 5000 and town[1] != "Jávea" and town[1] != "Calpe" and town[1] != "Elche" and town[1] != "Gandía" and town[1] != "Oliva" and town[1] != "Valencia" and town[1] != "Valle de Albaida"] ![enter image description here](
Finally I found the solution to this issue on documentation of wp all import < If you're sure that your XML file is valid, it's not using UTF-8 encoding, and WP All Import is still rejecting it, try adding this code snippet inside your child theme's functions.php file add_filter( 'is_xml_preprocess_enabled', 'wpai_is_xml_preprocess_enabled', 10, 1 ); function wpai_is_xml_preprocess_enabled( $is_enabled ) { return false; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "plugins, import, bulk import" }
Add woocommerce variation images in gallery? WooCoommerce doesn't show variation images within gallery on product pages( thumbnails below main product image ). This said, is there an plugin, preferably free, that allows this functionality? Ie. add an image for each variation and have those images shown as thumbnails below main product image?
Plugin name:(Additional Variation Images Gallery for WooCommerce) Allows to insert multiple images for per variation to let visitors to see a different images when WooCommerce product variations are switched.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, woocommerce offtopic" }
What is the global $wp object used for? In the wordpress documentation for Global Variables, I did not find information about the **$wp** global variable. I found a plugin which declares the global **$wp** variable as follows: public function login_form(){ global $wp; ... } But this variable is never used inside the declared function, so I wonder what is going on. The entire function can be found here _(links to the exact line in the GitHub WordPress Frontend Profile plugin)_
It contains the main instance of the `WP` class, which is primarily responsible for parsing the request URL and querying the appropriate posts, as well as sending headers and handling 404s. It can be used for things like getting the current request URL. If it's declared in a function but not used, it's likely a mistake, or left over from a previous version of the function that did use it. You would need to ask the plugin developer why.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "globals" }
Why are files enqueued with wp_enqueue_style and wp_enqueue_script 404 Not Found? ![enter image description here]( code script ![enter image description here]( Error net::ERR_ABORTED 404 (Not Found) Scrips Not Loaded
You tried to load files from the assets folder, but you made a typo and named the folder assests and didn't notice
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp enqueue script, wp enqueue style" }
How to send email when my plugin is activated? I’m creating and developing a new plugin for some of my private clients and I do want to see if my clients are sharing my plugin with other people (I asked them not to do that). How can I do something in my plugin every time plugin is activated, his website sends an email from ‘[email protected]’ to one or more emails I want ‘[email protected]’ and ‘[email protected]’. By the way, does this include if they update the plugin? Or I just would be able to see who activates only? And does it include the current activated plugin?
I offer you an idea that I have already used something like this. I wanted to know the sites that my plugin uses, I created a cron job allow me to send me an email every week : add_action('init', function() { $time = wp_next_scheduled('dro_cron_hook'); wp_unschedule_event($time, 'dro_cron_hook'); if (!wp_next_scheduled('dro_cron_hook')) { wp_schedule_event(time(), 'everyweek', 'dro_cron_hook'); } }); add_filter('cron_schedules', function($schedules) { $schedules['everyweek'] = array( 'interval' => 604800 ); return $schedules; }); add_action('dro_cron_hook', function() { // Here you can send the email using wp_mail() and some additional data });
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins" }
Set site title & tagline with wp.config or function.php Currently I can change `Site Title` & `Tagline` in Settings >> General but someone attack and remove it. So now I want to set these via function.php or wp-config.php Any Idea?
These fields have the keys `'blogname'` and `'blogdescription'` respectively in the options table. I'm not sure exactly why you need to do this as it seems like a priority to secure your site and be able to update it through the dashboard yourself, but you can update them easily from `functions.php` with `update_option`, e.g.: update_option( 'blogname', "site title goes here" ); update_option( 'blogdescription', "site tagline does here" );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, wp config" }
How to specify the path for require_once in a child theme? I have a child theme folder called themes/child-theme and inside I have a file dashboard_payments.php. Under the child theme folder I'm creating a new folder called gateway and inside there's a config.php. So, how do I do a require_once inside dashboard_payments.php to call the file gateway/config.php? How would the require_once or include line look like?
Since 4.7 `get_theme_file_path()` is the right function to use: require_once get_theme_file_path( 'gateway/config.php' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, theme development, child theme" }
How to append to an array and return the results in a filter? i am trying to get array in filters in wordpress i dont khnow how to do it. add_filter('ft_tabs', function ($tabs) { return array_push($tabs, array( '111' => 'aaa', '222' => 'bbb' )); }, 10); add_filter('ft_tabs', function ($tabs) { return array_push($tabs, array( '333' => 'ccc', '444' => 'ddd' )); }, 15); $array = array(); $asdasd = apply_filters('ft_tabs', $array);
Note this is mostly a PHP programming question about arrays and is better asked on e.g. Stack Overflow. As shown in the docs `array_push()` acts on the array and takes multiple parameters which get added as array values. It doesn't add key => value pairs to associative arrays, and it doesn't return the array itself, so you're probably looking for `array_merge` or just the `+` operator, then returning the new value e.g. add_filter('ft_tabs', function ($tabs) { $tabs = $tabs + arrary( '111' => 'aaa', '222' => 'bbb' ); return $tabs; }, 10); Also it's poor style to use reserved words like 'array' for variables names as you risk confusing the interpreter and getting a very unexpected result such as calling the `array` function when you meant to get the value of a variable.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, filters" }
WP REST API not retrieving all categories I am developing a project that is using the WP REST API. After some tests, I realized that it's not retrieving all the categories based on what I am trying to GET. In precise, there are supposed to be 21 results but only 10 come up. Is there some kind of restriction that I am not seeing? Any settings that I'll have to change. Here is what I am trying: ` TIA
As documented, the default number if results returned "per page" is 10. So you need to set `per_page` to however many you want to retrieve:
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, taxonomy, rest api" }
What determines whether admin toolbar is shown to a logged-in user? By default, Wordpress shows admin toolbar to Administrator, Editor, or Author but not to Subscriber or unauthenticated visitors. What determines whether admin toolbar is shown a logged-in user? I am wondering if it works based on Role, a specific Capability, or something else. I tried to dig in Wordpress core source code to find out but I could not get any clue.
The admin toolbar is displayed for all users, including Subscribers. If it's not appearing on your site, then you are likely be using a plugin that changes this behaviour. For example, WooCommerce hides the admin bar from users who do not have the `edit_posts` or `manage_woocommerce`, capability. They have a support article on disabling this behaviour here. Other plugins, such as membership plugins, might do something similar. You would need to check them individually.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "admin, user roles, capabilities, admin bar" }
WP_QUERY post_in problem why when i using this code : $paramss = array('post_in' => array( 760, 761) , 'post_type' => 'product'); $wc_querya = new WP_Query($paramss); i get 5 products list and not only product with id 760,761 ? Regards
As documented, it's `post__in`, with two underscores: $paramss = array( 'post__in' => array( 760, 761 ) , 'post_type' => 'product' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, wp query" }
Access ACF fields within custom preview function? I'd like to access custom ACF field values from `custom_preview()` filter? add_filter( 'preview_post_link', 'custom_preview' ); function custom_preview() { // how to access ACF field values here ? }
As documented, the `preview_post_link` passes the post object as the second parameter. You can use this to get any fields that you might want: add_filter( 'preview_post_link', function( $preview_link, $post ) { $custom_field = get_field( 'custom_field_name', $post ); return $preview_link; }, 10, 2 // MUST be 2 to get the $post parameter. );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, filters" }
Filter wp_redirect() to stop redirect under certain condition I am developing a tool to print PHP debug messages on screen. I would like to stop the `wp_redirect()` function from actually doing the redirect if the debug tool contains a message that it wants to display. One way would be to check this before calling `wp_redirect()` at all, but it's preferable to have something like a `before_redirect` filter where I can decide to "go on" or "don't go". I have seen the `wp_redirect` filter allows me to filter the redirect location. I could say "go back to the same place" but that would be a new http request and the logs would be already lost.
As you can see from the source code, `wp_redirect` always ends in a PHP header request, **except** if the location is empty, because then it doesn't know where to redirect. So you can indeed use the `wp_redirect` filter. If you return an empty string under certain circumstances, the redirect will not happen.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, redirect, wp redirect" }
Google Fonts not loading correctly I have enqueued google fonts in the usual way in functions.php: function travellers_field_guide_scripts() { wp_enqueue_style('travellers-field-guide-style', get_stylesheet_uri(), array(), _S_VERSION); wp_enqueue_style('googlefont_css', ' false); } add_action('wp_enqueue_scripts', 'travellers_field_guide_scripts'); However, upon checking the `<head>` all I see is this <link rel="stylesheet" id="googlefont_css-css" href=" media="all"> I've resorted to manually adding the link (exactly as I enqueued it) to the fonts in the header, and the fonts are downloaded as expected, but would be nice to know why Wordpress mangles the googlefont when trying to enqueue it. I checked my theme, there is no other reference to googlefont except to enqueue so I'm not doing anything to mangle it.
It looks like the URL is getting parsed somewhere and whatever does the parsing is probably internally only able to deal with one parameter for a particular name, so just keeps the second value for the family parameter. As you have a valid usecase for having two parameters with the same name, you might want to file this as a bug. If there are workarounds they could be hacky, so unfortunately adding to your header file might be the best solution for now, unless someone else can suggest another sensible way to add this to the header through hooks.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp enqueue style, fonts" }
How to restrict logged user to view only certain pages? How can I restrict a specific logged user (current role is subscriber) via wp_get_current_user() to view only specific pages?
This code filter the content for custom post types "news", you say "specific pages" so this can be adjusted to your needs. Then it checks if the user is a subscriber, and shows the content if it is, else, it just says "Not allowed". function filter_content($content) { global $post; if ( $post->post_type == 'news' ) { //Specify your pages here $currentuser = wp_get_current_user(); if ( in_array( 'subscriber', (array) $currentuser->roles ) ) { return $content; } else { echo 'Not allowed'; } } } add_filter('the_content', 'filter_content');`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "user access, content restriction" }
Where does WordPress store plugin (enabled/disabled) status for multisite? A recent update to one of the plugins I use broke my multisite blog and in the process of debugging it, all of the plugins got disabled. Now I have to try to figure out which plugins used to be enabled, but that's a big chore for various reasons. I've probably got at least one backup since the last time I toggled plugin, but I don't know where WordPress stores plugin state information for a multisite blog. I tried dumping the whole WordPress database to try to search for the plugin state settings, but the thing is too much of a monster to manually search through, especially since most search terms return too many results to be practical. Does anybody know where WordPress stores the state of plugins? Does it store them in every sub-blog's settings or is there a master one? What about network-enabled plugins?
I found it. It's in the `active_sitewide_plugins` value of the `wordpress_sitemeta` table.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, database, options, location search" }
How to change avatar of the comment author using comment ID? One visitor commented on one of my post as a guest. Now, i want to change avatar of this comment using comment ID. Comment ID of the comment is 1092. How can i change avatar of the comment using comment id? Actually i want to change avatar for couple of comments. Any help would be greatly appreciated.
You can use `pre_get_avatar` filter to manipulate comment avatar html and stop WP from getting a default avatar for the comment. > _Passing a non-null value will effectively short-circuit get_avatar(), passing the value through the ‘get_avatar’ filter and returning early._ E.g. add_filter( 'pre_get_avatar', 'my_filter_pre_get_avatar', 10, 3 ); function my_filter_pre_get_avatar( $avatar_html, $id_or_email, $args ) { if ( is_a( $id_or_email, 'WP_Comment' ) ) { // Add more cases with elseif or use a switch statement here if ( '1092' === $id_or_email->comment_ID ) { // set avatar to whatever html you want $avatar_html = '<img class="avatar" src="" alt="Custom avatar">'; } } return $avatar_html; } Use this in your theme's `functions.php` file or in a custom plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments, avatar, gravatar" }
Wordpress admin display post type tags as checkbox I used Wordpress ACF plugin to created a post type called `resource`, also I created two tag categories named `resource-type` and `resource-topic`, I can added in those tags in the post by the enter certain key in input box, but if the input is mistype, a new tag will auto added in the list, this is not what I want and I think of make the tags as checkbox so that it would easily know what tags is available and reduce the mistype error, is it possible to change like this way? ![enter image description here](
Have you considered changing them to Categories? Categories and Tags are essentially the same thing, just that Categories have a Hierarchy. Category selection is via a Checkbox so you will have more control over what is selected. **Update** If you have used the function 'register_taxonomy' to create your Tags then you only need to add or adjust one variable - 'hierarchical' - which needs to be set to true. See: Codex information on register_taxonomy If you used a plugin to create the Taxonomies it should have a similar option. Remember to backup your website before you make any changes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, tags" }
Conditional redirect to several pages Suppose I have these WordPress pages: * `page-A` * `page-B` * `page-C` and a published page `page-main`. **My question:** The clients see and access only `page-main` which is in the end _virtual_ \- it doesn't exist. Accessing this `page-main` page should redirect to **one** of the above mentioned pages A-C, depending on some conditions which are not important for this question. How can I achieve it?
So you need this to happen before Wordpress has output anything at all, otherwise you won't be able to send a redirect. A way to achieve this is with the `template_redirect` hook, documented here: < The example from that docs page is more or less exactly what you want. I've edited it a little bit for your question: function my_page_template_redirect() { if ( is_page( 'page-main' ) ) { if ( $some_condition ) { wp_redirect( home_url( $pageA ) ); } else { ... other caeses here with redirects to other pages } } } add_action( 'template_redirect', 'my_page_template_redirect' ); You'd need to add that to your functions.php or a plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect" }
How do I make reusable content blocks for header and footer when using Wordpress headless with another front-end? I'm setting up a Wordpress project with Gatsby as frontend, and also using ACF for content. But I wonder how you would setup global content parts like header, footer, or any other kind of content that is being used globally throughout the website? For example both HOME and ABOUT pages need to have their "own" content, but also shares some specific blocks with same content. I need to be able to edit the content for my header like setting up links to internal pages, be able to edit footer content (like text, an image etc), and for any other global blocks I'm looking for a way to setup them like title, text, maybe an image and so on (ACF control kind of...) Please help me out! Thanks
ACF has the ability to create a 'Theme Options' page which you can then use to conveniently centralise options for things like headers and footer etc.. ACF Options Page information As Jacob Peattie rightly points out, how you integrate this into Gatsby is outside of the scope of WPSE and may require custom development. However, providing you can inject custom code into these areas, via a function, shortcode or custom widget etc., using an ACF Options Page to control that content works nicely and is worth exploring.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, custom post types, rest api, headless" }
Why wordpress rewrite my custom URL? I am new in wordpress There may a mapping question in my website I hope this SEO URL is work and get Post data: < If not using SEO URL(get action), it is work! In this case < but why my page will redirect to: < Should I set or change something that can make my URL work? Thanks a lot # In .htaccess # RewriteEngine On RewriteBase /web/ RewriteRule ^d-post/([A-Z0-9]+)/(.*)/$ ?pagename=d-post&d;_id=$1&d;_name=$2 [L] # Without using wp & run at localhost it is work ![If not using wordpress](
Oh I find I should add some filter add_filter('query_vars','d_search_1'); function d_search_1($vars) { array_push($vars, 'd_id'); return $vars; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, rewrite rules" }
Call to undefined function insert_with_markers I'm experimenting with creating a function to write code into htaccess (I understand the security issues associated). I'm currently using the function insert_with_markers() as a starting point however its throwing a 'call to undefined function' error. I am using it within a function that is only running whilst logged into the Admin Dashboard. I understand that the function if found in the file: wp-admin/includes/misc.php but I made the assumption that this file is loaded whilst within the Admin Dashboard anyway, so I don't need to include it? If I manually include the file, the function runs correctly. **My question is:** does the wp-admin/includes/misc.php file not get loaded by default when logged in to the Dashboard? Or is it only loaded in certain cirumstances?
Looks like `insert_with_markers()` function becomes available during `admin_init` hook. So in order for your code to work, you should do the following: function do_my_htaccess_stuff_371705() { //function `insert_with_markers()` is working now } add_action('admin_init', 'do_my_htaccess_stuff_371705');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp admin, htaccess" }
Setting posts_per_page for taxonomy term template I have a custom taxonomy term page set up to display posts associated with that term (taxonomy-insight_type-academia.php). I figured I could use the following to limit the posts on that page based on code found here: < add_action( 'pre_get_posts', function( $query) { if ( $query->is_tax( 'academia', 'insight_type' ) ) { $query->set( 'posts_per_page', 1 ); } } ); I have added the term to the taxonomy but it doesn't seem to work. I can get it to work for the taxonomy, but not the term. Is there a way to do this? Thanks
The taxonomy template you have (`taxonomy-insight_type-academia.php`) is in the form of (`taxonomy-{taxonomy}-{term}.php`), and the format for `is_tax()` is `is_tax( '<taxonomy>', '<term>' )`, so in your `pre_get_posts` callback, you should: // Use this. if ( $query->is_tax( 'insight_type', 'academia' ) ) // Not this. if ( $query->is_tax( 'academia', 'insight_type' ) ) Additionally — to avoid conflict with other queries, you should also check if the current query is the main one or not, and also check if it's an admin-side request. if ( ! is_admin() && $query->is_main_query() && $query->is_tax( 'insight_type', 'academia' ) ) You may already know that, but I thought it'd be a good reminder. :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, functions, templates, taxonomy, terms" }
Excerpt – First Sentence & Read More I am using this function to limit the excerpt to the first sentence... function hello_first_sentence( $string ) { $sentence = preg_split( '/(\.|!|\?)\s/', $string, 2, PREG_SPLIT_DELIM_CAPTURE ); return $sentence['0'] . $sentence['1']; } add_filter( 'get_the_excerpt', 'hello_first_sentence', 10, 1 ); However, for some reason, I am unable to add the "read more" after the excerpt... any help?
To append strings in PHP use `.`, like: return $sentence['0'] . $sentence['1'] . "... Read More";
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "functions, excerpt" }
add all blog posts to folder I want to add all the blog posts to the /blogs/the-post-name type structure. I can do this through the permalinks settings with: `/blogs/%postname%/` but this also affects custom post types resulting in a `/blogs/custom-post-type/the-custom-post-type-name` How can i add all posts into the blogs folder without adding all my custom post types into the blogs folder?
When registering the custom post types, set `with_front` to `false`: register_post_type( 'my_post_type', [ // ...etc. 'rewrite' => [ 'with_front' => false, ], ] ); The post type URL will then not include anything extra you've added in the Permalinks settings.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts, permalinks" }
Can I delete `wp-config-sample.php` after installing and configuring Wordpress? Can I remove `wp-config-sample.php` after installing and configuring Wordpress? Could this have any consequences in the future? Is this file restored after updating? At first glance, it just seems unnecessary
Yes, you can safely delete that file. It's a template of what a minimal `wp-config.php` looks like, so as soon as you have a working wp-config, you don't need it. It will never be restored unless you reinstall Wordpress from scratch, e.g. by downloading and unpacking a clean Wordpress installation. If for some reason you need to refer to it in the future, then you can easily get it again by downloading Wordpress and pulling it out of the archive, although it's highly likely that you'll only need it for a new manual Wordpress install.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp config, filesystem, wp filesystem" }
How to fix blocked cookies error that doesn't let me log into wp-admin? I have edited functions.php file recently and also added a new folder to themes folder for custom endpoint and after that I wasn't able to login to wp-admin. I deleted the folder and code line from functions.php but it still doesn't let me to login. I have cleared all cache and cookies but still I get the same error :( This mixed content error was visible earlier but I was able to login then. P.S. I have recently changed wordpress domain name as well as home url and site url, also used search and replace tool to replace all old urls to new ones. P.P.S. the theme that I edited is a copy of the original and is with symlink. ![enter image description here]( P.P.P.S. I have fixed mixed content error but the cookie error still occurs :(
I added these lines in wp-config above `/* That's all, stop editing! Happy blogging. */` line: define('ADMIN_COOKIE_PATH', '/'); define('COOKIE_DOMAIN', ''); define('COOKIEPATH', ''); define('SITECOOKIEPATH', ''); define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST'] );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "multisite, login, errors, cookies, site url" }
Get all post types that supports tags I'm trying to get all the post types that has tags functionality. I searched a lot but couldn't find a conditional or something for that. I need a way to get post types or post objects for the posts which are taggable. Here are my current code to get post types: public function getPostTypes() { $excludes = array('attachment'); $postTypes = get_post_types( array( 'public' => true, ), 'names' ); foreach ($excludes as $exclude) { unset($postTypes[$exclude]); } return array_values($postTypes); } Thanks!
Please try this. function get_post_tp(){ $args = array( 'public' => true, '_builtin' => false, ); $post_types = get_post_types( $args, 'objects' ); foreach ( $post_types as $key => $value ) { $postArray = json_decode(json_encode($post_types), true); $array_key = key($postArray); print_r($post_types[$array_key]->taxonomies); // here you can see in taxonomies post_tag is exist or not. //if exist then push into array otherwise you can skip it.. //apply your logic here } } add_action('init','get_post_tp');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, post type, post type support" }
Detach site from multisite (turn off multisite) I have a series of wordpress sites which live under one multisite: - **My multisite** * Website A * Website B * Website C * Website D I am going to be rebuilding the site and as part of the new build, we don't need the multisite confiugration but I need all the content of one of the site as it's rather large. Essentially, what I want to do is have ' _Website C_ ' as a single site on it's own, websites ' _A_ ',' _B_ ' and ' _D_ ' can be deleted. Any sort of multisite functionality needs to be removed and it needs to work as a single WP site. The domains are as follows: * Website A - www.website.com/de * Website B - www.website.com/es * Website C - www.website.com/ * Website D - www.website.com/ru This should hopefully make any database changes easier as the new site will be: www.website.com/
I'd just export all content from the site you want to keep. Then create a new WP instance, import that exported data, tweak as required. Once the site is OK, make the new site active for the desired domain name (in your hosting, point the domain to the new site's folder). No messing with databases required. **Added 31 July 2020** Another way: Use the Clone plugin from Automatic to export subsite. Install the plugin as superadmin. Then admin to the subsite and use the Clone plugin to back up everything. Create a new WP instance (single-site), then install the Clone plugin there. Then import the backup you made of the subsite into the new site via the plugin. Make sure you remember the admin credentials, as everything on the new site will be replaced during the restore process. Everything from subsite will now be on the new site including themes, plugins, settings and content.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multisite, migration" }
Categories in Gutenberg I would like to have a multi select field for my categories. How can i do that? My code doesn't work: function getCategories () { var options = []; var categories = wp.data.select('core').getEntityRecords('taxonomy', 'category'); categories.forEach((category) => { options.push({ value: category.id, label: category.name }); }); } <SelectControl multiple label={__('Select a Post')} help={__('Select a post to display as a banner.')} options={getCategories} />
Ich have to write options={getCategories()} that solved this problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "block editor" }
Send email with Content-Type text/plain I have problem with emails in Wordpress. I have to send message with Content-Type is text/plain, but in Wordpress default Content-Type is text/html. That change chars like `&` to `&amp;`. How can I change Content-Type? Please help.
You didn't say how you're sending emails, but if you're using `wp_mail`, this is how you change the type to `text/plain`: function wp_set_mail_plaintext() { return 'text/plain'; } add_filter( 'wp_mail_content_type', 'wp_set_mail_plaintext' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "email" }
How to add one time a new page? I m working on a plugin and i would add a page for every value of my database. But for every refresh, a new page with same name will be added. How can i fix this? for ($i = 0; $i < count($namepages); $i++) { mic_create_new_page($name[$i],$namepages[$i]); } function mic_create_new_page($name, $namepages) { global $user_ID; if (post_exists($namepages) == false) { $new_post = array( 'post_title' => 'Services ' . $name, 'post_content' => 'New post content', 'post_status' => 'publish', 'post_date' => date('Y-m-d H:i:s'), 'post_author' => $user_ID, 'post_type' => 'page', 'post_name' => $namepages ); $post_id = wp_insert_post($new_post); } } register_activation_hook(__FILE__, 'create_new_page');
If this code is in functions.php or directly in plugin code, the for loop at the top will run every time Wordpress is loaded, and the hook at the end refers to a function which doesn't exist. So probably what you want is to put the top code in a function: function zed93_create_new_page { for ($i = 0; $i < count($namepages); $i++) { mic_create_new_page($name[$i],$namepages[$i]); } } And correct your hook to: register_activation_hook(__FILE__, 'zed93_create_new_page'); Note the function name can be anything, but making it unique to your project helps avoid collisions with other plugins / themes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts" }
Why doesn't WordPress use the smaller sized image? I've been trying to understand how WordPress picks images to use depending on the size of the user screen, but I've been unable to figure it out. Is it just by checking if the request is coming from a mobile or desktop device? I have a photo site that would like to cater to 4k screens, so I have a featured images of 2400px * 1120px. I know a version that has a width of 1536px is generated. On my mac, my the featured image is displayed as 1425px * 665px (1425px is the full width of my browser window). Why doesn't WordPress use the 1536px width image that was automatically generated instead of the 2400px width original?
It doesn't, WP supports responsive image markup, so your browser decides based on various factors such as pixel density, battery, network, viewport, etc
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, post thumbnails" }
Make every comment go to the spam folder Wordpress comments exists in 4 states: 1. 0 not approved 2. 1 approved 3. Trashed 4. Spam When a user makes a comment it will end up in the 0 not approved folder, or if it's a spam comment directly to the spam folder. Is it possible to send every single comment to the spam folder?
I don't know of a way the default comment status can be changed, but there's an action `'comment_post'` that runs after comments are inserted that you could easily hook to set every new comment to have the 'spam' status: function set_new_comment_to_spam($commentId) { wp_set_comment_status($commentId, 'spam'); } add_action('comment_post', 'set_new_comment_to_spam', 10, 1); Add that to your functions.php
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, spam, comment meta" }
How to hide Wordpress users' names externally? I have several users creating posts in Wordpress, but I don't want any of their names to appear publicly. On the site, I want it to only say By: Website Editor. This also means that the names should not appear in any other related URLs, for example author URLs. If someone were to visit www.example.com/?author=3 for example, it should not reveal any names. I don't mind disabling author URLs completely if that's easier to do. The SEO plugin I use also shows the name of the author in the source, that's gotta go away also. And in the backend, the names should appear just like usual. How could I achieve this? Thanks!
This can best be achieved with a plugin, as it requires changing certain data stored in the database.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "users" }
Why is wordpress suddenly stripping away all newline characters and how to disable this? I've spent about 3 hours trying out various functions to figure out why the newline characters are being removed every time I save. How do I figure out why is wordpress suddenly stripping away newline characters? I have not installed any plugins. How can I get newline characters to show up on my site without converting all blocks to HTML and modifying everything in code?
I found the following snippet which we can add to functions.php . I'm adding these via a plugin. function clear_br($content) { return str_replace("<br>","<br clear='none'>", $content); } add_filter('the_content','clear_br'); Note that I've put `"<br>"` tag which is what wordpress creates when you enter newline characters.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor, visual editor" }
Can I alter the main loop to 'orderby' a custom callback? I have a custom post type where the `title` is a name, and I want to sort the loop by the last word in `title`, the surname. I can easily break the names apart and filter by the last word in a custom query, but I don't want to re-write the main loop / pagination for the archive page. Is it possible to pass a callback to the `orderby` param in the action `pre_get_posts` or is this a lost cause? Thanks!
No you can't pass a callback function. Callback functions are PHP, so they can't be run in MySQL. For that to work it would need to query the results from the database first, but you'd get the wrong results because they're unsorted. You would need to use the `posts_orderby` filter to do this as part of the SQL query: add_filter( 'posts_orderby', function( $orderby, $query ) { if ( ! is_admin() && $query->is_post_type_archive( 'post_type_name' ) ) { $orderby = "SUBSTRING_INDEX(post_title, ' ', -1) ASC, post_title ASC"; } return $orderby; }, 10, 2 ); That uses the `SUBSTRING_INDEX()` MySQL function to order results by everything after the ~~first~~ last space in the post title, and then by the post title so that results with matching surnames are sorted by first name.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, loop, pre get posts" }
Remove extract from function I am using this code so that users can input `[photo no="1"], [photo no="2"], [photo no="3"]` etc.. in their posts. However I heard that `extract` is an unsafe function to use. How could I modify this code to remove `extract`? function photo_shortcode($atts){ extract(shortcode_atts(array( 'no' => 1, ), $atts)); $no = is_numeric($no) ? (int) $no : 1; $images = get_field('fl_gallery'); if ( !empty( $images ) ) { $image = $images[$no]; return ' $image['url'] ' ; } }
It's very simple: Just assign the value of `shortcode_atts()` (which is an array) to a variable and use it to access the shortcode attributes in the same way you access the items in any other arrays: $atts = shortcode_atts( array( 'no' => 1, ), $atts ); // Use $atts['no'] to get the value of the "no" attribute. $no = is_numeric( $atts['no'] ) ? (int) $atts['no'] : 1;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions" }
How to make wp_enqueue_style and wp_enqueue_script work only on custom post type How to make wp_enqueue_style and wp_enqueue_script work only on custom post type I have install plugin on my wordpress that creat custom post type which is " and i have other custom post type like " so i only want to css work on manga not anime or in the front page this is the code: wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css' );
You can use conditionals: <?php add_action( 'wp_enqueue_scripts', 'wpse_enqueues' ); function wpse_enqueues() { // Only enqueue on specified single CPTs if( is_singular( array( 'anime', 'manga' ) ) ) { wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css' ); } } ?> If you need the CSS on archives as well, that's another condition: if( is_singular( array( 'anime', 'manga' ) ) || is_post_type_archive( array( 'anime, 'manga' ) ) ) { wp_enqueue_style( 'wp-manga-plugin-css', WP_MANGA_URI . 'assets/css/style.css' }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, custom post types, wp enqueue style" }
Problem with favicon in the latest wp Im having a problem with the favicon icon in WordPress 5.4.2. Im including my own favicon in the sites header.php, that is used for wp and wp non related static pages. The problem is that when I open a pdf file inside this site, the wp logo automatically appears as a favicon, instead of my site's icon. This would not happen in previous wp versions. Is there a way to change the wp icon to my sites icon, or just to nothing?
There is basic Favicon functionality built into WP. Go to Theme Customiser > Site Identity and use the 'Site Icon'. In some cases its better to have custom code in the head, and the above doesn't work for non WP pages within the site, if thats what you are using. However its worth a try if you hadn't already. In the past I have also used a website that _generates real favicon_ code for the head, including a variety of sizes and allows you control the look of favicons on smartphones etc. So going with a more detailed setup in the head may also be worth exploring?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "favicon" }
Having a template per category? Bad for server overhead? I understand that you can create (as per the WordPress Hierarchical Structure) a specific template to load a specifc template. For example: category-new-york.php ^ this is a priority over simply: category.php My question is, would creating a template PER US State be a "bad idea?" So, I would have: category-alabama.php category-arizona.php category-akansas.php etc etc I say "bad practice" because perhaps I am just adding a ton of overhead that WordPress has to loop through templates - or is it not a huge problem? Would the overhead be nominal? Thanks
> I say "bad practice" because perhaps I am just adding a ton of overhead that WordPress has to loop through templates - or is it not a huge problem? Would the overhead be nominal? No, there won't be an extra performance cost because that's not how the template loading works. WP always runs through the template hierarchy from most specific to most generic, testing if the file exists as it goes along. It doesn't "loop" through them. As for creating a template for every US state, I would advise against it, mainly because it means your folder will have a lot of files making it difficult to navigate in the editor, and when you want to make a change you have to update every single state. You'd be better off making a single generic state template, or better yet, add a state taxonomy and create `taxonomy-state.php` instead of repurposing categories.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, custom taxonomy" }
How do I check if I can use the allowed_block_types filter? For a WordPress theme I deregister a few blocks for Gutenberg (in fact, I only register the ones I need). For this, I use a filter: add_filter( 'allowed_block_types', 'amb_allowed_block_types' ); This filter hooks into a function like this: function amb_allowed_block_types( $allowed_blocks ) { return [ 'core/paragraph', 'core/image', 'core/heading', 'core/gallery', ... This works nice. But I don't want to use this filter if it is being used on a WP theme that doesn't have Gutenberg enabled. How can I make sure that this filter is only being used on Gutenberg sites? Many thanks!
You can check if the current theme supports Gutenberg blocks inside your function function amb_allowed_block_types( $allowed_blocks ) { if(! current_theme_supports('wp-block-styles') ){ return $allowed_blocks; } return [ 'core/paragraph', 'core/image', 'core/heading', 'core/gallery', ...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, block editor" }
Should I use docker in wordpress production? My question is, is it a good idea to use docker for a big woocommerce website (more than 100k products)? Or will this incur a noticable performance cost compared to running wordpress straight on the VPS (without containerization)?
> My question is, is it a good idea to use docker for a big woocommerce website (more than 100k products)? Or will this incur a noticable performance cost compared to running wordpress straight on the VPS (without containerization)? **It won't make much difference, nothing you will notice.** It's not even in the top 50 things you should be concerned with for performance. > running wordpress straight on the VPS (without containerization)? A VPS doesn't run on bare metal, the V stands for Virtual, so it'll either be a Virtual Machine, or a container of some sort. At 100k+ items of content, I would be more concerned with avoiding problematic queries and setting up object cache, perhaps some varnish style equivalent.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, database, performance, docker" }
How to allow WordPress updates to only one specific administrator? I found a code to prevent WordPress update for certain user role: add_action( 'init', function () { if ( ! current_user_can( 'administrator' ) ) { add_filter( 'pre_site_transient_update_core', 'disable_updates' ); // Disable WordPress core updates add_filter( 'pre_site_transient_update_plugins', 'disable_updates' ); // Disable WordPress plugin updates add_filter( 'pre_site_transient_update_themes', 'disable_updates' ); // Disable WordPress theme updates } } ); What about allowing to update for only one user?
**SOLUTION:** We take this code and paste it to functions.php : function createit_hide_upd_for_other_adm_users() { $current_user = wp_get_current_user(); if ( 777 != $current_user->ID ) { //change the user ID add_filter( 'pre_site_transient_update_core', 'disable_updates' ); add_filter( 'pre_site_transient_update_plugins', 'disable_updates' ); add_filter( 'pre_site_transient_update_themes', 'disable_updates' ); } else { } } add_action( 'init', 'createit_hide_upd_for_other_adm_users' ); You just need to find the correct **WordPress user ID** and put it in place of 777, thats it!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp admin, users, updates, automatic updates" }
Enqueue script globally This only works for admin dashboard. add_action('admin_enqueue_scripts',array($this, 'login_register96_adminscripts')); And this only works for the user place. add_action( 'wp_enqueue_scripts', array($this , 'login_register96_scripts') ); Is there a way I can enqueue a script globally? Which will be operational on the whole website including admin dashboard.
I'm not aware of any other way but to use both add_action lines, for a single function. Example: function my_enqueue_sripts_function_name(){ // your enqueue logic here } add_action('wp_enqueue_scripts', 'my_enqueue_sripts_function_name' ); add_action('admin_enqueue_scripts', 'my_enqueue_sripts_function_name' ); There's no rule that forbids you from adding the same function on multiple hooks. Furthermore, if you need to know which action called the function, from within the function, you can use `current_action()` or `current_filter()`
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "plugin development, customization, wp admin, login, wp enqueue script" }
Why does WordPress want a 512×512 pixel site icon I get that a site icon needs to be square, but I don't know why it needs to be as large as 512×512 or larger. Can anyone advise why is this, and/or where that image would be used at a resolution higher than that of a favicon (which I understand to be 48×48px or smaller) and what would be the consequences of using a lower resolution image there?
The site icon in WordPress is worked as a favicon. And the knowledge about the favicon is mostly limited to 16×16 or 64×64 pixels. But this StackOverflow thread shows there's a necessity of a 114×114px favicon for Retina Opera, and a 200×200px favicon for Mobile Opera Speed Dial. The necessity of such a larger icon is mostly to support retina displays, where it requires larger output, and smaller favicon can get pixelated. This article by Thomas Fuchs has a mention of 512×512px retina-ready favicon. And I found this article with its comments stating that: > 512×512px icon in the web manifest to support browser loading splash screens Also found mention of other sizes like 192×192px, 228×228px etc. So, with a maximum 512×512px Site icon, WordPress has all the ease to display it in different devices in different display ratios. Finally this WordPress guide on using Site icon in WordPress could assist you.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "favicon" }
How to target all woocommerce categories that don't have any subcategories in them? I want to target all pages (product categories) that are displaying the products themselves. My woocommerce settings set to show only categories/subcategories (unless there are none) and then by default the products grid is displayed on the page. `is_product_category()` function doesn't help since it also targets the parent categories which don't have direct products in them. Most of my categories that don't any subcategories in them are grandchildren categories if it matters for the answer. How can I achieve it and to use it in woocommerce hooks?
You can use the `woocommerce_products_will_display()`. This function returns `true` if the current shop page is going to display products. This will be the case if your shop pages are set to display products or subcategories _and_ products, but it will be `false` if the shop pages are set to display subcategories only, and the current category has subcategories. if ( woocommerce_products_will_display() ) { // Products are showing. } else { // Products are not showing. } The `woocommerce_get_loop_display_mode()` is similar, but can let you know whether subcategories are also displaying: switch ( woocommerce_get_loop_display_mode() ) { case 'products': // Products are displaying. break; case 'subcategories': // Subcategories are displaying. break; case 'both': // Products and subcategories are displaying. break; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, woocommerce offtopic, taxonomy" }
How to redirect a page to another? On my website, I have following url structure: example.com/test/ example.com/test/a-page example.com/test/another-page How can I redirect all of the URLS that contains **/test/** right after the domain name to **example.com/info/** I understand I can do it using htaccess, but I cannot format the rule syntax.
Try the following at the top of your `.htaccess` file, _before_ the existing WordPress directives: RewriteRule ^test/ /info/ [R=302,L] The pattern `^test/` matches all URLs that _start_ `/test/`. Note that the URL-path matched by the `RewriteRule` _pattern_ (first argument) does not start with a slash (when used in `.htaccess`). If this is intended to be permanent then change the 302 to 301 - but only after you have tested that it works OK.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "pages, redirect, htaccess" }
Execute php after post save/update I have created a php script (generate.php) which is querying posts on set criteria and then writing result in custom xml file. I would like to execute the generate.php everytime the post Save/Update button is pressed. Do you have any clue on how to do this? May be with cron jobs every X minutes would be better?
At the end, I solved with jQuery and ajax jQuery( '.post-type-property #post' ).submit( function( e ) { if(!(checkMetaFields() && checkCategories())){ //some validation functions return false; }else{ jQuery.ajax({ url:" type:"post" }) } } );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, save post" }
how to assign content to a different author while loading content I am new to WordPress and am learning the platform on the fly. We are in the process of converting a large non-WordPress site to the WordPress platform. In the process, we have several people updating and loading content into the new site. As a result, all the content is being assigned to the individual loading the content. **My Question is Two-fold** **1st]** I am under the impression that I can reassign the content to the appropriate author through a mysql query/update script I write... Is this a correct Assumption? **2nd]** Is there a way to add an "author" selection box to the post/page form where the content loader could simply select the correct author and then manipulate the parsing process so that WordPress recognizes the selected author and assigns the content to them instead of the loader?
Just to add to what MozBoz has already said, you can also set the author from the post / page in WP directly. You can usually do this from the editor itself, but there are a lot of page builders available, so I'd suggest going to WP Admin and to your **All Posts** , hover over the post you want to set the author of and select **Quick Edit**. This will pull down a tray of options, one of which will be an author dropdown where you can select the posts author from all of the users on your site.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wpdb, author" }
Hook when post is set from published to draft? Is there an action i can hook into when a post is set from published back to draft? I have tried both `transition_post_status` and `publish_to_draft` but they don't seem to work when I set the post back to draft. I am doing something like: add_action('publish_to_draft', 'doStuff') function doStuff() { // do stuff here } Maybe there is something I am missing, but I wanted to check that these are the correct hooks to use.
Yes, these are probably the right calls to use for what you want. I just checked this by adding this to my functions.php: add_action('publish_to_draft', 'doStuff'); function doStuff() { update_option('foo', 'bar1'); } Then using the quick edit in the posts list to change a published post to draft, and this hook definitely ran at that point and set this option in the database. Note that if you echo something from this hook, or expect to see something output to your browser you likely won't see it, and you might cause an error as this might be being called via an ajax type call.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, hooks, publish, draft" }
How to show the error causing the 'There has been a critical error on your website'? I'm getting the error: 'There has been a critical error on your website. Learn more about debugging in WordPress.'. How do I display which error I'm getting in the frontend? I have these three lines in my **wp-config.php** -file: define( 'WP_DEBUG', true ); define( 'WP_DEBUG_DISPLAY', true ); define( 'WP_DEBUG_LOG', true ); It surprises me that enabling WP_DEBUG, doesn't show it. I can (however) still find the errors in `/wp-content/debug.log`, - but it's just an extra step in development, having to open that file and find the error. How do I just get the proper error displayed on the page, - and not hid away in that debug.log-file? I can see that WP_DEBUG is enabled, since this: echo '<pre>'; print_r( WP_DEBUG); echo '</pre>'; die(); ... returns: `1`.
Ahh! I found it. If I did this: phpinfo(); die(); Then I could see that 'display errors` was set to off. So if I added this in the top of my `functions.php`: `ini_set('display_errors', 1);`, then it started showing the errors.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "errors, debug, 500 internal error, wp debug" }
how to get a list of all top level pages I am trying to figure out how to get a list of the permalinks for top-level pages only. My goal is to put them in a selection box on a form. I have spent a couple of hours searching here for an answer to no avail. I was hoping someone could point me in the right direction.
$query_args = array( 'post_type' => 'page', 'post_status' => 'publish', 'parent' => 0, ); $pages = get_pages( $query_args ); Function `get_pages()` accepts parameter with `parent`. Keeping it 0 (zero) will give us first level pages. In the example `$pages` will contain the first level pages. Use loop for `$pages` and you can use it in option as you require.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, pages" }
is_user_logged_in() throwing undefined function error I am running this simple conditional statement on my plugin page: if (! is_user_logged_in()) { add_action('init', 's8w_ajax_login_init'); } It is throwing a fatal undefined function error for `is_user_logged_in`. Am I missing something? I have several wp globals on the same page. Do I have to call something else for this to work?
It's failing because WordPress isn't loaded. Instead of making AJAX requests directly to PHP files in your theme, make them to a REST API endpoint. For example: add_action( 'rest_api_init', function () { register_rest_route( 'petebolduc/v1', '/test/', array( 'callback' => 'petebolduc_ajax' ) ); } ); function petebolduc( $parameters ) { $foo = $parameters['foo']; return "foo is " . $foo; } With that code, visiting: `example.com/wp-json/petebolduc/v1/test?foo=bar` gives: "foo is bar"
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, wp user query" }
Add Taxonomy Description with wp_set_post_terms I am adding tags during wp_insert_post using **wp_set_post_terms**. But I have no clue how to add a tag description with my code. I have not found anything out there.
You can't use `wp_set_post_terms()` to set the term description, but you can use `wp_insert_term()` to create the term and set the description (plus other details), and then pass the term ID to `wp_set_post_terms()`. Working example for one term: $taxonomy = 'category'; $term_name = 'Foo Bar'; // First we create the term (if it doesn't already exist). if ( ! $term = term_exists( $term_name, $taxonomy ) ) { $term = wp_insert_term( $term_name, $taxonomy, array( 'description' => 'Test category', ) ); } // Now assign the term to the post (here the post ID is 1). if ( $term && ! is_wp_error( $term ) ) { wp_set_post_terms( 1, $term['term_id'], $taxonomy ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "terms" }
Can you Use the Rest API to query a custom database table I am new to the wp platform and just learned about the Rest Api. I am creating a plugin that will allow the user to access a note keeping system which I plan to manage in a custom database table. Is it possible to manage the CRUD through the Rest Api or is the Rest Api reserved for the core WordPress database tables?
Wordpress has no system of assigning privileges or access to control to _code_ that runs in functions.php or in an enabled plugin. Therefore if you can get code to run into functions.php or a plugin in your Wordpress environment, you can do **anything** that you can do in PHP in your web hosting environment, and this includes anything at all in Wordpress. So in your case, once you make your REST API endpoint work, the PHP there can do absolutely anything. You could access the table through the $wpdb object to use Wordpress's database connection and database helper functions. Or you could if you wanted to write your own PHP from scratch using direct mysqli_ calls if you wanted -- this might be advisable if e.g. you would like some of your application logic to be independent from WP.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "rest api" }
cURL error for cron I have this error which causes me a lot of trouble with all of my crons for some of my website : > cURL error 28: connect() timed out! The websites are stored on a shared servers i guess, how can I fix it ? Can't find something to help me on this point anywhere...
This error is most often related to the server configuration! Contact your hosting company and ask the hosting support to check the following points: * The server is running a recent version of PHP and the cURL library. * Increase PHP Memory Limit settings. * Ask your web host if there is some limitation with wp-cron, or if loopback is disabled. * Ask your WebHost if there a firewall or security module (e.g. mod_security ) that could block outgoing cURL requests. * Your hosting company might need to switch DNS configuration to something like OpenDNS.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "server, curl" }
Multilanguage website get the title, on different languages I am working on a website, and I am using Polylang to translate it to a different language. In my code I want to get a page title, and display it. My issue is I cannot get it by ID or page_by_path because its going to display the English version of the page on every language. For example: I want to display the Contact page title on english Contact and on another language its equivalent translated contact page title. Is there a way to do that? The code that I'm using so far: <?php $page = get_page_by_path( 'contact' ); ?> <span><?php echo get_the_title( $page ); ?></span>
In polylang you can use the function `pll_get_post($postID)` to get the id of the translated page like this: `<?php echo get_the_title(pll_get_post(52)); ?>` I'd be glad if you rate my answer if it was useful.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "get the title, plugin polylang" }
get_posts() SQL Injection I'm working on a custom search page and I usually use wpdb->prepare when crafting custom queries. But this time I went with get_posts to create the below query. But I'm wondering if I have to worry about SQL Injection with it. Should I? Or does get_posts() have that security built in? If not, how do I clean the incoming variables? $SEARCH_QUERY = @$_GET['s2']; $args2 = array( 'orderby' => 'date', 'order' => 'DESC', 's' => $SEARCH_QUERY ); $arrSearchResults = get_posts($args2); echo "<pre>"; print_r($arrSearchResults); echo "</pre>";
> If not, how do I clean the incoming variables? In most cases you don't, `get_posts` calls `WP_Query` internally, and `WP_Query` performs some sanitization, namely via `wpdb->prepare`. * * * However, for what you're trying to do, this is the wrong approach. Just use a standard `search.php` template with a standard post loop, and use `input` fields that have the same names as the parameters for `WP_Query`. WP will automatically filter as a result of them being added to the URL. There is no need for a custom page template with a custom query and custom URL parameters. It's just unnecessary complexity, and double the database queries ( don't forget the broken pagination, dealing with 404's, etc )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wpdb, security, get posts" }
Will revisions be retained when converting to a multi-site? Will revisions be retained when converting to a multi-site? We’re looking to convert a WordPress site to a multi-site, and the client we’re working with is very conscious that they don’t want to lose any revisions data. I can’t find anything in the codex about data loss when converting to a multi-site, but is it a possibility that we might lose some of this data when converting the site? Thank you
Revisions are stored as posts in the `*_posts` table(s). This shouldn't be touched during a conversion to Multisite. I just did a quick test on my local machine: * Installed WordPress * Added a couple pages and posts * Revised the pages and posts * Made sure the revisions were stored in the DB * Ran the Multisite conversion from the command line (`wp core multisite-convert`) * Checked to make sure the revisions were still stored in the DB It appears that the conversion did not affect the revisions at all. However, note that _your mileage may vary_. I'd recommend doing a full database backup before running the conversion to Multisite. (I'd recommend doing that in any event, of course.)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, revisions" }
WP is redirecting instead of going to 404 Why is wordpress redirecting to an existing page if the uri is staring like an existing page instead of redirecting to a 404 ? Example, i have theses pages > mysite.com/aeroport > > mysite.com/intralog But if I go to > mysite.com/aeroport/intra Instead of going to a 404, WP is redirecting me to the translated english version of intralog > mysite.com/en/intralog Same if I do **mysite.com/aeroport/medi** , it's redirecting me to **mysite.com/medias** instead of a 404 I'm using polylang, I can't disable it, but all my other plugin are disabled.
Does this WPSE article help? Looking at this article and similar, I'd recommend reading up on the purpose of this feature as you _may_ not want to (fully) disable it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "404 error" }