INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to allow   with wp_kses()?
I have an html containing   but I am unable to pass it through wp_kses(). I have tried adding allowed html `array(' ' => array(),)` but does not seems to work. I there a way or I should not do that?
< | > not sure the difference but I used ` ` for adding a white space ..then passed it through `wp_kses()`
The correct HTML entity for a non-breaking space is ` ` -- note the `;` which is required and _without it_ (i.e. ` `), the entity is not valid and when used with `wp_kses()`, you'd get `&nbsp` instead of a non-breaking space.
> strangely it was working fine before I used `wp_kses()`
I'm pretty sure it's because the browser is smart enough and auto-corrected it to ` `. :-)
So, **_always_** use valid HTML entities and also tags (e.g. close a `<div>` with a `</div>`), regardless you use `wp_kses()` or not. Don't rely on "intelligent guess" or auto correction by the browser. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "escaping, wp kses"
} |
Gravity Forms and regex - Doesn't seem to validate
I'm attempting to validate a field to ensure it is 9 numerical digits (Canadian SIN number format). I've got the below filter set up:
add_filter( 'gform_field_validation_1_1', 'validate_SIN', 10, 4 );
function validate_SIN( $result, $value, $form, $field ) {
$pattern = "^\d{3}-?\d{3}-?\d{3}$";
if ( !preg_match( $pattern, $value ) ) {
$result['is_valid'] = false;
$result['message'] = 'value:'.$value.' pattern:'.$pattern.' No Pattern Match';
}
return $result;
}
Invalid entries fail validation, but valid entries ALSO fail validation. I know the Regex is fine because I've used it before, so I'm at a loss as to why it's not working.
Does anyone have any guidance? | Probably you just forgot the delimiters for your pattern.
Try declaring your `$pattern` like:
$pattern = "/^\d{3}-?\d{3}-?\d{3}$/"; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin gravity forms"
} |
Sanitize $_GET variable when comparing
I know when I want to save data in database, I must sanitize data but what about following case which is a simple comparison. Should I sanitize?
if ( ! isset( $_GET['page'] ) ) {
return;
}
if ( 'google' === $_GET['page'] ) {
wp_redirect( ' );
exit;
}
if ( 'facebook' === $_GET['page'] ) {
wp_redirect( ' );
exit;
} | No, it's not necessary to sanitise in this case.
If you were redirecting to the value directly, or outputting it in some way, you would definitely need to, but since you're just comparing its value against a white list (essentially) no sanitising or escaping is necessary. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, sanitization"
} |
how to show all categories by get_terms
I am using the below code but just display parent categories while i have many child categories. I want to display all categories including parents and childs
<label for="<?php echo $this->get_field_id( 'link' ); ?>"><?php _e( 'دسته بندی' ); ?></label>
<select id="<?php echo $this->get_field_id('link'); ?>" name="<?php echo $this->get_field_name('link'); ?>" class="widefat" style="width:100%;">
<?php foreach(get_terms('category','parent=0&hide_empty=false') as $term) { ?>
<option <?php selected( $instance['link'], $term->term_id ); ?> value="<?php echo $term->term_id; ?>"><?php echo $term->name; ?></option>
<?php } ?>
</select> | The reason it's only getting parents is this part:
parent=0
This queries categories that don't have a parent, so you only get the top level. Remove it and you'll get all categories:
get_terms('category','hide_empty=false')
That being said, you'd be better off using `wp_dropdown_categories()`. That way you will get the proper ordering and indentation of child categories:
<label for="<?php echo $this->get_field_id( 'link' ); ?>">
<?php _e( 'دسته بندی' ); ?>
</label>
<?php
wp_dropdown_categories(
[
'id' => $this->get_field_id( 'link' ),
'name' => $this->get_field_name( 'link' ),
'class' => 'widefat',
'selected' => $instance['link'],
]
);
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "terms, categories"
} |
How I can add placeholder in shortcode
add_shortcode( 'show-the-views', function( ) {
);
$count = get_post_meta( get_the_ID(), 'views', true );
return $count . ' views';
});
This code is working but I have to add a placeholder in the shortcode for example [doc_wp_live_search placeholder="Have a question?"]. Currently, it is showing views. But I want to give an option for the user. | function show_the_views_func( $atts ){
$atts = shortcode_atts(
array(
'placeholder' => '',
), $atts
);
$count = get_post_meta( get_the_ID(), 'views', true );
return $count . $atts['placeholder'] . ' views';
}
add_shortcode( 'show-the-views', 'show_the_views_func' );
echo do_shortcode( '[show-the-views placeholder="test"]' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
Make dynamic string translatable
I have a plugin where people can add their own (title) somewhere, but this title is not picked up by multilingual plugins.
Reason for that is that I'm not using the `__()` function of course, I'm just echoing the option value that the user has input.
For example `echo esc_html( $my_title );`
How can I make it translatable? Would `echo esc_html__( $my_title, 'text-domain' )` work? I don't think so, I mean what would people see as the original string?
How WP would handle this? | No, you wouldn't use the translation functions (`__()`, `_e()` etc.). Those are for creating language files and must only be used on static strings. They need to be static because the tools for generating the language files don't execute PHP, so they can't process variables. They just parse the text of the code, essentially.
If you want to support multilingual plugins then you need to build that support in manually with whatever methods those plugins require. WordPress won't help you here. So you'll need to check the developer documentation of the multilingual plugins that you want to support. Here's some documentation for adding multilingual support for custom content for WPML, for example. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, translation, plugin wpml"
} |
WP Query with meta queries
I have the following WP_Query:
$query = new WP_Query(array(
'post_type' => 'some_cpt',
'posts_per_page' => -1,
'meta_key' => 'active',
'meta_value' => 1,
'orderby' => 'ranking',
'order' => 'ASC'
));
Both `active` and `raking` are ACF fields, `True/False` and `Numeric` respectively. I am trying to get all `some_cpt` posts that have `active` set to true and at the same time order them by `ranking`. However, the code above totally ignores `orderby`. | You have to use `"orderby" => "meta_value_num"` and set a `"meta_query"` at the same time. Then choose the `"meta_key"` you want to order by.
Try:
$query = new WP_Query(
array(
'post_type' => 'some_cpt',
'posts_per_page' => - 1,
'meta_query' => array(
array(
'key' => 'active',
'value' => '1',
'compare' => '=',
)
),
'meta_key' => 'ranking',
'orderby' => 'meta_value_num',
'order' => 'ASC',
)
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, advanced custom fields, order, sort"
} |
Advice on how to structure a custom plugin
I am attempting to create a custom plugin and would like some advice/ideas on how best to store the data.
Expected Posts ~ 1,000 Expected Users ~ 10,000
Each user will need to have at least one value stored PER post.
Is the best way to do this by adding new columns to the user_meta table?
Just looking for some guidance on the most efficient method so I don't bloat my db unneccesarily.
Thanks. | The number in the above example are not indicative of a need for a custom database table solution, the database will be fine with just using the `users` table for the users, `posts` table for the posts and `usermeta` table for the link between users and posts.
Its hard to offer a more definitive answer without knowing a little more about what the needs of the business / plugin are to be. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, database"
} |
wp_enqueue_script add integrity parameter
I'm **adding fontawesome** script to my site, and I didn't found a proper way to add the fontawesome's integrity parameter (`integrity="sha384-DJ25uNYET2XCl5ZF++U8eNxPWqcKohUUBUpKGlNLMchM7q4Wjg2CUpjHLaL8yYPH"`).
There's a way to do this? Or wordpress doesn't have a current support | You will have to generate your own tag after the script is enqueued. Below, it's looking for the `fontawesome` handle (the one you're using to enqueue the script) before returning the custom tag.
add_filter( 'script_loader_tag', 'my_scripts_modifier', 10, 3 );
function my_scripts_modifier( $tag, $handle, $src ) {
if ( 'fontawesome' === $handle ) {
return '<script src="' . $src . '" type="text/javascript" integrity="sha384-DJ25uNYET2XCl5ZF++U8eNxPWqcKohUUBUpKGlNLMchM7q4Wjg2CUpjHLaL8yYPH"></script>' . "\n";
}
return $tag;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "functions, wp enqueue script"
} |
Changing root password in PHPMyAdmin for Wordpress Database when going live
Is it a good idea to create a password and make your password secure for your Wordpress database when uploading the database to a third-party web host (going live instead of hosting on localhost) instead of root and no password? :
Change
u. root p. 'no password'
to
u. username p. password
Does it make your database more secure and still accessible to your new third-party host? | The short answer is yes. Having a secure username and password is paramount to keeping your site secure. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "database, mysql, phpmyadmin"
} |
Woocommerce rounding cart totals with tax up
I have a fairly common issue with Woocommerce when using product value includes tax.
When products are set to say 9.99 when added to the cart the total will display 10.00. Now I know why this happens. It's because Woo uses four decimal places for the tax calculation. So when you use 9.99 as a product price woo calculates the tax as 1.665 and if you add that to the calculated discounted price of 8.33 is 9.9950 put up to 2 decimal points its forced into 10.00.
So basically I was wondering if there is a way to always force the rounding of the totals to go down so it takes a lower value as opposed to a higher one. so that 9.9950 instead of being 10 would display as 9.99. | This was down to a Woocommerce setting.
Woocommerce -> Settings -> Tax -> Rounding
untick "Round tax at subtotal level, instead of rounding per line".
This will stop the bad rounding. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Absolute search against wordpress api
I am using the below to search to check if a product category is already created
$params = [
'search' => "category1"
];
$searchedparaCat = $woocommerce->get('products/categories', $params);
using <
This works however it seems to do searches as 'like' instead of absolute. For example the above could return
"category11", "category14", "category14552"....
What I need really is an absolute search so that it will ONLY return a category with the give search term as its slug. Is this possible? I know I can iterate over the returned results and filter them but before I go down that route can this be done via the api? | Searches are always fuzzy, not exact. You might be looking for the `slug` parameter here. From the documentation, it reads **Limit result set to resources with a specific slug.**
I assume it should fit your case and it would only return the categories that match the slug provided. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic, search, api"
} |
Access Wordpress query by index number outside the loop
In wordpress query, Can I single out the specific post by index number of the query result?
for example
<?php
$args = array(
'post_type' => 'headimages',
'orderby' => 'menu_order',
'order' => 'ASC'
);
$package_query = new WP_Query( $args );
$num = $package_query->post_count; ?>
so how do i display the second result or third result from this query? Can I do something like this?
<php $thirdresult = $package_query[2];>
please help. | The results of a query are stored as an array in the `$posts` property of the query object, so you can access the third result like so:
$package_query = new WP_Query( $args )
$third_result = $package_query->posts[2]; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp query"
} |
Upload restrictions - upload_mimes - filter: Adding multiple MIMEs for a single extension and adding multiple extensions for a single MIME type?
Trying to add certain allowed MIME types to the upload filter - currently my custom function looks like this:
// allow SVG and video mime types for upload
function cc_mime_types( $mimes ){
$mimes['svg'] = 'image/svg+xml';
$mimes['webm'] = 'video/webm';
$mimes['mp4'] = ['video/mp4','video/mpeg'];
$mimes['ogg'] = 'video/ogg';
$mimes['ogv'] = 'video/ogg';
return $mimes;
}
add_filter( 'upload_mimes', 'cc_mime_types' );
Uploading videos with ogg/ogv format seems to work well, but MP4 is failing. It seems like an array of different MIME types is not the solution. How should I add this? | @MikeNGarret's answer pointed me to the interesting function `wp_get_mime_types()`. Within this function you can look up how to correctly add MIME types to the `upload_mimes` filter (<
The correct answer therefore is:
// allow SVG and video mime types for upload
function cc_mime_types( $mimes ){
$mimes['svg'] = 'image/svg+xml';
$mimes['webm'] = 'video/webm';
$mimes['mp4|m4v'] = 'video/mp4';
$mimes['mpeg|mpg|mpe'] = 'video/mpeg';
$mimes['ogv'] = 'video/ogg';
return $mimes;
}
add_filter( 'upload_mimes', 'cc_mime_types' );
For registering an unknown MIME type you should therefore use the `mime_types` filter, for the upload (independently) you have to add it to the list of allowed upload mimes. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, uploads, media library, videos"
} |
REST API retrieving posts from www.sitename.com/category/news/ instead of just just from www.sitename.com
I look a bit thorough some of the previously asked questions and stumbled upon `/wp-json/wp/v2/pages/?slug=news` (and other permutations) but it doesn't turn anything up. I'm kind of stuck on how to get posts for each category. I looked at `/wp-json/wp/v2/` for trying to get a grasp on how routes work and looked at categories, but couldn't figure it out. I also checked out `/wp/v2/posts?filter[category_name]=news` but it just ends up being the same post no matter what I change the category name to. | If you want to retrieve posts, you need to use the posts endpoint for starters, not pages. So that's `wp-json/wp/v2/posts`. The documentation for that endpoint is here.
As you can see in the documentation, under _List Posts_ , you can retrieve posts for a specific category using the `categories` argument. However, you need to use the category _ID_ , not the slug.
If you absolutely must use the slug, then you need to retrieve that first, from the categories endpoint:
That will retrieve any categories with `news` as the slug. This response will include the category ID which you can store and use to query posts with that category. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "rest api"
} |
syntax error for changing user role from database
I want to change user role from the database,
UPDATE wp_usermeta
SET meta_value = 'a:1:{s:10:"subscriber";b:1;}'
WHERE meta_key = 'wp_capabilities'
AND meta_value = 'a:1:{s:9:"wpas_user";b:1;}';
but I get an error.
> #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''a:1:{s:10:"subscriber")' at line 1 | Found it.
It was a field in phpMyAdmin which is set to a semicolon(;) by default.
I have changed it to an unused char and the query ran normally.
.
Thanks for your time and help! | This plugin provides filter to manage the menu item by meta value:
function custom_menu_item_visibility( $visible, $item ){
if( isset( $item->roles ) ){
$user_id = get_current_user_id();
$user_meta = get_user_meta( $user_id, 'your-meta-key', true );
if ( /* your condition */ ){
$visible = true;
} else {
$visible = false;
}
}
return $visible;
}
add_filter( 'nav_menu_roles_item_visibility', 'custom_menu_item_visibility', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus, user meta, capabilities"
} |
How can I register multiple custom post fields to json?
sorry if this question has been asked before.
I have a few custom fields created with ACF and I am trying to push these fields to json, to use them in a js file.
My code looks like this:
function receiver_custom_fields() {
foreach ( array('brand', 'name', 'cinema_dsp') as $field ) {
register_rest_field( 'receiver', $field , array(
'get_callback' => function() {
return get_field($field);
}
));
}
}
But I get this error:
> **Notice** : Undefined variable: field in **E:\xampp\htdocs\test-comparator\wp-content\themes\hifi-compare\functions.php** on line **8**
>
The fields: brand, name, and cinema_dsp are created.
I already created a function for each field and it works, but I want to add many more fields and I don't want to create a `register_rest_field()` function for each one.
What can I do? | The `$field` variable isn't available inside your `get_callback()` function. PHP isn't like JavaScript in that way, and that function can't access variables from outside its scope (unless it's `global`, but that's a poor solution).
To pass the `$field` variable through to the callback function, you need to write it like this:
'get_callback' => function() use ( $field ) {
return get_field( $field );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom field"
} |
Hide Featured Image Meta Box on Editor Screen
I've tried to use
function my_remove_meta_boxes() {
remove_meta_box( 'postimagediv', 'post', 'side' );
}
add_action( 'add_meta_boxes', 'my_remove_meta_boxes' );
and
function hide_featured_image( $hidden, $screen) {
$hidden[] = 'postimagediv';
return $hidden;
}
add_filter('hidden_meta_boxes', 'hide_featured_image', 10, 2);
I've also tried it with `default_hidden_meta_boxes` filter.
**None of these work.**
I don't even know if I'm using the correct name for the box because I can't get it to print out the names of the default boxes.
I'm using WordPress 5.2.1 with Gutenberg and Nelio Content plugin which has its own featured image sidebar box. I want to hide the default Featured Image so the admins don't use it by mistake. | I tested it myself with the code you use and it only works with Gutenburg disabled. It seems to be related to the new editor.
Assuming you want to use the new editor, and depending on your theme and plugins this code may work for you (it worked from my tests):
add_action( 'after_setup_theme', function(){
// this removes the feature image panel from all your post types
// including 'post'
remove_theme_support( 'post-thumbnails' );
// include all post-types that use the featured image panel here
add_theme_support( 'post-thumbnails', array( 'example-post-type' ) );
}, 11 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php, filters"
} |
making users.php search include a specific user meta data field without messing with the SQL query itself
I'm tyrying to let the admin search through the users by a single meta value called 'indice de busqueda' insithe the wordpress /wp-admin/users.php page
How can I hook into the search box in such a way so that I can change the query to look something like this?
$query = get_users([
'meta_key' => 'indice de busqueda',
'meta_value' => $search_value,
'meta_compare'=>'REGEX'
])
I tried many possible aproaches but I cant seem to find one where I can avoid messing with SQL. | Take a look at the pre_get_users hook. It is very similar to pre_get_posts if you are familiar with that, except it is for wp_user_query instead of wp_query.
You will need to ensure that you only check the users screen in the dashboard, because that hook would affect any user listing otherwise.
Here is an example of what the code might look like. **Not fully tested** but based on some working code from my own plugin.
function so339209_filter_users_indice_de_busqueda( $query ) {
if ( !function_exists('get_current_screen') ) return;
// Only apply on the Users screen in the dashboard
$screen = get_current_screen();
if ( !screen || screen->in !== 'users' ) return;
$query->set('meta_key', 'indice de busqueda');
$query->set('meta_value', $search_value);
$query->set('meta_compare', 'REGEX');
}
add_action( 'pre_get_users', 'so339209_filter_users_indice_de_busqueda', 20 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp admin, search"
} |
How to redirect from various ?page_id= to home page?
I have a website where I need to 301 redirect all old pages that are incoming from old URLs like `/?page_id=261`, `/?page_id=204`, `/?page_id=2677` and so on to the main home page.
What would be a proper way of doing it? Will something like this in `.htaccess` work? I do not want to redirect all 404's - just these type of old links.
RedirectMatch 301 ^/?page_id=4&n=$1 | You can't match the query string using a mod_alias `RedirectMatch` directive. This directive matches against the URL-path only. You need to use mod_rewrite instead, with a condition that checks the `QUERY_STRING` server variable.
For example, at the top of your `.htaccess` file, try the following:
RewriteCond %{QUERY_STRING} ^page_id=\d+$
RewriteRule ^$ / [QSD,R=302,L]
The `QSD` flag (Apache 2.4) is required to remove the query string from the target URL.
However, from an SEO perspective, mass redirections like this will likely be seen as soft-404s by the search engines. You should try to redirect on a per page basis to the new URL. If the content no longer exists then return a 404. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "redirect, htaccess"
} |
Show post count in custom taxonomy page
How can I show the post count in a taxonomy page. I tried some codes but I could not get success. I will locate this information on the top of taxonomy page.
foreach ( get_the_terms( get_the_ID(), 'taxonomy' ) as $term )
{
echo $term->count ;
} | İ found a solution:
$posts = get_queried_object();
echo $posts->count; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, customization, pages, taxonomy, count"
} |
Set different css stylesheet for specific pages
Is it possible to assign a css stylesheet to specific pages only?
If so how?
Can I use something like this? Not sure how to specify the pages though?
add_action( 'wp_enqueue_scripts', 'enqueue_theme_css' );
function enqueue_theme_css()
{
wp_enqueue_style(
'default',
get_template_directory_uri() . '/css/default.css'
);
} | Yes, it is possible. All you need to do is to check whether you are on a specific page or not. For example, this will enqueue your scripts only for the page that has the `contact-us` slug:
add_action( 'wp_enqueue_scripts', 'enqueue_theme_css' );
function enqueue_theme_css()
{
if( is_page( 'contact-us' ) ){
wp_enqueue_style(
'default',
get_template_directory_uri() . '/css/default.css'
);
}
}
You can take a look into the `is_page()` function for more informations. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, wp enqueue style"
} |
How to make a search form?
I'm taking my first steps in wordpress, pretty newbie. and I find that I want to make a search form with its own styles and a little javascript to redimension. So I do not know how I should proceed in several ways.
* Is it better to use the get_search_form () method, inspect and change their styles? like for example the search-field class or for html5 searchform?
OR
Is it better to make my own form from scratch if it is going to have (many) changes?
* In the case that it is better to use get_search_form (), I inspect and change the styles directly? or do I support html5 and change the styles of these? Or is there a way to embed additional classes to the said form?
* in the case that it is better to make my own form as I do so that wordpress detects it as a search form? or that failing to do the search? | When you code `get_search_form()` WP search searchform.php in your theme root and print all inside that file. And you can create searchform.php inside your theme root and insert this:
<form role="search" method="get" action="<?php echo home_url('/'); ?>">
<fieldset>
<input type="text" name="s" value="<?php the_search_query(); ?>">
<button></button>
</fieldset>
</form>
That basic search form. Then code `<?php get_search_form() ?>` where you want this form in your theme. You can add your own class or ID inside that form and change what you want. Also I put link for couple notes about search_form | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "search, forms"
} |
How to link all featured images to custom url in single.php for only non-logged-in users?
I want to link featured images of every WordPress posts to specific page/url for only visitors (non-logged in members). And this function should be disabled for logged in users. It should only link featured images of single.php. Not for index.php, archive.php or others. How to do? | In `single.php` you can wrap your featured image in a link tag with a conditional to check if the user is logged in.
if ( is_user_logged_in() ) {
echo '<a href="
}
the_post_thumbnail();
if ( is_user_logged_in() ) {
echo '</a>';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, post thumbnails"
} |
Can I upload my self hosted WordPress website on GitHub as a project?
I have searched this question a lot
Can we call our WordPress Website a project?
and
Can we somehow upload our Wordpress Website as a Project on Github?
I have an e-Commerce based website, which is created on WordPress. And I am new here so if the question is irrelevant, please guide me. | You cannot host wordpress websites on Github. But you can host static websites on Github Pages, if that's any help. Try making a site with Jekyll, and hosting it on Github. Its easy, fun and free.
My wordpress repos are all either themes or plugins. I never add the wordpress core to a repo. The project is always the theme or plugin folder. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, github"
} |
Show FormCraft form on page open
I am using WordPress FormCraft plugin on my site. I created a form and got the form short embedded code
[fc id='4'][/fc]
I want to show this form when the user opens the page.
Can anyone tell how can approach this?
I also try in Page Editor I got an option to add form it generated below code for me.
[fc id='4' type='popup' button_color='#4488ee' font_color='white'][/fc] | From the documentation, you have to use the shortcode:
[fc id='12' type='popup'][/fc]
Next, something has to trigger the form, you can create a button for that and then click it from jQury, edit the link which would trigger this form, and put the href or hyperlink to:
<a class="triggerForm" href=" Trigger</a>
jQuery trigger.
$(document).ready(function () {
$('a.triggerForm').click();
}); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages"
} |
Weird strange letters appeared in all website links
I have an issue with my new wordpress website running WooCommerce plugin.
There is a random letters added in all website links “?v=d3d4c5deb455”
I tried deactivating the addon’s and it didn't work - only the letters disappeared when I deactivate “WooCommerce” plugin ... which i cant really deactivated cause it an online store
I tried changing the theam and went back the default template also it didn't work
Screenshot < Website : knzshop.com | This has to do with geolocation, and is functionality built into Woocommerce.
<
See under the title on that page `Geolocation, with a hint of Ajax`
This seems to be a pretty good write-up of the functionality and how to disable it:
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic, links"
} |
How to show loading spinner after click on add to cart button
WooCommerce has a known delay to add a product to cart.
Based on that, the official **StoreFront** Theme for WooCommerce has a “ **spinner** ” after clicking on the purchase button.
 to use and add some css like below (Not tested, modify to suit)
Let me know if that helps.
button.add_to_cart_button.loading:after{
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
font-family:"Glyphicons Halflings";
content: "\e031";
background: rgba( 255, 255, 255, 0.7 );
text-align:center;
line-height:34px;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "woocommerce offtopic, themes"
} |
issue in wp_localize_script
I am initializing wp_localize_script after enqueueing scripts like that
wp_enqueue_script('main',get_template_directory_uri().'/js/mains.js','','1.1',true);
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
but i am unable to get it in jquery file/code jquery code is
(function($) {
$(document).on( 'click', '.page-numbers', function( event ) {
event.preventDefault();
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination'
},
success: function( result ) {
alert( result );
}
})
})
})(jQuery);
on clicking i am seeing the error ajaxpagination is not defined , what can be the possible solutions for this ? | Change the first param of `wp_localize_script` to same as the handle of your main script file.
`main` in this case. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, themes, wp localize script"
} |
How to center all text body in single.php at once?
I'd like to center all of the text bodies (or content body before "read more") of all posts (in single.php) at once with simple (or advanced) code. How can i do that? | There is probably some CSS you can add via Additional CSS (in Theme CUstomization) that you could use. Use the Inspector tool of your browser (F12) to see the CSS 'class' element used in the content. If the class is called 'the_content', then add this to your Additional CSS:
.the_content{text-align:center !important;}
You might need this, if the content is inside 'p' tags:
.the_content p {text-align:center !important;}
Adjust it for what you like (you may not need the `!important`). In the Inspector, you can add CSS stuff to that element to try things out. There are googles/bings/ducks on how to use the Inspector. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, posts, functions, html, single"
} |
What is the action hook for an order that fails on frontend checkout in WooCommerce?
I am working on a plugin that handles logic for when a user tries to checkout on the frontend and the order fails (e.g., person is using a credit card but it does not have enough balance to meet the cart totals, etc). I can see the order is in fact set as "FAILED" in WooCommerce, because I get the automated email from WC alerting admin of a failed order. I'm spending a lot of time testing out various actions and filters, and hoping someone could point me in the right direction. | You can catch specific status change by using this action hook 'woocommerce_order_status_{status}'. It is defined in the WC_Order class.
This is how you define it:
/**
* Executed when the status is changed to failed.
* @param int $order_id
* @param \WC_Order $order
*/
function wpdg_9291_woocommerce_order_status_failed( $order_id, $order ) {
// Do something here
}
add_action('woocommerce_order_status_failed', 'wpdg_9291_woocommerce_order_status_failed', 15, 2); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "woocommerce offtopic, filters, hooks, actions"
} |
how can I use add_action with external class which the function contain 2 argument?
I create a file name `custom.php` which is like below:
class customClass{
function dothisfunction( $mobiles , $message ){
//use parameters
}
}
In my `function.php` file I add the following code:
$number = '09112223344';
$mymsg = 'nadia is testing';
$myClass = new customClass();
add_action( 'publish_post', array( $myClass ,'dothisfunction', $number, $mymsg ) );
but it returns error, the error is :
> **PHP Warning** : call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members in C:\xampp\htdocs\wp-includes\class-wp-hook.php on line 288
How can I solve it? Can anyone help me? | The `publish_post` post takes two arguments first is `$ID` of the post that is being published and the second is the `$post` instance (See codex). I modified your code a bit below.
Your class is almost identical just renamed the parameters of the function to not cause confusion.
class customClass{
function dothisfunction( $ID, $post ){
echo "something";
}
}
No need for the `$number` and `$mymsg` in the array() because you only need to specify instance and the method to be used of the instance.
$myClass = new customClass();
add_action( 'publish_post', array( $myClass ,'dothisfunction' ), 10, 2 );
Also, you should specify how much parameters you are passing to `dothisfunction` in add_action as 4th parameter. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "actions"
} |
How to hide CSS by default and show on button press
I have the Elementor Pro page builder plugin installed and I want to setup a expanding column so when a button is pressed it expands more Elementor sections.
I'm pretty certain this can be done with jQuery but can't get it to work properly.
I got the button to work using this code
jQuery( document ).on( 'click', '#MY_BTN', function( event ) {
event.preventDefault();
// Show/Hide the widget
jQuery( '#MY_WIDGET' ).toggle();
});
but I couldn't get the section to hide by default, how do I achieve this?
Many thanks
Thomas | You can actually hide it on page load using **`jQuery ready()`** method:
$(document).ready(function(){
$('#MY_WIDGET').hide();
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, jquery, widgets, css"
} |
How check that there is post thumbnail feature image or not on wordpress?
On my wordpress site ,
I have some post that all of them have post thumbnail, but their post thumbnail removed from host and now when i want to load them on site , there is no image for loading to user ,
I want to know how can i set that if feature image is removed, show default image?
thanks | The main problem here is what exactly was removed. If only thumbnails, then you can always regenerate them and everything should work OK.
If all files are missing, then you can check if attached file is missing using this code:
if ( file_exists( get_attached_file ( get_post_thumbnail_id( $post_id ) ) ) {
// file exists
} else {
// file doesn’t exist
}
You can also use `wp_attachment_is_image` function for that:
if ( wp_attachment_is_image ( get_post_thumbnail_id( $post_id ) ) {
// file exists
} else {
// file doesn’t exist
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post thumbnails, thumbnails, images"
} |
modifying every other element's class inside while loop
<?php
$homePosts = new WP_Query(array(
'posts_per_page' => 5
));
while ($homePosts->have_posts()) {
$homePosts->the_post(); ?>
<section class="align-right>
<div class="content">
<?php the_title(); ?>
<?php the_content(); ?>
</div>
</section>
<?php } wp_reset_postdata(); ?>
The above code is part of my `front-page.php`. I am trying to modify the class that is in `<section class="align-*****">`, so that the 1st, 3rd, and 5th sections have `class='align-left'` and the 2nd, and 4th sections have `class='align-right'`.
What would be the best approach to modify the class values within a WordPress loop? Would I need to write my own function in `functions.php`? Use jQuery? Is there a WP function that can help with this? | <?php
$homePosts = new WP_Query(array(
'posts_per_page' => 5
));
$count = 1;
while ($homePosts->have_posts()) {
$homePosts->the_post();
if ( $count % 2 == 0 ) {
$class = 'right';
} else {
$class = 'left';
}
?>
<section class="align-<?php echo $class; ?>" >
<div class="content">
<?php the_title(); ?>
<?php the_content(); ?>
</div>
</section>
<?php
$count++;
} wp_reset_postdata();
?>
You can try this code | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions"
} |
Difficulty hiding a span per a body class within WordPress
I am trying to hide a span class as per the CSS class within the body tag.
Here is the HTML I am trying to hide:
<span class='efav-span'><img src="">Content here</span>
And the body tag is this:
<body class="post-template-default single single-post postid-5613 single-format-standard wp-custom-logo wp-embed-responsive cookies-not-set post-image-above-header post-image-aligned-center no-sidebar nav-float-right fluid-header separate-containers active-footer-widgets-0 header-aligned-left dropdown-hover" itemtype=" itemscope>
So what I thought would easily work is this:
.single.efav-span {display: none}
But oddly it doesn't?
I want that span to be hidden on ALL regular WordPress Posts.
Any idea what I am doing wrong?
Thanks | Answer was simple:
.single .efav-span {display: none}
add spacing to each element | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "posts, css"
} |
error log bloated by add_view
Has anyone else had any issues with their error log adding a line that just says add_view every few seconds?
e.g.
[03-Jun-2019 15:25:11 UTC] add_view
[03-Jun-2019 15:25:14 UTC] add_view
[03-Jun-2019 15:25:14 UTC] add_view
[03-Jun-2019 15:25:18 UTC] add_view
[03-Jun-2019 15:25:19 UTC] add_view
[03-Jun-2019 15:25:19 UTC] add_view
[03-Jun-2019 15:25:28 UTC] add_view
[03-Jun-2019 15:25:29 UTC] add_view
[03-Jun-2019 15:25:33 UTC] add_view
[03-Jun-2019 15:25:38 UTC] add_view
[03-Jun-2019 15:25:39 UTC] add_view
[03-Jun-2019 15:25:39 UTC] add_view
[03-Jun-2019 15:25:43 UTC] add_view
I can't work out what is causing the issue | I'm not sure where this would be coming from, but it's likely a plugin or some custom code is doing this. You could try to track this down using `grep` on the command line:
cd /path/to/wp-content/
grep error_log -rn --include \*.php . | grep add_view
This should hopefully list any PHP files that have a line matching `error_log` and `add_view`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "errors"
} |
Multisite - maximum number of users with specific role
Is there any plugin or script where i can use to define maximum number of users with a specific role on subsite in a multisite network?
I'm offering cloud helpdesk wordpress and pricing is based on number of agents, so I want to make sure that site admin is not able to add more agents than the predefined.
Thanks a lot in advance | Ok here is how I did it:
add_action( 'editable_roles' , 'hide_editable_roles' );
function hide_editable_roles( $roles ){
$blog_id = get_current_blog_id(); // Get current subsite id
switch($blog_id) { // Define different max agents numbers depending on subsite id
case 6:
$max_agents = 10; //for subsite id#6 we can have maximum 10 agents
break;
case 7: //for subsite id#7 we can have maximum 3 agents
$max_agents = 3;
break;
default:
$max_agents = 3000; //default is 3000 agents
break;
}
$agents = get_users( array( 'role' => 'agent' ) ); // here you define the role
$agents = count( $agents );
if ($max_agents <= $agents){
unset( $roles['agent'] ); // here you define the role
}
return $roles;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, multisite, users, user roles, count"
} |
Client viewing before deployment
I'm currently building a site on my local computer. I will transfer the finished product onto my client's new host/domain. Before he chooses this, what's the best way for him to view my current progress? | there is a lot of plugins where you can make all modifications on your theme, plugins and only logged users will see those changes, so you could show your client while for not logged in users will see "Maintenance" or "Soon" mode.
Also you can make a authentication log in system on your host "If that permit" to see your changes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization"
} |
Block All in One SEO from altering site title
The new version of AIOSP( v3.0 ) is altering site title forcibly and doing anything in the theme does not block it to do so ! How to prevent it from this stupid behavior ? | Here is the solution to completely remove it's title filter First disable "force rewrites" in "performance" Then add this code to theme "functions.php"
add_action( 'template_redirect', 'remove_aioseo_wp_title', 1 );
function remove_aioseo_wp_title() {
global $aiosp;
if( isset( $aiosp ) ) {
remove_filter( 'wp_title', array( $aiosp, 'wp_title' ), 20 );
}
}
**Edit:** This is the new code for v4.0
add_action( 'wp', 'remove_aioseo_wp_title', 0 );
function remove_aioseo_wp_title() {
if( ! function_exists( 'aioseo' ) ) {
return;
}
$aioseo = aioseo();
remove_action( 'wp', array( $aioseo->head, 'registerTitleHooks' ), 1000 );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin all in one seo"
} |
how to show all type of author posts in author page (SOLVED)
my site have multiple authors. I need to show all type of author posts in author page that if visitors can see all posts of author when visitied his profile page.
this code
<?php get_header(); ?>
<!-- Show custom post type posts from the author -->
<?php global $wp_query;
query_posts( array(
'post_type' => 'sikayet' ,
'author' => get_queried_object_id(),
'showposts' => 10 )
); ?>
<?php if ( have_posts() ): ?>
<h3>SIKAYETKLER <?php echo $curauth->first_name; ?>:</h3>
<?php while ( have_posts() ) : the_post(); ?>
<p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>">
<?php the_title(); ?></a></p>
<?php endwhile; ?>
<?php else: ?>
<p><?php _e('User has no custom posts'); ?></p>
<?php endif; ?>
<?php get_footer(); ?> | If you use WordPress author template to show user posts ( `example.com/author/{user_name}` ) the best solution will be to change the main query via the pre_get_posts filter hook.
function se339534_author_any_post_types $query ) {
// apply changes only for author archive page
if ( ! is_author() || ! $query->is_main_query() )
return;
$query->set('post_type', 'any');
}
add_action( 'pre_get_posts', 'se339534_author_any_post_types' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -1,
"tags": "posts, pages, author, profiles"
} |
Can a wp_nonce created from domain 1 to be verified on domain 2?
From the Domain 1 i want to make an AJAX request to Domain 2.
I would like to create a `wp_nonce` on Domain 1 and send it with AJAX request to Domain 2, then verify it on Domain 2.
The 2 domains are on 2 different servers. Is that possible? | No, it is not possible. Nonce is generated on server as a function of domain name, user information, action, time, etc.
This is made especially to distinguish requests from one server to another. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "ajax, nonce"
} |
How can I get the list of all pages URLs including their shortlink IDs?
I would like to get the list of all URLs from a wordpress installation. Nevertheless, I Don't want the full post titles in the permalink but I would like the shortlinks instead. I would like to get the following in the same fashion:
| You can get this from the `guid` column in the `posts` table of your database.
![List of guids from database, eg | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks"
} |
Preferred way of cacheing a value in php
I have a couple of pages that make calls to an external API to retrieve a value. Obviously, doing this every time the page loads is horribly slow.
What is the preferred way of cacheing this value for a limited amount of time (I only need it once every 24 hours).
If it matters, i will eventualy be extending the calls to make a large call to get a JSON object back, for another page, and will need to cache the whole object for 24 hours.
Things i've explored: Static file, just reading/writing to it Database table wp_cache? (there was some wording about how this isn't persistent across page reloads) wp total cache (i think it might be pro only)
i'm not hugely familiar with php, so i'm not sure if there's something built into the framework to handle this. or am i looking at this completely wrong? Would WP super cache (which caches entire pages and serves them statically) do what i need to do with minimal effort? | You want the Transients API: get_transient and set_transient (and get/set_site_transient).
These store values in the wp_options table with a namespace and expiry date, so they do persist through page reloads. (As does anything stored in the database, unless you explicitly create per-connection temporary tables.) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, php, cache"
} |
AJAX button run function
I want after click button run function, . All is in one class.
**JQUERY**
jQuery('#text2').click(function() {
var data = {
'action': 'myfunction',
'whatever': $button.data('text2'),
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
**PHP**
public function myfunction() {
$write = intval( $_POST['whatever'] );
$write++;
echo $write;
wp_die();
}
**HTML**
<button id="text2" value="1500"> test </button> | In order to make this work as you expect, you need to add the following lines in your constructor (depending on the requirements you have)
add_action( 'wp_ajax_myfunction', array($this, 'myfunction') );
add_action( 'wp_ajax_nopriv_myfunction', array($this, 'myfunction') );
Note that `wp_ajax_nopriv_myfunction` executes for users that are not logged in. The other executes for logged in users only.
You also need to just check that in your JS, `ajaxurl` returns your ajax URL.
If not, you'll need to expose that URL for usage in your JS. You can do that by following the codex here: <
You will need to call `wp_die();` at the end of your PHP function as well. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, functions, ajax"
} |
Get page by path - honoring permalink settings (urls w/slashes)
Let's say I have a `page` with the name `sample-page`.
I can do this:
get_page_by_path('sample-page')
To get that page.
* * *
Now, let's say I want to get a post where the URL to that post is `/post/8`.
If I do
get_page_by_path('post/8'); // with or without leading slash
I get back `null`.
How do I retrieve the page/post for any given URL in WP?
Edit: here's a screenshot that might add some clarity to my issue
` to get the post ID with the relative page url.
$url = '/page-parent/page/';
$post_id = url_to_postid( $url );
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks, urls"
} |
Absolute Image URL in srcset is appended to the upload dir
I've WooZoone, Woocommerce installed and Divi for my theme. The product detail pages look perfect. But when I add a product block i.e. on my front-page, the images are not shown.
The generated HTML code is:
<img width="300" height="300" src=" class="attachment-woocommerce_thumbnail size-woocommerce_thumbnail wp-post-image" alt="" srcset=" 300w, 150w, 768w, 1024w, 400w, 1080w, 510w, 600w, 100w, 64w" sizes="(max-width: 300px) 100vw, 300px">
All links in the srcset are ` \+ `absolute amazon url`.
Does anyone know where this is comming from and how I can fix this? | I guess you worked around that issue - still I stumbled over your post having the same issue. I was able to work around by applying a bugfix from woozone itself - in your wordpress solution with woozone enabled go to:
1. WZone -> Config -> Bug Fixes
2. Scroll down to the option "Disable WordPress Images Srcset attributes"
3. Set the option value to Yes
4. Save the settings.
The issue was in my case that if multiple images were present, an woozone applied medias stored on amazon (my setting was on no but the plugin still does it in certain cases) the srcset was generated with the sites image upload url, followed with the absolute amazon url, as you described. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, woocommerce offtopic"
} |
How do I redirect all 404 error url to Subcategory url
I have a b blog of over 200k+ post and I moved all post from a specific category to a subcategory, I have also deleted the post from the my main site, so all the post of that category have been moved to a subcategory.
Our analytics show that a lot of crawling errors, and my wp permalink structure for main site is example.com/postname/, while the one for my sub-category is example.com/stack/postname/
The solution I came up with is to redirect all visits for non-existant URLs of main site to subcategory URLs
Example:
* `mysite.com/postname/` which does not exist will be redirected to my sub-category url
* `example.com/stack/postname/` this pages are active and have content.
How would I go about this? | <?php
header("HTTP/1.1 301 Moved Permanently");
header("Location:
exit();
?>
The above code was added directly to themes 404.php and everything worked as expected | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, redirect, htaccess, 404 error"
} |
Using same variable names in files added with get_template_part()
Say I have a file named `content-header.php` and `content-body.php`.
In content-header.php I have this variable:
`$some_var = 'apples';`
and in content-body.php I have a variable with the same name but different value:
`$some_var = 'bananas';`
In another file I use:
get_template_part('content', 'header');
get_template_part('content', 'body');
Would `$some_var` be limited to its own file or overwrite the other? Is it ok to use same variable names in files added through `get_template_part()`?
Would I have to use unique variable names? | You can absolutely use the same variable names. Arguments like that do not pass through from one template to another without a little help from a function.
So if in `content-header.php` you have `$fruit = banana;` and in `content-body.php` you have `$fruit = apple;` you will not have a conflict. Go nuts. Or bananas. ;) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "php, templates, get template part"
} |
Use the custom post type archive for taxonomies?
Im using a archive-cpt.php template page to display all my custom post type posts but now I will be categorizing them in taxonomies. I want to add a dropdown filter navigation that will be populated by the name (and link?) of each taxonomy.
I was wondering if I could use the same template and populate it dinamically for title, description and posts or should I do a taxonomy-cat-cpt.php?
I'd love to just use one page and make it load via ajax or maybe just reload but with the same template. Any thoughts? | You can create `taxonomy-cat-cpt.php`, and inside it just use:
<?php get_template_part( 'archive-cpt' ); ?>
Then they'll both use the same template.
Then inside `archive-cpt.php`, if you use `the_archive_title()` archive `the_archive_description()` it will display the appropriate title and description automatically based on whether you're viewing the taxonomy or post type archive.
Regarding posts, as long as you're using the main query (so just `have_posts()` and `the_post()` and no `new WP_Query()` nonsense), then the appropriate posts should be listed, as long as you're using the correct links.
For anything else that needs to be different, you can check `is_tax( 'cat-cpt' )` or `is_post_type_archive( 'cpt' )` to conditionally hide or show elements for each one. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, taxonomy, archives, custom post type archives"
} |
Remove <figure> tag on my RSS Feed
I need to remove the tag that appears on my feed content ($content variable).
<
Is there an existing function to this task?
Some tags appear with width instructions that are differents on each appear. How can I remove them completely? | I believe the most direct way of customizing WordPress feeds is to hook into them directly with the following filter. Edit: as we talked about, let's just edit the content to tear out any
function edit_your_feed_content($content) {
$content = preg_replace("/(<figure.*?[^>]*>)(.*?)(<\/figure>)/i", "", $content);
return $content;
}
add_filter('the_content', 'edit_your_feed_content'); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "functions, customization, tags, rss, feed"
} |
How can I setup a development environment which auto refresh page when code have changed
When develop a website with Wordpress, I spent a lot of time to change small pieces of code like CSS, HTML element.
Each time I did that, I needed to do so many steps:
1. Change the code
2. Save it
3. Switch to web page window
4. Refresh the web page
5. Check the updated content
I had 2 monitors in my workspace. So I wish that have some technical help me just save the code then web page will auto refresh.
After that, I just have 3 steps:
1. Change the code
2. Save it
3. Check the updated content
Many thanks for your help!!! | Something like BrowserSync is what you're looking for ( < ) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization"
} |
Security Issues with custom user role or changing core role capabilities?
I have a scenario where I need a editor like role but with extended capabilities where they can access woocommerce orders,products and user page. If I would to create a custom role or change the core editor role with these extended capabilities, will there be any security issue in the site or will there be a code break in the site when i'm upgrading wordpress version? | Modifying the editor role by adding new capabilities will grant users editor capabilities plus these new capabilities. As long as you're comfortable with that level of access, there aren't additional security concerns.
If you want to create a new role which is what I recommend for this scenario, you can craft the capabilities according to your needs and only grant the capabilities you want these users to have.
The only concerns I would have with updates is if the core WordPress editor role were to change in the future. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, user roles"
} |
Integrate separate web app inside wordpress
I want to integrate a wordpress installation with a third party application, it's an online football game simulation. Is it possible to wrap it inside my wordpress installation, but with a separate database? | Yes, it should be doable. And you should be able to leverage `wpdb`, with new instance, to connect to the separate database. Have a look at this old question, Using wpdb to connect to a separate database. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, core"
} |
Migrations for plugins, page and theme: looking for a good approach
What are good practices / best plugins / your personal approach for Migrations?
No matter the plugin, always always when I migrate a Wordpress website something goes wrong. Either links not working, pages not displaying, plugins not installed, forms built with plugins not imported, it never happened to me to have a smooth and flawless transition.
What is a good approach for it? I would like to know if I am doing something wrong or I am missing pieces.
I personally use:
* All-in-One WP migrate => I compile the package and then I import it in the new website
* Since this plugin misses some pieces here and there, I also do a query to substitute the GUID of the pages with the new website migrated
* General Theme files. Some images are not displaying, I wonder if I need to fix some links as well in the DB.
I thanks you in advance for all the suggestions and /or tutorial you can advice. | The best plugin experience I've had is with WP Migrate DB Pro. I've used a few others, including All-in-One, but this gave the best results and the most control, even allowing you to set up and save regularly used paths between sites for migrations between live, dev, stage environments, etc. It does media migrations, individual tables, and it gives you a clear report of what worked and what didn't. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, migration"
} |
Anchor link to every product
I use WooCommerce on WordPress. Now when I click (open) some product I have to scroll down lot, because there is long header and menu before product itself.
So, my question is: How to add anchor to product link when I click (open) it?
If you don't understand, please ask me. | You can use the `woocommerce_loop_product_link` filter to modify the archive product urls.
// Add to (child) theme functions.php
function my_prefix_modify_woocommerce_loop_product_link( $url, $product ) {
/**
* Adds the id of the product wrap element from single product view
* as an anchor parameter to the WooC archive loop product url
* e.g.
* update "single-produt-wrap-id" to match your setup
*/
return $url . "#single-produt-wrap-id";
}
add_filter( 'woocommerce_loop_product_link', 'my_prefix_modify_woocommerce_loop_product_link', 10, 2 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "woocommerce offtopic"
} |
customize theme with get_template_part()
I'm often using the `get_template_part()` function. I read the theme handbook about this function and the codex, but I'm not sure when this function can be useful. For example I've made some modular template parts that will have different functionality, like a swiper slider, image comparision or parallax effects. If I code a child theme manually, I will then modify it to be loaded whit the custom post category or name, but in a scenario where I want to sell my theme, How i can assign a post to this or that template part? | `get_template_part()` is useful for organizing chunks of your site into reusable parts. If you have parts of a larger template that might be used in multiple templates, it's useful to use `get_template_part()` to pull these in rather than have the same markup in each separate template.
### The real power of `get_template_part()` is that it allows child themes to override these _only_ these template parts.
For example, you mention a swiper slider. Using `get_template_part()`, someone could create a child theme and override the swiper slider template part to be a grid of images instead of a slider. All they would have to do is create a template file that's named correctly in the child theme and WordPress would use this new template part instead of the parent theme's template part. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development"
} |
Append php file to footer
I have javascript in my php file. and I want to load it in footer. Is any method for that? | This might help you.
add_action('wp_footer', 'insert_my_js_to_footer');
function insert_my_js_to_footer(){
?>
<script>
// your script here.
</script>
<?php
};
**UPDATE:**
And if you want to append the php file itself then you can try this.
add_action('wp_footer', 'insert_php_file_to_footer');
function insert_php_file_to_footer(){
include( 'your-php-file.php' );
}; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, javascript, wp enqueue script"
} |
Thumbnails are hard cropped not matter what
I'm using WP Job Manager, and would like user-uploaded logos to be resized and positioned to fit within a fixed height and width. Currently, my settings are at:
:

I tried adding the following to my theme's functions.php:
add_image_size( '150x150-crop', 150, 150, false );
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 150, 150, true );
Nothing makes a difference. Any ideas? | What you're apparently asking for isn't possible. WordPress will never _add_ white space to an image to make it fit a certain size. This is what cropping means. Cropping will always remove (i.e. crop) some of the image so that it fits a certain size. As far as I am aware, there is no tool that ever refers to _adding_ space as 'cropping', so WordPress' behaviour is the expected behaviour.
So your only options are to resize the image, keeping the proportions (your 3rd image), or removing some of the image to fit the desired dimensions (your 2nd example).
If you want images to fill specific dimensions without being cropped, you will either need to upload them at the desired dimensions originally, or if they're being used in a specific way in a specific template, use CSS to position the uncropped images the way you want. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post thumbnails, thumbnails, images"
} |
Gutenberg table block with Bootstrap .table class
On my frontend I am using Boostrap 4, however Gutenberg block table has class `<table class="wp-block-table">` so instead of creating new table style it would make more sense to append the Boostrap table class to `wp-block-table` class. Would like to know if this possible. Thanks. | Since my theme did not recognize wp block table class I have added table Sass class from Gutenberg to my theme.
.wp-block-table {
width: 100%;
min-width: 240px;
border-collapse: collapse;
margin-bottom: 24px;
td, th {
padding: .3em;
border: 1px solid rgba(0, 0, 0, 0.1);
word-break: break-all;
}
th {
text-align: center;
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, block editor, twitter bootstrap, table"
} |
Retrieving Author ID in wp-admin area
Currently able to display the post author ID on the frontend with no difficulties. Returning the ID in /wp-admin when editing a post is proving to be tricky. Here's what I have so far:
$current_user_id = get_current_user_id(); // Get the current users ID
$author_id = get_post_field ('post_author', $post_id); // Get the author ID
if( is_user_logged_in() && $current_user_id == $author_id ) {
// wp-dashboard script
}
I've tried a handful of other methods for getting the user ID with no success. Displaying $current_user_id through the theme's functions.php file worked without issues along with other PHP code. Perhaps the ID isn't being loaded when functions.php loads? | It can be done like this without having to rely on the $post global.
if ( is_admin() ) {
if( isset( $_GET['post'] ) && isset( $_GET['action'] ) && $_GET['action'] === 'edit' ) {
$post_id = $_GET['post'];
$current_post = get_post($post_id);
$author_id = $current_post->post_author;
}
}
The query string variable `post` is always the `post_id` you are editing and additionally you need to check if the `action` query variable is set and it equals to `edit`.
Additionally you can explore the get_current_screen() function to setup more advanced conditionals for better security. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, posts, wp admin, author"
} |
Theme My Login Shortcode Doesn’t Return Anything
I have created a new page with the slug /login. In this page I have added a short code:
[theme-my-login action=“login” show_links="0"]
And in the TML plugin settings page, I have set the right slug for the login form location (login).
After all of this, when I go to the login page of my website, the login form doesn’t show up.
Although I do not have a page for reset password set up, when visiting the resetpass page, the reset password form shows up.
What’s going on and how do I fix this? | It could be the quotes if the code you have pasted is the exact code you're using. Notice around the word `login` the quotes are curly rather than straight. Try pasting the same straight quotes you have around the number `0`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, themes, login"
} |
per blog metadata for plugin
I wish to have my plugin store metadata for each blog in a network (or just one if single site install). Most of the Google results are for post_meta and user_meta but I really need site_meta which does not appear to be the same (only a get method). The data is generally going to be of the form:
$metadata['this']['foo'] = 'something';
$metadata['this']['bar'] = 'one thing';
$metadata['that']['foo'] = 'mum';
$metadata['that']['bar'] = 'dad';
What is the best way to store this? | Options are site specific, so you just need to use `update_option()` and `get_option()`.
The network-wide equivalents are `update_network_option()` and `get_network_option()`. Note that `update_site_option()` is just a wrapper for `update_network_option()`, and is an older name from when a multisite network was (confusingly) called a 'site'. The same applies for `get_site_option()`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, custom field"
} |
How to display all terms from all taxonomies in post, but separately for each taxonomy?
If I want to display all terms assigned to a custom post with custom taxonomy, I could use for eg.
<?php the_terms( $post->ID, 'custom-taxonomy', '', ", ", '' ); ?>
but in this solution I need specify name of taxonomy.
I want to display all terms from all assigned to post taxonomies, but separetly. For eg. if I have taxonomies called "`holidays`" and "`countries`" I want to display their terms like that:
<div>
<span>[terms of "holidays"]</span>
<span>[terms of "countries"]<span>
</div>
How can I do that automatically, without giving the names of taxonomies?
Thanks! | You can get the taxonomies that are registered for a post type with `get_object_taxonomies()`. If you pass the post object directly, you don't even need to explicitly name the post type either.
You can then loop through the result of that function to achieve the result you want:
$taxonomies = get_object_taxonomies( $post );
foreach ( $taxonomies as $taxonomy ) {
the_terms( $post->ID, $taxonomy, '<span>', ", ", '</span>' );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, taxonomy"
} |
Can I put in Github the code of a abandoned plugin I want to fork?
My friends. I want to know if I can create a repository of abandoned plugin of wp.org that the author is not mantaining make 2 years.
The plugin is this:
<
I just want to know if I will have problem with the law if I put it in the Github because is a third party plugin, even if I mantain the author in the readme.txt. Thanks!
**Edit:** < | I‘m not a lawyer but a plugin developer. As far as I know you ca republish any GPL code. The only thing you should do first is
* try to reach the author in the forum
* have a look at the plugin files, maybe there’s an email address where you can try to reach out to the author
If both doesn’t work just fork it. This is the recommended process to take over a plugin if it seems to be abandoned. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, author, licensing, third party applications, github"
} |
RSS feed for a given user's post?
I know how to get the site's RSS feed - that `get_bloginfo('rss2_url')` but is there a way to get the same thing but only for a given user? Effectively the RSS feed of the posts listed on the author's page. | The function for getting an author's RSS feed URL is `get_author_feed_link()`. You just need to pass it the user ID. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "users, rss"
} |
Creating an endpoint in wordpress
I'm writing a plugin that will allow some of my installs to talk to each other and share specific information. I wish to specify an endpoint such that `example.com/path/here` is where the other site can GET some nicely formed XML or POST some nicely formed XML (depending on which way the data is flowing).
As a rough hack, I set up `./wp-content/plugins/myplugin/endpoint.php` but I get the impression that direct calling is going to be bad. How do I do this the WordPress way? | You can create a custom endpoint using the `add_feed` function. I have used this in the past to create custom iCal feeds.
// Initialize the feed
function your_add_custom_feed() {
// This adds a feed
add_feed('myfeed', 'your_create_feed');
}
add_action('init','your_add_custom_feed');
// Create a function to form the output
function your_create_feed() {
// Query variables are accessible here ($_GET)
$myvar = get_query_var('myvar');
// You may need to specify the header before output here depending on your type of feed
// header(...)
// Echo your feed here.
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "endpoints"
} |
301 Redirect Link to Media
I sent an email to some folks today with a link to a word document hosted on wordpress. The URL in the email is something like:
www.mycompany.com/media/2018/06/somedocument.docx
Unfortunately, somedocument.docx actaully resides at:
www.mycompany.com/media/2018/ **05** /somedocument.docx
When people click the link in the email, they get a 404. We have tried a 301 redirect from one to the other, but that doesn't seem to work. I'm assuming that's because it's a direct link to a file and not a normal HTTP request?
We have already sent a follow-up email with the correct link, but we'd like to fix the issue as well so that when someone clicks the original link in the email, they get redirected to the actual document instead of a 404. Does anyone know how to accomplish this? Thanks. | If you have access to the .htaccess file, a quick 301 redirect should fix that for yah!
Redirect 301 /media/2018/06/somedocument.docx
(If you don't there are other ways to handle it inside the theme if you need to.) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect, media"
} |
Delete a custom field in mysql for all posts with specific category id
Delete a custom field in mysql for all posts with specific category id
I am trying to delete all custom fields with the key 'key1' from posts that are in category id '66'.
I can delete all custom fields with the key 'key1' with the following mysql query: DELETE FROM `wp_postmeta` WHERE meta_key = 'key1'
How do I specify the category in that query? | Please try with below code :
$pro_args = [];
$pro_args['post_type'] = 'post'; //Replace your post type
$pro_args['post_status'] = 'publish';
$pro_args['posts_per_page'] = -1;
$pro_args['tax_query'] = array(
array(
'taxonomy' => 'category', //Replace your taxonomy name
'field' => 'id',
'terms' => array( 66 ),
)
);
// Optional
$pro_args['meta_query'] = array(
'relation' => 'AND',
array(
'key' => 'key1',
'compare' => 'EXISTS',
)
);
$pro_query = new WP_Query( $pro_args );
if ( $pro_query->have_posts() ) {
while ( $pro_query->have_posts() ) { $pro_query->the_post();
delete_post_meta( get_the_ID(), 'key1' );
}
}
wp_reset_postdata(); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom field, mysql"
} |
How to integrate custom HTML template in a premium wordpress theme?
I have installed a premium wordpress theme in the server. But I just want to use my own html and css in the page template. There will be a new header, footer and menu. Is there any way to do that without breaking the code of the theme? And also how can I build that navigation menu?
Please help. I am pretty new to wordpress development. | Your best bet is to figure out how to make a Child Theme for your premium theme. And learn how Templates work (and the template hierarchy) .
Start at the Codex < . Lots of information about everything WP. And there are lots of googles/bings/ducks about creating themes and child themes.
With a Child Theme, you use the main theme as the starting point, then adjust things with CSS, hooks, filters, and templates to get things the way you want.
This is not an easy or quick 'journey', but lots of fun if you like tweaking and programming things.
Good luck! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "page template"
} |
Yoast makes comment_reply_link function output plain link to comment instead of reply link
EDITED - I discovered that my problem only arises when the Yoast plugin is active. But I want to keep Yoast active, so my updated question is: Any idea what to do for comment replies working while Yoast is activated?
Here's my original question:
In a custom theme created by myself, or rather its child theme on a multisite, I am having trouble with the `comment_reply_link` function. I am using it as follows:
<?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
Now on the website, the link doesn't result in the expected `/?replytocom=6#respond` appended to the URL of the post, but simply in a local `#comment-6` `href` attribute for the link. So when a user clicks on "Reply", nothing happens. When he/she writes a reply then, it is posted as a first-level reply, not as a reply to the intended previous comment. | Version 7 of WordPress SEO by Yoast removes the replytocom variables by default.
> We’ve removed the option to turn off the replytocom variable. The replytocom feature in WordPress lets you reply to comments without activating JavaScript in your browser. However, every comment gets is own link and these could all end up in the search engines. So we now remove these variables by default.
To get the replytcom variables back we can add the following filter in our theme's `functions.php`
add_filter( 'wpseo_remove_reply_to_com', '__return_false' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments"
} |
Can I use a wpdb object to connect to a non-Wordpress Oracle database
I simply have a quick question. I've found information related to this, but I'm not completely sure if this is possible. I know that I can create a second database connection using the wpdb object as follows:
$new_db = new wpdb(usr, pw, name, host);
However, is this compatible with an Oracle database that wouldn't have any of the Wordpress tables? | Although this got asked some time ago, it came time to actually implement this and ran into issues (see: Connecting to external oracle database)
The answer is no. Oracle is not a mysql based database, thus wordpress will not be able to connect to it via wpdb.
For more information see the linked post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, wpdb"
} |
Fatal error: Uncaught Error: Call to undefined function wp_nav_menu()
I am getting this error which
> Fatal error: Uncaught Error: Call to undefined function wp_nav_menu() in /home/stageidg/public_html/idg/wp-content/themes/idg-child/secondmenu.php:2 Stack trace: #0 {main} thrown in /home/stageidg/public_html/idg/wp-content/themes/idg-child/secondmenu.php on line 2
line 2 in the php file is this:
wp_nav_menu( array('menu' => 'Services', 'theme_location'=>'services' ) );
and its being called by this jquery code:
$.ajax(
{
url: " // path to your PHP file
dataType:"html",
success: function(data)
{
$(data).appendTo(inner_overlay); // load-into-div is the ID of the DIV where you load the <select>
} // success
}); // ajax
any idea? what am i doing wrong? | Yes, like @fuxia says, include **wp-load.php** to get the WordPress API (wp_nav_menu included) to use. In your case:
<?php
include '../../../../wp-load.php';
This way you did is not wrong but there are better ways to use AJAX in WordPress:
<
Be happy, my friend! | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "php, ajax, jquery"
} |
Will has_category be true is used on index and one of queried posts has the category?
If i use `has_category('dogs')` on a template like index.php or archive.php or search.php and one of the posts displayed on the loop have the category dogs, will the function return true?
I know it works on single post but i need to know if it also works when on THE LOOP and any of the posts has the category. | As long as `has_category` is used within the loop then it should work when used within `index.php`, `archive.php`, etc. You will likely run into issues if it is used outside of the loop on those templates. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions"
} |
Dynamically update post title in admin page
I have a textarea in admin post page when creating new post, that's title:
<textarea id="post-title-0" class="editor-post-title__input" placeholder="Add title" rows="1" style="overflow: hidden; overflow-wrap: break-word; resize: none; height: 94px;">vbhgfhfgh</textarea>
I want to update title on the fly using jQuery. I tried
$('#post-title-0').val('some value');
$('#post-title-0').text('some value');
I also tried using plain javascript.
`val()` updates title but when I click on title it is being erased. Is there anyway to update title via JS? | The block editor is restoring back the title that was last saved (or typed manually into the textarea), so with the block editor, you can change the title dynamically using this code:
wp.data.dispatch( 'core/editor' ).editPost( { title: 'Title here' } )
PS: You should make sure your JS file has the `wp-editor`, `wp-edit-post` or `wp-data` as part of the dependencies.
## UPDATE
Here are the resources which helped me identify the above solution/code:
* <
* <
* < (the React component which setups the title textarea / UI) | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "posts, jquery, javascript, title"
} |
taxonomy list display custom post count
I use `$term->count` to display post count but it displays the total count of all type of custom posts attached to taxonomy...
I just want to display the count of only a specific custom post type attached to taxonomy
$icon = get_field('logo', $term->taxonomy . '_' . $term->term_id);
$va_category_HTML .= '<li class="logolar" '.$carrentActiveClass.'>' .'<a class="rownum">' .$i++. '</a>'. '</a>';
$va_category_HTML .= sprintf('<img src="%s" />', $icon) . '</a>';
$va_category_HTML .='<a href="' . esc_url( $term_link ) . '">' . $term->name . '</a>';
if (empty( $instance['wcw_hide_count'] )) {
$va_category_HTML .='<span class="post-count">'.$term->count.'</span>';
}
$va_category_HTML .='</li>'; | What makes this annoying is that the `count` is a `wp_term_taxonomy` table.
So the way to do this is a custom query:
function wpse340250_term_count( WP_Term $term, $post_type) {
$q_args = [
'post_type' => $post_type,
'nopaging' => true, // no limit, pagination
'fields' => 'ids', // only return post id's instead of full WP_Post objects will speed up
'tax_query' => array(
array(
'taxonomy' => $term->taxonomy,
'field' => 'term_id',
'terms' => $term->term_id,
),
),
];
$term_count = get_posts($q_args);
return count($term_count);
}
So change the line to:
$va_category_HTML .='<span class="post-count">'.wpse340250_term_count($term, 'CUSTOM_POST_TYPE').'</span>';
Just set the correct posttype. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom post types, posts, count, list"
} |
get_posts changes main query
Here is my code in single.php :
<?php if (have_posts()):the_post() ?>
<h3><?php the_title() ?></h3> <!-- Prints `Hello World` -->
<?php if (!empty($someOtherPosts = get_posts(['posts_per_page' => 3]))): ?>
<ul>
<?php foreach ($someOtherPosts as $post): ?>
<li><?php echo $post->post_title ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<h3><?php the_title() ?></h3> <!-- Prints `Bye World` -->
<?php endif; ?>
Why am I getting different title in the next _the_title()_ call and how can I manage this? | `get_posts()` isn't modifying the main query. The problem is that you're overwriting the global `$post` variable in your `foreach` loop. I guess if you're in a template then you're in the same scope as the global variable and don't need to specify `global $post;` for this to happen (as you would if you were inside a function). Rename `$post` in your loop and the issue will go away:
<?php if (have_posts()):the_post() ?>
<h3><?php the_title() ?></h3>
<?php if (!empty($someOtherPosts = get_posts(['posts_per_page' => 4]))): ?>
<ul>
<?php foreach ($someOtherPosts as $someOtherPost): ?>
<li><?php echo $someOtherPost->post_title ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<h3><?php the_title() ?></h3>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop"
} |
Return all users that have one or more published blog posts
I am working on a plugin for which I need to create an array of all users (name and ID) that have one or more publish blog posts.
Looking at the documentation for `get_users()` it does not seem to have an arg value for this particular requirement.
How do I obtain this data? | There is an argument for this, and it is documented. If you look at the documentation for `get_users()` is says this:
> See WP_User_Query::prepare_query(). for more information on accepted arguments.
If you follow that link you'll see the list of arguments, and one of those is:
> **'has_published_posts'**
>
> _(bool|array)_ Pass an array of post types to filter results to users who have published posts in those post types. `true` is an alias for all public post types.
So you can get published authors like this:
$authors = get_users( [ 'has_published_posts' => true ] );
Or, if you just want users who have published posts:
$authors = get_users(
[
'has_published_posts' => [ 'post' ],
]
); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "users"
} |
main menu hide woo commerce single products tittle
> sorry maybe its off topic but i couldn't find any answer in oceanwp and woocommerse forums
i use oceanwp them and elementor for design and my problem is main menu hide single products tittle
this is the site URL you can see main menu hide product tittle
<
this is another issues
<
;
function wpo_wcpdf_show_product_categories ( $template_type, $item, $order ) {
// get a comma separated list of categories (category links stripped)
if (isset($item['product'])) {
echo '<div class="product-categories">DETAILS:<br/> '.strip_tags( wc_get_product_category_list( $item['product']->get_id() ) ).'</div>';
}
} | Please try this code this will give you categories in list format: `echo '<ul>' . wc_get_product_category_list( $item['product']->get_id(), '</li><li>', '<li>', '</li>' ) . '</ul>';` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, woocommerce offtopic"
} |
How to invoke a HTML custom button based on a HTML dropdownlist menu
**I am a WordPress beginner and want a help**
I created a HTML dropdown list like this:
<select name="DropDownList1" id="DropDownList1">
<option value="select you location"> select your location</option>
<option value="cairo">Cairo</option>
<option value="alexanderia">Alexanderia</option>
<option value="aswan">Aswan</option>
<option value="port said">Port Said</option>
</select>
and also I created a HTML button like this:
<button type="button" name="restaurantpreview" type="submit" value="chefpreview">restaurantpreview</button>
I am trying to search about the code that I must use to :
* when a user select a value from dropdown list
* then the user click on my button
* I get this value to my custom page and preview the list of restaurants in it | You want to use `admin-post.php`) or `admin-ajax.php` (AJAX only) to allow your front-end form to interact with WordPress.
Setting this up will allow you to create an action where you use the `$_POST` array to find the content you're looking for with `WP_Query` and print it out as the response to your request.
Here's a decent guide to both methods: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, wp query, customization"
} |
How can I UN-orphan media files?
Something wrecked a non-profit WordPress site I'm responsible for (I'm not a WP expert, just the most technical of all our volunteers). I was able to restore most of it from a backup, but the database seems to have forgotten most of the links to the media in the wp-content/uploads. All the media is still in the directories, but the database doesn't know it is there.
Obviously I could manually re-import all the hundreds of photos, but before I resort to that, I wanted to see if there is a technique or a plugin that would add everything already neatly sorted and stored in /uploads to the media database. Most of the plugins I've found are all about deleting orphans, but I need to add them to the db. | This is random, but a friend of mine got himself into the same situation a two weeks back and found this plugin to be helpful.
<
But as Tom mentioned above in his comment, you'll run into attachment post type issues.
Hope this helps you get half way there!! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "database"
} |
Adding regular php file to site
How do I create a page(in wordpress theme folder) so that it can be accessed on my site as `examplepage.com/somepost.php`?
I can see it as `examplepage.com/wp-content/themes/mytheme/somepost.php` but is there any way to cut off the path? Placing the file in the root folder is not an option.
Thanks in advance. | You could accomplish this by setting up a redirect. If you're using an Apache server, for your example, you would add this to .htaccess above the WordPress block:
RewriteEngine On
RewriteRule somepost.php ^/somepost/
It's much more common, and recommended, to create a PHP file _and_ a Page (or other post type) within wp-admin). This will still run all of your PHP code, and has the added benefit of automatically including all the WordPress functionality as opposed to an orphan PHP file. In somepost.php in your theme folder:
<?php
/* Template Name: Show Some Post
*/
// all your PHP here
?>
then within wp-admin, actually create a Page (or another post type that supports page-attributes) and select this particular Page Template. You will then have a URL such as < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, templates, filesystem"
} |
How do I return all terms from multiple taxonomies?
I need to generate a sorted array of all the terms within a set of (six) taxonomies (custom tags) for a custom post type without any duplicates (of which there are likely to be many).
Is this something `get_terms()` can handle and if so, how do I go about doing that? If not, is my best approach 6 calls to `get_terms()` followed by an `array_merge`? | You have all sorts of fun questions today! There is also a `WP_Term_Query` available in WordPress. Here is some info on it as well as what parameters you can pass it. <
$term_args = array(
'taxonomy' => array('tax_one', 'tax_two', 'tax_six'),
'hide_empty' => false,
'fields' => 'all',
'count' => true,
);
$term_query = new WP_Term_Query($term_args);
foreach ( $term_query->terms as $term ) {
// Here is what lives inside of $term when the 'field' parameter above is set to all
/*
WP_Term Object (
[term_id] => 11
[name] => General Topics
[slug] => general-topics
[term_group] => 0
[term_taxonomy_id] => 11
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 22
[filter] => raw
)
*/
// Maybe build out your array() in here to NOT have duplicate Terms ??
}
Hope that helps!! | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "custom taxonomy, terms"
} |
List all ACF field values across every post on one page
I used an ACF repeater field for data sheets/instruction manual download links of products in woocommerce. There's 50 products and each has 1 to 4 download links on their product page. I've been searching for a way to list all the links form all 50 products on one page the way you would query all posts on a page in a list. I don't even know where to start looking and I didn't see anything specific on the ACF forums. | You want to start here and here.
Essentially you're just looping through all your posts like normal and then adding some custom fields into it.
Be sure to reference the Repeater Field documentation.
This should work inside a loop. Notice you'll need your post ID.
<ul>
<?php
if( have_rows('YOURREPEATERFIELDNAMEHERE', 'POSTIDHERE') ):
while ( have_rows('YOURREPEATERFIELDNAMEHERE', 'POSTIDHERE') ) : the_row(); ?>
<li><?php echo get_sub_field('SUBFIELDNAMEHERE'); ?></li>
<?php endwhile;
else :
// no rows found
endif;
?>
<?php endwhile; ?>
</ul> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, wp query, advanced custom fields"
} |
WPAdverts - How to limit form submission 10 per month
I currently use wpadverts plugin and wants to limit the submission to 10 submit / month.
How can I do that?
I think I need to make a new row like "form_submissions" in "wp_usermeta" and store every time when the user submitted the form and make a cron task to delete the row value after a month.
And I need to query the row value on the form submit page like this:
$result = mysqli_query($connect, "SELECT COUNT(*) AS `form_submission` FROM wp_usermeta WHERE user_id = $user_id");
$row = mysqli_fetch_assoc($result);
if($row['form_submission'] > 10) {
// can't submit the form because you already have 10 post
} else {
// you can submit the form
}
Or I'm totally lost? Sorry for my bad english. | You can do it using `get_user_meta` and `update_user_meta`:
$value = get_user_meta($user_id, 'form_submission', true);
if (!$value) {$value = 1;} else {$value = $value + 1;}
if ($value < 11) {
update_user_meta($user_id, 'form_submission', $value);
} else {
// too many form submissions
}
You could also expand on this to store the submission month too if you don't want to use a cron job.
$month = get_user_meta($user_id, 'submission_month', true);
$value = get_user_meta($user_id, 'form_submission', true);
if ($month && ($month != date('m',time())) ) {
update_user_meta($user_id, 'submission_month', date('m', time());
$newmonth = true;
} else {$newmonth = false;}
if (!$value || $newmonth) {$value = 1;} else {$value = $value + 1;}
if ($value < 11) {
update_user_meta($user_id, 'form_submission', $value);
} else {
// too many form submissions
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "forms, limit"
} |
get current product name in functions.php
i create a button in a current product page after woocommerce_single_product_summary
i would to get information about the current product ( for example name and price) and through the button send an email for get information
this is the code of my functions.php file:
add_action( 'woocommerce_single_product_summary','content_after_addtocart_button' );
function content_after_addtocart_button() {
echo '<div class="content-section">
<a href="mailto:[email protected]?&subject= Richiesta Informazioni&body= product name ??? product price ??? ">
<input type="button" value="Richiedi Informazioni"/ ></a></div>';
}
anyone can help me ? | Please check below code :
add_action( 'woocommerce_single_product_summary','content_after_addtocart_button' );
function content_after_addtocart_button() {
global $product;
$product_title = $product->get_name();
$product_price = $product->get_price();
echo '<div class="content-section">
<a href="mailto:[email protected]?&subject=Richiesta Informazioni&body=' . $product_title . '??? ' . $product_price . ' ??? ">
<input type="button" value="Richiedi Informazioni"/ ></a></div>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, functions, categories, woocommerce offtopic, production"
} |
How to check if the postID is in an array?
In Wordpress, I am trying to check through an if else statement if the post is of a certain ID as follows:
<?php if ($post->ID == array(224,222,583,645,203,11,639,228,226,230,634,615,625,214,220,194)) : ?>
...do something...
<?php else : ?>
...do nothing...
<?php endif; ?>
This isn't working. Can you please help in knowing how to use the check the post ID in arrays? | As Sally highlights, you can use in_array() like this (untested):
// target ids
$ids = array(123, 321, 213);
if (!empty($post->ID) && is_numeric($post->ID) && in_array((int)$post->ID, $ids)) {
// do jazz
} else {
// do stuff
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "array"
} |
What does the author_nicename parameter do in get_author_posts_url()?
I was looking at `get_author_posts_url()` which takes the user id as a param and returns a URL. It has an optional second parameter `$author_nicename`.
get_author_posts_url( $author_id, $author_nicename );
What does providing `$author_nicename` do exactly? | Say that `get_author_posts_url(1)` return the following URL
> <
Passing the `$author_nicename` will change this. So `get_author_posts_url(1, 'foo')` will result in
> <
You can also check this in the source code of `get_author_posts_url()`.
* * *
So what does passing the second argument do? It changes the resulting URL. If you don't provide further mechanisms, this will probably result in invalid URLs.
Why is this provided? No idea.
Ok, so checking this file via Git blame turns out, `get_author_posts_url()` was previously called `get_author_link()` (this change happened on Aug 30, 2006). `get_author_link()` was added on Mar 19, 2004 and required the argument `$author_nicename` (though it had a fallback).
Why is this provided? Because in earlier times, you needed to pass the (correct) nicename for this to work. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions"
} |
How to show a list of only categories (exclude subcategories)
I have a list where you show me the categories, but I would like you not to show me the subcategories, only the categories
$term_id = get_categories();
if (function_exists('get_wp_term_image'))
{
$meta_image = get_wp_term_image($term_id);
//It will give category/term image url
}
$categories = get_categories();
foreach($categories as $category) {
?>
<article>
<div class="poster">
<a href="<?php echo get_category_link($category->term_id); ?>">
<?php echo '<img src="'.get_wp_term_image($category->term_id).'">' ?>
</div>
<div class="orbit_starts">
<h2><?php echo $category->name ?></h2></a>
</div>
</article>
How would you exclude all subcategories?
Thank you | $args = array(
'orderby' => 'name',
'order' => 'ASC',
'parent' => 0
);
$categories = get_categories($args);
May this will help you. Refer this link | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, list"
} |
How to get user ID's from multiple usernames?
I am trying to produce user ID's from multiple specific usernames. The usernames are pulled from a profile field, and any number of usernames will be called. I want the user ID's from each of the users to be put into the 'include' of $args like `'include' => array( 1, 2),`. What am I doing wrong?
// Search these Usernames
$usernames = array( user1, user2 );
// Fetch the User IDs
$prof_ids = array();
foreach ($usernames as $prof_id) {
$user = get_user_by('user_login', $prof_id);
$prof_ids[] = $user->ID;
}
// WP_User_Query arguments
$args = array(
'include' => $prof_ids,
);
I tried printing each variable to see where I'm going wrong, and these are their outputs:
$usernames = Array
$prof_ids = Array
$prof_id = user2
$user =
$args = Array | Your call to `get_user_by()` has a small hiccup in it. It needs to be **login** rather than **user_login**
// Search these Usernames
$usernames = array('user1', 'user2');
// Fetch the User IDs
$prof_ids = array();
foreach ($usernames as $prof_id) {
$user = get_user_by('login', $prof_id);
$prof_ids[] = $user->ID;
}
// WP_User_Query arguments
$args = array(
'include' => $prof_ids,
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop, user meta, array, users"
} |
add to cart button not adding products in cart only in safari and edge browser
Add to cart button not adding products in cart only in safari and edge browser on other all browser working fine please advice | i got it fixed by updating all plugins and wordpress core version.. thanks alot | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Count custom post types with a specific meta value
We have a custom type called `books`. In a template, we need to show the counts of books that have the `book_type` as
1. Fiction
2. Non Fiction
3. Novel
4. Short Stories
We use ACF Pro, and the above field is set up as a checkbox multiple selection. So a book can be Fiction + Short Stories, Fiction + Novel, etc. We need to count only Fiction.
This does _not_ work, as found in another suggested thread here:
$query = new WP_Query( array( 'meta_key' => 'book_type', 'meta_value' => 'Fiction' ) );
$fiction = $query->found_posts;
I don't have enough points to comment there, so it's better I suppose to create a new ticket.
Also found a thread on the ACF forums, but the code suggested there doesn't work either. I use latest WP, latest ACF Pro (5.8.x).
Welcome any thoughts on how to do this. | 1st. you need to add post_type to your query, then you need to filter meta_value with LIKE. Finaly, you need to add posts_per_page as -1 to get ALL posts.
$args = array(
'post_type'=> 'books',
'meta_query' => array(
array(
'key' => 'book_type',
'value' => 'Fiction',
'compare' => 'LIKE',
)
),
);
$query = new WP_Query($args);
$fiction = $query->found_posts; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, advanced custom fields, count"
} |
Are there any CSS classes for the wordpress colours?
Are there any CSS classes for the wordpress colours: <
For instance, classes like these from the Twenty Seventeen Theme:
.has-text-color .has-background .has-very-dark-gray-color .has-very-light-gray-background-color | No. The only styles that WordPress itself loads on the front-end is `/wp-includes/css/dist/block-library/style.min.css`, and this stylesheet doesn't include any such classes or colours. All other styles are the responsibility of the theme.
So if you want to know if a specific theme has such classes you would need to ask the author, however I don't know any reason why anyone would include the WordPress brand colours in their theme. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, color picker"
} |
Wordpress: Redirect Main Site to Subsite in Multisite Where user is NOT logged in
I have found this solution ( ) regarding redirecting a mainsite to a subsite in wordpress.
But!
What IF I only want this to happen when a user is not logged in ? I tried to change the code to this, but without any success..
<?php
function wpse66115_redirect_to_sub_site() {
if ( is_user_logged_in() && is_main_site() ) {
exit( wp_redirect( ' 301 ) );
}
}
add_action( 'parse_request', 'wpse66115_redirect_to_sub_site' );
?>
I also tried using an ELSE statement. But it seems the argument ignores the "is_user_logged_in" argument.
Any ideas ? | Try this
function wpse66115_redirect_to_sub_site() {
if ( is_main_site() ) {
if ( is_user_logged_in() ) {
} else {
exit( wp_redirect( ' 301 ) );
}
}
}
add_action( 'parse_request', 'wpse66115_redirect_to_sub_site' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, redirect"
} |
Is it possible to bind a function to a filter hook via Ajax?
I'm trying to bind a function to a filter hook via Ajax, like that:
function ajax_called_function_contains() {
add_filter( 'wp_handle_upload', 'save_landscaped_version_of_img' );
};
The goal is to call the `wp_handle_upload` only when I click an "add image button" on a given field, so the `save_landscaped_version_of_img` function triggers on `wp_handle_upload` hook but **only after I've clicked the "add image button" on that given field**. | > Is it possible to bind a function to a filter hook via Ajax?
**No, because page requests are self contained.**
When you request something from PHP, everything gets loaded from a fresh clean slate. At the end of the request, that slate is discarded.
This is different from say a Node application that is always running.
So, if you make an AJAX request and unhook a filter, it's only unhooked for that request. A second page load, or AJAX request will not be affected by the unhooking, so it would need to be done on every request.
If you want something to persist across requests, you need to store it somewhere that persists, such as the database of the filesystem. Either way what you want to do won't work, and there's no change to WordPress or PHP you could make that would allow it to work the way you proposed. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "filters, ajax, hooks"
} |
Why does SVG upload in Media Library fail if the file does not have an XML tag at the beginning?
I have enabled SVG uploads using this code:
add_filter('upload_mimes', function($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
});
However, uploads of SVG files that start with the `<svg>` tag fail with the usual "Sorry, this file type is not permitted for security reasons." error that WordPress displays when SVG uploads are not supported.
If I add `<?xml version="1.0" encoding="UTF-8" standalone="no"?>` to the file, just before the opening `<svg>` tag, the upload succeeds.
Why is the XML tag required? Is this requirement normal in WordPress, or is there something wrong with my setup? | It seems that in the recent releases of WordPress, changes were made to the mime type handling to make sure that files have the extension they say they do: <
This poses an issue for SVG files without the tag in them.
SVG is actually an XML, and WordPress is now requiring to have a line such as
<?xml version="1.0" encoding="utf-8"?>
in an SVG file. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "uploads, media, xml, svg"
} |
Issue with CPT posts within WP REST API showing as []
When I am querying for posts of a CPT, I get a response of 200 but a return of brackets [].
How can I show all of my CPT post data?
My syntax I am using in the url is: ` | So I tried everything and every plugin to fix my issue and expose the list CPT data instead of showing brackets [ ].
And the answer is something that might be a bug in Wordpress Rest API.
The problem was I am using **custom statuses** and none of my posts were assigned as default Wordpress status. After changing the posts to any of the default built-in statuses, it worked. But doesn't work for custom statuses it seems.... at least not with custom statuses created with a plugin called PublishPress.. Perhaps it just doesn't work with custom statuses at all, all-around
Hope this can help someone else! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, rest api"
} |
"Class 'Phar' not found" error setting up WP-CLI with Cygwin
I'm trying to install the WP-CLI tools as described here using Cygwin, which the guide claims is supported.
When doing:
cd /XAMPP/htdocs
curl -O
php wp-cli.phar --info
It fails with the following error:
> PHP Fatal error: Uncaught Error: Class 'Phar' not found in /cygdrive/b/Users/User/Desktop/XAMPP/htdocs/wp-cli.phar:3 Stack trace: #0 {main} thrown in /cygdrive/b/Users/User/Desktop/XAMPP/htdocs/wp-cli.phar on line 3
What's causing this error, and how can I successfully get WP-CLI running under Cygwin? | You are missing the Phar extension or it's not enabled. Which version of PHP are you actually running? Check it with `php --version`.
> The Phar extension is bundled with PHP as of PHP version 5.3.0, and enabled by default.
See <
Your best bet is to upgrade PHP to at least PHP 7.1. Alternatively follow other guides around here to either get and enable Phar, or calling WP-CLI with a different PHP version.
See PHP: Class 'Phar' not found.
* * *
Finally this one may turn out as a big helper as well: Cygwin and Xampp, wrong PHP is being used. To have Cygwin use XAMPP's PHP instead its own call the following command every time you restart Cygwin or add it to its `~/.bashrc` or `~/.bash_profile` to be permanent.
>
> export PATH=/cygdrive/c/xampp/php:$PATH
> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp cli, xampp"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.