INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
WordPress website loads fine on desktop browsers but Safari for iOS cannot load it completely
Everything is fine on desktop browsers but Safari for iOS' loading bar for my website shies from reaching 50% for a really long time. The problem persists across multiple iOS devices I have. I have not tested on Android because I have sent it for repair and it's going to take a while to be back. I use a Content Delivery Network for my website but it's caching cannot be the reason because I already tried disabling it to no avail. I also use W3 Total Cache and I moved all of the JavaScript before the closing `</body>` tag. I thought that it could be the reason for the problem but the website loads fine on Desktop using the same connection for the iOS devices. | It was because of a plugin called Easy Social Sharing Buttons version 3.5 I bought from Code Canyon. It is quite feature rich and may slow down your website. I would not say you should avoid it but I would advise you to do an extensive research that your website is running fine on different devices and connections if you are going to use it and similar plugins. ESSB's stylesheet was 5 times the size of my whole website's stylesheet and it has many JS files as well. Use Pingdom Tools to find out what is causing your website to be slow just like I did and found out. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "mobile"
} |
Possibility to use WordPress built-in localization
Is it possible to use WordPress default / built-in localization without text domain when creating localization for theme or plugin? for example word like `__( 'Submit' )` or `__( 'Publish' )` or any other common words should already in the WordPress localization dictionary. But if we're not specifying text-domain when creating theme it will not pass theme check. Or is there a text-domain for WordPress default one? Any suggestion? | It is possible, and in some cases make sense, but I would advice against thinking that way. Some words in the context of wordpress core admin might be translated differently in the context of a theme.
If the motivation here is to save translation time, then don't bother as any one with translation experience will use software that has a DB of translations and will auto translate such words. In addition common tools (poedit) are text domain blind and can not differentiate between different text domains, therefor it will be hard to not include 'submit' as part of the .pot file even if it is not actually needed to be translated.
Last and very least, loading the core translation is a performance hit that better to avoid if possible. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "localization"
} |
User content database
I am trying to set up a login where in each users profile they can add their CV and details. These details and CV will then be shown in a page that can be seen by anyone. The user has the option to edit its information whenever desired and update the information seen in a public page.
For this goal so far I figured out that I need the TML plugin for the login, then I have been trying with Contact Form 7 and Contact Form DB to make the database that gathers the information from the Contact Form7. The problem is connect the profile or a contact form to the user logged in without having to force the user to constantly add a new contact form to the website.
Can anyone point me any headers? Plugins I should use? Is this possible to set up with plugins? Thanks in advance. | Based on my experience, I can say that with contact form 7 plugin it will require lot of customization to achieve what you have mentioned. I will suggest to use BuddyPress plugin with BuddyPress Docs
BuddyPress will provide you profile with ability to edit from front end. Also, you can add different fields to profile from backend **Users > Profile Fields**. By default BuddyPress provides ability to add few basic fields to profile. For advance options you can use Buddypress Xprofile Custom Fields Type plugin.
I tried these just to share some screenshots with you. Below you will see how the the profile page looks by default with WordPress **Twenty Thirteen** theme.
 );`
Take a look at the original size:
<
Now look at the "hard cropped" version:
<
It is practically the same image, only scaled.. | They are not the same. In the 800x350 image, a little bottom is cropped.
This is how the hard cropped work:
First, it scales your image to match your image size. It can be width or height. Your size is 800x350
* If your original image scaled according to 800px width has the 400px height (bigger than 350), 50px of the bottom will be cropped ( because you choose `'top'`).
* But if your original image scaled according to 800px width has the 300px height (smaller than 350), it will be scaled according to the height. Then the scaled version has the height is 350px and the width will be 933px, so 133px of the right will be cropped out because you choose `'left'`.
Feel free to comment if you don't get my poor explain. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "post thumbnails, images, cropping"
} |
Update order status based on condition
I've created a custom field `Customer Level` for users, and I've also created a custom order status `autoprocess`. Now I want to auto-process orders based on customer level:
add_action('woocommerce_checkout_order_processed', 'auto_process_orders');
function auto_process_orders($order_id) {
$current_user = wp_get_current_user();
if ( $current_user->customer_level >= 5 ) {
$order = new WC_Order( $order_id );
$order->update_status( 'autoprocessed' );
}
}
.. but it just doesn't work. Order stays "on-hold" (since I'm using bank transfer as payment method). | Figured it. `woocommerce_thankyou` is the hook to be used. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Contact forms not sending mails
I used two plugins, contact form7 and pirate form, both display the message of succes but nothing coming in my inbox. Alsto tried the SMTP with google and hotmail but i recive a message that someone tried to login on my account. | For SMTP and Gmail, you will need turn on 2 step verification, then create an App specific password in security panel of google account. Use your email and that password as login credential. You'll also need use TSL or SSL for SMTP.
Hope this help! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "email, contact"
} |
How to allow Readers to Select Post Order?
I added a select field for every category, tag archive page.
1. Sory By Post Date
2. Sort By Post Modified Date
3. Sort By (custom field)
When a reader select any of above how to load posts according to selected order.
I have no idea where should I start at least... | What you need here is Ajax. You will need to read about how to use Wordpress Ajax (link).
When your visitor click on select field to choose sorting, you need a JS function to handle the data about how to sort and where the visitor in, then a js function to make ajax request to server.
At server here (I mean your theme function) you will need a function to handle request and send the response to client. The handler function here is a WP_Query loop to loop your post according to the order that your visitor chose.
Sorry, I don't have enough time to provide you the code, but I think for a scripter/coder/developer, the direction is enough. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, archives"
} |
How To Display Category list from Portfolio post type plugin?
I'm new from WordPress development. I want to display portfolio category list in my theme, I'm useing portfolio post type plugin
` which takes two params are the taxonomy you will get and an array. It will return an array of terms. Just surf the codex about that. After get the terms, you can use a `foreach` loop to display your result.
Example code:
$terms = get_terms( 'portfilio_category', array(
'hide_empty' => false
));
foreach ($terms as $term) {
echo $term->name;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, categories, functions, theme development"
} |
How to display html code normally?
I want to display my html code as it write in edited format.
Here is my edited html code.  under "Text" mode.
What you have to do is **to cut all the html code** in "Text" mode tab. Then you have to set the editor in "Visual" mode tab, and to paste your code.
Your code will be displayed like you want to.
Best, now what you can do (in "Text" editor mode), is to use the html `<code>` tag before and a html `</code>` tag after...
Regards | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "html, formatting"
} |
Remove Tag Cloud Words from Custom Taxonomy
How can I remove the `Seperate tags with commas` and `Choose from the most used tags` from my custom taxonomy? These: ;
register_taxonomy('test_company', 'testimonials',
array('show_tagcloud' => false,
'hierarchical' => false,
'labels' => $labels,
'query_var' => true,
'show_in_menu' => false)); | Here is how to remove the words: `Seperate tags with commas` and `Choose from the most used tags`
Simply add to the labels the following:
'choose_from_most_used' => NULL,
'separate_items_with_commas' => NULL, | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "custom taxonomy, taxonomy"
} |
How to get Attachments(image) with specific width\height ratio
I need to get attachment images with horizontal orientation. I tried to use `Meta_Query` but I don't know how to compare two values ( **width** and **height** ) from one associative array that is in `wp_postmeta` table. I don't have any specific values of width and height, I only need to compare this values which is in associative array.
Also tried to do this with `$wpdb` custom query:
$attach_ids = $wpdb->query( "
SELECT wp_posts.ID FROM wp_posts, wp_postmeta
WHERE EXISTS (SELECT * FROM wp_postmeta
WHERE meta_key = '_wp_attachment_metadata'
AND meta_value= ???)
AND wp_posts.ID = wp_postmeta.post_id
AND wp_posts.post_type = 'attachment'
AND wp_posts.post_mime_type = 'image/jpeg'
ORDER BY RAND() LIMIT 0, 6" );
Can anyone understand my problem and help? P.S. Sorry for my English. | The `_wp_attachment_metadata` stores serialized data. It's not meant to be used directly in queries to match results. Instead hook `add_attachment` action and store original image's dimensions into separate post meta properties. After you're happy with how it works follow Rarst's advice and find a way to walk all existent image attachments and generate those meta data for them also. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, attachments"
} |
How to get ID of images used in gallery?
How to get ID of images used in gallery? Using `$gallery = get_post_gallery_images( $post );` I only get a string with thumbnails url, without image ID which is needed for basically everything.
<
(In the end I am looking for a way to get image object for all images used in gallery, I am searching in Codex but I can't find it) | Are you writing a template? A filter in functions.php or a plugin? A straightforward method could be using `get_post_gallery` with the second argument set to false, so that it return the object rather than the html.
if ( get_post_gallery() ) :
//Get the gallery object
$gallery = get_post_gallery( get_the_ID(), false );
//Form an array with the found ids
$gallery_attachment_ids = explode( ',', $gallery['ids'] );
endif; | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 2,
"tags": "gallery, id"
} |
How to get permalink in foreach loop
What to do in situation when I don't have an ordinary if-while loop, how do I get permalink?
$page_children = get_page_children( 8, $all_wp_pages );
foreach( $page_children as $page ) :
echo $page->post_title;
the_permalink();
endforeach; | You should use get_permalink function and pass $page as an argument.
foreach( $page_children as $page ) :
echo $page->post_title;
get_permalink($page);
endforeach; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "permalinks"
} |
How to display author post count for multiple custom post types?
On my theme `author.php` page I have a number of posts displayed but it only count posts of the type 'post', I need it to count multiple post types.
I think they are trying to make this core but no updates for a while, see the ticket #32243.
I'm not a coder so I don't really know how to make it, can someone help me? | This ticket was fixed and closed in version 4.3.
Make sure you got the latest version ( currently 4.4.2 )
If we check out the inline documentation for the `count_user_posts()` we find this part:
* @since 4.3.0 Added `$public_only` argument. Added the ability to pass an array
* of post types to `$post_type`.
Note the default post type for that function is `post`.
So you will most likely have to add the post types you want, here's an example:
echo count_user_posts(
$userid = 1,
$post_type = [ 'post', 'page' ],
$public_only = false
);
to get the count for the user with _user id_ as 1 and post types _post_ and _page_. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "custom post types, count"
} |
Plugin Options Array Set to Undefined
I want to set a number of plugin options set to blank if they are not defined so I can avoid the PHP notices.
What is a better way of writing this code?
$options = get_option('plugin_options');
// Add new plugin options defaults here
if( !isset( $options['plugin_option_1'] ) ) $options['plugin_option_1'] = '';
if( !isset( $options['plugin_option_2'] ) ) $options['plugin_option_2'] = '';
if( !isset( $options['plugin_option_3'] ) ) $options['plugin_option_3'] = '';
if( !isset( $options['plugin_option_4'] ) ) $options['plugin_option_4'] = '';
if( !isset( $options['plugin_option_5'] ) ) $options['plugin_option_5'] = '';
New options would need to be added in future updates to the plugin. | WordPress provides a default method, `wp_parse_args`, to combine a set of default options and a user-defined set of options. This method uses PHP's native `array_merge` for arrays, but also works when either of the two option sets is an object or a WordPress options string.
You simply provide an array of default options and an array of set options, and WordPress fills the options that are missing in the options set by their default value.
You can find this code, adjusted for your example, below:
$options = get_option( 'plugin_options' );
$options_default = array(
'plugin_option_1' => '',
'plugin_option_2' => '',
'plugin_option_3' => '',
'plugin_option_4' => '',
'plugin_option_5' => ''
);
$options = wp_parse_args( $options, $options_default ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, array, options, notices"
} |
Unable To Get Published posts using query_posts
I'm not sure why this is not working as its a very simple query. It works when i pull all posts including pending, but not when i want to get posts that are only published.
I have a function to get posts. I pass in a bool variable. If its true, i want to pull all posts from a custom post type called books, including ones that are pending/draft. If false i only want the published posts. I see no issues with the code, but it wont work.
$args = array(
'post_type' => 'book',
'showposts' => -1,
'tax_query' => array('relation' => 'AND',
array( 'taxonomy' => 'book-category', 'field' => 'term_id', 'terms' => $termid)
),
'orderby' => 'date',
'order' => 'ASC'
);
if($getpending == true) $args["post_status"] = "any";
else $args["post_status"] = "publish";
$posts = query_posts($args); | First off, you probably shouldn't be using `query_posts`, which modifies WordPress' main loop and is unsuited for pretty much any purpose (read When should you use WP_Query vs query_posts() vs get_posts()? for more info). There are numerous reasons why `query_posts` wouldn't work as expected in this case.
WordPress has two proper approaches to fetching posts: the `WP_Query` object and the `get_posts` function. They work very similarly, with `get_posts` using `WP_Query` internally. However, as one would expect, `WP_Query` allows for more control.
For your case, `get_posts` should work (as there is no further flaw in the code you posted). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "query posts"
} |
Restore woocommerce orders
Recently my server team replaced my database and they put our previous Database . So we lost our order details of one day[particular day] . Now the server team give the backup that contain the lost day order details .
Now please tell how can i restore these orders ?
I cannot replace our database with the given backup , because today also we have orders .
Could anyone tell the step by step instruction ?
I Created a new database and uploaded backup .I understand that order are saved in wp_posts, and post meta .
So what i need to do ? , i export the all the order in that date from wp_posts,and post meta as sql file . Then just need to import it in to current database ? It make any problem ? | It's Simple.
**Step 1:** Create a replica of the instance.
**Step 2:** Import the old .sql file which contained one day lost orders data.
**Step 3:** Use < plugin and export CSV or XML of 1 day data which you have lost.
**Step 4:** Install the above plugin in the LIVE instance and import the CSV or XML generated.
That's all. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, database, woocommerce offtopic, mysql"
} |
Display specific page (that is child) content on parent page
I have problem displaying child page content on parent page (both static). I can display other page content but only if on same level. It dosent work in relation parent - child.
<?php
$investor_content_query = new WP_Query( array(
'pagename' => 'current',
'post_parent' => 'investor-relations'
) );
if ( $investor_content_query->have_posts() ) {
while ( $investor_content_query->have_posts() ) {
$investor_content_query->the_post();
the_content();
}
}
wp_reset_postdata();
?> | Ok, i found solution. What I really needed was parent page slug in "pagename" argument.
'pagename'=> 'investor-relations/current'
_And working solution:_
<?php
$investor_content_query = new WP_Query( array(
'pagename'=> 'investor-relations/current'
) );
if ( $investor_content_query->have_posts() ) {
while ( $investor_content_query->have_posts() )
{
$investor_content_query->the_post();
the_content();
}
}
wp_reset_postdata();
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, loop, pages, the content"
} |
ACF - How to set the menu order for the relationship field
So, I've got a relationship field where I select a certain amount of posts to show on the home page. What I am trying to achieve is to apply the menu order of the posts as they are in the back end so that they appear in that order on the front end.
For example, the below screenshot is how the posts are ordered in the relationship field back end of ACF:
;
$query = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 15,
'post__in' => $ids
));
Thanks! | `orderby` defaults to `post_date`, to order by the IDs you supply, you have to orderby `post__in`
$ids = get_field('homepage_lineup_new', 'option', false, false);
$query = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 15,
'post__in' => $ids
'orderby' => 'post__in'
)); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, php, advanced custom fields"
} |
Replace term archives with static pages
I need to make different pages for different Woocommerce product categories with each having different look and functionality. Defining templates for each term archive would make it difficult for my client to change things, and I'd like to make static pages for these terms which could allow use of a page builder.
I tried using `archive_template` filter but it apparently can't be used with static pages.
I'm also thinking about rewrite rules but I don't have knowledge about them, and don't want a redirect either. | I think this should work if library functions are used everywhere.
function custom_term_archive_link($url, $term, $taxonomy) {
if($taxonomy != 'product_cat') { return $url;}
if( $term->name == 'my_term' ) {
$url = 'my_term_static_url';
}
return $url;
}
add_filter('term_link', 'custom_term_archive_link', 99, 3); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "url rewriting, taxonomy"
} |
Get the categorie name of Event Organiser plugin
How can I get the name of a category in a custom template of the Event Organiser Plugin.
So far the only thing I can get it slug of the category by reading the following variable:
echo $eo_event_loop->query['event-category']; // test-cat
From digging a little in standard template the only thing I found is that they use the standard WP function `single_cat_title()`
echo single_cat_title( '', false );
But it doesn't generates any output in the template.
The template based on the following two global variables:
global $eo_event_loop,$eo_event_loop_args;
From what I can find in function reference of the Event Organiser plugin there is not such a function I'm looking for. | Okay I found the solution. A view in the mySQL table helped to understand how the **Event Organiser plugin** is using Wordpress. The Event Categories a just normal categories with the taxonomy `event-category`. The only function needed is `get_term_by()`.
// Get term by slug ''test-cat'' in event-category taxonomy.
$cat = get_term_by('slug', $eo_event_loop->query['event-category'], 'event-category');
echo $cat->name; // Output: Test Category | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, plugin event organiser"
} |
How to call a widget in a loop at a specific iteration value?
On the index page of my website. I want to display a widget in the third position. I am calling the widget through "the_widget( 'Widget Name' );" code. Now the problem is, since it doesn't return anything.
It will display the widget in the first position in my loop. Is there any way, I can store the widget content in a variable and display on third position. Or any other work around may be.
Thanks. | You can check what iteration you're on inside the main loop with `$wp_query->current_post`
while( have_posts() ){
the_post();
the_title();
// count starts at zero, so after 1 will be after 2nd post
if( 1 == $wp_query->current_post ){
the_widget( 'WP_Widget_Recent_Posts' );
}
}
### Edit
Regarding your comment about capturing widget output, you can try PHP output buffering:
ob_start();
the_widget( 'WP_Widget_Recent_Posts' );
$widget_output = ob_get_clean(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, customization"
} |
Call a javascript function from another file
In wordpress, to use $ instead of jQuery prefix, i added the following code around all js code:
jQuery(function($) {
...
});
It works well, but i cannot call an object from another javascript file, the following problem persists:
Slider is not defined
This is my code:
**file1.js**
jQuery(function($) {
var slider = new Slider();
});
**file2.js**
jQuery(function($) {
function Slider() {
this.nb_ele = 10;
}
});
It seems that because the workspace of two js files is different so they can't call function from another one. Any solution? | The issue you have is that `Slider` is not accessible outside of its scope as that's defined by the `.ready()` though you've used shorthand for that. The function needs to be available in the global scope:
file1.js
function Slider() {
this.nb_ele = 10;
}
jQuery(function($) {
// ...
});
file2.js
jQuery(function($) {
var slider = new Slider();
});
If you want Slider to stay in the document ready, you'll need to use a function expression to add the function to the global object:
jQuery(function($) {
window.Slider= function () {
this.nb_ele = 10;
};
});
See Also: < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "jquery, javascript"
} |
What is The Best Way to Make Parallax header effect for wordpress theme ?? pure CSS or using JavaScript?
I'm new in wordpress theme development, I want ask some question here, I want to make a parallax effect for my theme header like this:
TestParallax.com
this is made by using some JS code, I want to know what is the best way for WP Theme ?? using pure CSS or using JS ?? what is the most compatible for web browser ?? please help me guys .. | You can create Parallax effect for header using pure CSS as well as jQuery. The difference between them is the loading time. CSS will load much faster than jQuery. Implementing a feature will depend on the developer/owner of the theme how they want the feature to be. My preference is that you use pure CSS rather than jQuery.
Below are the two examples one with pure CSS and other with jQuery combination:
1. Pure CSS
2. jQuery
Please let me know if you have any query. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "theme development, themes, css, javascript, browser compatibility"
} |
Wordpress URL question
I have a web page that I created and in doing a google search for the company and my name a weird page came up. For private reasons I will not reveal the company name so I will use a fictitious company name. The URL that I found that came up was www.abc-tech.com/author/john and when I go to the URL the page shows up as a broken home screen with my name in the H1 saying ALL POSTS BY JOHN SMITH. I have no idea where this page is or how it is being created. Any help is greatly appreciated. | These are your user information, this tutorial can be helpful for you to change/update author slug.
There is no Author Template on your theme, have to create author template, < this will be helpful for you. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, pages, urls, google"
} |
Get users order by meta key with limit
Each user in system has meta key called `points`
I need to get top 10 users (highest points)
How I can do this query ?
Should I use `get_users()` with `$args` OR native query | You can use `get_users()` with `meta_key` and order by meta value, descending.
**Example:**
$user_args = array(
'meta_key' => 'points',
'number' => 10,
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
$top_users = get_users($user_args);
> **NOTE:** Support for `meta_value_num` is available only from version 4.2 | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 1,
"tags": "users"
} |
Redirecting to old domain, tried everything, nothing works
I've moved a Wordpress site from one domain to another. I have changed the `siteurl` and `home` options in the `wp-options` table, added this tags into `wp-login.php` file:
`update_option('siteurl', ' ); update_option('home', ' );`
and I've tried to rewrite the URL using these tags in the `wp-config.php` file:
define('WP_HOME','
define('WP_SITEURL','
When I enter ` to the address bar, I'm redirected to my old domain. But ` is normally accessible. In the settings I can even see the `WordPress Address (URL)` and `Site Address (URL)` with the correct values.
Is there any way to fix this? I have tried (as described above) everything I have found on the web and I am beginning to feel very hopeless.
(Sorry for my English mistakes.) | As Sumit pointed out, the problem was in the old browser cache. The solution was to clear browser cache (or just add a query string after the address: `
Thank you. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "redirect, domain, options"
} |
Woocommerce Product page edit
I am making an online store with every category using a specific page template; that's all done, but now, I want to edit the layout of that page template.
As such, every product will have:
* a name,
* an image,
* a short description;
_I would like the **product description** to be between the **product name** and **product price tag_** ,
* a price tag, and
* a _Add to Cart_ button.
My challenge: I have no idea about how to get started and need assistance in that regard.
What file do I possibly have to clone and or edit? | WooCommerce allows you to override its default templates. All templates are located in a `woocommerce/templates` folder. All you have to do is to create a `woocommerce` folder within your theme’s directory, and in this folder duplicate the files you’d like to override.
If you want to update the markup then you will need to copy `archive-product.php` and `content-product.php` files. If you just want to show a little description between the product name and price, then you can simply put following code into your theme's `functions.php` file.
function show_product_summary(){
$product_summary = get_the_excerpt();
echo '<div class="product-summary">'. substr( $product_summary , 0, 30 ) .'</div>';
}
add_action('woocommerce_shop_loop_item_title', 'show_product_summary', 10, 2);
You will see the product summary like below on product listing page.
{
//function to add async to all scripts
function js_async_attr($tag){
// Add async to all remaining scripts
return str_replace( ' src', ' async="async" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 10 );
}
add_filter('wp_head', 'async_js_mssa');
What am I missing? Thanks! | Can you try this, it was what I tried to explain in my comment. Again, this is just a guess.
function js_async_attr($tag){
// Add async to all remaining scripts
return str_replace( ' src', ' async="async" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr');
function remove_js_async_head(){
// function to add async to all scripts
remove_filter( 'script_loader_tag', 'js_async_attr');
}
add_action( 'wp_head', 'remove_js_async_head', 100); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, filters, javascript"
} |
Get and display a user's profile info?
I'd like to get specific info about all users with a certain role, then display that info on a page.
So, I'd like to:
1. Get all users with the role "Manager"
2. Get each user's avatar, first name, last name, and bio text
3. Display that info on a web page.
Note: This has _nothing_ to do with user ID or the current logged in user.
How do I do this? Every option I see in the WP codex seems tied to current user or a user ID. | You could create a custom template page for this purpose and take advantage of the appropriate class provided by Wordpress itself: WP_User_Query
Eg:
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query(array (
'role' => 'Manager',
'order' => 'ASC',
'orderby' => 'display_name'
));
// Get the results
$managers = $wp_user_query->get_results();
// Looping managers
if (!empty($managers)) {
echo '<ul>';
foreach ($managers as $manager)
{
// get all the user's data
$user_info = get_userdata($manager->ID);
//printing basic infos
echo '<li>';
echo get_avatar( get_the_author_meta( $manager->ID ), 96 );
echo $user_info->first_name;
echo $user_info->last_name;
echo '</li>';
}
echo '</ul>';
} else {
echo 'No managers found';
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "user roles"
} |
Calling a wp_query $posts causes a 500 error
I had a very basic `wp_query`, below:
// WP_Query arguments
$args = array (
'post_type' => array( 'post' ),
'post_status' => array( 'draft' ),
'posts_per_page' => '15',
);
// The Query
$posts = new WP_Query( $args );
This caused a 500 error. When I changed `$posts` back to the more traditional `$query`, everything was fine. Is `$posts` a reserved variable? | > Is `$posts` a reserved variable
Yes, it is, `$posts` is the global variable which holds the array of posts from the main query. This is how it is set:
$GLOBALS['posts'] = & $wp_query->posts;
Just remember, `$posts === $GLOBALS['posts']` | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "wp query, variables, 500 internal error"
} |
Automatically use specific template to load subpages
I have a page called Joinery and when open some new pages where I set that their parent is Joinery (under Page attributes), I would like to set Wordpress to automatically use file page-joinery-subpages.php for displaying them without manually selecting template.
My solution is based on this < ,
function load_usetemplate(){
global $post;
// get top level parent page
$parent = get_post(reset(array_reverse(get_post_ancestors($post->ID))));
if($parent->ID === pll__(8) && !is_page(pll_get_post(8)){
if ($child_template = locate_template( 'page-joinery-subpages.php'))
return $child_template;
}
return $template;
}
add_filter( 'page_template', 'load_usetemplate' ); | Before getting the top level parent page, you could check if the page has parents; also you forget to define `$template`.
This code should work:
function load_usetemplate( $template ){
global $post;
if( $post->post_parent > 0 ) {
// get top level parent page
$parent = get_post( reset( array_reverse( get_post_ancestors( $post->ID ) ) ) );
if( $parent->ID === pll__(8) ){
if ( $child_template = locate_template( 'page-joinery-subpages.php') )
return $child_template;
}
}
return $template;
}
add_filter( 'page_template', 'load_usetemplate' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "templates"
} |
get_theme_mod returning cached values regardless of apache restart
`get_theme_mod` is returning cached content: this code:
$parallax_one_logos = get_theme_mod('parallax_one_logos_content',
json_encode(
array(
array("image_url" => parallax_get_file('/images/companies/1.png') ,"link" => "#" ),
array("image_url" => parallax_get_file('/images/companies/2.png') ,"link" => "#" ))
)
);
And this code, containing a bollocks `test` value.
get_theme_mod('parallax_one_logos_content',
json_encode('test'))
**Return the same value.**
I have:
1. Shut Down Apache
2. Shut Down MySql
3. Tried Ctrl-F5
I am at a loss as to how to remove / clear the cache that `get_theme_mod` uses.
If it helps I am using `XAMPP` on windows 10.
Thanks | If the theme mod option has a value in database, your code is working just fine as it should return the value in database and ignore the second parameter. The second parameter is the default value to be used if there is no value is set. And the value is stored in database.
The problem is that you are wrong considering that the values of the theme mod are cached in database, **they are stored in database** , not cached; the query to get them from database can be cached but if you need to update the value of a theme mod, you have to update the value already stored in database. You can do it using `set_theme_mod()`:
set_theme_mod( 'parallax_one_logos_content', 'new value' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "cache, get theme mod"
} |
Save buddypress xprofile data to author meta
I have created a buddypress extended profile field "description" and would like to save the data entered to the "descripion" profile field of the user (DEfault wordpress Biography description field) when user fills / edit the buddypress field.
Any clue .. how to achieve this?
Actually I'll be retriving in template as `get_the_author_meta('description',$author_id) ;`
So i want that the `xprofile` field save to this meta field as well | Use this action hook found in `buddypress/bp-xprofile/classes/class-bp-xprofile-profiledata.php`
do_action_ref_array( 'xprofile_data_after_save', array( $this ) );
You'll need to use the actual `field_id` for your xprofile description. This example assumes it is `25`. You can get the `field_id`by going to `wp-admin > Users > Profile Fields` and clicking 'Edit' on that field. The `field_id` will appear in the browser url.
function echoashu_save_description( $obj ) {
if ( $obj->field_id == 25 ) {
update_user_meta( $obj->user_id, 'description', $obj->value );
}
}
add_action( 'xprofile_data_after_save', 'echoashu_save_description' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "buddypress, user meta, author template"
} |
Why does not this wp_redirect work in is_single()?
I have a custom post type (portfolio) and I have to redirect a certain page (of this custom post type) to another page.
when I look at my custom post type page:
) {
wp_redirect('
}
but when I visit to the page (ID=2024) in front end it does not redirect to the page < why is that?
* 2024 - is a custom post type page's ID
* < \- is a default 'page' type not a 'post' type in wp. | `is_singular()` only accept `post_type`, use `is_single('2024')` for specific post.
if (is_single(2024)) {
wp_redirect('
exit();
}
**Update:**
Also `wp_redirect()` does not work after headers are sent. Please make sure you are redirecting before headers. So you can hook this function on `template_redirect` and put this in `functions.php`
function redirect_custom_page() {
if (is_single('2024')) {
wp_redirect('
exit();
}
}
add_action('template_redirect', 'redirect_custom_page'); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "custom post types, pages, wp redirect"
} |
get posts that doesn't contain a specific tag
I want to get all the posts that do not contain the tag 'index'. How can it be done?
I mean in the reverse of
get_posts(array('tag' => 'index'))
Thank you | You could try the `tax_query` with the `'NOT IN'` operator (untested)
$myposts = get_posts(
[
'tax_query' => [
[
'taxonomy' => 'post_tag',
'terms' => [ 'index' ],
'field' => 'slug',
'operator' => 'NOT IN',
]
]
]
);
where the taxonomy slug for _tags_ is `post_tag`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "tags, get posts"
} |
Check if Website is hidden from Search Engines?
Any idea how to check if the website is hidden from search engines? The reason is I want to show a big red banner at the top of the homepage when this option is checked because I always forget that this option is checked. | The setting is stored in the option `blog_public`.
if( 0 == get_option( 'blog_public' ) ){
echo 'search engines discouraged';
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "search engines"
} |
Add arguments to get_the_terms for custom post types
When using get_the_terms to retrieve terms within a taxonomy for a custom post type you can't pass arguments, like so:
function custom_cat_function() {
global $post;
$args = array(
'orderby' => 'ID',
'order' => 'ASC',
);
$terms = get_the_terms($post->id, 'category', $args);
$count = count( $terms );
if ( $count > 0 ) {
foreach ( $terms as $term ) {
echo '<li>' . $term->name . '</li>';
}
}
}
all documentation points to other functions like get_terms, but get_terms retrieves ALL terms within a taxonomy, not just the terms for that single post (within a loop).
How do you properly pass arguments like the example above (I'm aware the example above is not right, but I wrote it as a baseline example of what needs to be achieved) | `get_the_terms` uses `wp_get_object_terms` with defaults, which is orderby name ascending. You can use `wp_get_object_terms` directly if you want to set arguments differently.
$args = array(
'orderby' => 'term_id'
);
$terms = wp_get_object_terms( get_the_ID(), 'category', $args ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, terms"
} |
wordpress theme install failing
I am trying to install wordpress theme on my site, but is failing with message `Could not copy file. catch-responsive/404.php`
Folder permissions are as -
* ftp user is owner of the whole wordpress folder
* permissions are set as 755 for the wordpress folder
* When I start theme installation, it downloads into upgrade folder correctly but then i stops after the message above mentioned.
**I am able to upload themes manually with same ftp account**
Thanks | Problem was, that the _FTP_ user does not equal the _Apache_ / webserver user. I just had to (recursively) own the wordpress directory `/var/www` for the `www-data`/webserver user:
sudo chown -R www-data:www-data /var/www
Please refer to this link for further info about the owner of a directory. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "themes, permissions"
} |
create post with main category and other categories from admin panel
I want to add functionality in admin panel for add / edit post with selection like main category and other category. Main category will be used to generate permalink of particular post.
Default wordpress uses alphabetical order of category for generate permalink.
Once permalink will be generated for particular post, that permalink should not be changed when post will be updated.
I want to do this just because of SEO purpose.
Please suggest me if anyone has solution. Any help would be appreciated!! | Finally i got the solution.
I have used "WP Category Permalink" plugin to solve generate post permalink issue. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
How to get subscription key or id using Woocommerce Subscriptions
I need to get the subscription key of a particular subscription to pass into a custom function. I have referenced the documentation where it shows how to get the key, but I have failed to integrate this into my code. So what my code does is, when a renewal is triggered, I hook into processed_subscription_payment with my function. So this code is run only when a subscription renewal is payed. Code is below.
Documentation is here: <
Code here (which resides in functions.php):
add_action( 'processed_subscription_payment', 'callupdater' );
function callupdater()
{
//need to get the subscription key here to pass to updatedays()
$key = .....
updatedays(key);
}
function updatedays($subscription_key)
{
//do some tasks with the key
}
Any help is very much appreciated. I am very new to PHP so excuse my ignorance. | I figured out the answer, so I thought I'd post it. My code looks like this now and it works:
add_action( 'processed_subscription_payment', 'updatedays', 10, 2 );
function updatedays($user_id, $subscription_key)
{
//do what I need to the sub key
}
There really needs to be more examples on the Woothemes documentation though.. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, php, functions, woocommerce offtopic, subscription"
} |
Use has_filter on comment_post
I hook to comment form (on comment_form_logged_in_after if user is logged in and comment_form_before_fields if not) to add 2 fields (rating and title).
These fields can be mandatory or comment will not save. These fields will not appear on comment reply or if review are not enabled for a certain post or page.
If these fields are mandatory, I've to check on comment_post (just before to save comment) if filter has run, and if not just save the comment withoud any comment_meta.
The problem is that if I try to use
has_filter('comment_form_before_fields', 'my_function_to_check');
when I hook on comment_post it ALWAYS return FALSE.
If, for example, I try to show
var_dump(has_filter('comment_form_before_fields', 'my_function_to_check'))
on comment_text filter it works.
How can I do this? | You're adding the action on `comment_form_before_fields` in `comment_form_logged_in_after`. The latter is called only when the user is logged in, and the former is only called when the user is _not_ logged in.
You can add WordPress actions and filters at any time after WordPress is initialized. If you're adding the action in a plugin, add it on `init` or even when the code is first executed (i.e. not on an action but directly in the plugin).
This way, the action is added immediately and called when it needs to be called. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, comments, hooks, actions, comment meta"
} |
Fatal error: Call to undefined function the_posts_navigation()
I'm following a tutorial which is using WP 4.0 and _'s. I'm getting the following error and I don't know why.
> Fatal error: Call to undefined function the_posts_navigation() | The function `the_posts_navigation()` was added in WordPress 4.1.0, and will therefore not be available in version 4.0 (which you're using). It's highly advised to keep up to date with the latest version of WordPress anyway for security reasons, so you'd be better off updating to the latest WordPress version. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -2,
"tags": "theme development, navigation"
} |
How can I use custom menus with a Bootstrap WordPress theme?
I have this 'primary' menu with a few items in the CMS, which I can list nicely with this **PHP code:**
$args = array(
'theme_location' => 'primary'
);
wp_nav_menu( $args );
The PHP outputs the menu with the `<ul>` tag. but, I want to use **HTML** that looks like this:
<ul class="nav navbar-nav">
<!-- primary menu items -->
</ul>
I'm looking for the right way to output my primary menu with the HTML from above. | You can change the classes of the `<ul>` by adding `'menu_class'=>'nav navbar-nav'` to your `$args` array. _Remember, this parameter overwrites all the classes, so add "menu" as well if you want many themes and plugins to work!_
If you don't want the outer `<div>`, you can "unwrap" the `<ul>` by adding `'container'=>false`.
$args = array(
'theme_location' => 'primary',
'menu_class' => 'nav navbar-nav',
'container' => false,
);
See the full reference here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, functions, menus, html"
} |
Create decorative image border with CSS?
I'm trying to create a custom border style for several images on a website (building in WordPress.) Is there a way to get the style shown below with pure CSS? (i.e.: trying to add the dark green wavy border shown below)
 32 round round;
background-color: #3c93c9;
}
Good luck. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "images, css"
} |
Display Powerpress media url
I am trying to display the url of a media file in a template. I ran across this post: < but when I add that to my template (in the loop as it says) nothing shows.
So, I am not sure which is easier...to display what the field in the WordPress admin panel is in the template which looks like:
<input type="text" id="powerpress_url_general" class="powerpress-url" name="Powerpress[general][url]" value="myfile.mp3" style="width: 70%;">
or to try something like: < (maybe a function has changed).
This is what I have that doesn't output anything:
if( function_exists('powerpress_get_enclosure_data') ) {
$EpisodeData = powerpress_get_enclosure_data($post->ID);
if( $EpisodeData ) {
$url = $EpisodeData['url'];
echo $url;
}
}
Am I missing something? Shouldn't the code I have output the url I am looking for?
Thanks,
Josh | So, I have no idea how it happened, maybe it's a PowerPress thing...I activated the HTML 5 player, then went back and reactivated MediaElement's player and the issue resolved itself. Now, everything looks as expected on mobile.
Thanks,
Josh | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, theme development, customization, media"
} |
Add Sortable Column For All Post Types
I am creating a hit counter that counts the number of page views across all post types. I have gotten it to work and the column displays for each post type showing the total number of page views. I was able to get the column to show up for every post type by using the following filter.
add_filter('manage_posts_columns', 'posthit_columns');
I want to make this a portable column. I have gotten this to work for the main posts, post type, but i dont know how to make it show up for every post type without actually creating a filter for every post type.
The following filter will make the column sortable for the default post, but i have several post types and this isn't working. Is there a catch all filter for this?
add_filter( 'manage_edit-post_sortable_columns', 'managesortablecolumns' ); | Why not get all post_types and loop through them with the filter. This should work if the callback for all post types is the same (managesortablecolumns).
The code will look something like this:
function init_managesortablecolumns (){
$post_types = get_post_types();
foreach( $post_types as $post_type ){
add_filter( 'manage_edit-' . $post_type . '_sortable_columns', 'managesortablecolumns' );
}
}
add_action( 'init', 'init_managesortablecolumns' );
BTW, if you store the post hit value in a custom field (post meta) you could use the Admin Columns Pro plugin. This plugin has an interface for adding new columns to the overview with sorting, filtering and inline edit support. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "filters, wp admin, columns"
} |
Open upload media dialog from thickbox
I'm using Thickbox (lightbox) built-in in WordPress to display some controls for user, some of controls using javascript to open dialogs like Upload Media that is already works fine outside the Thickbox.
I know that the Thickbox creates a new div with a unique-ID [TB_window] so i made a stand-alone js file for all scripts in Thickbox only but it still not working, it may be because Thickbox takes all controls from hidden container div and put it inside popup but i cannot deal with this scenario.
Any ideas? Thanks! | Finally, I found the solution by replacing event handler!
Old Scenario (WRONG)
$('#TB_window').on('click', '.upload_media a.btn_media_upload', function (e) { //Code } );
New (Working)
$('body').on('click', '#TB_window .upload_media a.btn_media_upload', function (e) { // Code }); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "thickbox"
} |
Make a custom theme translate-ready
I created a my own theme, now I wish to make it translatable.
I made two files:
**theme.pot**
msgid "know_more"
msgstr "Vuoi saperne di più?"
**it_IT.po**
msgid "know_more"
msgstr "Vuoi saperne di più?"
Then in the index theme file i wrote:
<h2><?php _e('know_more',''); ?></h2>
But when I run the site appears just: _know_more_ | To do it properly, you need to generate a valid .mo file and load the text domain in your theme functions.php:
function wpse222346_localize_theme() {
load_theme_textdomain( 'your_theme_domain', get_template_directory() . '/languages' );
}
add_action( 'after_setup_theme', 'wpse222346_localize_theme' );
You can check the WordPress Codex for more info on the load_theme_textdomain function: <
Then you would call the translatable strings using your theme's text domain:
<h2><?php _e( 'know_more', 'your_theme_domain' ); ?></h2>
Also, it's strongly advised to use a tool for automating the creation of the POT files. It makes maintainability much easier. There are many options, such as Poedit, several online generators, makepot.php and even a very nice plugin to do it from the WordPress Dashboard called LocoTranslate. Most of them will also help you creating the .PO and .MO files. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "theme development, translation, multi language"
} |
Notify after 3,6,9 and then 12 months after plugin activation
I save plugin current month with below code on plugin activation. I want that after 3 , 6 , 9 and then 12 months a notification is generated for the user. How can we do that. Below is the code to record the current month and save it in a variable. On everyday on page open I want the plugin to compare the value with the first save date and notify after exact 3 months, then after 6, 9 and 12 months after plugin activation .. How can that be done.
$start = date('m'); | You could try to set a Transient and set its expiration to 3 months. Once it expires, it can trigger a message or some other behavior that alerts the user about the timeframe. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "date"
} |
How to add #navbar to all page links?
I have several Wordpress websites with large images at their tops, using 2013 child theme.
How to add `#navbar` anchor to all page links, so that the browser scrolls down a bit, when a user clicks a link in the _Pages_ widget?
.
In the file wp-includes/widgets/class-wp-widget-pages.php I have found the source code for the `WP_Widget_Pages`, but I am not sure how to modify it the best way (it should probably happen in my `twentythirteen-child` theme too). | You can add a filter to `page_link` to modify link output:
function wpd_add_fragment_to_pages( $url ) {
return $url . '#navbar';
}
add_filter( 'page_link', 'wpd_add_fragment_to_pages' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "menus, filters, widgets, child theme, theme twenty thirteen"
} |
Hiding site title for Twentyfifteen sidebar on (responsive) desktop display size
I'd like to hide the site title that appears on the sidebar on a twentyfifteen theme WordPress website when viewing it in a desktop display, but have it show when the display is fitted for mobile or tablet view (and a dropdown hamburger menu shows instead of a sidebar).
Ideally, I'd like to accomplish this through CSS. I couldn't see any unique CSS id's or classes applied to the body when resizing from desktop to mobile, so I can't figure out a way to do something like;
.site-title { display: none; }
but have it apply in the desktop view only. Any suggestions on how I could accomplish this? I'm also open to solutions via adjusting the theme PHP files if need be (via a child theme). | This should do it for you.
@media screen and (min-width: 59.6875em){
.site-title {
display: none;
}
}
I'm new here so I'm not sure why the downvotes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -3,
"tags": "css, responsive, theme twenty fifteen"
} |
PHP/WordPress -- How do I check if Shortcode returns content?
What I'm basically trying to do is check if a shortcode is returning any content, I'm using a plugin called Ninja forms and they have default content posting using their own shortcodes which look like this:
[ninja_forms_field id=84]
Assuming it works like a WordPress's default shortcode, how would I check if it returns any content, I've been trying to get this basic PHP code to work but it doesn't seem to ever evaluate as true:
<?php
if(!empty([ninja_forms_field id=84])){
echo "has content";
} else{
echo "not working";
}
I'm using a WP plugin called "Insert PHP" to run PHP in the default post form, I did several test and this plugin runs PHP wonderfully, so it's the shortcode logic that's failing me.
Here's a quick Ninja Forms article on their Shortcodes, this might help | Run the Shortcode through `do_shortcode` and check what the output contains.
$shortcode_content = do_shortcode( '[ninja_forms_field id=84]' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "shortcode, plugin ninja forms"
} |
Show or hide custom fields by user's role [frontend]
Is it possible to hide or show custom fields by user's role.
For example: I have custom field "wholesale_notice" and it have to be visible only for my "wholesale" user role.
Thanks | Yes, it is possible to hide or show custom fields by user's role. Use current_user_can() for finding current user role. This function returns true if current user has capability or role. For example your current user is "wholesale" then you can use like this:
<?php if( current_user_can('wholesale')) { ?>
// stuff here for wholesale
<?php } ?>
For more reference check this: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "custom field"
} |
Is it advisable to use $post->comment_count instead of get_comments_number( $post_id )
I was learning from the WordPress codex about global variables and after
`var_dump($post)` I found out that `$post` has a property called `comment_count`
I was wondering whether I can directly use `$post->comment_count` instead of `get_comments_number( $post_id )` inside the loop? Or does it have any disadvantage? | This is that classic question, do you have 6 eggs or half a dozen, and frankly, it doesn't actually matter.
It is however better to use `get_comments_number()` because
* the post object is retrieved from the `$GLOBALS['post']` global which is set by `the_post()` inside the loop
* the post object is validated through `WP_Post` (through `get_post()`)
* the output from `get_comments_number()` is filterable should you later need to filter the output | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, functions, comments, variables, globals"
} |
Fatal error: Call to undefined function wp_insert_post()
So I have a form that has makes the action jump to another php page.
There my php code tries to upload a post. I get the following error:
> Fatal error: Call to undefined function wp_insert_post()
PHP Code:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "upload_ugc") {
if($_POST["editindication"] == 'newpost'){
$post_array = array(
'post_title' => $_POST["post_title"],
'post_content' => '',
);
$post_id = wp_insert_post( $post_array, true );
} | If you'd like to use WordPress functions inside your naked PHP file, you'll have to load the WordPress environment:
require_once '/path/to/wp-load.php';
That said it's best practice to NOT handle things via separate PHP files like that outside of WordPress, but use a plugin instead and fire your code on an appropriate action. You can use a page template or a shortcode to render your form, and then catch the form input on the `init` or `template_redirect` hook from within a plugin:
add_action( 'init', function() {
if ( empty( $_POST['action'] ) || $_POST['action'] != 'upload_ugc' )
return;
// Your wp_insert_post statement
wp_redirect( home_url( '/upload-success/' ) );
die();
});
Also, when working with user input, don't forget about security, especially for logged in users. In your case you'll need a wp_nonce_field at least, and probably run your post title and content through wp_kses. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "forms, wp insert post"
} |
Getting a users username in get_user_meta
I am getting people's first and last names this way:
$_UFName = get_user_meta($_uid, 'first_name', true);
$_ULName = get_user_meta($_uid, 'last_name', true);
where
$_uid
is the persons id I pulled in a query from the users table.
How do I get their username? this code:
$_UUName = get_user_meta($_uid, 'user_login', true);
that is not working. It is blank.
Is there a way to get it from the user meta?
thx, Richard | The username is not a user meta entry, so you'll probably want to work with a `WP_User` object instead:
$user = get_user_by( 'id', $_uid );
echo $user->user_login; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "user meta"
} |
order posts by `meta_key`, Does not display posts that does not have `meta_key`
I'm using this query orderby `meta_key` for show posts. if one of the posts does not have `vip_row` meta, So not shown; Is it possible that if one of the posts does not have `vip_row` meta to be displayed,But in the last row?
$args = array(
'post_type' => 'my_product',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'my_product_cat',
'field' => 'slug',
'terms' => array($category->slug)
)
),
'meta_key' => 'vip_row',
'orderby' => 'meta_value_num'
);
$query = new WP_Query($args); | You can get all posts by using a `meta_query` that gets posts where the key either does or does not exist, and then order on meta key with a secondary order for posts with same value or no key:
$args = array(
'post_type' => 'my_product'
'tax_query' => array(
array(
'taxonomy' => 'my_product_cat',
'field' => 'slug',
'terms' => array( $category->slug )
)
),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'vip_row',
'compare' => 'NOT EXISTS',
),
array(
'key' => 'vip_row'
'compare' => 'EXISTS',
)
),
'orderby' => array(
'meta_value_num' => 'DESC',
'date' => 'ASC',
)
);
$query = new WP_Query($args); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, wp query, query posts"
} |
How to load different CSS in different Header?
I have two different files for the header in my theme. These are `header.php` and `header-full.php`.
How can I load different CSS in different headers?
I enqueue my CSS files in `function.php` like this:
 ) { // check the template file name
// enqueue header.php style here
}
if('header-full.php' == basename( get_page_template() ) { // check the template file name
// enqueue header-full.php style here
}
`wp_enqueue_style` already registers a style so you don't need to register a style before enqueueing it except in very special cases. See wp_enqueue_style. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development, templates"
} |
contactform7 remove tags with "wpcf7_autop false" from functions.php
i want to remove those `<p>` and `<br/>` tags from my contactform7 forms. now they have this wpcf7_autop which can be set to false when inserting:
define('WPCF7_AUTOP', false);
to wp-config.php
**The problem is:** I need this setting to be attached with my theme, so is it possible to some how do it through the functions.php file? | * You can try minify html from the contact form 7
* To completely disable the wpautop filter, you can use:
remove_filter('the_content', 'wpautop'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "functions, forms, plugin contact form 7"
} |
Edit custom fields in posts list
Is it possible to edit (or add) custom fields directly in posts list (/wp-admin/edit.php)?
I need to do it quickly for many posts (1000s) so editing every and each of them would take ages to accomplish. | Yes, you can use Admin Columns Pro (paid plugin with free version) to use inline edit for custom fields columns just from the WordPress posts list. It even comes with sorting and filtering for columns. You can easily add new columns with this plugin. <
There are also plugins that allows you to bulk edit custom fields from the overview. < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, custom field, quick edit"
} |
Using Jetpack to track an Ajax powered blog
I am setting up my own blog, and I'm having fun making it with Ajax calls to WP API (plus a default php fallback). Everything works properly so far, but what's making me wonder is how to make Jetpack work properly. I know that with Google Analytics I could send a pageview event, do you know if this is possible with Jetpack?
I was thinking of firing something like a Jetpack pageview event using Javascript. Any idea?
Thanks! | I don't think it's documented, but you can probably use `_stq.push`. Here's what I see on one of my sites with WordPress.com Stats:
_stq.push([ 'view', {v:'ext',j:'1:3.8.2',blog:'1234567',post:'123',tz:'3',srv:'example.org'} ]); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -3,
"tags": "plugin jetpack"
} |
Include comments form in plugin page
I want to include the comments form on a page generated by my plugin. I got the post id I want to attach the comments to, but I can't get any of the Wordpress comments functions to work.
Tried to create a Wordpress loop within my plugin page like this, but the comments form won´t show up:
$args = array ('post_type'=> 'cpt', 'p' => $post_id );
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
comment_form();
endwhile; endif;
wp_reset_postdata(); | Just as @Jevuska mentioned, you can use the $post_id as an argument here, in fact, you can also use a ton of optional $args as well `<?php comment_form( $args, $post_id ); ?>`
You can find the information in the Codex here: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, comments, include"
} |
How does $wpdb->get_var work with offset?
In WordPress documentation, it says:
(<
> SELECT a Variable The get_var function returns a single variable from the database. Though only one variable is returned, the entire result of the query is cached for later use. Returns NULL if no result is found.
>
> get_var( 'query', column_offset, row_offset ); ?>
>
> query (string) The query you wish to run. Setting this parameter to null will return the specified variable from the cached results of the previous query. column_offset (integer) The desired column (0 being the first). Defaults to 0. row_offset (integer) The desired row (0 being the first). Defaults to 0.
My query is, can you please explain this line:
> Setting this parameter to null will return the specified variable from the cached results of the previous query.
Which variable? If i code:
<?php $wpdb->get_var( null, column_offset, row_offset ); ?>
Which variables value is it talking about?
Thanks. | You must specify values for column_offset and row_offset. For example:
<?php $wpdb->get_var( null, 5, 0 ); ?>
Will return "Hello World" (see attached image) But for that to work you had to have a previous query like this:
<?php $wpdb->get_var( "SELECT * FROM $wpdb->posts" ); ?>
; ?> | You are following a wrong format to call sub header file.
**Here is how we have to call sub header files:**
<?php get_header('subexample'); ?>
**Here is how you have to name the sub header file:**
`header-subexample.php`
Hope this helps! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "headers"
} |
Filter posts of custom post type by meta key in (List All Section)
How can I filter the posts which are displayed on the admin list all page of a custom post based on the value of the a value.
So far I know how to do the following anywhere on the front end:
$args = array(
'meta_key' => 'magic_key',
'meta_value' => $post_id,
'post_type' => 'question',
'post_status' => 'publish',
);
$posts = get_posts($args);
How do i incorporate this into the List All page of this custom post type? | You can use the action `pre_get_posts` . Just make sure to check `is_post_type_archive('question')` and `is_admin()` to prevent affect queries in the whole website. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, wp query, admin, metabox"
} |
How do I display child post types in the parent post type template
I have a custom post type called `airports` which uses a template called `single-airports.php`.
I have created a new airport called _Gatwick_ and created a child of this called called _Gatwick North Terminal_.
How do I get the permalink of Gatwick's children to display on the Gatwick page (`single-airports.php`).
I would greatly appreciate any help provided! | After some digging I found the answer!
Hopefully this helps some other people!
## EDIT
**Improved Answer!**
<?php
$args = array( 'post_parent' => get_the_ID(), 'post_type' => 'airports', 'posts_per_page' => -1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<h2><?php the_title(); ?></h2>
<a href="<?php the_permalink(); ?>">
<button><?php _e('View', 'text_domain'); ?></button>
</a>
<?php endwhile; wp_reset_postdata(); ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, page template, children"
} |
When should I call add_settings_section and add_settings_field?
All of the examples I've seen for `add_settings_section` & `add_settings_field` have them being called on the `admin_init` action. This means that they're being called when loading every single admin page.
However, my understanding is that they're only used when rendering the options page on which they're displayed. Is there any reason no to put all calls to `add_settings_section` & `add_settings_field` in the callback function given to `add_menu_page`?
I'm wondering because I've got a plugin where the selection of fields to display is determined by a call to an external API. I certainly don't want to have to do this on every admin page load. Even if I cache the result of the API call in a transient that's going to expire every so often. | You can call `add_settings_section` and `add_settings_field` any time before you `do_settings_sections`:
add_action( 'my_plugin_add_settings_sections', function() {
wp_remote_get( ... );
add_settings_section( ... );
add_settings_field( ... );
});
// On the plugin settings page output
do_action( 'my_plugin_add_settings_sections' );
do_settings_sections( ... );
You'll still want to `register_setting()` earlier though because that custom hook won't be fired when your settings are saved, so you want to make sure sanitize callback is in place, probably `admin_init`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "actions, settings api"
} |
Shortcode attribute escaping
I'm trying to set shortcode attribute value to `' "` (single and double quote) by using escaped values `' "`.
Example: `[shortcode attr="' ""]test[/shortcode]`
As soon as I switch to visual editor, they get converted back to `' "` and shortcode is now broken. How does one properly escape shortcode attributes so that they can work even after switching between visual and text editor? | I suggest using `keywords` for them. so you would do something like `[shortcode attr="single_quote double_quote"]test[/shortcode]`. Then, while parsing the shortcode you can change them back. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "wp editor"
} |
Change permalink for default archive - yearly
I want to change the structure of yearly archive URL of default post type `post`.
As we know that default URL structure is like:
Default: `
but want them rewritten, so end up like this:
New: `
I tried following but do seem to work:
function wpa116030_init(){
global $wp_rewrite;
$wp_rewrite->date_structure = 'archive/%year%/';
}
add_action( 'init', 'wpa116030_init' );
But it does not work.
I'd like someone to point to the right direction, need more info do leave a comment.
thanks. | It should work but note that the date structure contains the structure for year, month and day archives as well, so you'll need something like:
add_action( 'init', function() {
global $wp_rewrite;
$wp_rewrite->date_structure = 'archives/%year%/%monthnum%/%day%';
});
Don't forget to visit your permalinks settings page in wp-admin so that rewrite rules are flushed. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, archives"
} |
Front-Page.php and Index.php
So I have a front-page.php that is shown when a visitor visits my site.
I also want to create a blog page using my index.php file but I'm not sure what I need to do?
Do I just create a new page template for my blog page by copying and pasting my index.php code into my newly created page template file?
I haven't touched any of my reading setting either.
Does that make any sense?
Thanks | Not sure if this is the right way, but I used my front-page.php as my front page and then used my index.php as a page template when I created my blog page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "template hierarchy"
} |
Adding a html class based on post count
I'm creating a grid of columns and need to add a css class to each column at the end of the loop based on the amount of posts returned so it returns something like this:
<div class="column-3"</div>
<div class="column-3"</div>
<div class="column-3"</div>
**ANSWER**
Use $loop->found-posts()!
<div class="airport-children">
<?php
$args = array( 'post_parent' => wp_get_post_parent_id( $post_ID ), 'post_type' => 'airports', 'posts_per_page' => -1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?>
<div class="airport-child column-<?php echo $loop->found_posts ?>">
<h2><?php the_title(); ?></h2>
<a href="<?php echo the_permalink(); ?>"><button>View</button></a>
</div>
<?php endwhile; wp_reset_postdata(); ?>
</div> | If I understood this issue correctly the problem with your current code is that you are incrementing $totalPosts variable inside the while loop, so the variable gets incremented after every post thus resulting in the running order you described.
To get the amount of posts returned matching the query, use `$loop->found_posts` (in this case)
More information, examples and documentation about the `WP_Query`can be found from WordPress Codex | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp query, loop"
} |
domain.in/wp-admin give the result to 403 Access to this resource on the server is denied!
I'm new to wordpress. I installed wordpress in my domain. It shows the theme, But When I type `
It's redirecting to 403 page with message `"Access to this resource on the server is denied!"`
If I install the wordpress in ` It allowing me to login in the admin panel and works fine. I don't want to give another `/folder`. I want to install in the root directory only.
can any one suggest me what i have to do.
I tried the `.htaccess` with
DirectoryIndex index.html index.php
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
But no use and i gave `0777` permissions to all the files and the directories.
Please help me out. | What happens when you visit /wp-login.php ? Is the .htaccess itself set with proper permissions? My wp-content, wp-admin, and wp-includes all have `rwxr-xr-x / 0755` and my wp-login.php, .htaccess all are `rw-r--r-- / 0644`
Is this a fresh install? You can also check the server logs and the last resort, but perhaps the easiest, contact your host and have them take a look at root permissions and config. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "htaccess"
} |
Custom Post Type: Upload Multiple Images
So I'm making this Property Listing theme for a client of mine, and on the Properties Custom Post Type (CPT) which I have created I need to add a meta box that allows him to upload multiple pictures - something similar to this:
 | I recommend you these videos --> <
In my opinion I prefer use the plugin ACF. The plugin helps to save time. It's easy to use and the client will be happy. Also, the client won't care if you used a plugin or you wrote the code by yourself, the client will care if the functionality works.
I am the first in not installing plugins but ACF plugin is necessary (mandatory). I use it in all my projects. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, plugin development"
} |
Childs PHP files not overwriting Parent's PHP files
I have a php file located at:
.../wp-content/themes/kallyas-child/pagebuilder/elements/TH_TeamBox/TH_TeamBox.php
I'm trying to use the above file to overwrite the parent's _TH_TeamBox.php_ file which is found here:
.../wp-content/themes/kallyas/pagebuilder/elements/TH_TeamBox/TH_TeamBox.php
My child theme is active and I have created the file path in my child theme to mimic my parent theme. I was under the impression that if I did that I would be able to edit PHP files to my liking in my child theme without losing my changes when I update my parent theme.
I've been developing for a while, but as you can see I'm new(er) to Wordpress. Any insight on why my child's .php file isn't overwriting it's parent's .php file would be greatly appreciated. I'd be glad to give anymore info that you might need to assist me, thanks! : ) | Child themes are allowed to override _templates_ , not simply arbitrary PHP files.
In WordPress, a theme consists of a bunch of PHP files which are used as Templates. You can find a list of those files in the Template Hierarchy.
Those specific template files can be overridden with new ones, but unless the parent theme has some special means for you to override other files, then files simply included by the parent as part of a support structure or as libraries for a pagebuilder piece of code cannot simply be overridden in that manner. | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 12,
"tags": "php, child theme"
} |
Can we add more than one control under a setting in WP theme customizer?
In wordpress theme customizer, we need to define a setting to add a control. My question is can we add more than one control under a setting?
If yes, how to access the values of those controls. In documentation i found that we can read values of settings. `get_theme_mod( 'site_logo' )`, but its not mentioned how to read value of controls.
If we can not add more then one control under one setting, what's the benefit of having settigns?
I believe i have missed something somewhere, that describes how both settings and controls differentiate with each other.
Any help is appreciated! | I would say no, because a setting needs a unique ID, if you have two controls with the same ID, they will set the same `name` attribute to two different inputs in the controls and conflict so only one value will be saved.
Actually do not see much point in having them separated at all, you can't really use one without the other in any meaningful way I can see, but maybe there is a use case for keeping them separate.
Instead if you wanted more control over a single setting you would need to create a custom control class with multiple UI inputs and javascript in it to help calculate a single setting value. But be sure to only use the setting `name` attribute on the actual element where the final value will be. Otherwise, better to just create another setting with it's own control. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "theme development, theme customizer"
} |
Modify the file inside plugin dir - the right way
I need to modify some `*.php` file of some plugin, but I don't want to modify it inside the plugin dir for the obvious reasons(updates etc). Is there any acceptable and known way to do this? Like placing this file in the theme folder or something close to this? | It is not possible to override a file (not technically 100% true, but you don't want to go the way that will make it possible), and in any case, if it was possible the long term effect would be similar to the one you are trying to avoid - when upgrding the plugin, the upgrade might not have any impact, since your file will override it.
Good plugins will provide API or filters and actions which will enable you to change their behavior without risking that an upgrade will nullify them. If not possible, and you just have to have the change, just use a tool like git to track your changes, and at least when a new upgrade will arrive you will have easier life when merging your changes into it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins"
} |
Looking to limit file attachment downloads
I am using WP user front end plugin to let users submit posts to my site that includes a file on that post that other users can download.
The problem is I want user-a to only be able to download a file from that post once forever on the site.
Something along the lines of - if current logged in user - is viewing a post that includes a file he has already downloaded - change download button to - already downloaded!
Hope you can help..
Thanks! | If your attachment is handled via the WP media library, each one has unique ID, just like Posts. When your users download the attachment by clicking the button, store a reference to that attachment ID in a `user_meta` setting and then update the button accordingly.
Another option: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "attachments"
} |
Hide a specific post from Archive Feed
I want to remove a custom post type post from it's archive feed only. But keep in the main feed.
Like is I have 1) main feed: myexample/feed 2) Custom post type Archive Feed: myexample/mytype_archive/feed
And a custom post named "How are you?" I want to show the post to main feed marked as (1) but hide on post type archive feed marked by (2)
This is what I tried till now:
function archive_exclude_post($query) {
if($query->is_feed() && $query->is_archive()){
$query->set('post__not_in', array(40, 9) );
}
return $query;
}
add_filter( 'pre_get_posts', 'archive_exclude_post' );
Not worked for me .Help me to fix the issue please. | I think this may be what you need - customizing feeds Feed templates are in wp-includes. It's pretty straight forward from there to edit a loop to exclude a post or create a new feed template for the custom post type. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, archives, feed"
} |
Where is the php file of single member profile view (BuddyPress)
The edit.php file is for single member edit profile page.
And I'm looking for the page that handle single member profile view. So the I can modify the display of user's profile view.
Is there someone knows where is the .php file that I'm looking for? | Unless you are specifically using the `bp-default` theme, then the file you want is:
buddypress\bp-templates\bp-legacy\buddypress\members\single\profile\profile-loop.php | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, buddypress"
} |
Pagination for search results of custom post type
I'm trying to display numbered pagination for search results of a custom post type. Basically a search form allows users to search a custom post type by 2 different taxonomies and then the results are displayed on a page template. I want to display 10 posts per page.
I've managed to get the pagination to work, but only if I hard code the tag and I can't seem to figure out how to get it to automatically add in the links depending on how many pages of results there are.
Pastebin of page template code - < | You need to set your paged arg in your $args array:
$listing_args = array(
'post_type' => 'business',
'posts_per_page' => 10,
'meta_key' => 'listing_num',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'offset' => ($paged -1) * 10,
'paged' => $paged, // <- tell the query what page we are on.
'tax_query' => ......etc
);
And then use the `pageinate_links` function, < to populate the links to the next/prev pages.
Example from the codex on how to use it with a custom query:
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $the_query->max_num_pages
) ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, wp query, pagination"
} |
How to call thumbnail by aqua resizer in best practice. Specify image dimensions's notify from GTmetrix
I am using Aqua resizer to resize thumbnail on my loop. More flexible than using thumbnail from WordPress. The problem is, image result by Aqua Resizer's has no width and height pixel. The are missing width and/or height attributes. It's decrease the load speed as shown by GTmetrix.
Here my code to call the image on the loop:
<?php $thumb = get_post_thumbnail_id();
$img_url = wp_get_attachment_url( $thumb,'full' );
$image = aq_resize( $img_url, 150, 200, true, true, true );
?>
<img src="<?php if($image) { echo esc_url($image);
} else {
echo catch_that_image();} ?>" alt="<?php echo get_bloginfo('name'); ?>"/>
Would really appreciate your help.
Thank you. | So what's wrong with adding in the attributes as Mark is saying?
<?php $thumb = get_post_thumbnail_id();
$img_url = wp_get_attachment_url( $thumb,'full' );
$image = aq_resize( $img_url, 150, 200, true, true, true );
?>
<img src="<?php if($image) { echo esc_url($image);
} else {
echo catch_that_image();} ?>" width="150" height="200" alt="<?php echo get_bloginfo('name'); ?>"/> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images"
} |
wp_customize - detect post type to show/hide customizer options
How can I tell the customizer to only load certain customizer options based on the post type that is being previewed?
i.e. using:
is_woocommerce
is_shop
is_cart
etc.
When adding customizer option fields, I can check to ensure woocommerce is in the "active_plugins" array so those options are only provided if woocommerce is installed and active, however I need to find a way to only load those fields into the customizer when actually viewing a shop, product, cart, etc. type page.
My only workaround for now is using js/css to show/hide the fields but optimally when navigating among pages in the customizer preview, and since each gets a full refresh anyway, it would be much leaner to dynamically load those options only when necessary based on the post_type being previewed. | Customizer Controls can be displayed based on context. With `active_callback` API introduced in WordPres 4.0, you can control where to show your specific options. Add your customizer options like this with the optional active_callback argument.
$wp_customize->add_control( 'wc_cart_page_option', array(
'label' => esc_html__( 'Cart Page Options' ),
'section' => 'wc_cart',
'active_callback' => 'estore_is_cart',
));
Now create a function called 'estore_is_cart' to check if user is previewing the cart page.
function estore_is_cart(){
if( is_cart() ) {
return true;
} else {
return false;
}
}
Note: You can also directly pass is_cart function check to 'active_callback' argument.
Check contextual controls section in the blog post: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "woocommerce offtopic, theme customizer, post type"
} |
Autosave interval remains default despite wp-config.php defines
On site which I maintain there are writers that spend a lot of time editing single posts, and autosave every minute is very painful for them. So they asked me to set it to at least 10 minutes.
I found an official way to change autosave interval, so I've put this line in wp-config (at the end of it and there is no duplicate of this constant in this file):
define('AUTOSAVE_INTERVAL', 600);
But it didn't help. I checked everything, browser cache, memcache, redis cache and even waited a few days.
But Wordpress still uses default 60 seconds to run autosave script. Any ideas why is this happening or how to overcome this? | You should not put any defines in the end of the `wp_config.php` it is actually explicitly stated in it ;) Every define you add should be above the line saying
> /* That's all, stop editing! Happy blogging. */
Anything after that will have impact only **after** wordpress had finished to process the request | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp config, constants, autosave"
} |
Multiple endpoints in one URL
I am trying to add multiple endpoints in one url like:
<
But this way the query var `lead_id` is equal to `1000/product/123455` and not `1000`.
When I do it the following way everything goes right:
<
So I think that I need to add some rewrite rules, so Wordpress understands that lead_id and product_id are 2 query vars.
**How I add my endpoints:**
function add_lead_management_endpoints() {
add_rewrite_endpoint( 'lead_id', EP_PAGES );
add_rewrite_endpoint( 'product_id', EP_PAGES );
}
add_action( 'init', 'add_lead_management_endpoints' ); | Not sure of the context for this, is it a custom post type or just a page?
This might be something which you're looking for -
function add_lead_management_endpoints() {
add_rewrite_rule(
'manage-lead/lead_id/([0-9]{1,})/product_id/([0-9]{1,})',
'index.php?pagename=manage-lead&lead_id=$matches[1]&product_id=$matches[2]',
'top'
);
add_rewrite_tag( '%lead_id%', '([^&]+)' );
add_rewrite_tag( '%product_id%', '([^&]+)' );
}
add_action( 'init', 'add_lead_management_endpoints' );
You'll need to flush permalinks for this to take affect (visit settings->permalinks). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "wp query, url rewriting, endpoints"
} |
How do I get the labels from a post
I am new to wordpress and in the post admin section there is a place on the right that is clearly called `labels`. I need to be able to access these `labels` and display them on the post when it is rendered.
I did some research and i found this code below, it seems to make sense but does not do what I need it too.
<?php
$post_type = get_post_type_object( get_post_type($post) );
echo $post_type->label;
?>
I created 2 labels called `test` and `test2` and assigned them to the post. When this code executes it echo's `posts`. There is a label property in the `post_type` object but I do not believe that it is the one I am looking for.
` like so:
echo get_the_term_list( get_the_id(), 'labels', '', ', ', '' );
That snippet assumes two things:
1. That it's used in the loop.
2. That "labels" is the correct taxonomy name. You should go to Posts > Labels and look for `taxonomy=___________` in the admin page's URL to figure out the correct taxonomy name for use above.
If you need a list of post terms to work with in PHP, use `get_the_terms()` instead.
p.s. It's worth noting that "Labels" is not a core WordPress taxonomy so it must be registered by a theme, plugin, or other custom piece of code that may provide alternate ways of displaying the labels on the front end. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy"
} |
Create a widget to use shortcode?
I have a plugin (Social Warfare) that I love. But, there's no widget available. What is involved in creating a widget so that I can use the shortcode that seems to work fine on the pages and posts? | You can find more information in the Widgets API | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "widgets, shortcode"
} |
latest posts shortcode with image
I am trying to make a shortcode that will take my latest 5 posts and render them on page. I get all the posts rendered correctly except for the image source, I receive it blank. Is it something I'm doing wrong?
$content = $content?$content:'Latest Posts';
$a = shortcode_atts(
array(
'posts'=>5
),
$atts
);
$args = array('numberposts'=>$a['posts']);
$recent_posts = wp_get_recent_posts( $args, ARRAY_A );
echo '<div class="recent-posts">';
echo '<h1>'.$content.'</h1>';
foreach($recent_posts as $post){
?>
<div class="updated"><p><?php echo $post['post_title']; ?>. <a href="<?php echo get_permalink($post["ID"]); ?>"><img src="<?php the_post_thumbnail_url($post["ID"]); ?>"/>.</a></p></div>
<?php
}
echo '</div>';
} | ### Image fix
You are using the incorrect function to return the image source url. Change
the_post_thumbnail_url( $post["ID"] )
to
get_the_post_thumbnail_url( $post["ID"] )
see <
### To fix the echo
Use a _$return_ variable like so:
$out = '<div class="recent-posts">';
$out .= '<h1>'.$content.'</h1>';
foreach($recent_posts as $post){
$out .= '<div class="updated"><p>' . $post['post_title'] . '.<a href="' . get_permalink($post['ID']) . '">';
$out .= '<img src="' . get_the_post_thumbnail_url( $post['ID'] ) . "'/>.</a></p></div>';
}
$out .= '</div>';
return $out; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
opcache_reset on plugin/theme/core update
wordpress it seem not reset opcache after plug-in/theme/core update.
For solve this issue i have set in the php.ini
opcache.validate_timestamps=1
all work correctly but `validate_timestamps` when it's enabled, PHP will check the file timestamp each request with a performance degradation. When it's disabled, PHP files are NEVER checked for updated code. When wordpress updating code, new code files can get mixed with old ones, the results are unknown. It's unsafe as hell.
Why wordpress not perform an `opcache_reset()` after each update?
alternatively... if I can call `opcache_reset` on action `upgrader_process_complete`, eg.:
if( extension_loaded('Zend OPcache') ){
add_action('upgrader_process_complete', 'opcache_reset', 1000, 0);
}
it is correct? | Several comments
1. just in case, you probably should check that the PHP version is 5.5 and above before calling the function (or check for its existence, not sure if an equivalent function existed in the original APC under the same name)
2. You priority is too high. You actually want to call it after all other plugins have finished whatever they are doing after an upgrade, just in case they do something that impacts any PHP files. Go for a priority of `PHP_INT_MAX -1`.
Your code might actually get triggered too many times if there are several upgrades done in the same time but except for slight performance hit I don't see anything bad that might come out of it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "updates, cache"
} |
The Simple and Correct Way to Add User Meta
I want to give points to users to their activities like writing posts, writing comments, etc.
I thought to use user meta to store points.
I know that I can use add_user_meta...
But the problem is, there are many ways to register a user for my site like normal reg form, buddypress reg form, Admins can add via admin panel and many more.
So it is hard to add add_user_meta to every where.
Is they any way to add a user meta for all current users and future uses with a default value? | Trying to detect when a UI was triggered, is indeed the wrong general approach (unless you want to tie to the UI). A proper one will be to hook on the user_register action.
add_action( 'user_register', 'wpse223196_registration_save', 10, 1 );
function wpse223196_registration_save( $user_id ) {
add_user_meta($user_id, 'score', 5);
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "users, user meta"
} |
What user/group does Wordpress belong to in terms of file permissions?
When I check the file permission on a newly, locally installed Wordpress site (i.e. downloaded from wordpress.org/download) the owner is `ll782` (my username) and the group-owner is `admin`. Wordpress doesn't seem to belong to either of these.
I'm looking at the permissions for the .htaccess file which I want Wordpress to be able to write to.
e.g. `-rw-r--r--@ ll782 admin .htaccess`
If I change the permissions to 774 and Wordpress still can't write to this file. I have to change the group to '_www' before Wordpress can update the file. Should I be setting the owner to `_www` or is there a better way?
Secondly, if I SFTP the file to the server, will it retain the same owner and group? Will it retain the same permissions?
I'm trying to understand what `_www` is and why Wordpress belongs to this user/group on my local server. | I think the real question you have here is — what user/group WordPress belongs to?
WordPress itself essentially doesn't _have_ a user/group. From perspective of filesystem it is just a bunch of PHP source files lying around.
What is really "has" a user here is your web server and/or PHP binary. Together they _execute_ WordPress source files and any file operations are under _their_ authority.
In a nutshell — owner and permissions of files that you want editable need to be configured appropriately _for your specific server_ , which varies depending on the server. Obviously permissions need to be as narrow as possible (777 and such isn't wise that is). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permissions"
} |
Is it possible to set different payment gateway on each Gravity Forms form?
I run a Wordpress site in Australia involving credit card payments. I've been using eWay payment gateway for a while, now I want to introduce Stripe as well to my forms. I have multiple products, each of them has its own form, and I want to be able to control which payment gateway to use for each form.
Example:
1. Product A --> Form A --> use eWay payment gateway
2. Product B --> Form B --> use Stripe
Is this possible? If not, what are my options? Is there a better plugin for this kind of case? Should I modify the internals of the plugin? For the record I am a final year CS major and have an intermediate knowledge of PHP code, so any advanced tricks hopefully would not overwhelm me.
Any help would be appreciated. Thanks! | Absolutely, no code modification needed. Simply create an eWay feed (looks like it's only available in their Pro version) for the form you want to process with eWay, and set a Stripe feed for the form you want to process with Stripe. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -3,
"tags": "plugins, forms, plugin gravity forms"
} |
How to Order By Two Custom Fields?
Note : This is not a duplicate question to If value present, order posts by two consecutive custom fields. After filtering a custom filed, I need to order by another custom filed. (The above link explains filtering by two custom fields. But I need to filter by a custom filed and then order by another custom filed.
This is a my current wp query array.
$args = array(
'post_type' => array('post', 'video'),
'meta_key' => 'pp_like_count',
'orderby' => 'meta_value_num',
);
I have order by custom filed called `pp_like_count`. This works fine.
But I need to display only _if`'pp_lang'` custom filed equals to 'english'_. How to modify this to add it?
(Order by `pp_like_count` also should be there.) | You can try this by using meta query to filter results and then adding orderby to order results. Below arguments should work
$args = array(
'post_type' => array('post', 'video'),
'meta_key' => 'pp_like_count',
'orderby' => 'meta_value_num',
"meta_query" => array(
array(
"key" => "pp_lang",
"value" => "english",
"type" => "CHAR",
"compare" => "="
),
),
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, loop"
} |
MU domain mapping without using a plugin
**Context** :
After using some Domain Mapping plugins and having issues with all of them, I am wondering if I cannot just use a multi site with my own top-level domains in a safe way, without using any plugins for it.
I researched out there and all I find is outdated information that's unclear and doesn't help but unhelp.
**Question** :
Is it alright and safe to:
* set the site_url to whateverdomain.ftw in the db (for each site)
And just be okay with it?
Or is there something else I should consider?
**UPDATE**
How may I fix the fact that the admin area preserves the original url **when using the Domain Mapping plugin** (the one with the sunrise.php)? | To be honest even after your Update:
> How may I fix the fact that the admin area preserves the original url **when using the Domain Mapping plugin** (the one with the sunrise.php)?
I don't quite understand whether you want to " _Redirect administration pages to network's original domain_ " or not.
In any case, as per the installation page:
> 4. "Redirect administration pages to network's original domain (remote login disabled if this redirect is disabled)" - with this checked, if a user visits their dashboard on a mapped domain it will redirect to the dashboard on the non mapped domain. If you don't want this, remote login will be disabled for security reasons.
>
There is also an abundance of even youtube videos that may help. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, domain mapping"
} |
Change user slug in Buddypress
I am creating a site with Buddypress. Everything is going good so far but default member slug for buddypress is `domain.com/members/abc`. I want that it as `domain.com/abc` like facebook and twitter. Any one can help me for that..... | Place the following code in your theme's functions.php file:
add_filter( 'bp_core_enable_root_profiles', '__return_true' );
I hope this helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, buddypress, slug"
} |
Custom post type name and assigning custom taxonomy
I've made mistake creating custom post type. I've put:
register_post_type( 'Post Name', $args );
instead of
register_post_type( 'post_name', $args );
Now I need to assign new custom taxonomy to this post type. Problem stars here:
register_taxonomy( 'custom taxonomy', array( 'Post Name' ), $args );
doesn't work.
I've tried to change custom post type name to one string and then assign taxonomy and it works.
register_taxonomy( 'custom taxonomy', array( 'post_name' ), $args );
Problem is that because of existing content I can't change custom post type name like this. Looking for workaround that let me save my existing content. | I've checked another option and asigned my custom taxonomy to custom post type using its name but without capitals and space.
**'postname'** works with original **'Post Name'**
So for custom post type
register_post_type( 'Post Name', $args );
I can use
register_taxonomy( 'custom taxonomy', array( 'postname' ), $args );
And it works. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, custom field, custom content"
} |
Correct and safe way to include php content in my page
I have a website where I use [[insert_php]]( to insert php content to my page. What I do is simply use php's include inside insert_php to include my complex php script.
I asked a question a while ago, and got highly criticized for doing it this way and using insert_php. What is the right way to do this?
Let me explain what I have: I wrote a php page with my hands from scratch. This php executes some sophisticated commands on my system and extracts data from my server and displays them. What is the right way to include this php script/page in a wordpress page to display data? | 1. Duplicate the post.php in your theme folder.
2. Rename that file as any_name.php
3. Enter the following code at the top of that file.
> < ?php /* Template Name: Any Name */ ?>
4. Add your php codes to that file.
5. Go to admin panel -- > Create a new page -- > Select your template and publish the page | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, security, include"
} |
Way To Store Global Meta Values
When using posts there is a way to store meta values on a per post level. Is there a way to store values on a global site value? I want to save a numeric value that isnt tied to any single post.
I was thinking i could just do something like
get_post_meta( 0, 'somevalue', true );
This will work, but it will still be storing the value as a post field. is there anything specific that was designed for this | Yes there is Option API to store site global data.
You can store some global values using `add_option()` then can retrive values as `get_option()`
**Example:**
add_option( 'option_name', 'option_value', 'deprecated', 'yes' );
//OR
update_option('option_name', 'option_value', 'yes');
//Get the value
$your_data = get_option('option_name', 'option_default_value');
echo $your_data; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom field"
} |
WooCommerce Custom Product to checkout
I was trying to create a custom shop page for a project where users can click on a product to view the details in a modal window and select some options on price variations.
What I want to do is to send the product details to checkout page upon chosen by the user.
Is it possible to do ? If so , how ?
Your help is appreciated. Thanks ! | You need first to buy _WooCommerce Quick View_ plugin, because _woocommerce lightbox_ plugin doesn't work without it.
Please read this: Woocommerce single product show in modal…?
And if you go to the wordpress page of **woocommerce lightbox** plugin, you will see that is a complementary plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, php, woocommerce offtopic"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.