INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
why in my wordpress admin panel the membership option is not showing
In my wordpress admin panel general settings membership check box is not showing please check the screenshot and kindly help me to resolve it Thanks.
During this sequence of actions, WordPress's normal behavior is to call an action hook (`do_action('wp_login', ...)`) and a filter hook (`apply_filters('login_redirect', ...)`).
If they're invoked at points in time which correspond to when they would have been invoked in Core, is it safe (and acceptable practice) to invoke these built-in hooks directly from my plugin? Or is the risk too great that other developers who have hooked into this expect the action to be executed at a very specific time? | I think there is a difference here between `do_action` and `apply_filters`.
`do_action` usually triggers a global state change, either output, enqueuing of resource, initialization of modules, and such. This, like anything which infuance global state can result in surprising side effect when used out of context.
`apply_filters` OTOH behaves much more like a function call, and if written properly should return the same result whenever it is "called".
Still, the quality of plugins varies (just few hours ago someone asked about a "pro" plugin that uses `eval` :( ), so your implementation strategy will depend in the end on the coding skills some 5$/hr developer copy pasting snippets he finds around the internet. You will need proper testing against leading plugins to make sure that your code works with at least the leading ones. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin development"
} |
Latest Sticky Posts with Grid Thumbnails for static front page
i want to make very simple thumbnails grid 4 or 5 images only to show the latest sticky posts with " shortcode to be easy add anywhere "
Thanks! | I found it.
<div class="trending-right">
<?php
$sticky = get_option( 'sticky_posts' ); // Get all sticky posts
rsort( $sticky ); // Sort the stickies, latest first
$sticky = array_slice( $sticky, 0, 6 ); // Number of stickies to show
query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) ); // The query
if (have_posts() ) { while ( have_posts() ) : the_post(); ?>
<div class="trend-post">
<div class="thumb"><?php the_post_thumbnail(array(100,100)); ?></div>
<div class="title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></div>
</div>
<?php endwhile;?>
<?php } else { echo ""; }
wp_reset_query();
?>
</div>
I used this code inside header.php | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sticky post"
} |
the menu of the network does not display my second website
I have a problem that is not referenced anywhere. In the toolbar, the menu of the network does not display my second website, while it is active and appears in the list of the sites in the network. I checked the wp-config and .htaccess files and I did not error. I followed step by step the stages of the codex. | Resolved : the second website created must be managed by the same administrator or more exactly super-admin. For that I must do that : Network Admin > Sites > Click Edit on a specific site > Users tab > Add Existing User -> and choose "id" of admin. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, admin menu, network admin"
} |
How to limit the number of Related Posts?
In my theme's file single.php, there is this part of code to get Related Videos:
<?php
if ( $wp_query ->have_posts() ) {
while (have_posts()) : the_post();
get_template_part( 'preview', get_post_format() );
endwhile;
}
wp_reset_postdata();
?>
But this get the entire loop of all posts on the website. I'm wondering, is there a way to limit this and display for example 10 posts? Thanks a lot. | You need the argument **post_per_page** to limit the posts.
Before your loop it should be something like this.
$args = array (
'post_type' => 'custom_post',
'posts_per_page' => '10',
);
$wp_query = new WP_Query( $args );
// your loop
if ( $wp_query ->have_posts() ) {
while (have_posts()) : the_post();
get_template_part( 'preview', get_post_format() );
endwhile;
}
wp_reset_postdata();
If it is the custom post, make sure to replace **custom_post** | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "get template part"
} |
Displaying logged in user name
I'm trying to show the User's Name in a login button at the top of our page. I tried to base it off of this advice, but it's just showing the PHP code. Specifically, I'd like "My Account" to change to "Welcome {UserName}. How do I display logged-in username IF logged-in?
<?php global $current_user; wp_get_current_user(); ?>
<?php if (!is_user_logged_in()) :?>
<a href="/member-login/" class="login">Member Login</a>
<?php else : ?>
<a href="/account-page/" class="login">My Account</a>
<?php endif; ?>
<a href="/membership/join-sccap-renew-membership/" class="join">Join</a> | The answer in your link is correct. If it's just showing PHP code then your code isn't between PHP tags `<?php` & `?>`.
<?php if (!is_user_logged_in()) :?>
<a href="/member-login/" class="login">Member Login</a>
<?php else : ?>
<a href="/account-page/" class="login">Welcome <?php echo $current_user->display_name; ?></a>
<?php endif; ?>
<a href="/membership/join-sccap-renew-membership/" class="join">Join</a> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
How to log out everywhere else, destroy all sessions "all other devices"?
WordPress panel service "log out everywhere else" is doing a nice job. I want to use this as a function outside the panel.
**Screenshoot**
`.
It's not really abstracted in such a way that you can re-use it outside of AJAX, but if you copy the source into your own function, minus the JSON parts, then you could perform the same action yourself.
The key part is this bit, which will destroy all sessions for a given user ID:
$sessions = WP_Session_Tokens::get_instance( $user_id );
$sessions->destroy_all();
The rest of the function is just checking the user exists, checking permissions, and sending a JSON response. They might not be relevant for your use case, so the above might suffice. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "php, functions, session, logout"
} |
Save the_content into custom field
Is it possible to save the content (inside the WP WYSIWYG (`the_content`)) into a custom field?
**This is what I have so far:**
add_action('edit_post', 'save_content_to_field');
function save_content_to_field($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
$content = get_the_content($post_ID);
add_post_meta($post_ID, 'desc', $content, true);
}
} | OK!
I found this way and this might be useful to someone:
add_action('edit_post', 'save_content_to_field');
function save_content_to_field($post_ID) {
global $wpdb;
if(!wp_is_post_revision($post_ID)) {
//$content = get_the_content($post_ID);
global $post;
$content = apply_filters('the_content', $post->post_content);
add_post_meta($post_ID, 'desc', $content, true);
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom field, the content"
} |
Woocommerce email template customization
I have the latest version(3.3.4) of woocommerce and I'm trying to customise the email templates that come with it. Tried following this tutorial, but the version I am using doesn't seem to contain the option to modify the HTML code from the template.
So my question is, how can the email templates be customized in the latest versions of woocommerce? | There is an option in the WooCommerce settings that shows you how to override and edit the email templates: `WooCommerce -> Settings -> Emails`
From there, simply click on the email name or the cog/settings icon  licensed libraries in your GPL plugin. WordPress plugin guidelines states,
> Although any GPL-compatible license is acceptable, using the same license as WordPress — “GPLv2 or later” — is strongly recommended. All code, data, and images — anything stored in the plugin directory hosted on WordPress.org — must comply with the GPL or a GPL-Compatible license. Included third-party libraries, code, images, or otherwise, must be compatible.
Here is a list of licenses compatible with GPL. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "plugins, licensing"
} |
In my Website homepage I want to remove date which is written along author name
Kindly tell me how should I remove the date written alongside all posts in Homepage. | Little dirty but fast solution is to hide it via css. add this code to custom css
.home .td-big-grid-post .td-post-date {
display: none;
}
Better approach would be to find a template file or function responsible for this section and remove or change it... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "date"
} |
Unknown file php5fcgi.core
Does anyone know what a php5fcgi.core file is? I've installed WordFence on a site that I've recently become an admin for and am getting warnings for two instances of this file:
* Unknown file in WordPress core: wp-admin/php5fcgi.core
* Unknown file in WordPress core: wp-includes/js/tinymce/php5fcgi.core | *.core files are usually generated by the linux OS when an un handled exception crashes an application, and it include (hopefully) useful deugging information that can help you analyze the cause. From the name of the file it was probably generated from a php5fcgi.
But.... those files for sure should not be in your wordpress directory, so first go ahead and remove them from there. You should try to inspect one of them and make sure it is total gibrish and nothing that seems like any software code. Assuming it is not malicious, you should keep monitoring for their appearance, and if they do appear again, you should definitely look how to prevent them from appearing in the wordpress directories as they might include sensitive information. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "warnings"
} |
how to get post meta where value is an array of key value pairs
I am trying to get the post meta with meta query where value is an array of key value pairs.
$user_id = '123';
$arr = array();
$arr['a'] => "somevalaaa" ;
$arr['user_id'] => $user_id ;
$arr['c'] => "somevalyyy" ;
Adding post meta
add_post_meta($review_post_id, 'key_of_post_meta', $arr );
Getting post meta (having user id same as $user_id) with meta query, where I am wrong ?
$args = array(
'post_type' => 'as_reviews',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'key_of_post_meta',
'value' => array('user_id'=>$user_id),
'compare' => 'IN',
),
),
);
$query = new WP_Query($args); | The meta_query cannot be used to search value which are stored as serialized arrays. You can use it to search multiple values (meta-fields can have several values using the same key).
You need a different approach to solve your problem, this is what I suggest,
store your meta field with the user id as part of the key name,
add_post_meta($review_post_id, 'key_of_post_meta_'.$user_id, $arr );
next, retrieve your posts with,
$args = array(
'post_type' => 'as_reviews',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_key' => 'key_of_post_meta_'.$user_id
);
$query = new WP_Query($args); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "meta query"
} |
Redirect to page list when page published
I have a role that allows users to self publish pages but does not allow them to delete or edit after. Currently, when a page is published it returns the restricted 'Cheating' message as the user cannot view the page in edit view.
Please can someone tell me how it is possible for the publish action to redirect the user back to the page list rather than the edit view?
Many thanks | I have the below code which works as expected if anyone else is looking for similar.
add_action( 'publish_page', 'redirect_user_page_list', 10, 3 );
function redirect_user_page_list() {
if( is_user_logged_in() ) {
$user = wp_get_current_user();
$role = ( array ) $user->roles;
if ( 'role_slug' == $role[0] ) {
$url = 'url to redirect to';
wp_redirect($url);
exit;
}
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "pages, publish"
} |
Help Adding filter to Add Media button for custom post type
I'm trying to add a filter to the add media button for a custom post type. I'm using add_filter('media_send_to_editor') and it work's fine, but I'm having difficulty finding a way to determine the post type of the admin page so that I can only perform the filter on that specific post type. Any ideas on how I can get the post post type?
I'm trying to filter the output of the image and caption, but I only want to do it on a specific post type. I would need the other post types to function as normally when adding images. I need the the image to be wrapped in a shortcode and the caption to be included in a parameter for that shortcode. I have it working. I just need a way to make it conditional for post types. | to test the post type where the image is included, try that :
add_filter("media_send_to_editor", function ($html, $attachment_id, $attachment) {
$image = get_post($attachment_id);
$post = get_post($image->post_parent);
if ("CUSTOM_POST_TYPE_CODE" === $post->post_type) {
}
return $html;
}, 10, 3); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, filters, admin, media, dashboard"
} |
Add more fields on media attachments uploaded in the dashboard
Is it possible to extend, or add more field when using WordPress browser uploader ?
`var_dump($_POST)` return 3 field, I wish to add more :
array (size=3)
'action' => string 'upload-attachment' (length=17)
'name' => string 'file.jpg' (length=8)
'_wpnonce' => string 'abcde12345' (length=10) | Looks like, you can add additional values using `plupload_default_params` filter hook.
Example usage
add_filter( 'plupload_default_params', function( $params ) : array {
$params['some'] = 'some';
return $params;
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads"
} |
WordPress permalink setup in Hindi
I'm trying to set WordPress permalink in sitename/post name in Hindi language but it's gives me `%e0%a4%b2%e0%a5%8b%e0%a4%b0%e0%a4%ae-%e0%a4%87%e0%a4%aa%e0%a5%8d%e0%a4%b8%e0%a4%ae-%e0%a4%95%e0%a5%8d%e0%a4%af%e0%a4%be-%e0%a4%b9%e0%a5%88/`
This kind of permalink . | as the comments indicate the url is actually a correct hindi unicode, and your browser should show it if you have the right fonts installed on your computer.
 { ?>
<style type="text/css">
#login h1 a, .login h1 a {
background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/site-login-logo.png);
height:65px;
width:320px;
background-size: 320px 65px;
background-repeat: no-repeat;
padding-bottom: 30px;
}
</style>
<?php }
add_action( 'login_enqueue_scripts', 'my_login_logo' );
You can also add your other custom CSS in the code above to change the background colour or image by targeting the `<body>` HTML tag in your CSS | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp admin"
} |
if statement for search results
My search results show pages from both WordPress & woo-commerce. I want to show some specific product information in the search results that only products have. Normal WordPress pages do not have this meta information and the search page fails if there are WordPress pages in the results.
So I want to show different search information if the result refers to a wordpress page, or if the result is a woo-commerce page. I thought it would be as simple as using `is_woocommerce()` or `is_product()` on my `searchloop.php` but these codes refer to the search page itself, not the search results. Hence only `is_search()` will result in a positive result.
Is there a way to use conditional statements that apply to the search results? | Within the loop the best way to check if the result is a product would be to check the value of `get_post_type()`:
if ( get_post_type() === 'product' ) {
}
As you say, `is_woocommerce()`, `is_product()` and `is_search()` are for checking which type of page is being viewed regardless of the current item in the loop. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "woocommerce offtopic, search"
} |
Is there a function to cause empty categories not to show in menus?
Scenario: Clients can add or remove posts at will, but may not be comfortable (or even bother) adding categories to a menu.
Problem: This can cause empty categories to be displayed in menus.
Question: Is there a core function or resource that can be called from functions.php that will cause empty categories not to show on the front side even if they are showing as added in the dashboard.
Previous research: I have searched in both Google and this StackExchange for an answer. I may not be finding it by using the wrong search terms. | add_filter( 'wp_get_nav_menu_items', 'nav_remove_empty_category_menu_item', 10, 3 );
function nav_remove_empty_category_menu_item ( $items, $menu, $args ) {
global $wpdb;
$nopost = $wpdb->get_col( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE count = 0" );
foreach ( $items as $key => $item ) {
if ( ( 'taxonomy' == $item->type ) && ( in_array( $item->object_id, $nopost ) ) ) {
unset( $items[$key] );
}
}
return $items;
}
Please use the above code, it will unset the category which has No post. Assuming that you were are managing Menu from Apperance->Menu.
Hope that helps :) | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "categories, menus"
} |
How to get around iframes with WordPress?
I'm working in WordPres 4.9.5. I have some projects that involve data from a third party application called Wrike. The easiest way for me to display the data is through an iframe. I'm placing the following iframe onto one of my pages...
<iframe src=" width="6500" height="675" frameborder="0" allowfullscreen="allowfullscreen"></iframe>
I prefer not to deal with iframes at all. If there is alternative way I can call that data into a WordPress page, can someone provide any pointers? | That would be more of a question for the makers of Wrike, not WordPress, since it depends on whether or not Wrike has APIs or some other way to access their data. A quick glance at their site reveals they do have an API - developers.wrike.com - you would create code that pulls the data from their API, then outputs whatever HTML you want it to, and you could then either place your code in a plugin (if you want this functionality even if you change themes) or within your custom theme (if you include a lot of styling/formatting in your code and it's tied to the theme). | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "iframe"
} |
Wordpress roles - Protect administrator role
We want to provide owners of their site, administrator role, but we don't want them to delete user 1. We also don't want a cheap solution which stops their admin account from being able to delete users in general, they need full user permissions to add/edit/delete users, just not the user 1 account or a role above them.
In Drupal there is a module called: "Protect user 1" which allows creation of multiple admin accounts, but none of them can edit/delete user 1. Does the WP ecosystem have anything like this? | 1. Install User Role Editor Plugin
2. Create a Role for them assign everything except removing admin. | stackexchange-wordpress | {
"answer_score": -2,
"question_score": 2,
"tags": "plugins, user roles, permissions, members"
} |
How to add add blank non-editable wp page like default blog for use with plugin
Wordpress has a default, for the most-part, non-editable place holder page for your blog. How can I recreate a similar page to this for use with my plugin?
When accessing the page defined as blog page within wp you can edit basic info including the permalink but not the content. The content is blanked out with the warning "You are currently editing the page that shows your latest posts."
I can see the line in the posts table for the blog page but nothing out of the ordinary there. I am aware of the blog.php specific script but struggling to find dev info on replicating such a function
TIA | You can do it by hooking admin_init action:
1. First, you can create a option to select the page you create for your plugin. I suppose that the option will be save in `wp_options` table with name `your_plugin_special_page`.
2. Remove editor support on that page with this action.
add_action( 'admin_init', 'your_plugin_hide_editor' );
function your_plugin_hide_editor() {
// Get the Post ID
if ( isset( $_GET[ 'post' ] ) ) {
$post_id = $_GET[ 'post' ];
} elseif ( isset( $_POST[ 'post_ID' ] ) ) {
$post_id = $_POST[ 'post_ID' ];
}
if ( !isset( $post_id ) ) {
return;
}
// Remove editor support
if ( get_option('your_plugin_speical_page') == $page_id ) {
remove_post_type_support( 'page', 'editor' );
}
}
3. Then you can use admin notices to display your message to user (<
Hope this help! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, permalinks, blog page"
} |
Additionally added URL params leading to "Invalid post type." in the Admin Panel
I've a bug that I cannot reproduce on my local/staging evn and occurs only on prod(having the same code, db and files). Here is what I get when visiting all of the default post types/taxonomies or custom created by me or plugins(it's not bugged on settings pages for ex):
When visiting `/wp-admin/edit.php?post_type=page` the page loads as it should, immediately after it load the URL changes to
/wp-admin/edit.php?post_type=page%3Fpost_type%3Dpage
therefore any further action in this window will lead to Invalid post type. Updating the core and all of the plugins, or removing all of them didn't fixes the issue. Couldn't find anything related in the debug.log. Only when I disable my browser JS it's working fine, but I don't load any custom script to the wp admin.
I'll really appreciate if someone can give a hint, thanks in advance. | Posting the solution I've found for my problem.
It appears that we have mod_security on our prod env, and recommended clause is to replace "server info" and on what the site is hosted on(for security reasons).
In my case it was replaced with IIS 6, and that tricked the WordPress installation as well, which on it's end is doing additional URL optimizations... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "wp admin"
} |
GIF featured image is resized on server but not used in frontend. Why?
I use a very basic setup of twentyseventeen and die most recent wp version. When I upload PNGs or JPGs they as a featured image, they are saved as a resized version on my uploads folder and used on the homepage and archive pages as a resized versions for the responsive images.
GIF files are also saved in the uploads folder but are not used as responsive image. Only the original size is referenced and loaded in HTML. The pixel dimension of my GIF is1920x890px:
<
Is there any reason for this behaviour? Why arn't the image sizes used if they exists as resized gif files generated by wordpress? I have no plugins installed. The gifs are not animated gifs. | It seems to be a feature and not a bug: screen sizes are not added to scrset if you upload a gif as teaser image: < This applies **only to teaser images** and not images in the article.
I used 8-Bit PNG instead and now all scrset attributes are filled. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "responsive, images"
} |
How can get comment link by comment id?
How can get the comment link by using comment id?
I trying to search on google but I can't find anything useful. | You can use the `get_comment_link()`.
Here's an example from the `wp-cli` shell:
$ wp shell
wp> echo get_comment_link( 4 );
| stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "comments"
} |
Insert stylesheet into WordPress header?
I just want to add one extra line (a third-party font stylesheet) to the header of my blog. I have a child theme set up, but at the moment it only has a custom stylesheet, `style.css`.
Very simply, how can I do this?
All the answers I can find seem to suggest that I create multiple long and complicated files that replicate a lot of parent theme code. Surely there must be a simple way?
If I create a new `header.php` with just one line (the extra stylesheet), as per this answer, that file overwrites all of `<head>`.
If I add a simple `functions.php` file like this answer suggests, it just inserts raw code into the page.
Is there any way I can just insert one line into the header without having to replicate all the header PHP code? Surely it can't be this hard. | You simply enqueue your stylesheet using the get_stylesheet_uri()
function my_scripts() {
// enqueue style
wp_enqueue_style('name-of-my-script', '
}
add_action('wp_enqueue_scripts', 'my_scripts'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "headers, css"
} |
Meta Query with spaces in value?
Im using meta query to filter a post loop...
'meta_query' => array(
array(
'key' => 'some_key',
'value' => 'some value here', #single word values work
'compare' => 'IN'
)
the loop works if the value is one word, but if it has spaces it doesn't, how can I get this working?
Thank you! | Try to pass your multi value in array, example
'meta_query' => array(
array(
'key' => 'some_key',
'value' => array(
"value1 with space",
"value2",
"value3",
),
'compare' => 'IN'
) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "loop, meta query"
} |
WooCommerce shop page orderby
Recently I found that, WooCommerce was removed the `Display` option from WooCommerce admin settings. So that, my shop page all products currently showing in ascending order. But, I want to show them in descending order. This means that I want to keep the new products above always. Now I am using the WooCommerce with version of 3.3.5 and the theme name is storefront.
TIA | WooCommerce have moved this setting to the WordPress Customizer. From your WordPress admin area, browse to: `Appearance -> Customise`
Then, from within the customiser, you can find the setting here: `WooCommerce -> Product Catalogue` and simply change the order under the option 'Default Product Sorting' | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, wp query, woocommerce offtopic"
} |
WC displaying products from category
I'm currently working on shop page and custom product loop. With **WP_Query** I can succesfully display products based on meta_key and meta_val but i run into trouble. Now i have to display all products from category and as argument i need to pass category_id. This is my code:
$args = array(
'post_type' => 'product',
'posts_per_page' =>12,
// get category by slug is working -
'product_cat' => 'products-from-cat-40',
);
I know that woocommerce have slightly different query arguments than wordpress so i've tried so far:
* product_cat_id
* product_cat
* product_category
* product_category_id
* cat
* cat_id
* category_id
As ID i passed both integer and string but still nothing works. I've searched trough internet for list of viable Woocommerce WP_Query arguments and i couldn't find it. Can anyone help? I'll much appreciate. | For custom taxonomies, including Product Categories, you should use the `tax_query` argument:
$args = array(
'post_type' => 'product',
'posts_per_page' => 12,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => 40,
),
),
); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp query, woocommerce offtopic"
} |
How to remove woocommerce_breadcrumb() from do_action( 'woocommerce_before_main_content' );
I want to remove woocommerce_breadcrumb from `do_action( 'woocommerce_before_main_content' )` in WordPress. How can I do that? | The action is added at L47 of wc-template-hooks.php. So just remove action at the same priority.
Add this to your child theme functions.php file or as a separate plugin.
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20 ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "php, theme development, woocommerce offtopic, hooks"
} |
My Own layout in WooCommerce pages
I have static template made from PSD to HTML. Now I am implementing it in WordPress. It's not fully E-Commerce site. So I need to create single product page category page and shop page individually. I have already designed them in Bootstrap. Now I am having problem creating custom layout as my static site in HTML. is there any way so we can get product data in object and display in our theme by creating custom page template? or any other better option? Hooks and filters are so confusing for me. | Sounds like you're trying to theme a site. If you're using WooCommerce you can find their docs here.
Hooks and filters can be very confusing, but the more you use them and break stuff the more you'll grow comfortable with them. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, functions, theme development, woocommerce offtopic"
} |
Uppercase to Lowercase in URL
i have a function that creates a modRewrite rule
function markets_rewrite_url() {
add_rewrite_rule( '(.+?)/symbol/(.+?)/exchange/(.*)', 'index.php?&pagename=$matches[1]&symbol=$matches[2]&exchange=$matches[3]', 'top' );
add_rewrite_tag( '%symbol%', '([\-\w+]*)' );
add_rewrite_tag( '%exchange%', '([\-\w+]*)' );
}
this works fine but to rewrite the rule but i will want =$matches[2] and =$matches[3] in lower case if it appears in uppercase
thanks | This is NOT mod_rewrite rule, it's WordPress rewrite rule and it proposes to parse variables from URL to wp_query (most of the time).
You can apply your logic during `parse_query` filter hook., something like this.
add_filter( 'parse_query', function( WP_Query $wp_query ) : WP_Query {
foreach ( [ 'symbol', 'exchange' ] as $key ) {
if ( '' !== $wp_query->get( $key ) ) {
$wp_query->set( $key, strtolower( $wp_query->get( $key ) ) );
}
}
return $wp_query;
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "rewrite rules"
} |
BuddyPress - Message's Send To auto-fill functionality not working
The "Compose" page has a field labeled "Send To" that seems to attempt a call to get names, but nothing happens. I checked for JavaScript errors and there were none. I have "Friend Connections" disabled, but I also tried with it enabled and the profiles being friends. I don't know how to further troubleshoot the issue. | The auto-fill functionality does not seem to work if Friend Connections is disabled. I found a plugin that has an option to make auto-fill work for all members.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "buddypress"
} |
Custom template for sub-sub-categories
I'm trying to add a custom template for all posts in a sub-sub-category. I mean like
Category --> SubCategory Level 1 --> Subcategory Level 2 --> post
I'm using the following code:
<?php
$post = $wp_query->post;
if (cat_is_ancestor_of( 42, $cat ) ) {
include(TEMPLATEPATH.'/services_template.php');
} else {
include(TEMPLATEPATH.'/single-default.php');
}
?>
However, it only shows a blank page, both in the sub-sub-cat post as well as all teh other posts. I double checked and the templates are there, so I guess there's something wrong with my code, but can't figure what
edit: I have several CPT single pages named `single-{CPT-slug}.php` . Is it possible this is affecting things? | Instead of include(), use get_template_part()
<
`<?php $post = $wp_query->post; if (cat_is_ancestor_of( 42, $cat ) ) { get_template_part( 'services', 'template' ) } else { get_template_part( 'single', 'default' ); } ?>`
If you create those files and use get_template_part(), then within those files you can set them up to display posts however you see fit. Take a look at the Underscores theme on github, the archive.php file has a good example of using get_template_part() within the loop -
<
Here is a link as well to one of the template_parts for Underscores to see how they set it up within that file -
<
Tom Mcfarlin explains this extremely well here -
<
Response to your edits: Your single-{CPT-slug}.php templates should not cause any issues with this. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, templates"
} |
WordPress REST API - JSON "Rendered" Content Incorrect
i'm working in android application that use wordpress rest api to get blog from website to , i don't have any knowledge about php or wordpress , but i take some time to learn about it , any way my problem is on the json .the content contain paragraphs unknown and i don't know how to solve this problem ,please help ; | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "content, rest api, json, post content"
} |
Create page that is not deletable
How can I mark a page as "no deletable" in the wordpress database? I've already seen this solution, but it requires a plugin. Is there really no way beyond a plugin? | You can make use of the filters supplied via the delete/trash functions of WordPress API: `wp_trash_post` and `wp_delete_post`:
function prevent_post_trash_delete($bool, $post){
$posts_to_keep = [30];
if ( isset( $post->ID ) && in_array($post->ID, $posts_to_keep) ) {
return false;
}
return $bool;
}
add_filter('pre_delete_post', 'prevent_post_trash_delete', 10, 2);
add_filter('pre_trash_post', 'prevent_post_trash_delete', 10, 2);
You can pass an array of IDs (so be it post, page, or any other post type) through the `$posts_to_keep` variable.
That way they will throw a notice when a user tries to delete them via the dashboard. You can't prevent plugins using direct SQL queries from deleting these pages. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "pages"
} |
Get root folder without domain
Sometimes when developing my theme my WordPress website will be on a obscure domain such as `
Is there a WordPress API function (or maybe just a PHP function) to get the root folder without the domain? So I am looking for a function that will give me `/project/foo/bar` without the ` part. | PHP stores this info in `$_SERVER['REQUEST_URI']`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "urls"
} |
From admin edit user page query either the user_nicename or username field value of the user profile being edited or viewed
I want to query the Username field when im in the edit user page and profile page
` function.
Pass it the users ID
$user = get_userdata($user_id);
Then the have access to the username or user_login as its called
echo $user->user_login;
You can read more about this function here: <
Or if you need to get the user by other information, see `get_user_by()` < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, custom field, profiles"
} |
What the user_status column?
I was look in the `wp_users` table a `" user_status "` column... **( all contain zero )**
What works is this data?
. In my functions.php file I am trying to use pre_get_posts to change the order of my custom post type archive using a custom field.
function apply_projects_query_filter ($query)
{
if (is_admin()) {
return $query;
}
if (is_archive() && $query->query_vars['post_type'] == 'projects' && $query->is_main_query()) {
$query->set('orderby', 'meta_value');
$query->set('meta_key', 'project_status');
$query->set('order', 'DESC');
}
return $query;
}
add_action('pre_get_posts', 'apply_projects_query_filter');
My project_status custom field has the possible values of 0 or 1. Using the code above returns no results at all. What am I doing wrong? | Not sure exactly why, but by adding another filter using the meta_query it all started working. I now only get posts in my custom post type archive that do not have the project_update field set and are ordered by project_status. This is what I was after.
$meta_query = array(
array(
'key'=>'project_update',
'value'=>'1',
'compare'=>'!=',
)
);
$query->set('meta_query', $meta_query); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom field, pre get posts"
} |
Strange video appears in background on Safari only
I hope someone can help me. My site popplekharlamova.com
has this issue in Safari. Not in Chrome or elsewhere, it's taking an age to load and I deleted the video media file ages ago but it's still showing and looks corrupt..
It should be just white background. I recently had a Wordpress update, it happened after this.
I am no developer, but can build a site with a them, any advice would be greatly appreciated.
Any way of getting rid of the video would be great.
Thank you , Jamie | There is only one video file on your page: < It is being loaded on all browsers.
It's hidden in this CSS-block as a `background-image`:
<style id="thb-app-inline-css" type="text/css">
.page-id-282 #wrapper div[role="main"] {background-color: !important;background-image:url( !important;background-repeat: !important;background-attachment: !important;background-position: !important;background-size: !important;}.footer {background-color:#d60000 !important;background-image:url(
</style>
Delete it from there and you will be fine if you don't have the knowledge to remove it from the code, then you could delete it from the folder, which will solve your problem. However, every browser will then try to load an inexisting file, which isn't really good but won't make any greater harm. Put it on your to-do-list and ask once some developer to delete it for you from the code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -3,
"tags": "videos"
} |
Shortcode with product catgory counter
I would like to create a custom shortcode that count individually product-categories in Woocomerce but I haven't found any code on net. I need somethink like:
**[counter product-category="example"]**
Anyone can help me? I've no idea about php :(
<?php
$product_categories = get_terms( 'product_cat', $args );
$count = count($product_categories);
?> | Try this: (add it to the theme's main _functions.php_ file)
add_shortcode( 'products-counter', 'products_counter' );
function products_counter( $atts ) {
$atts = shortcode_atts( [
'category' => '',
], $atts );
$taxonomy = 'product_cat';
if ( is_numeric( $atts['category'] ) ) {
$cat = get_term( $atts['category'], $taxonomy );
} else {
$cat = get_term_by( 'slug', $atts['category'], $taxonomy );
}
if ( $cat && ! is_wp_error( $cat ) ) {
return $cat->count;
}
return '';
}
You can use it like this:
* By specifying the product category **ID** :
`[products-counter category="19"]`
* By specifying the product category **slug** :
`[products-counter category="hoodies"]`
Example:
; | Use the `meta_key`, `meta_value`, and `fields` parameters.
Example using `get_posts()`: (Take note though, `get_posts()` ignores or doesn't include _sticky posts_.)
$meta_key = 'hide_rss';
$meta_value = 'yes';
$post_ids = get_posts( [
'meta_key' => $meta_key,
'meta_value' => $meta_value,
'fields' => 'ids',
] );
Or using `new WP_Query()`:
$meta_key = 'hide_rss';
$meta_value = 'yes';
$q = new WP_Query();
$post_ids = $q->query( [
'meta_key' => $meta_key,
'meta_value' => $meta_value,
'fields' => 'ids',
] );
See < for other possibilities, or advanced meta query. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "array"
} |
How to set default values in Woocommerce checkout?
I cannot seem to set the default field for the country field for Woocommerce at checkout.
I am using this code from here, placing it into my functions.php of the child theme.
add_filter( 'woocommerce_checkout_fields' , 'default_values_checkout_fields' );
function default_values_checkout_fields( $fields ) {
// You can use this for postcode, address, company, first name, last name and such.
$fields['billing']['billing_country']['default'] = 'GB';
$fields['shipping']['shipping_country']['default'] = 'GB';
return $fields;
}
I have tried "UK" and "United Kingdom (UK)" as values as well. | Try this code to change the default billing country on the checkout page.
add_filter( 'default_checkout_billing_country', 'change_default_checkout_country' );
function change_default_checkout_country() {
return 'US'; // country code
}
> To change default shipping country on the checkout page
function change_set_checkout_field_input_value_default($fields) {
$fields['shipping']['shipping_country']['default'] = 'Australia';
return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'change_set_checkout_field_input_value_default' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
Permalink and ACF field
I'm trying to get the thumbnail and title from permalink outside the main loop using ACF field:
<?php
$post_id = get_field('1_main_post');
if( $post_id ): ?>
<a href="<?php echo get_the_permalink($post_id); ?>">
<div class="top_post">
<div class="top_post_img">
<?php the_post_thumbnail( 'post_cover' ); ?>
<h2><?php the_title(); ?></h2>
</div>
</div>
</a>
<?php endif; ?>
?>
but I receive post_thumbnail and title from current page, not the selected page. Can someone look? | You'll need to use some different functions for obtaining the post thumbnail and title from outside of the loop:
`get_the_title( $post_id )` \- <
and
`get_the_post_thumbnail( $post_id, 'post_cover' )` \- <
**Note** : These functions only return the title and post thumbnail so will need to be echoed out. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "title"
} |
redirect any category in URL to the ID and post-name only - hundreds of pages affected
I have many articles linked from external sites without categories. They end up with a 404 not found. A minor migration was done a long time ago and just noticed the 404s.
One of many examples:
incorrect: wrestleview.com/20060-update-on-joey-mercury-and-his-wwe-status
Correct: wrestleview.com/wwe-news/20060-update-on-joey-mercury-and-his-wwe-status
I want when people click on a link with no category to automatically redirect to the ID and post name. Since there is always a unique ID to each post. Can this be done through htaccess or functions.php? I cannot do a 301 redirect manually, I have over 1000 links affected by this.
Thanks | I'd suggest you to forget about htaccess in this case.
In your functions.php file add:
add_action( 'template_redirect', 'check_missing_urls' );
function check_missing_urls() {
if ( ! is_404() ) {
return;
}
$has_match = preg_match( '/\/?(\d+)/', $_SERVER['REQUEST_URI'], $match );
if ( ! $has_match ) {
return;
}
$new_url = get_permalink( $match[1] );
if ( ! $new_url ) {
return;
}
wp_redirect( $new_url, 301 );
wp_die();
}
Please note that this is an untested code, use it as a very basic and rough idea to accomplish what you need.
Also, i'd suggest you to use 302 instead of 301, during the test period. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, redirect"
} |
How to add wordpress username after url?
maybe u can help to solve this problem. for example i have this link
and i want to add username after login, like `
I want to make it on button.
<a href="
<button>Click me</button>
</a>
I want to put this on post / page. | You can do
<?php
if( get_current_user_id() ): // check if user is loggedin
$current_user = wp_get_current_user(); //get user
?>
<a href=" echo $current_user->user_login;?>
<button>Click me</button>
</a>
<?php endif;?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "users, urls"
} |
How to use add_submenu_page() for editors?
Currently I load a custom WooCommerce sub menu point in an own plugin like:
// Add an additional submenupoint
add_action('admin_menu', 'register_mycustom_menupoint');
function register_mycustom_menupoint() {
add_submenu_page( 'woocommerce', 'Name on Menubutton', 'Name on Menubutton', 'manage_options', 'custom-submenu-page', 'dsrv_init_backend' );
}
function call_this_function_name(){
// ...
}
But this is only available for WP users at administration level. After searching the internet I tried to use `edit.php?post_type=shop_order` instead of `woocommerce` but then the menu point disappears. What do I have to change to fix it?
Woocommerce: **2.6.4** , Wordpress: **4.6.11** | You should use `edit_posts` capability instead of `manage_options`. `manage_options` is an administrator level capability. Try the following code -
add_submenu_page( 'woocommerce', 'Name on Menubutton', 'Name on Menubutton', 'edit_posts', 'custom-submenu-page', 'dsrv_init_backend' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, woocommerce offtopic, admin menu, add submenu page"
} |
One to many custom post relationships
I have a custom post type to serve as an event calendar and would like to be able to introduce multiple child sessions to each event post with a date and start and finish time accordingly. So let's say
Event title blah blah -> Session One Title - 10/05/2018 - 10:00-12:00 -> Session Two Title - 10/05/2018 - 14:00-18:00
I am using the ACF custom fields plugin which actually provides a relationship field type but it does not seem to provide the functionality of being able to add the child type on the parent type edit form but just to select from existing ones.
Any alternatives to that?
thanks a lot! | There many ways to solve this kind or problem, and without more details about what it is you are trying to achieve, it is difficult to give you a precise answer. Keep in mind also that ACF is made to ease the creation and usage of custom posts/fields and not really a tool to build relationships between data constructs. You really ought to code your own data constructs in order to have full control over their relationships.
Here is a general approach that you can use,
1. create a custom post type called `calender_event` for example.
2. create another custom post type called `event_session`.
3. create a meta-field for the first post type called `calendar_event_sessions`.
4. Each time you create a a new post `event_session` assign it to an existing `calender_event` and store its post ID as an array into the field `calendar_event_sessions`. This also means that when a post is deleted you need to remove it from any `calender_event`. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "custom post types, custom field"
} |
How to filter search results by post type?
I am able to filter tags archives by adding a parameter like ?post_type=slug to the url and this works fine except for search results. I mean where the url contains a search term like:
site.com/?s=searched&post_type=slug
How can i make the "&post_type=slug" also work in this case?
EDIT: It wasn't working on my end due to custom function.php code. | By all rights it should work, here's the same thing applied to my own site:
tomjn.com/?s=talk&post_type=tomjn_talks vs tomjn.com/?s=talk . Something else is the problem
Specifically, if you replace the main query with a `query_posts` call or a `WP_Query`, that query won't take into account parameters passed via the URL unless explicitly passed through manually.
Instead, use the `pre_get_posts` filter to modify the main query, rather than creating a new query to replace it.This ensures any additional queries passed via the URL will also work, and reduces time spent querying the database significantly for a nice performance boost.
Additionally, if you already use `pre_get_posts`, setting the `post_type` will override the URL parameter, so you need to check for its existence | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom post types, search"
} |
WP REST API only returning partial list of users
Started working with the WP REST API for the first time. Our ultimate goal is to dynamically load UI elements based on which user is presently logged in. However, my attempts to pull a list of all users is hitting a wall - I'm only able to return two users out of five when running the base http request:
`
I tried including other params like `search` but that will only work if the user I'm searching for is one of the two in the response I'm already getting; it doesn't return any data for the other three users whatsoever. Looking at the user profiles, there aren't any unique data points or roles that set the two users being returned apart from the other three. The two being returned are both administrators, but so is one of the three that is missing.
What on Earth am I missing?? | After much reading I found the reason why all users are not returned with the straight-forward HTTP request for WP REST API:
This is a **non-authenticated** request, therefore only publicly available users data is released in a GET request.
*** _It's important to mention that if some data you need is unavailable, you probably need to add those fields to responses, using`register_api_fields` (see docs for example usage), to your user endpoints as well._
The best resource I found, which gave me this answer, was part of the detailed and easy-to-read guide on the WP REST API from Torque (see pages 35-38). Someone needs to buy that man many, many beers for writing such a great guide!! | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 7,
"tags": "api, rest api, json, wp api, plugin json api"
} |
How do I perform a "get" call to an external API, and then display the JSON results on a page in my WordPress site?
A client has an external API that is storing all member info.
My tasks are:
a.) Create a 'Member Profile Search' page on his site, where users can search for members using certain keywords.
b.) When the submit button on the search page is clicked, perform a "get" call to the external API, that will return JSON objects, and then display the results in a page on the site - possibly, the same page as the search page
My questions:
1.) Is there a plugin that I can use to achieve this?
2.) If there's no solution using an available plugin, how can I accomplish this?
I'm a web developer and have customized a few WP sites, but nothing requiring this level of expertise, so your help would be **greatly** appreciated.
Thanks! | Ended up developing a plugin using AJAX to make the calls to the API | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "customization, api, json, membership, plugin json api"
} |
WooCommerce Stripe Plugin not showing up in settings
This is probably a simple thing but I have tried installing the WooCommerce Stripe Gateway plugin but it's not showing up in my WooCommerce settings under checkout.
My Installed plugins -
, then (on loading that page) verify the parameter as being valid (and not being used before). On successful upload, the code would diasble (inactivate) that guid so it couldn't be used again.
You will have to figure out how to use transaction processing on PayPal (or whatever payment provider) so that your 'thanks for the order' page would generate the stored guid/parameter.
Good luck! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "woocommerce offtopic"
} |
How can I list only custom shortcodes?
Wanting to list specific shortcodes I've added, rather than all shortcodes, can the code at How to list all active and specific shortcodes in wordpress can be adapted to show only shortcodes which contain a specific word? (The custom shortcodes I want to access each contain the same specific word.)
And, if so, how...
I've searched extensively on this, and haven't found anything (nor know enough to decide if it's possible). | The linked question shows you how to get all the shortcode tags in an array. So narrowing them down to specific ones is purely a PHP question. But the answer's simple enough.
Use `array_filter()` on the array of tags with a callback function that uses `strpos()` to see if each tag contains the work you're looking for. Since the shortcode tag is the _key_ in the array, use `ARRAY_FILTER_USE_KEY` to use the actual shortcode tag for the comparison in the callback function:
global $shortcode_tags;
$shortcodes = array_filter(
$shortcode_tags,
function( $shortcode_tag ) {
return strpos( $shortcode_tag, 'woocommerce' ) !== false;
},
ARRAY_FILTER_USE_KEY
);
In that example `$shortcodes` will now be all the shortcodes from `global $shortcode_tags;` that contain the word "woocommerce". | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode"
} |
How to check if a comment has replies?
I want a function to check if the comment id has children (replies) or not. | Here's one example how to construct such a custom function:
/**
* Check if a comment has children.
*
* @param int $comment_id Comment ID
* @return bool Has comment children.
*/
function has_comment_children_wpse( $comment_id ) {
return get_comments( [ 'parent' => $comment_id, 'count' => true ] ) > 0;
}
using the `get_comments()` function with the `count` attribute (to return the number of comments) and the `parent` attribute to find the children. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 0,
"tags": "comments"
} |
Fatal error when activating my custom wordpress plugin
When i try and activate my custom plugin i get the error shown below but this makes no sense to me as it seems ok code wise.
Fatal error: Class 'Functionality\AlterTable\AlterTableComments' not found in C:\wamp64\www\wp-content\plugins\functionality\example.php on line 130
incase your wondering this is on line 130:
new AlterTableComments; | What I conclude form your comments is `pethouseuk-functionality.php`
include 'AlterTableComments.php';
use PethouseukFunctionality\AlterTable;
$a = 'PethouseukFunctionality\AlterTable\test';
$a(); // function call
$b = 'PethouseukFunctionality\AlterTable\AlterTableComments';
$c = new $b; // new object
$c->yourfunction('test'); // Method call
Another file AlterTableComments.php
<?php
namespace PethouseukFunctionality\AlterTable;
interface AlterTableInterface{
function yourfunction($param);
}
class AlterTableComments implements AlterTableInterface{
function yourfunction($param){
var_dump($param);
}
}
function test(){
echo 'this is test ';
}
**Result:** this is test string(4) "test" | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Detect change to user_meta and retrieve old and new values
I want to track when a certain piece of user meta is changed in the admin, and then perform an action. I thought I found the correct hook for it (from < but when I use this code:
add_action( 'profile_update', 'my_profile_update', 10, 2 );
function my_profile_update( $user_id, $old_user_data ) {
error_log(print_r($old_user_data,true));
}
My error log does not show the user meta that I am changing, only values from the main wp_users table and a bunch of capabilities. How can I grab the previously changed user_meta value (or detect a changed user_meta value) when a profile is saved in the admin? | I figured out the answer. I needed to use the `insert_user_meta` filter, not an action hook. And then I ALSO needed a combo of `get_user_meta` (to get the old data) and `$_POST` to get the value being changed to. Putting it all together, here is my final code to find when a particular `user_meta` field (in my case created with ACF) changes from one value to another:
add_filter( 'insert_user_meta', function( $meta, $user, $update ) {
if( true !== $update ) return $meta; // if not an update (b/c it is a create) do nothing
if(is_admin()) { // check if we are in admin not front end
$old_meta = get_user_meta( $user->ID );
if( $old_meta['verified_member'][0] !== $_POST['acf']['field_5ad4eecd7564b'] ) {
error_log("verified_member was modified from " . $old_meta['verified_member'][0] . " to " . $_POST['acf']['field_5ad4eecd7564b']);
}}
return $meta;
}, 10, 3 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "hooks, user meta"
} |
Tips and suggestions for WP intranet extranet set up
I have my main WP site on my .com but I'm looking to have a separate WordPress installation for an intranet/extranet — essentially a library to keep internal information. I just plan on writing notes in Posts or along those lines.
Is it better to set it up on a subdomain vs subfolder? Does it matter? Should the main domain be a multisite and have the intranet a site off of that?
What are some options for hiding the site to the public (as much as possible) and for those that have direct experience with this, do you have any tips?
I suppose I can make use of a membership plugin, which is the likely route I'll take, but are there any additional methods to add privacy for information protection?
Thank you! | Roughly, I'd set up a new WP instance, installing it on an internal server that is not visible to the 'outside', and protected from outside use via firewalls.
If the info is just for you, you can use htaccess rules to deny access to all but your own IP address. You'd probably want to restrict access to your local subnet as further protection. You could even password-protect (via htaccess) the root folder of the WP instance.
Then, strong passwords (and a user name that is not 'admin') with no other users allowed (if just for yourself).
If you need access from the 'outside' (as from home to the WP instance at work), you should set up secure VPN access, with perhaps access only allowed to your home IP. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "privacy"
} |
How can i restore only Blogs from a SQL backup file?
I have taken backup of full DB from PHPmyAdmin. All other files have been restored successfully. But few blogs didn't come. Now I want to restore only Blogs. Please tell me how?? | "Blogs" or `posts` as they are called in WordPress are stored in the `wp_posts` table of your database. And custom fields related to your `posts` are stored in `wp_postmeta` table. So you should just be able to restore those two tables to get all your "Blogs".
This assumes your database is prefixed with `wp_` of course. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, blog"
} |
Where to store reusable content that is not a page
I want to store content like an address block or opening times, that will be displayed at different locations across the site. The website owner should be able to edit this content. What's the best way of storing these snippets of content? I could use a page for it, or create a custom post type, but that doesn't feel right. | You can use the Settings API to create a settings page where the admin can enter the address, opening times or whatever is needed. The same can be accomplished by using the Customizer. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, content"
} |
Can this code be concatenated?
I realise this is perhaps more of a php question, but it relates to WP use.
Can the example below, be modified (and if so, how?) to fully concatenate the 2 echos rather than having them separate?
if... {
echo '<p>', get_template_part( 'templates/xxx' );
echo '</p>';
} | this is more a PHP question
you can try these folowing forms :
if (...) {
echo '<p>';
get_template_part('templates/xxx');
echo '</p>';
}
or
if (...) {
?>
<p>
<?php get_template_part('templates/xxx'); ?>
</p>
<?php
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "conditional tags"
} |
Inheritance of parent theme plugin files in a child theme
I have parent theme that has some plugins in it, those plugins are added as a dependency.
In the child theme, I want to override some of the files that belong to those plugins, but it looks like that isn't working.
Is this possible at all? | > I have parent theme that has some plugins in it, those plugins are added as a dependency.
You shouldn't be bundling plugins in themes
> In the child theme, I want to override some of the files that belong to those plugins, but it looks like that isn't working.
Child themes let you override templates, these are not templates, and use `require`/`include` to load.
> Is this possible at all?
**No**
Modifying plugins involves either forking them or extending them via actions and filters. As a result, replacing a plugin file in the way you propose is bad practice. Doing it via a child theme is even worse, but luckily that is not possible.
Use actions/hooks/filters instead | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, child theme, template hierarchy"
} |
page-slug goes to not found
I have uploaded a file called page-testtest.php to my template folder. Aren't I supposed to get to this file when I go to **example.com/testtest**
It seems very strange to me because the documentation clearly states that I should go to that file without any struggle. Instead I get "Oops! That page can’t be found."
By the way the permalink is set as: < and I use Underscores template
Before somebody bravely refer me to the documentation this is from <
page-{slug}.php — If no custom template has been assigned, WordPress looks for and uses a specialized template that contains the page’s slug. | A template is not a page you can load directly. A template is used for the formatting ('building') of a 'page' (created via Page, Add) or 'post' (created via Post, Add).
On that page/post editing page, there is a place to specify the template that the WP will use when the page is output. There are default templates used (see Template Hierarchy) for posts/pages.
But you can't call (load into your browser) a template file directly. The template file is sort of 'output instructions' that WP uses to build the actual page (or post). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "page template"
} |
WordPress Reserved Terms, any workaround?
I noticed that "embed" is part of "reserved terms" so it automatically change my slug in embed-2. There is any solution to force it to "embed"? | No, the list of reserved terms is there for a reason: to make sure WordPress core features relying on URL's work correctly, and to prevent conflicts with content or plugins. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "slug"
} |
How to detect if some page template has been selected
I'm wondering if, in the static front page, is possible to detect if the some page template has been selected for my page. I'm building a template and I'd like to have a static front page, but I'd like to load a particular page-template just in the case my client selected it in the page Attributes, otherwise will be load the standard page structure.
Is it possible?
Thank you for any help or clue! | sure it is possible. Just check the page meta field (assuming you're in the loop):
$template = get_post_meta( get_the_ID(), '_wp_page_template', true ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, page template, homepage, frontpage"
} |
Easy Image Gallery - Retrieve Serialized Data
I am using Easy Image Gallery. It is called: `_easy_image_gallery` and looks like it's an array like 1234,5432,2345,.....
Now, Easy Image Gallery update to 1.3 is saving into a meta called: `_easy_image_gallery_v2` and the content is something like this:
[0] => a:1:{i:0;a:2:{s:4:"DATA";a:5:{i:0;s:5:"62255";i:1;s:5:"62259";i:2;s:5:"62261";i:3;s:5:"62263";i:4;s:5:"62265";}s:9:"SHORTCODE";s:3:"569";}}
My question is: How can I "decode" this gibberish from v2 into a nice array just like before? | What you're seeing is Serialized Data. WordPress does this automagically when trying to save an array or object to the database. The `get_post_meta()` function will unserialize the data if you pass the right parameters:
$array = get_post_meta(
$post->ID, // The post ID you want metadata from
'_key_name', // The meta key name
true // Whether to attempt to unserialize or return the raw value.
);
PHP has a built in function to deal with this too such as `unserialize()`. WordPress also has it's own function called `maybe_unserialize()` which will attempt to unserialize the given string. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "gallery, post meta"
} |
Combine all posts into one places
I have post type: All items, i need in this All items display posts from post type: Archive and Recent, how i can in post type All items - get posts form 2 post types | You will need to setup a new query to get posts from another post_type. The post_type parameter will accept an array, so you can just do:
$other_posts = new WP_Query([
'post_type' => [ 'archive', 'recent' ], // or what ever your post_types are.
]);
// Then do your loop...
Check this documentation for more information. < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
How to have permalink like domain.com/%category%/%postname%/
As the title says, I want to have a permalink structure like
domain.com/%category%/%postname%/
When I save this structure, no change is do. Someone can help me please ? | Go to `Settings -> Permalinks`. Select `Custom Structure` and enter `/%category%/%postname%/` in edit field. Save. That's all. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks"
} |
The changes I make to an external JS file of my WP plugin are only applied after I clear my browser's cache
I'm making a WordPress plugin which loads an external JS file for some Google Maps related operations. But the problem is that the changes I make to this external JS file are not applied immediately and shown on the Google Chrome browser, but instead I have to delete the "Images and other data" cache of Chrome in order for the changes I make to the JS file to be applied.
For example I have an `alert("DynamicMap.js file was loaded succesfully.);` in the first line of the file but the changes I make to the text only apply after I clear the cache. Does anyone know why does this happen and if I can prevent it? Thanks in advance. (Note that I'm testing plugin online on my personal website, not on the localhost.) | Use function `filemtime($path)`, where `$path` is a path to your script, in `wp_enqueue_script` call, as fourth parameter (version). Every time you modify the script, the cache will be bypassed.
### Update
Calls to `wp_register_script` and `wp_enqueue_script`:
wp_register_script('DynamicMapScript', plugins_url('DynamicMap.js', __FILE__), array('jquery'), filemtime(dirname(__FILE__) . '/DynamicMap.js'));
wp_enqueue_script('DynamicMapScript'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, javascript"
} |
How to remove a link of date archive
I want to remove the link from the date, this link leads to archiving. I'd be happy to get help - thank you very much
 there. In this function you will get code as like
return sprintf(
/* translators: %s: post date */
__( '<span class="screen-reader-text">Posted on</span> %s', 'twentyseventeen' ),
'<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
);
Remove 'a' tag and it will become as like
return sprintf(
/* translators: %s: post date */
__( '<span class="screen-reader-text">Posted on</span> %s', 'twentyseventeen' ),
$time_string
);
In your theme may be similar code with some other function name, search and do same. Hope it will help you.
Thanks | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "links, date"
} |
Copy usermeta value where ID matches in the same table
I would like to copy the meta_value from row to another (in the same table) where the user_id matches.
Each user in the `wp_usermeta` table has a `meta_key`/`meta_value` pair for `first_name` and a `meta_key`/`meta_value` pair for `shipping_first_name`. I would like to copy the `shipping_first_name` value to the `first_name` value where the `user_id` matches. I would like to update all users in the database at once (e.g., via phpMyAdmin).
How should this MySQL query be written? | use this code, it may help you
$users = get_users($args);
if($users) {
foreach($users as $user) {
$user_id = $user->ID;
$shipping_first_name = get_user_meta($user_id, 'shipping_first_name', true);
if($shipping_first_name) {
update_user_meta( $user_id, 'first_name', $shipping_first_name);
}
}
}
for $args - refer link < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, user meta"
} |
Not sure what to do next to optimize
I've got a reasonably large site that I've been developing for some time in a test directory. I have a database about 160 MB, about 100 pages, and over 1000 posts. There are few comments at this time.
I've run an image optimization plugin (imagify), I've deleted old revisions and used WP Cleaup optimizer to delete transients, orphaned data, etc. I've optimized the database both via cpanel and via wp-optimize.
The load speed is still insanely slow - 7 to 12 seconds and no one else is even accessing my site yet. P3 profiler crashes my site :)
I've read a lot of articles on optimization but I'm not sure where to go next. Any ideas? Thank you! I'm mostly just designing it and am not too savvy on back end technology :)
I did read somewhere that the wp-postmeta can become bloated with useless stuff if you import posts from blogger which I did some time ago, but I don't know enough to explore that. Any help is appreciated! Thank you! | It might be useful to analyze where the bottleneck is in rendering pages. Use the Developer mode of your browser (usually via F12) and then use the Network tab to see the load times of the various parts of the page.
Maybe the problem is in images, or 'off-site' Javascript code, or any other off-site item that is included in pages. Maybe it is an inefficient template, or perhaps a plugin causing the problem. Looking at page load times will help.
There are also plugins that will show you all kinds of info about database query times. One is described here: < .
Looking at page load times might give you a direction to start concentrating on. If it is a database problem, a query analysis plugin might help. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database"
} |
Getting page / post URL on publish and / or update
I am trying to use a simple `publish_post / publish_page` hook to get the URL of the post/page when it is either published or updated so I can later turn it into a static page.
Is it possible to add this hook outside of the theme functions.php file, because this is far more preferable to me? I also am unsure how to grab the file location / URL from the result? Any help is very much appreciated. | A simple solution for you - this hook will send you a full URL to the post that is being published. Don't forget to update `[email protected]`
function post_published_notification( $ID, $post ) {
$permalink = get_permalink( $ID ); // GETTING THE PERMALINK
$to[] = '[email protected]'; // UPDATE THIS
$title = $post->post_title;
$subject = sprintf( 'Published: %s', $title );
$message = sprintf( 'View: %s', $permalink );
wp_mail( $to, $subject, $message, [] );
}
add_action( 'publish_post', 'post_published_notification', 10, 2 );
If you want it to work on post update as well, just add this action to the bottom of it:
add_action( 'save_post', 'post_published_notification', 10, 2 );
You can add this hooks to the bottom of your functions.php or in your plugin. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, posts, functions, pages, hooks"
} |
WordPress refuses to read the .htaccess file and gives a 404 for sub-pages
I have a DigitalOcean server with Apache2 installed, which runs virtual hosts.
I have set up the site in a sub-folder `var/www/html/[site-name]`. The URL being something like `192.168.1.8/[site-name]/`.
All was working well until I created a virtual hosts `.conf` file and pointed a domain to the server.
The home page loads, but non of the subpages. If reset the permalinks to default, they load fine like `192.168.1.8?p=123`.
Normally the problem would either be `AllowOverride All` not set, `a2enmod rewrite` not on, or the `.htaccess` file is not there or doesn't have the correct permissions.
I've never seen this problem before! Do you know what may be up? | Even though the `000-default.conf` file had...
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory /var/www/html/>
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
I had to place...
<Directory /var/www/html/>
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Into the `apache2.conf`
And use the `sudo service apache2 restart` command. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "404 error, apache"
} |
Set SQL_BIG_SELECTS and MAX_JOIN_SIZE on a WP_Query
Despite using;
$mysqli = new mysqli("localhost", "user", "pass", "db");
$mysqli->query('SET SQL_BIG_SELECTS = 1');
$mysqli->query('SET MAX_JOIN_SIZE = 999');
$the_query = new WP_Query( $args );
I'm receiving;
> [23-Apr-2018 14:37:31 UTC] WordPress database error The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay for query... WP_Query->__construct, WP_Query->query, WP_Query->get_posts
The original query works, but stopped once I added another meta query that exceeded the cap despite that additional meta query working when I comment out another.
How can I get the $mysqli query settings to apply to $the_query? | According to WP_Query hit max joins... How else can I build a search function that uses custom fields? you should use
$wpdb->query('SET OPTION SQL_BIG_SELECTS = 1');
which makes sense as you set it for the current connection. You create a separate connection through `new mysqli` and WordPress has another on `$wpdb`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, query"
} |
How to make WordPress orderby work with post_excerpt column?
I can use WordPress in-built orderby to sort playlist by any column except `post_excerpt`
echo wp_playlist_shortcode( array(
'ids' => '7,8,9',
'order' => 'DESC',
'orderby' => 'post_excerpt',
));
WordPress Codex apparently states _'post_excerpt' is not a valid parameter for the 'orderby' parameter_ , and nobody nowhere knows how to make `orderby` work with `post_excerpt`. How to bypass this limitation? | I edited the `wp_playlist_shortcode` function at `\wp-includes\media.php` WP core file, by adding
if ($atts['orderby']=='excerpt' || $atts['orderby']=='post_excerpt') {
function cmp($a, $b) {
return strcmp($a["caption"], $b["caption"])*(-1);
}
usort($tracks, "cmp");
}
before `$data['tracks'] = $tracks;` line.
Basically after all tracks are generated into the `$tracks` array and before this array is passed to the final array `$data`, I intercepted the code and checked if `orderby` parameter is set to `excerpt` or `post_excerpt`. If true did a `usort` to sort array descendingly by using `caption` as criteria. In playlist context, WordPress refers to `excerpt` as `caption`. If you need to be sorted ascendingly remove the `*(-1)` within the `cmp` function.
Thanks to the @Pat-J for suggesting `usort`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "order, excerpt, playlist"
} |
Escape post image attachments added to template
What is the secure way to use wp_get_attachment_image() in a template? | Running the output through escaping function should be just fine. You can either use `wp_kses_post()`, which by default allows the same html attributes that you would use in the post content (see in code reference):
echo wp_kses_post( wp_get_attachment_image( $image_id ) );
or if you want to be more precise and strict, you can pass an array with allowed attributes for that particular context, like so:
echo wp_kses( wp_get_attachment_image( $image_id ), [
'img' => [
'src' => true,
'srcset' => true,
'sizes' => true,
'class' => true,
'id' => true,
'width' => true,
'height' => true,
'alt' => true,
'loading' => true,
'decoding' => true,
],
] );
It's up to you to decide what is allowed, just change the array contents to adjust to your needs! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "php, images, escaping"
} |
New folder and file permissions are not correct
I have read through a bunch of sites, but I could only find the right permission to set to existing files and folders, but I could not find anything related to the new files and folders to be created.
Whenever I create a new file or folder they will be created with permissions `660` and `770`, so some of the contents are not accessible. For exaple if I install a plugin, it will be installed with `770` and `660` permissions, so I get a `403` error through the javascript console for all assets of the plugin.
Is there a way/plugin, to adjust persmissions to the files and folders to be created in the future, not just the existing ones?
> Please note: I don't have SSH access (or any access, but FTP) to the hosting server. | Adding these two lines to the `wp-config.php` file solved the problem:
define('FS_CHMOD_FILE', 0644);
define('FS_CHMOD_DIR', 0755); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "user roles, permissions, ftp, user access"
} |
Plugin error "array_key_exists(): The first argument should be either a string or an integer"
Checking the Query Monitor, it's throwing out this error,
> array_key_exists(): The first argument should be either a string or an integer
which relates to this function:
public function lsx_team_scporder_get_terms_orderby( $orderby, $args ) {
if ( is_admin() )
return $orderby;
$tags = $this->get_lsx_team_scporder_options_tags();
if ( ! isset( $args['taxonomy'] ) )
return $orderby;
$taxonomy = $args['taxonomy'];
if ( is_array( $taxonomy ) && count( $taxonomy ) == 1 )
$taxonomy = $taxonomy[0];
if ( ! array_key_exists($taxonomy, $tags ) )
return $orderby;
$orderby = 't.lsx_team_term_order';
return $orderby;
}
Why is it throwing out that error? | From the php manual the `array_key_exists()` function takes as first argument _"any value possible for an array index."_ , again looking up for arrays in the docs we can get that _"The key can either be an integer or a string. The value can be of any type."_ , which also corresponds to the error you see from the Query Monitor.
Meaning that the `$taxonomy` variable that is passing to the `array_key_exists()` is not either a string or integer.
You can debug the `$taxonomy` variable, by making a `var_dump($taxonomy);`.
Hope, that helps. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, array"
} |
Hosting my WordPress site out of a subdirectory
I'm currently hosting several WordPress sites on one host account with cPanel, each site with its own domain. Right now, each of my domains maps to a subdirectory on the server, except for the primary domain, which by default maps to the public_html directory directly.
Because of this, in my public_html folder, I have my primary domain's WP files mixed in with the add-on domain root folders, thus becoming a little confusing. I'd like to put my primary site's WP files into its own folder and host from that folder.
With add-on domains, I know I can select the folder to which they refer to, but I'm not familiar with how to change where the primary domain directs as its root directory.
Or is there a better way to resolve this? | Wordpress have a Codex entry just for you: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "directory, hosting"
} |
How to add a class directly on a unordered list element that is a primary navigation
I'm working in Wordpress 4.9.5 For any WP navigation menu I create, what would be the best approach for adding a custom class name directly on the `<ul>` element? I need it on this element and prefer not to do javascript injections to add the class name to it. | I think this will solve your problem.
wp_nav_menu( array(
'theme_location' => 'top-menu',
'container' => false,
'items_wrap' => '<ul class="nav your_custom_class">%3$s</ul>',
)); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus, navigation"
} |
How do I change database charset when using `wpdb`
I have a separate connection to connect to another DB with this code of line:
$wpdb = new wpdb(STATYBA_USER, STATYBA_PASS, STATYBA_DB, STATYBA_HOST);
and it has another DB charset (`latin1` instead of `utf8`), so how can I change the charset without changing `DB_CHARSET` constant in `wp_config.php`? | You can try the wpdb `set_charset` method (more info here).
example use:
$statyba_wpdb = new wpdb(STATYBA_USER, STATYBA_PASS, STATYBA_DB, STATYBA_HOST);
$statyba_wpdb->set_charset($statyba_wpdb->dbh, 'utf8');
Hope that helps. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "wp query, encoding"
} |
div show on home page only not in paged
im using this piece of code to show my div only on homepage.
<?php if ( is_front_page() ) :?>
but it's shown on pagination 2, 3 and so on. is there any help regarding to fixing this issue? | Thank you guys for quick response. Here is the code that worked for me.
<?php if( is_home() != '' && !is_paged()) { ?>
div here
<?php } ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "homepage, paged"
} |
Changing the argument of a function
This is part of a function in Woocommerce:
function woocommerce_breadcrumb( $args = array() ) {
$args = wp_parse_args( $args, apply_filters( 'woocommerce_breadcrumb_defaults', array(
'delimiter' => ' / ',
'wrap_before' => '<nav class="woocommerce-breadcrumb">',
'wrap_after' => '</nav>',
'before' => '',
'after' => '',
'home' => _x( 'Home', 'breadcrumb', 'woocommerce' ),
) ) );
//blah blah blah
}
I am wondering how I can change the "wrap_before" in my child-theme without touching the function itself. First I though it must be with apply_filter but it didn't look right.
I am certain that this question has been asked many times but I couldn't find the relevant keywords for that. | Try: (add to _functions.php_ of your theme)
add_filter( 'woocommerce_breadcrumb_defaults', 'wpse_woocommerce_breadcrumb_defaults' );
function wpse_woocommerce_breadcrumb_defaults( $args ) {
$args['wrap_before'] = '<nav class="woocommerce-breadcrumb my-class">';
$args['wrap_after'] = '</nav>';
return $args;
}
Or, copy:
_wp-content/plugins/woocommerce/templates/global/breadcrumb.php_
to
~~_wp-content/ **themes/your-theme** /templates/global/breadcrumb.php_~~
**UPDATE:** This is the correct path and not above: ( _thanks @mmm_ )
_wp-content/ **themes/your-theme/woocommerce** /global/breadcrumb.php_
and change the `echo $wrap_before;` and `echo $wrap_after;` to your liking..
Reference: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, child theme"
} |
Wordpress Images Not Showing When FTP
Could someone explain or show me a link to learn why when you ftp an image to `uploads/sites/<blog_id>/` folder it does not show in the image gallery? Image gallery as in the one you see all your images in.
I'm using multi site. I could not find any documentation on why. Im transferring large amount of images onto a new sever. | Uploading the image is only one part of the process. When you add media to your site via the Media Library, it's actually added as an `attachment`, a built-in post type that carries with it a bunch of metadata. Simply FTPing images into the appropriate directory doesn't create the associated `attachment` post or set any of the metadata.
A bit of quick Googling led me to the Add from Server plugin, which might do just what you need. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "multisite, ftp"
} |
Is there SEO or related limitations to using Custom Post Types instead of WPMU?
With regard to the structure of a multi language wordpress site, I read articles discussing the pros and cons of a subdomain based WPMU(wordpress multisite) or a subdirectory based WPMU or WMPL plugin etc?
What about using Custom Post Types? I can use one site and segregate each language into a particular Custom Post Type.
Is there any drawback with regard to google SEO or anyother thing I don't know yet?
For example, I noticed CPTs don't have their own category taxonomy or are not supposed to have that. Does that work well with google "localization"? (since it might seem that the different languages are mingled together and served from one site)
Thanks | Internal DB structure has nothing to do with SEO. SEO is all about front end content and URL structure, and while internal APIs can make some URL structures easier or harder to achieve there is no limitation at all about the front end.
This applies both to "normal" wordpress and multisite.
As for WPML, you will have to ask the author. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, multisite, multi language, seo"
} |
WP_Query: Query posts only if their access is restricted to logged user's role
So this is what I'm trying to do. I have some posts that are visible only to users with a certain role. I want to display them in a user's profile section, so they're immediately visible after they log-in. Let me underline it: I don't want to display ALL the posts that my user is allowed to see, but only those that are restricted to my user's role.
What I found and tried didn't solve my issue.
$q = new WP_Query(array( 'perm' => 'readable' ));
while ($q->have_posts()) : $q->the_post();
the_title();
endwhile;
Of course this does query all the accessible posts, which is not what I want. So, can I avoid creating a restricted category to solve this? | If posts are restricted to a specific role users are required to have, you must add some piece of metadata to the post. Else, WP won't know which posts you mean.
There's a standard box for adding metadata to your post (select 'custom fields' under 'screen option' in your edit screen), or you could create your own metabox or (easier) taxonomy. From your question I gather you already considered the latter option and thought it too cumbersome. But there's no way to escape putting some tag on the post telling the system which ones are meant for which type of user.
Once there is some metadata on the post, you can query for it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, user roles, permissions"
} |
Return only top-level navigation items from a menu using wp_get_nav_menu_items
I have the following function in my project:
function cr_get_menu_items($menu_location)
{
$locations = get_nav_menu_locations();
$menu = get_term($locations[$menu_location], 'nav_menu');
return wp_get_nav_menu_items($menu->term_id);
}
The function is used in my theme like this:
<?php $nav = cr_get_menu_items('navigation_menu') ?>
<?php foreach ($nav as $link): ?>
<a href="<?= $link->url ?>"><?= $link->title ?></a>
<?php endforeach; ?>
This currently returns all navigation items present in my menu - parent/top-level and sub navigation. I am wondering how to alter this to **exclude** all sub navigation items. I only want to display the parent/top-level items. | Let's take a look at `wp_get_nav_menu_items` code reference.
It takes two parameters:
* `$menu` \- (int|string|WP_Term) (Required) Menu ID, slug, name, or object,
* `$args` \- (array) (Optional) Arguments to pass to get_posts().
So we can use `get_posts` args in here... And if we want to get only top-level posts, then `post_parent` arg comes useful...
So something like this should do the trick:
function cr_get_menu_items($menu_location)
{
$locations = get_nav_menu_locations();
$menu = get_term($locations[$menu_location], 'nav_menu');
return wp_get_nav_menu_items($menu->term_id, array('post_parent' => 0));
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "functions, theme development, menus, navigation"
} |
how to add dynamic footer credit in Greatmag theme
I want to add a dynamic footer copyright credit in my Great mag theme that will automatically updates years like © 2000 - 2018 like this . Please tell me how to do in in Greatmag theme by a themes. Thanks | With out knowing the theme personally it's not easy to tell you exactly what you need to do. However, as @WebElaine has pointed out, the code you will need to change will most likely be in your themes `footer.php` file.
It's not recommended to edit themes directly and you should, instead, consider using a WordPress child theme - <
If you have a child theme setup and activated, you should then copy the `footer.php` file from your 'parent' theme to your child themes folder and edit the file where you want your copyright notice displayed.
In order to display the copyright notice as you requested you would need to use something like the following code:
`© 2000 - <?php echo date('Y'); ?>` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "themes, child theme, copyright"
} |
If one meta key value is empty, try to get another meta key, and if both meta keys are empty show something else?
I have this code:
<div class="video-embed" style="margin-top: 0px; z-index:102; margin-bottom: 0px;">
<?php
$url1 = get_post_meta( $post->ID , 'video_play' , true );
$search = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x';
$replace = '
$url = preg_replace($search,$replace,$url1);
?>
<iframe width="560" height="315" src="<?php echo $url; ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
Now I need to implement feature...
If video_play is empty, try to get video_stop `$url1 = get_post_meta( $post->ID , 'video_stop' , true );`, if video_play and video_stop are empty show text "This video is removed". | You can use if else:
<div class="video-embed" style="margin-top: 0px; z-index:102; margin-bottom: 0px;">
<?php
$url1 = get_post_meta( $post->ID , 'video_play' , true ) ?: get_post_meta( $post->ID , 'video_stop' , true ) ?: false;
if( $url1 ):
$search = '#(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x';
$replace = '
$url = preg_replace($search,$replace,$url1);
?>
<iframe width="560" height="315" src="<?php echo $url; ?>" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
<?php
else:
echo "This video is removed";
endif;
?>
</div> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field"
} |
Creating a form and displaying entry data as a table
I'm brand new to Wordpress, but I have experience in web-development.
I'm trying to create a form with custom fields. When submitting the form, I'd like to append the entries of the form to a table. I'm not sure where or what to look for.
I saw that using a combination of Ninja Forms + Conductor, it is possible to achieve this, but sadly, due to its cost, I cannot get access to Conductor.
What is a way I can do this?
Thanks | 1. Create your db table. Example here.
2. Generate your wp_list_table admin page. Generator is here.
3. Insert your form values to your db table. Like this. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, forms"
} |
Remove classes from post_class()
I am trying to tidy up the `post_class` function.
I've managed to remove "hentry" class using the filter below, but I would also like to remove the "post-id", "type-" and "status-" classes as well. How can I use my filter to do this?
function lsmwp_remove_postclasses( $classes ) {
$classes = array_diff( $classes, array( 'hentry' ) );
return $classes;
}
add_filter( 'post_class','lsmwp_remove_postclasses' ); | One way would be to use `preg_match` and remove classes that matches given patterns, but... Since we know `$post_id`, we can use your code with a tiny modification:
function lsmwp_remove_postclasses($classes, $class, $post_id) {
$classes = array_diff( $classes, array(
'hentry',
'post-' . $post_id,
'type-' . get_post_type($post_id),
'status-' . get_post_status($post_id),
) );
return $classes;
}
add_filter('post_class', 'lsmwp_remove_postclasses', 10, 3); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, post class"
} |
How to add css class to image attached in all the posts?
Currently by default image have similar classes
<img class="size-full wp-image-8996" src="
**What i am trying here to add a class as img-fluid to all the attachments in posts not the thumbnails.**
<img class="img-fluid size-full wp-image-8996" src="
How could it be done?
Any Idea will be appreciated! Please help me | You can use the filter `get_image_tag_class` which exists exactly to do what you want:
add_filter('get_image_tag_class','wpse302130_add_image_class');
function wpse302130_add_image_class ($class){
$class .= ' img-fluid';
return $class;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "functions, theme development, images"
} |
Print specific values stored in a post meta array
I'm triing to print some values stored in a post meta.
My post meta_values looks like this :
a:3:{s:6:"amount";s:117:"€2.00";s:6:"entity";s:5:"11854";s:9:"reference";s:9:"800146779";}
I'm using the function bellow in order to try to print the Amount, the Entity and the Reference but all I'm getting is the first character of the Value.
Here's my function:
function get_value( $order, $parameters ) {
$order_id = Compat\Order::get_id( $order );
global $wpdb;
$ref_multibanco = get_post_meta($order_id,'_stripe_multibanco', true); // select array
return $ref_multibanco['amount']['entity']['reference'];
}
And since i'm asking I would like to print this like:
Ent: 11854
Ref: 800146779
Value: €2.00 | function get_value( $order, $parameters ) {
$order_id = Compat\Order::get_id( $order );
global $wpdb;
$ref_multibanco = get_post_meta($order_id,'_stripe_multibanco', true); // select array
$text_print = 'Ent: '.$ref_multibanco["entity"].'<br>Ref: '.$ref_multibanco["reference"].'<br>Value: '.$ref_multibanco["amount"];
return $text_print;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "array, post meta, meta value"
} |
does wordpress serve static files?
I am debugging an issue with WordPress and I wonder if static files like css/images/js are affected by WordPress/PHP or if they are served directly by apache?
I do not have any WordPress cache plugin active at the moment. | Usually: no. When WordPress is running on apache with mod_rewrite enabled, it'll use
# 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
To make sure that static files will **NOT** be served through WP. A plugin might add its own rewrite rules to the .htaccess, but generally WP will not interfere with static files, those will be dealt with by apache directly. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "performance"
} |
How to make a can't hide widget?
I want make a widget show on my wordpress dashboard and show for other users .
and I want make it always show (can't hiddden by other use ,only can by code).
Is here any one can help me ?
THIS IS MY CODE
function example_add_dashboard_widgets() {
wp_add_dashboard_widget(
'example_dashboard_widget', // Widget slug.
'Example Dashboard Widget', // Title.
'example_dashboard_widget_function' // Display function.
);
}
add_action('wp_dashboard_setup', 'example_add_dashboard_widgets');
function example_dashboard_widget_function() {
echo "Hello World, I'm a great Dashboard Widget";
} | to block the ablility to hide it, you can use that :
const WIDGET_TO_SHOW = "example_dashboard_widget";
add_filter("get_user_option_metaboxhidden_dashboard", function ($result, $option, $user) {
$result = array_diff($result, [WIDGET_TO_SHOW]);
return $result;
}, 10, 3);
this is just server side. to be more clear for the user, you can use JavaScript to hide the checkbox in "screen options". | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "widgets, dashboard"
} |
What is the difference between the different ways of linking stylesheets
I'm only just learning WP theme development so this may be a very stupid question, but I have noticed there are different ways to link to the main stylesheet from the `index.php`:
<?php bloginfo('stylesheet_url');?>
<?php echo get_stylesheet_uri(); ?>
`Register` and `enqueue` styles via a function and `add_action` hook in `functions.php`.
These are the ones I have come across so far.
What is the difference between them? They seem to do the same thing to me but I have read that registering and enqueueing styles via `functions.php` is the preferred way. Why? | Enqueueing via your `functions.php` is by far preferable, because it allows WordPress to keep track of which styles are loaded and in which order. This matters, because when css statement are equivalent, the one that is loaded last will be applied to the page.
This may not matter too much when you are developing a simple theme all by yourself (as you're likely to do as a beginner), but once you want something more complex you'll see the benefits. For instance when you want to reuse your theme for a second site, you'll want to build a child theme to store the changes in. At that point you need the enqueuing system to control the order in which the style sheets from parent and child theme are loaded.
Also, when you want to load style sheets you got elsewhere (like font icons), the enqueuing system makes sure you don't run into conflicts with a plugin that might be loading the same stylesheet. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp enqueue style, css, bloginfo"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.