INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
What CSS rules are introduced to core blocks through wp-block-styles? The Gutenberg Handbook mentions that some CSS for WordPress core blocks are applied to the front-end and within the editor by default (and that they cannot be disabled) but there are more opinionated CSS styles available that can be optionally added by adding the following your theme (in one of the PHP files, typically done through functions.php). add_theme_support( 'wp-block-styles' ); I'm trying to find a list of these CSS rules added by `wp-block-styles` I've searched through the Gutenberg repo and the only contents of `wp-block-styles` are the documentation that I linked to above.
If you have the Gutenberg plugin installed and enabled, the css rules are loaded in `/plugins/gutenberg/build/block-library/theme.css` ; If you're just using the block-editor that is in core WordPress, the rules will instead be loaded from: `wp-includes/css/dist/block-library/theme.css`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "css, block editor" }
WordPress Gutenberg How to make TextControl Required? I want to make this field required. Can anyone suggest how to do it? <TextControl tagName="p" label="url" placeholder=" focus = {focus} className="full-width " value={ props.attributes.url } onChange={ onChangeurl } keepPlaceholderOnFocus= {true} />
This could possibly done using lockPostSaving Some code example <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, block editor" }
How to authenticate via API to allow writes/updates I've been working with the Wordpress REST API Authentication plugin (from miniOrange) as part of an article I'm writing. I want to demonstrate how to integrate a third-party application with a WP site through the API. The miniOrange plugin is actually great for API calls that only want to read, but if I want to post pages or other information to the site, it is necessary to authenticate as a user with privilege. Unfortunately, this plugin doesn't appear to even offer a trial mode for doing this. In order to use authentication modes that would allow writing, the plugin must be upgraded to the tune of somewhere between $150 to $400 (various sources of intel on this differ). * Is this the ONLY suitable authentication plugin? * Is there no other way to utilize the API for write operations without a similar plugin?
In the documentation I could find, it seems there were four options. * OAuth1.0a Server \- this appeared to be unsupported and obsolete * Application Passwords \- This might work, but it seemed a bit awkward to me * JSON Web Tokens \- this appears to be unsupported and obsolete * Basic Authentication \- this appears unsuitable as far as I can see I explored the API Authentication plugin from miniOrange, and discovered that you can do a lot of things with the free version. You can GET pages, posts, comments, and media. You can POST media, comments, and posts. The plugin supports Basic Authentication, JWT authentication, or (with the premium version,) OAuth 2.0. So the short answer to my question is, " _yes, you can configure authentication for the WP API on your site without incurring big expense._ "
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, rest api" }
How to remove Database Table in Wordpress via Function file? I recently installed Rankmath, I am using different Page Builder, Where the content not readable by the Plugin. So I disabled SEO Analysis from Setting. Now I wonder if we can remove this Table from Daba via **functions.php**. I think removing this table will improve load time. ![enter image description here]( Table Name : "wpbr_rank_math_sc_analytics"
Add this to `functions.php` function delete_wpbr_rank_math_sc_analytics() { if ( ! isset( $_GET['delete_wpbr_rank_math_sc_analytics'] ) ) { return; } global $wpdb; $wpdb->query( "DROP TABLE IF EXISTS wpbr_rank_math_sc_analytics" ); } add_action( 'admin_init', 'delete_wpbr_rank_math_sc_analytics' ); Visit this URL: ` Obviously change "yoursite.com" to your actual domain. I made it so you have to visit a specific URL so it doesn't run every time.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, mysql" }
How to escape $_GET and check if isset? I submitted a plugin to wordpress and I got a feedback that I have to escape this one `$active_tab = isset( $_GET[ 'tab' ] ) ? $_GET[ 'tab' ] : 'front_page_options';` If I do like `$get_the_param = esc_html($_GET[ 'tab' ] );` `$active_tab = isset( $get_the_param ) ? $get_the_param : 'front_page_options';` Seems to work but as isset ( Cannot use isset() on the result of an expression ) as $_GET is not set it will throw a notice? What can be the possible solution? Thanks
The proper way to do that is using `filter_input()`. Here is an example for using a custom sanitize function: $tab = filter_input( INPUT_GET, 'tab', FILTER_CALLBACK, ['options' => 'esc_html'] ); $tab = $tab ?: 'front_page_options';
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "sanitization" }
Upload Wordpress Plugin from ZIP Broken - Returns Symbols Squares & question marks I am trying to upload plugins to my wordpress website. However, when I click "Install Now" my wordpress reloads and prints out a long string of symbols like this: #EU0'q=y{VP(-=p=%'GdB߯_ak bB#t!81Qj@HL˷֝q&TvRQ {3W79<ug:.d|L$EYYSF )T*2Rɮ4C! Everything else on my site works fine AND I can add plugins by searching and clicking "Install Now." I guess there's a corrupted file? I have literally no clue and couldn't find anything by googling. Server details: 1. Wordpress 5.5 2. Hosted on Siteground with Cloudflare 3. Deactivated all plugins and problem still occurs 4. I just pushed from my dev environment to my live (I used Local by Flywheel and WP Migrate DB Pro) * * * Update: I don't know what happened, but when I checked my installed plugins list ... the plugin was there and not activated. I guess the "activate now" screen is broken for my wordpress installation.
The plugin you are using is perhaps corrupted. With 7-zip or similar archivers on your PC, try testing it, or simply extracting it. If you encounter errors, chances are your downloaded plugin is corrupted. If not, try removing it from your website, then uploading it again using FTP/SFTP. Otherwise, contact your plugin support. ![Test Archive with 7-zip](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, installation, ziparchive" }
custom post type and user post count shortcode Hello i m a newbie in php and Wordpress development. I was struggling to get a user custom post count in my wordpress/buddypress site frontend. i m using this code: // add [author-post-count] shortcode to your frontend add_shortcode('author-posts-count', 'count_user_posts_function'); function count_user_posts_function ($userid, $post_type ) { $user_id = get_current_user_id(); $totalUser =count_user_posts( $user_id, $post_type = 'posts_comcurso' ); return $totalUser; } i m adding [author-posts-count] in my frontend. This way i manage to show user custom post count. If anyone has a simple or better way please let me know.
If you were to use WP_Query to retrieve a list of posts, you can then access the number of posts using 'found_posts'. e.g. (from the support pages) $query = new WP_Query( array( 'author' => 123, 'post_type' => 'posts_comcurso' ) ); Would return all posts with a userid of 123 in your selected post type. Then access the number of posts like so: $count = $query->found_posts; There may be other ways but the above gives you a lot of flexibility to target the posts you want to count. Here's the link to WP_Query support page
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugin development, customization, query posts" }
Wordpress Console Application (ability to excecute a custom function via crontab only) I have a few custom tables in the database and I need to clean expired data from time to time. If I was using WP-Cron, it would be easy, but WP-Cron sucks and is a no-go (especially for what I am doing). Having that in mind, I need to launch some code using `crontab`. How should I do it in a clean, effective manner that would not require nasty hacks? I was thinking of creating a REST endpoint, but how to protect it so it could only be opened by the crontab? The solution should be inside the plugin folder so it could be stored in GIT easily (i.e. nasty workarounds storing files in the main folder (a.k.a `public_html`) are not welcomed). Was searching for a good solution for hours with no success... Thanks in advance!
The solution is as @Tom J Nowell mentioned to launch WP Cron via crontab (and disable it on user visits).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, php, cron" }
How should I be using filters and is_single together? I have a plugin that uses this filter to add some content to a Custom Post Type. // From plugin: add_filter( 'the_content', 'sixtenpresssermons_get_meta', 15 ); I'd like to remove that filter on certain views (singles). I'd like to do so using code in my theme files - without editing the plugin. I tried with the code below in functions.php, but obviously it's not working. // Not working, in functions.php if ( is_single('sermon') ) { remove_filter( 'the_content', 'sixtenpresssermons_get_meta', 15 ) } Can I use conditionals with a filter like this, or how can I remove the filter on singles only?
You can do this in `functions.php`, but you have to make sure the function is hooked into `wp`. Any earlier than that and `is_single` is undefined. Try adding this to `functions.php`: /** * Unhooks sixtenpresssermons_get_meta from the_content if currently on single post. */ function sx_unhook_sixtenpresssermons_get_meta() { // Do nothing if this isn't single post if ( ! is_single() ) { return; } remove_filter( 'the_content', 'sixtenpresssermons_get_meta', 15 ); } add_action( 'wp', 'sx_unhook_sixtenpresssermons_get_meta' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, conditional tags" }
Update wordpress causes white space on admin I've updated wordpress to the 5.5 version, how can I remove this? I've an empty div which has a **margin-top: 2rem** , which causes the white space on top, but can't explain for the footer <div id="adminmenuback"></div> ![enter image description here]( ![enter image description here](
According to this post: How to fix the admin menu margin-top bug in WordPress 5.5? There is no solution yet, but maybe this will help you find one. Personally, I tested locally and on a SiteGround server, but I can't recreate the problem. However, if you can tell yourself it's a PHP error like the link I gave you above, maybe your file with PHP log errors will tell you something. (Sorry for my bad english, j'ai voulu t'écrire en français, mais bon ^^) Don't forget to write define('WP_DEBUG_LOG', true) in your wp-config file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, updates" }
/wp-admin not accessible after migrating to local host (no plugin issue) I migrated my local Wordpress site to my WPEngine account and it's been working without any problem! After adding some content, I decided to export the database from the live version and import it to my local version so that they are synced. I adjusted the two `siteurl` and `home` fields in the database and the home page ( comes up well but the /wp-admin page is forced to https and responds with `ERR_SSL_PROTOCOL_ERROR` error. All the other pages of the website cannot be loaded and return this error: Not Found The requested URL /news was not found on this server. It seems like a "permalinks" reset problem for inner pages! All these problems would go away if I switch the database back to the one I was using for local version so I'm pretty sure it's a database issue! Thanks
I'm not sure but I would try 2 things * Change `siteurl` and `homeurl` into http:// and not for https:// to work locally you'll need a local SSL certificate. You can easily manage this with MAMP PRO. But it's not required for your local site to work at all. * Could you check if .htaccess is missing from your projects root folder. This is the directory where wp-config.php is located. This has impact on the permalinks, most-likely if the homepage is working and nothing else is, the .htaccess is missing. Hope this helps out
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, migration, https" }
How to get post permalink url without a href I need code to get post url without a href, for example: `<a href=" rel="permalink">single post title</a>` i just need the url like: ` on single.php
What you need is `get_permalink`, e.g. $current_post_url = get_permalink(); You can either use it inside a post loop, or pass it a post ID as a parameter.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, permalinks, links" }
Update wp_postmeta table based on 2 keys I want to update the wp_postmeta table in the database based on 2 keys, is there a way to do that using any of the wordpress default functions. This is my DB query which is working fine: $sql = "UPDATE wp_postmeta SET meta_value = meta_value + 1 WHERE post_id = 167788 AND meta_key = \"tie_views\"";
Yes, there is. These are some WP functions to get, add and update post meta values: get_post_meta() add_post_meta() update_post_meta() Your code could be: $meta_value = (int) get_post_meta( $post->ID, 'meta_key', true ); update_post_meta( $post->ID, 'meta_key', $meta_value + 1 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, database, post meta" }
is_author(get_current_user_id()) returns false when author id and user id match Inside the loop, when logged in to a localhost test site as `$user->ID == 1` the function `is_author(get_current_user_id())` returns `false` when `get_the_author_meta('ID')` returns 1. Thus, the following conditional is never executed (`is_user_logged_in()` returns `true`): if( is_user_logged_in() && is_author(get_current_user_id()) ) { // do stuff } Have I missed something obvious?
Are you sure you're doing it within the loop? The `is_author` function checks if `$wp_query` is set. Another option would be to try this: $current_user = wp_get_current_user(); if (is_user_logged_in() && $current_user->ID == $post->post_author) { // do stuff }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "functions, user meta" }
Conditionally enqueue a stylesheet based off of a javascript click event I would like to use a different ccs file based on a javascript click event. The user will have a choice of color themes by clicking one of the colored buttons on the screen. I originally have it working by providing the linked css with an id that can be targeted with javascript. The link is in the HTML head tag of course. In WordPress though we enqueue the css file in the functions.php file and so I am not sure how to give the css file an ID to target it with the javascript. If anyone can help me out or point me in the right direction I will really appreciate it. I am open to all possibilities and I thank you all in advance. if you need me to elaborate more feel free to let me know.
I think you're working too hard! My approach to this would be to load all the stylesheets, then use JS to manipulate the `BODY` with an appropriate modifying class. **An example** You have 3 stylesheets: default.css, red.css, blue.css. Load them all on page load. default.css `body { background: #ccc; color: black;}` red.css `body.red { background: red; color: white;}` blue.css `body.blue { background: blue; color: white;}` Then just use JS to modify the classes on the `BODY` tag and the CSS will follow.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, javascript" }
Any way to change post/page status when editing page? Pre-Gutenberg, in the “Status & Visibility” panel, there used to be a way to change a Post’s status from “Published” to “Draft” or “Pending Review” – is that just gone now? The only way I can see to change a Page/Post’s status now via Quick Edit on the main admin-list page. That’s not ideal, as often it is far easier to navigate to a Page on the front-end and use the top Admin bar to ‘Edit Page’ vs having to find the page in the backend control panel. I've posted this WordPress.org forums too, to see if we can get the functionality back in a future update, just figured I'd see if anyone here had a solution or suggestion. Thanks.
When editing a page, click on the cog wheel in the upper right corner to ensure the sidebar displays. There should be two tabs: `Document` and `Block`. Make sure `Document` is selected. There is an accordion item called `Status & visibility`, among `Permalink`, `Discussion`, and `Page Attributes`. If you click on `Status & visibility` to expand it, there is a `Visibility` item in there. Clicking on the current visibility reveals radio buttons to select `Public`, `Private`, or `Password Protected`. To change a page from `publish` to `draft`, take a look at the top right, to the left of the `Update` button. There is a link that says `Switch to draft`. Once it's back in `draft`, under `Status & visibility`, there is now a checkbox above the `Move to trash` link that says `Pending review`, and if you check that, at the top you can now `Save as pending`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post status" }
Accessing WordPress Functions get_permalink() in Vanilla PHP? Simple question. I'm attempting to use `get_permalink()` in vanilla php but cannot access it. I have `include_once` all these "used" files: * wp-settings.php * wp-includes/load.php * wp-includes/link-template.php * wp-includes/rewrite.php * wp-includes/functions.php and 10 other files. How do I access `get_permalink()`?
I worked it out. This file loads Wordpress and makes functions accessible. include_once("wp-load.php"); then was able to $id = $rowa["ID"]; //from MySQL fetch array $permalink = get_permalink(number_format($id));
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, functions, permalinks" }
How to edit the <body> Tags within the image file URLs? At present, my image files appear within the following URL structure: www.example.com/wp-content/uploads/year/month/image-file-name.jpg These image files, contain the following Body Tag <body style="margin: 0px; background: #88888;"> I would now like to modify this Body Tag, so that it becomes: <body <?php body_class();?> style="margin: 10px; background: #01010;"> Performing the modifications, within the Core Files, is obviously not great as the alterations would be overridden after each WordPress update. Therefore, I am looking to be able to make the changes via the theme's `functions.php` file. Is anyone able to give any pointers on how this can be achieved? I am assuming I am going to need to make use of the `add_filter` filter hook?
**You can't, WP doesn't generate that markup, Google Chrome/Chromium does**. There is no way to influence this from the server via PHP or JS or any other technology. It's just how browsers display images on their own directly. As far as the web server is concerned, WP isn't even loaded, and no HTML is sent, just the image data. * * * Firefox does something similar, but it adds some HTML classes to the img tag and lads a stylesheet from a `chrome://` URL to center the image. Safari adds a margin of 0 on the body tag, and adds inline styling rules. You can prove it's the browsers by making the raw request via `curl` on the command line and inspecting the raw HTTP. You'll see HTTP headers indicating an image is about to arrive, followed by the image file. No HTML markup. You can also prove it by dragging and dropping an image from a folder on your computer on to a new tab page. You'll see it too has an auto-generated DOM tree with basic browser styling.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, filters, hooks, tags, core" }
temphangle variable missing when using wp_filesystem copy I get the following error when using `$wp_filesystem->copy();` to copy a file from one destination to another. Undefined variable: temphangle in <b>../htdocs/wp-admin/includes/class-wp-filesystem-ftpext.php</b> on line <b>159</b> Any idea what **temphangle** is?
It appears to be a typo corrected by SergeyBiryukov in the Github Repo for 5.6 : <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filesystem, wp filesystem, filesystem api" }
How do I change the default sort order of a custom column on the posts page? I have a fancy custom column on the posts page in the WordPress admin. I have this column set up to be sortable. The first time that you click on the column header, the URL in the address bar changes to order=asc and then each time that you click on it, it toggles back and forth between asc and desc. However, I'd like the first click to make it desc and then begin toggling it. How can I do that. Here is my current code: add_filter( 'manage_edit-post_sortable_columns', array( $this, 'my_function' ) ); public function my_function( $columns ) { $columns['my_column'] = 'My Column Name'; return $columns; } So how do I make it so that when the column is first clicked, it goes to DESC first and then ASC? Thanks.
You just need to provide an array with two items — the column slug and the initial sorting order. $columns['my_column'] = array( 'my-column', 'desc' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "query posts, columns" }
Can't Customize Wordpress Page ![click customize]( When I click to customize my page, I get the spinny wheel. I've tried restoring to previous days on my site, but am having no luck. Thank you for your help. ![infinite spinning wheel](
There are several way to fix this problem 1. Clear your browser cache 2. Deactivate all plugins and reactive step by step 3. Change php versions
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, theme customizer" }
wordpress convert timestamp to date not correctly I use `wp_date()` function to convert and show dates with hours and minutes. wp_date( 'Y/m/d - H:m:s',1598205923, 'Asia/Tehran' ) My problem is it shows `Y/m/d` correct. the hour is ok. but it shows `m:s` with a difference of about thirty minutes!!!
Try this. It works `wp_date( 'Y/m/d - h:i:s', 1598205923, new DateTimeZone('Asia/Tehran') )`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "date, timestamp" }
Get first level children of a page ID I am looking to get immediate children of a page ID. I tried below code, but it does not seem to work $pageIDchild = get_pages( array ( 'parent' => 0, 'child_of' =>$pageID, 'sort_column' => 'menu_order' ) ); Any help is greatly appreciated. Thanks!
As per the `get_pages()` documentation: > * **'child_of'** > _(int)_ Page ID to return child and grandchild pages of. > > * **'parent'** > _(int)_ Page ID to return direct children of. Default -1, or no restriction. > > So to get immediate children of a specific page, you would use the `parent` arg and not `child_of`. $pages = get_pages( array( 'parent' => $pageID, 'sort_column' => 'menu_order', ) ); // Get the ID of the first child page. $pageIDchild = ( ! empty( $pages ) ) ? $pages[0]->ID : 0; // Or to get all the IDs, you can do: $all_ids = ( ! empty( $pages ) ) ? wp_list_pluck( $pages, 'ID' ) : array();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "child pages, children, get children" }
How to keep custom post type related information I have two custom post types "Product" and "News". I want to keep a description that describes each of these types and I want to display it under the custom post title inside a banner. Also the user should be able to change it from admin dashboard. That means when I go to products page, there is a banner on top of the page and the title will be PRODUCTS and then product description should be displayed. EX: ## _PRODUCTS_ PRODUCTS DESCRIPTION Now if I can add a meta box common to the product cpt which has an input field, I can display it on the web page. But I only know how to add meta boxes to each products under product type. How do I solve this?
You have a few potential options that I can see: 1. Each CPT has a parameter for a Description, and you could access that via a plugin like CPT UI for admin purposes (though not ideal if you want non-admin users to have access to control the Description!) 2. Create a theme/plugin option page to control the Description parameter so that you limit the non-admin control to just that 3. Create a theme/plugin option page that uses general text fields to populate the description for you. You could use ACF Theme Options to do this quickly and simply if you preferred this route Have a look at: Accessing the Description parameter in a CPT ACF Theme Options Page
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, post meta" }
Do not show sub categories in the loop on archive-product.php Currently, the site I am working on uses `archive-product.php` to load the Woocommerce product loop and with it, load the `content-product.php` template part. However, in my loop, if there are subcategories, they are being displayed in the loop instead of the products, along with with the category image and a 'Find out more' button. How can I ignore the sub categories and just load 100% pure products for each main category in the loop?
The answer lies in the Customiser. This setting used to exist in the WooCommerce settings but they moved it into the Customiser at some point. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, woocommerce offtopic, loop, archives" }
How to list all categories and their IDs using SQL query? I am looking for a SQL Query that can give the list of all categories created in WordPress Site along with it's category IDs. Please advise a query to get it as category/term relationship is quite complex in WordPress. I got this but didn't work - SELECT ID,post_title FROM wp_posts INNER JOIN wp_term_relationships ON wp_term_relationships.object_id=wp_posts.ID INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_taxonomy_id=wp_term_relationships.term_taxonomy_id INNER JOIN wp_terms ON wp_terms.term_id=wp_term_taxonomy.term_id WHERE name='category'
I finally got the solution. Below SQL Query gets the list of all categories with it's ID from WordPress table - SELECT wp_term_taxonomy.term_id, wp_terms.name FROM wp_term_relationships LEFT JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id) LEFT JOIN wp_terms ON (wp_terms.term_id = wp_term_taxonomy.term_taxonomy_id) WHERE wp_term_taxonomy.taxonomy = 'category' GROUP BY wp_term_taxonomy.term_id order by wp_terms.name Hope this could help others.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, database, mysql" }
Change the Default Plugin page filter to Active intead of All Thanks in advance to all, is there a way to change the default filter in the plugins page that is set to `All` to something else like `Active` ? I'v tried to find a hook, but couldn't find any info. ![enter image description here](
There is no WordPress hook to filter the current status on the plugins admin, but if you must, you can use `$_REQUEST['plugin_status']` to change the default status. See example below where I use the `load-plugins.php` hook to ensure we're changing the status (or modifying the superglobal `$_REQUEST`) only on the `plugins.php` page: function wpse_373622() { if ( ! isset( $_REQUEST['plugin_status'] ) ) { $_REQUEST['plugin_status'] = 'active'; } } add_action( 'load-plugins.php', 'wpse_373622' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks" }
How can i redirect click to new admin page not to edit screen in post table Hi community i create a custom post type "message". The posts are created from front-end by user by filling a form. i want on admin side when admin access this post and click on post title in table it should not go to default edit screen. it should go to another page in dashboard where this post details shown. any help please i am stuck on that. how could i redirect to that page and get post.
On functions.php function disallowed_admin_pages() { global $pagenow; # Check current admin page. if ( $pagenow == 'post.php' && isset( $_GET['post'] ) && $_GET['action'] == 'edit' && (get_post_type( $_GET['post']) =='Post_type' )) { wp_redirect( admin_url( '/edit.php?post_type=post_type&page=page_to_redirct&post='.$_GET['post'] ) ); exit; } } add_action( 'admin_init', 'disallowed_admin_pages' ); page_to_redirect is already created an included in functions.php
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, admin menu, dashboard" }
How change a core block label I would like to be able to change the `core/heading` block label that is shown here, what is the best way to do so? ![enter image description here](
That is the block title and you can use the `blocks.registerBlockType` filter in the block editor to change the block title and other settings as well. So for example, this would change the title to "My Heading": function changeHeadingBlockTitle( settings, name ) { if ( name !== 'core/heading' ) { return settings; } return lodash.assign( {}, settings, { title: 'My Heading', } ); } wp.hooks.addFilter( 'blocks.registerBlockType', 'my-plugin/foo', changeHeadingBlockTitle );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp admin, block editor" }
Redirect to a page for only logged in user On my website, there are 2 custom pages that are `/login` and `/register`. If logged in user access the pages. I want to redirect them to `/account` page. But not sure if my PHP code is safe to use. The code is working. Please help. add_action( 'template_redirect', 'login_redirect' ); function login_redirect() { if ( is_user_logged_in() ) { if ( is_page( 'login' ) ) { wp_redirect ( site_url( '/account' ) ); exit; } if ( is_page( 'register' ) ) { wp_redirect( site_url( '/account' ) ); exit; } } }
You can make more readable, like. Small notes at the code. As a hint, the template tag is_page() supports an array of values - `is_page( [ 'login', 'register' ] )`. add_action( 'template_redirect', 'login_redirect' ); function login_redirect() { // If user is NOT logged in, doing nothing. if ( ! is_user_logged_in() ) { return; } // This OR (||) this. is_page supports an array of different values. if ( is_page( [ 'login', 'register' ] ) ) { wp_redirect ( site_url( '/account' ) ); exit; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Wordpress Installation in Subfolder only works half Hello I need to pick your brains here. So one of my projects went live a long time ago. The customer then asked me to build a second project which was supposed to be go live on a different domain. Not they aske dme to upload the project into a subfolder of their root. Everything is fine, I can access the admin and stuff, but the moment I open a blog post for example or navigate to one of the pages on their subfolder it automatically redirects me to the main domain. I have checked the .htaccess which looks fine to me # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /nameofnewsite/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /nameofnewsite/index.php [L] </IfModule> # END WordPress
OK after doing some more research I found out that I had to change the configs for the NGINX files as well. I simply had to add the following parameters before the last closing bracket location /nameofnewsite { try_files $uri $uri/ /nameofnewsite/index.php?$args; } location ~ \.php$ { fastcgi_split_path_info ^(/nameofnewsite)(/.*)$; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "404 error, installation" }
add 3rd party link (with script) to menu item I was given a code to add to a button to make a pop up for calendaring (booking). I can figure out how to add this to the body of the page, but I'd like to add it to a menu item. here is my code: <a href=" class="spwidget-button" data-spwidget-scope-id="6c77380d-c2a0-4190-a51e-77cad166320f" data-spwidget-scope-uri="hopeandwellness" data-spwidget-application-id="7c72cb9f9a9b913654bb89d6c7b4e71a77911b30192051da35384b4d0c6d505b" data-spwidget-scope-global data-spwidget-autobind>Book Now</a><script src=" Placing this in the body works great...it adds a button that when clicked, opens a pop-up. If I put this code in a menu item for a custom link, the link just disappears when I save the menu. I also tried just adding the link to the URL field, and the class to the "css classes (optional)" field, but didn't know where I would put the script or data fields.
I usually add those links with "Custom links". I have tried your link and it works as expected, it shows on my menu and open the popup. ![Custom link](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, scripts" }
How to display only specific Error types in debug.log? No notices, warnings, etc I can't find the right way to make it work. I tried many things, like putting this in wp-config.php define('WP_DEBUG', true); define('WP_DEBUG_DISPLAY', false); define('WP_DEBUG_LOG', 'wp-content/themes/mytheme/mylog.log' ); // yeah, customized it a bit. It logs everything ini_set('error_reporting', E_ERROR ); also tried to set it in the php.ini on various websites i manage. Not on managed hosting. Or at least not on the well known international ones. Can it be server side or syntax error, or not even possible what i want? Thanks!
In short: this is the most detailed documentation on the topic (most likely..) The only source you need. Oh, and here is an amazing Php Error Level calculator to set up the php error mask binary code fast (if needed) Based on this, i made my custom error reporting: In `functions.php` function error_report_log_customize(){ // error_reporting(E_ALL); // error_reporting(E_NOTICE); // error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE); error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE & ~E_WARNING); // helpful tool } add_action('init','error_report_log_customize'); In `wp-config.php` define('WP_DEBUG', true); define('WP_DEBUG_LOG', 'wp-content/themes/my-theme/my-logfile.log'); define('WP_DEBUG_DISPLAY', false); Only thing I'm not 100% sure about which hook is the best for this. `init` seems working so far, but anyone with better insight, pls comment.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, debug, notices, wp debug" }
WordPress transient doesn't use the transient I'm new to the transients but I think I get the logic behind it. So I have a blog and I grab the posts via the API from another blog of mine. Now I would like to save the data in a transient so I don't make a request every time I visit the page. Here is my code: if (false === ($posts === get_transient('posts_array'))) { $response = wp_remote_get( ' ); // Exit if error. if ( is_wp_error( $response ) ) { return; } $posts[] = json_decode( wp_remote_retrieve_body( $response ) ); set_transient('posts_array', $posts, DAY_IN_SECONDS); } Now for some reason my WordPress doesn't get the transients it seems that it always makes the request to the API to get the `$posts` should I somewhere assign `$posts` with `get_transient` if it exists?
I mean in shortly your code is wrong in the first line, the comparing is wrong. The variable `$post` should store `=` the data of the request via `get_transient()` and not compare `===`. So you should switch to: if ( false === ( $posts = get_transient('posts_array') ) ) { // this code runs when there is no valid transient set }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "transient" }
How do i show different group of images below a button when the button is clicked on the same page in wordpress? I am working on a WordPress website using elementor page builder plugin to design the website. I am stuck on creating an image gallery that displays images when a button is clicked on the same page below the button. The image gallery consists of two rows of four images. Attached below is the mockup of the page of the website I intend to design. ![enter image description here](
From a comment by user @rup: > You could treat the buttons as tabs, and there are tabs widgets for Elementor from a quick search.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Using webhook sending message to telegram from wordpress? I want send a message to telegram whenever a form submitted. i am using gravity form plugin form. and it has the hook add_action( 'gform_after_submission', 'post_to_third_party', 10, 2 ); which will be call after form submitted. and i create a telegram bot and submit my url as webhook url base on instruction. here is my code: $url = $path."/sendmessage?chat_id=".$userID."&text=".'messaginggggg'; $request = file_get_contents($url); the problem is when i use the url in my browser it perfectly send notification to my bot , but from the site it returns error : Warning: file_get_contents failed to open stream: Connection timed out in (my file path) line 20 line 20 is : $request = file_get_contents($url);
I had an internet problem. i couldn't send a message from my site because of filterning probelm. Telegram is ban in my country then i should change the server to use Telegram.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp remote request" }
Get /users/me details from Wordpress backend **Is there anyway to get the same details as /users/me api command but in WP backend?** I have backend function that would get the user meta details **custom api /user_meta** public myFunc( $userId ) { $user_meta = get_user_meta( $userId ); return $user_meta } The user meta field has an **ACF option** that is formatted strange "place": [ "a:1:{i:0;s:12:\"Earth\";}" ], But when using the /users/me API call, the return is **/users/me default wp api** "place": [ "Earth" ], Although I could use a conjunction of both apis to get the proper user meta details, it isn't ideal. Is there anyway of getting the /users/me api call in wordpress backend?
"a:1:{i:0;s:12:\"Earth\";}" This is a PHP serialized value. If you pass it to unserialize you'll get back the array you're expecting. (And it looks like you've edited it because "Earth" is not 12 characters long: that should be `s:5:"Earth"`.) However I'm surprised that get_user_meta doesn't already do this for you: it passes the value it's fetched from the database through maybe_unserialize() before it's returned to you, which ought to do this automatically for you. Is there any chance you've double-serialized this before storing the string in the database? (And note also the warning on the documentation page about unserializing arbitrary user-provided strings.) To answer the general question though, everything you can get from /users/me is available with normal API calls and you don't need to use the REST API from inside WordPress itself.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, api" }
How to get a specific string from a url I am creating a custom WordPress theme and i am little stuck in one situation . what i want is that < get the name : paulwoods in a $variable. Note every-time there is new name instead of paulwoods, when i click on a post. Does anybody have a clue how can i get it ? I searched on google but no relevant problems found, and also i don't have any clue to do that.
I believe you should be able to use this: global $post; $page_slug = $post->post_name; Where $page_slug is the variable you're looking for. This has a pretty good explanation of why that works: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, wp query, javascript, jquery" }
Is there any size difference between single quote ' ' and double quote " " in CSS I use single quote `''` and double quote `""` in CSS regularly. Is there any size difference between them? If yes, I'd like to use the smaller one.
There is no difference in terms of file size between single and double quotes. Generally speaking, you should use whatever quotes are called for in the coding standard defined by the project you're using. If no coding standard is being used, at least be consistent with your usage. WordPress specifies the following guidelines for using quotes in the CSS coding standards: **Selectors** > Attribute selectors should use double quotes around values **Values** > Use double quotes rather than single quotes, and only when needed, such as when a font name has a space or for the values of the content property. I'd suggest following the WP coding standards if your project doesn't already have a standard defined.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "css" }
To know whether insert shortcode in custom meta box I build custom meta box that get text and i need to know if user insert shortcode inside and convert the shortcode to his code. for example: inside textarea user insert: Hello Word [contact-form-7 id="63" title="Contact form 1"] the textarea can get strings and html and shortcodes... the result will be: Hello Word and his form.
Shortcode won't automatically execute. I order to achieve your result you need to apply a filter. When you `echo` the value of your metabox in frontend do it like this: `echo apply_filters( 'the_content', YOUR_METABOX_VALUE_HERE );` this way contact form shortcode will execute and form will show.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode" }
Verify a nonce in Form submission I am new in using Nonce.I am using Nonce like below in a Form wp_nonce_field('add_new_addres','add_new_address'); I am trying to verify Nonce like below if(isset( $_REQUEST['action'] ) && ('newAddress' === $_REQUEST['action']) && (wp_verify_nonce($_REQUEST['add_new_address'], 'add_new_addres'))) { //more code here }else { //more code here } `else` block is executing but I need to execute `if` block.
Problem is, you are submitting data as POST data, but verifying nonce from GET data. Here is how you can create a nonce field in a form easily: wp_nonce_field( 'add_new_addres' ); Actually, I personally don't use more than 1 parameter when calling the `wp_nonce_field` function. Then when verify use the following code: if ( ! wp_verify_nonce( $_POST['_wpnonce'], 'add_new_addres' ) ) { wp_die( 'Are you cheating?' ); // Anything that you want to display for unauthorized action } else { // Good to go for next step }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "nonce" }
{$key} or $key? I came across this function in a wordpress theme. function get( $key ) { if ( method_exists( $this, 'get_' . $key ) ) { return call_user_func_array( array( $this, 'get_' . $key ), array() ); } elseif ( property_exists( $this, $key ) ) { return $this->{$key}; } return false; } Why is {} around $key needed in $this->{$key}? How is $this->$key not ok? Thanks.
When we perpend $ in any variable then it become Variable variable (Variable vars) like $$name Check this reference for Variable variable. < Here `$this->$key` will become Variable var because it is about public/private/protected variable of class. So {} in `$this->{$key}` will set $key vars variable of class
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
How to get specific string/value from an array? php I am creating a custom wordpress theme and i am little stuck in one situation. I created an array $ark and get some values in it <?php $ark[] = esc_url( add_query_arg( 'pdff', $post->ID ) ); print_r($ark) ; echo 'jonty'; ?> here below is the output of the above code; Array ( [0] => /jobifylocal/wp-admin/admin-ajax.php?pdff=127 ) jonty what i want is that the only value of pdff after equals-to like here 127 i only need 127 in a $variable to echo somewhere else.
Use below code to get the 'pdff' value: $url_components = parse_url($ark[0]); // Use parse_str() function to parse the // string passed via URL parse_str($url_components['query'], $params); // Display result echo $params['pdff'];
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, php, functions, ajax, javascript" }
Can we completely remove the WordPress Sitemaps (WordPress 5.5)? I have been using my WordPress site to create various types of content, I obviously submit my sitemaps to Google for getting my site indexed. But there is some content which I don't want on Google, and therefore don't want it in Sitemaps too. I used to use a plugin to implement it, but now we have got overlapping functionalities, as WordPress supports sitemaps now. So How can I either completely remove the WordPress sitemap, so that I just use the Plugin, and Google Search Console cant read my `wp-sitemap.xml`, OR selectively remove some posts from WordPress Sitemap, so that I can Customize Sitemap to my taste, and then remove the Sitemap Plugin
Disabling the sitemap is easy, just add this line to your `functions.php`: add_filter( 'wp_sitemaps_enabled', '__return_false' ); Removing specific posts goes like this: add_filter( 'wp_sitemaps_posts_query_args', function( $args, $post_type ) { if ( 'post' !== $post_type ) { return $args; } $args['post__not_in'] = isset( $args['post__not_in'] ) ? $args['post__not_in'] : array(); $args['post__not_in'][] = 123; // 123 is the ID of the post to exclude. return $args; }, 10, 2 ); There a quite a lot of ways to customize the sitemap if you would rather use the WP native way than a plugin.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "plugins, php, posts, functions, theme development" }
Loop inside page template not working I am facing a problem with the loop inside the page template. Here is the code. <?php /* Template Name: Blog-Template */ get_header(); $args = [ 'post_type' => 'post', 'posts_per_page' => 1, ]; $queryP = new WP_Query( $args ); if ($queryP->have_posts()) { while ( $queryP->have_posts() ) : $queryP->the_post(); ?> <article> <?php the_title( '<h1>', '</h1>' ); the_excerpt(); ?> </article> <?php endwhile; } get_footer(); If I set this page as a blog page in settings then no problem happens. But when I create a custom loop for this template it doesn't work. It shows nothing just header and footer.
It solved automatically. I think the WordPress version 5.5.1 is full of bugs. Thanks, everyone for your support.
stackexchange-wordpress
{ "answer_score": -2, "question_score": 0, "tags": "theme development, page template" }
Trying to use a variable to set image width I am writing a WordPress plugin that will display a devotional image. One of the options I would like to include is image width. I am trying to wrap the image and some text in a div so I can style it and let the user chose some different styling options. However, just trying to set the div width using the variable is not working. It says there is a syntax error. Any help would be appreciated! Thanks, Nick. $imageWidth = get_option('devotional_imageWidth','100%'); $content = "<h2>Devotionally Images</h2>"; <div style="width:$imageWidth;"> print '<img src="' .$show_file. '" alt="Image Title Here">'; $content .= "devotional by Devotional.ly"; </div> return $content; } add_shortcode('devotionally','devotionally_function');
There are invalid PHP codes in your sample. Try to use valid PHP code like below. $imageWidth = get_option('devotional_imageWidth','100%'); $content = "<h2>Devotionally Images</h2>"; $content .= '<div style="width:' . $imageWidth. ';">'; $content .= '<img src="' .$show_file. '" alt="Image Title Here">'; $content .= "devotional by Devotional.ly"; $content .= '</div>'; return $content;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, plugin development" }
a href adds default URL with the given echo URL I am a little stuck in one situation. I am removing some errors from my site and got one unexpected error here below is my code:- <?PHP $release_web_url = get_post_meta( get_the_ID(), '_links', true ); print_r($release_web_url) ; ?> and the output of this code is: Array ( [0] => Array ( [name] => Website [url] =>www.google.com ) ) I only want to echo the array URL value in the anchor HTML tag. So I did this coding below: foreach($release_web_url as $item): ?> <a href="<?php echo $item['url']; ?>">Website</a> <?php endforeach; now instead of getting anchor link = www.google.com | I got anchor link = 192.168.1.50/jobifylocal/www.google.com | that thing doesn't make any sense adding the other URL automatically in-front of the given URL.
You’ve forgotten the ` This will happen in any HTML where you don’t add the protocol to a URL. Nothing to do with WordPress. However, you should use `esc_url()` when outputting user entered values into a link, to make sure the output is a valid URL, even if the user makes this same mistake: <a href="<?php echo esc_url( $item['url'] ); ?>">Website</a>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, plugin development" }
Recreate the upload folder from a website without having access to the backend/cpanel/filezilla directly from the website Here's my scenario: I'm working on a website, I have access to the dashboard on WordPress BUT: 1. I can't install plugins. 2. I don't have access to all the folders except for wp-content. 3. I don't have access to the Cpanel/filezilla I'm able to work on the website and copy the database, but I don't have access to the default image folder, UPLOAD but in order to recreate the structure of the website, I should paste and copy ALL the pages, then extract the images, then create other folder and, at the end of the day, place the images files there and then I could be ok. I'm wondering if it is possible to do it differently.. Like a chrome extension, some WordPress native function, so anything else.. from outside that website because I'm recreating the website locally. Any suggestion or hint would be appreciated!
You don't mention what your user privileges are - are you an admin, editor, author, etc? An admin-level should be able to install plugins via Plugins, Add New. Most new-to-WP people don't realize that access to the folder structure (via cPanel or FTP) is not needed to admin the site. Any installation of themes/plugins is done via admin access, at the admin-rolelevel. Any adding of images to the uploads folder is done via the admin panel Media entry, or when adding/editing a post/page (assuming you have privs/ro;e to do that). If your user is an admin-level role, then you should be able to add plugins (via Plugins, Add New), or add media (via Media page, or when adding/editing a page/post). If you aren't an admin-level role (which is different than logging into the admin panel), then your capabilities are limited. To understand roles and privileges, see < .
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, uploads" }
Foreach loop inside an array_merge I need to get a list of users display names in a dropdown menu. I have the query right, but I'm not sure how exactly to get my user foreach inside of an array. Here is the code I need to inject the users into: $data['settings']['advanced_options'] = array_merge($data['settings']['advanced_options'], [ [ "label" => "Dynamic Option 1", // This is field label "value" => "Dynamic Option 1", // This is field value ] ]); My users are currently inside of this array: foreach ($subscribers as $user) { $users[] = $user->display_name; } How can I get the users inside of the array? The label and value need to be the same as `$user->display_name`
Someting like this? foreach ($subscribers as $user) { $users[] = array( 'label' => $user->display_name, 'value' => $user->display_name ); } Then do the array_merge with $users
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, users, array" }
standard custom page template hierarchy for plugins I know woo-commerce has it's own way of providing custom php templates in a child theme for its various views. I'm wondering if all plugins adhere to a standard way doing the same. For example, I'm using a plugin with a template located at `wp-content/plugins/PLUGIN_NAME/templates/view-x.php`. Is there a standard location in my child theme that I can create my own custom view-x.php that will override the default version? Or does it vary from plugin to plugin?
There's no standard way to replace plugin files from a theme. It's up to each individual plugin to provide support for this, and many don't. If a plugin does support it, the correct way to do it would be specific to that plugin. You will need to consult a plugin's developer documentation to see whether or not they support anything like this, or an alternative.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, template hierarchy" }
Woocommerce digital download not working - database error Cannot add or update a child row: a foreign key constraint fails I'm having an issue when trying to download a digital product from Woocommerce. When clicking the download link/button on thank you page or woocommerce email, the link shows an error. After going to the PHP Error logs I found this: WordPress database error Cannot add or update a child row: a foreign key constraint fails. CONSTRAINT fk_wc_download_log_permission_id FOREIGN KEY (permission_id) REFERENCES wpdev_woocommerce_downloadable_product_permissions (permission_id) for query INSERT INTOwp01_wc_download_log` How can I solve this?
Just go to your database, drop table ending with "wc_download_log" (it might have a prefix). After droping the table deactivate Woocommerce and activate it again. That will solve the trick. Just be careful, drop just that table, be sure to back things up first. This post helped me solved this: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Timber: Theme class not fetching the right directory? I am new to using Timber, but I've wanted a way to use Twig inside Wordpress and ran across Timber, so I'm really excited! To note, I'm also using the starter theme provided by Timber. In playing around with things, I was starting out by just trying to set a logo image in base.twig. I added this line of code: `<img src="{{ theme.link }}/static/images/logo.png" />` This works as expected, except that the url given on output is: `<img src=" The issue to me is that `theme.link` goes one directory too deep. According to the documentation at < it should go to the root theme directory, but it's not in my case. Is there a way to set this or am I just missing something? Thanks in advance for your help!
@bocaj you're doing everything right. Unfortunately, we made a tweak to the starter theme which caused some unanticipated errors like the one you're seeing. If you can simply move the contents of the `/theme-name/theme/` folder into `/theme-name/` (including `style.css`, `functions.php` and others) the problem will resolve itself and links/paths will behave as expected. We tried to clean up the organization in a recent update. While it's cleaner, it caused this problem. I'm in the process of rectifying this so it won't lead to errors/questions in the future. Sorry for the confusion!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
How to limit the number of forgot password reset attempts in Wordpress? I'm using the Wordpress's built-in forgot password reset form and views. I want to limit the number of reset password email attempts. By default Wordpress allows you to send unlimited reset password emails and I want to set a limit. How can I do? This feature is only available in the Wordfence security plugin. I don't want to use Wordfence. I searched for other plugins but could not find them. I can actually write code. You can write a suggestion.
You need put the attempts on user meta, then do check every time user hit reset passwords. add_action( 'password_reset', 'my_password_reset', 10, 2 ); function my_password_reset( $user, $new_pass ) { $limit=5;// Set the limit here $attempts=(int) get_user_meta($user->ID,"reset_attempts",true); if($attempts>$limit){ //Do something in here, example redirect to warning page. wp_redirect( "/warning" ); exit; } update_user_meta($user->ID,"reset_attempts",$attempts++); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, forms, password, reset" }
How can i disable auto save & revisions with `function.php` in wordpress? I need disable auto save & revisions with function.php in wordpress. What should I do? thanks
define('WP_POST_REVISIONS', false); function disable_autosave() { wp_deregister_script('autosave'); } add_action('wp_print_scripts', 'disable_autosave'); Simple method
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions, revisions, autosave" }
How can I purge all post revisions except the latest 5? I know I can use `define('WP_POST_REVISIONS', 5);` to limit future post revisions to 5, but how would I go about purging all _existing_ revisions except the latest 5?
I just found this plugin that lets you specify how many revisions you wish to keep: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "revisions" }
Where in a Wordpress installation is the code for the default Gutenberg blocks located? I apologize if this has been answered already. I've spent several hours searching through the WordPress directories and documentation, and I haven't been able to find the code for the default Gutenberg blocks. Could anyone point me in the right direction? To clarify, I am specifically wondering where in the directory tree of a WordPress installation the blocks are defined.
If your end goal is to have a better understanding of how blocks work, I would encourage to install the gutenberg plugin instead. The block code within the WordPress installation itself is not intended to be read by end users nor directly modified. It's minified to save space. To answer your question, the code is stored in a couple places: * `wp-includes/js/dist/block-library.js` * `wp-includes/blocks/` If you wish to modify a core block, like a block style variation where you can modify the CSS of a particular block, do not modify those files, it's recommended to place your code in a custom plugin that you would make. (and depending how much you want to modify it, you may want to just create your own block).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "block editor" }
Can I mass change all admin emails for a multisite instance? I am managing a multi-site instance of Wp with 300 sites and so I am trying to see if this can be done automatically. I know individually I can go to each site and change the admin email value in the settings but is there a way to affect all sites? I have tried searching for this and can't seem to find a post discussing this exact topic.
Okay so thanks to the suggestion from Rup I got this to work and apply to all my sites locally (will double check this before using on live!) $blogs = get_sites(['public' => 1, 'orderby' => 'registered', 'order' => 'DESC', 'number' => 1000]); foreach($blogs as $blog) { $bid = $blog->blog_id; switch_to_blog($bid); update_option( 'admin_email', '[email protected]' ); update_option( 'new_admin_email', '[email protected]' ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "admin, email" }
I want to add string array to this function to filter displayed option in drpodown Wordpress wpallimport plugin This filter allows modifying the option shown in the options type dropdown for import The function is as follow: I want to add $custom_types as string array. function wpai_custom_types( $custom_types ) { // Modify the custom types to be shown on Step 1. $custom_types = array("woocommerce orders" , " posts") // Return the updated list. return $custom_types; } add_filter( 'pmxi_custom_types', 'wpai_custom_types', 10, 1 ); But it won't work
For posts & products: add_filter( 'pmxi_custom_types', 'example_import_show_only_posts_and_products', 10, 2 ); function example_import_show_only_posts_and_products ($custom_types, $type = '') { global $wpdb; $new_types = array(); foreach ($custom_types as $post_key => $post_obj) { if ( $post_key == 'post' || $post_key == 'product' ) { $new_types[$post_key] = $post_obj; } } return $new_types; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters" }
Why .mo .po files are not working with my site? I have a site with polylang installed with 3 languages. LV as default, EN and RU. For the PLURAR(polylang does not support it) strings translation I want to use poedit locally and then copy the translated mo/po files to the child theme /language folder. I tried to translate two string, copied the created mo/po files to the server, but the at the sites frontend transaltion is not shown. I have read multiple manuals and everything should be working, but nothing really happens. In my child themes /languages folder I even created two types of language code files lv.mo , lv.po and lv_LV.mo and lv_LV.po but nothing happens. My child themes function.php has definition of language folder. load_child_theme_textdomain ( 'greattheme', get_stylesheet_directory () . '/languages' ); What could be wrong with my setup?
As per Theme Handbook ⇒ Internationalization, you should call `load_child_theme_textdomain()` from within the `after_setup_theme` hook: function load_greattheme_textdomain() { load_child_theme_textdomain( 'greattheme', get_stylesheet_directory() . '/languages' ); } add_action( 'after_setup_theme', 'load_greattheme_textdomain' ); Make sure you name your *.mo and *.po files properly (follow the link above).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multi language" }
Password protected page with a form submits for me fine but for others redirects them back to the password prompt I have a custom coded page (using a page-xxx.php template). This page defined in the /Pages area of the WP admin has password protection. The content in my custom template is a form and so that is naturally what you see once past the PW prompt I've setup. The issue is that for some users (not me, I've never been able to recreate the issue) is that when they have completed the form, upon submitting it, instead of reloading the same page with a success msg it reloads the same page but it doesn't seem to remember that they have already got past the password prompt. Can anyone assist troubleshooting this? I don't know how a password protected WP page is functioning (via session vars/cookies?) but I had assumed that once past it, you could reload it/submit a form on it and you wouldn't need to then get past the PW again. Can anyone clarify this?
When a user logs into a protected page, WordPress sets a cookie. We can check for the existence of that cookie with this conditional: if ( isset( $_COOKIE['wp-postpass_' . COOKIEHASH] ) ) { // Do stuff. } Also, you should be aware that only one password is stored in cookies at a time, to the last entry viewed. By default, the cookie expires 10 days from creation If you need to change add_filter('post_password_expires', 'true_change_pass_exp', 10, 1); function true_change_pass_exp( $exp ){ return time() + 5 * DAY_IN_SECONDS; // 5 days }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "forms, password" }
Code works, but warning about call_user_func_array() appears I'm a newbie to Wordpress. I'm trying to make custom page that displays contact info for all users. I use code snippet provided by THIS POST. <ul> <?php $blogusers = get_users('blog_id=1&orderby=nicename'); foreach ($blogusers as $user) { echo '<li>Nick: ' . $user->user_nicename . '</li>'; echo '<li>Name: ' . $user->display_name. '</li>'; echo '<li>Email: ' . $user->user_email. '</li>'; } ?> </ul> It works, but it also shows this warning at the top: Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'yoursite_pre_user_query' not found or invalid function name in C:\xampp\htdocs\mytheme\wordpress\wp-includes\class-wp-hook.php on line 287 What should I do to resolve this?
Somewhere in your theme or plugins, you must have a line like this `add_action( 'something', 'yoursite_pre_user_query' )`. Find it and remove or fix it. Also, the get_users function has since been updated. Your first parameter must be an array. <ul> <?php $blogusers = get_users( array('blog_id' => 1, 'orderby' => 'nicename') ); foreach ( $blogusers as $user ) { echo '<li>Nick: ' . $user->user_nicename . '</li>'; echo '<li>Name: ' . $user->display_name. '</li>'; echo '<li>Email: ' . $user->user_email. '</li>'; } ?> </ul>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "callbacks" }
How to dequeue script on woocommerce product? I'm trying to dequeue some scripts on woocommerce product, but for some reason I can’t find a way to check for a single product. `is_singular('product')` doesn't work for some reason. The dequeue itself works without the checks, e.g.: add_action( 'wp_enqueue_scripts', 'my_custom_scripts', 100 ); function my_custom_scripts() { wp_deregister_script( 'wp-mediaelement' ); wp_deregister_style( 'wp-mediaelement' ); }
< you can try `is_product()` its on the woocommerce docs
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
How to avoid duplicate dependencies in Gutenberg blocks The WordPress Gutenberg block build script uses wordpress/dependency-extraction-webpack-plugin to build the blocks without WordPress dependencies being repeated but what about other dependencies? If I build a plugin with 10 blocks and they all re-use dependencies, the WordPress build script will embed the dependency in every block bundle. Is there a good way to handle this without having to re-create webpack build by myself?
WordPress Dependency extraction plugin `@wordpress/dependency-extraction-webpack-plugin` basically makes your ES6 dependency imports use WordPress scripts instead of adding them to the bundle over and over. This makes modules registered and enqueued in WordPress (including but not limited to `jquery`, `moment` and `react` and `wp.*` modules) to be properly excluded from builds. You can add additional dependencies to be excluded (make sure you register/enqueue in WordPress) with `requestToHandle` callback. For example for excluding say `react-sortable` component from build registered as `react-sortable` script in WordPress (PHP), module.exports = { plugins: [ new DependencyExtractionWebpackPlugin( { requestToHandle: function ( module ) { if ( module === 'react-sortable' ) { return 'react-sortable'; // WordPress script handle } } } ), ] }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "block editor" }
If I use WordPress REST API V2 and someone makes an app using it. Will my site count the posts views from the APP? And if not, then how? I'm making a mobile app on both `Android` and `iOS` and I can fetch the posts and even open them but I don't know if `WordPress` will count the new views from my `App` Will `WordPress` do that automatically? If not, then how can I do such a thing? I'm a beginner so please, be kind
**WordPress does not count views or traffic,** it's not a part of WordPress' feature set. Plugins and code snippets can add this but it's highly specific to the service you're using. Usually for apps you will need to integrate tracking into the app itself. But how you would do that is specific to the **service** you choose, not WordPress. To answer this you will need to consult the documentation for the service you've chosen to integrate. _There isn't a WordPress based answer._
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "rest api, json" }
Is it possible to have "two" sets of tags? I have several Custom Category Taxonomies but what I am wondering is, if it's possible to have a second set of "tags"? I am using my tags for a very specific purpose (the naming of cities) so I don't want to mix up that with what I need for another set of tags. Sure, I can create another Category Taxonomy but the quantity of items means that a "tag" environment might be better... Thanks
No, you can't have 2 groups of a singular taxonomy, so there is no way to separate post tags from each other without introducing hierarchy. **However** , you could register a `city` taxonomy and declare that it's non-hierarchical. That's the primary difference between categories and tags. Categories have hierarchy, tags do not. Any taxonomy you register this way will have the same UI as tags. For example, I registered a talk tag taxonomy for a CPT on my own site: ![enter image description here]( I just set `hierarchical` to `false` when I registered it. In general, don't repurpose tags and categories for things, just register a new taxonomy, it saves a lot of trouble and makes your life easier.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, tags" }
WPML custom string translation get outside of container I am trying to add a custom string to translate in wpml, but when I use the _e(...) the content jumps outside of container if I use like this: echo '<h1>' . $month . ' ' . $day . '</h1>'; the html is ok: <h1>September 29</h1> but if I use with translation like this: echo '<h1>' . _e($month, 'simultan') . ' ' . $day . '</h1>'; the translated string jumps out of h1: Septembrie<h1>29</h1>
When you use `_e` your echoing the translated string. But you already have an `echo` so just use `__(`. This is the correct code for your example echo '<h1>' . __('September', 'simultan') . ' ' . $day . '</h1>'; If you want to add variables in your translations you should use `sprintf` like this: $date = sprintf ( __('%s %d', 'simultan'), $month, $day ); echo '<h1>' . $date . '</h1>'; You might want to also have a look at date_i18n function since you are translating dates. Reference: Wordpress I18N sprintf manual
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "translation, plugin wpml" }
Is it possible to populate my wordpress site with many random posts for testing purposes? I have just deployed the Wordpress application on my Kubernetes cluster following the instructions from < Now I would like to populate the Wordpress database with a lot of posts for testing purposes. I do not really care about the content of these posts. As far as I am concerned they can be completely random. All I care that there are a lot of them. Is there a way to do it?
As I can see you are using Kubernetes. There are few routes you could go. 1. **REST API:** Write a light script (nodejs or php) that creates fake data and sends to rest route to create posts. You can then use cron hit rest route for creating posts. 2. **Plugin:** Check Fakerpress plugin, I haven't used it but it looks like something you can use.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "automation, testing" }
Is it possible to place a WordPress widget into the main page layout? As the question suggests, can a widget be placed with the main body of a page rather than in a side-column? I guess this is plugin-specific but generally, if the functionality is placed on a side-bar then does that "restrict" it to that section of the layout?
of course you can, you can place widgets wherever you want in your page: 1. Define them in a callback function in your functions.php file which calls the `register_sidebar()` function, and then hook that callback to the 'widgets_init' action hook, also in your functions.php file. 2. On the page where you wanna use it, wherever you wanna use it, print the widget with this code, by using the value you specified as the 'id' parameter when calling `register_sidebar()` in your callback: <?php if ( dynamic_sidebar( 'id_of_ur_widget' ) ) : else : endif; ?> Don't get distracted by the name of the function, `register_sidebar` doesn't mean that your widget is a sidebar, it's just the not-so-smartly chosen name of the wp function you use to create a custom widget.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
WP_safe_redirect not working Instead of the project archives in my Divi theme being at `/project_category/[category name]/` I want them to go to `/portfolios/#[category name]`. I modified the following code from this question and added it to my child theme's **functions.php** file. function my_category_redirect() { if ( is_category( ) ) { $category = get_queried_object(); $cat_id = $category->term_id; $url = site_url( '/portfolios/#' . $cat_id); wp_safe_redirect( $url, 301 ); exit(); } } add_action( 'template_redirect', 'my_category_redirect' ); However this is not working. The project categories are still going to `/project_category/[category name]/`. I can't tell if the **my_category_redirect** function is even being called. Any help is much appreciated!
Your action callback probably gets called, but it could be that the if-statement that just fails. Are you using the default "category" taxonomy ( _i.e. Dashboard > Posts > Categories_) or a custom taxonomy ( _i.e. Dashboard > {my-post-type} > {my-taxonomy}_) as the project category? If you're using a custom taxonomy, then you should use is_tax('my-taxonomy') instead of is_category() as the latter checks for the default category, not custom ones. But, you can temporarily add a `die('it works');` to your callback also, before the if statement, to verify that it gets called.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, wp redirect" }
Fatal Error when trying to load Permalinks page on WP admin I'm receiving the below error when trying to access the Permalinks section on the WP admin. The page does not load and shows the error message instead. I cannot understand what this means or what has to be done. Any ideas are appreciated and thanks in advance. Fatal error: Uncaught Error: Call to undefined function apache_get_modules() in /home/customer/www/mydomain.com/public_html/wp-includes/functions.php:5283 Stack trace: #0 /home/customer/www/mydomain.com/public_html/wp-admin/includes/misc.php(17): apache_mod_loaded('mod_rewrite', true) #1 /home/customer/www/mydomain.com/public_html/wp-admin/includes/misc.php(46): got_mod_rewrite() #2 /home/customer/www/mydomain.com/public_html/wp-admin/options-permalink.php(71): got_url_rewrite() #3 {main} thrown in /home/customer/www/mydomain.com/public_html/wp-includes/functions.php on line 5283
The error is related with the Hosting Server PHP Version. So if you are on PHP 7.3.XX try downgrading to 7.2.xx or 7.1.xx and see if that helps! P.S. I was facing the same issue and had to downgrade to PHP 7.1 to fix it!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, wp admin, errors, fatal error" }
blog post not accesible on click im just developing a web page with the gutenbiz theme and im changing a lot of the features through the elementor webpage builder, i have my blog page set as a blog but the post im editing them on the elementor and then im publishing them,the problem now its that i cannot access this post only on elementor and when im clicking on the blog post they are not responsiVE they are not sending me to the actual post. so in my blog archives the picture and the description of the post appears but then its empty on the click of read more it doesnt go anywhere. i hope you guys can help me with this issue thank you in advance
Have you tried to disable some plugins and tried again it seems to look like a plugin conflict I will say. however, I might be wrong.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, options, archives, blog" }
Error - 'create_function is deprecated' Our WP Debug is report that 'Function create_function() is deprecated'. Any idea how to rewrite this code to not include create_function ? self::register_form_init_scripts( $form, $field_values, $ajax ); if ( apply_filters( 'gform_init_scripts_footer', false ) ) { add_action( 'wp_footer', create_function( '', 'GFFormDisplay::footer_init_scripts(' . $form['id'] . ');' ), 20 ); add_action( 'gform_preview_footer', create_function( '', 'GFFormDisplay::footer_init_scripts(' . $form['id'] . ');' ) ); }
You no longer need to use `create_function` you can instead just use an anonymous function: add_action( 'gform_preview_footer', create_function( '', 'GFFormDisplay::footer_init_scripts(' . $form['id'] . ');' ) ); Should be: add_action( 'gform_preview_footer', function() use ($form){ GFFormDisplay::footer_init_scripts($form['id']); }); <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, javascript, jquery" }
Redirecting specific sites to HTTP in WordPress Multisite What I need to do is redirect only some of the sites in my multisite installation to use HTTP instead of HTTPS. Currently my setup has been so that every site redirects to HTTPS but I can't seem to figure out how to force only some sites to go over HTTP. How would I achieve this?
Turns out what I tried before actually worked but my browser forced the site to https from old habits (cache). If anyone else is having problems with this, here is what I did: * Make sure the URL does not have **s** in it in your Sites page in Multisite Dashboard * Make sure you don't have a plugin installed forcing HTTPS on (I had iThemes Security so I had to disable the SSL option from there) * Make sure you change all the URLs in the database from https to http for the specific site (use a plugin like Better Search Replace that has support for changing serialized data and take backup of your database before doing it!) * If you're still getting redirected to https, make sure you don't have antivirus program installed that checks SSL certificates (I had Bitdefender's option on to check for SSL certificates) * After doing all of the above, try with different browsers and/or devices and everything should work now
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, redirect, https, http" }
Is there a delay to include call function modification in a scheduled cron task? I´m testing my cron task. I´m not sure but it seems to be the effect of a previous code. So, I´m wondering when you modify you call function and you run now your cron task (I´m using WP Control) and you load a page, the code applied is not the most recent code you upload. It´s right or wrong ? What happens excalty, call functions are cached ?
> What happens excalty, call functions are cached ? **They do not get cached.** When you schedule a cron job, it stores a record in the database to trigger a hook with certain parameters at a time/date. No code is cached. So when that time comes, the code is loaded and run from the disk as it is at that time, not when it was scheduled. For example, if I schedule a cron job for tomorrow that writes the word "hello" to a file, then immediately change the function to instead send an email, when the cron job runs an email is sent.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "cron, testing" }
WooCommerce is_product_category() not working I'm trying to add text to the product short description by category. So for example, for all Cake Toppers, I want to add to the bottom of the short description to show "This is a cake topper". For all products which are not cake toppers, I want to show the text "Not a cake topper". This is the code I'm using: add_action( 'woocommerce_single_product_summary', 'product_short_description_by_category', 20 ); function product_short_description_by_category() { if( is_product_category('cake-toppers') ){ echo '<p>A cake topper</p>'; }else{ echo '<p>NOT CAKE TOPPER</p>'; } } But all products, including cake topper, show "THIS IS NOT A CAKE TOPPER". What am I doing wrong here? "cake-toppers" is the slug for the category name. Site at: < Any help is greatly appreciated!
is_product_category() – Check If Current Page is a Product Category Try this add_action( 'woocommerce_single_product_summary', 'product_short_description_by_category', 20 ); function product_short_description_by_category() { if( has_term( 'cake-toppers', 'product_cat' )){ echo 'A cake topper'; } else{ echo 'NOT CAKE TOPPER'; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, woocommerce offtopic" }
how to make has_block() see inside blocks too I am using `has_block()` to check if post has a specific block type but it does not see blocks inside another blocks, like columns block. So, how to make it find a gallery inside the column?
It should, because `has_block( 'gallery' )` uses source `strpos()` to determine if the post content has the `<!-- wp:gallery` string.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, block editor" }
Change lost password url to a mailto URL in Wordpress can you help me, how can I change the lost password link to an email action with specified subject? I found that in the functions.php I can add a new filter like this: add_filter( 'lostpassword_url', 'my_lostpassword_url', 10, 0 ); function my_lostpassword_url() { return site_url('/password-reset/'); } But I dont know how can I implement the mailto action instead of the new url. Can you help me?
This answer assumes you're running PHP 5.3 or above. Use the filter code below in-place of your code that you quoted above. Then simply update the variables provided so that it's sending to the correct email address and with the particular subject you'd like. add_filter( 'lostpassword_url', function () { $email_to = '[email protected]'; $email_subject = 'Help I lost my password'; return sprintf( 'mailto:%s?subject=%s', $email_to, $email_subject ); }, 100, 0 ); **Note** : You cannot change the anchor text "Lost Password" that is used in the link.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, filters" }
Getting wp_timezone undefined within a namespace My workaround at the moment, within a shortcode, is to just copy the WP native code to get the Timezone within my (namespaced) class: new \DateTimeZone( $this->wp_timezone_string() )); private function wp_timezone_string() { $timezone_string = get_option( 'timezone_string' ); if ( $timezone_string ) { return $timezone_string; } $offset = (float) get_option( 'gmt_offset' ); $hours = (int) $offset; $minutes = ( $offset - $hours ); $sign = ( $offset < 0 ) ? '-' : '+'; $abs_hour = abs( $hours ); $abs_mins = abs( $minutes * 60 ); $tz_offset = sprintf( '%s%02d:%02d', $sign, $abs_hour, $abs_mins ); return $tz_offset; } But I'm wondering why I can't just call make a call to `\wp_timezone()` (escaped for namespace). Is it because the file that contains that class hasn't loaded yet?
Thank you Tom J Nowell for the insightful comment above. Turns out that wp_timezone is a _relatively_ recent addition to Wordpress, and didn't exist in the version of WP I was developing in. It was added, as the Changelog says, in `v5.3`. I was using `v5.2`. The function itself: function wp_timezone() { return new DateTimeZone( wp_timezone_string() ); } Simpy wraps the result of `wp_timezone_string` in a native php `DateTimeZone` object. The `wp_timezone_string` was also added in `v5.3`. Since this is a brand new plugin, I'm not going to support older version of Wordpress. For pragmatic reasons, and in solidarity with the movement to encourage users to upgrade WP environments, I have also opted to not support versions of php (like `v5.6`) that are past their End of Life.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "timezones, namespace" }
Is this a hack? WordPress Usernames of every website we have changed into one single name automatically? We host a lot of WordPress websites, today we noticed that almost every WordPress website we hosted changed their users' usernames into one single name, not only one user all the users of a website is changed into one single name but for some reason, the password is still not changed. Is this a possible hack?
Most definitely, all user names changed to admin I'm guessing ? I had this happen to an old website before. If available, I recommend recovering from a backup just in case they injected code in your posts / pages. I also recommend updating your plugins, templates and WordPress to the latest version and removing old unused plugins / templates.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, hacked" }
Cron jobs when running multiple instances on the same DB I have a user using my plugin that has multiple AWS instances hosting WP and pointing to the same database. One of the jobs of my plugins is to run a large number of small jobs. I was thinking of using `wp_schedule_single_event` to schedule the jobs but I'm not sure how that will work with multiple instances. Each job will have unique parameters so there won't be any duplication. **Question** : Will each instance try to run the same job or will WordPress be able to resolve this so that each job is only run once?
> Question: Will each instance try to run the same job Yes! If you have 5 machines running the same site, they'll all try to run the cron job. It'll be inconsistent, but if machine 1 triggers WP Cron and there's an event ready to run, and machine 2 triggers WP Cron, then machine 2 will also see that event if the timing is right and attempt to process it. > or will WordPress be able to resolve this so that each job is only run once? Nope, it can't. You can try adding a lock of sorts, but it can't fix the problem, only prevent it in some scenarios * * * What you really need is to disable WP Cron in your config and run it via a system level cron job on a single machine. Or better yet, install a cron service such as cavalcade
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp cron, cron" }
How to hide "You are now logged out" message on Wordpress login form? **Expectation:** I want to hide the login message that shows up on the Wordpress login form after a user has logged out. Added screenshot of the message that I am trying to hide. < Wordpress Version 5.4.2 Wordpres theme: Oceanwp 1.8.9 I have used the below mentioned code in the functions.php file of my theme. add_filter( 'wp_login_errors', 'my_logout_message' ); function my_logout_message( $errors ){ if ( isset( $errors->errors['loggedout'] ) ){ return null; } return $errors; } **Error Recieved:** I have provided the screen shot of the error that I have recieved. < Also, the login form isn't visible after user logout.
The cause of your error is that the filter receives and is expected to return a `WP_Error` object, `null` is not an error object. We can confirm this via the docs, and enforce it via type hinting: function my_logout_message( \WP_Error $error ) : \WP_Error { Additionally, if your code had worked, all errors would be eliminated, not just the logout message. There would be no way to tell a user their password was incorrect, that a password reset email or a confirmation email was on its way, etc With this in mind, the `WP_Error` say there is a `remove` method, so we can remove the loggedout error if it's present: $error->remove( 'loggedout' ); I do not recommend this though
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "logout" }
WooCommerce display price before add to cart I'm trying to make the WooCommerce product price display before the "add to cart" button, however, I cant seem to get the price to display. Here is the code I'm using in my **functions.php** add_action( 'woocommerce_before_add_to_cart_button', 'misha_before_add_to_cart_btn' ); function misha_before_add_to_cart_btn(){ echo '<div class="btn-price">'. $product->get_price_html().'</div>'; } Please would someone be able to point out where I'm going wrong with the code that I'm using above.
The variable $product is undefined when your function runs, you need to access the object to call the method get_price_html(). One way to do it is to call the global variable: add_action( 'woocommerce_before_add_to_cart_button', 'misha_before_add_to_cart_btn' ); function misha_before_add_to_cart_btn(){ global $product; echo '<div class="btn-price">'.$product->get_price_html().'</div>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, woocommerce offtopic" }
How to change the Default block in the block-editor away from the paragraph block? When I open the block editor on a new post or page or edit an existing post or page, the Default Gutenberg Block is the paragraph block. How do I change this to a gallery block or another block?
You can use the Gutenberg Block Template it is used to have a content placeholder for your Gutenberg content. < <?php function myplugin_register_template() { $post_type_object = get_post_type_object( 'post' ); $post_type_object->template = array( array( 'core/image' ), ); } add_action( 'init', 'myplugin_register_template' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "block editor" }
How can I enable IDE integration (autocomplete) for WordPress test suite When testing a theme or plugin, you can use WP-CLI to scaffold the test suite setup, `wp scaffold plugin-test plugin`. So is there a good way to integrate an editor/IDE (VS Code in my case) so that autocompletion (method signatures, etc) works within the tests? Since the test library is installed in `/tmp/` the editor is not indexing those files and thus thinks classes and functions are missing.
In order of preference: 1. `composer require wp-phpunit/wp-phpunit --dev`. Depending on the IDE you use you might need to mark the package in `vendor/` as a source directory. 2. Each IDE allows you to add definitions from external libraries. In PHPStorm it's `Settings → Languages & Frameworks → PHP → Include Path`. 3. Just copy the files over to some directory in your project and exclude them with `.gitignore` (if you use Git for version control).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "testing, unit tests, ide, integration tests" }
Page template option missing I checked everything suggested in that response: "page attributes" option is checked, template file is located at theme root folder, I tried several file encoding options in my text editor (UTF8 with or without BOM), I tried switching to another theme then back to my custom theme, I do have the right stuff on top: <?php /* Template Name: Page Actualites */ ?> Why am I still not seeing the page template dropdown list?
The page was set as the posts page in `settings > reading`, which prevents from chosing a specific page template since this setting automatically assigns `index.php` as the page template for that page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, page template" }
Only show posts with a specific term of an associated taxonomy in a custom post type archive I have a custom post type "movie" with a taxonomy "period". The "period" taxonomy has two terms: "current" and "past". Is it possible to only show posts with the "current" term in the "movies" archive page (`archive-movie.php`)? If so, how? I've used the `template_include` filter before to show templates conditionally, but I'm not sure if this hook is useful in this case. Any ideas?
Try adding to functions.php function filter_movies( $query ) { if( !is_admin() && $query->is_main_query() && $query->get('post_type') == 'movie') { $tax_query = array( array( 'taxonomy' => 'period', 'field' => 'slug', 'terms' => 'current', ), ); $query->set( 'tax_query', $tax_query ); } } add_action('pre_get_posts', 'filter_movies', 9999);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, filters, archives" }
Posts Page shows Classic Editor interface not Gutenberg I have an issue, When I open Pages->Posts Page (the page which I pinned for latest posts) the classic editor interface shows up. I can't understand should it be by default? Because in my localhost it shows up in Gutenberg interface, but not on my hosting. Can someone check it, please? I have wordpress version 5.5.1. I tried to deactivate all plugins, but the same result. I haven't any errors. Thanks in advance.
check you don't have classic editor installed, remove completely. if not, **try to re-install wordpress** , sometimes it solves mysterious issues. did you tried switching themes? is it a multi-site?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, block editor" }
Wordpress JSON API nonces and Vue development server As stated in the official docs, the JSON API CSRF protection only works from within Wordpress. > It is important to keep in mind that this authentication method relies on WordPress cookies. As a result this method is only applicable when the REST API is used inside of WordPress and the current user is logged in. In addition, the current user must have the appropriate capability to perform the action being performed. Which means anytime I start a Vue development server to build my Vue app, the API will refuse my requests, as there's no WP environment that could provide me with a nonce that I could then pass to the API. Anybody found a workaround for that problem?
For making authenticated API requests from a third party app, you'll need to install a plugin to give you different methods of authentication. The most convenient but less secure is Basic Authentication: < it's appropriate for a local development environment. This allows you to make authenticated requests by passing username and password in the body of the POST request. I don't have an example in Vue, as I'm not familiar with its syntax.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "nonce" }
Hide wordpress field if data is empty in post! I'm using this code to show my field: <?php echo '@ ' . get_post_meta(get_the_ID(), 'Author:', true); ?> When I add a field in my posts it shows it with no problem but for posts that I don't add any fields it shows "@". What I can do to not show anything if field is empty in a post? Examples: field with data \- field with no data [Warning: Both links are NSFW +18]
You can just make a simple check, to see if you have this meta $author = get_post_meta(get_the_ID(), 'Author:', true); if ( $author ) : echo '@ ' . $author; endif;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, posts, customization, code" }
Does Wordpress provide different levels of logging? (I come from a Java development background, so please excuse my lack of PHP and WordPress knowledge.) My understanding of logging in WordPress is that it must first be enabled in `wp-config.php` and then calls to `error_log()` can be seen and read. But logging is not just about errors. It is very useful when developing and debugging to be able to log. For this reason many Java logging libraries (e.g. SLF4J) provide the ability to log at the following levels: * TRACE (lowest) * DEBUG * INFO * WARN * ERROR (highest) You can then configure the logging level that you wish to see in the log. For example when developing you would like to see DEBUG and above, but when running in production you probably just want to see WARN and above. Is there something equivalent in WordPress? Logging everything as an error does not seem right.
Your understand is correct. WordPress doesn't have levels beyond Warning and Error from PHP. Wonolog, a WordPress wrapper for Monolog, expands the default error logging into the levels you require. You can also expand the logging by adding your own custom debuging alerts and level.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "logging" }
chose category in plugin I am making a plugin to upload records and I want to put the option to choose category, also I would like those categories to be the ones that are normally created with wordpress, but I don't know if can How do I put the option to choose category in the form?
IDs are your friends. Get the category list using get_category (i'm assuming we are talking about the in-built Wordpress "category" taxonomy, which slug is _category_ ). $categories = get_categories( array( 'hide_empty' => false // This is optional ) ); Use the obtained category list in the output of your <select> field: <?php // get $selected_term_id from somewhere ?> <select name="category_id"> <?php foreach( $categories as $category ) : ?> <?php $is_selected = $category->term_id == $selected_term_id ? 'selected' : ''; ?> <option value="<?php esc_attr_e( $category->term_id ); ?>" <?php echo $is_selected; ?>><?php esc_html_e( $category->cat_name ); ?></option> <?php endforeach; ?> </select>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Output all terms in a custom taxonomy and add a "active" class only to the ones attached to the current post I want to output all the terms in my custom taxonomy and at the same time add a class to any of these that are attached to the current post. I'm doing this in a custom shortcode that displays on each single post page. I've used get_terms() to show all the terms in the taxonomy but I can't work out how to check if each term is attached to the current post. $terms = get_terms( array( 'taxonomy' => 'package', 'hide_empty' => false ) ); if (!empty($terms) && ! is_wp_error( $terms )) { echo '<ul>'; foreach ($terms as $term) { echo '<li>' . $term->name . '</li>'; } echo '</ul>'; }
> how to check if each term is attached to the current post You can do that using `has_term()` which defaults to checking on the current post in the main loop, hence you can omit the third parameter (the post ID). So for example in your case: $class = has_term( $term->term_id, $term->taxonomy ) ? 'active' : ''; // like this //$class = has_term( $term->term_id, 'package' ) ? 'active' : ''; // or this echo '<li class="' . $class . '">' . $term->name . '</li>';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, terms" }
Advice on image heavy site, compression and slow page loads I have a videogame fansite. By its nature it's image intensive. No matter how I capture the images, process them, run them through compression plugins like Smush or standalone software, I cannot reduce them enough so they don't drag my page load times into the dirt. At least not without the images looking like crap. I'm using Siteground web hosting platform. I need advice on how to compress my images more without losing too much quality. If possible. My most recent idea was seeing if images could be stored somewhere (other than my webhost servers) that might be faster. It turned out to be too complicated for my skill or comprehension level. Any advice is welcome. Including directing me somewhere that could help more.
I think that the best option, as you already pointed out, is to host your images elsewhere. We use an Amazon AWS S3 account and with the WP Offload Lite plugin the process is quite strightforward
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, compression" }
How is the author's name given a different color? Author's and visitors' names use the same color in comments.The point here is that the color of the author's name is different in the comments. For example, in visitor comments, name is red. But, the name of the site author should be gray. (Only in comments) I know an ID needs to be added for the author's comments. However, I could not add this ID. Therefore, the style I gave in style.css does not work either. I just tried this in css, but that didn't work. .comment-list .bypostauthor .fn {color: gray;} How can I achieve this?
You wrote `.comment-list` but that's not the class, it's `.commentlist`. You may also need to target the anchor link inside that tag explicitly to override link colours
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta, comments, author, comment meta, wp comment query" }
how to check if an element in an html file exists in another html file? Imagine that I have an HTML file as one of my WordPress blog pages (let's call it page B). I want to write an if condition inside a tag on page B to check if a specific element exists on another web page (page A). My question is what function should I choose to check this condition? Should I also import the HTML file of page A inside page B? And what should I do on the server-side, if I have to? Thanks
If I understand you correctly, and you want to find an HTML element inside another page, you need to use some HTML parser. Take a look at < or < I believe there are more tools that can help you with this. On page B you load page A as a remote document by URL, then parse it and look for the desired HTML element.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, html, html5" }
Show content without a post I am writing a plugin, and want to show an about page, but without a post/page record. So if, the url < is entered, my 'hardcoded' content is shown. A bit like the login page, there is no login post, but the login screen displays. Which hooks would I need to use to catch the url, and then output my content without getting a 404?
you can try 'request' hook: add_filter('request', function( $vars ) { $request = urldecode($_SERVER['REQUEST_URI']); if ( stristr($request, '/YOUR_SLUG') != false ) { ... } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, permalinks" }
Multisite: How to get a list of installed languages In a network install there is a language setting which will let the super admin user install a language from a list of available languages. How can I get a list of the **installed** languages? For example, en_US, hi_IN, hu_HU, ja
That's get_available_languages(): > Get all available languages based on the presence of *.mo files in a given directory.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "multisite, localization" }
ACF - Pick first or second value from comma separated values Everyone, I have just started using ACF and mostly using feature to show data uploaded from csv file. Everything is working fine. But in some fields i have data in the form of comma separated values such as Fiery Red, Leafy Green, Sky Blue. My current output works as follows. Available Colors - Fiery Red, Leafy Green, Sky Blue I want to achieve; Available Color - Fiery Red Available Colors - Fiery Red, Leafy Green Thank you !
You can use the `explode()` function to split a string into the array of values So you have a string of colors, separated with a comma, where the comma is a delimiter: $colors = 'Fiery Red, Leafy Green, Sky Blue'; Now use the `explode()` function (here is a link to the documentation) to convert it to the array: $colors_array = explode( ', ', $colors ); As a result, you will get: array(3) ( [0] => string(9) "Fiery Red" [1] => string(11) "Leafy Green" [2] => string(8) "Sky Blue" ) Now, when you have an array of values, you can display only the first value: echo $colors_array[0]; or the first two elements: $output_array = array_slice( $colors_array, 0, 2 ); echo implode( ', ', $output_array );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "advanced custom fields" }
"The editor has encountered an unexpected error" After add defer tag to java script I added below script to add defer tag in javascripts. Once it added to function.php Gets error on create post "The editor has encountered an unexpected error." I cannot create or edit post. How can i add defer tag to javascripts without affecting to the editor. I don't have mush experience in coding. Thanks. add_filter( 'script_loader_tag', function ( $tag, $handle ) { if ( 'jquery-core' !== $handle ) return $tag; return str_replace( ' src', ' defer="defer" src', $tag ); }, 10, 2 ); **console errors are** > TypeError: d.media is not a function wp-includes/js/dist/media-utils.min.js?ver=9ad24b42cc69f241229ded4dc61409fb:2:6432) wp-includes/js/dist/vendor/react-dom.min.js?ver=16.9.0:63:107) and more..
Seeing as your aim is to improve loading on the front end, the best approach would be to simply not add the `defer` attribute when loading in the admin area, like so. add_filter( 'script_loader_tag', function ( $tag, $handle ) { if ( 'jquery-core' !== $handle ) { return $tag; } if ( ! is_admin() ) { $tag = str_replace( ' src', ' defer="defer" src', $tag ); } return $tag; }, 10, 2 ); As the editor has a number of scripts, often depending on other scripts already loading, it's generally not a good idea to try and use `async` or `defer` in the admin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, javascript, jquery, wp enqueue script" }
Homepage template and url changed? when I activated the theme. it is only one page. the navbar links are Home #About #Services #Contact the problem when I make template name on the frontpage <?php /* Template Name: front-page */ get_header(); ?> then I created a page from the dashboard called Home it added slug /home at the end of the url so the website url differed because of this homepage template. it added the home slug the url. I need to remove /home slug. just want the same link without changing. what should I do, please? to make template for homepage without changing the url of the website? and many thanks in advance.
Check this article on how to create a static homepage in WordPress <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks" }