INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Site in subfolder - all pages work except home
Our WordPress site is in a subfolder `/subwp/`, and all pages except the home page work. This is the root folder:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /subwp/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /subwp/index.php [L]
</IfModule>
When visiting the homepage (e.g. ` I get the hosting providers default site ('this domain is hosted by xyz'). All other slugged pages work perfectly.
Just to make sure that the hosting provider is not somehow auto redirecting requests to `/`, I created a file named `index.php` with just 'blah' in it, to see if it would work then, and then if I visit ` I see the text 'blah' (and also all other pages display blah now :))
I'm kinda stuck. Any ideas? | Because when you request the document root, the rule in `.htaccess` does not match and the request is not rewritten to the subdirectory. So the request falls through and whatever is the default response for the document root is served (eg. `/index.php` if it exists).
You need to add another directive to rewrite the homepage only.
(The first `RewriteRule` directive is not correct either.)
For example:
RewriteEngine On
RewriteBase /subwp/
RewriteRule ^[^/]+/index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
# Special case - rewrite requests for the homepage (which is also a directory)
RewriteRule ^$ index.php [L]
Since you are using `RewriteBase` you can remove the `/subwp/` prefix on the `RewriteRule` _substitution_ strings (that's the whole point of using `RewriteBase`). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "htaccess, mod rewrite"
} |
Items from media library won't get added to a custom taxonomy
So I created 2 custom taxonomies and attached these to the media post type
:
add_action( 'elementor/query/acf_filter', function( $query ) {
$value = the_field( "category_filters" );
}, 10, 1);
That query doesn't work. All the categories are rendered instead of selected ones. Above, there is the field rendered with categories ID, see the photo:  {
$filtre = get_field( "category_filters" );
$query-> set('cat' , $filtre );
} ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, query"
} |
Show code dependant on CPT & category
I'm currently using the following plugin on my WordPress website to show our up coming events:
<
I need to write an IF statement that will check the custom post type and then a category of the post type which will then return my custom code.
So far I've tried the following code:
`if ( is_singular( ‘eventbrite_events’ ) && has_category( ‘network’ ) )`
If I remove the category reference it works, but it will show my custom code on all events pages. Whereas I only want it to show the code in a certain category of the custom post type. | `has_category` applies only to default `post` type. You are working on a CPT so you should use has_term()
if ( is_singular( 'eventbrite_events' ) && has_term( 'network', '{YOUR_CUSTOM_TAXONOMY}' ) )
where {YOUR_CUSTOM_TAXONOMY} is optional and it must be the slug for eventbrite_events taxonomy to which the term 'network' is attached to. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, php, slug"
} |
Adding tawk.to code just before body tag on functions.php file
I would like to add tawk.to widget script just before the body tag. I would like to add the code to the functions.php file of my child theme. How can I do this? A code sample will assist a long way. The following is my code:
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script--> | You can the code to head or before body tag this way. Add this code at the last of `functions.php`
add_action( 'wp_head', function() {
?>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date(); (function(){ var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0]; s1.async=true; s1.src=' s1.charset='UTF-8'; s1.setAttribute('crossorigin','*'); s0.parentNode.insertBefore(s1,s0); })();
</script>
<?php
} );
Hope it helps | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, functions, javascript, child theme, wp enqueue script"
} |
Resize post thumbnail
I'm trying to ensure that all assets are the same size, no matter what resolution they are uploaded in. I'm stuck finding outdated info on the matter, I think.
I've gotten to the following snippet
if( get_the_post_thumbnail_url()){
$image = wp_get_image_editor(get_the_post_thumbnail_url());
if ( !is_wp_error( $image )){
$image->resize( 300, 300, true );
$image->save("image.jpg");
}
}
Which seems to work, but I have no idea how I get the resized URL (or insert it properly). As I want to add it to my page. Something like
echo '<img src=" . $image.url() . ">";
Is what I'm thinking of. Am I going about this wrong, or how should I continue from here?
Thanks! | Why don't you use this `add_image_size( 'custom-thumbnail', 300, 300, true );` in `funtions.php`
and call it `<img src="<?php echo get_the_post_thumbnail_url('custom-thumbnail'); ?>">` in your page? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, images, post thumbnails"
} |
Taxonomy archive page listing terms instead of posts
Is it possible to show list of taxonomy terms in archive page instead of the post list? Via modifying the query and not temper with theme templates?
I have a taxonomy archive that I want to display list of terms from another taxonomy, because they are linked via term meta.
Is this possible to achieve? | Not without messing with templates, no.
All WordPress pages are based on a query for a post or posts. If you want to list terms the only way to do that is a custom template that queries the terms and lists them. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, query, advanced taxonomy queries"
} |
Hook to execute after deleting a Custom Taxonomy
I need to execute a portion of code after each: Add / Edit / delete a custom taxonomy . For creation / edition it works well, but for deletion non :
add_action( 'edited_product_category', array ( $this , 'term_edit_success' ), 10, 2 );
add_action( 'create_product_category', array ( $this , 'term_create_success' ), 10, 2 );
add_action( 'delete_product_category', array ( $this , 'term_delete_success' ), 10, 2 ); | I changed the hook to this :
add_action( 'delete_term_taxonomy', array ( $this , 'term_delete_success' ), 9, 1 );
it resolved my issue. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
Check if current page is using blocks (Gutenberg) or is legacy
Is there a way to know if a page is using Gutenberg or not?
The use case is migrating an old post to Gutenberg and letting crafted pages just render themselves with blocks but add some wrapping around old pages which probably won't be migrated since they're just text (Privacy policy and those). They need to coexist at least for a while.
A block editor page can usually be just rendered with
<?php
get_header();
while (have_posts()) :
the_post();
the_content();
endwhile;
get_footer();
While I have that handled for the homepage using a p `front-page.php` template, I'd like to have a generic template that can handle both types so I don't have to go slug by slug. | I know it's been awhile, but yes. You can check if a post uses blocks, check out `has_blocks()` : <
I'm using it when filtering content, to see if I need to parse blocks or not. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "block editor"
} |
Why Does The `auto_update_plugin` Hook Disable Management?
I'm working with the `auto_update_plugin` to update active plugins on a specific schedule. If the current time is between X and Y then the filter returns true and the plugin is allowed to auto-update.
The problem I'm running into with this hook is that the return value either enables or disables update management entirely. This means that by returning `true` I am unable to disable updates for a specific plugin as the "Automatic Updates" link is removed and replaced with text.
Why does this happen?
Is there a better hook to allow users to manage which plugins should auto-update while also being able to filter when it should auto-update? | The root problem here is a misunderstanding of the appropriate hook. `auto_update_plugin` does not control if automatic updates are enabled, but rather it's a filter to gain finer control over wether a specific plugin should auto update a specific update.
For example, if you want to enable or disable wether plugin auto-updating is possible, use the `plugins_auto_update_enabled` filter.
If you want to override a plugin and force it to auto-update or not update, use `auto_update_plugin` and inspect the second parameter, the format of which matches what the .org API at < would return | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development"
} |
wp_enqueue_scripts
How to remove `<link rel='stylesheet' id='geowidget-4.5-css-css' href=' type='text/css' media='all' />` in only for front-page and products pages.
I tried this code:
function remove_font_awesome() {
wp_dequeue_style('geowidget-4.5-css-css');
}
add_action ('wp_enqueue_scripts', 'remove_font_awesome', 9999);
add_action( 'wp_head', 'remove_font_awesome', 9999 );
I see still this css on all pages. | In a link element ids WP add **-css** , so you need to remove it.
May be this will help:
function remove_font_awesome() {
wp_dequeue_style('geowidget-4.5-css'); // not geowidget-4.5-css-css
}
add_action ('wp_enqueue_scripts', 'remove_font_awesome', 9999);
add_action( 'wp_head', 'remove_font_awesome', 9999 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, php, functions"
} |
Is it good practice to use wpdb->query() function?
I am using custom php code to perform data insertion, deletion, updating and other tasks. I am able to insert data into a table in two different ways,
$wpdb->insert($table_name, array('id' => NULL, 'name' => '$name', 'email' => '$email', 'city' => '$city'));
and
$sql = "INSERT INTO $table_name VALUES('', '$name', '$email', '$city')";
$wpdb->query($sql);
Is it a good practice to use `wpdb->query()` function each time by passing my query to the function instead of using the dedicated functions like `insert()` and `delete()` etc? If not, what are the disadvantages of this approach? | If you look a bit into the source, you'll see that `$wpdb->insert()` will use `->query()` under the hood. So should be the same, right?
Not that simple. It doesn't just use `->query()` but also `->prepare()`, which is considered best practice. Meanwhile with your code example you've probably just opened yourself to SQL injections.
The takeaway here: If it is a simple operation and the `->insert()` etc. method work - use them. They're tested and contain little risk. Writing your own queries always carries the risk of opening yourself up to troubles such as SQL injections. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 1,
"tags": "functions, database, query, mysql"
} |
How to make email field not required in comments?
I need to make email field not required in comments, is it possible ?
I know about this option: < But then Name field will not be required to
Thanks! | You may use this filter. Removing the required field option from the form.
`add_filter('comment_form_default_fields','modify_comment_fields');` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments"
} |
Show wp_die if url form comment not emply
I removed the url from in comment block, but spammers still post comments and add links. How to rejected comment if url not empty?
Sorry fom My English. | For all simple operations prior to comment submission use the action `pre_comment_on_post`. Like this:
add_action( 'pre_comment_on_post', function() {
if ( !empty( $_POST['url'] ) ) {
wp_die( 'Go away!', 'Nope', [ 'response' => 403, 'exit' => true ] );
}
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, comments"
} |
Parse error: syntax error, unexpected 'echo' (T_ECHO) in C:\xampp\htdocs\AttendanceSystem\resources\php\method.php on line 250
How to echo php variable in html that in String
$body = '<p style="font-size: 18px; line-height: 1.2; text-align:; word-break: break-word; mso-line-height-alt: 22px; margin: 0;"><span style="color: #2b303a; font-size: 18px;"><strong>Name: </strong><span style="font-size: 16px;">'echo $student_name'</span></span></p>' | You don't need to echo it. You can just add it to the string since we're in PHP at that point:
'<span style="font-size: 16px;">' . esc_html( $student_name ) . '</span></span></p>'
You should also escape any variables you're adding to HTML strings using esc_html() in case the strings contain HTML tags not just plain text. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "php, html"
} |
How to persist custom posts, custom fields and styles on a Github repository?
I need to send a code to a third person through Github with custom posts and custom fields for them just add the posts.
I have tried to find this approach online but I could not find the answer since all of them just talk about version control between local and production WP.
I am using `MAMP`, `ACF` and `Custom Post Type UI` to develop the site, linking the custom fields to custom post. | ACF has two options for this:
1. PHP / JSON exports
2. acf-json
Method 1)
Go to ACF->tools->select field->export file / generate PHP.
If you choose generate PHP, you can copy the result into a .php file in your theme, which you then need to include. You cannot import PHP exports though ACF again: the fields will be available but you will not be able to edit them through the ACF UI.
If you choose JSON, you can import them again and edit them through ACF.
Method 2)
I prefer this method: create a folder called acf-json in your main theme folder. ACF will detect the folder and automatically save a copy of the fields as JSON files.
Whichever method you choose, make sure to add/commit any files created/changed to your repo.
Never used the Custom Post Type UI plugin, but I imagine it has a similar import/export capability.
Alternatively, you can also share an export of your DB, but there will be no version control for fields/etc. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "github"
} |
$wpdb->get_results($wpdb->prepare(... You have an error in your SQL syntax;
I am making a database request in wordpress to make this question: select * from tc_chat_clt;
How ever a error appears, what am I doing wrong?
$users = $wpdb->get_results($wpdb->prepare('SELECT * FROM %s',`tc_chat_clt`)); | PHP views backticks (ie, ``) as delimiting something that should be executed, not as a quotation character. Use single quotes (`'`) instead.
$users = $wpdb->get_results($wpdb->prepare('SELECT * FROM %s', 'tc_chat_clt')); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database"
} |
How to scroll item in the Menu setting effectively?
My menu list is so long. If I want to move an item to the top of the list, I need to hold and scroll all the way up. This is inefficient and annoying. Is there any way to improve this process?
 the menu becomes an hamburger (). I want to know how to do the following two things:
1. Change the default status of the menu from the "not toggled" status (when you can only see ) to the "toggled" status (when you can see the whole opened menu, and tapping on closes it).
2. Change the symbol from to another, perhaps something like " MENU" or perhaps an entirely different thing.
How can I do these things? If it helps, I am using the Illustratr theme and my website (under construction) is < | You can remove the current icon by css and then you can add your new icon in the .menu-toggle button with background-image.
the css is below;
.genericon-menu:before{
content: " ";
}
.main-navigation .menu-toggle{
background-image: url(/*image url*/);
background-size: contain;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "customization, menus"
} |
I want to disable login of admin (/wp-admin) with email and make it accessible only with username
I want to do it as a security precaution. I've already taken other actions. But I want to be able to login only with my admin username. Is there a way to do that or even a plugin? | Yes, you can disable login by email by removing the specific authenticate filter:
remove_filter( 'authenticate', 'wp_authenticate_email_password', 20 );
from a plugin or your theme's functions.php. This won't update the UI though, which will still say 'Username or Email Address'. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin, admin, login, security"
} |
Add more then one site logo - custom-logo theme support
We can add one site logo to site customize with ` add_theme_support( 'custom-logo' );`
How can add another logo? Seems like the custom-logo theme support only allows to add one site logo and I need to a footer logo as well
I know its possible to add this to a custom theme settings page but prefer to add this to the customize screen same place where theme logo is added. | I think you might be looking for something like this:
add_theme_support( 'custom-logo', array(
'height' => 480,
'width' => 720,
) );
You could also go with:
add_theme_support( 'custom-header', array(
'height' => 480,
'width' => 720,
) );
Use the custom-header for the top logo and the custom-logo for the footer (or the other way round).
Another approach might be to define a thumbnail size:
add_image_size( 'custom-footer-logo', 220, 220, array( 'left', 'top' ) );
You would have to work with the WordPress customizer controls to make a control to add and change the footer. But you could add as many images to your theme as you want that way. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "customization, theme development, theme customizer, logo, header image"
} |
Display multiple custom taxonomy values on single custom post types page?
I can't seem to figure this out, I have tried and looked at multiple forums posts with example codes but nothing is working for me.
I have wordpress and a custom post type called videos-on-demand.
Video on demand post type has a few taxonomies like age, teachers, length of video, etc..
I created a test post and made a custom page that is working and I am able to customize it... however I can't get the taxonomies to show on the footer of the page similar to how you would see categories and tags on a standard blog post.
I want to be able to click on those terms/links to bring you to an archive of all those terms for searchability.
What am I missing here?
<?php
$terms = get_the_terms( $post->ID, 'video-on-demand' );
foreach($terms as $term) {
echo $term->name;
}
?> | The first line of code in your question appears to be the problem.
The `get_the_terms()` function expects the post (object or ID) as the first parameter. The second parameter should be the taxonomy name, not your custom post type.
Something like this should work for you:
$age_terms = get_the_terms( $post->ID, 'age' );
$lang_terms = get_the_terms( $post->ID, 'language' );
`get_the_terms( int|WP_Post $post, string $taxonomy )` < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, customization"
} |
Why do I keep losing links when I switch to visual editor in Wordpress
I have this problem in a specific page of my wordpress website: when I switch from text editor to visual editor I immediately lose all my links (placed in a div element).
I give you a detailed example of what happen every time:
**I start editing my page and the section with href looks like this**
 can contain other inline elements and text nodes.
and
> Generally, block-level elements may contain inline elements and other block-level elements. Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.
Anchors are inline, while `<div>` tags are block-level, hence the block-level element cannot go inside of the inline element. If you need the element inside of the link, try using a `<span>` with the `display:block` CSS property:
<a href="somelink"><span class="tag">Link</span></a> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp admin, visual editor"
} |
Create custom function for hero image
I'm newbies with php development and I want create a custom functions
I would like to create a function that calls an image which has the same name as the product but I fail to call the product name and then place it in the image name. Could you help me please.
my code :
add_action('init', 'custom_hero_image');
function custom_hero_image() {
$result = get_the_title( 'ID' );
if ( is_product() ) {
$html .= '<img class="jarallax-img" src="'. get_template_directory_uri() .'/inc/assets/img/shop/hero/'.$result.'.jpg">';
} else {
$html = '<p>No results found.</p>';
}
return $html;
}
What I'm doing wrong? | `get_the_title()` returns the post (product) title including all HTML, whitespaces and symbols not allowed in URLs, etc. Use post slug instead.
Also, you don't need to use any actions.
function custom_hero_image( $post_id ) {
$product = get_post( $post_id );
$slug = $product->post_name;
if ( is_product( $post_id ) ) {
$html = '<img class="jarallax-img" src="'. get_template_directory_uri() .'/inc/assets/img/shop/hero/'.$slug.'.jpg">';
} else {
$html = '<p>No results found.</p>';
}
return $html;
}
And call the function within a template file:
<div id="hero">
<?php
// get the post ID outside the Loop
$post_id = get_queried_object_id();
// print the <img>
echo custom_hero_image( $post_id );
?>
</div> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, customization, woocommerce offtopic"
} |
Blocks. How to store default settings?
I use a default custom image block in all my articles in 3 blogs, aligned left, link to media file.
In Gutenberg every time I upload/insert a new image I have to reconfigure those settings.
Seems stupid but it's frustrating if you only use 2-3 kind of blocks repeatedly, a long waste of time.
Is there some way to define "default settings" for some block, especially paragraph and image? | As Tom mentioned, you can use Templates, which allows you to define a preset of blocks that are available by default in your post whenever you try to create a new post: <
If you aren't ready to get your hands dirty with code, you can also use Justin Tadlock's Block Pattern Builder plugin to create and re-use block patterns across your site: <
Hope it helps! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "block editor"
} |
How to use get_theme_mod in gutenberg editor wordpress?
In my old WordPress themes (before Gutenberg) I used `get_theme_mod` to get custom values for certain things in the theme.
get_theme_mod( 'news_custom_headline' );
Now I would like to use the gutenberg editor, however still want to access data from the customizer. How can I do something like this:
save({ attributes }) {
return <p>Value from backend: get_theme_mod( 'news_custom_headline' ) </p>;
} | **You don't** , if you need a dynamic value you have to have a server rendered block.
Otherwise, if you managed to get the theme mod, it would be frozen to the value it had at save, and changing the value in the customiser would not update the blocks. So use a dynamic server rendered block and grab the value in PHP the same way you normally would. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, plugin development, customization, theme development, block editor"
} |
Get HTTP response code on non-2xx apiFetch request
I'm using WordPress' apiFetch library to make requests (in WordPress admin dashboard) to my WordPress REST endpoints. It looks like apiFetch will throw an error if the response is a non-2xx code, using the JSON body of the response as the error. However, it does not appear to be inserting the HTTP code anywhere in that error.
This is necessary since it allows me to differentiate between a "normal" error (like 404 if the resource asked for does not exist) and an "unexpected" error (like a 500 internal server error). | By default, apiFetch will parse the response for you automatically. You can get the raw response object by setting `parse` to `false` in the `apiFetch` option, e.g.:
const handleClick = async () => {
try {
const result = await apiFetch( {
path: '/your/path',
parse: false,
} );
console.log( result ) // you will see ok status (e.g. 200) in here.
} catch ( error ) {
console.log( error ); // you will see error status (e.g. 404 or 500) in here.
}
};
More info: apiFetch's parse option
Relevant code for parsing the response: see utils/response.js in apiFetch | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "javascript, rest api"
} |
What is the alternative code to if (isset ($_POST) && !empty ($_POST) to avoid warnings?
I am trying to insert some php code to my WordPress website but it gives security warnings perhaps due to directly accessing `$_POST` variable.
Instead of `$name = $_POST['name'];`, I can use `$name = filter_input(INPUT_POST, 'name');` however I am not able to figure out what alternative piece of code I should use instead of `if(isset($_POST) && !empty($_POST)) { //some code }`?
Thanks for your help in advance. | `filter_input` is the proper way to go. If it doesn't return anything valid, it will return `null`:
$myvar = filter_input( INPUT_POST, 'something', FILTER_SANITIZE_STRING );
if ( empty( $myvar ) ) {
// Do whatever you would have done for ! isset( $_POST['something'] )
}
// Use $myvar
`filter_input` won't throw any notices if the requested index isn't found, so it's like having `isset` built-in to the function.
**Edit:** just be sure to use a `FILTER_` to sanitize or validate, and note there are some gotchas that are documented in PHP's documentation about these. For most general use-cases they should work fine, but always validate your user input appropriately once you have it (the same as you would when getting it directly from `$_POST`). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, forms, variables, globals"
} |
How to Remove or Deactivate "Application Passwords" in WordPress
With version 5.6, I got this new weird "Application Passwords" under all user profiles. No idea what it is and what it does except for what it says -- and I want it gone.
If anyone knows how to remove this using `__return_false` with a filter or something, please tell me. I've googled and looked at the developers handbook and so far; nothing.
See image for more information.;
or wp_is_application_passwords_available_for_user to turn them on and off by role or individually. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "password, profiles"
} |
How to get the latest posting time of archived pages in WordPress?
Is there a way to get the post time of the latest post under the WordPress archive page?
I would like to add a feature to the archive page to show the latest time of posts published under that category.
Any help, thanks in advance! | Query the posts ordered by date, restricted to 1 post to display, then get the date.
$args = array(
'posts_per_page' => 1,
'orderby' => 'date',
'order' => 'DESC'
);
$lastpost = get_posts($args);
echo $lastpost[0] -> post_date;
Edited last line for proper display:
$lastpostdate = $lastpost[0] -> post_date;
echo '<div class="lastpostdate>"' . $lastpostdate . '</div>';
Or, if you already have the query with the default order, you can just get the last post's date from it:
// assuming $myquery is your query
$lastpostdate = $myquery -> posts[0] -> post_date;
Or, if you have not altered the global query, in archives just use:
$lastpostdate = $wp_query -> posts[0] -> post_date; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "posts, archives, date time"
} |
Looking for a free quiz plugin which saves the candidates answers for review
I am trying to create a nice quiz for my students which is not single or multiple choice. My questions are about historical topics or books so the students might add a couple of sentences as answers. Therefore I want to save the results and later on check them. Currently I have HD Quiz installed and their additonal plugin to save results, but unfortunatly it just saves how many questions where answered right or wrong. Is there any plugin available which saves the text as result or some workaround? | The free plugin - QSM Quiz and Survey Master does offer this functionality in the free version. You can define whether the user has to be logged in or not etc. As answer to your question you select "short answer" and the answer will be stored for later review. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Add a word to the first // wp_get_attachment_url // as the subdomain name
We use this code to display the link ...
$mp3Link = wp_get_attachment_url($mp3_file_id);
<a class="w3-black" href="'.$mp3Link.'" rel="nofollow" >mp3</a>
It looks like this now :
<
I want it to be like this :
<
I mean, I just want to do this by editing the above code | $mp3Link = wp_get_attachment_url($mp3_file_id);
$mp3Link = str_replace( 'example.com', 'sub.example.com', $mp3Link );
<a class="w3-black" href="'.$mp3Link.'" rel="nofollow" >mp3</a>
replace `example.com` with your actual domain - it's not the most elegant solution, but might work. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "attachments"
} |
Wordpress widget not appearing in editors widget list
I have created a custom Wordpress (5.6) widget named "Server" which can be added to all sidebars without any problem:
 to map?
for example
i know that subdomain.mydomain.com is possible but subdomain.notmydomain.com can be possible?
what can be the requirements/suggestions for such a setup in terms of hosting.
thank you. | If you have control of the DNS settings for "notmydomain.com", then sure. A subsite can be under a completely different domain if you want. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "multisite, hosting, domain mapping, dns"
} |
Header menu aligned right on all pages except for single-post page
I have a header with a logo, menu items and a search bar. I have aligned the menu on the right (close to the search bar), but in the 'single-post' page, the menu items appear on the left, starting right after the logo.
The header HTML is the same for each page (I'm getting it using the get_header() function) and the CSS is a single shared file between all components.
I am really dumbfounded here... I've developed the theme myself so maybe I did something to cause this, but I don't really know how it's possible for a completely identical component to appear differently on different pages.
EDIT: I am using the boostrap navbar with the ml-auto class for aligning on the right. | I added custom css to a plugin that apparently affected the navbar too. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, customization, menus, themes"
} |
Custom post type editor uses old tinyMCE
It is an old site made before the new block editor arrives. Now it's running WP 5.0.11, and I do not want to make an upgrade right now for various reasons.
The default post types are using the new block editor, but the custom post type still use the old TinyMCE and I even cannot insert images to it. The image problem wold not be a problem if I could switch to the block editor witch works.
Thank you in advance. | In your code where you defined your custom post type (in a custom plugin or in your `functions.php`file), you need to add this snippet for Gutenberg block editor support:
'show_in_rest' => true,
'supports' => array('editor')
Here is an example:
function portfolio_post_type() {
register_post_type( 'portfolio',
array(
'labels' => array(
'name' => __( 'Portfolio' ),
'singular_name' => __( 'Portfolio' )
),
'has_archive' => true,
'public' => true,
'rewrite' => array('slug' => 'portfolio'),
'show_in_rest' => true,
'supports' => array('editor')
)
);
}
add_action( 'init', 'portfolio_post_type' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, block editor, tinymce"
} |
Enqueued style gets commented if not logged in
When using stylesheets I like to use wp_enqueue_style to have wp handle the loading. For some reason this works perfectly fine when I am logged in. But when I am not logged in the include statment gets wrapped in html comments, thus the browser doesn load the stylesheet. When loading I use: `wp_enqueue_style("a-unique-name-style", plugins_url('/css/filename.css',path);`
I also tried
function name_enqueue_style() {
error_log(__LINE__);
wp_enqueue_style("a-unique-name-style", plugins_url('/css/filename.css',path));
error_log(__LINE__);
}
add_action( 'wp_enqueue_scripts', 'name_enqueue_style' );
But name_enqueue_style does not load at all. (Nothing in the error log either.)
I run this from both the plugin "main" php as from functions that build widgets.
What is happening? I don't even know where to start looking. | as Tom J Nowell asked in the comments a caching plugin was the culprit. In this case WP Fastest cache. Just deleting the cache did not work. Turning the caching off and on again fixed the problem.
update: I did some more digging and the fact it gets commented is correct. The caching plugin also runs a code minimizer. For some reason the minimized code did not use the stylesheet I added. Turning it off and on again forced a rerun of the minimizer (I guess). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp enqueue style"
} |
'user_register' hook - need to distinguish if created from wp admin panel
Users are created in two ways in my application.
The registration form uses a gravity form hook to register the user and send to various api's.
But when creating a user from the admin panel, we use the '`user_register`' hook.
This causes a conflict because in the gravity form procedure , when calling `wp_insert_user()`, it triggers the '`user_register`' hook , interrupting the script which isn't finished saving the user to the api's.
So I would have liked a hook which is only triggered when run from the admin panel. Can this be accomplished? | You could use the `user_register` hook, then check if the user registration is happening from an admin interface with `is_admin()`:
> ### is_admin()
>
> Determines whether the current request is for an administrative interface page.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "hooks, user registration"
} |
Re-Direct ALL Users to the Home Page IF not logged in
I just read the codex on `wp_redirect();` and found an example that I modified. Problem is, all I get is an error in my browser saying "The page isn’t redirecting properly".
I need all users, unless logged in, to be re-directed to the home page (`home_url()`).
Can someone please help me?
add_action( 'template_redirect', 'not_logged_in_redirect_home' );
add_action( 'do_feed', 'not_logged_in_redirect_home' );
function not_logged_in_redirect_home() {
if ( is_home() ) return;
if ( ! is_user_logged_in() && is_home() ) return;
if ( ! is_user_logged_in() && !is_home() ) {
wp_redirect( home_url() );
exit;
}
} | Perhaps something like this?
add_action( 'template_redirect', 'not_logged_in_redirect_home' );
add_action( 'do_feed', 'not_logged_in_redirect_home' );
function not_logged_in_redirect_home(){
if ( is_user_logged_in() ){
return false;
}
if (
! is_home() // use this option if you show blogs posts on the home page
// ! is_front_page() // use this if you show a static page
){
wp_redirect( home_url() );
exit;
}
}
Check the documentation on is_home() - <
Since WordPress 2.1, when the static front page functionality was introduced, the blog posts index and site front page have been treated as two different query contexts, with is_home() applying to the blog posts index, and is_front_page() applying to the site front page
So, you might need to use is_front_page() - depending on your setup. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect, wp redirect"
} |
Fetch_Feed cURL error 28
So whenever I try to use fetch_feed with urls like the one below, I get back _" WP HTTP Error: cURL error 28: Operation timed out after 30070 milliseconds with 0 bytes received"_ However when I use just a plain cURL on the url get a response. So I can only conclude something in Fetch Feed is the issue. Anyone have a better idea how to get past this issue?
include_once( ABSPATH . WPINC . '/feed.php' );
$feed_url = '
$rss = fetch_feed( $feed_url );
var_dump($rss);
Edit: I did some digging in the fetch_feed function, and found it worked when I commented out
$feed->set_file_class( 'WP_SimplePie_File' );
Any reason that could be? Any way to make this change in the theme file so it's not changed when wordpress is updated? | Maybe it's just us, but it seems like you need to set a user agent other than the default which is stored in the `SIMPLEPIE_USERAGENT` constant, and with `fetch_feed()`, you can use the `wp_feed_options` hook to set a custom user agent — or none also worked for me.
Working example:
add_action( 'wp_feed_options', function ( $feed ) {
$feed->set_useragent( 'MyPlugin/1.0' ); // works
$feed->set_useragent( $_SERVER['HTTP_USER_AGENT'] ); // works
$feed->set_useragent( '' ); // empty; worked for me..
// You can also try increasing the timeout, but the default one (10 seconds)
// worked fine for me.
$feed->set_timeout( 15 );
} ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "feed"
} |
Delete post revisions only for a single post
How to delete post revisions only for a specific post identified by its ID using an SQL query? | If you need an SQL query, then this option should be suitable
function src_flush_revisions () {
global $wpdb;
$post_id = 5//exp post id
if ( isset( $timeLimit ) ) {
$revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT `ID` FROM $wpdb->posts WHERE `post_type` = 'revision' AND `post_parent` = %d", $post_id ) );
foreach ( $revision_ids as $revision_id ) {
wp_delete_post_revision( $revision_id );
}
}
}
add_action( 'admin_init', 'src_flush_revisions' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, database, query, revisions"
} |
How can I automatically download all images from all imported posts, place them on my new host, and replace all the links
First some background information.
I have an old website ( **not** _wordpress_ ) => < from now on, I will call this **old**.
I have a new website ( _in wordpress_ ) => < from now on, I will call this **new**.
I have imported all posts of the _old_ website through an RSS feed into my _new_ website. The links to all the images inside those posts remain linking to the old website.
* The images on the old website are served trough an _axd_ file < (So I can't just change the path everywhere)
Is there some kind of plugin that let's me download all the images, replace all the links in all posts, and serve those images trough my _new_ website? Or are there perhaps other ways to do this? | There are plugins that do this, e.g. Auto Upload Images (found in this article). I haven't tried it myself to recommend it.
You're migrating from BlogEngine.NET. There is also an old BlogML importer plugin to migrate directly from BlogEngine.NET (which produces BlogML exports), but the copy in the main WordPress directory hasn't been updated in years and is no longer available to download. There is a fixed up version here: < however the process does also require manually fixing up image paths. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, posts, images"
} |
Some weird users in database
I've noticed that I have some users that seem fraudulent in my database (in the wp_users column). And the curious thing is that they don't appear in the users list in the admin panel.
How could this happen?
many thanks | Might be this is due to the Spam. Diable use registration under the `General -> Settings` if you don't need registration on the front-end or use the `captcha` or other `spam` protection plugins.
Regarding the backend -> Have you checked the wp_usermeta table if any role assigned to those users or not? Check user roles for those users. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, users"
} |
Wordpress not showing jQuery
I am trying to link a new JavaScript file where I want to add some custom jQuery to the content. But it is not showing on my website or pages.
Here is the code in `functions.php` and my JavaScript file
function my_child_script(){
wp_enqueue_script(
'custom-child',
get_stylesheet_directory_uri() . '/js/child-custom.js',
array( 'jquery' ),
'1.0.0',
true
);
}
add_action( 'wp_enqueue_script', 'my_child_script' );
and this is what am trying to do in my custom js file
jQuery(document).ready(function() {
jQuery(".block-title-wrap").hide();
}); | Just replace your add action line to this one: `add_action( 'wp_enqueue_scripts', 'my_child_script' );` and check again | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, wp enqueue script"
} |
How to hide description on categories and tags?
Does anybody know how I can hide the descriptions from view for the categories and tags for my website? I have searched for a while but can't find any solutions. I would like it so that when they are clicked it just shows the categories or posts available, no description visible. Can someone show me how to do this please?
< (when hovering the mouse over the category it brings up a description).
< (when opening a category it shows a description).
< (when opening a tag it shows a description).
(Author wordpress theme).
Happy new year! | If there is no description disabled in the theme settings, then you will have to edit the template files. This description is displayed in the title tag of the link, and you need to look for the category_description () function in the files. If you find it, you can just comment it out. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, description"
} |
Any tips for a plugin to define specific pages navigation for specific types of users / members?
Is there a plugin for Wordpress to define sort of a membership program? My requirement is to have registered users, basically members, and according to their (paid) plan, they can have access to some specific areas of my website.
Currently I found < but I was wondering if there are other plugins on the market. So I can evaluate pro and cons of more than one plugin and target my best choice.
Thanks in advance | If you just want to display a different menu then use the below Plugin, Define the different roles for each plan, and set menu/navigation accordingly.
<
For the Membership plan, I guess you already set up the membership plugin or you can use the Paid Membership Pro plugin | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, membership, plugin members"
} |
Execute shortcodes in PHP
I have a geolocation shortcode which i am adding in the post editor to display different information based on user's location, works perfectly by having it in the post page content.
How can i execute this shortcode [geolocation][/geolocation] inside a PHP file of my theme? i am using a free to modify Wordpress theme and i want to add a new `<span>[geolocation][/geolocation]Information text content</span>` but inside the theme's .php file, how can i do that? if i add straight the `<span>[geolocation][/geolocation]Information text content</span>` it will show the shortcode as text, it won't execute, please help, thanks in advance. | Found it: `<?php echo do_shortcode( '[your shortcode goes here]' ); ?>` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode"
} |
Add term of current custom post type to admin body class using admin_body_class
I am trying to add the current custom post type term to the body class of my WordPress admin page. So when I am viewing an existing custom post type that has been assigned a term it will add that term to the body class.
I have found the following code but cannot get it to work for me:
add_filter( 'admin_body_class', 'rw_admin_body_class' );
function rw_admin_body_class( $classes )
{
if ( 'post' != $screen->base )
return $classes;
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'all' ) );
$terms = wp_list_pluck( $terms, 'slug' );
foreach ( $terms as $term )
{
$classes .= ' my_taxonomy-' . $term;
}
return $classes;
}
Any pointers on how to get this working? | I think you're missing `get_current_screen()`.
add_filter( 'admin_body_class', 'rw_admin_body_class' );
function rw_admin_body_class( $classes ) {
$screen = get_current_screen();
if ( 'post' != $screen->base ) {
return $classes;
}
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'all' ) );
$terms = wp_list_pluck( $terms, 'slug' );
foreach ( $terms as $term )
{
$classes .= ' my_taxonomy-' . $term;
}
return $classes;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "admin, body class"
} |
Custom Plugin - Package and Deployment Solutions
We are a very small company working with a specific customer base. In this, we often have to create small WP plugins specific to the customer. Typically, we re-use our own basic folder structure and files (base php file that lays out some standard variables, assets folder structure for css and js files, installation/settings features templates, etc.).
We don't currently use anything that is "industry standard" or that will package, process, combine or minify our files for deployment (css, scss, js, etc.). Does such a thing exist? I'm familiar with the package/deployment of Vue/React and I'm curious is something similar exists for WP or if there are any standards for this?
I've done some research but can't seem to find a clear solution. | Sounds like you are trying to find a way to "build" your public assets - this is commonly achieved using Task Runners - Grunt or Gulp are two well-known examples.
Grunt is part of Node.JS, so you would need to download and install the node.js app and then find the packages you want to use - such as dart-sass for scss or uglify for minification of JS
The last step would be to config the gruntfile.js for your project or sub modules - how this works is very specific to you needs, but there are good examples available on the ` website.
As far as structure and distribution of your plugins, as these probably do not sit on wordpress.org - you need to find a way that works well for you - we use public and private repos on github, which gives us versioning via Git, a good CI pipeline, and also a good way to allow multiple developers to work on the same code base.
We create a new repo for each plugin or theme. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, deployment, production, compression"
} |
URL through custom field returning null
;
aboutus_img = field name aboutus = field group name | Refer ACF link : Link
And use
<?php echo get_field('aboutus_img'); ?>
Choose option image url
 ): ?>
<img src="<?php the_field('image_field_name'); ?>" />
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "images, advanced custom fields"
} |
Do I need to re-register all my images in the media library after a migration?
I'm moving a 6+ years running WordPress site to a new (Azure VM / LEMP) server, taking the time to upgrade Ubuntu, Nginx, etc, and trying to clean up years worth of grunge. ~20 authors, 40k posts, 6+GB of images, etc. I'm moving things over manually, copying the uploads folder over, so the images aren't registered in the Media Library. I'm looking at some plugins to help, but am wondering if it's necessary to re-register all the old images into the Media Library? They're all properly linked in the posts, etc. So, wondering what kind of performance gains, if any, I would get from just not bringing (most of) the images back into the Media Library? Most of these will never be used again (the ones that will I will def get into the ML). Is it worth the bother? | Assuming your old site is still accessible, I would just go Tools -> Export and create an export file containing your media.
In the new WordPress server, import the file and select the option to "Download and import file attachments". (your old site needs to be public for this to work).
This seems to be good guidance: <
If you just copy the uploads folder, WordPress knows nothing about this and all your image references will be 404. Even if you import the media by dragging everything from your uploads folder from old site, they will have different IDs, so I would advice to follow the import method.
Once you have done this, you might want to use a plugin to find stale images and remove them. There probably is a performance gain from getting rid of image references that are somewhere in the database. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, media library, migration"
} |
How to Object.freeze wp_localize_script
I have a localize script that have sensitive information that i dont want other users change it from the console. is it possible to Object freeze my localized script?
wp_localize_script('test-script', 'test_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('test-nonce'),
'action_thanks' => ACTION_THANKS,
'univ_short_name' => UNIV_SHORT_NAME,
'action_general' => ACTION_GENERAL,
'action_catalog' => ACTION_CATALOG,
'action_ebook' => ACTION_EBOOK,
'university_id' => UNIVERSITY_ID,
// in js needs to be converted to bool
'is_sf' => IS_SF
)); | No, it is not possible to do this from `wp_localize_script()`.
You would need to add add `Object.freeze( text_ajax );` to the beginning of your script. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "ajax, javascript, wp localize script"
} |
How to add support for caching plugins for my own plugin?
Is there a generic way to support caching plugins? For example to set a flag after you update an option that caching plugins watch?
For example WP Super Cache has this:
function wp_cache_clear_cache() {
global $cache_path;
prune_super_cache( $cache_path . 'supercache/', true );
prune_super_cache( $cache_path, true );
}
But I will have to add custom code for each caching plugin out there. Is there a better way to do it?
My plugin has some options and prints a shortcode based on those options. Pretty standard stuff. | > Is there a generic way to support caching plugins? For example to set a flag after you update an option that caching plugins watch?
**No, there isn't.** On top of that, caching may not even occur in WordPress itself. E.g. Varnish, Cloudflare, etc
You will need to handle each plugin on a case by case basis.
The closest you might get, is that a caching plugin watches for post saves to update or invalidate cached results. But since you're writing a shortcode, there is no mechanism for flushing the cache in a generic way, or indicating that a page should not be cached in WordPress. This is because WordPress does not perform page caching, so all page caching plugins have bespoke unique implementations. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, cache, plugin w3 total cache, plugin wp supercache"
} |
How to display Common posts from specific Tag & Category with Shortcode
How to display posts that are common in Category A and Tag A, and I want to display posts by shortcode so that the Shortcode can be used on multiple locations with different **category Ids** and **Tags**.
I found the below code by google but don't know how to implement it in **functions.php** and not sure how to use it in the **shortcode**. I want to display Post **Title** , And Some **Custom Field** Value [For Example - Value A, Value B] in a **table** structure.
$args = array(
'category__and' => 'category', //must use category id for this field
'tag__in' => 'post_tag', //must use tag id for this field
'posts_per_page' => -1); //get all posts
$posts = get_posts($args);
foreach ($posts as $post) :
//do stuff
endforeach;``` | function common_cats($att){
$args = array(
'category__and' => $att['category'], //must use category id
'tag__in' => $att['tag'], //must use tag id for this field
'posts_per_page' => $att['posts_per_page']); //get all posts
$posts = get_posts($args);
$output = "<ul>";
foreach ($posts as $post) :
$output .= "<li>".get_the_title(). "</li>";
endforeach;
$output .= "</ul>";
return $output;
}
add_shortcode('commoncats', 'common_cats');
use [commoncats] where you like to show the output of the above code. above code will return a list of titles. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, custom field, shortcode"
} |
How to change "Call To +1800090098" in TopStore pro theme
I'm looking for a way to change the text in the lower menu row (on right side) in a page with TopStore pro (theme).
An example of the theme is at <
where the text is "Call to +99-987654321" | I got it, from the theme-modifier page
Go through menu
Layout > Header > Main Header
Then
Call To Text / Call To Number | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "widgets, frontpage"
} |
Removing the limit on the number of nested comments
Does anyone have a solution for removing the limit on nested comments?
I've found on a site I maintain that there are a few comments where no "Reply" button is visible and since worked out that this is due to the mxa nested comments being reached. It's already set the max setting possible in the WordPress settings (in the discussions settings page) which is 10.
There was a plugin that did this (< but it's not maintained and don't even want to try it. Has anyone found a proper fix to extend / remove this limit? | `thread_comments_depth` is the option you need to change, and while the dropdown gives you several predefined values, the option can store any value.
So if you use the dev tools to adjust the dropdown to add a 9999 option, you can set it to a max of 9999 nested comments, or more even. You can also set the option directly via `update_option`, or with the `options.php` admin page that lists all options. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments"
} |
FireFox Inspector :: find CSS file related to <div>
I'm creating my new website and I would like to change the background colour. Through FireFox Inspector I nailed the CSS line that manages the colour, it's `background-color: #fff;`
 - search the whole page source code for `#masthead` and you will probably find it.
If you want to know how it is being added to the theme HTML, you will need to search the entire project codebase for a unique string - again `#masthead` might bring good results.
**Update:**
Added grab of the source code of your website, showing line 25 where you will find the `#masthead` CSS selector, as described by Inspector - it is much further to the right - but the scroll bar is hidden, as the css is formatted into long lines.
 | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, url rewriting, blog"
} |
Hook to change the site URL
I am working on a WP system that is supposed to be served by multiple domains. For example, `foo.example.com` and `elpmaxe.com` point to the same installation. But depending on the URL, the system will conditionally serve a different landing page.
The question is, how do I make the `site_url()` just return the current URL, NOT the URL value from the database. | You can filter `site_url` using a filter - called `site_url`
The hook has the following signature:
apply_filters( 'site_url', string $url, string $path, string|null $scheme, int|null $blog_id )
You can use it like this:
add_filter( 'site_url', 'wpse_381006_custom_site_url', 10, 1 );
function wpse_381006_custom_site_url( $url ){
if( is_admin() ) // you probably don't want this in admin side
return $url;
// for example, return the request_uri - but this is not a complete solution, you would need to work out what you return and in what conditions..
return $_SERVER['REQUEST_URI'];
}
Reference: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, hooks, actions"
} |
Save order without sending the invoice / order details woocommerce
I need to create manual orders for the customers in the woocommere --> orders section and send them the link for payments.
The issue is that when i create the order, there is no option to save it. The order action requires the email confirmation to be sent to the user for me to save the order.
I have disabled the email notification from Woocommerce --> Settings --> emails --> Processing order but the "Customer invoice/ order details" don't have an option to remove the notification.
I want to find a way where I can save the order but not send the email to the customer (instead i will send them a custom email with the order payment link)
any ideas? | I won't go in code details, but I would consider two different strategies among many others:
* using a custom query using WPDB class, based on WooCommerce queries;
* unhook all undesired filters and actions from WordPress, WooCommerce and other plugins.
I would probably start with the second one. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, woocommerce offtopic"
} |
Start a line with - without converting to list
When editing a text I cannot start the line with "-" because it is converted to list automatically. Sometimes, yes, this is what I need. But, when I want to keep the text as paragraph how can I use the editor to have the line starting with "-"? | Start typing out the way you described and it'll covert to a list. 
* auth_redirect
* update_option
* wp_loaded
* init
* pre_get_posts
* after_setup_theme
* get_template_part
* setup_theme
* plugins_loaded
* muplugins_loaded
What are you trying to do, exactly? the complete answer depends on your use case. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp admin"
} |
External pages redirecting back to wordpress
So I've created a folder under my wordpress root directory containing simple vueJS html files and assets such that anyone can access them from a url like:
**Mywordpress.com/externalfolder**
My external folder however contains its own routes and url params so going to a url like **Mywordpress.com/externalfolder/about** should be handled in the page logic itself, entirely seperate from wordpress, but instead, wordpress redirects to 404.
How do i remove this behaviour and get the server to use whatever my external folder serves up, and remove wordpress from interfering with anything on the original /externalfolder/ path. | You have 2 options:
1 - Move either WP or your vueJS into a separate folder severd from a new or sub domain,
2 - Adjust the default Wp `.htaccess` to ignore your `externalfolder` .
after
RewriteEngine On
RewriteBase /
add
RewriteCond %{REQUEST_URI} !^/externalfolder/ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filesystem"
} |
website is not loading home page (moving from one server to another server)
I have a wordpress site and i want same site with other domain name at same server. I moved all files and folders to new domains directory and also successfully moved database. My admin panel is working fine but when i enter url of homepage , it does not load homepage as you can see in image;
foreach ( $types as $type ) {
if ( isset( $type->labels->name) ) { ?>
<?php echo $type->labels->name ?>
<br>
<?php }
} ?>
In this, I am getting:
Posts
Pages
Media
My Templates
Locations
But I only want Pages, Posts and Locations (Locations is the Custom Post Type).
Any help is much appreciated. | You can make an array of the post types you don't want and then check `in_array()` to see if they match before you output anything with them.
<?php
//You'll want to get at the actual name for My Templates.
//My attempt is just a guess.
$types_array = array( 'attachment' , 'elementor_library' );
$types = get_post_types( ['public' => true ], 'objects' );
foreach ( $types as $type ) {
if( !in_array( $type->name, $types_array )) {
if ( isset( $type->labels->name) ) {
echo $type->labels->name . '<br>';
}
}
}
?> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "custom post types, post type"
} |
How to override url params with rewrite rules vars?
**Setup a rule:**
add_action( 'init', function() {
add_rewrite_rule( '^myparamname/?$', 'index.php?myparamname=hello', 'top' );
} );
**Whitelist the query param:**
add_filter( 'query_vars', function( $query_vars ) {
$query_vars[] = 'myparamname';
return $query_vars;
} );
**Get query vars:**
`localhost/myparamname`
get_query_var('myparamname'); // hello
`localhost/myparamname?myparamname=hi` or `localhost/myparamname/?myparamname=hi`
get_query_var('myparamname'); // hi
As you can see, **" hi"** message is displayed instead of **" hello"** in the second example. Here, the desired situation is generally **" hello"**. | > **" hi"** message is displayed instead of **" hello"** in the second example
Yes, because that's how it works: `query_vars` is a hook for registering custom query vars that are _public_ , so if the URL query string contains the custom query var, then WordPress will set the query var to the value parsed from the query string.
> the desired situation is generally **" hello"**
You can override the query var via the `request` hook. E.g.
add_filter( 'request', function ( $query_vars ) {
if ( isset( $query_vars['myparamname'] ) ) {
$query_vars['myparamname'] = 'hello';
}
return $query_vars;
} );
Just be sure to use a unique query var or be cautious that you don't override query var that shouldn't be overridden. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, wp query, rewrite rules"
} |
How to download my custom theme?
I'm taking over a website that was previously managed by another person, which had installed a **self-made custom theme** (uploaded through .zip file). In other words, the theme is not available online. It was made for the website.
The person does not have the original files and I need to update it. Is it possible to reconstruct/download the theme so I can modify it offline and then re-upload it? I do not find anywhere a download option for the theme.
Alternatively, is it possible to bulk download the website and somehow reconstruct the theme? In principle, all should be there.
I know there are some related posts here but can't find the proper answer to my question. | You can download installed themes and plugins from the WordPress dashboard with a plugin like this: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes"
} |
How can I spin up a new website for a registered user automatically?
We have created a bunch of custom plugins at our agency, and the whole packaged website is like a 'product' at hand.
Is there a way to scale this in a way that we can give out a free trial, where when a user registers a new website gets spinned up as a duplicate of the original "product" under a subdomain?
At present we have a bash script that we run manually for a new user, and the 'product' site gets duplicated on a subdomain (which we create before running the script)
But I'm wondering if there is a way to automate this via API calls or something.
Alternatively, is multisite a better option to implement this? I have refrained from multisite as it doesn't let me copy plugin settings etc into a new child site, so setting up a child site from scratch is another pain to avoid
for me, StackExchange = hope! | The easiest way I have found to do this is to set up a Multisite installation with subdomain installs, and run the plugin "WP Ultimo" to manage signups. It does exactly what you're looking for: duplicates a template site on demand, and activates various plugins depending on which plan the customer has signed up for. You can offer a 30 day trial subscription for free, you can offer coupons, and Arindo has more recently integrated support for OpenSRS if you want to sell domains through your site. I am not affiliated with them, but I use their product and based on my experience I would recommend it to you. Best of luck!
Reference: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, rest api, wp api, deployment"
} |
jQuery Show DIV and Remove Button
Playing with jQuery,
I wanted to remove the button after displaying div (#div-wordpress)
I thought I understood the trick but no ... It didn't work I think I forgot something.
.on('click','#my-button',function() {
jQuery('#div-wordpress').slideToggle('230','swing','hide');
jQuery(this).remove();//supposed to be #my-button ?
}); | /* Show/Hide my div*/
jQuery(document).on('click','.my-button',function() {
//jQuery('.div-wordpress').slideToggle('230','swing','hide');
this.remove();//supposed to be #my-button ?
});
Note that I have swapped ids for classes and just made a small JS update - `this` is the clicked element inside a jQuery event - not `jQuery(this)`
Here is a CodePen: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
} |
how to make wordpress change the title and keep page name?
I want to change the title of my archive page from "category" to "department" to get something like this: Department: Marketing. Where "department" is the archive page title and "Marketing" is the actual name. This is the code that I used:
add_filter( 'get_the_archive_title', function ( $title ) {
if( is_category() ) {
$title = 'department';
}
return $title;
});
But It hides the page name. When I use this code, I get only "Department" as a title and when I delete it, I get "category: department".
How to fix it? | You need to add the actual page title back in. Try this:
add_filter( 'get_the_archive_title', function ( $title ) {
if( is_category() ) {
$title = 'Department: '. single_cat_title( '', false );
}
return $title;
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, archives"
} |
Sidebar endpoint using WordPress API
I cannot find any info on this. Is there a default endpoint for sidebars?
For example pages:
I have looked at the WordPress API documentation but don't see any endpoints for sidebars or widgets.
I also tried something basic like this:
function sidebar_api( $data ) {
$response_body = get_sidebar('one');
return new WP_REST_Response(
array(
'body_response' => $response_body
)
);
}
add_action( 'rest_api_init', function () {
register_rest_route( 'custom/v1', 'sidebar1', array(
'methods' => 'GET',
'callback' => 'sidebar_api',
) );
} );
which gives me the sidebar not in json format and then a json response with an empty body_response. | > Is there a default endpoint for sidebars?
No, I don't think there is. So (for now), using a custom REST API endpoint does sound like a good option to me.
> gives me the sidebar not in json format and then a json response with an empty `body_response`
That's because `get_sidebar()` echo the output, hence the `$response_body` is empty.
So you'd want to use output buffering like so:
ob_start();
get_sidebar( 'one' );
$response_body = ob_get_clean(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rest api, sidebar"
} |
Why can’t I edit HTML in WordPress even with the administrator role?
I am using WordPress. I need to edit the HTML code of the page. Not `page.php`.
When I go to ` I see this:
 and other configuration options which are stored together in the post_content.
Perhaps you can create new pages and not assign them to be edited with Element, this would then allow you access to edit the HTML. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "html"
} |
Translate Post date (month) of china language
How can I translate with the date output format like this: `AUG 2020` with php wp or my wordpress site is currently using the polylang plugin. Please help me, thank you. | You can set translation of date/time format from here while Polylang plugin was actived:
dashboard menu -> Languages -> Strings translations
for example:
* for date_format English translation: **m/d/Y**
* for date_format Chinese translation: **Ynj** | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "date, plugin polylang"
} |
Running script based on Category
I have a child theme with function.php where I am running a script in the header but now I want to tweak it to run only on posts listed under one category and avoid on homepage or other categories. Here is my existing code which I modified but it is firing the script on the entire website.
add_action('wp_head', 'mailchimp_wp_head');
function mailchimp_wp_head() {
?>
<?php if ( is_category( 93 ) ) :?>
<script id="mcjs">!function(c,h,i,m,p){m=c.createElement(h),p=c.getElementsByTagName(h)[0],m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script","
<?php endif; ?>
<?php
}
Thanks! | > run only on **posts** listed under one category
I highlighted that "posts" because if so, then the conditional tag you should use is `in_category()` and not `is_category()` which is for _category archive pages_ (e.g. `example.com/category/foo`) — so for example, `is_category( 93 )` checks if the current archive page is for the category (with the ID of) 93, whereas `in_category( 93 )` checks if the current post is in the category 93.
So try with:
<?php if ( is_single() && in_category( 93 ) ) :?>
<script id="mcjs">!function(c,h,i,m,p){m=c.createElement(h),p=c.getElementsByTagName(h)[0],m.async=1,m.src=i,p.parentNode.insertBefore(m,p)}(document,"script","
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, categories, child theme"
} |
How to create a new section on the wordpress admin dashboard?
I'm trying to create a new "section" to store the names and photos of team members. Is there a default way in WP to add this section or is it through the theme? I also want to add another section to showcase the work that has been completed. Seems like this should be easy, but I'm struggling to find the solution. FYI, I'm using Elemenator with Astra theme.
Thanks. | You should take a look at **Custom Post Type**. CPT are what we use if we want to add more data to our website (events, projects...)
<
If you're not a developer, take a look at this plugins :
Create a post type in admin <
Add fields to your post types (in admin) <
And you can also take a look at some plugin called "Staff" or "Staffer" (based on your needs) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp admin"
} |
Is the .flac audio file format supported by Wordpress?
It works for me but I can't find evidence of it being officially supported so I'm concerned it may not work for everyone. | Yes, the flac audio format is supported. See the doc block for the function `wp_get_mime_types()` (and other mentions).
/**
* Retrieve list of mime types and file extensions.
*
* @since 3.5.0
* @since 4.2.0 Support was added for GIMP (.xcf) files.
* @since 4.9.2 Support was added for Flac (.flac) files.
* @since 4.9.6 Support was added for AAC (.aac) files.
*
* @return string[] Array of mime types keyed by the file extension regex corresponding to those types.
*/
function wp_get_mime_types() {
Whether the visitor's browser supports it is a completely different question and not in WordPress' hands. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 0,
"tags": "audio"
} |
Enable specific CSS Code for Visitors and specific Roles
how i can enable an specific css code for visitors and an specific user role
for example this code:
input[type=radio] {
border: 1px solid !important;
} | You can add custom css on your html header using wp_head hook action & checking your current User Role
add_action('wp_head', 'add_css_of_current_specific_user_role');
function add_css_of_current_specific_user_role()
{
/*Check Current User is Login*/
if ( is_user_logged_in() )
{
$user = wp_get_current_user();
/*Check Current User Role*/
if (in_array('visitor', $user->roles)) { ?>
<style>
// Some CSS
</style>
<?php }
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "css, user roles"
} |
Display all taxonomy terms, add class if term applies to current post
I have a custom taxonomy for a custom post type. I need all available terms (and their descriptions) to display on a single post from this post type, regardless of if each term is applied to it. Basically if a post has the term it will be bold and if it doesn't have the term it will be greyed out but visible. I was able to get it to work with conditional statements for each term, but I want the client to be able to add or remove terms in the future without my having to update the template each time. | I was able to put this together from a similar question I found. If anyone else needs it:
<?php
$terms = get_terms( array(
'taxonomy' => 'features',
'hide_empty' => false
) );
if (!empty($terms) && ! is_wp_error( $terms )) {
echo '<section>';
foreach ($terms as $term) {
$class = has_term( $term->term_id, 'features' ) ? 'active' : 'unassigned';
echo '<div class="term ' . $class . '"><h6>' . $term->name . '</h6>';
echo '<div class="availability"></div>';
echo '<p>'.$term->description.'</p></div>';
}
echo '</section>';
} ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, custom taxonomy, loop"
} |
Is wp_insert_post exactly the same as publishing a post through the core UI?
I'm building a plugin that will call the `wp_insert_post()` function. I need to know if it is functionally identical to posting via the UI. For example, would other plugins (I'm thinking particularly of JetPack) share to social media or are there additional steps to replicate manually publishing (or scheduling) a post? | There's a bit more to the answer than just `wp_insert_post()`. That is the canonical way to insert a post and what the Classic Editor used to submit all of the post information at once.
The REST API (and thus Gutenberg) changes it a tad but running `wp_insert_post` initially just to setup a post in the db, then separately adds all of the meta data and taxonomies, etc (see < ).
In terms of Jetpack's Publicize feature, `wp_insert_post` will work just fine. We look for the `wp_insert_post` hook to sync up the post data used for the social media share ( < ). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp insert post"
} |
Is there a way to set the gutenberg color palette outside the theme?
Is there a away to set the gutenberg block-editor color palette other than in the theme? | Yes, you have to use the `init` hook if you want to use `add_theme_support` from a plugin. I've tested the below code as a plugin and worked for me.
<?php
/* Plugin name: Add Color Palette
*/
function mytheme_setup_theme_supported_features()
{
add_theme_support('editor-color-palette', array(
array(
'name' => esc_attr__('Strong magenta', 'themeLangDomain'),
'slug' => 'strong-magenta',
'color' => '#a156b4',
),
));
}
add_action('init', 'mytheme_setup_theme_supported_features');
Please consider avoiding using `add_theme_support` outside the theme's functions.php file.
The official description for the `add_theme_support` :
> Must be called in the theme’s functions.php file to work. If attached to a hook, it must be ‘after_setup_theme’. The ‘init’ hook may be too late for some features.
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "block editor, color picker"
} |
How to improve my non-unique metadata MySQL entries?
I'm working on a plugin for WooCommerce which uses a cpt called Restock. In a Restock post you can enter products ( id ) plus restock. The user can add as many product restock pairs as they want per post.
 inside add_post_meta is set to false, so I can add as many values as products have been restocked.
foreach ( $new_content as $new_product ) {
$new_product = array ( id => 1313, restock => 55 );
add_post_meta( $post_id, 'rs_products', $new_product, false );
}
I believe this is not the most optimale way how to save the metadata and I would like to improve this before I start connecting the data to WC.
How would you save such a repetitive data pair inside MySQL? | > How would you save such a repetitive data pair inside MySQL?
As separate key/value pairs, which is what you have already done.
The only situation I would reconsider this, is if you need to filter or search for restock posts via these IDs. If that is the case then I would use a private/hidden taxonomy where each term has the post ID as the slug. Post meta is not good for searches/filtering. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, post meta, metabox, mysql, meta query"
} |
How to add PHP code in functions.php wordpress
<?php
//Insert ads after second paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>Ads code goes here</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
Hi, how to repace
<?php
$a1 = get_field('fa1', 'option');
if ($a1) : ?>
<a href="<?php echo $a1['a1-l']; ?>" target="_blank" rel="nofollow"><img src="<?php echo esc_url( $a1['a1-b']['url'] ); ?>"></a>
<?php endif; ?>
instead of `<div>Ads code goes here</div>` in `functions.php` Wordpress? | Perhaps this is what you mean?
<?php
//Insert ads after second paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>'.sewp_381661_get_advert().'</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// function to return ad markup / logic ##
function sewp_381661_get_advert(){
$a1 = get_field('fa1', 'option');
$string = ''; // define return var ##
if ($a1) {
$string = '<a href="'.$a1['a1-l'].'" target="_blank" rel="nofollow"><img src="'.esc_url( $a1['a1-b']['url'] ).'"></a>';
}
// return string for echo ##
return $string;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, functions"
} |
custom functions in function file delete automatically daily
I have added some custom ajax calls and functionality on my WordPress site. I added code in function.php which is placed in wp_includes folder. It was working fine but from the last 2 weeks, my custom functions automatically removed from functions.php file. what is the solution of this? I am new to WordPress. Any help would be highly appreciable. | The simplest advice is that you should never edit what are generally know as `Core` WordPress files, that includes adding new files within the wp-includes and wp-admin directories.
The simple reason why this is not a good idea is that they are replaced when WordPres updates - deleting any changes or additional files - which I presume is the reason your files were also removed recently.
Instead, you should add changes to your own theme or a custom plugin - the theme is the easiest route in most cases, but again you should avoid to edit things you don't control, so don't edit a theme you have bought or downloaded, instead learn how to create a child theme which you can safely edit, knowing that your updates will not get lost.
Once you have your child theme - or custom plugin \- you can add your code there - in a theme the easiest place is inside the functions.php file | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions"
} |
wp_get_environment_type is undefined
I don't understand wordpress, why is this `wp_get_environment_type` function `undefined`?
 {
$environment = wp_get_environment_type();
//... | It is a core WP function, but only after WordPress version 5.5.0.
If you're using an older version of WordPress, it won't exist yet.
Do this:
add_action('admin_init', function() {
if ( ! function_exists( 'wp_get_environment_type' ) ) {
return;
}
$environment = wp_get_environment_type();
//...
Or, better still, make sure your WordPress installation is up to date. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "plugins, mu plugins"
} |
I changed font of wordpress dashboard but it is slow!
my language is Persian and I wanted to change font of wordpress dashboard To be more pleasant. so I created a plugin that works easy. just changes the font of HTML elements of dashboard by CSS (font-family).
But the problem is, while using the plugin, dashboard will be slow and every page takes longer to load. so I need your help to do it Without affecting the speed of the dashboard. How can do that?
you can download my plugin:
[REMOVED]
thanks a lot :) | as @TomJNowell told me in the comment, it was because of heavy font files. so I decided to use just `woff2` format and removed other formats. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, dashboard, fonts"
} |
Is there a hook to update / replace values in the "Enable threaded (nested) comments x levels deep" drop down?
I know how to add a value here that is higher than the max of 10 that is allowed as default (change the value manually in the wp_options table for the value 'thread_comments_depth').
However if I change it in the DB directly the interface will override that value if I go into Settings/Discussions and alter anything else in that page.
I really need the drop down itself to have more numeric values in it and for the correct value to be auto selected when the settings page loads.
 {
return 15;
} ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments"
} |
Why does WordPress create two transients with the same name when I specify timeout value?
Working with transients with a timeout, I seem to be getting two transients created, and I don't quite understand why. Looking at the source code on: < it would appear this only occurs when wp_using_ext_object_cache() returns false.
My calls are:
set_transient( 'mytransientprefix_key', 'value', 3600);
and then I update the same transient with:
set_transient( 'mytransientprefix_key', 'new_value', 3600);
In the wp_options table, I'm then left with:
One **_transient_timeout_mytransientprefix_key** ("value") and **one _transient_mytransientprefix_key** ("new_value").
What? | Why WordPress creates two transients: Because the first transient with `timeout` in the name, is used for storing the expiration you set for your transient (but the stored value is a UNIX timestamp, not simply the value you passed like `3600`) so that WordPress knows when to delete your transient. As for the second one, it stores the actual transient value that you passed to `set_transient()`, i.e. the second parameter.
$key = 'mytransientprefix_key';
set_transient( $key, 'value', 3600 );
// That will create two options:
// _transient_timeout_mytransientprefix_key and
// _transient_mytransientprefix_key
var_dump(
get_option( '_transient_timeout_' . $key ),
get_option( '_transient_' . $key )
);
// Sample output: int(1611143902) string(5) "value"
So the value of the "timeout" transient shouldn't be `value` — try the above code and see how it goes? | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "plugin development, transient"
} |
Hide category name but show posts
I’m looking for a way to hide a specific category title ( **not all but just one specific category title** ) from being displayed on the **home page, archives, and search results** but still show the posts tagged under the category.
Is it possible to do it via CSS or functions hook?
Keep in mind that I want to hide the category title (not the posts under the category. Just the title) from being displayed on home page, archives, and search results.
However, the category name should be displayed on posts. | This code works perfect. Note that `137` is the `category ID` that I wish to hide and `.home` is the page where I don't want it to be displayed
.home .entry-category-item-137 {
display: none;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
How to disable the topbar in mobile?
Hello I wonder how can I hide/disable the topbar in mobile (the black one)? Here is a link to my site: < I'm using wpbakery with Kudos theme. | You can do it with CSS.
@media screen and (max-width: 600px) {
.qodef-top-bar {
display: none;
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "mobile"
} |
How to add .ini file type to the plugin editor to read and edit?
Referring to `/wp-admin/plugin-editor.php`
The plugin editor does not include `.ini` files and I use that file type in a plugin to create dynamic message constants. I want to be able to edit that file via the editor.
I explored `wp_doc_link_parse()` but to no avail.
### How can I add file types to the allowed list? | This code below should work if you add it to your `functions.php` in your theme:
add_filter( 'editable_extensions', function ( $default_types ) {
$default_types[] = 'ini';
return $default_types;
} );
Assumptions:
* You're using at least PHP 5.3
* You're using at least WordPress 4.9 | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
Wordpress 404 in development area
I have a live WP site, which I have taken a copy of and put onto a new server for testing / development.
Once I put the website on the new area I updated the site url and home url in the database, ensured the .htaccess file was showing correctly and everything in the wp-config was correct.
When I try and access a page which is not the **Home Page** or **wp-admin area** I get a 404 error.
I have tried resaving the permalinks, ensuring all urls in the database are the new servers ip's , and disabling each plugin one by one to see if there was any conflicts but nothing seems to work.
Is there something I am missing / any advice.
Thank you | As MrWhite mentioned above, mod_rewrite was not enabled on the new server. Enabled that and all is working fine now.
Thanks for your help | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks, htaccess, 404 error"
} |
Disable wordpress reordering functions in backend screen element
Does anyone know how to disable WordPress reorder button? I mean the **up and down arrow** (located in the upper right corner of the image attached below), and not the collapse button. So the box will stay at the default original position. Fyi, I'm using the classic editor plugin.
 | You have to add the following CSS to an admin.css file (name it whatever you like but it has to be a css file that applies to the admin.
You need the following in that file:
.order-lower-indicator,
.order-higher-indicator{
display:none;
}
To enqueue a stylesheet properly in the admin:
<
It's the same basic process as enqueuing for the front end but you're just applying a different action: `do_action( 'admin_enqueue_scripts', string $hook_suffix );` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp admin"
} |
Cant get blog name with get_option
I am using WordPress functions to get the blog name and the current user username, I need this info to embed them on my contact form which is custom code too, but for some reason they are not working even though the WordPress codex says they are correct
<html>
<?php
$username= get_current_user();
$url = get_option( 'blogname');
?>
<body> | You need access to the property of $username to get the name
$user = wp_get_current_user();
$username= $user->display_name;
Get option method will return the name of the site you have set in setting -> general options
$url = get_option( 'blogname');
If you need home URL then
$url = get_option( 'home' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions"
} |
Get Custom taxonomy parent with wordpress REST API
I have a custom taxonomy `product_category` , and it accepts parent / child relationship.
The url: `/wp-json/wp/v2/product_category` shows me everything, Parent and Child.
is it possible to add parameters to show only parents? | Found solution :
/wp-json/wp/v2/product_category/?parent=0 | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, rest api"
} |
Two prefixes in database? Which one is valid?
I am trying to manually migrate an install and have come across this. My DB has some qfo_ prefixed rows and some wpaq_ prefixed rows. The qfo_ are all duplicates of the others (in other words, there is a qfo_commentmeta and a wpax_commentmeta, etc.).
To get the db hooked up, I have to change the options row, but which one? or both? And is having these two prefixes in one DB a problem? | Check the `wp_config.php` file... look for a line that reads:
`$table_prefix = 'qfo_';`
Or...
`$table_prefix = 'wpax_';`
Which ever one is set in `wp_config.php` is the one that your WordPress site is using. If the tables aren't being used then they're not really doing any harm other than taking up space, but once you're sure you've got everything you need from them then you can probably just drop them from the database. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "database"
} |
Checking for a new version from WP Repos
I would like to know if there is a new version from the official WP Repos for a specific plugin.
How can I check for this in json/xml format? Or other format maybe?
Something like this: <
But for each single plugin in the WP repo | As expected, there is a JSON API.
Just had to dig a lot in the codex!
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "version control"
} |
Syntax for $wpdb->prepare when searching in two columns
I have this working statement for searching a single column in my database:
$foods = $wpdb->get_results( $wpdb->prepare( "SELECT id, foodname, namevariations, calories, carbs, fat, protein, sodium FROM foodsTable WHERE namevariations like %s", "%$search_text%"), ARRAY_A );
I would like to include another column in the search called "foodname" but I can't seem to figure out the correct syntax.
How should I formulate my prepare statement so that I'm searching "namevariations" OR "foodname" and a match in either column will select that row? | The part after `WHERE` decides which columns are searched.
So you need to change it this way:
$foods = $wpdb->get_results(
$wpdb->prepare(
"SELECT id, foodname, namevariations, calories, carbs, fat, protein, sodium FROM foodsTable WHERE namevariations like %1$s OR foodname like %1$s",
'%' . $wpdb->esc_like( $search_text ) . '%'
),
ARRAY_A
);
Also you were using LIKE queries incorrectly. If the `$search_text` contained `%` character, it would be interpreted as wildcard and not as simple character. That's why I've added some escaping in your code. More on this topic here: How do you properly prepare a %LIKE% SQL statement? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wpdb, sql"
} |
Can't extend some core classes
I am relatively new to wordpress development, I am trying to extend 'Walker_Category_Checklist' class found in `/wp-admin/includes/class-walker-category-checklist.php` to customize it for `wp_terms_checklist()` or `wp_category_checklist()` but when I try to `require_once` a link to my extended class in the child-theme `function.php` I get this error and site not loading!
> x" Fatal error: Class 'Walker_Category_Checklist' not found in ..... "
Is it because of this class file in 'wp-admin/includes/' dir? if so then how to extend it ?
wordpress ver: 5.6 - php ver: 7.2
Thanks in advance Cheers Mo. | I could not extend directly Walker_Category_Checklist I think because it's in wp-admin dir. even it's for "output an unordered list of category checkbox"!! similar classes to it etc. "Walker_Nav_Menu" existing in wp-include witch is should be the right place for the "Walker_Category_Checklist" I guess.. The answer that I found is going around by extending the parent class "Walker" to "my_Walker_Category_Checklist" then copy the code from "Walker_Category_Checklist" then do my customization on it, like that everything if working. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, menus, wp admin, child theme, walker"
} |
Display page and custom post title inside shortcode
I am trying to write a shortcode to display the page title. I only got the archive title to work, but not custom post type category and single post. Can anyone shed light how to do this?
The reason for going this path is Elemenentor theme builder generating too much code for simple page title and subheading inside secondary header that is masked wrap around an image. I use the shortcode widget to insert the code and style it.
So far this is what I have written:
// Page Title inside shortcode
function page_title_sc( ) {
$title = ('Page Title');
if ( is_post_type_archive() ) {
$title = post_type_archive_title( '', false );
}
elseif ( is_page() ) {
$title = single_post_title();
}
return apply_filters( 'page_title_sc', $title );
}
add_shortcode( 'page_title', 'page_title_sc' ); | Add Below Code For post title, page title, category title , tag title , taxonmy title , Author title .
According to your Needed.
function page_title_sc( ) {
$title = ('Page Title');
if ( is_page() || is_singular() ) {
$title = single_post_title();
} else if ( is_category() ) {
$title = single_cat_title( '', false );
} else if ( is_tag() ) {
$title = single_tag_title( '', false );
} else if ( is_author() ) {
$title = '<span class="vcard">' . get_the_author() . '</span>';
} else if ( is_post_type_archive() ) {
$title = post_type_archive_title( '', false );
} else if ( is_tax() ) {
$title = single_term_title( '', false );
}
return apply_filters( 'page_title_sc', $title );
}
add_shortcode( 'page_title', 'page_title_sc' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, shortcode"
} |
How to use own css of functionality plugin?
I had built a functionality plugin and hooked with actions to another plugin. I had also made a style.css in myplugin/stylesheets/ directory. I placed the code there. I would like to make the styling dependent on my plugin and not my theme.
So far I have been trying this:
function epf_override_style() {
wp_register_style( 'epf-style', '/stylesheets/style.css' ); //Subdir in plugin directory.
wp_enqueue_style( 'epf-style' );
}
add_action( 'es_extra_bottom_info','epf_override_style' );
How can I use the stlye.css of my plugin instead of the theme's (child theme's) style.css? | What I find working is this:
function epf_override_style() {
wp_register_style( 'epf-style', '/wp-content/plugins/extended-plugin-functionality/stylesheets/style.css');
wp_enqueue_style( 'epf-style' );
}
add_action( 'wp_print_styles','epf_override_style' );
I have found the solution here: <
All the comments helped to find the solution. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
Subsets and Splits