INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Display out of stock products in WooCommerce
Is there a way to still display out of stock products on my WooCommerce website? | Go to WooCommerce / Settings / Products / Inventory – turn off “Out of Stock Visibility – Hide out of stock items from the catalog” | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, woocommerce offtopic, e commerce"
} |
How to get blocks with same heigh in columns?
I put 3 paragraph blocks in a 3 columns block. I'd like the paragraph to have the same size (and ideally to have the vertically centered). Is there a way to achieve this with Gutenberg?
![Here is what I have so far](
I tried using the `diplay:flex` attribute with CSS. But it didn't work.
Thank you for your help. | Finally, I found a solution with flex attributes:
I defined the following CSS rules :
.flexColumn {
display: flex;
flex-direction: column;
align-self: auto !important;
}
.flexItem {
flex-grow: 1 !important;
}
I can now apply `flexColumn` to the columns and `flexItem` to the items that I want to grow to fill the empty space:
![enter image description here](
For some items I also need to deal with top/bottom margins (`margin-top:0`) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "block editor, columns"
} |
How to remove https:// from shortcode generated url
I am using the following code to create a shortcode that generates the url of my website:
add_shortcode( 'base_url', 'baseurl_shortcode' );
function baseurl_shortcode( $atts ) {
return site_url();
}
However, when the url is generated it has ` at the beginning of it. Is there a way to remove this please? | That would be: `return parse_url( get_site_url(), PHP_URL_HOST ) );`
Explanation:
get_site_url is the WP function that returns the full url (it is the function that `site_url` relies on). parse_url is a PHP function that splits the url into several components and returns one or more of them. In this case it returns the hostname, which you seem to be looking for. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "shortcode"
} |
querying to custom field over ACF REST API
Iam using the "ACF" plugin with "ACF to REST API". I found a solution for querying a custom field over REST API.
I inserted this into my functions.php:
add_filter( 'rest_{type}_query', function( $args ) {
$args['meta_query'] = array(
array(
'key' => 'my_field',
'value' => esc_sql( $_GET['field'] ),
)
);
return $args;
} );
Url: /wp-json/wp/v2/posts?field=test The wildcard {type} can be: post | user | comment | attachment | custom post type | taxonomy
This solution is not perfect. Once this code snipped is added, the filter works but if you go to /v2/{type} <\-- which usually lists all, this stops working.
Any solution for that? | I got that working :)
add_filter('rest_myRoute_query', function($args, $request) {
$fields = array('myCustomField');
foreach ($fields as $field) {
if (! empty($request[$field])) {
$args['meta_query'][] = array(
'key' => $field,
'value' => esc_sql($request[$field]),
);
}
}
return $args;
}, 10, 2); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, wp query, custom field, rest api"
} |
Wordpress keep logged in after browser close
I want my users to be logged in even after they close the browser. I have tried below code but nothing happens, it still logging me out after closing the browser.
function keep_me_logged_in_for_1_year( $expirein ) {
return 31556926; // 1 year in seconds
}
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' );
How will I keep my users logged in even after they close the browser? | You can use the following 2 filter hooks
add_filter('auth_cookie_expiration', 'auth_cookie_expiration_filter_5587');
function auth_cookie_expiration_filter_5587()
{
return YEAR_IN_SECONDS * 5;
}
and:
add_filter('auth_cookie_expiration', function () {
return YEAR_IN_SECONDS * 5;
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "cookies, session"
} |
plugin not loading my css and js
Hi I'm using the standard way to load styles and scripts within my plugin. But I have no clue why it's not working. It's not shown in the network tab nor in the `<head>`. Can this cause issues when overriding templates?
add_action('wp_enqueue_scripts', 'add_styles_scripts');
add_action('admin_enqueue_scripts', 'add_styles_scripts');
function add_styles_scripts()
wp_enqueue_style('rs_css', plugin_dir_url(__FILE__) . 'style/default.css', array());
wp_enqueue_style('rs_fullscreen_css', plugin_dir_url(__FILE__) . 'style/fullscreen.css', array());
wp_enqueue_script('rs_js', plugin_dir_url(__FILE__) . 'style/default.js', array('jquery'));
wp_localize_script('rs_js', 'wordpress_data', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_filter( 'template_include', 'render_custom_template' );
function render_custom_template( $template )
{
add_styles_scripts(); | The fix was really easy. The template I was trying to load, did not have wp_head() in it. So ofcourse no JS/CSS was loading in. Thanks for the help everyone! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, wp enqueue script, wp enqueue style"
} |
wp_footer content appearing in admin area
I am using the following code and I can't see anything in the footer of my site on the front end where the wp_footer function is called. It does, however, appear before the opening `<!DOCTYPE html>` in the admin area.
function xyz_footer_print() {
echo 'footer script here';
}
add_action( 'wp_footer', xyz_footer_print() ); | That's because you're not using `add_action` correctly, what you've written is functionally the same as this:
function xyz_footer_print() {
echo 'footer script here';
}
$value = xyz_footer_print();
add_action( 'wp_footer', $value );
`xyz_footer_print()` immediately runs the function and returns nothing. As a result your `add_action` call says that on the `wp_footer` even, do nothing.
So you actually have 2 problems not 1, and if you check your PHP error log or install a tool such as query monitor/debug bar you'd see the warning/notice.
Instead actions always take the form:
add_action( 'action name', 'callable type value, aka the name of function to run when the action happens' );
**That should give you enough information to fix this, but, it's the wrong way to put javascript in your footer.** You should instead use a JS file and enqueue it the way webelaine suggested. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "hooks, footer"
} |
Transate plugin with js & wp_localize_script
I'm trying to translate a plugin with JS functionality. I was able to translate the classic php part with a .po file etc...
In my plugin there are 2 words in js that I would like to translate and I absolutely can't get it to work
When I regenerate my .po file and I indicate that there is a translation for the js file, the software tells me the word that I can translate but the translate not work
**JS example**
const message = {
'copy': 'it's okay !',
};
buttonclip.on('success', function(e){
e.trigger.textContent = message.copy;
});
**PHP functions**
function js_script(){
wp_localize_script('code-js', 'messageClip', array('copy' => __('its okay', 'textdomain'),));
wp_enqueue_script ('code-js', plugin_dir_url(__FILE__).'js/main.js', array('framework_js'), 1.0, true);
}
add_action('wp_enqueue_scripts', 'js_script'); | In your PHP you are localizing the script using `wp_localize_script()`. The way you've used it will create an object in JS named `messageClip` with the string as the `copy` property, but then in your JavaScript you're not actually using this. In your JavaScript just get rid of `const message` etc. and use:
buttonclip.on('success', function(e){
e.trigger.textContent = messageClip.copy;
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, plugin development, translation, wp localize script"
} |
Hook automatic_updates_complete to autoupdate plugin
I'm trying to trigger some internal update class when WP is autoupdated. For manual update (when clicking on update), I found a way, it's pretty well documentated, I use the hook
`add_action( 'uprader_process_complete', 'my_update_function', 10, 2)`
However, when using the
`add_action( 'automatic_updates_complete', 'my_update_function', 10, 1) ` It is not executed.
Is there anyone using an update function in its wordpress plugin? Documentation is pretty scarce. | I found a solution:
function my_function_to_run_on_autoupdate(array $results ): void {
// Iterate through the plugins being updated and check if ours is there.
foreach ( $results['plugin'] as $plugin ) {
if (
isset( $plugin->item->slug )
&& strlen( $plugin->item->slug ) > 0
// 'your-plugin-slug' is usually the folder name of your plugin
&& $plugin->item->slug === 'your-plugin-slug'
) {
// Run whatever you want to run
}
}
}
This will be executed every time there is a plugin auto-update. If it finds your plugin, the code in "if" will be executed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, hooks, actions, automatic updates"
} |
Does the error "A structure tag is required when using custom permalinks." mean my permalinks haven't saved?
I'm troubleshooting an error elsewhere in a site and apparently need to resave my permalinks (without changing them), however when I do that I get (what seems to be) an error "A structure tag is required when using custom permalinks" as shown below.
I want to know if the permalinks were resaved or not, even though I didn't change them.
The "Learn more" link that comes with the message points to this core WordPress documentation, which seems to indicate the message is triggered by something in WordPress core, though I can't be 100% sure.
This site is running WordPress 6.0.3.
![Error shown when trying to save permalinks with no changes]( | It appears the permalinks were unsaved.
In my case, the currently selected option was "Post name". I changed to "Numeric" then clicked "Save changes" and got the same error. I then changed the selected option back to "Post name" and clicked "Save changes" again, and received a message saying it was successfully saved.
At that point, the 404 error I was getting from the default WooCommerce order-received page no longer occurred, which was the whole point of me trying to resave the permalinks. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks"
} |
How can I make my plugin detect if a certain theme is active?
I made a WordPress plugin, so now what I want is, I want to set a logic like if a certain theme is active, then load the plugin. Else, only keep the plugin activated, but don't apply any changes on the site. Any idea how can I achieve that? Sorry if I sound very nerdy :') | Use `get_stylesheet()` to get the directory name of the theme being used. If a child theme is being used you can determine the parent with `get_template()`.
At the top of the plugin file you can simply `return` early if the value is not what you want.
if ( 'my-theme' !== get_stylesheet() ) {
return;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, plugin development"
} |
How to add custom menu to block theme?
I'm creating a theme based on the 2023 block theme from WordPress 6.1.
I need to create a custom menu as the built-in one is too limited for me. I initially thought I can just enter the menu under "appearance-> menus", then output it with php somehow, but then I've noticed that appearance-> menus no longer exists.
What is the right approach for building a custom menu with block themes?
Do I just create a custom HTML block and hardcode the menu? is that the way? | It appears like old menus are just going away in FSE wordpress and a new way of doing it is through inserting a menu block. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, block editor, full site editing"
} |
plugin translations not reflected in admin dashboard
I have a plugin which has all strings originally in English, now translations to Arabic have been done at 100% and are appearing on the project link. When I check the plugin's page in Arabic, it is working perfectly, but the changes inside the admin dashboard, ex: plugin description and settings page, are still showing the untranslated English strings. Which have been already translated. I don't know what I am missing. | Please make sure you are passing your plugin domain as an argument in the internationalization:
`__('label example', 'plugin slug')`
and for the description and the plugin name, you should add the `Text Domain: 'plugin-slug'` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, wp admin, translation"
} |
How to set menu Display location
I have created a menu and I have the ID.
$menu_id = wp_create_nav_menu( 'Main Menu' );
And I have registered a navigation menu location:
register_nav_menus(
array(
'menu-header' => 'Header menu',
)
);
How to set "Display location" for this menu? | You can retrieve nav menu locations with `get_nav_menu_locations`
> int[] Associative array of registered navigation menu IDs keyed by their location name. If none are registered, an empty array.
<
This refers to a theme mod internally named `nav_menu_locations` which can be used to update the locations.
You can modify that returned value and then save the new array like this:
// Update theme mod
$locations = get_nav_menu_locations();
$locations['menu-header'] = $menu_id;
set_theme_mod( 'nav_menu_locations', $locations );
Note that this won't run filters and actions, caches may not be updated as a result, etc.
I'd also note that if you're trying to create side menus for dynamically generated content that this does not scale, and you will run into issues. There are better ways to show content specific menus and sidebars that do not involve the creation of nav menus. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, navigation"
} |
Dashboard show only published pages instead of all pages
Is there a way to view only the published pages instead of all the pages on the wordpress dashboard? I almost never need to use the drafts, and I would like to be able to get to my published pages easier. Thanks in advance :) ![enter image description here]( | Try this solution. Works for me.
add_action( 'admin_menu', 'customize_pages_admin_menu_callback' );
function customize_pages_admin_menu_callback() {
global $submenu;
foreach ( $submenu['edit.php?post_type=page'] as $key => $value ) {
if ( in_array( 'edit.php?post_type=page', $value ) ) {
$submenu['edit.php?post_type=page'][ $key ][2] = 'edit.php?post_status=publish&post_type=page';
}
}
}
further, you can also hide **All** using CSS if needed.
<style>
.post-type-page .subsubsub .all{ display:none}
</style> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "pages, dashboard"
} |
Is there a way to read JSON data inside Custom Fields without editing PHP?
I have a post with `Custom Field` called `json_data`, inside there is an array of strings such as: `{"data":["string no 1","string no 2","string no 3"]}`.
Is there a way to read the data using JavaScript and Elementor without editing the PHP file itself? | Yes. Use `JSON.parse($string);` to convert your string value to JSON format within Javascript.
<script>
var json_data_string = '{"data":["string no 1","string no 2","string no 3"]}'; // or echo the json_data field as <?php echo $json_data; ?>
var json_data = JSON.parse(json_data_string);
// Now access the properties as
$data = json_data.data; // outputs: string no 1,string no 2,string no 3
$string1 = json_data.data[0]; // outputs: string no 1
</script>
Reference to JSON.parse() function in Javascript. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "custom field, javascript, json"
} |
Wordpress Site transfered to another Server. 404 all pages
I transfered a Wordpress page to new Server, and now all pages are 404. I tried this solution <
but still nothing is fixed... Is there any other solutions?
Thank you in Advance... | Ok, so I had 5.5 version of wordpress and it was Incompatible with 8 PHP (on new server) so I updated Wordpress to 6.1 and it worked. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "404 error, migration"
} |
How to change wordpress adminstrator user 's ID from 1 to 0?
I have a WordPress site with one user (ID : 0) (administrator). I would like to set this to 0. so my subscribers will have their IDs starting from 1 onwards.
I tried to change it manually from the wp_users table, but that didn't work and I had to restore the database for the user to be able to log in again.
Any suggestions, please? | The MySQL table that stores the user data `wp_users` have an autoincrement on the primary key `ID`. The database will handle it automatically to avoid duplicated values and the minimal value is `1`.
There is nothing you can do about it. Here is the WP tables shema if you want to have a look <
There is no such thing as admin/client distinction in the user storage. What you might want to do is create a new user for your admin (its ID would be `2`) and then rename the first user and set the right role for your client. Of course, the next user will have ID `3` and so on... | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "phpmyadmin"
} |
Text before price on WooCom
I want to add text before the price on the WooCommerce product catalogue only, which I have working using this code in functions.php:
// Add text before price
function bd_rrp_price_html( $price, $product ) {
$return_string = 'Rent from: ' . $price;
return $return_string;
}
add_filter( 'woocommerce_get_price_html', 'bd_rrp_price_html', 100, 2 );
However, the above function is also adding the text before the price on the product detail page, which I do not want...
What would I need to change in the function to get it so it only displays on the product catalogue?
Thanks. | Try this out. Add other conditional tags according to the requirement. Hope it helps.
// Add text before price
function bd_rrp_price_html( $price, $product ) {
if(is_shop()){
$price = 'Rent from: ' . $price;
}
return $price;
}
add_filter( 'woocommerce_get_price_html', 'bd_rrp_price_html', 100, 2 );
![enter image description here]( ![enter image description here]( | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, code"
} |
Send email to user if their role is changed to Author
I would like an email to be sent to the user when their role is changed to Author.
The code below sends an email when a user's role is changed to any role, but I would like it only to send if the role is changed to 'Author'.
function user_role_update( $user_id, $new_role ) {
$site_url = get_bloginfo( 'wpurl' );
$user_info = get_userdata( $user_id );
$to = $user_info->user_email;
$subject = 'Role changed: ' . $site_url . '';
$message = 'Hello ' . $user_info->display_name . ' your role has changed on ' . $site_url . ', congratulations you are now an ' . $new_role;
wp_mail( $to, $subject, $message );
}
add_action( 'set_user_role', 'user_role_update', 10, 2 ); | Check for the value of `$new_role` before sending the email, if it isn't author then do nothing
function user_role_update( $user_id, $new_role ) {
if ( $new_role == 'author' ) {
$site_url = get_bloginfo( 'wpurl' );
$user_info = get_userdata( $user_id );
$to = $user_info->user_email;
$subject = 'Role changed: ' . $site_url . '';
$message = 'Hello ' . $user_info->display_name . ' your role has changed on ' . $site_url . ', congratulations you are now an ' . $new_role;
wp_mail( $to, $subject, $message );
}
}
add_action( 'set_user_role', 'user_role_update', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, user roles"
} |
Post object GUID adding http:/
In my template I have `href="'.$package_link->guid.'"`
The resulting HTML is: `href="http:/package/download-2023-friday-arrival-monday-departure-weekend-coach-festival-ticket/"`
Why is the `http:/` being added? I am using Advanced Custom Fields with the field setup as below. Any suggestions?
![enter image description here]( | You should not be using the GUID as a link. If you want to get the URL for a WordPress post object you should use `get_the_permalink()`:
href="' . esc_url( get_the_permalink( $package_link ) ) . '"
Note that I also escaped the URL. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "custom post types, custom field, advanced custom fields, guids"
} |
Pages do not load after migration to new server
I migrated my site to another server with a migration plugin, and everything seems ok. But it is the Hello World sample post which is loading, not my frontpage or any of my other pages, instead the critical error on website appears.
I can access my dashboard, and everything is ok, but I can’t change theme, thats strange. Database configuration is set up to the new server in wp-config, and DNS ip changed at CloudFlare.
I can see that others are facing similar issues, but I havn’t found a solution which solves mine.
Regards | We cannot investigate the server-side problem this way since we don't have access to it and probably the moderator will mark it off-topic.
However, these are common troubleshooting points that you can try to fix this kind of issue: -
* Try saving the permalinks for once and refresh. Go to Admin Dashboard > Settings > Permalinks > Save Permalinks
* Check what is exactly the critical error. Go to `wp-config.php` and add `define( 'WP_DEBUG', true); define( 'WP_DEBUG_DISPLAY', true);` This will start displaying the actual error instead of just saying critical error.
* Do you see other posts or content in the backend? Since you said Hello World is loading fine but not others. This seems like _old site database_ is not imported correctly. Import the DB again.
* Hire an expert to investigate and fix the issue via Upwork (mine) etc. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "migration"
} |
Remove / Disable default custom.css?ver=1.0.0
On my front end on every single page, I have `custom.css?ver=1.0.0` loading. But it's not included anywhere in my custom-built theme.
At present, I am running `WordPress v6.1.1`.
`<link rel='stylesheet' id='custom-css' href=' type='text/css' media='all' />`
Is this somehow loaded by default? If so, how can I prevent this? | Here's how you could use the `wp_dequeue_style` function in a WordPress hook to unenqueue the custom-css stylesheet:
function wpsx411806_unenqueue_custom_css() {
wp_dequeue_style( 'custom-css' );
}
add_action( 'wp_enqueue_scripts', 'wpsx411806_unenqueue_custom_css' );
In this example, the `wpsx411806_unenqueue_custom_css` function uses the `wp_dequeue_style` function to unenqueue the `custom-css` stylesheet. The function is then registered as a callback for the `wp_enqueue_scripts` hook. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "css"
} |
How do I change bullet on categories block?
The **categories block** displays an unordered list with bullets. I want to change the `list-style` property to `none`. How do I edit `theme.json` to modify this property?
"styles": {
"blocks": {
"core/categories": {
"listStyle": "none"
}
}
} | I think you have to do this via CSS, because Categories List only supports align, spacing (margin, padding) and typography (fontSize, lineHeight) and not list-style. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "block editor"
} |
How do I set register_meta for a specific CPT?
I want to set meta for specific CPT. The below code works but it sets the meta for all CPT. How do I set meta for specific CPT? I have a CPT "testimonial" and want to set "_duib_cl_heading" meta for it.
function _duib_cl_heading_register_post_meta() {
register_meta(
'post',
'_duib_cl_heading',
[
'auth_callback' => '__return_true',
'default' => __( '', '_duib_cl_heading' ),
'show_in_rest' => true,
'single' => true,
'type' => 'string',
]
);
}
add_action( 'init', '_duib_cl_heading_register_post_meta' ); | `register_post_meta` has a post type parameter, or just set `object_subtype` to the post type.
register_meta(
'post',
'_duib_cl_heading',
[
'auth_callback' => '__return_true',
'default' => __( '', '_duib_cl_heading' ),
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'object_subtype' => 'testimonial',
]
);
Or
register_post_meta(
'testimonial',
'_duib_cl_heading',
[
'auth_callback' => '__return_true',
'default' => __( '', '_duib_cl_heading' ),
'show_in_rest' => true,
'single' => true,
'type' => 'string',
]
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, plugin development, block editor"
} |
How to get custom setting from get_option and pass it in getEntityRecords in gutenberg block?
In my plugin settings I got the custom post type set in variable $clientlogocptname
$clientlogocptname = get_option( 'clientlogocpt-select' );
How do I retrive the value of $clientlogocptname setting and pass it in getEntityRecords in "custompost_type" gutenberg block?? Is it possible to get the value in the block or can you suggest a better way?
const data = useSelect((select) => {
return select('core').getEntityRecords('postType', 'custompost_type');
}); | As far as I can tell from looking into block editor store (you can use Redux devtools plugin for browser for that), entity for reading options is not registered. That means you cannot use `getEntityRecord` selector, which is usual way to obtain such data. Instead, either you can:
1. Use apiFetch to fetch data from designated REST endpoint.
2. Register your own entity to REST endpoint from 1. with addEntities and use `getEntityRecord` for getting data from option. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, plugin development, block editor"
} |
templates page not showing on gutenberg editor
Have install the latest wordpress 6.1.1 and want to use a template using the gutenberg theme editor, using the twenty-twenty-three theme for example. Then when I go to edit page, the template page option to apply the theme isn't there, have try it out with 7 or 10 different themes and still not showing, how can I apply a template to a page this way
![enter image description here]( | The template option has been moved here in WordPress 6.1:
![enter image description here]( | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "templates, block editor"
} |
How to get Wordpress to resize images for srcset?
I've added a custom image size to my functions.php: `add_image_size('banner', 1920, 300, true);`
I'm loading images in this custom size, using `wp_get_attachment_image()` to get a srcset.
However Wordpress will only generate a srcset if the image(s) it needs in this srcset are actually present on the disk.
When an image (lets say 2000x2000 for illlustration purposes) is uploaded, Wordpress will crop it down to 1920x300, great.
But none of the smaller sizes it will later need for the srcset are created, unless the image is specifically uploaded in 1920x300.
Forcing users to upload in the exact size required seems terrible and I would prefer not to do this.
~~Adding extra custom images sizes would just result in differently cropped or scaled images.~~
How do I get Wordpress to resize uploaded images to the sizes `wp_get_attachment_image()` needs for srcsets? | `srcset` is populated with all sizes of the image that are the same aspect ratio as the original image.
The reason smaller images are added to `srcset` if you upload the exact size is because that means that the default resized versions like `medium` and `large` will have the same aspect ratio. However, when using a custom cropped image size those smaller sizes will be created with the same aspect ratio as the original image, not the cropped custom size.
The solution to this is to register additional custom sizes with `add_image_size()` that are smaller than the custom size but have the same aspect ratio. WordPress will then be able to use these to populate `srcset` when didplaying your custom size. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, uploads, attachments, cropping"
} |
Store large dataset in WordPress installation temporary
My WordPress plugin depends on a large dataset (around a megabyte). The dataset is downloaded through REST API and then decoded to a PHP array. Right now the dataset is downloaded on each page load and then used for calculations etc. That gives page load times around 1 minute.
However, it is not necessary to have the data downloaded on each page load - it does not update that often. My idea is to store the data and just receive a fresh copy of the data once a day or week. I have used transients in similar cases but transients has a 172 characters limit.
It is not a problem that the first page load each day (or week) takes longer time in order to receive the fresh copy of the data. I just do not know the WordPress-way to store the large dataset when transients is not an option.
My question is: What is the WordPress-way of storing the data temporary? | Transient _names_ are limited to 172 characters; the data held in a transient can be much, much larger.
`set_transient()` documentation
Under the hood, transients are stored in the same table as options, and some WordPress code manages their lifetimes and expiry. You should easily be able to store 1MB of data in a transient.
## Autoloading
In response to a comment asking about autoloading:
> NB: transients that never expire are autoloaded, whereas transients with an expiration time are not autoloaded. Consider this when adding transients that may not be needed on every page, and thus do not need to be autoloaded, impacting page performance.
So as long as you set an expiry date, your transients will _not_ autoload.
// Sets a transient with a week-long lifetime.
set_transient( 'my_transient_name', $data, WEEK_IN_SECONDS ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, api"
} |
Remove image next to header image on WellExpo theme
We are using the WellExpo theme and when you view a specific post, next to the header image, there are 16 dots in a grid and an image for a missing image (see screenshot and the red box).
![How can we remove the part highlighted in red?](
We either want to remove these dots/image or know how to add an image.
We have tried (we think) changing every theme option, to no avail.
Can anybody tell us how we can access the relevant option/CSS (whatever) to manipulate this part of the post?
Thank you | If you simply want to hide it just add this to your css
.qodef-blog-holder article .qodef-post-type-id { display:none;} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
How to display the archive for native posts
I want to display an index of all posts, separate from the homepage.
The current settings on my WordPress Admin > Reading is:
![enter image description here](
I have a file called archive.php in my theme folder.
But when I visit the page "Blog", it's loading the index.php file. Not page.php and not archive.php.
How can I make it load the archive.php template file?
The official docs (< don't say anything about it, maybe I'm looking at the wrong docs. | The docs you’re looking for are: < You need to use `home.php` or `index.php`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "archives"
} |
How can I get values from a custom post type depending on where I click on my SVG map?
Here's what I would like to achieve (desktop only): <
When I click on my SVG map, I would like to display an information card for each store.
I have already created my custom post type "stores" and also the card HTML.
<div class="store-card">
<div class="content">
<div class="address">
<span>Address</span><br>
<span><?php the_field('store_address'); ?></span>
</div>
<div class="opening-hours">
<span><?php the_field('store_opening_hours'); ?></span><br>
</div>
</div>
</div>
But now I don't know how to get my values for each store created in my CPT. How can I do that? For instance, when I click on a specific store, I want its name and its opening hours to be displayed. I haven't figured out how to make it happen.
Many thanks! | This question will probably be marked off-topic because you're asking about a plugin, Advanced Custom Fields, but here's the answer anyway - you need to add the 'post id' to your call of `the_field()`, so that it's looking up the custom fields set in each of your custom post type's posts. See < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, custom post types, advanced custom fields"
} |
I cannot enter the letter C in the form
I have installed three different form plugins and they all have the same problem, I can't type the letter C in the form, if I press the C key it doesn't show in the form.
link: < | Most likely you have some functionality to block the `C` character. If you disable JavaScript and disable the loading indicator, you can use the character.
There is a lot of discussion online on the merit of these kinds of tools (trying to stop copying). As you've seen now: it worsens other functionality while giving little benefit (I can still copy with JS disabled, e.g.) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "forms"
} |
How to edit the name of a plugin on wordpress.org/plugins
Is there a way to edit the plugin name published on the WordPress plugin repository?
I tried editing the source code, but it still shows the old name.
Any help is appreciated.
Thanks | The Official Answer! is
> Yes and no. You can change the display name, but the slug — that part of the >plugin URL that is yours — cannot be changed once a plugin is approved. That’s why we warn you, multiple times, upon submission.
> To change the display name, edit your main plugin file and change the value of “Plugin Name:” to the new name. You also will want to edit your header in your readme.txt to match. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, wordpress.org"
} |
Set a minimal number for next user_id
I have a WordPress website with 111 users, I have to import +45000 users who had a predefined user_id starting from 31800001 to 32200905.
I know that I can import and set their user_id to their, already defined, id.
But I want that my next users keep this sequential ID, so the following user who register at my website after my import would need to have 32200906 has user_id.
When I try with a BETA the next user who registers has 112 as user_id.
So I am looking for a way to set a minimum for my following user_id. Any ideas ?
I think I could create 32200900 lines in my wp_usermeta + wp_users to fill the table with "fake accounts" in my database but, as you can imagine, I would prefer to avoid this ^^.
Thanks by advance ! Jonathan | You can access via phpMyAdmin and change the Auto Increment number to be your next user ID number.
Open phpMyAdmin Go to SQL tab at the top.
Enter the following:
ALTER TABLE 'wp_users' AUTO_INCREMENT=32200906;
Now create a new user and the ID should be 32200906 | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, import, id"
} |
Hide custom post type slug url from search engine
I want to hide, let's say, example.com/services/washing ('Services' is the this is a custom post type) from the search engine and show a 401 error page. How do I? | Instead of showing a 401, why not just add the URL to a robots.txt and the search engine will ignore it from indexing.
You could also manually add to the headers a meta robots to noindex the page.
You could run this via .htaccess to redirect a page to somewhere else (or show 401), but that would show for both users and search engines. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, permalinks, urls, slug"
} |
How to get all Existing Categories from a Custom Post Type
so I'm fairly new to worpdress development and I'm still learning my way through, I tried searching anywhere but I cannot find the answer I'm looking for.
The image below is the All categories from my Custom Post Type named **Jewelry** , How can I display this categories in my website? I tried using `get_categories()` but it doesn't work that way or I'm using it the wrong way
![enter image description here](
The code below just returns all categories from my POST not my CUSTOM POST TYPE
$categories = get_categories(array(
'hide_empty' => false,
)); | If you know the taxonomy slug of it you can use code below:
$tax_slug = 'product_cat';
$cpt_terms = get_term( $tax_slug );
echo '<pre>';
print_r( $terms );
echo '</pre>';
but if you don't know the slug, you can use these method: **First** click on the taxonomy you want to see its terms. In the URL bar in your browser you find sth like this:
> **product_cat** &post_type=product
you can find taxonomy slug and use it in the above code.
**Second** use code below to find taxonomies of a Post Type:
$cpt_tax = get_object_taxonomies( array( 'post_type ) => 'product' );
echo '<pre>';
print_r( $cpt_tax);
echo '</pre>';
Note: In this example I used 'product' as post type slug. if you don't know the slug you can find it by clicking on all posts of your CPT and in the URL bar of your browser you find this:
> **post_type=product** | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories"
} |
How to I remove Featured Image from the Posts/Category Lists?
It seems like this should be easy, but I do not see an option to exclude the featured image from the category index pages, or posts index pages (whatever they are called). Here is an example of the page I'm referring to: ` You see, there are multiple featured images, one for each article, however we just want to list of articles, no featured images.
I've looked through all the settings on WordPress and the Asta there, which we are using, and did an internet search. I find articles to remove feature image from the individual posts, but not the post list pages.
Any help would be nice. | Since you're using Astra Theme , you need to create a new "archives" template and set the display conditions. In that template, you can choose only to show what you want and hide or remove the images.
This is Theme related, and not WordPress related as @vancoder pointed out. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post thumbnails"
} |
restore backup full content or just specific folders
I have a .wpress backup, I extracted it and saw all the data, I am wanting to upload to the server this backup, but I just need to restore a specific plugin, should I restore all wp content or all plugins folder or can i just update the specific plugin inside plugins folder does a plugin can affect other? I ask this because I did a roll back of Elementor plugin and damaged the UI and now I want to restore to the backup version If I just upload this specific plugin will be enough or is a bad practice, does rolling back a plugin can affect others or them are all independents? | If you only need to restore a specific plugin, then you could just restore that one folder.
The only extra item to be concerned about is any database changes made with the different version of plugin. You will want to check the plugin version in your backup and compare to the LIVE version in your site. Check the readme file for changes. if there are no database changes, then you are likely OK to restore just the files.
Most likely, when you restored Elementor, it had database changes too. For that software, it's best to go to their Tools section and use their "Rollback" feature to restore a previous version as that will do both files & database changes for Elementor and Elementor Pro. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, backup"
} |
How do I unset category from a product in wordpress by code
I would like to take it out a category from a product. If I want to insert a category I use:
$categories = array(1, 2, 3); // Categories IDs
wp_set_post_terms($product->ID, $categories, 'product_cat', true);
However I do not know how to unset a category from the product. Someone can help me? | To remove all category from a WooCommerce product, you can use the wp_set_object_terms() function.
Here is an example of how you can use wp_set_object_terms() to remove categories from a product:
// Set the product's categories to an empty array
$categories = array();
wp_set_object_terms( $product->ID, $categories, 'product_cat' );
If you want to remove a specific category, you can use the wp_remove_object_terms() function instead. This function allows you to remove specific terms from an object.
Here is an example of how you can use wp_remove_object_terms() to remove a specific category from a product:
// Set the category ID to remove
$category_id = 123;
// Remove the category from the product
wp_remove_object_terms( $product->ID, $category_id, 'product_cat' );
This code will remove the category with an ID of 123 from the current product | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
add_post_type_support but for front_page only
I want to enable excerpt for pages, but for front_page only. Using `add_post_type_support('page','excerpt')` enables it for all pages, since the first argument is `$post_type`. How can I narrow down it to front_page? Various ifs in functions.php like `is_front_page()` doesn't work since I've read Wordpress, on `functions.php` loading, doesn't know yet about post types.
Prefer not to use css to hide excerpt field. | If you want to enable excerpt for specific page, then you can add some conditions to narrow down.
For check "front page id" you can use `get_option('page_on_front');` in admin area. (`is_front_page()` should not work here)
global $pagenow;
// check current screen is edit page
if ( $pagenow == 'post.php' ) {
$fron_page_id = get_option('page_on_front');
$current_page = $_GET['post'];
// check current page is match with front page
if($fron_page_id == $current_page){
add_post_type_support('page','excerpt');
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php"
} |
Woocommerce send custom email receipt based on product attribute
I was wondering if someone can point me towards the big picture on how to send a Woocommerce Custom email based on the product attribute. I'm mostly a front end javascript dev, and don't know the Woocommerce ecosystem that well. I've got some Woo products that are event tickets, that I would like the customer to get a different email for. I see under each product you specify an attribute, which would be ticket.
I've got a basic WP plugin going that will house this functionality. I've found some resources on sending custom emails with Woo. So i guess the piece I'm missing would be when a customer buys a product, if it has the ticket attribute, send the custom email. Any input on figuring out how to do this? Thanks! | I would hook into the woocommerce_thankyou then evaluate the order data. I see there is a good answer on Stack Overflow for hooking and a good answer on Stack Exchange for getting the item's meta data into the email. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, email"
} |
Get postId in a wordpress pattern file?
How can I get post data or just post Id inside of a pattern?
I've created the following pattern file:
<?php
/**
* Title: Post link
* Slug: mytheme/post-link
*/
?>
<!-- wp:html -->
<div>
<?php
$id = $postId; //how can I get it????
$post = get_post($postId);
$slug = $post['slug'];
?>
<a href="<?= $slug; ?>">Some Button leading to a post</a>
</div>
<!-- /wp:html --> | In block themes patterns won't have access to context such as id it seems:
<
One has to create a custom block to get post id and use useSelect hook to get post Id like so: `import { useSelect } from "@wordpress/data";`
... inside Edit block function:
`const postId = useSelect(select => select('core/editor').getCurrentPostId());`
then, postId can be used inside edit function and if it has to be used in save function, `useEffect` should be used inside edit to store id to attribute like so:
useEffect(() => {
if (postId) {
setAttributes({postId})
}, [postId]);
Provided you have defined postId attribute in `block.json`, you can get and use that attribute in save function or render_callback. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "block editor, full site editing"
} |
orderby property of query on pre_get_posts returns incorrect value
I am attempting to implement some custom sorting logic for a column but are facing issues in the pre_get_posts hook. The value of the orderby property on the query is not returning the value corresponding to the currently selected sorted column. I have no plugins installed and are using the latest wordpress version 6.1.1 for context. Here is my code:
add_action( 'pre_get_posts', 'users_custom_column_query' );
function users_custom_column_query( $query ) {
write_log( 'is main query: ' . var_export( $query->is_main_query(), true ) );
write_log( 'orderby value: ' . var_export( $query->get( 'orderby' ), true ) );
}
Which outputs this on my local test site:
// Output on page site.local/wp-admin/users.php?orderby=email&order=asc:
// is main query: true
// orderby value: ''
Expected output is 'email'. Any help is greatly appreciated! | As Tom J Nowell pointed out in the comments, I was targeting the wrong hook for this. Correct hook to modify the WP_User_Query is pre_get_users. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, theme development, columns"
} |
get_post_types() is returning null
I am trying to retrieve the post types and put them into an array with their slug being the index and their label being the value. When I `print_r( get_post_types() );` it returns the proper array with data, but when I try to use it like below, it returns null.
function get_posttype_list() {
$pt_list = [];
$post_types = get_post_types( array( 'public' => true ) );
foreach( $post_types as $pt ) {
$pt_list[ $pt->name ] = $pt->labels->singular_name;
}
} | You have to return your formatted array. Change the code like below
function get_posttype_list() : array {
$pt_list = [];
$post_types = get_post_types( array( 'public' => true ), 'objects' );
foreach( $post_types as $pt ) {
$pt_list[ $pt->name ] = $pt->labels->singular_name;
}
return $pt_list;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, plugin development"
} |
Not Able to Access Terms Under Custom Taxonomy Archive
Having a `Custom Taxonomy` called `movie-genres`
'rewrite' => array('slug' => 'movie-genres', 'with_front' => true) );
register_taxonomy( 'movie-genres', array( 'movies' ), $args );
And I have a WP template hierarchy for the `Taxonomy` and it's associated `Terms` like below
archive.php
archive-movie-genres.php
taxonomy.php
taxonomy-movie-genres.php
taxonomy-movie-genres-action.php
Now when navigating in the browser I am able to see the CPTs listed for term of action like this
domain.com/movie-genres/action
but when landing at `movie-genres` to get the all terms listed under this taxonomy like
domain.com/movie-genres/
I am getting the `404` page in return!
As you can see I have the `archive-movie-genres.php` and `taxonomy-movie-genres.php` created so can you please let me know why I am getting ended at `404`? | A 404 is the expected behaviour.
You'll find no link to such a URL in the WordPress admin, there's no functions to generate that URL in code, and there is no possible template for such an archive, as shown in the Template Hierarchy documentation (`archive-movie-genres.php` is not a valid template). The path `/movie-genres` alone will not return anything in WordPress under normal circumstances.
All WordPress templates are based around The Loop, and that loop is for looping over and displaying _posts_ , not terms. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, custom taxonomy"
} |
Image file urls still point to http instead of https
I just noticed that all my images in "Media" have the " URL under "File URL:".
I certainly have SSL installed and under Settings > General the domain is correctly set with https. Is this set somehwere else or is there something else I could configure this?
Thank you :) | That's because the image (media) URL is stored as part of the record in the posts table. (Images/media are another type of post.)
You have several choices:
1. Manually change each media URL to https. This might take a while if you have lots of pictures. Not really recommended.
2. Use phpMyAdmin to change the value. There are several googles/bings/ducks on how to do this. But also not recommended - playing with the database can be dangerous.
3. Use a plugin to fix things. One such is "Better Search and Replace". It will do it all for you. Instructions are clear, and it is an established and well-supported plugin. It also has a 'test' mode that doesn't do anything, but shows you what would have been done. I have used this many times.
Also, make sure that you have changed your htaccess file to force requests to use HTTPS. Your hosting place will usually have instructions on how to do this. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "http"
} |
WordPress shows a count of published items on the site, but the items are not appearing when you click on the "published" link
WordPress shows a count of published items on the site, but the items are not appearing when you click on the "published" link.
![enter image description here](
It's showing 39 published posts but when I click on published link, it's not even showing a single post. | In my case, deleted posts from the dashboard were not deleted from the database. After deleting unnecessary posts from the database my problem is solved. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, dashboard"
} |
How to enable REST API on custom post type without Gutenberg?
I understand that you have to enable the REST API in order to use the Gutenberg block editor, because Gutenberg relies on it; however, I want to use the Classic Editor for a custom post type and still use the REST API. Is there another way to disable Gutenberg?
I am aware that setting `show_in_rest` to `true` in my `register_post_type()` function enables the REST API, but it also enables Gutenberg when I do.
Any suggestions are greatly appreciated. | This code should do the trick. You will just need to add the post type(s) to the line below.
function my_disable_gutenberg( $current_status, $post_type ) {
// Disabled post types
$disabled_post_types = array( 'book', 'movie' );
// Change $can_edit to false for any post types in the disabled post types array
if ( in_array( $post_type, $disabled_post_types, true ) ) {
$current_status = false;
}
return $current_status;
}
add_filter( 'use_block_editor_for_post_type', 'my_disable_gutenberg', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "php, custom post types, block editor"
} |
How to add paraent in Blog post URL in wordpress
I have a post in WordPress with having URL like <
I want to change the URL to something like <
How can I do that in a simple WordPress blog post | You can set this in your WordPress settings.
Go to your Permalinks settings `(WP Admin → Settings → Permalinks)` and select ‘Custom Structure’. It should display your current structure in the text box next to it. Now, add `/blogs` in front of what is in the text box. And then Save.
See screenshot for reference ![enter image description here]( | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, permalinks, urls, blog page"
} |
How to automatically set a Template Page Name next to a page in menu screen such as WooCommerce pages, front page, or posts page in wordpress?
When creating a menu, and after selecting a page as front page and another page as posts page..it appears next to the page in menu screen. For example, "Front Page" appears next to home page, and next to the blog page, the "Posts Page" appears, as well as the WooCommerce pages, Next to each page, the page type appears, such as Cart page, Account page, Shop page, etc..
How do I do this with a custom page template called- for example - "Services Page" ? | Use the `display_post_states` hook:
function custom_display_post_states( $states, $post ) {
if ( 'Services' === $post->post_title ) {
$post_states['custom-content'] = 'Services Page';
}
return $post_states;
}
add_filter( 'display_post_states', 'custom_display_post_states', 10, 2 );
or you can do by ID
if ( 1 === $post->ID) {
$post_states['custom-content'] = 'Services Page';
}
To check if page has template:
function custom_display_post_states( $states, $post ) {
$template = get_page_template_slug( $post->ID );
if ( $template == 'YOUR_TEMPLATE_FILE' ) {
$states['custom-content'] = 'Services Page';
}
return $states;
}
add_filter( 'display_post_states', 'custom_display_post_states', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, menus, themes, page template"
} |
How to group by column a and sum column b and c in a php array
I got the following array:
[0] => Array
(
[kanel] => 5
[peber] => 0
[shipping] => A
)
[1] => Array
(
[kanel] => 25
[peber] => 0
[shipping] => A
)
[2] => Array
(
[kanel] => 25
[peber] => 0
[shipping] => C
)
[3] => Array
(
[kanel] => 5
[peber] => 0
[shipping] => B
)
[4] => Array
(
[kanel] => 5
[peber] => 0
[shipping] => C
)
I want to print the following:
> A Kanel: 30 Peber: 0
>
> B Kanel: 5 Peber: 0
>
> C Kanel: 30 Peber: 0
Literally grouping on `shipping`, sum on `kanel` and sum on `peber` as well. I can find a lot on how to do it with one column, but it doesn't do the trick. :)
Thank you! | To group and sum the values in your array by the shipping field, you can use a loop and a temporary associative array to store the intermediate results. Here is an example of how you can do this:
$result = array();
foreach ($array as $item) {
$shipping = $item['shipping'];
if (!isset($result[$shipping])) {
$result[$shipping] = array(
'kanel' => 0,
'peber' => 0,
);
}
$result[$shipping]['kanel'] += $item['kanel'];
$result[$shipping]['peber'] += $item['peber'];
}
// Print the results
foreach ($result as $shipping => $values) {
echo $shipping . ' Kanel: ' . $values['kanel'] . ' Peber: ' . $values['peber'] . "\n";
}
This will produce the following output:
A Kanel: 30 Peber: 0
B Kanel: 5 Peber: 0
C Kanel: 30 Peber: 0 | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, array"
} |
How to find source of these strange SQL queries?
I'm looking at my slow queries and i don't understand how some bot or person is doing them. They look like this: (i copy/paste them no placeholders!)
SELECT post_id FROM wp_postmeta, wp_posts WHERE ID = post_id AND post_type = 'rentals' AND meta_key = '_wp_old_slug' AND meta_value = '%5dsibbo-cmp-layoutthor-cookiesdiv';
SELECT post_id FROM wp_postmeta, wp_posts WHERE ID = post_id AND post_type = 'rentals' AND meta_key = '_wp_old_slug' AND meta_value = 'sauved2ahukewjjx9uu2zb8ahvwbxaihz3waceqfnoecaiqagusgaovvaw2fcppukbhgtva5flmmmnzl';
These are increasing server load in the server. I don't understand how can you even query by meta_value in the front end?! Makes no sense to me. | They're from WordPress. They come from the `wp_old_slug_redirect()` function which is run whenever there is a 404. The purpose is to check if the requested URL was the old URL for a post so that it can redirect to the new URL.
If you're seeing a lot of these then it means you're getting a lot of 404 hits. The slugs in your example suggest that it's probably bots, but it's hard to say. I highly doubt this query alone is causing significant server load. It's probably the volume of the requests themselves that is the problem. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "mysql, security"
} |
How to detect if we are in the Site Editor part of the Block Editor (as opposed to editing a Page/Post) in JavaScript?
We use JavaScript to unregister some Core blocks from the Page Editor. We'd like to unregister a slightly different list of blocks when using the Site Editor vs when editing a page or post.
Rather than something clunky to make this determination, such as looking at the current page's URL, does WordPress provide any native functions we can rely on? Some JavaScript version of get_current_screen or is_site_editor() or similar? | The Block Editor, in both the context of the editing pages or the Site Editor, actually does provide some simple variables in JavaScript similar to the data that is available via get_current_screen in PHP.
Sample variables in Page Editor:
var ajaxurl = '/mysite/wp-admin/admin-ajax.php',
pagenow = 'page',
typenow = 'page',
adminpage = 'post-new-php',
thousandsSeparator = ',',
decimalPoint = '.',
isRtl = 0;
Sample variables in Site Editor:
var ajaxurl = '/mysite/wp-admin/admin-ajax.php',
pagenow = 'site-editor',
typenow = '',
adminpage = 'site-editor-php',
thousandsSeparator = ',',
decimalPoint = '.',
isRtl = 0;
So one can simply access 'pagenow' to make the determination which context we are in. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "javascript, block editor"
} |
How to find posts that are missing translation? (wpml)
I have a page with hundreds of posts that should all be available in two languages. In the admin area however I have differing post counts – so I guess some of the posts are not translated. Instead of scrolling the post list in both languages and comparing the lists basically post by post I would love to do the searching programmatically. Maybe there is even a plugin I don't know of? I suppose this is possible – I just can't get the right starting point.
Would appreciate any pointers or suggestions on this. Thank you! | To whom it may concern: finally I found a way – and it turns out to be rather simple: there is a wpml function or actually a filter that checks whether a post or page has a translation or not:
`wpml_element_has_translations`
<
It returns TRUE if a translation exists and FALSE if there is no translation. I used the following to check for posts inside the loop where $the_id is the ID of the post I want to check:
`$is_translated = apply_filters( 'wpml_element_has_translations', NULL, $the_id, 'post' );` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "translation, plugin wpml"
} |
HELP: Code To Check Status And Write Debug Entry
I use a simple function to send out a 'heartbeat' to a website uptime monitoring service (Better Uptime):
function my_better_uptime_heartbeat() {
wp_remote_get( ' );
}
add_action( 'my_heartbeat', 'my_better_uptime_heartbeat' );
This function is called by wp-cron on a regular schedule but I'm finding that sometimes it isn't sent and I don't know why. I've spent hours with SiteGround, my website hosting provider, and they are telling me everything is fine with the infrastructure.
I would like to:
1. Check that a HTTP200 code was received from the GET request and
2. Log any failures ( _either no status, or anything except HTTP200_ ) to the Wordpress debug log
Does anybody know how to elaborate on the code above to achieve this?
David.
* * *
p.s. wp-cron is initiated by the OS's crontab, not on page visits (as would be the norm). | You can get the response code with `wp_remote_retrieve_response_code()` and log the response with `error_log()`.
function my_better_uptime_heartbeat() {
$worked = false;
$response = wp_remote_get( ' );
if ( ! is_wp_error( $response ) ) {
if ( 200 == wp_remote_retrieve_response_code( $response ) ) {
// It worked, no need to log anything.
$worked = true;
}
}
if ( ! $worked ) {
// Logs the response that was received for debugging.
error_log( print_r( $response, true ) );
}
}
add_action( 'my_heartbeat', 'my_better_uptime_heartbeat' );
This _should_ log failures to WordPress' debug log, assuming that you've got something like the following in your site's `wp-config.php`:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', false );
define( 'WP_DEBUG_LOG', true ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions, actions, wp cron"
} |
Count custom posts type and filter by tag
I'm using this code to count the number of posts of a specific custom post type that have also a specific tag:
<?php
//Array
$args = array(
'post_type' => 'cars',
'tag' => 'available'
);
$loop = new WP_Query( $args );
if( $loop->have_posts() ) :
$count_posts = wp_count_posts("cars")->publish;
?>
<?php
echo "<p>Total: $count_posts cars</p>";
else:
?>
<?php
echo "<p>No cars available.</p>";
?>
<?php
endif;
wp_reset_query();
?>
However the loop does not filter out the posts under "available" tag, but it just takes all the posts under "cars" post type.
Probably I'm close to the solution but I'm not getting what I'm doing wrong. | `wp_count_posts` is not affect your custom query. You can use `found_posts` to return the number of posts from the custom query. So try to change the code after your loop query as follows. Hope it helps.
if ($loop->have_posts()) :
$count_posts = $loop->found_posts;
echo "<p>Total: $count_posts cars</p>";
else :
echo "<p>No cars available.</p>";
endif;
wp_reset_query(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, wp query"
} |
How to write a plugin that "listens" every time, an edit occurs?
Let's say I want to write a plugin that replaces (i.e.: overwrites) every `src`-tag of every iframe-element on a WP-Website with a custom string AND the plugin shall watch every new post or page-edit whenever a new iframe is inserted, how would I go about it? Is there something like an event-api for WP every time an edit visible on the frontend occurs? | 1. Use the "save_post" action hook, which is triggered every time a post or page is created or updated. In the function called by the hook, you can check the post content for new iframes, and if found, replace the src attributes of iframe elements before they are saved to the database.
2. Use the "the_content" filter hook, which allows you to modify the post content before it is displayed on the frontend. In the function called by the filter, you can replace the src attributes of all iframe elements on the website with a custom string.
3. To limit the plugin functionality to certain post types, you can check the post type before making the replacement in both the "save_post" and "the_content" functions.
4. Once the plugin is ready, activate it in the WordPress backend and it will start listening for post and pages changes and replacing the iframe src attributes as per your custom string. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, api, events"
} |
How properly use social link block in template part
How I must use social links block in template part?
This variance give me that icons don't render in frontend part:
1.
<!-- wp:social-links -->
<ul class="wp-block-social-links"><!-- wp:social-link /--></ul>
<!-- /wp:social-links -->
2. 3.
<!-- wp:social-links /-->
I don't understand, why it don't working - others blocks like
<!-- wp:site-logo /-->
<!-- wp:site-title /-->
<!-- wp:navigation /-->
works perfectly | Different blocks work differently. Some blocks are just a comment, while some require HTML. Others depend on inner blocks for their actual content. The Social Links block is a wrapper block and each social link is a variation of the Social Link block.
But no matter how the block actually works, the easiest way to get the markup for use in a template part is to add it to the editor an copy and paste the result. If I add a Social Links block with two links inside it then this is what the markup looks like (indentation corrected for clarity):
<!-- wp:social-links -->
<ul class="wp-block-social-links">
<!-- wp:social-link {"service":"facebook"} /-->
<!-- wp:social-link {"service":"twitter"} /-->
</ul>
<!-- /wp:social-links --> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "block editor, social sharing"
} |
Renaming the 'build' directory generated by @wordpress/scripts for React development
When using @wordpress/scripts to create a React app for WordPress, the default configuration to build the app is via running one of the following two scripts `wp-scripts build` or `wp-scripts start` (both run from within **package.json** ). Both scripts will take the code from the **src** directory and build it into the **build** directory.
I would like to change the destination directory; for example, I would like the result to be in **dist/app** instead of **build**. I found an option to change the source directory; the option is `--webpack-src-dir` (I have not used it, but I think with a little bit of tinkering, I will find out how), however I could not find a way of changing the destination directory. Is this possible?
Thanks.
PS: This is the first time using React with WordPress, so apologies about the simple question. | I am writing this answer after testing the suggestion given by @SallyCJ (thank you for pointing me towards the right direction)
Writing the following entry into the `scripts` section of **package.json** will change both the _source_ and _destination_ of the React code.
"scripts": {
"build": "wp-scripts build --webpack-src-dir=path/to/source/dir/ --output-path=path/to/destination/dir/",
"test": "echo \"Error: no test specified\" && exit 1"
},
If you'd like to override the default entry point (i.e., use a different file than **index.js** as your entry point), and if this custom entry point file is located in a custom path, then here is how to setup your scripts
"scripts": {
"build": "wp-scripts build path/to/source/dir/custom.js --webpack-src-dir=path/to/source/dir/ --output-path=path/to/destination/dir/",
"test": "echo \"Error: no test specified\" && exit 1"
}, | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "scripts, react"
} |
How to add custom prefix before category base for category page URL?
Is it possible to add a **custom prefix** right before the **category base** of the category page URL(s)?
For example, in the Category Page URL: `sample.com/category/top-10`, **category base** is `category`, and **term** is `top-10`
I want to add a custom prefix, so that the URL will be like this: `sample.com/my-custom-prefix/category/top-10`.
I've read the `add_rewrite_rule()` but I don't really get how to apply it to this approach. Is there any documentation that you could point me out, or any existing similar question here? | This can be easily done from WordPress `settings`.
Go to the admin panel of your WordPress site (also known as the Dashboard), and from the left menu, go to `Settings Permalinks`:
![WordPress permalink settings](
From there, you'll see the `Category base` input field.
Use the prefix you want in this input field, e.g. `my-custom-prefix/category` and then `Save Changes`.
If this is a new site, then this should be enough, no need to do any code change. After this change, your category Page URL `sample.com/category/top-10` will become `sample.com/my-custom-prefix/category/top-10`.
If this is an old site with old category links, then in addition to the above step, it's better to redirect the older category links using either a redirect plugin or `.htaccess`.
Following are a couple of links with some additional details about categories that may be helpful to you:
1. <
2. < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "categories, permalinks, slug"
} |
Why am I getting an error when requiring a file in my plugin?
I am developing a plugin and when trying to require a file, I get thrown the error: `Warning: require(): http:// wrapper is disabled in the server configuration by allow_url_include=0 `.
One of requires work, but the other one is throwing the error for some reason:
// This one works
require plugin_dir_path( __FILE__ ) . 'includes/class-wp-portfolio-pro.php';
//This one throws an error
require plugin_dir_url( __FILE__ ) . "includes/wp-portfolio-pro-cpt.php";
I am not sure why the bottom one throws the error but the top works just fine. In the file that throws the error, I am registering a custom post type. | As the names suggest, `plugin_dir_path()` will get the filesystem path, while `plugin_dir_url` gets the URL.
A file path looks something like this `/var/www/html/wp-content/plugins/my-plugin/` and can be used by PHP to find a file on the server.
A URL will look like ` and is intended to be accessed over the web. If you attempt to require a file in PHP using a URL the server will need to request that file over the web, which is far _far_ slower, and a security risk. This is why the ability to even do this is disabled by default in many setups. The error you're seeing is telling you that this is disabled.
File paths should be used for accessing files on the server, while URLs should be used to find assets from the browser. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "plugins, plugin development"
} |
get_query_vars always retruns empty value
I try to get this example running:
function themeslug_query_vars( $qvars ) {
$qvars[] = 'custom_query_var';
return $qvars;
}
add_filter( 'query_vars', 'themeslug_query_vars' );
$testvar = get_query_var('custom_query_var');
echo "testvar=[$testvar]";
as found on page <
With my test page I can see my little testvar string but with "?custom_query_var=help" at the end of my URL my "testvar" is empty.
In my test scenario I use the original twentytwentyone theme with no plugins activated. My code is placed at the end of functions.php.
Does anybody have me an advice of how to fix this issue?
Regards Peti | > In my test scenario I use the original twentytwentyone theme with no plugins activated. **My code is placed at the end of functions.php.**
This is the problem. Your code is running as soon as functions.php is loaded, which is before the query vars are populated. If you use `get_query_var()` inside an action hook that runs later, or inside a block or shortcode, it should work fine. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
How to tell if a dynamic sidebar is being displayed on page?
I'm trying to conditionally add a class of `has-sidebar` to a wrapper div, and I'm struggling to find a conditional statement to see if the sidebar is active on the current page.
For example:
<!-- Open site main wrapper -->
<div id="site-content" <?php if (is_active_sidebar('sidebar-1')) echo 'class="has-sidebar"' ?>>
The issue is "is_active_sidebar" is always returning true - is there a function or conditional I can check to see if a sidebar is displayed or not? | Because of the way templates are rendered in WordPress it won't be possible to know if a page has a sidebar until after that sidebar has been rendered. This is because code in templates can't 'know' what code exists later in rendering sequence.
What I would recommend is determining what the conditions are which your sidebar is displayed under and using those conditions in your `has-sidebar` check. For example, if your wrapper opens in `header.php` but your sidebar is only displayed on posts by rendering it in `single.php` only, you could check `is_single()` in header.php to determine whether the sidebar is going to be rendered. You could combine this with `is_active_sidebar()` if you need to know of the sidebar will have any widgets in it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, sidebar"
} |
Does the 'init' hook works for all sites in multisite?
Im trying to trigger a configuration everytime I create a new subsite on multisite environment, like so:
add_action('init', 'mgh_set_events_option', 99);
function mgh_set_events_option(){
$mgh_is_set_options = get_option('mgh_is_set_options');
if(!$mgh_is_set_options){
print_r('setting options');
update_option( 'mgh_is_set_options', true );
}
}
The problem is that the 'init' action does not trigger in some sites from our multisite instance. There is any principle of why this happens? | If your code is in a theme's `functions.php`, it'll only run on sites where that theme is active. You can ensure that it's active on _all_ your sites by putting that code snippet into a plugin that's active on every site (ie, Network Activated). Alternately, you can use a Must-Use plugin to ensure that it runs on every site in your Multisite network. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite"
} |
Do plugin auto-updates also run for a lower version?
We are planning to upload a new major version of our plugin to the WordPress Plugins Directory.
As part of our contingency planning, we wanted to understand how _rolling back_ to the old version might affect existing users. In other words, what will happen if we upload version `2.x.x` \- and then re-upload version `1.x.x`?
**Specific use cases:**
a) User updated to `2.x.x` **via auto-updates** (and has auto-updates turned on). If we upload `1.x.x`, will they auto-update to that version?
b) User installed plugin `2.x.x` **manually** (using a ZIP file), and has auto-updates turned on. If we upload `1.x.x`, will they auto-update to that version? | Updates are very basic and simply check the version number. Anybody on 2.x.x of your plugin will not see an update available because it the latest version will appear to be an older version. How the plugin was originally installed has no impact on this behaviour. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, automatic updates"
} |
Escaping get_option( 'time_format' ) is nesserary?
I've submitted a plugin for review and it was not accepted as it needs some fixes with data sanitization and escaping.
One of the flagged examples was this line:
echo'<td>'.$date .' '.$time.'</td>';
last line of this code block
// date & time
$date_format = 'Y/m/d';
$time_format = get_option( 'time_format' );
$s = strtotime($row->created_at);
$date = date($date_format, $s);
$time = date($time_format, $s);
echo'<td>'.$date .' '.$time.'</td>';
I don't understand why $date or $time would need to be escaped since they are put through PHP functions strtotime() and date()
Thanks in advance. | Should you escape these?
$date_format = 'Y/m/d';
$time_format = get_option( 'time_format' );
**No.** That would be early escaping! Early escaping is very bad!
However, should you escape this?
echo'<td>'.$date .' '.$time.'</td>';
**YES**.
Escaping is not about wether it's needed or not, if you ever find yourself saying _" It shouldn't be a problem because it's always a"_ stop yourself and escape.
_Escaping is about enforcing assumptions and expectations. Why trust that it will be safe when you can escape and **guarantee** that it's safe?_
This protects you in multiple ways, e.g. if you use `esc_html` you've guaranteed the string will never contain HTML, even if you make changes in the future further up, filters get added, etc, **you always know that it's safe because you escaped at the moment of output.** | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "escaping"
} |
How to add a new attribute to core wp block editor without npm?
I need to add a new attribute with color selector to a core paragraph/heading block. What would be `braces-color="#5a6a81"` for example. I've been googling all day and only found examples with npm installation. But I can't install it on wp hosting.
I saw the article < but it doesn't help without the npm. | You don't need block attributes to do that! Core has an alternative that provides a superior experience, **block variants**.
Block variants let you reuse an existing block, but declare a variant which has predefined block attributes that match your use case.
For example, all embeds are variants of the embed block, even though they have different names titles icons and descriptions.
<
For example with this:
wp.blocks.registerBlockVariation( 'core/heading', {
name: 'bracketed-heading',
title: 'Bracketed Heading',
attributes: { className: 'heading-with-brackets' },
} );
I got this:
![enter image description here](
I can add new descriptions, titles, icons, previews, and HTML classes to style the heading differently ( with brackets ). No PHP needed.
The only difference between this and a normal heading, what makes it a bracketed heading is this:
![enter image description here]( | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, block editor"
} |
How to use multiple custom post types to archive as front page?
I am trying to modify my code to show multiple custom post types on the front page. This code works good for a single custom post type, but I can't figure out how to add a second custom post type.
How can the following code be modified to show a second custom post type?
function blestrecipes_cpt_filter( $query ) {
if ( ! is_admin() && $query->is_main_query() && is_home() ) {
$query->set( 'post_type', array( 'recipes' ) );
}
}
add_action( 'pre_get_posts', 'blestrecipes_cpt_filter' ); | Well, looks like you've almost got it. To include multiple custom post types in the `WP_Query` object, just change:
$query->set( 'post_type', array( 'recipes' ) );
to:
$query->set( 'post_type', array( 'recipes', 'another-custom-post-type' ) );
Basically adding more elements to the array.
So the final code becomes:
function blestrecipes_cpt_filter( $query ) {
if ( ! is_admin() && $query->is_main_query() && is_home() ) {
$query->set( 'post_type', array( 'recipes', 'another-custom-post-type' ) );
}
}
add_action( 'pre_get_posts', 'blestrecipes_cpt_filter' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "php, custom post types"
} |
Is it possible to add javascript to template parts
Is it possible to add javascript to a template part, specifically I would like to add alpine.js to a template part. Any time I add a `x-data="menuOpen"` or even a data attribute I get `This block contains unexpected or invalid content`
Any help on this is appreciated. | This is not supposed to work (and it does not work) in a way you wanted. I guess you are talking about new FSE template parts (.hmtl), and not legacy (.php) template parts. You can only add HTML and blocks to .html template parts and javascript is enqueued as a part of a block. Alternatively, you can check in a functions.php if certain page/post/template/block is loaded and then enqueue javascript you want. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, block editor"
} |
What is the best way to relate different custom post types?
Let's say I have 3 CPTs: series, seasons, and episodes. Now if I post in these custom post types the URL would be:
* Series CPT > post name: sample serie > URL: `site.com/series/sample-serie`
* Seasons CPT > post name: sample season > URL: `site.com/seasons/sample-season`
* Episodes CPT > post name: sample episode > URL: `site.com/episodes/sample-episode`
Now what I want to do is combine these URLs together:
* `site.com/series/sample-serie/sample-season/sample-episode` : To show the page for the sample episode (previously: `site.com/episodes/sample-episode`)
* `site.com/series/sample-serie/sample-season/` : To show the page for the sample season (previously: `site.com/seasons/sample-season`)
How can I implement this? Was creating 3 custom post types a good idea for doing this? Or is there any other methods to do this? (Preferably without any plugins)
Appreciate any further assistance! | I think a better approach for this would be to create a single nested (hierarchical) custom post type.
For example, it can be `series`.
Then a single series named `sample-series` as a top level post of `series` post type: `site.com/series/sample-series/`.
Then seasons named `season-one`, `season-two` etc. can be children of `sample-series`, like: `site.com/series/sample-series/season-one`, `site.com/series/sample-series/season-two`.
Similarly, episodes can be children of those seasons, like: `site.com/series/sample-series/season-one/episode-one`, `site.com/series/sample-series/season-one/episode-two` etc.
Same thing can be done by default by WordPress `page`, since pages are by default hierarchical. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "custom post types, permalinks, url rewriting, rewrite rules"
} |
Redirect posts to post editor page based on query string
I want the posts that has the param `edit` to open the respective post editor page.
This is because the admin bar is disabled on my site. So I need to make things easier to edit on my sites.
I made the following code and inserted it in my plugin, but it's not working. I tried `header("Location: ")` instead of `wp_safe_redirect`, but that didn't work either.
Any ideas?
function myfunction() {
if( isset( $_GET['edit'] ) && empty( $_GET['edit'] ) ) {
wp_safe_redirect( admin_url( '/post.php?action=edit&post=' . get_the_ID() ) );
exit;
}
} | ## Implementation notes:
1. You need to use that function with an appropriate action hook. For example, `template_redirect` hook can be used here.
2. If you want URL to have `?edit`, then `empty` check is not necessary, if you want URL to have something like `?edit=1`, then use `! empty` check.
3. Check and ignore if we are already on the `admin` pages.
4. Check and proceed if we are on a single `post` page.
## CODE:
Following is an example code that'll work:
function fyz_edit_redirect() {
if( ! is_admin() // skip if we are on admin pages already
&& is_single() // apply only if it's a single post
&& isset( $_GET['edit'] ) && ! empty( $_GET['edit'] ) ) {
wp_safe_redirect( admin_url( '/post.php?action=edit&post=' . get_the_ID() ) );
exit;
}
}
add_action( 'template_redirect', 'fyz_edit_redirect' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "php, plugin development, wp redirect"
} |
change div text and link for logged in users
this question was already similar asked but I don't find a way to get it working without using a plugin. So basically I got a text on my homepage which says login, so it's a normal text which i want to change to "my account" if a user is logged in. Also then the link has to change. I thought about creating 2 divs and hide one via css wether a user is logged in or not but this seems pretty inefficient and non-responsive to me. I would like to do it on my own but since I'm pretty new to php, I don't know how to do it.
Tnaks in advance | So, firstly thanks for your answer. The mentioned code above didn't work out for me, smh It doesn't recognize me being logged in.
Anyways I changed the if condition to the inbuilt logged_in check from wordpress/woocommerce and managed to fix it. So for everyone who is as desperate as I was, I will post the results
<?php
if(is_user_logged_in()) {
$link = '/myaccount';
$text = 'My Account';
} else {
$link = '/login';
$text = 'login';
}
?>
<a href="<?php echo $link; ?>"><?php echo $text; ?></a>
Use wp code snippets, create a shortcode, insert it and then style it via css :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, login, html, core, text"
} |
I'm building a WordPress theme and noticed that the 404 page template runs along with the corresponding templates for each page. Any idea why?
function debug($message){
error_log($message, 3, get_template_directory() . '/debug.log');
}
I added the above function to each of the templates.
For example, **front-page.php** includes a line that goes like this: `debug("front-page.php \n");`
I use `tail -f debug.log` in the terminal to determine which templates are being used by a particular page. Here is the result.
![enter image description here]( | I used the following function to retrieve the URLs of each page.
function template_debug($filename = null) {
$url = home_url($_SERVER['REQUEST_URI']);
debug("Called from: $filename using URL $url \n");
}
Then I inspected the front page which triggered the 404 template along with the front-page template. The **Network Monitor** tab showed the error, which was an incorrect folder name included in the CSS file.
After making the necessary changes, the 404 template isn't being triggered anymore. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "page template, template hierarchy"
} |
Properly sanitize an input field "Name <test@example.com>"
In my plugin I want administrators to be able to set the from name and email address in a single form field.
I anticipate the field content to be `Name <test@example.com>` However both `sanitize_text_field()` and `sanitize_email()` do their jobs and remove critical parts of the data.
Is there better way to do it rather than `wp_kses()`? | You could do something like this:
$input = 'Name <test@example.com>';
// Break the input into parts
preg_match( '/([^<]+)<([^>]+)>/i', $input, $matches, PREG_UNMATCHED_AS_NULL );
// Clean the name
$name = sanitize_text_field( $matches[ 1 ] );
// Clean the email
$email = sanitize_email( $matches[ 2 ] );
// Bail early if the values are invalid.
if ( !$name || !$email || !is_email( $email ) ) {
die( 'Invalid input' );
}
// Success!
$cleaned_input = "{$name} <{$email}>"; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "sanitization"
} |
Changing login url
I've been following this guide on how to change your login url : <
However, upon adding the logout, login and lost password hooks, I've noticed that I cannot log out anymore. Whenever I log out, it just redirects me to /wp-admin without logging me out.
How can I fix these issues? | I think the article's logout hook is wrong on two or three counts:
* it needs ?action=logout, similar to the lost password link
* it needs a generated nonce too
* it doesn't respect the $redirect argument.
Here's a new version based on the current wp_logout_url() code:
add_filter( 'logout_url', 'my_logout_page', 10, 2 );
function my_logout_page( $logout_url, $redirect ) {
$args = array();
if ( ! empty( $redirect ) ) {
$args['redirect_to'] = urlencode( $redirect );
}
$logout_url = add_query_arg( $args, site_url( 'my-secret-login.php?action=logout', 'login' ) );
$logout_url = wp_nonce_url( $logout_url, 'log-out' );
return $logout_url;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "hooks, login, logout"
} |
Using a variable in page permalink
I'm trying to alter some of my pages permalink by adding a variable in the permalink, it works for changing the permalink, but the link gets 404 error.
My page permalink:
My function:
add_filter('page_link', function($link) {
return str_replace('YEAR_NAME', '2023', $link);
});
As I said, the permalink changes from `YEAR_NAME` to `2023`, but the link gets 404 error.
Is there something missing? | > As I said, the permalink changes from `YEAR_NAME` to `2023`, but the link gets 404 error
Yes, and it's because the post slug no longer matched the value in the database (in the `wp_posts` table, column `post_name`), hence the permalink URL became invalid and WordPress displayed a 404 error page.
So you need to add a rewrite rule for handling the year value which replaces the `TOP_NAME` in the slug.
Here's an example you can try, and you can change the `^top_in_2023` with `^top_in_\d{4}` instead so that it matches _any 4-digit year_ :
add_action( 'init', function() {
add_rewrite_rule(
'^top_in_2023',
// for Pages, the query var is pagename
'index.php?pagename=top_in_YEAR_NAME',
'top'
);
} );
Remember to flush the rewrite rules, by simply visiting the Permalink Settings admin page. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "permalinks, url rewriting"
} |
theme.json should be in the child theme folder when using xxxx.json style located in the styles folder?
I'm making a child theme of TT3. I'm using a json style in my child theme located in a styles named folder. Do I have to have a copy of TT3 theme.json in my child theme ? | Short answer: No
Long answer: The child themes theme.json will simply use the TT3 theme.json values if a specific value is not found. So you can make a new theme.json file only with the specific values needed for the child theme.
An excellent writeup is available here: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "child theme, theme.json"
} |
Where did I put this one line of css?
So I'm a bit lost. There are so many places to tuck away custom css between the WordPress customizer and Elementor Pro, and I added some css to style a couple little recurring anchor tags in a file sharing list, but now I can't remember where I put it and can't find it. I have looked in every place I can think of.
I know now that I can put all of my additional css in the theme file (I created a child theme for that reason) but that doesn't help me now to find that one darn line of code to edit it.
**I did use the page source and found the css I added but where is the source file located so I can edit it?**
I am completely self taught through various resources and prerecorded classes online so I don't know what I don't know. I am pretty good with working in WordPress but I am new to editing the file itself rather than using custom code on individual pages via a plugin. | You can use the Developer Inspector (usually F9 in your browser) to bring up the page data. Right click where you see the CSS being used, and use the developer panel to click on the CSS code (you should be on the Inspector tab).
Over in the right side of that developer area you should see the various CSS styles. And to the right of that, the Computed CSS.
Click on one of the items in the Computed area. You should see the file and line number where that value came from. Example below. See the CSS for the 'border-top-right-radius' came from 'stacks.css' in line 8.
![Sample screen shot of developer area](
The screenshot is from the FireFox Developer screens. There are many tutorials on how to use this that you can find on the googles/bings/ducks. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, css, theme customizer"
} |
if get_post_meta do something
I use this to show custom product number field:
<div class="phone-num">
Phone: <?php echo get_post_meta(get_the_ID(), '_custom_product_number_field', true); ?>
</div>
How should nothing be displayed if the field is empty? | If you mean you don't want the `<div class="phone-num">` to appear at all, here's how:
<?php
$phone_number = get_post_meta(get_the_ID(), '_custom_product_number_field', true );
if ( ! empty( $phone_number ) ) : ?>
<div class="phone-num">
Phone: <?php echo $phone_number; ?>
</div>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
WordPress REST API - Custom field not added to pages
I have this code in my wordpress plugin. I'm working on an vue powered headless theme and I need to get all the informations about pages using the rest API.
I've registered with success a custom res field for a cpt, but now when I try to add a rest field for page object, it will be not added if I call the `wp-json\wp\v2\pages` I will not see the added field
function __construct()
{
add_action('rest_api_init', [$this, 'setup_custom_routes']);
}
function setup_custom_routes(){
register_rest_field(
'page',
'page_cover',
[
'get_callback' => [$this, 'get_pages_cover']
]
);
}
function get_pages_cover( $post ){
return get_the_post_thumbnail_url( $post['id'] );
}
Is there something wrong, or I need to do this in another way? | You may need to flush the REST API cache in order to see the added field. You can do this by adding the following code to your plugin:
This code will flush the REST API cache whenever a post (including a page) is saved or updated, so that the changes to the registered field will appear immediately.
If the field still does not appear after flushing the cache, you may want to check that the REST API request you're making is for a single page object and not a collection. The field will only be returned when you make a GET request for a single page, for example: wp-json/wp/v2/pages/123.
function flush_rest_api_cache() {
wp_cache_flush();
}
add_action( 'save_post', 'flush_rest_api_cache' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, plugin development, rest api"
} |
slider wont load unless you scrolldown on mobile, slick.js carousel
I use slick.js for my carousel. Everything is working fine on desktop but in my mobile I have this weird problem where the slider doesn't load correctly until I scrolldown. Have anyone here also experienced this, behavior.
<script>
$(document).ready(function() {
$('.row-one-container .sliders-container').slick({
infinite: true,
dots: true,
arrows: true,
responsive: [
{
breakpoint: 500,
settings:{
slidesToShow: 1,
slidesToScroll: 1,
infinite: true,
}
}
]
});
</script> | This behavior of the page is caused by the WP Rocker plugin you are using.
With the active " **Delay JavaScript Execution** " option (" _File Optimization_ " tab), all scripts on your website are loaded only after the user performs some action (e.g. will move the cursor). This applies to both the mobile and desktop versions.
Excluding just `jquery` and `slick.js` from lazy load in WP Rocket settings should solve the problem. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
} |
Using the REST API filter, including two meta_queries breaks the response for one custom post type
I'm using the WP REST API filter parameter plugin to be able to add filters to my REST requests.
This works fine.
Except, suddenly, adding two meta queries returns an Internal Server Error for, it seems, all post types.
So, this is a problem:
These are not:
Beyond a doubt, this worked up till very recently.
I modify my API responses, but this problem persists after removing all my modifications.
I have no idea where to start looking for what could be the underlying problem. Any ideas would be great.
FWIW, removing the `_embed` and `_fields` parameters makes no difference.
Update: I've been able to replicate this on another Wordpress install. | Oddly, the cause of the problem seems to be the quotation marks around the comparison parameter.
For example `filter[meta_query][0][compare]=%27=%27` now needs to be `filter[meta_query][0][compare]==`.
When only matching one meta value, this is not necessary, when matching two, this is, now, necessary. :/
Update: I realised that my hosting provider changed the version of Linux on my server around the same time. I can imagine this might be connected. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, rest api"
} |