INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Unable to set font colour I'm unable to set the font colour on hyperlinks in my blog posts. I'm runnung WordPress 6.0 running Twenty Fifteen theme. Can anyone let me know if I have to add code to make the hyperlinks blue, or any other colour. No matter what I do, or the colour option I select in the colour-picker, the hyperlinks remain black. Any help would be welcomed as I'm looking to migrate to a newer WordPress theme. ![Unable to set font colour](
You are setting the color of the paragraph the link resides in, but in `style.css` (that is part of the theme you are using) there is a rule targeting all `<a>` elements that is more specific targeting and is overriding the color you are trying to set at the `<p>` level. You can try customizing the theme by adding additional CSS rules to override the hyperlink color. I would not edit `style.css` in the event the theme gets updated and overwrites any changes you make.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "color picker, fonts, theme twenty fifteen" }
How to use the wpsnonce clone post link? I have this link from a CPT, to clone a post, in this case `post=30808`: ` Now, I need to use this within a jquery script like this: $('body.post-type-pessoas .page-title-action').replaceWith( '<a href=" class="page-title-action">Clonar Modelo PESSOA</a>' ); }); (this will replace the "New Post" button with "Clonar Modelo PESSOA" with the same link) The thing is that after several days the link won't work because of the wpsnonce lifetime. I don't want to remove the wpsnonce lifetime due to security issues. My question is how do I get the correct and actualized link? Thank you. AMP.
One option is to use `wp_add_inline_script()` to inline the action url to the page source. This can be done for example on the `admin_enqueue_scripts` action. In the example below I used `admin_url()` with `wp_nonce_url()` to retrieve the nonce wp-admin url and then added the query paramters to it with `add_query_arg()`. add_action( 'admin_enqueue_scripts', 'my_admin_action_url', 5 ); function my_admin_action_url() { $actionUrl = add_query_arg([ 'action' => 'duplicate_post_clone', 'post' => 30808, ], wp_nonce_url( admin_url('admin.php'), 'action' )); wp_add_inline_script( 'jquery', "var myAdminActionUrl = '{$actionUrl}';" ); } The url should be now available in your script via the `myAdminActionUrl` variable.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, jquery, links, nonce" }
Child categories doesn't echo if it doesn't contain at least a post I'm looping though child categories of a given parent, but what I've noticed is that it doesn't get echoed if the child category itself doesn't have any posts in relation to it. How can I echo children even though they don't have any posts? $children = get_categories( array( 'parent' => 923) ); foreach ($children as $child) { echo "<h6>Child: " . $child->name . "</h6>"; }
By default, `get_categories()` won't return terms that have no posts (the `hide_empty` parameter is true). This should do it: $children = get_categories( array( 'parent' => 923, 'hide_empty' => false, ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
Sort downloads by most recently purchased first in my account WooCommerce Currently my-downloads.php shows the customer the oldest files first. It would be really nice to sort it by their most recent downloads at as on large file download sites, its a lot of scrolling and annoys some of our customers. Thank you for guiding me how to do this?
You should be able to use the `woocommerce_customer_get_downloadable_products` filter and return the array of downloads in reversed order. function reverse_my_downloads_order( $downloads ) { return array_reverse( $downloads ); } add_filter( 'woocommerce_customer_get_downloadable_products', 'reverse_my_downloads_order' ); Add this code to your functions.php file of your active child-theme or theme. I didn't test it, but it should work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to override theme class function to child theme? File: `wp-content\themes\theme-t\includes\classes\ClassX.php` class ClassX extends Base { public function some_logic() {} } I want to change the logic of `some_logic()` via child theme, how it is possible?
Based on the information provided? You can't, it's not possible. Child themes can only override code from parent themes if the parent theme explicitly provides a way for child themes to do so. They can do this by providing a hook, or by making functions 'pluggable', but class methods can't be pluggable.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, child theme" }
Upload non-featured image to image field I'm trying to upload some associated media to a custom post type. Using `file_put_contents()` I'm uploading an image and trying to set an ACF image field to be the path to that file. But reading the documentation I apparently need to supply an `attachment_id` as part of the `update_field` parameters. However, if I insert the image with `wp_insert_attachment` (to get an attachment id) it's going to be set as the featured image, will it not? How can I get an attachment_id without overriding the pre-existing featured image?
You should read up on the `wp_insert_attachment` function. You can check it out here < It does not automatically set the image as a featured image. For that you would need `set_post_thumbnail`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, images, advanced custom fields" }
Catching Gutenberg sidebar switch event I'm working on a plugin with Gutenberg integration. I registered a plugin in React, and my sidebar is showing and working fine. But I need to perform an action each time my sidebar is showing up. I noticed that functions Render, componentDidUpdate, componentDidMount are not called when I switch the sidebar (for example I open Rank Math sidebar, and then I return to my sidebar). So using those are not good for me. I'm looking for some kind of event listener that will be executed when I reopen my sidebar. I'm new to React, so I'm not sure if I can use useState hook in some way to do this? Furthermore, I also field at looking for any built-in events in Gutenberg in documentation, so not sure if there is any ready solution.
For everyone who is looking for a solution: The issue was that I wanted to use React. Component as I was sure it is required by WordPress. But Functional Component is also accepted, and in this case instead of componentDidMount you can use useEffect hook, which is executed each time sidebar is loaded and do the job perfectly.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, block editor, events" }
Add query args if website open in mobile how do I add a custom query in the URL if my website open in mobile? for example, if open on desktop show: < I want in mobile URL like < I want to add "?mode=app" only if in mobile
Jquery can solve this problem - can you try this. jQuery(document).load(jQuery(window).bind("resize", checkPosition)); function checkPosition() { if (window.matchMedia('(max-width: 767px)').matches) { window.location.replace(" } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, url rewriting, query" }
How does Wordpress decides how many sizes of an image to create? Once an image is uploaded to WordPress server, how does it decides how many sizes to create for the same image? I can see for one image, it didn't create any variants, but for a bigger image, it created 6 different image sizes. Just need to know beforehand how many variants/sizes will be created for an image.
Well it really depends on how many image sizes are defined through themes, plugins, settings and the WordPress itself. Some of which you can see in the media section in WordPress settings in admin panel. One thing you can do is to install a plugin like [AJAX Thumbnail Rebuild] and go to it's page in Tools section of WordPress dashboard and see how many image sizes you have. also in this page people offered pieces of code that can generate a list of image sizes for you. Note: if you have a small picture, WordPress doesn't usually try to make it bigger than its original size. So it make sense to not have bigger sizes of a small image. For example if my image is 300x400px, WordPress isn't gonna make a different version of it when it needs a 650x820px picture somewhere. It just uses the biggest, closest possible variant.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "uploads, media, attachments" }
Add post's category as a meta tag to the post For tracking purposes, I need to add a meta tag to each blog post with the post category it's in. The meta tag would need to look like this: <meta name="category" content="politics"> I'm not too familiar with .PHP, but is there a specific snippet I can add to functions.php that would accomplish this? Thank you
You can use the below snippet to achieve the result. add_action( 'wp_head', 'so_407790_add_meta_tags_to_post' ); /** * Add category meta tags to post. */ function so_407790_add_meta_tags_to_post() { // Get the current page categories. $categories = get_the_category(); if ( ! $categories ) { return; } // Category slug into list with comma separated. $category_list = implode( ',', wp_list_pluck( $categories, 'slug' ) ); // Add meta tags to the head. echo '<meta name="category" content="' . esc_attr( $category_list ) . '" />'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post meta" }
can i have shopping carts without plugin? can I have a shopping cart in word press without plugins? and if yes how ? hard code or there is some easy way? I don't trust plugins these days . but if you guys know any trusted plugin for a shopping cart please let me know, I have tried so many hard code options but all have some problem
You can certainly code your own shopping cart - but ultimately that code should live inside a custom plugin (or plugin functionality housed in a custom theme). So the short answer is "no" \- one way or another you need to write or use a plugin. Please note that plugin recommendations are off-topic on this stack. But WooCommerce is now an Automattic property - it is developed and supported by corporate stewards of WordPress. It's fairly robust, but if you have been coding your own cart you may find that it is too heavy for your needs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "e commerce" }
get_post_types - exclude multiple post types by name I am trying to get an array of all the post types except for `attachments` and `pages`. I've been able to do this with one exclusion like this: get_post_types( array( 'name' => 'page', 'public' => false ), 'names', 'not') ); This returns all post types except for `page` as expected. However, I can't seem to get it to work if I try to exclude multiple `names`. I figured I could just pass in an array like this: get_post_types( array( 'name' => array('page','attachment'), 'public' => false ), 'names', 'not') ); But this doesn't exclude either of the post types I am trying to exclude. Any ideas?
The query args you're passing to `get_post_types()` are handled by the underlying function `wp_filter_object_list()`, which isn't designed to handle advanced querying operations like "if key value (not) in array". Since you're just getting the names of post types, use the native PHP function `array_diff` to filter the out the ones you don't want: $post_types = array_diff( get_post_types(), [ 'page', 'attachment' ] ); FWIW, if you were getting post type _objects_ , you could use `array_filter` with something like: $post_type_objects = array_filter( get_post_types( [], 'objects' ), function ( $post_type_object ) { return ! in_array( $post_type_object->name, [ 'page', 'attachment' ] ); });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, post type" }
WordPress cron creation during plugin installation results with initial execution I'm currently developing a plugin which uses WP cron. During the installation of the plugin, I'm creating 2 needed cron jobs with a timestamp of midnight -2 and a and midnight -1 hour, since job 2 should only run 1 hour after job 1. Even when using a timestamp during creation which is 3-4 hours in the future, it seems like that both functions are getting initially executed directly after the plugin install / update, which results in a lot of issues. wp_schedule_event( strtotime( 'midnight' ) + ( - 2 * HOUR_IN_SECONDS ), 'daily', 'test1' ); wp_schedule_event( strtotime( 'midnight' ) + ( - 1 * HOUR_IN_SECONDS ), 'daily', 'test2' ); Any idea how to prevent an initial execution of each event during creation?
`strtotime( 'midnight' )` will give you midnight _for today_ , which has already happened! You want midnight _for tomorrow_. e.g. `date( 'F jS H:i:s', strtotime( 'midnight' ) )` on July 19th is `July 19th 00:00:00` However, `date( 'F jS H:i:s', strtotime( 'tomorrow midnight' ) )` would be `July 20th 00:00:00` ...which is what you want! So just use `tomorrow midnight` instead.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp cron" }
What is the purpose of a companion plugin I have run into several themes, that clients have chosen, that have "companion plugins." These plugins have to be installed as a separate step after the theme is installed. What is the purpose/benefit of having this type of plugin, instead of just adding the functionality to the theme?
If you put your functionality in a plugin then it can be reused across many themes. E.g. a plugin that adds font options to the customizer would be useful for lots of themes, but if it was directly built into every single theme and you needed to make a change, you would have to release updates for every single theme, then make sure there were no version differences and they were all kept up to date. That isn't an issue with a plugin. Additionally, themes aren't intended to host functionality such as post types etc, only templates and visuals. Almost all themes break this advice though, but it's still useful. E.g functionality built into a theme locks you into that theme and is lost when you switch.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, theme development" }
Is the information returned by get_bloginfo( 'version' ) always the same as the one in version.php? In the WordPress Core, I see some cases doing: $wp_version = get_bloginfo( 'version' ); And other cases doing: // include an unmodified $wp_version include( ABSPATH . WPINC . '/version.php' ); That comment about `including an unmodified $wp_version` makes me wonder what could make the first case return a different value than the second one. Why would they be different?
Mostly it is the same, but sometimes its not. The edge case is when a core upgrade is being done. At that point the version in memory is going to be of the "old" version while the file version might be (depending where you are in the upgrade process) the new one. This is a very remote edge case and as maintenance mode kicks in when upgrade is done it is very unlikely that a plugin or theme will run in to it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "core" }
How to render a block from php template forgive me a question that may seem stupid, but has been keeping me busy for hours: I'm trying to insert a gutenberg block into a category php template, but neither the render_block () function nor the do_blocks () function seem to give results. Can anyone help me?
Solved by manually inserting HTML into the template, Thanks.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, templates, block editor" }
Why does adding a dashboard widget in includes/admin.php fail? Does includes/admin.php have special status I don't understand? This is my dash widget code: add_action('wp_dashboard_setup', 'custom_dashboard_widgets'); function custom_dashboard_widgets() { global $wp_meta_boxes; error_log("I love testing!"); wp_add_dashboard_widget('test_dash', 'Test Dash', 'test_dash'); } function test_dash(){ echo "Test"; } ?> If I put that code in `includes/dash.php` it works perfectly. If I put it in `includes/admin.php` nothing happens. Both files are included in the plugin using the same method: require_once('includes/admin.php'); require_once('includes/dash.php');
The problem is here: `require_once('includes/admin.php');` It should be: `require_once(plugin_dir_path( __FILE__ ).'/includes/admin.php');` The original code actually sources a core WordPress file with the same name.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "dashboard" }
Intiger meta value with '>=' returns posts with lower value My post has a custom post meta named **duration**. which has the video duration in seconds. Like, Post 1's duration: 1 Post 2's duration: 56 Post 3's duration: 155 Post 4's duration: 7 Post 5's duration: 2 My args for wp query: Array ( [post_type] => post [posts_per_page] => 45 [paged] => 0 [orderby] => modified [meta_query] => Array ( [0] => Array ( [key] => duration [value] => 30 [compare] => >= ) ) ); The query returns post 2,3,4 but it should return only post 2 and 3. Any idea?
The meta type needs to be set as numeric. 'type' => 'numeric', The full Query: Array ( [post_type] => post [posts_per_page] => 45 [paged] => 0 [orderby] => modified [meta_query] => Array ( [0] => Array ( [key] => duration [value] => 30 [type] => 'numeric'; [compare] => >= ) ) );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp query, custom field" }
When is the wp-mail.php in the WP root requested? I see there is this _wp-mail.php_ file which seems to be a feature to open a mailbox via pop3 and grab a post to publish it. But I wonder, when is this file being executed? It seems to not be used anymore.
> But I wonder, when is this file being executed? It seems to not be used anymore. The old Codex info here: < mentions this being **deprecated** and recommends using plugins instead. It seems to be the user's own responsibility to run `wp-mail.php` to fetch posts from the mailbox, either via hook, calling the file manually via browser or via a cron job. See the Codex link above for code examples. This seems like a very slow deprecation as it still ships with WordPress core: < The ticket to remove it is here: < and the old dev blogs here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "core" }
Difference between get_site_transient() and get_transient() I'm reading through the WordPress core and noticed that the _update_core_ transient is fetched with `get_site_transient()`. What is the difference between `get_site_transient()` and `get_transient()`? If I had seen this somewhere else, I'd have thought: " _well... this is to get a transient for a specific site in multisite._ " But if this is used for _update_core_ , that thought does not make sense, since the core is one ond only one, even in a multisite. Did I read the official documentation? Of course, but it doesn't really clarify it.
`get_site_transient()` uses the older nomenclature for multisite which referred to a multisite network as a "site" and individual sites on the network as "blogs". So `get_site_transient()` is getting the value of a transient for the whole network, while `get_transient()` gets a transient for an individual site/blog. If you look at the source of the function you'll see that it uses `get_site_option()` internally, and the documentation for that function reads (emphasis mine): > Retrieve an option value for **the current network** based on name of option. Also note that `get_site_option()` has been effectively replaced with `get_network_option()`, but for some reason the same change hasn't been made for the transient function.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "transient" }
Sort WP Search results by date I know we can easily sort WP search results by appending **& orderby=post_date&order=desc** to the search URL like this: ` How do I implement this natively to search form code I am using: `<form method="get" action=" id="sv2"><input name="s" id="s" size="30" title="Search example.com" type="search" placeholder="Search example.com"></form>` Pls help! Perhaps a code for functions.php is required.
@KA.MVP You can create hidden fields for 'orderby' and 'order' with default values 'post_date' and 'desc' or 'asc' in it, you can also put this form inside add_shortcode function explained below and use wherever you want to use by adding shortcode [custom_search_form] function search_form_func() { ?> <form method="get" action=" id="sv2"> <input name="s" id="s" size="30" title="Search example.com" type="search" placeholder="Search example.com"> <input type="hidden" name="orderby" value="post_date"> <input type="hidden" name="order" value="desc"> <input type="submit" name="submit" value="Search"> </form> <?php } add_shortcode('custom_search_form','search_form_func');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "search" }
How to get saved elementor template list programmatically? I want to get the saved elementor template list (from this location wp-admin/edit.php?post_type=elementor_library&tabs_group=library) programmatically and display its name as dropdown select menu. How to do that?
Found my own answer. To get the elementor template list you can use this snippets code $args = array( 'post_type' => 'elementor_library', 'posts_per_page' => 30, 'tabs_group' => 'library', 'elementor_library_type' => 'page', ); $elementor_templates = get_posts($args); Now, to display it as dropdown select element, you can iterate through `elementor_templates` foreach ($elementor_templates as $elementor_template) { echo $elementor_template->post_title; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
Block user roles from accessing the WordPress dashboard I want to block multiple user roles from accessing the WordPress dashboard, I have a custom role, and I want to block it along with other roles, but I don't know how to edit the code. the code below has one role (shopkeeper) I want to add more roles how can I do that? function wpse66094_no_admin_access() { $redirect = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : home_url( '/' ); global $current_user; $user_roles = $current_user->roles; $user_role = array_shift($user_roles); if($user_role === 'shopkeeper'){ exit( wp_redirect( $redirect ) ); } } add_action( 'admin_init', 'wpse66094_no_admin_access', 100 );
You can make an array of the roles that need to be blocked, and use `array_intersect()` to check if the current user is in any of those roles. function wpse66094_no_admin_access() { $redirect = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : home_url( '/' ); global $current_user; $blocked_roles = array( 'shopkeeper', 'block-this-role', 'block-this-role-too' ); $user_roles = $current_user->roles; // If the user is in any of the blocked roles, redirect 'em. if ( ! empty( array_intersect( $user_roles, $blocked_roles ) ) ) { wp_safe_redirect( $redirect ); exit; } } add_action( 'admin_init', 'wpse66094_no_admin_access', 100 ); Thanks to @Cornell Raiu in the comments for correcting the `wp_redirect()` / `exit` code, and @TomJNowell for recommending `wp_safe_redirect()`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "user roles, dashboard" }
WP Still Generating 150x150 Thumbnail Size Even After Un-Setting Small Size in Functions.php I am using following code to prevent WordPress from creating some un required image sizes for my theme and only upload the original size add_filter( 'intermediate_image_sizes_advanced', 'prefix_remove_default_images' ); function prefix_remove_default_images( $sizes ) { unset( $sizes['small']); // 150px unset( $sizes['medium']); // 300px unset( $sizes['large']); // 1024px unset( $sizes['medium_large']); // 768px return $sizes; } The code is somehow working and I am able to upload the original size but as you can see WordPress still generating `150x150` size images ![enter image description here]( As you can see I explicitly added `unset( $sizes['small']);` to the code, but this is still happening! Can you please let me know what I am missing here?
That's because there is no image size called `small` in WordPress. It's possible your theme registered it but the thumbnail size WordPress uses internally at 150x150 is named `thumbnail` not `small`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, theme development, images, post thumbnails" }
Custom Post type collection If you've set up custom types and given them a custom slug through `register_post_type` 'rewrite' => array( 'slug' => "shoes" ) Can you assign a template for `/shoes/`? At the moment all custom types are just nested inside of a url path that's dead if you navigate to it without the specific item at the end `/shoes/specific_shoe` -> custom post `/shoes/` -> index.php
Do you have `has_archive` set to `true` in you `register_post_type` function? If so, you can use `archive-shoes.php` as your archive template. For more information about registering custom post types, please check < **EDIT** To load a custom archive template (without having to use the default WP template naming conventions), you can use the `archive_template` hook to set your own. add_filter( 'archive_template', 'my_shoes_archive_template' ); function my_shoes_archive_template($archive_template) { global $post; if ( is_post_type_archive ('shoes') ) { $archive_template = dirname(__FILE__) . '/my-file-name.php'; } return $archive_template; } Check out < for more information on this.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
What is the purpose of the "term_id" column in the "wp_term_taxonomy" table? The table below shows some example rows from a "wp_term_taxonomy" database table. Notice that values of the "term_taxonomy_id" and "term_id" columns are exactly the same. What is the use of the "term_id" column if it has the same value as the "term_taxonomy_id" column? ![Example of rows in the wp_term_taxonomy table]( In what cases will the value of the "term_taxonomy_id" and "term_id" columns differ? Can a given term belong to more than one taxonomy? If so, could you give a concrete example where this is useful? WordPress version: 6.0.1
In versions of WordPress prior to 4.2 terms could belong to multiple taxonomies. This is no longer the case and in WordPress 4.2 or newer new terms cannot belong to multiple taxonomies and any existing terms that belong to multiple taxonomies are split into multiple terms whenever they are updated. You can read this post for an introduction to the change from before it was made: < There is also this article which describes the splitting process: < So unless you are dealing with pre-4.2 data the values of these columns should always be the same.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, taxonomy, terms" }
Strange "lea" prefix on wp-json I've been using wp-json steadily for a couple years now on a headless CMS project and had no problem getting valid JSON back. I set the website to auto-update all themes, plugins, and WP version. I also added some extra plugins to enhance the wp-json: * WP Rest Api V2 Multiple PostTypes * REST API Helper * Custom Post Types Today, we started getting invalid JSON back with an "lea" prefix string on the beginning of the JSON for some unknown reason, creating invalid JSON. When I remove this "lea" prefix at the beginning of the JSON, the website works normal again. Where might I look to see where this "lea" is being added?
I found it. There's a bug in the TotalPress.org Custom Post Types plugin in the file: wp-content/plugins/custom-post-types/custom-post-types.php At the top of the file, you will see the mistake: lea<?php When I remove the `lea`, the problem goes away. I'm contacting the plugin developer to let them know. Plugin version was 3.0.12.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "json" }
How to execute a hook asynchronously? I have a function to send user data to a google sheet whenever the user's profile gets updated: add_action('profile_update','send_user_data_to_google_sheet') function send_user_data_to_google_sheet(){ ... } It works well except that I can feel that it apparently takes longer when users update their profiles because it has to wait for the data to be sent. Is there a way to execute the hook asynchronously so it won't affect user's experience?
Yes, that's what the WP Cron system does. It will fire an action/hook as close to a requested time as it can, and can do it once or multiple times. You would still have a hook that runs on `profile_update` but it wouldn't send data to google spreadsheets, rather it would schedule a cron job that executes an action, and you would send that data on that action. Note though that you will need to check if the cron job has been scheduled already or not to avoid duplication, and you will need to give it everything it needs to do its job as it will not be the same request ( any variables/GET/POST/FILES/etc will not be accessible, new request, blanks slate ). For information and examples of WP Cron, refer to the official plugin handbook on the WP developers site
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "hooks" }
Can't find image to remove I noticed when debugging my first ever Wordpress site that I was getting an error > Access to image at ' from origin ' has been blocked by CORS policy So this image appears to be left over from the default theme but the thing is I can't find it. I am using Elementor to edit. Doing a search of the raw HTML I found the reference in a huge block of code which is bounded by `<style id="astra-theme-css-inline-css">` Here is the relevant code snippet .site-primary-footer-wrap{padding-top:45px;padding-bottom:45px;}.site-primary-footer-wrap[data-section="section-primary-footer-builder"]{background-image:linear-gradient(to right,#101218,#101218),url( center;background-size:cover;background-attachment:fixed;border-style:solid;border-width:0px;border-top-width:1px;border-top-color:#e6e6e6;} So I believe the image is somewhere in the footer but I can't find it to delete it. My question is how can I fix this annoying error?
Unfortunately for those that might come across this in the future I am not sure if this solution will help you. As I worked out the offending image was in the footer. I ended up just clicking on various options in CUSTOMISE>>FOOTER BUILDER and then I selected the PRIMARY FOOTER and found BACKGROUND which has options of COLOR/ GRADIENT/ IMAGE and when I selected IMAGE there was a broken image link icon and the option to "Remove Image". So difficult to find but fixed now.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, errors, footer" }
How can I redirect a request to the site root using htaccess, if there's not a specific cookie set? I'm using this code, versions of which I've seen referenced on various other sites, but it always redirects home page requests to /fr/ if the browser is set with French as a primary language preference. I only want to redirect root domain requests (/) if the cookie “language_known” isn't set to the value “yes”. Does anyone have any ideas, please? <IfModule mod_rewrite.c> # Redirect if French browser RewriteCond %{HTTP_COOKIE} !language_known=true;? [NC] RewriteCond %{HTTP:Accept-Language} ^fr [NC] RewriteRule ^$ /fr/ [L,R=301] </IfModule>
> if the cookie “language_known” isn't set to the value “yes”. > > > RewriteCond %{HTTP_COOKIE} !language_known=true;? [NC] > The _condition_ is checking that the value is not "true" (string), not "yes"? However, the rule is also configured as a 301 (permanent) redirect, so this will be cached persistently by the browser. If the browser has redirected once, when the cookie was not set then it will _always_ be redirected, even when the cookie is later set (since the request never reaches the server to perform the check). This _needs_ to be a 302 (temporary) redirect so the browser does not cache the redirect (by default). And the browser (and any intermediary) cache needs to be cleared before this can be tested.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "redirect, htaccess, language" }
Warning: Attempt to read property "term_id" on int - Woocommerce I would like to create a condition to manually hide product categories within the shop. I already started from a code base but I am trying to understand why if I put the `is_product_category()` condition the error comes out as I specified in the question with PHP Version 8.0 This is the code: add_filter( 'get_terms', 'sct_hide_cat', 10, 3 ); function sct_hide_cat( $terms, $taxonomies, $args ) { //global $product; $exclude = [50, 22, 20, 31, 35, 45, 40, 65, 37, 40, 3434]; $new_terms = []; if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_shop() || is_product_category() ) { foreach ( $terms as $key => $term ) { if ( ! in_array( $term->term_id, $exclude ) ) { $new_terms[] = $term; } } $terms = $new_terms; } return $terms; }
You can I think you should use `get_terms_args` filter instead of `get_terms` and just add exclude arg, so now get_terms() function won't retrieve those cats and you'll get right count. Here's code example: add_filter( 'get_terms_args', 'mamaduka_edit_get_terms_args', 10, 2 ); /** * Exclude product categories from Woocommerce * */ function mamaduka_edit_get_terms_args( $args, $taxonomies ) { //print_r($taxonomies); if ( is_admin() && 'product_cat' !== $taxonomies ) return $args; $args['exclude'] = [50, 22, 20, 31, 35, 45, 40, 65, 37, 40, 3434]; // Array of cat ids you want to exclude return $args; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, woocommerce offtopic" }
Getting false for is_home() on Posts page I've made a child theme of Twenty Twenty theme and want to display the posts/ category archive pages in flexbox grid. However, none of the conditional tags I'm hoping to check outside the loop (is_home, is_archive, is_category) are returning true on posts page or category archive pages: * @since Twenty Twenty 1.0 */ get_header(); ?> <?php if ( is_archive() ): ?> <h1>ARCHIVE</h1> <?php endif; ?> <?php if ( is_category() ): ?> <h1>CATEGORY</h1> <?php endif; ?> <?php if ( is_home() ): ?> <h1>HOME</h1> <?php endif; ?> <main id="site-content maybe-flex-directive-class-here"> <?php if ( have_posts() ) { while ( have_posts() ) { the_post(); I expect either I'm missing something obvious or going about it the wrong way.
I was going to (and actually did) delete this post, but after sleeping on it, think it might end up being of some use. What I was missing, above, is [Template Hierarchy][1]. I was looking at the `singular.php` template file, which will _only_ ever be loaded when `is_archive()`, `is_home()`, etc, aren't true. What got me is that the HTML `<main>` element exists on both the `index.php` and `singular.php` documents in this theme. So I was able to update the child theme's copy of `index.php`: <main id="site-content" class="flex-container"> With CSS: .flex-container { display: flex; flex-direction: column; } /* Responsive layout - make multi-column on larger screens */ @media (min-width: 800px) { .flex-container { flex-direction: row; } } Thanks for the solution in the comment, @bosco. [1]:
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "conditional tags, conditional content" }
How to add/enqueue Custom CSS for a custom taxonomy page? So this is what I have done for my homepage so I load css that only loads on my homepage function enqueue_frontend_assets(){ if(is_page_template( 'homepage.php')) { wp_enqueue_style( 'homepage', get_template_directory_uri().'/assets/css/homepage.css' ); } } And it works just fine and only loads on the homepage. I am trying to load the exact same file for my custom taxonomy page but it doesn't load. function enqueue_frontend_assets(){ if(is_page_template( 'taxonomy-state.php')) { wp_enqueue_style( 'homepage', get_template_directory_uri().'/assets/css/homepage.css' ); } } What should I use instead to make sure it loads on all the custom taxonomy pages?
Instead of checking against the template, you should use `is_tax()` which is one of the conditional tags in WordPress. So in your function, you just need to use `is_tax( 'state' )` in place of `is_page_template( 'taxonomy-state.php')`, and your asset would only be loaded on the archive page for your custom `state` taxonomy.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, css, taxonomy, wp enqueue style" }
Bulk delete media by year We have large media library with more than 300000 images. We decide to delete all images < 2017 year manually using "FTP", from WP upload folder. But after that in WP Admin > Media > Library, they still "exist" as screenshot - broken media links in library We tried with couple of plugins , but there isn't any with option to bulk delete images by month or year. Is there any way to speed up the process, instead manually deleting it using "filter by year" and "Pagination Number of items per page" show: 999 , where we always get "request timeout".
> We tried with couple of plugins , but there isn't any with option to bulk delete images by month or year. If you have access to wp-cli you can try to delete attachments by **year** and **month** with: wp post delete $(wp post list --post_type='attachment' -—year=2016 -—monthnum=12 --format=ids) or just by **year** with: wp post delete $(wp post list --post_type='attachment' -—year=2016 --format=ids) Remember to **backup** before testing!!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "attachments, media library, bulk, command line" }
Edit text of Wordpress "Register" button On the default WP registration page I want to edit the text of the blue button from "Register" to "Accept and Register". I want to do this without using a plugin, if possible. ![enter image description here](
To change a particular string, you can use the `gettext` hook: /* * Using priority 20 to override the default 10. * If another theme or plugin has a higher number, * you might need to raise this. */ add_filter( 'gettext', 'wpse_change_strings', 20 ); function wpse_change_strings( $translated_text ) { // If this is the specific string to change, update it. if ( 'Register' === $translated_text ) { // Change this to your desired string. $translated_text = 'Updated Call to Action'; } // Always return the text, whether we changed it or not. return $translated_text; } The above is case-sensitive. You could use `strtolower($translated_text)` to compare if you'd like to change the text regardless of capitalization.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, user registration" }
How to solve react dom 'removeChild' on Node error while google translate extension is on and selecting any core block console log error image !error image I also attach video how error occur please see this <
This cannot be fixed from the WordPress side, it requires changes from the Google Translate team to work with WordPress' block editor. **Only Google can do that.** If you need to translate the content of a post it can't be done from inside the editor using a browser extension unless that browser extension was specifically built to work with WordPress.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor, bug" }
See when a tag was first added Does anyone know how to determine the time/data when a tag was added to the site? Is this even kept in the database?
The information is not stored but you may tweak it to fit your need. Refer: How to add a date creation field when a custom taxonomy relationship is created?
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "tags" }
What is the `post-status` icon handle when using `@wordpress/icons`? I'm trying to use the `@wordpress/icons` npm package: npm install @wordpress/icons --save To display the `dashicons-post-status` icon within the block editor: import { Icon, postStatus } from '@wordpress/icons'; <Icon icon={ postStatus } />; **The issue -** As far as I can tell, this icon doesn't exist within the icons package. Either that, or I'm utterly blind and need my eyes tested? Would one of you lovely people be able to confirm what I'm not seeing? I appreciate any help. **Note:** I've also asked this question in the `wordpress.org/gutenberg` repo on Github for more exposure. Link to thread discussion.
So after a little digging and being maybe a little bit oblivious . The correct way to use `dashicons` within WordPress is as follows; import { Dashicon } from "@wordpress/components"; <Dashicon icon="post-status" /> **Note:** This info can be found in the `Developer Resources: Dashicons` docs, but annoyingly it is buried at the bottom of the page. There are no links to this info at the top of the page, so I didn't even know it existed. **Anyways** , here's a direct link to the instructions on how to use `Dashicons` from `@wordpress/components` You'll find the specifics under **Block Usage**.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "icon" }
cURL request to plugin repository fails 403 I am trying to update a file in my plugin by getting the original contents from the wordpress repository via cURL The URL is of the format < \- visiting the URL in a browser shows the code, exactly what I am after. However, the cURL response is <html> <head><title>403 Forbidden</title></head> <body> <center><h1>403 Forbidden</h1></center> <hr><center>nginx</center> </body> </html> It appears grabbing source code this way isn't allowed. `file_get_contents()` doesn't work either. Is there a way to do this that works?
Thanks to the WordPress forums someone answered that this only works via PHP if you set the UserAgent to a browser. $ua = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13'; curl_setopt( $cd, CURLOPT_USERAGENT, $ua);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "curl, svn, plugin repository" }
How do I change the datetime format from ( 'y-m-d' ) to ( 'd m y' ) I have code that finds the date a page was last updated: <?php global $wpdb; $psm_mod_datetime = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_title = 'Current Chapter Volunteer Openings'"); echo("Updated: " . substr($psm_mod_datetime, 0, 10)); ?> which prints **Updated: 2021-09-05** after the page title. I need it to print **Updated: 05 September 2021** How do I change the format for the date?
This doesn't have anything to do with Wordpress, just some PHP code to get what you're after. You need to convert MySQL datetime to Unix time by using: `$timestamp = strtotime($psm_mod_datetime);` Then you output this timestamp in the format you desire by using: `echo "Updated: ".date('d F Y', $timestamp);`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wpdb, date" }
Doesn't set_transient() add multiple rows with the same key? Just like `add_post_meta()` I want to add multiple `transients` with same key with different values and different timeouts, but I see that the `set_transient()` function doesn't do that. Is this possible?
No: each transient will need a unique name. Per the documentation: > If a transient exists, this function will update the transient’s expiration time.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "transient" }
Install wordpress and replace database (from previous site) Hi I had a WordPress installed on a shared hosting server. somehow the entire folder gets deleted and hosting provider cant help with this. I only have backup of the theme. Now I managed to recover database (sql file). I have just installed a new WordPress site. Is there any way I can replace the database with my backup. I only need the posts/categories from previous site. Image I can update later.
in the server if you are using cpanel restore the database there, on Databases » phpmyadmin » choose the correct database » then to the tab import » choose file (enter your mysql backup) and press go ![enter image description here]( ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "get posts" }
$_GET vs get_query_var() Is there is any advantage of using the `get_query_var()` over `$_GET()`? I have tried like this myurl?posts_per_page=2 and the results are totally different echo $_GET['posts_per_page'] // output is 2 echo get_query_var('posts_per_page') //output is 10 I have not added 'posts_per_page' to query var list using action so where does this 10 is coming up from?
`get_query_var()` gets variables from the main instance of `WP_Query`. It's the equivalent of running global $wp_query; $wp_query->get( 'posts_per_page' ); It is not _directly_ related to `$_GET` in any way. However, WordPress has a list of 'public' query variables that will be applied to the main query if they are passed as URL parameters. This is what the `query_vars` is filtering. You can see the list here, as the `$public_query_vars` property of the `WP` class. So when you run `get_query_var('posts_per_page')` you are getting the `posts_per_page` property of the main query. This will typically be the value from _Settings > Reading_. Passing `?posts_per_page=2` is not setting this value because `posts_per_page` is not a _public_ query variable.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugin development, wp query, query variable" }
Why does a super admin on multi site get a rest_user_invalid_id error code when requesting user details through REST? My goal is to (completely) delete users from a multi site installation using the REST API. Using DELETE or GET ends with a rest_user_invalid_id error code even though the user (and its id) exist. `curl --user "superadmin:TOKEN" -X GET The authentification works just fine. What is even more obscure is the fact that for some random users this works. I do not use WordFence or to my knowledge any other security plugin (and I am quite sure about this). What's the API's problem and how do I solve? Any hints are appreciated. Thank you!
Deleting users with the REST API isn't supported for multisite, as seen in the source code: // We don't support delete requests in multisite. if ( is_multisite() ) { return new WP_Error( 'rest_cannot_delete', __( 'The user cannot be deleted.' ), array( 'status' => 501 ) ); } For GET requests the user ID is checked against `is_user_member_of_blog()` for the current site. If the user is a super admin but has not been explicitly added to that site then they will not be returned and you will receive the `rest_user_invalid_id` error.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "users, rest api" }
Remove Unused Menu Locations I added two menus register_nav_menus ( array( 'primary_menu' => esc_html__('Primary Menu', 'sre'), 'footer_menu' => esc_html__('Footer Menu', 'sre'), ) ); But I'm unable to remove the two old ones, `Primary menu` and `Secondary menu` ![enter image description here]( When I use this code, it hides `Primary menu` but when I remove the code, it reappears in the list. add_action( 'after_setup_theme', 'remove_default_menu', 11 ); function remove_default_menu(){ unregister_nav_menu('primary'); }
Seems like you're using a parent theme or a plugin that registers those menu locations. If that's the case then you shouldn't remove your last function. You need to keep the `remove_default_menu` function in your functions file. If you are not using a parent theme or some sort of plugin than that means you are registering those menu locations yourself. If that's the case then you should check your code and remove the lines where you register them.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, menus" }
Display ACF object field data using Elementor Custom Query Hello i'm working on a website using elementor pro + ACF. I have create a custom post type (CPT1) with ACF object field that take another CPT2 as values. I would like to display on my CPT1 page all CPT2 linked. How can I used Custom Query to display this? I tried to write this but still not working add_action('elementor/query/13600', function ($query) { $query->set('post_type', 'CPT1'); $results_posts= get_field('cpt1_field_for_cpt2',$post_id,false); $meta_query[] = [ 'post_in' => $results_posts->ID , ]; $query->set('meta_query', $meta_query); });
The issue can be solved with this code : function my_cpt_query( $query ) { $myPostObjetField= get_field('cpt1_field_for_cpt2',$post_id,false); foreach( $myPostObjetField as $post_field_item_value ) { $ids[] = (int) $post_field_item_value; } $query->set( 'post_type', 'CPT2'); $query->set( 'post__in', $ids); } add_action( 'elementor/query/13600', 'my_cpt_query' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp query, custom field, advanced custom fields, query posts" }
Using `esc_attr( get_block_wrapper_attributes() )`, results in `class=""wp-block-foo""` So, `phpcs` is telling me I need to escape the `get_block_wrapper_attributes();` function. I thought it would be a simple as `esc_attr( get_block_wrapper_attributes() );`, but it would appear not to be the case as the output; `class=""wp-block-foo""` is not valid markup? Is this a bug? or am I missing something? or maybe I've done something wrong... I'm not sure, so I figured I'd ask. Thanks in advance.
Use the `wp_kses_data` function to escape the data. See the official Gutenberg examples repo for an example
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "block editor, escaping" }
How can I add a section with a different background color? I've installed Wordpress on my server and I'm attempting to implement the design I've mocked up in Figma. It's a pretty simple design but it employs different colored sections to break up the content of the page by topic. I was hoping that I could add a block that is a "section" or "area" but I'm not seeing anything like that.
If you're using gutenberg choose a "group" block. You'll be able to set the background to any color you would like. If you want the group to span the width of the page you'll need to set the alignment to "full-width". When you hover over the block itself you'll get a toolbar pop up. Make sure you're on the "group" block! Then look for the alignment icon and choose full width. If you're looking to put content into the group and want it contained, add whichever block you need into the Group.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, block editor, theme twenty twenty two" }
How did WordPress link an empty page at dashboard to an actual php file? ## I set these 2 settings under WordPress dashboard » Reading: * `Homepage` dropdown: set to `home` (an empty wordpress page I created in dashboard). * `Posts page` dropdown: set to `blog` (an empty wordpress page I created in dashboard). ## Which PHP files WordPress is loading: * Accessing ` loads this php file `front-page.php` * Accessing ` loads this php file `index.php` ## My question is: In dashboard reading settings, I only chose empty pages (titled home & blog) but how on earth did WordPress `link` the empty pages to corresponding php files? Even though I didn't use `Template Name` in the php files. Kindly note, I read the `Template Hierarchy`. But I doubt it's related to this.
thats how wordpress template works `front-page.php` is the very first file that wordpress check for the homepage and to be use as a template, if it doesn't exists it checks another file in specific order like `page-slug.php`, `page-id.php`, `page.php` until it reaches index.php the blog/posts page would first check if `home.php` exist and if not it will use `index.php` all the url sturcture would end-up in `index.php` if their template doesn't exist. Creating pages, posts in the back-end only interact with the database, the rendering of those content in user browser are handled by php files in a template heriarchy
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "frontpage, template hierarchy" }
Is there a way to append a trailing slash to get_home_url() and get_permalink( get_option( 'page_for_posts' ) )? Both `get_home_url()` and `get_permalink( get_option( 'page_for_posts' ) )` don't append a trailing slash at the end. Is there a way to append it similar to `home_url( '/' )` other than `get_home_url() . '/'`?
You can use the `trailingslashit` function to make sure your URL's always have a trailing slash. <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "site url, home url" }
Check if plugin is being disabled I have created a wordpress plugin. But when i disable the plugin i must delete a certain file before a user can reactivate the plugin. Is there a function or a way to know when someone disables my plugin Thanks
Sure, there are activation and deactivation hooks. See: < <?php register_deactivation_hook( __FILE__, 'wpse_deactivate_myplugin' ); function wpse_deactivate_myplugin() { // Delete the file and do any other cleanup needed here. }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Prevent FormTokenField component to accept random entries FormTokenField component has suggestions property which provides a list of suggestions when user start typing. But, FormTokenField also accepts any value, if separated by comma, even if it is not defined in the suggestions property. Just like you can add anything to Post Categories and Post Tags field. Is there a way to prevent this? I would like to limit users to be able to only add items from suggestions. Or, if this is not possible with the FormTokenField, is there any other component that could do this - allow users to select multiple items from predefined lists of options?
On a recent project I handled this by just filtering out invalid values in the `onChange` callback: export default () => { const [value, setValue] = useState([]); const suggestions = ['lorem', 'ipsum', 'dolor', 'sit', 'amet']; const onChange = (tokens) => { const value = tokens.filter((t) => suggestions.includes(t)); setValue(value); }; return <FormTokenField onChange={onChange} suggestions={suggestions} value={value} />; };
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "block editor" }
Add custom css class to wp-list-table row for custom post type Is there any way to add a custom css class based on post data in the custom post type admin table? ![wordpress custom class in admin table row](
Finally got a solution. Founded in WordPress Documentation add_filter('post_class', 'set_row_post_class', 10,3); function set_row_post_class($classes, $class, $post_id){ if (!is_admin()) { //make sure we are in the dashboard return $classes; } $screen = get_current_screen(); //verify which page we're on if ('my-custom-type' != $screen->post_type && 'edit' != $screen->base) { return $classes; } //check if some meta field is set $profile_incomplete = get_post_meta($post_id, 'profile_incomplete', true); if ('yes' == $profile_incomplete) { $classes[] = 'profile_incomplete'; //add a custom class to highlight this row in the table } // Return the array return $classes; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "admin" }
Rest api request throttling Couldn't find any information, so here I go. ## Does WordPress have a native request throttling behavior or not? For instance Laravel gives you < ## If not I know how to implement it myself but I'm a little short on time, so I want to make sure I'm not reinventing the wheel here, so if you know any gist, repo, plugins to get me started please let me know. Thanks in advance.
I wasn't sure from the Laravel docs exactly how it works there, but there are a couple of security plugins (at least) that have rate limiting on a per-IP basis: * ShieldPRO * WordFence This may be more useful, however, as it is focused only on rate limiting and isn't a product, and would be more flexible for you: * WP REST Cop That one requires a persistent object cache — if you can't use Memcache or Redis, there's this (which you found): * Docket Cache
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "rest api" }
WordPress GiveWP Plugin showing blank page in none default theme I am using the `GiveWP` plugin with a `U-Design theme`. The donation page shows _preloader_ for short time then turn into a **blank page** : I.E. In this page: < I noticed in Googe Chrome's Browser that there are 11 elements with 'Slow network detected' and jQuery-Migrate-3.3.2 is sometimes loaded sometimes 2 times! Could this be the problem why the donation page is turned, Blank? When I deactivate the `U-Desing theme` and Activate the `2022 theme` it works perfectly. ![enter image description here]( **Update:** PHP version is 8.0.1 and Error Reporting is enabled in PHP.INI but I don't see any error. Please advice.
In the iframe that has the Give form, there's this line, repeated twice: <style id="alpha-critical-css">body{opacity: 0;}</style> All you need to do is to remove it for it to work. Does that ring any bells? If it's hard to figure out, you could try searching the codebase and see where `alpha-critical-css` is coming from. By the way, I found this just by deleting sections of the CSS in the browser inspector until it was fixed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, jquery" }
how to get the url of a custom uploaded file For a custom function I need to generate a file, upload it to the upload folder and also access the upload file afterwards to attach the file to an email. For uploading the file I use the wp_upload_bits function. But how do I get the upload url so I can attach the file to an email afterwards? Or should I use the wp_handle_sideload function? Thanks in advance!
`wp_upload_bits` will return an array with info about the URL, as mentioned in the documentation for it. So it would look something like this: $results = wp_upload_bits( ... ); $url = $results['url'];
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, uploads" }
Bullet List Indentation not showing up in the wordpress In wordpress, I have written on article and in that I have bullet list to showcase but my indentation is greyed out, and not able to indent the list further as you can see in the sreenshots. I want to move bullet list **Need** and **Cost** **Further** but not able to do that and hence they are looking as if they are not part of my heading. ![enter image description here]( **Below is the consequence of no indentation.** ![enter image description here](
One simple way to address this, if you only have access to the block editor, would be to click on the three dots, edit the block as HTML and add something like this: <li style="margin-left: 60px"> (Change the value to suit.) It may not show in the block editor, but will when you load the page. To handle this site-wide using CSS, you could use the Simple Custom CSS and JS plugin for example, and add a rule like this: li { margin-left: 60px; } ... but that would have to be customized to your site to work properly since you probably don't want to affect ALL list items.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, editor, visual editor" }
Alternative to Underscore.me for gen custom blank theme I see that the website underscore.me is no longer available for generating Wordpress theme templates. Is there an alternative to underscore.me for Wordpress theme generation? Best regards!
I think you just have the wrong URL. You want: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "themes, web services" }
Override the default password length when creating or updating a user profile I may be missing something. My understanding is `wp_generate_password` is pluggable. When I run the function below, it doesn't change the password length in the display when adding a new user or modifying a current user. function wp_password() { // Modify the args supplied to wp_generate_password $args = array( 'length' => '100', 'special_chars' => true, 'extra_special_chars' => false, ); wp_generate_password ($args); } apply_filters( 'wp_generate_password', 'wp_password' );
"Pluggable" means that you actually replace the complete function with your own of the same name, e.g. you call it `wp_generate_password` and have it do the same thing as the original function, with whatever modifications you want. I don't see a filter for modifying the args in the way you are describing, but you can modify the output if you want, using `random_password`. It might help to see the source code here to get a deeper understanding of what is going on. Hope that helps!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "password" }
How to replace plugin icon? Could be a silly question, sorry for this but is my first wordpress plugin. I would like to change the icon that appears in the update page: ![enter image description here]( How to do this? Unfortunately I cannot find anything in the doc.
According to the plugin directory assets page in the Plugin Handbook, create one or more of the following, relative to your plugin root directory: * `assets/icon-128x128.(png|jpg)` * `assets/icon-256x256.(png|jpg)` * `assets/icon.svg`
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "plugin development, icon" }
Check if specific role exists I'm trying to write a function that checks if a specific role exists. I found the following code on the web but it doesn't work for me: function role_exists( $role ) { if ( ! empty( $role ) ) { return $GLOBALS['wp_roles']->is_role( $role ); } return false; } I get the following error message: Fatal error: Uncaught Error: Call to a member function is_role() on null in C:\xampp... I tried to output `$GLOBALS['wp_roles']` with a `print_r` but it's empty. What am I missing? Thanks
This is based on Bosco's comment. You can do this instead of line 3 in the above code: wp_roles()->is_role( 'editor' ); That grabs a `WP_Roles` object (what the code you had tries to do by getting a global variable) and calls the same `is_role()` function.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "user roles" }
How to create a job post by email parsing? I want to develop a job board in wordpress in which job posts will be created from email parsing automatically. With zapier or Postie plugins we can create only blog posts by email parsing. How to create a job post by email parsing? Please help me to solve this issue.
This seems doable thanks to Postie ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "custom post types, posts, customization, email, parse" }
FormTokenField passing objects to value property In the documentation it is noted that value property can be "...an array of strings or objects to display as tokens in the field. If objects are present in the array, they must have a property of value." And there is an example of how these objects should look like. However, when I copy the exact same object, remove the unnecessary properties, and pass it as initial FormTokenField value, "title" property is ignored. For example: const initial = [ { value: '29654', title: 'Post Title' } ]; const [ selectedContinents, setSelectedContinents ] = useState( initial ); When using the code above, I would expect to get the "Post Title" in the FormTokenField on page reload, but I still get "29654". What I need to do is to save and read both post title and ID, but to show only the post title in the FormTokenField.
In short, the "title" which the documentation refers to is a `title` attribute on the `<span>` which is rendered for the token, which is to say that the token { value: '29654', title: 'Post Title' } will (rhetorically) render as <span title="Post Title">29654</span> In order to display "Post Title" as the inner text in the span, it must be used as the `value` of the token - or the value must be transformed into a post name via a callback passed to the `displayTransform` prop. However, the callbacks passed in to the `displayTransform` prop only receives the token `value` string as an argument - so you will still require some form of external data management or mapping in order to work with more complex values. `<FormTokenField>` simply won't maintain state for any sort of complex values on it's own.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "block editor" }
Cannot update plugin I've implemented this class for update my plugin, I've followed this tutorial. I tested the update in localhost using XAMPP and everything works well, but unfortunately when I test on a live site I get a weird situation that doesn't allow me to update the plugin. Essentially, I can see the update notification in the panel, when I update the plugin seems that everything was done correctly but for some reason in the `plugins` folder I get this: ![enter image description here]( As you can see the plugin folder has been replaced with a temporary one, within `get-IO5hpY` there are the updated plugins file. So here the question: Why wordpress replace my plugin folder name which is `my-plugin` with `get-IO5HpY`?
Your 'uploaded-plugin'.zip must contain all your plugin files in subdirectory named as your plugin subdirectory (in example "my-plugin").
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, updates, automatic updates" }
How can I display custom snippet codes in the front end of my WordPress site I have a Wordpress website and I want it to display raw snippet codes on the front end but it keeps showing the output. This is what I need to show on the front end ![enter image description here]( I have used several plugins like a module within Elementor Pro ... highlighter, etc,HTML Editor, Syntax Highlighter, Insert HTML Snippet, PHP Code Widget, Raw HTML Snippets, SyntaxHighlighter Evolved, SyntaxHighlighter Evolved: VHDL Brush How do I get this done?
If you are using Gutenberg: 1. In your WordPress dashboard, click Posts or Pages. 2. Select Add New or hover over an existing post or page and select Edit. 3. Place your cursor where you want to display the code. 4. Click the Add Block icon (the plus sign) and search for "code". Select the code block when it appears. If you are using the Classic Editor Display code snippets by using the preformatted text option. 1. Open the post where you want to include the code using the classic editor. 2. Enter your code in a text box 3. Highlight the code snippet and choose the preformatted text option from the dropdown. Edit: Gutenberg Example: <ul id=”mylist”> <li id=”list-item3″>text 3</li> <li id=”list-item4″>text 4</li> <li id=”list-item2″>text 2</li> <li id=”list-item1″>text 1</li> </ul> Screenshots showing results here:
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
How to get parameters with add_filter with a static method? I use this add_filters to append some links to each comment: add_filter('comment_text', array($this, 'printModerateLinks')); How do I pass the other attributes in this static method to my method "printModerateLinks"? I need the comments object in "printModerateLinks". Thank you =)
First, consult the documentation or source code to see how many arguments are passed to the filter. We can see it has 3 in total, and the comments object is the second one, so you'll need to have at least two. Next, you'll want to declare the number of arguments to pass to the function you're hooking on, which is the 4th parameter of `add_action`/`add_filter` add_filter( 'comment_text', array( $this, 'printModerateLinks' ), 10, 3 ); Lastly, make sure you add the parameters to your method that's being hooked on. public function printModerateLinks( $comment_text, $comment, $args ) { Now you can access the comment object with the `$comment` variable.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "oop" }
Can I upload my HTML/CSS/Javascript game onto a Wordpress page? I've written a basketball simulator game in plain HTML/CSS/Javascript. I also have a Wordpress site. Can I upload my game, so my visitors can play it? I know that if I had written my website from scratch, this would be easy. So, how can I wrestle WordPress into letting me upload my simple game?
What you want is a page template. It has a PHP comment that tells WordPress its name as a template. The page doesn't have to have any PHP code, and you can fill it with your HTML instead, which can link to CSS/JS files that you upload separately. Then in WordPress you create a page and choose this template — et voila, you have your game on the site.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, javascript, html" }
wp_enqueue_scripts with JS script as a string isn't there any way to load a script through `wp_enqueue_scripts` and have my script instead of in a file, in a variable declared earlier? Something like: add_action('wp_enqueue_scripts', 'ajax_check_payment'); function ajax_check_payment() { $script = <<<JS <script type="text/javascript"> jQuery(function($) { $(document).ready(function() { alert('asdasd'); }); }); </script> JS; wp_enqueue_script('ajax_check_course_payment', $script, array('jquery'), time()); }
Unfortunately, `wp_enqueue_script` doesn't work that way — the second parameter is for a URL as per the documentation. But you could use `wp_add_inline_script()` (if there's an enqueue'd script to attach it to) or, as in olden times, just hook in to `wp_head` or `wp_footer`.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, ajax" }
the_ID & wp_get_attachment_image_src(the_ID(), "medium") blank Using: $my_query->the_post(); $thumbnail_arr = wp_get_attachment_image_src(the_ID(), "medium"); $thumbnail = $thumbnail_arr[0]; `$thumbnail` is outputting a blank value. If I echo `the_ID()` it is blank also. Help appreciated. **EDIT** I've tried: $my_query->the_post(); $thumbnail_arr = wp_get_attachment_image_src($my_query->post->ID, "medium"); $thumbnail = $thumbnail_arr[0]; but `$thumbnail` is still empty.
I changed to: $attch_id = get_post_thumbnail_id( $my_query->post->ID ); $thumbnail_arr = wp_get_attachment_image_src($attch_id, "medium"); $thumbnail = $thumbnail_arr[0]; and `$thumbnail` is returning what I want now.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post thumbnails" }
How to detect if an ACF custom-field is really in use? I want to find out if a custom-field is in use for a `post` or `term`. That means the custom-field has a content and is not empty. I guess that's more difficult for selects, radio or checkbox-inputs. So let's imagine i am looking for a text-input field named `my_special_value` and if it is used in any `post` or any `term`. * * * Background: I got an installation where I want to reduce custom-fields as I expect that some are not in use anymore. * * * Subquestion: Is there already a plugin for and I didn't found it yet?
Most sensible here is probably just a custom query global $wpdb; $sql_find_meta = "SELECT post_id FROM database_name_here.wp_postmeta WHERE meta_key = 'my_special_value' AND meta_value > '';"; // > '' == not null, whitespace or blank $posts_with_meta_key = $wpdb->get_col( $sql_find_meta ); foreach ( $posts_with_meta_key as etc..... You can repeat this for `wp_termmeta` and `term_id`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, custom field, advanced custom fields, terms" }
Redirect users by role to custom pages I have created a custom login form that will use the default action of the wordpress one. I need to display errors on it if occurs but at the moment the user will be redirected to `wp-login.php` in case of errors. Also I want that users are redirected to specific page based on their role, I have two custom roles and I need to show different pages to each single role. How I can accomplish this, will the `login_redirect` filter be useful if I add it in a custom plugin? Will a custom page added to dashboard using `add_menu_page`can be displayed to user without a particular role, or there is another way to replace the default dashboard?
For redirect you can do something like this. function redirect_to_page() { global $user; if (in_array( 'specified_role', $user->roles ) ) { return '/wp-admin/post.php?post=7&action=edit'; } } add_filter('login_redirect', 'redirect_to_page');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, plugin development, dashboard, wp login form" }
Replace Entire Comment Box with Text I have a need to disable comments for a specific group of users. But I want to replace the entire comment box with a message like "Sorry, you are not allowed to enter a comment". Other users should still be able to enter a comment in the normal way. I don't think I found a filter to do that, but I may be looking in the wrong area of comments.php. Is there a way to replace the entire comment area with a message? **Added** This ability is being added to a plugin, so it needs to be theme-independent - effective on all sites where the plugin is enabled.
Something like this should be pretty universally functional across themes, as long as they use something like the normal comment form code. if ( ! current_user_can( $capability_required_for_commenting ) ) { add_filter('comments_open', 'disable_comments', 20, 2); add_action('comment_form_comments_closed', 'display_no_comment_permissions_message' ); } And then somewhere you'll want to define: function disable_comments() { return false; } function display_no_comment_permissions_message() { ?> <p><?php _e( 'Sorry, but you aren’t able to comment!', 'text-domain' ); ?></p> <?php } Probably the place you want to add this is somewhere around the call to `comment_form()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, comment form" }
How to set variable to specific field when querying I am trying to validate an input box against a field in a database. My question is, how does one check a single input equal to any field in a column? I am able to connect to my query, but am unable to perform the validation. Am I missing something? Here is my code: add_action('woocommerce_checkout_process', 'username_auth'); function username_auth() { global $wpdb; // INPUT FIELD $username = $_POST['custom_field_username']; $user_login_sql = $wpdb->get_results("SELECT username, FROM registration_info WHERE username"); if(isset($username) && $username !== $user_login_sql) { wc_add_notice(('Incorrect username123'), 'error'); } }
Always sanitize input fields. Use `$wpdb->get_var` to check a single variable. You forgot to add the compare value to the `WHERE` clause. function username_auth() { global $wpdb; $username = sanitize_text_field( $_POST['custom_field_username'] ); $user_login_sql = $wpdb->get_var("SELECT username FROM registration_info WHERE username = '$username' "); if( $username !== $user_login_sql ) { wc_add_notice(('Incorrect username123'), 'error'); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, woocommerce offtopic, mysql" }
Show Next/Previous without Link I have a question. Currently I have `<?php next_post_link('%link', 'Next Post'); ?>` and `<?php previous_post_link('%link', 'Previous Post'); ?>`. Both return `Next` and `Previous` with a link. I want it to be Next and Previous without a link. I tried removing the `%link` from the code, but the text disappeared. I want to use this code without a link because I want the built-in condition. What should I do to render the text without the link? Appreciate the help from the community.
I already got the solution myself. Just use this code, and you will get the Next/Previous post without a link: <?php previous_post('Previous Post'); ?> <?php next_post('Next Post'); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, functions, single" }
Next/Previous Url only I only want to get the URL of the next/previous post link instead of title+link. I searched WP's codex but unfortunately, I couldn't find it. Any ideas?
There are no functions for that in WordPress core (yet), however, you can: * Use `get_previous_post()` to get the previous post. * Use `get_next_post()` to get the next post. * Or you can also make a direct call to `get_adjacent_post()` which is used by the above functions. And then just use `get_permalink()` to get the previous/next post's URL. For example: $post = get_post(); // get the current post $next_post = get_next_post(); // or use get_adjacent_post( false, '', false, 'category' ); $next_post_url = $next_post ? get_permalink( $next_post ) : ''; $prev_post = get_previous_post(); // or use get_adjacent_post( false, '', true, 'category' ); $prev_post_url = $prev_post ? get_permalink( $prev_post ) : '';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "codex" }
How to remove js using theme, which was added by plugin in WordPress site? I have my WordPress site. It has one plugin which adds a JavaScript which I don't want to use. I want to remove it from my site using theme. Tried multiple solutions like added hook in function file to dequeue the script but doesn't work for me.
You can use the below code with the required changes in the theme's function file. Refer to the documentation for more info * wp_enqueue_scripts * add_action * wp_deregister_script add_action( 'wp_enqueue_scripts', 'remove_thrive_appr_main_script' ); function remove_thrive_appr_main_script() { wp_deregister_script( 'handle-of-style' ); } Note - 'handle-of-style' = handle of style (You have to replace it with your own one) I hope this will help you.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "javascript" }
How to escape html code? WordPress says, "You always want to escape when you echo, not before." Now how to escape below line in my plugin. Notice that I pass a variable inside html. $wfam_woocommerce_active = '<th>Woocommerce</th>'; echo ' <div class="wfam-restrict-individual-file_list-wrapper"> <table class="wp-list-table widefat fixed striped table-view-list users"> <thead> <tr> <th>Image Name</th> ' . $wfam_woocommerce_active . ' <th>Access Type</th> <th>User Roles</th> </tr> </thead> <tbody> ';
Escaping depends on two things: what your variable contains, and what its container is. What the variable contains means - is it a URL? A string? JS? and so forth. What its container means - is it an attribute? Is it enclosed between two HTML tags? and so forth. Assuming your variable `$wfam_woocommerce_active` is a string that does not contain HTML, and also that you probably want it output inside of a `<th></th>` tag, for this instance you could use: <th>' . esc_html( $wfam_woocommerce_active ) . '</th> If instead the variable contains the `<th></th>` tags, you could use ' . wp_kses_post( $wfam_woocommerce_active ) . ' which means to allow only the HTML that is allowed in Posts, which includes `<th></th>` and many other tags. See more about escaping in the developer handbook.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, theme development, themes" }
Page Attributes Panel (Parent option) is not showing on a custom post type i have this when registrating my cpt: 'supports' => ['title', 'editor','thumbnail', 'page-attriutes'], 'hierarchical' => true, // Allows your posts to behave like Hierarchy Pages However, the 'page-attributes' panel with the Parent Option is not displaying. What am I missing? How can I enable the parent option for the cpt?
You've misspelt `attributes` and used `page-attriutes` which doesn't exist, Instead add `page-attributes`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Remove ALL HTML from single page I want to remove **all** HTML from a page generated by Wordpress. It needs to be simple plain text, without **any** HTML, at all. When opening the page in the browser, it should not return any HTML code. Therefore, I do not want to edit a post -- I want to completely remove everything. I have only found ways to replace the post content. However, I do not want to replace the post content. I want to completely remove the entire HTML of a page. Starting from `<!DOCTYPE html>` and ending with `</html>`.
You could make a template for this in your active theme, then assign that page to use the new template file. ## `null-template.php` <?php /** * Template Name: Null */ if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title(); echo( wp_strip_all_tags( get_the_content() ) ); } } Then create a new page (or edit the one you want to be HTML-free) and make sure it's using the **Null** template. ![Screenshot using the "Null" template]( This should result in a page that has no HTML whatever in it. ## References * Template files * `wp_strip_all_tags()` for when you _really_ don't want any tags left behind
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "themes, html" }
register_term_meta not working I have a simple code snippet, and seems like I am missing something obvious. add_action( 'init', 'custom_term_meta_setup'); function custom_term_meta_setup() { register_term_meta( 'procedures', 'source_post_id', array( 'type' => 'integer', 'description' => '', 'single' => true ) ); } I tried to hook this to some actions which are executed a bit later, such as `wp_meta`, but had no luck. Tried it in both Docker local env, and in a regular local (MAMP) WP installation, had no luck. Tried to do the same thing with `register_meta`, unsuccessful. Tried with `sting` type, no luck. PS: To see the results, I am echoing the "procedures" term I expect to get this meta field: $terms = get_term( 49 ); echo "<pre>" . var_export( $terms, true ) . "</pre>";
> I am echoing the "procedures" term I expect to get this meta field `get_term()` returns a `WP_Term` object which _by default_ does not include any metadata, even for registered meta keys. So registering a meta key does _not_ automatically add it to the term object, but registering a meta key has 2 main benefits: 1. You can set a default value for the meta, which is returned when you call `get_metadata()` or `get_term_meta()`, see the `default` argument here. 2. You can make the meta be accessible via the REST API, via the `show_in_rest` argument (see the same link above). So for example, if you set `default` to 1234 and `show_in_rest` to `true`, then a request for a taxonomy's collection in the REST API (e.g. at `/wp-json/wp/v2/procedures`) would contain a `"meta":{"source_post_id":1234}` in the JSON response, for terms without that meta.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, term meta" }
how to catch a data from a array in WordPress ![enter image description here]( I got page information. but now I can't print specific data from this array. $page_details = get_pages( array( 'post_type' => 'page', 'meta_key' => '_wp_page_template', 'hierarchical' => 0, 'meta_value' => 'template-parts/about.php' )); echo '<pre>'; var_dump($page_details);// check the array value echo '</pre>'; var_dump($page_details["post_title"]);// it's return null value. this way I am trying catch the specific value. but it is wrong I was known but recently I forget it. so please help
The "array" you show in your screenshot is an array of `WP_Post` objects (well, in this case it's an array of 1 `WP_Post`). In this specific case, you can get the page's information like this: var_dump( $page_details[0]->post_title ); ...which will get the `post_title` property from the zeroth (first) (well, only) `WP_Post` object in your array. In the case where you've got more than one `WP_Post` in the array, you can get all their titles like this: foreach ( $page_details as $page ) { var_dump( $page->post_title ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, theme development" }
Can I remove WooCommerce specific product categories from shop managers? Can I remove WooCommerce specific product categories from shop managers, so that they can publish products only in some specific categories. I tried this, but it's not working. $user = wp_get_current_user(); if (!current_user_can('activate_plugins')) { add_action('wp_head', 'removeCategories', 100); function removeCategories() { echo "<style>#product_cat-23{display: none !important;}</style>"; } }
$user = wp_get_current_user(); if (!current_user_can('activate_plugins')) { add_action('admin_head', 'removeCategories', 100); function removeCategories() { echo "<style>#product_cat-23{display: none !important;}</style>"; } } It's admin_head for admin UI.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, user roles, capabilities" }
Any way to use classic Menus in Full Site Editing? I use an FSE theme and as you might know the Navigation block is pretty limited. I want to implement a custom mega-menu-ish navigation for a big website. Is there any way to enable the Appearance->Menus in the admin dashboard while FSE theme is enabled, so that I could use a shortcode to implement this?
> Is there any way to enable the Appearance->Menus in the admin dashboard while FSE theme is enabled I noticed that in some FSE themes the classic **Menus** admin page shows up under _Appearance_ : ![enter image description here]( when they include a `register_nav_menus( ... )` call within the `after_setup_theme` hook to define the relevant classic menu locations. See for example the Raft theme's setup: < It's also possible to select classic menus within the **Navigation** block: ![enter image description here]( We note that the "Manage menus" link in the Navigation block is /wp-admin/edit.php?post_type=wp_navigation and it is not pointing the classic Menus admin page: /wp-admin/nav-menus.php
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "menus, full site editing" }
Is it possible to have two templates in an article hirearchy? I'm creating a custom theme. The articles are organized so that related articles form a hirearchy of specificity. More general articles (e.g. articles about automobiles) are at the top level and more specific articles (e.g. articles about Honda Civics) are at lower levels. This hirearchy is reflected in the breadcrumbs at the top of the page and in a topic-navigation menu on the left side of each article (see image). Not every article page will use the same template. I'll need at least two types of page templates used in the hirearchies. Is that possible?
Yes, you can create multiple templates for a custom post. Simply create a new template page and add the following code in the template header: <?php /** * Template Name: Article type 1 * Template Post Type: post, page */ get_header(); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development" }
Custom Fields after update to WordPress 6 I had a site where posts had custom fields and upgraded to WordPress 6 recently. However, now I cannot find the custom fields in the back-end. They still display correctly in the front-end, so the data is there somewhere. I am not using a custom field plugin, these were just custom fields added manually in the Custom Field panel in the older version of WordPRess. Gutenberg no longer has any custom field options when clicking the 3 dots it seems, so mentions of that must have been in older tutorials. Any idea how I can view custom fields in the back-end again?
In the top right corner, click on Options, from there click on Preferences. Now select Panels from the left side of the prefs window and you'll find an option to toggle custom fields listed under Additional. !Screenshot
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, block editor, upgrade" }
Remove automatic excerpts only for single posts I want to be able to remove automatic excerpts (and keep the custom ones) only on single posts since I make use of automatic excerpts in my archives. I am using this code: if ( is_single() && 'post' == get_post_type() ) { remove_filter('get_the_excerpt','wp_trim_excerpt'); } But it doesn't seem to be doing anything. Without the condition, it strips out automatic excerpts from all places where excerpts exist.
It seems to me that your code **runs too early** , i.e. before WordPress determined what the queried object is, i.e. whether it's for a single post, a category archive, a search results page, etc. Such issue could happen if you added the code "just like that" to your theme's functions file, so try doing it like so instead where I put the code inside a function which is hooked on `wp`: add_action( 'wp', function () { if ( is_single() && 'post' == get_post_type() ) { remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' ); } } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "excerpt" }
Find Any Theme's page.php File I'm developing a plugin that needs to create a page template that uses any theme's 'page.php' file. The intent is to read the source code of that theme's page.php, modify it to add additional functions, and store the modified template file in the plugins folder. The new template will then be made available on a page's 'template' dropdown (using the 'template_include' filter as described here). The new template needs to add additional plugin scripts ('includes'), and will have a shortcode that will insert a form at the shortcode's location. Since all themes have their own version of a 'page.php' file, I need to use the structure of the theme's page.php file (with all it's CSS and whatever content), so that using the new template on a new page will result in a page that matches the theme's 'look'. Is there a function that will figure out the page.php template file? Or is there a way that a shortcode can add 'includes' to a page?
Further contemplation, and looking at the template hierarchy, lets me know that every theme needs at least a page.php, or singular.php, or the index.php file is used. So, I just need to figure out the current theme directory (via get_theme_directory function), and see if the page.php file exists. If so, use the code from that template as the basis for the new template. If it doesn't exist, then look for and use singular.php and index.php in that order. And if that doesn't exist, the theme has problems, and probably wouldn't work correctly. So, there is no need to figure out what template a theme will use for a page. They will have a page.php (or a page-something.php, which I can look for).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, themes, page template" }
How do I empty a specific meta_value for all users in PHP I've been able to successfully empty the meta_value for a specific meta_key. The problem is that a new meta_key will be created for all users in the database. I do not want all users to have the meta_key created in the database unless it already exist. I think perhaps if I set 'guest_list_venue_names' as a variable and check if it exist I can use an IF statement? I'm new to PHP so any insight would be helpful. $wp_user_query = new WP_User_Query(array('role' => 'Subscriber')); $users = $wp_user_query->get_results(); if (!empty($users)) { foreach ($users as $user) { update_user_meta( $user->id, 'guest_list_venue', ''); update_user_meta( $user->id, 'guest_list_venue_names', ''); } }
You could specify the meta key in the user query so the results you're getting back are only for users who have an existing field. For reference `WP_User_Query` custom field(user meta) params. $args = array( 'role' => 'Subscriber', 'meta_query' => array( array( 'key' => 'old_meta_key_name', 'compare' => 'EXISTS' ) ), ); $users_with_meta = new WP_User_Query( $args ); $users = $users_with_meta->get_results();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, database, meta value" }
Is it possible to specify a time interval (from, to) in ACF with date picker, or other custom field? I am working on an online magazine in WordPress PHP (with Advanced Custom Fields plugin). I specify the date of the article's publication with 'date picker' field. Even though for articles representing events, a time interval should be defined, in the form of 'from-to'. As I noticed, there is no option for this in date picker, or other fields. Or does such a field exist in ACF? Thank you in advance for your help.
There's no native "Time Interval" field type in ACF, but you could: * Use a third-party custom field like the "Date Range Picker" provided by ACF Extended (it's a commercial plugin that adds features to ACF). * Use 2 distinct native Date Picker fields for "from" and "to", possibly inserted inside a Group. You may take advantage of some existing snippets to display the value (example).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, advanced custom fields, date, datepicker" }
WordPress Rest API Escapes Returned URLs Forward Slash I have created an endpoint via `register_rest_route()` that gets serialized data from the DB. When it is returned, all of the URL strings are escaped. `https:\/\/s.w.org\/plugins\/geopattern-icon\/action-scheduler.svg`. It seems this is because returned values are passed through PHPs `json_encode()` function. How would I return the URLs, so they are not escaped `
This is no different to when `&amp;` in raw HTML is displayed as `&`, **it's standard JSON encoding** , and is resolved by _decoding_ the JSON. Any application that is unable to handle this has probably forgotten to parse the JSON response. For example: const url = JSON.parse( '"https:\/\/s.w.org\/plugins\/geopattern-icon\/action-scheduler.svg"' ); console.log( url ); Will print the URL as you expected. JSON decode then grab that value from the resulting array/object.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "rest api, json" }
How to upgrade WordPress automatically? How to upgrade WordPress automatically? What is the standard way to upgrade an entire WordPress installation --- core **or** core and plugins, automatically?
By default WordPress automatically updates itself, plugins, and themes. If your WordPress install doesn't do that then you probably have something that disables this. You can check your theme for something like this add_filter('auto_update_plugin', '__return_false'); add_filter('auto_update_theme', '__return_false'); And/Or in your wp-config.php define('AUTOMATIC_UPDATER_DISABLED', true); define('WP_AUTO_UPDATE_CORE', false); If your WordPress is not on a local machine and is on a hosting env, and you can't find anything like the code above, you can try contacting your hosting about this, they might provide additional help.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "automatic updates" }
Count words for all posts by all authors So I got this code from another query and it works for one single post. However, I want to show the `total words of all the published posts by all authors`. How do I modify this or is there a wp function that exists? functions.php: function prefix_wcount(){ ob_start(); the_content(); $content = ob_get_clean(); return sizeof(explode(" ", $content)); } Template: <?php echo prefix_wcount(); ?>
You will need a function to get all the published posts and count the words. function wpse410818_count_published_words() { $posts = new WP_Query(array( 'post_type' => array( 'post' ), 'post_status' => 'publish', )); $count = 0; //Starting words count if ( $posts->have_posts() ) { while ( $posts->have_posts() ) { $posts->the_post(); //Add to the word count $count += str_word_count(trim(strip_tags(strip_shortcodes(get_the_content())))); } } echo $count; } This will query the database everytime it runs, therefor, you might want to cache the result and update it when a new post is published or an existing post is modified.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, query posts, count" }
get_terms of specific parent (including the parent itself) The title is self-explanatory, but let me say a word on this... I want to get the terms of a specific parent, but also include the parent itself in the returned terms. I tried something this `$args['parent'] = $args['include'] = $tax->term_id;` but unfortunately it didn't work... I'm thinking to find the parent of the parent, and do something like this `$args['parent'] = {id of grandfather}; $args['exclude_treeint'] = array({ids of siblings of the parent});` But isn't this an overkill of a solution? Am I missing something obvious here? TIA
I don't think there's a way you can setup the arguments such that you can get all children of a term and that term in one call, so you'll probably just have to tack on the parent as a separate call. Using `get_terms` for the children, then `get_term`. $parent_id = 100; // set as appropriate $terms = get_terms( array( 'taxonomy' => 'YOURTAX', 'hide_empty' => false, // omit if not applicable (used for testing) 'child_of' => $parent_id, ) ); $terms[] = get_term( $parent_id, 'YOURTAX' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "taxonomy, terms" }
How can I use wp_after_insert_post with $current_screen? I'd like to call `add_action( 'wp_after_insert_post'` on particular screens. I'm currently checking the page like so followed by calling the `wp_after_insert_post` hook. It doesn't seem to fire but does if it's swapped with `add_action( 'current_screen', 'test' );` instead. function test() { global $current_screen; if ( isset( $current_screen->base ) ) { if ( $current_screen->id == 'post' ) { $args = array( 'ID' => '10', 'post_name' => 'Some title', ); // Update the post wp_update_post( $args ); } } } add_action( 'wp_after_insert_post', 'test', 100 );
Based on your comment, you don't actually care about the current screen. You care about the post type. They might be related but they're not the same thing. If you want to target a specific post type in the `wp_after_insert_post` hook, you can use the post object passed to the hook callback: add_action( 'wp_after_insert_post', function( $post_id, $post ) { if ( 'post' === get_post_type( $post ) ) { // Do something. } }, 10, 2 ); Just replace `'post'` with whichever post type you want to check.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, pages, wp update post" }
How to enqueue js script after another specific js script? Hi I have a js script that needs to be included after a specific js script. function wpb_adding_scripts() { wp_register_script('egovt-add-js',get_stylesheet_directory_uri(). '/add.js','','1.1', true); wp_enqueue_script('egovt-add-js'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); This add.js file is included, but not in the positions that I need, I need it to be after another js file, named first.js (for ex.)
That's part of the default functionality available in wp_enqueue_script/wp_register_script. The third argument, as seen in the official documentation of enqueue/register script, < < is the dependencies array. > $deps string[] Optional > An array of registered script handles this script depends on. Default: array() So lets say you have script with the handle "sliderjs", using your code it would look like this function wpb_adding_scripts() { wp_register_script('egovt-add-js', get_stylesheet_directory_uri() . '/add.js', ['sliderjs'],'1.1', true); wp_enqueue_script('egovt-add-js'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); // A multi line arguments example /* wp_register_script( 'egovt-add-js', get_stylesheet_directory_uri() . '/add.js', ['sliderjs'], // <- this is the dependencies arrray '1.1', true ); */
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp enqueue script" }
CSS url rules not relative to css path in account endpoint areas. IE. subscriptions I am using @font-face in CSS file with a relative url to font files (relative to the css file). However on the endpoints of the account page (create by woocommerce) the relative nature of the url breaks and includes the endpoint. For example: `url('url/something/something/')` will become `url('url/endpoint/something/something/)` I am assuming that this is normal behviour, however I cannot find any references as to how to overcome it in the css file short of generating rules at load or by using absolute paths.
It was my mistake. I forgot I was using a preload link in the head of the file. In the head of the html I had: <link rel = "preload" href = "../wp-content/themes/themename/locationfolders/font.woff2" as="font" type = "font/woff2" crossorigin /> Note the .. at the start of the href what it should be is: <link rel = "preload" href = "/wp-content/themes/themename/locationsfolders/font.woff2" as="font" type = "font/woff2" crossorigin /> This is still "relative", but to the home URL... which is what I was after.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, css" }
Why does WP theme not look like promoted? I am searching for a WP template on < There I see for example "Kadence": ![enter image description here]( I would like to preview it, so I click "More Info" (which appears when I hover the mouse over it). This takes me to this page: < However, this page does not look like the preview. What do I need to do to view the preview as it was shown? ![enter image description here](
You need to use the same content and settings the author used to take the thumbnail, theme authors have no control over the content used in the theme preview on .org so the preview rarely shows what the theme is fully capable of. If the difference is more extreme and it's not possible to install and configure the theme to look that way you should take it up at wordpress.org in their themes support forum.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "themes" }
Console errors after Wordpress Update 6.1 I am using Soledad theme with Woocommerce and after updating to version 6.1 I get these errors. Failed to load resource: the server responded with a status of 500 () post.php:1 Failed to load resource: the server responded with a status of 500 () /wp-admin/admin-ajax.php:1 Is anyone having the same issue? Cheers
Turns out it's an issue with "WooCommerce Multilingual & Multicurrency" plugin which is related to WMPL. WMPL is having big issues right now with their products and probably are fixing them at this moment. For example a lot of developers had problems with "WPML String Translation" plugin which caused critical error for websites.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, woocommerce offtopic, errors, updates, 500 internal error" }
My Blog page ( posts page ) theme isn't changing with the new theme I have changed my WordPress theme to Raft and the whole website changed its theme accordingly to my new theme but my post page which name is "Blogs" is still in its old theme which came with the default with the WordPress I install through the hosting website (infinity free). I don't know whats the problem I deleted the cache from the browser and reload the website multiple times but the blogs section is still the old theme. All the other pages of the websites are shaped according to the new theme except the blogs page
Interesting. Is there a caching plugin active? Is there caching at the hosting level? Have you loaded the page in a private/incognito browser window? Have you tried to completely remove the old theme? What is the URL of the site and the blogs page? I'd love to look at the response headers to see if there is anything there that would indicate what the issue is.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, posts, themes, templates" }
Change the environment for creating a WordPress page I tried WordPress this time, and the YouTube screen and my page development environment are very different. How do I set it up like the second screen?![enter image description here]( ![enter image description here](
You have to use classic-editor and a page builder for building the page. plugins->add new search name and install plugin and activate it. < <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages" }