INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
echo do_shortcode just prints the shortcode name and not its content
I have this code:
<div id="order_form">
<?php echo do_shortcode('[order_form]'); ?>
</div>
And my shortcode:
<?php
add_shortcode('order_form', 'order_form');
function order_form(){
return "hello!!";
}
But this simply prints out
[order_form]
Why is that? | I can't comment yet - So I will do my best for providing an answer until i get enough rep -
function add_my_shortcode(){
$content = "Habba";
return $content;
}
add_shortcode('yourShortcodeName', 'add_my_shortcode');
I have been doing it like this for a long time, and never had any problems - have you written this code in a file that executes early? like functions.php, or have you put it in a template? I can't see anything else there could be wrong with your code? | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "shortcode"
} |
Deleting Custom Post type data using mySQL command
I have around 2000 posts under a custom post type `storelocations`. Deleting them from WordPress admin takes a lot of time.
1. How to delete all the posts from this custom post type from database using mySQL command. Here is my approach:
`DELETE FROM 'wp_posts' WHERE 'post_type' = 'storelocations'`
But I guess the post also have some data in `wp_postmeta` and some other tables maybe. And I guess I should delete data from there too.
So, may I know which tables have the data for a post. And what command I should run to clear them.
2. Another doubt that I have is: why deleting the posts from WordPress admin takes so much time compared to deleting the posts from mySQL. Isn't WordPress doing the same thing as running few SQL commands, or there is much going on? | Honestly, the time writing this question and waiting for an answer, is longer than just going into screen options, setting the posts to about 200, and just doing bulk move to trash, and emptying the trash - if you speed is high, you can probably do even more than 200.
else there is a nice tutorial on how and which tables you should work with here - but it will probably take longer
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, posts, mysql, customization"
} |
How to convert custom fields to content
I have some custom post types and inside them I have some custom fields that I need to convert in post content.
Is this possible? How can I do this? | You can do this by using something similar
<?php
//Post we need to update
$id = 37;
$custom_field = get_post_meta( $id, 'custom_field_key', true );
// Update post 37
$mg_post = array(
'ID' => $id,
'post_content' => $custom_field,
);
// Update the post into the database
wp_update_post( $mg_post );
//Delete the custom field
delete_post_meta( $id, 'custom_field_key' );
?>
Hope you got the idea. Let me know what have you tried. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom field"
} |
I accidentally added a widget area called sidebar 1
I accidentally added a widget area called sidebar 1 (because I was an idiot and read the instructions in the Widget Name area wrong). Now it's currently conflicting with my Theme Sidebar (theme is Divi Elegant Themes). Went I load the blog page of the website, the sidebar 1 shows up instead of the default sidebar.
Is there any way to remove this new widget area without breaking the entire website? | There should be a line like this in your functions.php of the theme:
"register_sidebar"...
<?php
// ... some code before
//
register_sidebar(array(
'name' => __('unwanted widget', 'your-textdomain'),
'description' => __('Your new widget desciption', 'your-textdomain'),
'id' => 'your-new-widget-name'
));
// ...some code after
?>
Search for that line and change it. Basically, simply rename your unwanted Sidebar 1 to something different.
You have overwritten the default widget with a new one and created a name conflict. Change the name of your unwanted widget, that should fix it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets"
} |
Is it possible to instantiate a new WC_Cart?
I am trying to use a different plugin's functionality without letting it run normally. It has a function that uses a WC_Cart object, and I want to give it a cart that is completely spoofed. Absolutely not the standard WC()->cart.
I do not want to modify any plugins, and I want to keep my work inside the functions.php file.
Is it possible to make a new WC_Cart like this? How exactly can I do that?
Do I have to import the plugin file that contains the WC_Cart class? Or is it possible to access it without having to do that? | Turns out that I was in the incorrect namespace. A new woocommerce cart can be instantiated by
$cart = new WC_Cart();
assuming you're in the same namespace as the cart, but if you are in a different namespace and suffering the problem I had with my original question, you would change it to:
$cart = new /WC_Cart();
As the / means to check the standard namespace, the same namespace the WC_Cart was declared in. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, woocommerce offtopic"
} |
Wordpress filter custom posts by multi terms of of a taxonomy
I have this headache for couple of days now.
I am on a project where it requires to sort/filter custom posts by both single and multiple terms of a taxonomy. There should be additional filter for ordering the posts by ASC/DESC.
Basically like this filter on the page: <
I have tried to use dozens of plugins and gone through several online code samples, but failed to find appropriate one, the closer one was: Beautiful taxonomy filters but it does not provide multiple terms filtering option and there is no way to present the filter as a list of items rather than a dropdown.
My development page: <
Stackexchange is my last resort. | Have you checked WP Advanced Search ?
I think that will make the solution for you. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development"
} |
Passing variable from template file to the plugin file
I need to send some variable from template file (themes/template/page-profile.php) to the plugin file(plugin/instagram-slider/instagram.php).
For example: I have
$instagram_url = get_user_meta($user_data->ID, 'instagram_url', true);
I need to send that $instagram_url to plugin file:
private function display_images( $args )
{
$username = $instagram_url;
}
Any suggestions on how I might do this? | You can use this way:
private function display_images( $args )
{
$instagram_url = get_user_meta($user_data->ID, 'instagram_url', true);
$username = $instagram_url;
//You can use $username in another function by simply call it using global method.
}
This is an easy way to get the post meta data in your custom plugin file. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, page template, variables"
} |
Woocommerce display price without formatting
## What I Want
I want to display the prices in the product page exactly as inputed. So for eg: if for a product I give price as 70.000 and another price as 70. I want to display exactly as entered. So regular price for first will be displayed as 70.000 and for second product price will be displayed as 70.
The reason for this is for certain products I want to display the decimal points and for some I don't want decimal points. So setting decimal point to 3 in woocommerce settings to 3 is not an option.
## What I Tried
I tried modifying `wc_price` function in wc-formatting `get_price_html` function in absctract-wc-product.php
But it seems like the price is formatted before. How can I achieve this? I'm new to wordpress and would like some help. | Try using `get_price()` instead of `get_price_html()`. You can call the function on any woocommerce template like this
$product->get_price(); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "woocommerce offtopic"
} |
change default RSS feed URL
I need to change the default rss url of my website:
from example.com/feed to example.com/MyfeedName
**Update:**
what i tried so far is to create another Url feed but i need to remove first`example.com/feed`:
add_action( 'init', function()
{
add_feed( 'secretfeed', 'do_feed_rss2' );
});
add_action( 'pre_get_posts', function( \WP_Query $q )
{
if( $q->is_feed( 'secretfeed' ) )
add_filter( 'option_rss_use_excerpt', '__return_false' );
} );
do you have any idea how to just edit `example.com/feed` or how to delete it without losing rss functions? | I found my answer here : <
function remove_feed( $feedname ) {
global $wp_rewrite;
if ( in_array( $feedname, $wp_rewrite->feeds ) ) {
$wp_rewrite->feeds = array_diff( $wp_rewrite->feeds, array( $feedname ) );
}
$hook = 'do_feed_' . $feedname;
// Remove default function hook
remove_all_actions( $hook );
add_action( $hook, $hook );
return $hook;
}
Usage:
remove_feed( 'feed' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, urls, rss"
} |
link to page_for_posts
Trying to create a button that leads to the blog from my static homepage. As i understand it there is a function called get option page_for_posts that seems suitable for this. But when i try to pass it through to my button nothing happens, what am i missing here?
<input type="button" class="cta-button" value="Newsfeed" onclick="window.open('<?php get_permalink( get_option( 'page_for_posts' ) ); ?>', '_self')"> | I wouldn't classify this as a WordPress issue persay. The problem is that any `get_*()` functions return values. This means that `get_permalink()` returns the permalink to be assigned ot a variable which you're not doing or intend to do in this case. So we have the value sitting in memory all we need to do is print / `echo` it:
echo get_permalink( $post_id );
Or in your case:
<input type="button" class="cta-button" value="Newsfeed" onclick="window.open('<?php echo get_permalink( get_option( 'page_for_posts' ) ); ?>', '_self')"> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "php, posts, javascript"
} |
How to define active widget with js in a customizer
I need to use js to define the identifier of the active (open / editable) widget.
+
Catch the event (trigger) switch the active widget.
Is there a built-in js api for these events?
I need something like this:
jQuery(document).on('widget-updated', function(event, widget){
//...
});
jQuery(document).on('widget-added', function(event, widget){
//...
});
Or js object (view) with this data. | Found in the source code the answer to my question, maybe someone will come in handy:
jQuery(document).on('expand', function (event) {
console.log(event.target);
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, widgets"
} |
How to rotate every letter in a title
I was wondering how to rotate every letter in a title.
You can rotate every letter in a word with
<span class="slant">A</span class="slant">
<span class="slant">c</span class="slant">
<span class="slant">m</span class="slant">
with the CSS
.slant {transform: rotate(10deg); }
But how to do it with WordPress?
I was thinking use JavaScript/jQuery to split the `<?php bloginfo("url")?>` into letters, add the slant class and put the css in the `style.css` section. | You could use jquery to split the title into letters and apply the class. That would work for any html page, regardless whether it was made by WordPress, Drupal, some dude that is stuck with Dreamweaver or whatever.
The WP way would be different. If you're new this is fairly complex, but a good start if you're willing to learn. The title of a WP post is generated by a function called `get_the_title`. This function ends with a filter, that allows you to modify the resulting title. Like this, which you would put in the `functions.php` file of your child theme:
add_filter ('the_title', 'wpse263471_split_title');
function wpse263471_split_title ($title) {
... do stuff ...
return $title;
}
In the place of 'do stuff' you would have to write php code that splits `$title` into letters, adds `<span class=slant>` around them and then glues `$title` together before returning it. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, filters, css"
} |
Do I need a Multisite?
I have a client who has asked me to develop a sales-based WordPress site with a customized subdomain for each potential client (< < etc.).
Is a multisite the way to accomplish this or is there a better way?
Thank you!! Angie | If your client asks for multi-sites, there is no alternate option for it then.
But according to the need, sometimes creating separate pages for clients like website.com/client1/, website.com/client2/ etc. and masking/redirecting client1.website.com, client.website.com to these (respectively) may work as well.
This will lessen the trouble of handling multiple sites. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "multisite"
} |
Remove a menu sub-item
I want to remove a menu sub-item. But i cant'find the right item to delete. It is a plug caled "New User Approve". And the slug is :/wp-admin/users.php?page=new-user-approve-admin
I don't want to disable the plugin and the functions, just the sub-menu item.
I don't come further than:
add_action( 'admin_menu', 'remove_admin_menus' );
add_action( 'admin_menu', 'remove_admin_submenus' );
//Remove top level admin menus function remove_admin_menus() {
}
//Remove sub level admin menus function remove_admin_submenus() { remove_submenu_page( 'users.php', 'users.php?page=new-user-approve-admin' );
}
or
function remove_submenu() {
remove_submenu_page( 'users.php', 'users.php?page=new-user-approve-admin' );
}
add_action( 'admin_menu', 'remove_submenu', 999 ); | You'd want to add this code:
add_action( 'admin_menu', 'remove_admin_menus', 999 );
function remove_admin_menus() {
remove_submenu_page( 'users.php', 'new-user-approve-admin' );
} | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "menus, customization"
} |
My redirect URL doesn't show any pages on my website
I recently started using Wordpress. To do so I installed wordpress on my FTP server. Everything is working perfectly fine so far, except for my page URL.
My FTP server's URL is really complicated so I bought an domain name and redirected it to the FTP server. The site is called **jongbeleggen.com** . However, because I redirected with something called 'transparancy' (some kind of iframe), my site is only showing jongbeleggen.com no matter what page I go to.
Example: When I go to my website, the URL jongbeleggen.com is showing. Then when I click on my Blog page it should say jongbeleggen.com/blog . However, it says jongbeleggen.com
I would really appreciate if anyone can help me with this issue or tell me what iam doing wrong!
Thank you in Advance!
Peter | You're doing the whole thing in a wrong way. First of all you should not redirect the domain to ftp server url.
You should point your domain using `A record` or `Nameservers`. Whatever option you have/works for you.
And then change `siteurl` and `home` url in your database with the new domain name. More Details about this process
And then use a plugin like Velvet blues update urls to replace old url's with new domain's url.
After doing these, your site should work fine. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "redirect, urls, hosting, ftp, iframe"
} |
Using more than one meta_key in pre_posts_query
I am already filtering some custom posts depending on a querystring in pre_get_posts:
if( $query->is_main_query() ) {
if( is_post_type_archive( 'events' ) ) {
if ($_GET['status']) {
$retrieved_status = $_GET['status'];
$query->set('meta_key', 'event_status');
$query->set('meta_value', $retrieved_status);
}
}
}
I would then also like to sort by a different custom field, but I can't use something like below because it rewrites the meta_key:
$query->set('orderby', 'meta_value');
$query->set('meta_key', 'event_date');
$query->set('order', 'DESC');
How could I structure this to get the desired effect? Thanks! | Use WP_Query to select any post based on meta key and value. You can also sort posts Ex:
$args = array(
'post_type' => 'events',
'orderby' => 'meta_value_num', //probably you will need this because the value is date
'meta_key' => 'event_date',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'event_status',
'value' => $retrieved_status,
'compare' => '=',
),
array(
'key' => 'other_key',
'value' => 'other_value',
'type' => 'numeric', //for example
'compare' => 'BETWEEN', //for example
),
),
);
$query = new WP_Query( $args );
See Order & Orderby Parameters & for `meta_value_num` see Custom Field Parameters | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom field, pre get posts"
} |
Right permissions to WordPress directory
Knowing that not all files and folders have the same permissions, What are the right permissions in order to avoid hacker attacks and to allow the sites updates and upgrades?
My site is installed on Linux Debian 7
**Note.** My mother language is Spanish, so I apologize if my question is not fully understood. | Standard file/folder permission for WordPress:
`755` for folders
`644` for files | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "directory, linux"
} |
check if tag exists in wp database
I have to display a button that links to a tag, but I have to hide the button if tag doesn't exists to avoid broken links.
How can I check if a specific tag exists inside wp database?
**This is what I have so far:**
$tag_path = '/tag/testing/';
if( !$page = get_page_by_path( $tag_path ) ){
//hide button link
} else {
//show button link
} | I think you're looking for `term_exists` function.
Example Code:
<?php
$term = term_exists('tag1', 'post_tag');
if ($term !== 0 && $term !== null) {
echo "'tag1' post_tag exists!";
} else {
echo "'tag1' post_tag does not exist!";
}
?> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "taxonomy"
} |
How To Show All Custom Post Types In A Category Instead Of Pagination?
I want to adjust or edit below codes to show all custom post types without showing page numbers. I just want to show all items in one page. I don't want to keep pagination here. What thing I need to edit or add in this below codes?
// show all active coupons for this store and setup pagination
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
APP_TAX_STORE => $term->slug,
'ignore_sticky_posts' => 1,
'paged' => $paged
) ); | Update your code as below.
// show all active coupons for this store and setup pagination
query_posts( array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
APP_TAX_STORE => $term->slug,
'ignore_sticky_posts' => 1,
'posts_per_page'=>-1
)
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, pagination, navigation"
} |
Language Translation is not working?
**My wpconfig.php file:**
define('WPLANG', 'tr_TR');
**My Code:**
echo '<div id="wtdCustomizButtonDetailsPage"><a href="'. $getCustomPage .'?type=wtd_sc_designer&wtd_id='. $id .'">'. __('Customize', 'wctd') .'</a></div>';
**My PO File Naming:**
;
and be sure that the directory to languages folder is correct.
This fixed the issue for above question. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins, plugin development, translation, multi language, language"
} |
Filter Widget Title Wrap
This code i wrote works but it doesn't remove the h4
add_filter( 'widget_title','modify_text_widget_title_tags', 10, 3 );
function modify_text_widget_title_tags( $title, $instance, $id_base ) {
if ( 'text' == $id_base )
return '<h2 class="widget-title widgettitle">' . $title . '</h2>';
}
It does output h2 but i need to filter the h4 tags and replace them with h2.
I looked in class-wp-widget-text.php but there is no filter for the widget title wrapping tags or any div class which wraps the widget title. | The filter to do this is dynamic_sidebar_params also see this tutorial on this filter at ACF's site (even if you don't use ACF).
function prefix_filter_widget_title_tag( $params ) {
$params[0]['before_title'] = '<h2 class="widget-title widgettitle">' ;
$params[0]['after_title'] = '</h2>' ;
return $params;
}
add_filter( 'dynamic_sidebar_params' , 'prefix_filter_widget_title_tag' ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "filters, widgets, title"
} |
Fatal error post.php help :(
I would really appreciate any help with my website that crashed and the following error appears
> Fatal error: Call to undefined function is_user_logged_in() in /home1/zesiku/public_html/wp-includes/post.php on line 2160"
I have checked cpanel and see the following. The line that says `if ( 'readable' == $perm && is_user_logged_in() ) {` is the 2160. What to do :(((
function _count_posts_cache_key( $type = 'post', $perm = '' ) {
$cache_key = 'posts-' . $type;
if ( 'readable' == $perm && is_user_logged_in() ) {
$post_type_object = get_post_type_object( $type );
if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
$cache_key .= '_' . $perm . '_' . get_current_user_id();
}
}
return $cache_key;
} | Put your code in `whatever` function:
function whatever(){
// do stuff
}
add_action( 'init', 'whatever' );
Or use this to check whether user is logged in or not:
if( get_current_user_id() ) {
// logged in user
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "posts, errors"
} |
Avoiding "Missed Schedule" errors when inserting future posts
I'm inserting future posts as you'd expect using a `post_status` of `future` and a future `post_date` and `post_date_gmt`.
The dates look fine in WordPress, but these posts appear with the "Missed Schedule" warning. They haven't missed schedule yet because they're future posts.
My guess is that it's because when inserting these future posts I'm not adding a cron event. Is this hunch correct and if so, do I simply schedule an event after the publish time? If not, what can I do to avoid "Missed Schedule" errors when inserting future posts? | The missed schedule warning comes form those lines: <
It should be independent on any cron event, as the warning is being displayed only in case the current UTC time - post_date_gmt > 0 - there is no other condition (except for post having the `future` status).
In order to debug the issue, check what value is saved in the database in the `post_date_gmt` column of the post object with the false-positive warning. The value returned from PHP's `time()` should always be UTC so I don't expect any issues there.
In case the post has correct GMT time, check whether some of installed plugins is not filtering the `get_post_time` filter used in get_post_time function used here: <
Hope it helps. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "posts, cron"
} |
Retrieve custom fields on Categories, using WP-API
I've added a single Advanced Custom Field to the categories taxonomy (that appears to work as expected) and am trying to retrieve it along with the categories using the REST API, via `/wp-json/wp/v2/categories`.
I've managed to customise the posts JSON returned, using the `rest_prepare_post` filter...
function prepare_restful_posts($data, $post, $request) {
// Do stuff to $data
}
add_filter('rest_prepare_post', 'prepare_restful_posts', 10, 3);
...but I can't seem to find any helpful information about how to customise the categories JSON.
Can someone possibly shed some light on this? | Turns out it's the helpfully titled `rest_prepare_category`filter
function prepare_restful_categories($response, $item, $request) {
// Do stuff to categories
}
add_filter('rest_prepare_category', 'prepare_restful_categories', 10, 3); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "custom field, advanced custom fields, rest api"
} |
Is there significant risk in not keeping a theme updated?
Is there significant risk in not keeping a theme updated?
We have various themes which we have purchased and modified. It would be a lot of work to install theme updates and re-implement our changes. Do themes, not kept updated, pose a significant security risk? | Generally speaking outdated plugins are more of a risk, but themes should be updated.
The "heavier" the theme (more javascript, custom functions etc) the more likely it is to become a risk when out of date. Frankly it's one good reason to code lean/mean themes yourself and not buy of the shelf, but that's just my opinion.
The answer to your question then, yes is "It's a risk". But I wouldn't not go as far as as saying "significant" (as opposed to the plugins) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "themes, security"
} |
WP API returning SQL results as strings, rather than numbers
I have this code, but what I get in the browser are all the fields - even those stored as Int and Bool in SQL - as strings.
add_action( 'rest_api_init', function () {
register_rest_route( 'restos/v1', '/resto/(?P<qname>.*)', array(
'methods' => 'GET',
'callback' => 'handle_get',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
} );
function handle_get( $data ) {
global $wpdb;
$query = "SELECT * FROM `restaurants` WHERE `qname` = '".$data['qname']."' LIMIT 1";
$res = $wpdb->get_results($query)[0];
return $res;
}
I tried `return json_encode($res)` but that did not help. How can I get an object sent over with numbers and booleans in json. | The string output type is expected for `$wpdb` query results, the db data types are not mapped to the corresponding PHP data types.
You will have to take care of it yourself, like:
$data = [
'int' => (int) '123',
'bool' => (bool) '1',
'string' => (string) 'abc'
];
return rest_ensure_response( $data );
with the rest response:
{"int":123,"bool":true,"string":"abc"}
Here's an interesting approach by Matthew Boynes, to handle it automatically in `wpdb` with a custom wrapper.
Note that you can use `wpdb::get_row` to get a single row. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 6,
"tags": "json, wp api"
} |
get_term_link() returns incorrect url
I have a custom post type (`item`) with multiple custom taxonomies (`item_category_A`, `item_category_B`, etc.) I'd like to retrieve custom taxonomy terms of the current `item` from `item_category_A`, also make them clickable. My code retrieves the correct terms, but then using `get_term_link()` retrieves a url, looking like `sitename.com/item_category_B/category_A_term_slug` . What am I doing wrong? My code looks like this:
function get_item_category_A(){
$item_cat_A = get_the_terms(get_the_ID,'item_category_A');
echo '<a href="' . esc_url(get_term_link($item_cat_A[0]->slug,$item_cat_A[0]->taxonomy)).'">'.esc_html($item_cat_A[0]->name).'</a>';
}
Still, when I run the function, it returns the url than points to the correct term in the incorrect taxonomy (`sitename.com/item_category_B/category_A_term_slug`). | WordPress allows for customization of the default URL rewrite behavior (/slug/term) with a `rewrite` arguments array passed to the `register_taxonomy()` function.
By defining values for the `slug` or `hierarchical` keys in this array, the default URL structure can be altered to suit your needs. It may also be altered such that unexpected results are returned.
When creating multiple taxonomies, it is easy to copy & paste the labels and parameters arrays for one tax and overlook the necessity to update some of the specifics for subsequent uses.
WP Codex reference: <
Hierarchical taxonomy explanation via Milo: How to enable hierarchical permalinks for hierarchical taxonomies | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, custom taxonomy, terms"
} |
Displaying a button on each post
I'm trying to add a button for each post.
add_action( 'the_post', [ $this, 'myButton' ] );
public function myButton( $post ) {
$this->ID = $post->ID;
$myId=$post->ID;
echo "<button onclick=\"buttonAction()\" p style=\"font-size:10px\" id=\"ActionButton\">ACTION</button>";
}
This works well, but there is a problem, it not only appears in post, but also on homepage above each post and at all pages that contains a link to post. Additionally I can't style for displaying it at the proper place, it is on the top of post. How can i style it, and make it only appear on post's webpage. | Use `the_content` hook and hook only when you are on a single page:
add_filter( 'the_content', 'my_button_function' );
function my_button_function( $content ) {
// See if it's a single post or a loop
if ( is_single() && in_the_loop() && is_main_query() ) {
return $content . "<button onclick=\"buttonAction()\" p style=\"font-size:10px\" id=\"ActionButton\">ACTION</button>";
}
return $content;
}
This will only add the button if you are on a single post, and will add the button at the end of your content.
Further reading at : WordPress Developer's website. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, posts, buttons"
} |
How to handle a background-size: cover image in Wordpress?
Designer new to wordpress here. I want to take the featured image on a post and make it a hero image for the post single page.
The way I would normally do this is to create a div, set width to 100%, height to whatever vh I want, and then set background to the image url in the CSS with background size set to cover.
So how I'm trying to do this in Wordpress is like this:
<section class="hero" style="background: url('<?php echo $hero_image['url'];?> ');" xmlns="
But that comes out a little wonky because setting background with inline styles overrides all the CSS back to default element stuff. Any ideas on how to do this better? Preferably without any plugins, as I'm trying to learn how to do as much in code as possible. Though I do already have Advanced Custom Fields and Custom Post Type UI installed and I'm using those extensively. | So Jack's answer works, and is correct, but I also found a more elegant solution for what I already had. I made the inline style background-image instead of background:
<section class="hero" style="background-image: url('<?php echo $hero_image['url'];?> ');" xmlns=" | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "images, css, custom background"
} |
Force include a stylesheet from parent theme
I have a theme that includes the stylesheet /css/woocommerce.css This stylesheet is also loaded in the child theme on shop pages. BUT I want to be loaded and on post pages in order to style products that are showed by some plugins. Any advice?
Thanks | Not tested, by you could try something like the code below. If first register your css as css-woocommerce (yout theme may allready have this) then you can on init use wp_enqueue_style IF it is a post (is_single). Does this help you?
function register_custom_stylesheets() {
wp_register_style( 'css-woocommerce',
get_stylesheet_directory_uri() . '/css/woocommerce.css' );
}
function custom_stylesheet() {
if ( is_single() { // if is post type, except attachments and pages
wp_enqueue_style( 'css-woocommerce' );
}
}
add_action( 'init', 'register_custom_stylesheets' );
add_action( 'wp_enqueue_scripts', 'custom_stylesheet' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css"
} |
Server error after log in
Hello everyone when I am going to the admin Area and fill the user name and password and than click on login button.
The login page is taking too long and after that I am getting below error. Please see the screenshot:
, the URL fetches the Author profile based on the ID.
Example: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "profiles"
} |
Deny a user role to log in after register
I have a site where customers can register themselves (they get a user role "pending"). However, what i want is that after this registering these user role cannot automatically log in or log out directly. They must also not be able to log in. Login must therefore be denied for these user role. | What you want to do is hook into the `authenticate` hook, check if the user has the `pending` role, and if so, throw an error.
//* Add filter to the authenticate hook
add_filter( 'authenticate', 'wpse_263762_authenticate', 20, 3 );
function wpse_263762_authenticate( $user, $username, $password ) {
//* Check if the user has the pending role
if( ! is_wp_error( $user ) && in_array( 'pending', $user->roles ) ) {
//* Throw an error
$error = new WP_Error();
$errorMessage = __( 'Your error message goes here.' );
$error->add( 401, $errorMessage );
return $error;
}
//* Or return the user
return $user;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "login, user roles"
} |
Why does my jQuery plugin show up as text in WordPress?
I am attempting to install unslider jquery plugin for my WordPress website. I enter the below code inside my WordPress text editor and I don't get the expected result. I changed $ to jQuery and that didn't fix it either.
<!-- The barebones HTML required for Unslider -->
<div class="banner">
<ul><li>This is my slider.</li><li>Pretty cool, huh?</li></ul>
</div>
<!-- And the relevant JavaScript -->
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="/path/to/unslider.js"></script> <!-- but with the right path! -
->
<script>$(function() { $('.banner').unslider() })</script>
Output:
This is my slider. Pretty cool, huh?
$(function() { $(‘.banner’).unslider() }) | You can use this PHP code to output your slider's initiator in your themes footer:
add_action('wp_footer','initiate_unslider');
function initiate_unslider () {
?>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="/path/to/unslider.js"></script>
<script>
$(document).ready(function() {
$('.banner').unslider();
});
</script>
<?php
}
Also it's safer to add a `$(document).ready` before initiating your slider, in case some necessary components of your page has not been loaded yet. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, jquery, javascript"
} |
How to add new post using a form to categories when categories are using as menu
I have a form to create new post and I pass my post_category into post creating array, but it not insert into that category , it insert into Uncategorized category.And I want to see the post using the menu that I created using categories.
I pass may data to following array to create post.Its working but it insert post into Uncategorized(default) category. any solution?
$post = array('post_type'=>'post',
'post_author'=>$author,
'post_status'=>'publish',
'post_title' => 'Test Title',
'post_category' => '679'
); | Issue is in following line
> 'post_category' => array('679')
Use `'post_category' => array(679)` without single quote. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, php, posts"
} |
Post tags show outside loop?
I'm trying to use tags of the single post, as meta keywords.
I tried using this:
<meta name="keywords" content="<?php the_tags('',',','');?>test<?php }?>"/>
It works, but the output is:
<meta name="keywords" content="<a href=" rel="tag">aquaman</a>,<a href=" rel="tag">batman</a>,<a href=" rel="tag">wonder woman</a>"/>
Is it possible to remove the tags link/URL? And just the text/tag itself will appear? | The code is tested and working fine.
Place this code
<?php
$posttags = get_the_tags();
if( ! empty( $posttags ) ) :
$tags = array();
foreach($posttags as $key => $value){
$tags[] = $value->name;
}
?>
<meta name="keywords" content="<?php echo implode( ',', $tags ); ?>,test"/>
<?php endif;?>
instead of
<meta name="keywords" content="<?php the_tags( '', ',', '' );?>test<?php }?>"/> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "conditional tags, tags"
} |
Local and live synchronized dev and production environment
First sorry for my bad english :)
I'm a beginner of wp and I wonder how to manage/synch the follow dev environment : \- Local and live dev (local server xampp and staging subdomain dev.mywebsite.ext) - After how to update to production environment on www.mywebsite.ext considering eventual new content added from visitors/users.
So in other words how can i manage the syncronization beetween the 3 envirnment (2 dev and 1 produztion) withouth lost anything (contents, files, database):
xampp <\--> dev.mywebsite.ext <\--> www.mywebsite.com
thanks | If you start to look at versioning now you will not regret it later! It's one of the biggest improvements you can make to your development workflow.
You work locally. Commit files as they change, and they are then deployed (even automatically, if you are happy with that) to your live server.
I recommend you look at something like < which makes version control less scary.
Once you have this working, you can enhance it with Chrome plugins like "Server Switcher" and simply snap between local and live servers on the fly. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization"
} |
How to display a background image in a page body area?
I changed the `style.css` file like this:
body.page-id-8 {
background: url(' center center fixed;
width: 100%;
height: 100%;
}
But I get this result:
` function in `head` section of your `header.php` file like this
if(is_home()){
<style>
.class-name{
background: url('
center center fixed;
width: 100%;
height: 100%;
}
</style>
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css"
} |
WordPress localhost site redirect to live site
I have download the code and export the database from server and setup the site on my localhost also I have been changed the home and site URL in wp_options table I am able to login at wp-admin but when I am clicking on the home page it redirect me to live site.
If anyone know the issue please help me.
Thanks in Advance. | Try following
* If there are caching plugins installed like W3 total cache. Then purge cache first. Or may be disable them for time being
* Perform Search and Replace in the database for Old Site URL. You can Use this Plugin
* Reset Permalinks ( Dashboard >> Settings >> Permalinks )
* Last but not the least. Clear your browser Cache and History
* In Chrome, you can try to clear your DNS cache before clearing _all_ your cache | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 16,
"tags": "redirect"
} |
Restrict Wordpress File Type Uploads by User Type
I'm looking to restrict all users (other than admins) to only be able to upload images e.g JPG's and PNGs allowed for all users but still allow admins to upload pdfs etc. (Or even better would be to only prevent unregistered users from uploading anything other than JPGs and PNGs!)
I've been trying the following functions.php code but it still seems to restrict admins from uploading PDFs:
add_filter('upload_mimes','restict_mime');
function restict_mime($mimes) {
if(!current_user_can(‘administrator’)){
$mimes = array(
'jpg|jpeg|jpe' => 'image/jpeg',
'png' => 'image/png',
);
}
return $mimes;
}
Any ideas? | There is a syntax error in your conditional:
current_user_can(‘administrator’)
The input value is wrapped in `‘ ’`, which should be wrapped in `' '` instead. Right now, because `‘administrator’` is neither a role nor capability, the above will always return a false value, therefore
if(!current_user_can(‘administrator’))
will always return `true`, which will restrict the mime type for everyone, including administrators. The correct form will be :
if( !current_user_can('administrator') ) {
//CODE HERE
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "php, functions, uploads"
} |
Remove Dash/Hyphen From Wordpress CustomPosttype Permalink
I want to remove all hyphens/dashes from the Custom Post Type permalink in Wordpress.
For example:
www.website.com/customposttype/post-name/
Becomes
www.website.com/customposttype/postname/
Any advice on how to do this with any functions. | You need to use to hook into WordPress's sanitize title hook.
function no_dashes($title) {
return str_replace('-', '', $title);
}
add_filter('sanitize_title', 'no_dashes' , 9999);
for particular post type you can use these hook
function no_dashes( $slug, $post_ID, $post_status, $post_type ) {
if( $post_type == "page" ) {
$slug = str_replace( '-', '', $slug);
}
return $slug;
}
add_filter( "wp_unique_post_slug", "no_dashes", 10, 4 ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "permalinks"
} |
Page attribute template dropdown not displayed even the syntax is correct
<?php
/*
Template Name: foo
*/
?>
I added this to my foo.php but dropdown not displayed in admin panel. | If you're wanting to enable the Page Template dropdown for a custom post type, you have to enable support for "page attributes" when you define your CPT.
You should currently have something like
register_post_type('foo',
array('labels' => array(
...
),
);
You need to add 'supports':
register_post_type('foo',
array('labels' => array(
...
),
'supports' => array('title', 'editor', 'page-attributes'),
);
'page-attributes' will allow your CPT to use Page Templates, which is what enables the dropdown menu. 'title', 'editor', etc. etc. are optional depending on your needs.
Since your CPT is already defined, you will probably need to first call `unregister_post_type()` to "unregister" it and then re-register it with your new code. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "theme development, page template"
} |
How do I change where a plugin pulls updates from?
I'm trying to write a custom plugin for a few of my clients, and I'd like to serve updates for this plugin from my own server. I tried doing some research on how to do this, but everything I find is stuff like "how to update WordPress."
How can I change where a plugin checks for updates? | Check below a link to a custom update checker for WordPress plugins. Useful if you don't want to host your project in the official WP repository, but would still like it to support automatic updates. It also works with themes.
Plugin Update Checker: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, filters, updates"
} |
Add table to WordPress database
I want to add an extra table on my WordPress database and I intend to query it with a custom script that will be embedded to WordPress.
I'm worrying if this is a safe way to do it, or I should go with the option of adding an entirely new database, not a table on WordPress, as future updates of WordPress system might wipe my custom table? Any experience with such a scenario. Is this a valid risk/worry, or I should just create the table on the WordPress database, instead of creating another db, and connect to that new db in my custom script.
Thank you. | There is no risk in creating new table in WP Database. Infact many well known and giant plugins, like Woocomerce do this.
You can also opt for creating new database but creating new table is not at all risky...
Hope I am clear enough... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, database, scripts"
} |
How to reference PHP in Javascript
I'd like a php link for my Wordpress attachments to appear in part of a javascript function, but my below attempt does not output any text:
var link = "<?php echo wp_get_attachment_link();?>";
function myFunction(link) {
return link;
}
Is this an issue with formatting? Thanks! | To answer the question, no: It's not an issue with formatting, it's as jdm2112 explains the matter. You can, however, "send" the variable , or have it plucked from the server, either via an Ajax call as jdm2112 suggests or as set by wp_localize_script(). Which you use will likely depend on what the script does and when and how it's run. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, functions, javascript, variables"
} |
Post by Email - Shortcode for Language?
I really like the idea of being able to publish new blog posts through an easy email.
However i'm missing one feature, or i haven't been able to find it. Is it possible to define a language of the new blog post through a shortcode aswell?
I'm using Jetpack and Polylang.
Thank you!
Regards, Leeooh | I haven't found a way to get Jetpack and Polylang to properly work together when it comes to pushing posts by mail into the desired language category.
But, i have found a plugin that offers that called Postie. The Polylang addon costs 29$. < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, email"
} |
How to use Wordpress rest API with Angularjs 4
I am learning AngularJS and wanted to created a project in AngularJS 4. In this I want to use WordPress back-end and get data through rest API. I have done little bit research but not found any useful tutorial or example. I don't want to create theme in WordPress based on AngularJS, but want independent application in AngularJS which only use WordPress rest API for displaying content. I want to know how can i implement Wordpress Rest API in to AngluarJS application. So tutorial or example in this topic will be great helpful | Here is a good starting point if you are new to angularjs and WP Rest API with very brief and well documented code.
<
Cheers to Michael Bromley | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "rest api"
} |
How do I add custom column to woocommerce cart?
I want to add a custom column for "Installation Charges" inside cart items. This is going to be different installation charges for every product. I can pass that to cart using woocommerce_add_cart_item_data action hook. But how do I add the separate column to show these installation charges in cart?
Attached is a screenshot mockup of how it needs to be built.
 {
require_once( get_template_directory() .'/inc/customizer/general-settings.php' );
add_action( 'customize_register', 'themeslug_customize_register' );
Thanks in Advance. | Of course. In fact, I would consider requiring files in this way to be a best practice. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme customizer"
} |
Wrap every 2 posts
I have 2 columns blog and I want to wrap every 2 posts inside row class, because I have problem with grid if one of the posts has long name or description
So I try this
<?php $counter++;
if ($counter % 2 == 0) : ?>
<?php echo '<div class="post-wrapper">'; ?>
<?php endif; ?>
<?php get_template_part( 'templates/blog/blog-2-cols', get_post_format() );?>
<?php $counter++;
if ($counter % 2 == 0) : ?>
<?php echo '</div">'; ?>
<?php endif; ?>
but it doesn't work. | You need to start Row class after every 2N+1 post.
And end the Row class after every 2N+2 Post.
Try this one
<?php $counter++;
if ($counter % 2 == 1) : ?>
<?php echo '<div class="post-wrapper">'; ?>
<?php endif; ?>
<?php get_template_part( 'templates/blog/blog-2-cols', get_post_format() );?>
<?php $counter++;
if ($counter % 2 == 0) : ?>
<?php echo '</div">'; ?>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "posts, loop"
} |
Add a new tag based on the category name in the publish event
As you can see in this action, it is overwriting all existing tags by catname, how to add a new tag, preserving the current tags, and not only in update but in publish event, since I use an import plugin, And currently I have to enter all posts and click on update to take the desired action.
add_filter('wp_insert_post', 'add_cat_to_tags', 10, 3 );
function add_cat_to_tags( $post_ID, $post, $update ) {
$tags = array();
$cats = get_the_category( $post_ID );
foreach ( $cats as $cat ) {
$tags[] .= $cat->name;
}
// overwrites any existing tags!!
wp_set_post_tags( $post_ID, $tags );
}
Thanks all. | You have to add the `true` parameter to the `wp_set_post_tags()` function. Tested and works, the corrected code:
add_filter('wp_insert_post', 'add_cat_to_tags', 10, 3 );
function add_cat_to_tags( $post_ID, $post, $update ) {
$tags = array();
$cats = get_the_category( $post_ID );
foreach ( $cats as $cat ) {
$tags[] .= $cat->name;
}
// overwrites any existing tags!!
wp_set_post_tags( $post_ID, $tags, true );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, categories, tags"
} |
Add acf field in title (admin table)
I want to add an ACF field in my post title, only on admin table (not in the title field stored in database), and only for a specific Custom Post Type. Some of my posts have the same name, so it will be more useful to have this information. In final, my title will look like that :
$new_title = get_the_title($post->ID).' - '.get_field('place', $post->ID);
I have found other solutions on other topics, but all the post types are affected. Thank you. | Use this to filter the title:
add_action(
'admin_head-edit.php',
'wpse264139_edit_post_change_title_in_list'
);
function wpse264139_edit_post_change_title_in_list() {
add_filter(
'the_title',
'wpse264139_construct_new_title',
100,
2
);
}`
`function wpse264139_construct_new_title( $title, $id ) {
if(get_post_type($id) == 'post_type') {
$field = get_field('place', $id);
return $field . " " . $title;
}
else {
return $title;
}
}
NOTE: most of the code came from: Replacing the title in admin list table | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, admin, title, wp list table"
} |
Category page not showing
I installed wordpress 4.7.3. After that I created one "Test" category. After that I created one post and assigned to that "Test" category. Then I go to front end, in the right menu and clicked on "Test" category.
Then it shows page with text "OOPS! THAT PAGE CAN’T BE FOUND." "It looks like nothing was found at this location. Maybe try a search?"
Using default wordpress theme "Twenty Seventeen".
Please why it is not showing category page with post assigned to that category? | Just save your permalinks. And the problem should be resolved.
Go to : Settings > Permalinks > Click 'Save Changes' | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, design"
} |
get_plugins() is not give plugin list after performed delete_plugins()
Upon performing delete_plugins() action, get_plugins() is give deleted plugin list.
For example:
delete_plugins(array('akismet/akismet.php'));
get_plugins();
Is I am doing something wrong? Any one give some insight about it. | To answer your main question, you are missing one line before calling `get_plugins()`. Without it, the list of plugins will come from cache. You can use the following sequence:
delete_plugins( array( 'akismet/akismet.php' ) );
wp_clean_plugins_cache( false );
get_plugins();
**`WARNING:`** it is not recommended using `delete_plugins()` in scripts, unless it is a part of complete procedure consisting of deactivation, uninstallation, and then deletion. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development"
} |
Filtered query_vars becomes global. Why does this work?
For some reason that's not quite clear, when I add custom query_vars, they become available everywhere without the need of an accessor like `global` or `get_query_var()`
// if your url contains the var
// and you add it to $query_vars...
<?php
function filter__query_vars( $query_vars ) {
$query_vars[] = 'document_id';
return $query_vars;
}
add_filter( 'query_vars', 'filter__query_vars' );
// you can reference it anywhere.
/* single.php */
<?php
echo $document_id; // outputs 99. wtf?
Why does this work? | Within the `WP::parse_request()` method (src) we locate the `query_vars` filter:
$this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
and within `WP::register_globals()` we can see **why** it becomes globally accessible (src):
// Extract updated query vars back into global namespace.
foreach ( (array) $wp_query->query_vars as $key => $value ) {
$GLOBALS[ $key ] = $value;
}
where the global `$Wp_query` has been fed with the query vars from the global `$wp` object. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "filters, globals, query variable"
} |
Where is All in One SEO Pack sitemap.xml located?
I used the XML Sitemaps in the All in One SEO Pack plugin to generate my sitemap.
When I type in the site address/sitemap.xml (< the sitemap appears.
I want to get rid of some links that don't make sense but when I look for sitemap.xml on the machine it is not present.
sudo find -name sitemap\*
Does anyone know where the sitemap is and how it is being assembled to appear as if it is in the htdocs folder? | The sitemap added by most of the plugins (such as Google sitemaps or YOAST SEO pack) is a virtual file added to your websites by the plugin. This file doesn't physically exist, therefore modifying it is not an option for you.
There might be 2 things that you can do about it,
Either find the `php` file that is generating the XML and modify it, or maybe add a filter if it's supported. In your case, the file is located in `/plugins/all-in-one-seo-pack/inc/sitemap-xsl.php`.
OR
Find the option to demote your URL from the XML list. This option may not exist on every plugin. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "sitemap"
} |
Change / Delete the default post type and category?
I'm developing a website with 3 different post types, and 4 different taxonomies to save the posts under.
The default post type and categories are unused in this template, and since many of authors are not very familiar with WordPress and we can't always control them, i wish to delete, change or at least hide the categories and default post from them, so they have to post it under a custom type.
For example, someone creates a new post under 'Breaking news' type, and assigns it to `News` Taxonomy, this post won't be categorized under any category (Uncategorized).
If he publishes this as a normal post type,it won't be shown anywhere in the website.
Is it possible to work around this? | Yes this is possible with a very simple solution. Add this code snippet to your theme's funtion.php
add_action('admin_menu','remove_default_post_type');
function remove_default_post_type() {
remove_menu_page('edit.php');
}
More info: < or < | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "custom post types, categories"
} |
Get menus created with menu editor?
I am new to wordpress and I am creating a theme for a local company as my final project towards my college degree. They wish to use this theme as a main theme for all their wp sites and that any change in design shall be taken care of by child themes.
they requested that some subpages should have a sidebar menu and some others to have another sidebar menu.
I have made a metabox with a dropdownlist in the page editor so that I can select a menu for each page. The dropdownlist displays all registered menus that are hardcoded inside the theme but not the ones created inside the admin menu editor.
$menus = get_registered_nav_menus();
echo '<select>';
foreach($menus as $menu => $value){
echo '<option value="'.$menu.'">' . $value .'</option>';
}
echo '</select>';
How can I also get the menus that are created with the admin menu editor? | Maybe this helps :
function get_all_wordpress_menus(){
return get_terms( 'nav_menu', array( 'hide_empty' => true ) );
}
get_registered_nav_menus only gets the theme's menu's and not the clients menu's.
Source : Paulund This returns all ID's. To get the name you can use :
<?php $nav_menu = wp_get_nav_menu_object(ID comes here); echo $nav_menu->name; ?>
All menu objects have the next settings :
Object (
term_id => 7
name => Test menu
slug => Test menu
term_group => 0
term_taxonomy_id => 3
taxonomy => nav_menu
description =>
parent => 0
count => 6
)
Source : Stanhub Display wordpress menu title | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "menus, navigation"
} |
"Undefined variable: array" Error In Displaying Post Tag
I'm trying to display the post tags through a widget, I've following codes and getting error "Undefined variable: array":
if ( $instance['stats_tag']['category'] ) {
$posttags = get_the_tags();
if ($posttags) {
$array = array();
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$array[] = '<a href="' . esc_url( $link ) . '" rel="tag" itemprop="keywords">' . $tag->name . '</a>';
}
}
if ( $stats != '' ) {
$stats[] = '<span class="the-day-tags">' . implode(', ', (array)$array). '</span>' ;
}
Can anyone help me to fix the issue ? | You are probably not getting into your first if - And therefore the $array is not defined, since you do it in that condition and also use it if $stats is not empty - Either define the $array before the if($instance) or find another way :-D so something like this, will get you on the right track
$array = array();
if ( $instance['stats_tag']['category'] ) {
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$array[] = '<a href="' . esc_url( $link ) . '" rel="tag" itemprop="keywords">' . $tag->name . '</a>';
}
}
if ( $stats != '' ) {
$stats[] = '<span class="the-day-tags">' . implode(', ', (array)$array). '</span>' ;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "array, conditional tags"
} |
Cannot display comment in page
I added some custom fields in comment, so i have a couple of more fields.
from that form I can comment but am unable to display that comment. The comments are set to moderation so admin have to approve the comments. The value of the new fields are saved on database.
what I've done so far, displayed the comment form via `comment_form()`
But `wp_list_comments( array( 'style' => 'ol' ) );` is not retriving any comments.
Discussion page looks like this  );` should get the comments. But it is not displaying anything.
Any help is appreciated. | I am not sure where you are using the function wp_list_comments but you should use it in the theme comments.php template file and call it using comments_template function.
If you want to display comments anywhere else then you can use function get_comments | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comment form, comments"
} |
Can I run a slow action in a seperate thread?
I have a really slow-running action (30-45 seconds) that loops over each user in my DB and syncs the data with some off-site database. I want this to happen once or twice daily, so I have a WP-Cron job setup to trigger the action.
My problem is that the action isn't essential for rendering the page, so ideally it's something that would run in the background instead of blocking the page rendering.
Is there any built-in system in WordPress that'll do this kind of thing?
One really hacky solution I thought of was to trigger the action via AJAX and just let it run in the background as the user visits the page. It doesn't seem like a good option, so I wanted to hear if you guys have any inputs or thoughts about a cleaner way to achieve this. | Techcrunch has released a library to spawn an asynchronous task within WordPress.
<
Essentially, you can take any process that is triggered by an action hook, and you can defer the processing on that hook to run asynchronously. You extend the class to define which action you are triggering and a couple of functions to prepare_data to pass, and the action to perform. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "actions, cron, threading"
} |
where is the main file in this plugin?
I am looking through a no longer maintained plugin to see if perhaps I may want to revive it:
<
but I cannot identify the main file, the one that would be named after the plugin in accordance with the WordPress Codex Plugin Handbook.
I thought perhaps it was this:
<
but I do not see a plugin header comment with the metadata about the plugin. Is this just a poorly written plugin or am I looking in the wrong place? I reviewed a few different files, I mean, the main file with the plugin metadata comment should not be that hard to find, should it? | The plugin header, and thus main plugin file, is located in rate-this-page-plugin/trunk/rtp-load.php. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Add New Text Box To Wordpress Twenty Seventeen Header
The Twenty Seventeen header displays two text boxes: the Site Title and the Tagline. I would like to add a new text box at the top right of the screen. How can I do it?
I have an active Twenty Seventeen child theme. | That works if you put your code in header.php, copied in the childtheme, after the line:
<header id="masthead" class="site-header" role="banner">
My html code is:
<div class="logo-right-text">
<span style="font-size: 14px; font-weight: bold; color: #555;">1800-123-456-22</span>
<div class="clear" style=" height:3px;"></div>
<span style="font-size: 14px; font-weight: bold; color: #555; ">[email protected]</span>
</div>
And CSS:
div.logo-right-text{ margin: 0px 10px; }
div.logo-right-text { float: right; text-align: right; }
.logo-right-text{ padding-top: 42px; }
But finaly I'll try to put these 2 phone and mail in the menu line... if I find how to do ;) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, css"
} |
RSS Feed has older items at the top
My site's RSS news feed has most of the items expected, but begins with two older items, both of which have pubDate tags with dates well before the rest of the items.
I looked at the revision history for the first post, and it doesn't appear to have been updated.
Does anyone have any ideas why this might be happening? | The reason there are old items at the top of the RSS feed is because they are sticky posts. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "rss"
} |
Adding settings link to plugin doesn't work
I'm trying to add a "settings" link to my plugin on the plugins page. I used this code, which I found on various sites and also in the documentation, but it simply doesn't work (the link doesn't show).
What did I do wrong?
function apd_settings_link( $links ) {
$url = get_admin_url() . "options-general.php?page=my-plugin";
$settings_link = '<a href="' . $url . '">' . __('Settings', 'textdomain') . '</a>';
array_unshift( $links, $settings_link );
return $links;
}
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'apd_settings_link'); | The code is working and tested. Activate your plugin you will see the settings link
add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'apd_settings_link' );
function apd_settings_link( array $links ) {
$url = get_admin_url() . "options-general.php?page=my-plugin";
$settings_link = '<a href="' . $url . '">' . __('Settings', 'textdomain') . '</a>';
$links[] = $settings_link;
return $links;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, settings api"
} |
Make post_content and other custom fields required
What's the best way to set the `required` atribute on html forms in wordpress, for instance I would like post-content to be required, so this code need to be changed:
<textarea class="wp-editor-area" style="height: 300px; margin-top: 37px;" autocomplete="off" cols="40" name="content" id="content"></textarea>
To appear like this:
<textarea required class="wp-editor-area" style="height: 300px; margin-top: 37px;" autocomplete="off" cols="40" name="content" id="content"></textarea>
How can do it by a filter or action hook? This same solution I will also use it for other fields in the publish post form.
What I want is to add the HTML5 `required` attribute on certain fields, once the page has been rendered.
< < | Finally I have solved it as follows:
add_action( 'admin_enqueue_scripts', array($this, 'my_admin_scripts') );
function my_admin_scripts($page) {
global $post;
if ($page == "post-new.php" OR $page == "post.php") {
wp_register_script( 'my-custom-admin-scripts', plugins_url('/js/my-admin-post.js',dirname(__FILE__)), array('jquery', 'jquery-ui-sortable' ) , null, true );
wp_enqueue_script( 'my-custom-admin-scripts' );
}
}
And put the required atribute by JQuery in the next js code (/js/my-admin-post.js):
// JavaScript Document
jQuery(document).ready(function($) {
$('#title').attr('required', true);
$('#content').attr('required', true);
$('#_my_custom_field').attr('required', true);
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, validation, html5"
} |
I want to create a 300 multi-site wordpress network using subdomains
This is the network on this site and i have two multi-sites apart from the main one, what i want to know that, can i create this many multi-sites, without the network crashing or having too much errors or the database itself would crash because of the too much data? | 300 sites within a multisite shouldn't be a problem by itself. Just be aware that things scale out quickly when you are operating that many sites. In particular, the number of posts will grow fast, and depending on the type of site, the traffic can grow fast.
300 empty sites with no traffic can be run on any shared hosting, but as the post count and traffic grows, you'll want to look into more robust hosting options. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "multisite, phpmyadmin, multisite user management"
} |
Wordpress JSON API returns normal site page in html. How do I get it to give me JSON?
For example, entering ` into the browser loads the main site html, the same as omitting the json querystring variable: `
The JSON API is activated. I have tried reactivating and deactivating, checking .htaccess file settings, and deactivating all other plugins. None of those have made much difference so far. | Ok, so the new endpoint for Wordpress 4.7 is mywordpresswebsite.example.com/index.php/wp-json. It's part of Wordpress Core as of 4.7 and not a plugin anymore, there's nothing to be activated. Thank you, Mark Kaplun. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "json, rest api, plugin json api"
} |
Fusion Slider Just keeps loading
I have a fusion slider that just continues to load.
Where this tag `<div class="fusion-slider-loading">Loading...</div>` appears, the spinning circle displays (and won't disappear).
I've read blogs about making sure fusion is up to date. My site is at version 4.7.4 On the update page it reads: "Your plugins are all up to date."
Anyone had a similar issue and know what I could check?
Thank you! | check in the developer tools if all files are being loaded and if any JS errors pop up | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins"
} |
How do I create a user using the new JSON api in 4.7?
I formerly had the JSON API and JSON USER API plugins working before 4.7 and I have seen the documentation at the ReST API User reference, < but I don't know how to get started. I'm sure there is an authentication procedure that must happen first to get a nonce, but I don't know how to do that anymore either. I'd really appreciate it if someone would show me or point me to some example cURL statements and URI's for both getting the nonce and creating a user.
TIA | The REST API included in WordPress doesn't actually have authentication built into it.
If you do normal authentication in WordPress by logging in, then your browser will receive a set of cookies. If you send those cookies along with your request, then that will authenticate you to perform the actions in question.
If you need to add authentication for an external service, then you need to install a plugin to handle it. A few are available:
* <
* <
* <
If you're just testing locally, there is also a Basic Authentication plugin which allows you to simply send your username and password with every request in an Authorization header:
* <
In any case, once you've either gotten the proper cookie or enabled the authentication method, then creating a new user is simple. Send a POST request to /wp-json/wp/v2/users with the username, email, and password as the payload.
You can find this documented here:
<
< | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 5,
"tags": "user registration, json, rest api, nonce"
} |
Custom Plugin Development: What priority should wp_enqueue_scripts have?
What priority should I give `add_action('wp_enqueue_scripts', 'plugin_scripts');`?
Should my plugin scripts and styles load after the theme? Since I don't know what the theme's priority for scripts and styles is, should I arbitrarily select a large number?
In my testing, if I load a stylesheet in both a custom plugin and a custom theme, and don't define a priority for either, the theme seems to take priority and enqueue after the plugin. | Default priorities are fine unless you have special cases where things need to load in a specific order, and even then, you should be defining dependencies for them instead of relying on priority numbers.
Priority numbers are a last resort mechanism, like CSS !important. Avoid setting them unless actually needed. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "wp enqueue script, wp enqueue style"
} |
Relative path not working at all in WAMP local environment
As you can see from below, the logo is in the same folder as header.php. I do the relative image reference in header.php by
img src="logo.png"
Its not working. Please help
; ?>/logo.png" | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "images, html, paths"
} |
How do I edit text displayed on my browser tab?
I want to remove the page name from displaying in my browser's tab. How do I hide the page name and only show the name of my website?
;
add_filter('wp_title', 'filter_pagetitle', 99,1);
function filter_pagetitle($title) {
$title = get_bloginfo('name');
return $title;
}
Or install plugin like Yoast SEO.
* * *
EDIT : Screenshot
; ?></title>` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, page template, html"
} |
Access post from post id in URL
I'm doing unit tests for my plugin, and in my unit test, I check some basic things such as posting a custom post type. My script can create new post, and I can retrieve the ID of the posted item (I'm redirected to an URL like ` so I can deduce that the new post has the ID 16).
From this ID, I'd like to check if the post is as it should be by accessing it via URL, with something like ` but I can't find a way to get directly to my new post using just the ID and without doing any PHP stuff.
Is that possible? | Post can be accessed using post id by passing it as `page_id` query param to `index.php`. e.g.
Or simply
| stackexchange-wordpress | {
"answer_score": 16,
"question_score": 10,
"tags": "posts, urls, unit tests"
} |
Disable wp_enqueue_style for theme on wp-admin
At this moment I use functions as described in the "Theme handbook" from the WordPress site. The problem is that the stylesheet is loading on the backend pages too and it affects the layout of the backend pages. This behavior is not wanted.
The code I use to load the stylesheet -> <
Does anyone know a way/method to load the stylesheet only on the frontend so the wp-admin backend does not get affected?
Note: The CSS is compiled with scssphp when the $dev variable is set to true. | There is a conditional tag `is_admin()` which checks are you in the Administration Panel or Frontend. So,
if( !is_admin() ) {
wp_enqueue_style(
'css-minified',
get_stylesheet_directory_uri() . DIRECTORY_SEPARATOR . 'style.css',
[],
null,
'all'
);
wp_enqueue_style(
'font-awesome',
'
[],
null,
'all'
);
}
See is_admin(). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development, wp enqueue style"
} |
Upload files to the plugin menu
I'm currently trying to build a wordpress plugin. I'd like its users to be able to add an upload file to the settings field menu of my plugin and then to be registered into the wordpress database, is there some way to do that? | I think I've been down that road. Take a look at `wp_handle_upload`, which will upload your file to the /uploads directory and then `wp_insert_attachment` and `wp_generate_attachment_metadata` to list said upload in the media library as an attachment which will 'register it in the wordpress database'. Then you can query attachments like this:
$attachments = get_posts( array( 'post_type' => 'attachment') ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Stop editor from adding “amp;” after every “&”
The WordPress editor keeps adding “amp;” after every “&”.
This effectively breaks all my custom links. How can i stop this? I don’t mind all the others things the editor does to the formatting i just need it to stop adding “amp;”. Is there a filter i can use? | One solution is to hook into `wp_insert_post_data` and do some regex magic to replace all instances of `&` with `&`:
// when saving posts, replace & with &
function cc_wpse_264548_unamp( $data ) {
$data['post_content'] = preg_replace(
"/&/", // find '&'
"&", // replace with '&'
$data['post_content'] // target the 'post_content'
);
return $data;
}
add_filter( 'wp_insert_post_data', 'cc_wpse_264548_unamp', 20 );
You will obviously only see changes when a post is saved/updated. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "tinymce, visual editor, wp editor, wysiwyg"
} |
Why word <newline> can't be displayed in wordpress?
The content is simple.
it is a test
\n=<newline>
 this is fairly simple.
You can just do like this =
<div class="container">
<div class="row">
<div class="site-branding">logo 1</div>
<div class="secondLogo">logo 2</div>
</div>
</div>
*menu goes here*
first div you give :
.site-branding {
float: left;
margin-bottom: -30px;
width: 110px;
}
Second div :
.secondLogo {
float: right;
position: relative;
}
; ?>
</div>
</div>
<div class="row">
<div class="col-md-10 col-xs-12 col-centered">
<?php
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile; // End of the loop.
?>
</div>
My CSS
.col-centered {
float: none;
margin: 0 auto;
}
img {
margin: 0 auto;
} | The image is probably not display:block (they are inline by default), and so using margin: 0 auto won't do anything.
Try either adding text-align:center to your .col-centered, or setting your image tag to display:block (with margin: 0 auto).
Best I can do without seeing more of the surrounding styles. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, twitter bootstrap"
} |
Getting all custom posts with a certain category
I'm apparently retarded, and i have a hard time figuring out a simple task as getting all posts with a certain category. I tried:
* query_posts()
* New Query()
but im struggling to get something out of them
$args = array(
'post_type' => 'fb',
'fbcate_category' => array(35),
'order' => 'DESC',
'posts_per_page' => -1,
);
$posts_array = new WP_Query($args);
I've tried similar with query_posts(), but I don't get anything out except a empty array of that either. | `$blabla = new Query($args);` should be `$blabla = new WP_Query($args);`
**UPDATE** Your actual code should be something like:
$args = array(
'post_type' => 'fb',
'tax_query' => array(
array(
'taxonomy' => 'fbcate_category',
'field' => 'id',
'terms' => '35',
),
),
'order' => 'DESC',
'posts_per_page' => -1,
);
$posts_array = new WP_Query($args);
Where `taxonomy` is your taxonomy name.
Let me know how it goes. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "custom post types, wp query, categories"
} |
Add to Cart button woocommerce background and with doesn't display correctly
I have a problem with Add to Basket background and width display on mobile phone. I do not know why it has been like that.
Can you guys checkout my website < and let me know how I can fix "ADD TO BASKET" button, which is displaying not correctly ( the background of the left is white). Thanks and look forward to hearing ideas from you guys.
Thanks | You have to add `background-image: none !important;` to your buttons CSS.
Complete CSS-Rule:
@media screen and (max-width: 767px) {
a.button.product_type_simple.add_to_cart_button.ajax_add_to_cart {
background-image: none !important;
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "css, woocommerce offtopic"
} |
programmatically create posts from files in a folder
I have a folder named 'pdf' (with around 1000 pdf files) in my uploads directory, i would like to create a post for each file in the folder.
I am not trying to import the content from the pdf but simply create a post for each file in that folder.
**What i was hoping to achieve:**
the posts would get the title from the filename.
the posts would be assigned a single specific category/tag for all the posts.
the post would get the publish date from the file creation date.
I am new to php, wordpress and programming in general, I have a decent understanding of the syntax, loops and functions. I was hoping someone could give me a nudge in the right direction as to what wordpress functions / php loops would be helpful to achieve this. Any thoughts, guidance, information would be a huge help.
Many thanks for your time and help, Sam | At first you have to use `readdir()` in a while loop to get all pdf files. You should look at the examples on the readdir page to know how to use it. Inside the loop you have to add the posts with the pdf files. Normally you would use `wp_insert_attachment()` to add files to your blog. But if you want a single post for each pdf which is shown on your homepage you have to use `wp_insert_post()`, where the argument "file" contains the path to the file. After adding the post (but also in the loop) you have to use the id, which comes back from `wp_insert_post()`, you have to add the category using `wp_set_post_categories`.
I could provide you the whole code to perform this task, but in my opinion it is better to learn it by writing the code yourself. If you have further questions don't hesitate to ask. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "uploads, customization"
} |
Is there a way to determine if the media-iframe is visible?
My plugin adds a tab to the media iframe and I need to know when it is running within the iframe. Using jQuery('#media-iframe').is(':visible’) does not work. Any ideas? | I came up with a way to do it:
1. Add an element to the contents of the frame such as a text input with and ID (i.e. 'search_text')
2. In the plugin's CSS file, style the element to be visible only when it is displayed in the frame:
#search_text {
display: none;
}
#media-upload #search_text {
display: inline;
}
3. Test if the element is visible:
if(jQuery("#search_text").is(":visible")) { } | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "media library"
} |
buddypress activity social share
Hello Guys I am using buddypress and I am sharing activity on social network like facebook and google and I am using url like
. $activity_title . '&u;=' . $activity_link . '
buy when facebook crawls the page it is not logged in so it redirects to home page so instead of sharing the image and title of that activity what shows on the facebook is the image and title of home page.
activity title and link shows correct in the link but when you share it shows the content of home page | So I have figured it out instead of giving the ids of your activity you have to create a page and pass the id in a get parameter and put a condition in it so that only the facebook or twitter crawler can access it on that page according to the activity id show the content on the og tags. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "buddypress, social sharing, logging"
} |
Enqueue Style Only On Certain Pages Not Working
I am trying to enqueue Bootstrap's CSS only on two pages.
Here's the code I have in my `functions.php` file:
function bootstrap_css() {
if (is_page('who-we-are-2') || is_front_page()) {
wp_enqueue_style('bootstrapstyle', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
}
}
add_action('wp_enqueue_scripts', 'bootstrap_css');
From other StackExchange questions and Googling, that code should work. It works for the home page, but not on the "who-we-are-2" page. What's odd is `is_page('who-we-are-2')` doesn't work by itself. I have also tried `is_page(32365)` and `is_page('32365')`, 32365 being the page ID to no avail.
Any help would be greatly appreciated! | UPDATE: It looks like it has something to do with the URL. For some reason I can view the page at /who-we-are-2 and it looks normal, minus the scripts/styles I am trying to enqueue. But the page should really be at /about/who-we-are-2 as About is the parent page. If I go to /about/who-we-are-2 it works perfectly. /about/who-we-are-2 is what is in the nav and the URL that users will see so we're all good. And obviously my enqueue wouldn't work on /who-we-are-2 since my `if` statement didn't call for that page. So ultimately, problem solved. But I'd love to know why I can view the page at /who-we-are-2 if anyone knows! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, wp enqueue style, css"
} |
WordPress call_user_func_array() expects parameter 1 to be a valid callback, class
I am not the Plugin or theme developer, but after updating the Better AMP , I discovered the following error log. What could be the reason? Is there any manual solution to this?
> [24-Apr-2017 19:15:08 UTC] PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'Better_AMP' does not have a method '_return_false' in /wp-includes/class-wp-hook.php on line 298 | This is a problem with the Better AMP plugin. Best to do is report it to the plugin developer.
There is an invalid filter hook in the plugin, for a quick fix you can try to modify the file `wp-content/plugins/better-amp/better-amp.php`.
Change line 1197 and 1198:
// From:
add_filter( '...', array( $this, '_return_false' ) );
// To:
add_filter( '...', '__return_false' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, php"
} |
WooCommerce restore stock on order cancel
I have built an store on WooCommerce, I've used WC Cancel Order plugin to implement Cancel Order functionality for COD as well. But when any user requests for cancellation and even after it's approved by the admin, the quantity of the product does not restore. | I tried WC Cancel Order recently and it worked. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
Change title slug or separator in WordPress
I have added `add_theme_support( 'title-tag' );` function in theme setup in my functions.php now it shows the title as:
title-WordPress
I would like it to be changed as follows:
title | WordPress | To change the title separator, you'll need to use this filter document_title_separator which was introduced since WordPress 4.4.0.
Here's how you can customize the separator:
apply_filters( 'document_title_separator', 'your_custom_separator' );
function your_custom_separator( $separator ) {
$separator = '|';
return $separator;
}
Hope this helps.
**Updated Answer**
add_filter( 'document_title_separator', 'your_custom_separator' );
function your_custom_separator( $separator ) {
$separator = '|';
return $separator;
}
I've tested this with Twenty sixteen theme.
What I expect : the API should only return the posts more recent than `2016-10-13`. Right now, the filter seems to be ignored.
Any idea? | As of WP >= 4.7 `filter[]` is not supported and have been removed. Also WP REST API Plugin became part of WordPress Core.
According docs your link should be:
**EDIT**
As enguerranws mentioned the date should be in ISO8601 format | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "api, rest api, wp api"
} |
Woocommerce cart displays outdated prices
I'm facing the following situation on a fresh WooCommerce installation. Have added a custom field on product brands, to allow administrators set a discount on all products of a selected brand.
The discount displays nicely everywhere (category pages, custom loops, single page, variable products etc), but when a product is added to cart, its initial price is displayed instead at the totals section.
Have tried to hook on the `get_price()` \- which calls the `get_prop()` \- using `woocommerce_product_simple_get_regular_price` filter, but for some strange reason the filter doesn't get applied!
Already validated that the `context` parameter has a value of `view`, so the filter should be applied, but...
Initially thought this is a session/cache issue and tried incognito mode, other browsers, other devices etc, but that doesn't seem to be the issue.
Any thoughts on this? Thanks in advance
Using Wordpress 4.7.4 and WooCommerce 3.0.4 | It's a typo! Instead of using the `woocommerce_product_simple_get_regular_price` I had to use the `woocommerce_product_simple_get_price` filter.
Hope this helps someone | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "woocommerce offtopic"
} |
ERR_TOO_MANY_REDIRECTS on wordpress page
Hi Im developing a page in wordpress but not working on https, when I try to access show me this error:  || false !== strpos( $url, 'wp-login' ) ) {
define( 'DB_NAME', 'SLAVE_DB_NAME' );
define( 'DB_USER', 'SLAVE_DB_USER' );
define( 'DB_PASSWORD', 'SLAVE_DB_PASSWORD' );
define( 'DB_HOST', 'SLAVE_DB_HOST' );
} else {
define( 'DB_NAME', 'MASTER_DB_NAME' );
define( 'DB_USER', 'MASTER_DB_USER' );
define( 'DB_PASSWORD', 'MASTER_DB_PASSWORD' );
define( 'DB_HOST', 'MASTER_DB_HOST' );
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "database, security"
} |
How to send messages when a customer is registered
I am trying to send `MESSAGES` when a customer is
Registered or he/she
Reset his/her password
Or any specific events that will be decided later .
I have an SMS API.
Suggest some step.
I just want to know how to trigger the API when a customer registered. Is there any hook available by which i can trigger my custom function.
**UPDATE : My Problem is solved & Thank You @TomC**
if ( is_user_logged_in() ) {
$user_id = get_current_user_id();
$registration_field_1 = get_user_meta( $user_id, 'registration_field_1', true );
$smsDone = get_user_meta( $user_id, 'smsDone', true );
if(!empty($smsDone) && $smsDone === 'True'){
}else{
$respuesta = wp_remote_get( "
update_user_meta( $user_id, 'smsDone','True' );
}
}
I used this method to send the sms once a customer is registered. | If you're talking about Wordpress user registration, you want to start by reading about the User Register hook: <
Then your code would be something like this which will automatically fire each time a user registers on the site:
add_action('user_register','send_sms');
function send_sms($user_id){
// Code for your SMS API Here
}
The code would go in a plugin or in your Theme's `functions.php` file. If you're talking about an ecommerce plugin, you need to see what action hooks they have available for customer registration and use that as per the developer documentation. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 0,
"tags": "api, user registration"
} |
Showing content to specific BuddyPress Member Types
On my project I'm using BuddyPress Member Types. The problem is I would like to display specific content to each member type. Something like; website checks Member Type based on logged in user id and then it shows a piece of content based on the member type.
Has anyone tried this? If so can you pint me in the right direction?
_Note_ This is a core BuddyPress feature, I will not be using any membership plugins to achieve this. | Your answer is on the codex page link in your question.
// Get the member type of user 5412.
$member_type = bp_get_member_type( 5412 );
So you could do something like this:
$member_type = bp_get_member_type( get_current_user_id() );
if ( $member_type == 'dog' )
echo 'Bark'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "buddypress, membership, members"
} |
Child Theme CSS not showing at all
I have a child theme that is not showing my CSS changes at all. When I inspect element, the changes don't show in the explorer window. I look in the head and the child theme style is not enqueuing.
Child functions.php:
<?php
add_action( 'wp_enqueue_scripts', 'enqueue_parent_theme_style');
function enqueue_parent_theme_style() {
wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
}
Child style.css:
/*
Theme Name: Jevelin Child
Description: Child theme for Jevelin theme
Author: Shufflehound
Author URI:
Template: jevelin
Text Domain: jevelin-child
*/
/* Add your custom CSS below */
I have no idea what the culprit could be. | Please use this instead of what you are using. This will definitely work.
<?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
**For more details on configuring Child themes in WordPress please refer to thislink.** | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "css, child theme, wp enqueue style"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.