INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Where's The Best Place to use Register_Shutdown_Function()?
I want to use Register Shutdown Function to track Fatal Errors, my question is, where's the best place to call this so it hits both WordPress, Plugin, and Theme Fatal Errors? | WordPress core register a shutdown function on its own (source) the function `shutdown_action_hook` registered to be ran on shutdown, call
do_action( 'shutdown' );
and little more (source).
So, if you want to register a shutdown function in _WordPress way_ just add your function on 'shutdown' hook:
add_action( 'shutdown', 'my_shutdown_callback' );
function my_shutdown_callback() {
error_log('Goodbye');
}
Where to put this code is not very important, a plugin, a mu plugin, functions.php, it doesn't matter, it will run always on shutdown...
Of course register it as soon as possible allows you to catch early errors, so using a mu plugin you can catch errors that happen on plugins init. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "debug"
} |
username_exists() function can't be access without logging in
I'm using the following function in functions.php to check if a username exists in the DB
function check_username() {
$username = $_POST['user'];
if ( username_exists( $username ) ) {
$return['user_exists'] = true;
}
else {
$return['user_exists'] = false;
}
echo json_encode($return);
die();
}
add_action('wp_ajax_check_username', 'check_username');
The problem is that the `username_exists()` function only seems to work if a user is already logged in and checks a username. I tried to check for an existing username without logging in and it just returns `undefined` for me.
I have no idea why this is happening and can't find any documentation about this issue.
My question is, how do I enable a user to check if a user exists without having to log in?
Thanks | When using Ajax API, and you want to make the ajax callback available for non-logged users, you need to add 2 actions, `"wp_ajax_{$action}"` and `"wp_ajax_nopriv_{$action}"`.
Using only the first action, the callback will be called only for logged users, using only the second it will be called only for non-logged visitors.
Try this:
function check_username() {
$uname = filter_input( INPUT_POST, 'user', FILTER_SANITIZE_STRING );
wp_send_json( array(
'user_exists' => get_user_by( 'login', $uname ) ? 'true' : 'false'
) );
}
add_action('wp_ajax_check_username', 'check_username');
add_action('wp_ajax_nopriv_check_username', 'check_username'); | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 5,
"tags": "php, functions, ajax"
} |
Wordpress capabilities and restricted categories access
I've a Wordpress blog to share content with some people only. Users has to login to access this website.
I created new roles and new capabilities on this blog.
I've got some articles which belongs to a certain category that I would like to share only with people with a certain role.
Is there a hook I could use when somebody request an article, and where I could test if the curent user has the good capabilities, and so modify the request if needed? | I think best hook should be `'template_redirect'`, when this hook is fired main query is already set, so you can look at queried object and if the user has no required capability you can redirect request _somewhere_ :
add_action( 'template_redirect', function() {
if (
(
is_category( 'special-category' )
|| is_singular() && has_category( 'special-category', get_queried_object() )
) &&
! is_user_logged_in() || current_user_can( 'special-cap' )
) {
wp_safe_redirect( home_url() );
exit();
}
} ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "hooks, user roles"
} |
https redirect hell (adding www)
I migrated my multisite wordpress website (www.example.com) to a subdomain (dev.example.com) to work on some big changes. Of course, I changed _siteurl_ and _home_ in the DB for all sites.
The problem is whenever I go to < I get redirected to a non existing <
I can't figure out where this www is coming from (and it is not .htaccess). This is driving me nuts. After hours of google, I finally decided to reach out for help.
Thanks! | In case anyone has a similar problem the answer was a lot more complicated than I thought. It turns out that NameCheap (my hosting company) installed a different SSL cert incorrectly. It was causing a redirect to another site, which applied it's .htaccess rules, adding the "www". | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "multisite, redirect, https"
} |
Show meta box only when post is being published first time
I'm creating a WordPress plugin where it is required to show the meta box only when a post is being published for the first time.
The only way I can think of is to show the metabox iff there is no $_GET['post'] parameter set(it represents the post ID), but then meta box will not be visible for the posts which are in draft.
Is there any way to determine if the post has been published before? | I haven't tested this but the idea is to check the post status, if the post is not published, show the metabox otherwise don't.
function non_publish_metaboxes() {
global $post;
if(!isset($post))
return;
if($post->post_status !== 'publish'){
// ... Show Metabox
}
}
add_action( 'add_meta_boxes', 'non_publish_metaboxes' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, metabox"
} |
Modify main loop in taxonomy archive page
Is there a way that I can modify the main loop in a single taxonomy template, but leave it untouched in every other template?
In this case, I have a custom post type called "Events" which in turn has a custom taxonomy called "Region". What I want to do is, instead of listing each custom "Events" post chronologically by post date I want to order it by a custom meta value (In this case `event_date`).
I only want to do this in my `taxonomy-region.php` template and leave any other instance of the main loop untouched. | You could hijack the `$query` just before fetching the posts.
function wpdev_156674_pre_get_posts( $query ) {
if (
$query->is_main_query()
&& $query->is_tax( 'region' )
) {
// Manipulate $query here, for instance like so
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'meta_key', 'event_date' );
$query->set( 'order', 'DESC' );
}
}
add_action( 'pre_get_posts', 'wpdev_156674_pre_get_posts' );
**References:**
* `pre_get_posts` action hook
* `WP_Query` class | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "custom taxonomy, loop"
} |
Custom post type - two taxonomies
I would like to have a page dedicated to gathering plants in nature. So lets say that in march and april it is possible to pick nettle leaves, while in september and october its root should be gather.
So I did a custom post type for a plant and two taxonomies - Months and Plants-part.
Is there a way to connect both taxonomies on the same post while still staying separate? Because I would need to fetch data based on a month.
Ocasionally, there would be a need for multiple data for same plant, for example
Some plant / latin name / tips
- roots -> october
- fruit -> march, april
- leaves -> august
- seeds -> september | It makes sense that each attribute should be a taxonomy - eg roots, leaves, seeds - but you don't need a separate taxonomy for months. Instead, the months should be the terms of these taxonomies.
The second argument to `register_taxonomy` in each case should be the name of your custom post type. This will mean you'll get a box for each taxonomy on the 'Edit Plant' screen. And in each box, a list of months (you'll need to populate this yourself).
Obviously this makes it straightforward to get the months of interest with respect to a certain plant, but it's perfectly possible to go the other way. For instance, if you wanted to get all of the plants which were of interest in a given month, you could construct this query quite easily. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy"
} |
Removing user contact methods works from functions.php but not from a plugin
I'd like to remove user fields and I used this code:
add_filter( 'user_contactmethods', 'newfields' );
function newfields( $user_contact ) {
unset($user_contact['facebook']);
unset($user_contact['twitter']);
return $user_contact;
}
If I use this code in `functions.php` of my theme, it works, but if I use this code in a plugin, it doesn't work.
Why? How can I resolve it? | This could be the matter of adjusting the _priority_ of your filter callback, since the plugins files are executed before the `functions.php` theme file. That could explain why it works in your `functions.php` file, if the priority is the same.
When you add the code snippet to a plugin, it might be executed before the other plugins that use the same filter.
The default priority is `10`, so you should try something higher in your plugin code, for example:
add_filter( 'user_contactmethods', 'newfields', 99 );
or even
add_filter( 'user_contactmethods', 'newfields', PHP_INT_MAX );
if you want to be absolutely sure your filter callback is the last one to be executed - assuming the other plugins are not using `PHP_INT_MAX` as well.
But better yet, just check the priority the `user_contactmethods` filter callbacks the other plugins are using. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, functions, filters, users"
} |
Customise search form in the Widget
I would like to customise the Search Form that you drag and drop from the widgets panel.
The customisation will be more than just css changes. I would like to add and custom classes. Is this possible?
Is there a hook to customise the Search Field?
The only option I can think of is to create a custom search widget. | if your theme have not `search-form.php` file then you will create the file and add the custom css there. Because search widget is calling the **get_search_form()** function. First it will search the `search-from.php` file from activated theme folder. If there have no file then it will call wp's default search form.
See the Codex | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "customization, widgets, search"
} |
What's the best approach to do this?
I want to start a new site where I want the main page to be a static page showing information about myself, a kind of resumee without personal details.
Then, there would be a `site.com/blog/` where I occasionally write to demonstrate the skills listed on the static page.
Finally, I want all of this to be in English and Spanish.
* * *
So far, I changed the static front page to "About me" and then I created a new empty page "Blog", and chose it as posts page. When I click on "Blog", I get to the posts page but the URL looks like `/?page_id=11`. I would like it to look as I said before (`/blog/`).
About the language, I see there are multiple plugins that translate the content. I'm interested in write it by myself, and the only plugin that seems to allow this is qTranslate, which doesn't work with the latest WP version. The only idea that comes to my mind is to do two separate installations on `site.com/en` and `site.com/es`. What else could I do? | about the permalinks you should go to settings->permalinks and change permalinks to "post name". then you can see "/blog/" for your blog page. for translating your theme you dont need any plugins. you should work with .po files. go to your theme folder and then "languages". there you can see translation files inside this folder. you can create your own translation files but actually you need a software like "poedit". it's free to download and use. good luck | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, multi language"
} |
Show only first children level of current category?
I wish to display only first level of subcategories on current category page (if any).
I tried this code:
<?php
$args=array(
'child_of' => $cat-id,
'hide_empty' => 0,
'orderby' => 'name',
'order' => 'ASC',
'depth' => '1' //NOT WORKING
);
$categories=get_categories($args);
foreach($categories as $category) {
echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'; }
?>
But, it shows all children, and children's children (grandchildren). I tried with "'depth' => '1'" but it is ignored.
How to show only first level of children (if exist) on category page? | You are using get_categories() function and this function have not ' **depth** ' argument. Also php is not supporting `$cat-id` variable. it would be `$cat_id`.
So try this kind of code:
$cat_id = get_query_var('cat');
$args=array(
'parent' => $cat_id,
'hide_empty' => 0,
'orderby' => 'name',
'order' => 'ASC'
); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "categories, children"
} |
Editor access to menu: custom post type missing
I have used this code;
$roleObject = get_role( 'editor' );
if (!$roleObject->has_cap( 'edit_theme_options' ) ) {
$roleObject->add_cap( 'edit_theme_options' );
}
to add menu access for editors.
I have a custom post type 'Masterclasses". That appears correctly in the Administrator's Menu editing page but doesn't appear in the Editor's Menu editing page.
How do I add this? | As ever, when you know the answer it's maddeningly simple. The custom post types were there all along, together with their taxonomy. All posts are absent from the menu editor and have to be turned on in Screen Options.
I pressed the button and lo, there they were. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "custom post types, menus, editor"
} |
Development before domain name chosen
I have a new customer who hasn't chosen a domain name yet but I need to start development for him using a subdomain of my domain. I'm on Bluehost using add-on domains and subfolders. Is there a way to convert the permalinks in the content easily? Can they be changed with SQL once he's selected a domain name? | You can use the Search and Replace plugin to fix the URLs once the new domain is chosen.
Likewise, plugins such as BackupBuddy (paid) or Duplicator (free) -- which are very useful for backup, possibly coupled with migration to another server or domain -- also perform this search-and-replace operation. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, pages"
} |
WordPress 4.0 beta - how to change the link URL in RSS feeds
I am using WP 4 beta and have a site at blah.com/blog but I display the posts on my site at blah.com/articles
I want all of the URLs in my RSS feed to use my site URL. Following what was mentioned here: Change the link URL in default RSS feeds
I added this filter to the bottom of plugin.php (add_filter doesn't work in functions.php in 4 beta because it's defined in plugin.php which is loaded after functions.php, I found out)
add_filter( 'the_permalink_rss', 'wpse_96602_change_feed_item_url' );
function wpse_96602_change_feed_item_url( $url )
{
return str_replace('/blog/','/article/',$url);
}
But this hasn't worked. What do I need to do? Thanks in advance :) | It was because my blog is at blah.com/blog but I use the WP API to actually display blog posts on another page on my site. Setting the priority of the filter to PHP_INT_MAX fixed the problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, rss, feed"
} |
I want to edit the search function
I'm changing some parts of WordPress, like adding posts or comments, to use procedures in the database instead of using inline database calls to see if the performance enhances. I've been looking the search function now, but I can't find the code for it, the select string more importantly.
Anyone who can help me locate where the code for the search function is (like searching for posts or comments not the archive)? Thanks in advance. | Basically everything query-related is in `wp-includes/query.php`. Search for the `parse_search` function in that file and the `posts_search` and `posts_search_orderby` filters. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "search"
} |
Get latest post from all categories except one
I trying to get all the latest post from every category, but I discovered I must ignore one of them. I don't want to show it at all. My problem is I don't know what syntax to write `ifelse` in this code.
Here is my code :
<?php
while($i<count($output_categories)):
$latest_cat_post_6 =
new WP_Query( array('posts_per_page' => 1,'category__in'=>$output_categories[$i]));
if($latest_cat_post_6 == 48){
//do nothung
} else {
if( $latest_cat_post_6->have_posts() ) :
while( $latest_cat_post_6->have_posts() ) : $latest_cat_post_6->the_post();
}
?> | Your code doesn't make sense to me. The easiest way to do this is to use `get_categories()` to get all the categories, and use the **`exclude` parameter to exclude the category that you don't need**. You can then feed that back into a new `WP_QUERY`
Example
$categories = get_categories( 'exclude=ID_OF_CATEGORY')
foreach ($categories as $category) {
$new_query = new WP_Query( 'posts_per_page=1&cat=' . $category->cat_ID );
if($new_query->have_posts()) :
while($new_query->have_posts()) : $new_query->the_post();
// YOUR LOOP ELEMENTS
endwhile;
wp_reset_postdata();
endif;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, posts, categories"
} |
Cloning the last few posts & comments only
I cloned an entire WP site to a different location a few weeks ago. The new site is being redesigned (but keeping the same content). In the meantime my client posted new posts with comments from her readers.
What's the easiest way to clone those last few posts and comments? If the solution involves PhpMyAdmin, which tables will I be working with? | The easiest solution would be to use the WordPress export tool. Here you can chose a category and date range so you only export the latest ones. Posts should export with their comments too. Here is a link to the WordPress codex.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "clone site"
} |
Missing argument 2 for wpdb::prepare() Issue
I'm having to update a WP installation for a community organisations from version 2.9.1 to the current 3.9.1.
The installation has a couple of custom built plugins that aren't documented.
I've just performed the WP version update and now I see a warning (Missing argument 2 for `wpdb::prepare()`) on every page that relates to the following line in the code of one of these custom built plugin:
$rows = $wpdb->get_results($wpdb->prepare("SELECT id, name FROM ".$table_name));
From what I've read online, this is due to a change in the coding, that requires 2 values to be sent to `wpdb::prepare()`, but I've no idea how the line of code given above, needs to be changed.
If someone could help me out, I'd really appreciate it. | That was not exactly change in code, that was change to better inform people they are not using the method correctly.
In line with wpdb documentation you need to properly pass values, or they won't be properly escaped in query.
In your case it would turn into something like:
$wpdb->prepare("SELECT id, name FROM %s", $table_name)
Note that if `$table_name` isn't coming from any untrusted input, then there is no need to prepare query in _such_ case altogether. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, upgrade, wpdb"
} |
Fatal error: Call to undefined function reset_mbstring_encoding
I see the message when trying to access wp admin at localhost:
Fatal error: Call to undefined function reset_mbstring_encoding() in Z:\home\localhost\www\k-gayduk.ru\wp-includes\class-http.php on line 251
I suspected plugins, however, nothing has changed when turned all of them off.
Any thoughts? | Do a complete update of WordPress, including all the files. The function named "reset_mbstring_encoding" is in the wp-includes/functions.php file and has been since 3.7, so if you're missing it or some other file, then you need to make sure all the WordPress files are up-to-date. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "fatal error"
} |
Looking for a plugins for organization portal (Staff, Units, Departments)?
I am looking for a plugin for internal organization portal that will display all the member of
the organization also the hierarchy between the differents units and departments.
Also I will be able to move one person from one departments to another.
if someone know of such a plugin or could guide me to how to solve it will be great. | the best thing that exists as a plugin for you to use is "buddypress"
this plugin has a lot of features for interacting users with each other but i think it's not exactly what you need! but the good news is buddypress itself has a lot of plugins to install! first install buddypress on your wordpress site and then try its free plugins. better than nothing i think! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugins, custom post types"
} |
menu_class showing up on DIV instead of UL
I was having an issue where my menu was being created using:
wp_nav_menu(array('theme_location' => 'main_menu', 'menu_class' => 'sf-menu''))
The resulting HTML was like this:
<div class='sf-menu'><ul><li...></ul></div>
As you can see, the `$menu_class` argument was being applied to the div instead of the ul. And the ul doesn't even have an id attribute despite using the default `items_wrap`. | The reason this was happening was simple - I had just installed the theme and had not yet associated a menu with the 'main_menu' theme location. Once I had the menu assigned, the markup generated acted as expected.
To assign a menu, go to Appearance > Menus then select the Manage Locations tab. On there you can choose which menu goes with the theme location. Save your changes and the markup should then be correct. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
Possible to switch between admin view and author view?
The wordpress admin dashboard can be a bit daunting for "normal" wp authors.
Is it possible for users who need admin privileges to only see the simpler author view, but be able to switch to the full admin dashboard when required?
I understand we could simply create another author account for them. Or use a plugin to create a unique dashboard for each user type.
But is it possible to switch between admin / author dashboards at will, without having to log out and then back in again as a different user? Thanks | It is just easier and much more secure to have an admin user which **is not** an author, and use plugins like < to switch if there is something that can't be solved with having two browsers open at the same time ;) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "author, admin menu"
} |
How to disable the "Your site has updated to WordPress x.y.z" admin email?
Using the automatic update of my self-hosted WordPress blogs, I configured automatic updates of both the WordPress core as well as WordPress plugins and themes (through this plugin).
Whenever a core update occurs, I get an email like:
> _Your site has updated to WordPress 3.9.2_
>
> Howdy! Your site at < has been updated automatically to WordPress 3.9.2.
>
> No further action is needed on your part. For more on version 3.9.2, see the About WordPress screen: <
>
> If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help. <
>
> The WordPress Team
I understand that I can completely disable administrative notification emails but I would prefer to only disable the above notification.
**Therefore my question is:**
How to disable update notification emails in WordPress? | In your `functions.php` add:
add_filter( 'auto_core_update_send_email', '__return_false' ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 6,
"tags": "admin, email, notifications, automatic updates"
} |
Overide enqueue in non plugable function via child theme
I am trying to override a non-plugable function using the information on this page but it seems to have no effect. Can anyone see what's wrong.
My code is
remove_action('wp_print_styles', 'az_enqueue_dynamic_css');
function childtheme_dynamic_css() {
/* I don't need to actually add anything so this is just a placeholder */
}
add_action( 'wp_print_styles', 'childtheme_dynamic_css' ); | My guess would be that you are remove the action before it is actually being added in the parent theme.
The parent's theme functions.php file gets loaded after the child one so it looks like your removing something that is not there yet.
The 3rd parameter in remove_action() is the priority. Try playing around with that number - the default is 10 - to see if there is any change.
remove_action() also returns a boolean so you can debug it with
var_dump( remove_action('wp_print_styles', 'az_enqueue_dynamic_css') );
I am assuming as well that you have the action and method names exactly as they appear in the parent theme :)
Hope this helps | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "theme development, actions, wp enqueue script, child theme, pluggable"
} |
How can LDAP/Active Directory be integrated in WordPress?
I know there are a few plugins. I need to more than likely roll my own. But, I don't know enough about the WP security infrastructure. Where does WP authorization and authentication code go? I'm not really asking about a broad spectrum here, just a very basic answer to where the code is to begin editing so it looks at my AD. | Best thing is to learn as much as you can from the available plugins even if they are not a perfect match to your requirements. This will help you identify areas of functionality which you will need to handle.
As for coding itself, for the authentication part you will most likely need to override the `authenticate` filter which lets you do user/password authentication before wordpress tries by itself.
Authorization can be a complex beast and I am not sure what kind of it you will need so can't even guess what will be useful. You most likely will need to get familiar with user roles and permissions. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "authentication"
} |
How to force Wordpress to add new images at the beginning of the gallery?
I have the standard gallery embedded in the page and want to add new images to it. When I select images and click `Add to gallery` button Wordpress adds them at the end. How to force it to add images at the beginning (top)? | I just fixed this after several hours of research. If one need to do the same thing, he must edit file `wp-includes\js\media-views.js` and replace `add` with `unshift` in this line (#2611, galleryAddToolbar):
edit.get('library').add( state.get('selection').models );
So the code will look like this:
edit.get('library').unshift( state.get('selection').models );
After that when you add images in the gallery they will appear at the top. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "images, gallery"
} |
How to query WP Multisite primary site link
Currently I have created a multisite for my client. Within the network, there are a (primary)corporate site, a newsbites site and a blog site. Is there a way to query the primary site link, so that newsbites and blog site can connect back to the (primary) corporate site, without hard coding the site url? | Use `network_home_url( $path = '', $scheme = null )`.
You can see it in `/wp-includes/link-template.php`.
Examples:
// Root of main site
$network_home = network_home_url();
// About page on main site
$network_about = network_home_url( 'about/' );
In a network, the main site has always the same ID as the network ID. `network_home_url()` uses `get_current_site()` which return the global variable (sigh) `$current_site`, an instance of `stdClass`. This one is filled in `wp-includes/ms-settings.php`, which in turn is loaded in `wp-settings.php` **before** mu-plugins are loaded.
So you can rely on it in your plugin or theme. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "multisite"
} |
WordPress Twenty Fourteen Theme Sidebar
The Twenty Fourteen theme was used to create the basis of my own child theme. It's been pretty easy to override, but the left sidebar is proving difficult.
I don't want to remove the sidebar completely, but nothing I do in the CSS file allows me to get rid of the black bar. Even removing the sidebar from a template file leaves an empty black strip where the sidebar used to be.
Has anyone found a way to peacefully override this without throwing out the whole system? | The sidebar is created in two different places:
* The black strip is created from `.site:before`, check line 3910 of style.css
* `#secondary` actually displays the sidebar information, check line 3923 of style.css
`.featured-content, .site-content, .site-main .widecolumn` provide left padding to the content area should you wish to dispose of that too. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "css, sidebar, child theme, theme twenty fourteen"
} |
Custom Menu url is Empty
I added a new menu using this code:
wp_update_nav_menu_item($menu->term_id, 0, array(
'menu-item-title' => 'Custom menu',
'menu-item-url' => '
'menu-item-db-id' => 0,
'menu-item-object' => 'custom',
'menu-item-parent-id' => 328,
'menu-item-type' => 'Custom',
'menu-item-status' => 'publish',)
);
That code generates a menu the way I wanted. But the link is totally empty. What did I do wrong? | Your menu type is:
'menu-item-type' => 'Custom',
But if we look in `wp_update_nav_menu_item`:
if ( 'custom' != $args['menu-item-type'] ) {
`custom != Custom`, so your URL gets stripped | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "menus"
} |
Set default link type to "file" for image galleries
Whenever you add a image gallery to a post, the images automatically link to the image attachment pages. This is not ideal, because I want to use Fancybox so the user can cycle through the images.
I tried the following code to let the images link to the files by default, but this doesn't seem to work for galleries. Any suggestions on how to set the default link type to "file" for image galleries?
I would be even happier if the image attachment page wouldn't be available at all (on galleries an regular images). I don't really like this feature.
/**
* Set default image link type to file
*/
function tp_set_default_link_type() {
update_option( 'image_default_link_type', 'file' );
}
add_action( 'after_switch_theme', 'tp_set_default_link_type' );
Thanks in advance! | You can override the gallery shortcode `link` attribute with:
add_filter( 'shortcode_atts_gallery',
function( $out ){
$out['link'] = 'file';
return $out;
}
);
This means that even if your shortcodes are:
[gallery ids="1,2,3"]
[gallery ids="1,2,3" link="none"]
the gallery output will always be generated as if you used `link="file"`. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 3,
"tags": "gallery"
} |
Sorting posts by Multiple custom fields in defined order
I'm currently sorting some posts out by custom fields 'role' and 'surname', using the following:
function customorder($orderby) {
return 'mt1.meta_value DESC, mt2.meta_value ASC';
}
$args = array(
'post_type' => 'staff',
'meta_key' => 'role',
'meta_query' => array(
array(
'key' => 'role'
),
array(
'key' => 'surname',
),
)
);
add_filter('posts_orderby','customorder');
$query = new WP_Query( $args );
remove_filter('posts_orderby','customorder');
How can I define the order that I would like the first meta_key in, as opposed to alphabetically desc or ascending. For example where role = 'Head Teacher', 'Deputy', 'Teacher', 'Support', 'Clerical' ... etc Therefor grouping the posts by the meta_key value.
Thanks in advance for any help
Cheers
Noel | You can use FIELD or FIND_IN_SET:
return "FIELD(mt1.meta_value, 'Head Teacher', 'Deputy', 'Teacher', 'Support', 'Clerical') ASC, mt2.meta_value ASC";
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, custom field, order"
} |
Removing old code from header
In our site, we've got some old code sitting in the header. I'm guessing it originated from a plugin we used to use (embedding Scribd content into the site), but we are no longer using it.
<script type="text/javascript" src="
The problem is I can't figure out how to get rid of this script. It's not in header.php - so where would I go to edit this out? | If you have SSH, go to your `wp-content` directory and grep it.
/ grep -HRn 'scribd' . | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "headers"
} |
Disable Debug Log Programmatically
I'm trying to disable `WP_DEBUG_LOG` if and only if `debug.log` exists. I'd like to hook into `wp_footer` and test if the file exists and if so disable my debug log. All I've found though is that `WP_DEBUG_LOG` is a constant and can only be changed from the `wp-config.php` file which is too early for my case. Is there a way to change it from a constant on install and keep it working as normal?
My only other thought is to create an option on install in the options table and just check it every time `wp-config` loaded to see if the value has changed but I was wanting to avoid that.
Granted I could check if the file exists before I define `WP_DEBUG_LOG` but somebody would have to view a page twice before debug log actually exists and is detected by the `file_exists()` (since it's run very early) which is not optimal.
Does anybody know of a workaround to programmatically turn off `WP_DEBUG_LOG`? | @Wyck was right, ( well sorta :P ) you can set error logs but
1) You need to enable debugging
2) `ini_set('log_errors', 1);` or 0 for `false`
3) You need to set a log location via `ini_set('error_log, $location)`
Once you have that set you can then if need be test if said file exists via `$location` and turn off `log_errors` by setting its value to 0. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "debug, wp debug, errors"
} |
Display current category without an active link in wp_list_categories
I appreciate your time in looking into this for me.
I'm using `wp_list_categories` tag to display a list of categories in my navigation menu and I'd like to disable the link to the current category when viewing said category page.
My main reason is that the color attribute in my CSS style for `li.cat-item a` is overriding the color attribute for my CSS style for `.current-category a` and blocking my attempts to create a contrasting text color for the current category item. | You can use `get_the_category();` to display your category in menu
<?php
$categories = get_the_category();
$separator = ' ';
$output = '';
if($categories){
foreach($categories as $category) {
$output .= '<a " href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
}
echo trim($output, $separator);
}
?>
I used the `<a>` tag you can remove it for link. I Hope it help you | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, categories"
} |
Subdomains to pages
Hi I have a website on wordpress which have 2 pages which I meant to convert it to subdomain.
Eg: Let my website at be <
there are two pages < and <
I want them to be accessible at < & < respectively.
Also I have may subpages to page1 which i wanna access using subdomain of main page. I mean if < is subpage of < then I want to access it as <
I have already created subdomains in cpanel pointing them to root folder of my website and tried following htaccess.
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^subsite\.domain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/subsite [NC]
RewriteRule ^(.*)$ /subsite/$1 [L]
I have tried different other variants of htaccess code I got from different forums and also www.stackoverflow.com
Also tried WP Subdomains (Revisited) plugin and found of no use.
Please help me to fix it. | It's better to use WP_Rewrite for that.
add_action('page_rewrite_rules','my_page_rules');
function my_page_rules($rules){
$pageslug = 'sample-page';
$rules['([^/]+)/?$'] = 'index.php?pagename='$pageslug'/$matches[1]';
return $rules;
}
add_filter( 'page_link', 'sub_page_link');
function sub_page_link(){
// preg_replace here
}
I have found a premium plugin which uses the same mechanism to convert pages into subdomain, it uses rewrite rules and Server WildCard Configured.
Hope it is helpful! | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "permalinks, pages, redirect, subdomains"
} |
Notification when left menu bar is closed?
How to get a notification via Javascript when the left menu bar has been collapsed ?
I was looking everywhere in the net but there is zero out there... thanks!
update: somebody asked what the left menu bar in Wordpress is : the left menu bar is on the left side. the last button is 'collapse menu'. all i need is a notification when the user changed the collapse state. | How to get a notification via Javascript when the left menu bar has been collapsed ?
If you are taking about the admin menu bar and you want to get a notification when the that is closed and expanded, then watch thoroughly that, when admin menu bar is collapsed, a `folded` class is added to the body. You can get any notification according to that. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript"
} |
If Month=Particular month display content
I want to use conditional tag to display content according to month. Such as if it is April, it should show something else something else. Right now I am using :
<?php if(is_month() == '2' ) : ?>
<p>hello</p>
<?php else: ?>
<p>Wow</p>
<?php endif ?>
The above doesn't work. Any solution? | <?php if( "8" === date('n')):?>
//what you want to show
<?php endif;?>
Change '8' with the number of the month you want. More on the date function. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, conditional tags, conditional content"
} |
Deploying Wordpress for clients - what do they have access to?
I've developed websites from scratch up till now and would like to switch to using Wordpress to save time and money.
I've done some theme customization and plugin work so far. I can see that users can update posts and customize themes themselves from `/wp-admin`.
What I'm concerned about it - is that how projects are generally deployed in wordpress? That the client has access to customize pretty much everything themselves? Do they really get to see all this?
!enter image description here
I've generally made custom CMSs for clients based on whatever their website was, but somehow I feel like this is a bit much for clients to have access to? Or is it normal? | There is also a plugin named Adminize that will allow you to completely customize what the client can see in the admin.
If you use this plugin you can set yourself up as Admin and then give your client a lesser role, which will allow you to continue to have administrative control over the site. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp admin, user access, deployment"
} |
Fluid Featured Post Carousel Slider for Wordpress with no Javascript
I implemented a pure CSS Slider without Javascript on my Test-site with 5 image slides. How can i adapt the slider to show the 5 latest posts from my featured post category with thumb, title, excerpt and link to the post instead of the images?
Thank you so much
**Here is the Fiddle** | <div class=carousel>
<ul class=panes>
<?php
// the query
$args = array('cat' => id_of_featured_posts_category, 'posts_per_page' => 5);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_post_thumbnail( 'full'); ?>
</li>
<?php endwhile; ?>
<?php endif; ?>
</ul>
</div>
I don't have wordpress here to test it, but it should work, to learn more about this you can check the documentation for WP_Query. I don't know where you want to add the excerpt (the_excerpt() is the function you need to call to get it), but I'm sure you can take from here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php"
} |
How to use wp_terms_checklist() on front end
Getting a Fatal Error using `wp_terms_checklist()` in one of my advanced search form in Front End.
> **Fatal error:** Call to undefined function `wp_terms_checklist()`
With search I got that it's creating problem because the function is for _admin panel use only_ , BTW _not_ deprecated.
<?php
$args = array(
'descendants_and_self' => 0,
'selected_cats' => false,
'popular_cats' => false,
'walker' => null,
'taxonomy' => 'mytaxonomy',
'checked_ontop' => true
);
wp_terms_checklist( 0, $args );
?>
But if I need a similar thing in my front end. How can I achieve that? Is that possible in current flow? | You could just include it in your `functions.php`:
if ( ! is_admin() ) {
include ABSPATH . 'wp-admin/includes/template.php';
}
Or better (as suggested by @Lance Cleveland in the comments):
if ( ! function_exists( 'wp_terms_checklist' ) ) {
include ABSPATH . 'wp-admin/includes/template.php';
} | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "custom taxonomy, templates"
} |
Output categories in something different than a list
I wanted to output all my categories in the sidebar of my wordpress theme. Now I use the function `wp_list_categories();` which works fine. However it always displays the categories in a list and I don't want that.
What I want is to display the categories as links so that they are inline elements. I could stay with the list and just style them as inline elements by applying `display: inline-block;` to the list items. I guess it is semantically correct, too.
So is there a way of getting rid of the list in WordPress or should I stay with my approach? And is it semantically correct?
Thanks for all your answers. | Did you had a look at the _Display Categories Assigned to a Post_ example in `wp_list_categories` in the Codex. This should give you a very good idea on how to modify your own code. This is just my simplistic way to achieve what you want. Feel free to modify as needed
<?php
$taxonomy = 'category';
$separator = ', ';
if ( !is_wp_error( $post_terms ) ) {
$terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy );
$terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator );
// display post categories
echo $terms;
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "list, categories"
} |
User Tracking for Custom Post Type "Lesson". Database Queries and Performance
So I wrote this little code snippet to add a post id along with the current users id to the user meta table. I'll use this to show the "lesson" posts that a user has viewed back to them.
My only concern with this way of doing it this way is that it seems Wordpress will have to loop through this whole table to retrieve these posts. What if there are tens of thousands of users (I'm being optimistic) and they all view on average 10 or 20 lessons? Could this cause performance issues? I don't know enough about databases yet to know. Is there maybe a better way to go about this that I'm missing?
<?php
if ( is_user_logged_in() ) {
$user_ID = get_current_user_id();
$post_ID = get_the_ID();
add_user_meta( $user_ID, 'viewed_lesson_tracking', $post_ID ); // tracks that user has viewed the current post
}
?>
Thanks for your help! | Since there are going to be more than one post (lesson) per user, your code would be more like this:
<?php
if ( is_user_logged_in() ) {
$user_ID = get_current_user_id();
$post_ID = get_the_ID();
$viewed = get_user_meta( $user_ID, 'viewed_lesson_tracking', true);
if(empty($viewed)){
$viewed = array();
}
$viewed[] = $post_ID
add_user_meta( $user_ID, 'viewed_lesson_tracking', $viewed ); // tracks that user has viewed the current post
}
?>
So, all you have to do, when showing a list of all viewed lessons(posts) is to use the post__in parameter of WP_Query.
WordPress will not loop through the whole table. That's not how MySQL queries work. At any given time, there'll only be one query per user. You won't need to worry about the performance. Plus, WordPress caches all the queries and if you have a cache plugin on top of it, you don't need to even give it a thought. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database"
} |
Custom post type post taxonomies
I created simple custom post type with few taxonomies. I
<?php $query_params = getQueryParams(); $query_params['post_type'] = 'client';
if(isset($query_params['search'])){
$query_params['post_title_like'] = $query_params['search'];
unset($query_params['search']);
}
$loop = new WP_Query($query_params);
if($loop->have_posts()) : while($loop->have_posts()): $loop->the_post();
// SOME HTML
endwhile; endif; ?>
Then I tried to list display taxonomies for each post, by this:
$categories = get_categories("taxonomy=city");
foreach ($categories as $category) :
echo '<li>' . $category->name . '</li>';
endforeach;
But I always get all created taxonomies, not only selected to post. Any suggestions? | <?php get_the_terms( get_the_ID(), 'city' ); ?>
You can learn more about this function here. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, custom taxonomy, taxonomy"
} |
Is it possible to override this function/class in a child theme?
Is it possible to override this `widget` function from a parent theme? I saw this blog, but it dealt with a simpler case.
<
### parent
class Chocolat_Widget_New_Entrys extends WP_Widget {
function __construct() {...
function widget( $args, $instance ) {...
}
add_action( 'widgets_init', create_function( '', 'return register_widget( "Chocolat_Widget_New_Entrys" );' ) );
I attempted to use `remove_action('widgets_init','???');` but soon realized I could not get a handle on the function that registered it!
I thought about overriding the function and creating a subclass, but still, it is registered in the parent by the name of the parent class.
I thought about just copying the whole class, but child `functions.php` is loaded before `parents.php`. | You simply need to run your code on a higher priority than what the parent theme is, the default on `add_action` function is 10 so you can use:
function s157343_unregister_widgets() {
unregister_widget( 'Chocolat_Widget_New_Entrys' );
}
add_action( 'widgets_init', 's157343_unregister_widgets', 20 );
This will unregister that widget. Of course, you can still create a new class that extends that widget's class to override the methods you want and register a new widget based on that:
class my_Chocolat_Widget_New_Entrys extends Chocolat_Widget_New_Entrys() {
public function __construct() {}
public function widget( $args, $instance ) {}
}
add_action( 'widgets_init', create_function( '', 'return register_widget( "my_Chocolat_Widget_New_Entrys" );' ) ); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "functions, child theme, pluggable, parent theme"
} |
Detect error 404 page to find out the issue
I have a wordpress website, which when I visit
> www.mywordpress.com/test/setup
it throws an error 404 page.
Which class in wordpress handles the request dispatching? | 404 errors are handled browser site and has nothing to do with Wordpress. When nothing is returned from the request, the browser triggers a 404 action and displays a 404 not found error page
By default, if no custom 404 page exists on the site, the browser will display its own default 404 page.
For further reading, check out: Creating an Error 404 page | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, 404 error"
} |
Altering "posts_per_page" for defaut loop
I am trying to alter `posts_per_page` value in default wordpress loop on-the-fly, not for a custom loop.
global $wp_query ;
// $wp_query->query_vars['posts_per_page'] = 1000 ;
$wp_query->set('posts_per_page',1000) ;
while ($wp_query->have_posts()) {
$wp_query->the_post() ;
// other operations
}
How to do that? | As Tom said, that will never work, as the main query have already executed. The only way to achieve that is to alter the main query **before** it is executed.
There is a action hook for that, `pre-get_posts` and this is the correct method to alter the main query.
Example:
function wpse_custom_ppp( $query ) {
if ( !is_admin() && $query->is_main_query() ) {
$query->set( 'posts_per_page', '1000' );
}
}
add_action( 'pre_get_posts', 'wpse_custom_ppp' );
You can use additional conditional tags to target specific pages | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "loop"
} |
Custom CSS not being added by plugin
I am attempting to add custom css through my plugin. I do have wp_head() called in my header.
My code is -
/**
* Enqueue plugin style-file
*/
function prefix_add_my_stylesheet() {
wp_enqueue_script('style1', plugins_url('style1.css', __FILE__) );
}
add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );
I can access style1.css when I
echo plugins_url('style1.css', __FILE__);
So I know it exists and is available. I do not get any errors and the style sheet does not show.
I am placing the above code inside mysite/wp-content/plugins/mycustomplug/plugin.php
Can anyone let me know why this may not be loading? Nothing errors out so I assume my syntax is correct. | OK, you have two problems here.
Firstly, you are enqueueing your style with `wp_enqueue_script()`, which is meant to be used by scripts. You should be using `wp_enqueue_style`
Secondly, you need to understand what functions are loaded when. Plugins are loaded first, child themes second and parent themes last. So you styles gets loaded first, and then the styles of the theme. This means, duplicate css selectors get overwritten by the theme styles.
To make sure that your plugin style gets loaded after the theme's style, just add priority to your action. For reference, see `add_action( $hook, $function_to_add, $priority, $accepted_args )`. Be sure to use a very low priority (very high number)
Your code should be
/**
* Enqueue plugin style-file
*/
function prefix_add_my_stylesheet() {
wp_enqueue_style('style1', plugins_url('style1.css', __FILE__) );
}
add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet', 999 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, css, actions, wp enqueue script"
} |
Sanitizing and validating email field
Should I use `is_email()` to validate an email field? In WP. I've put the email field in a widget. I would really appreciate some help.
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['email'] = is_email($new_instance['email']);
return $instance;
}
And
<p>
<label for="<?php echo $this->get_field_id('email'); ?>">
<?php _e('Email'); ?> </label>
<input class="widefat" id="<?php echo $this->get_field_id('email'); ?>" name="<?php echo $this->get_field_name('email'); ?>" type="email" value="<?php echo $email; ?> " />
</p>
<?php
}
Is using `is_email()` correct for this? Thank-you! | According to the documentation, is_email() is used to validate an email and either returns the email if it is valid or false if it isn't. So are using it correctly.
The only thing I can see in your code is that if the email is not valid, you are settings the data to a boolean value of FALSE.
$instance['email'] = is_email($new_instance['email']);
//with a bad email address, this will be the same as writing
$instance['email'] = false;
Depending on what you're doing in the widget that may give you unexpected results.
I would instead do something like the following
$instance['email'] = ( is_email($new_instance['email']) ) ? $new_instance['email'] : '';
This is going to make sure that if the is_email() call returns false then you are setting $instance['email'] to an empty string instead of a boolean value.
Hope this helps! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "email, validation"
} |
Getting the slug into a variable, how to echo that variable
The page slug for each of our wordpress articles is a unique set of seven digits, and we are using that string of numbers as the page slug.
In trying to learn how to customize our site even further, I'd like to learn how to echo that slug in template files (outside the loop - it would actually be used in the sidebar). Here's what I've tried so far (and failed miserably):
At the top of the post template file, I have this code:
<?php $doi = get_page_template_slug( $post_id ); ?>
So I'm trying to create a $doi variable that has the page slug.
Later on in the template file, I'm trying to echo that variable:
<?php echo $doi; ?>
That also fails. Anyone got time to help a PHP newbie out? | Try this:
$post = get_post($post_id);
$slug = $post->post_name; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, slug"
} |
Get JSON from self hosted wordpress site
I am very new to wordpress so this may seem basic.
I have a **_NON-WordPress_** website in which I would like to consume various blogs (via category/tags etc etc) from my **WordPress** site.
**Currently I am using this plugin:** <
* Although it works fine, sadly it seems to only return the latest 10 blog entries (0-9) which does not cover all the data I want to interact with.
* I have looked at the documentation for this plugin but I cannot see any way of changing how many entries to return.
I have seen this plugin: <
* Would that plugin solve my problem?
* Is it likely to cause conflicts having two JSON type plugins running at the same time?
Any help on this would be much appreciated. | This is a Wordpress setting you can change. Login to the WP admin panel, click Settings > Reading, change "Syndication feed show the most recent" from the default 10 items to something higher, and click Save. If you don't see the change immediately, try clearing the recent cache in your browser, or open the link in a different browser. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "json, plugin json api"
} |
WP Load post with ajax and apply isotope
I ma using `Ajax Load More` to get my posts and show in a frontend, then I have applied isotope to the items. When I first show some items and applied isotope, it's working perfectly.
But When second time I load post by ajax and try to apply the isotope, that isotope is not working and posts are overriding.
Could someone help me in this regard? | I got the solution for this question. I need to apply there Isotope append method, when adding posts to the frontend. Here is the Isotope append method. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, theme development, jquery, ajax"
} |
New User Save Filter
I'm using the new(ish) filter `add_action( 'user_new_form', 'funcy', 9 );` to add custom fields to Create A New User page. I'm then using
add_action( 'personal_options_update', 'save_user_meta' );
add_action( 'edit_user_profile_update', 'save_user_meta' );
hooks to save my meta on other edit user pages. I've confirmed that when creating a new user WP does not hook into the above. I've tried looking through
1. `/wp-admin/user-new.php`
2. `/wp-adin/user-edit.php`
but nothing stuck out as to how it was saving the new user info. The core of the question is, what can I hook into to save user_meta from the `user_new_form`? | For this, you have to use `user_register` hook defined on _wp-includes/users.php line 1759_.
* `personal_options_update` hook is called, when an user updating his own profile.
* `edit_user_profile_update` is called, when an administrator updating other user profile.
* nothing is called, when an administrator creating a new user.
On `user-new.php` page, new user are created using the `edit_user` function, function ref: ( _wp-admin/includes/users.php line 30_ )
So, the only option to use `user_register` hook. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, hooks, user meta, customization"
} |
Display what taxonomies a custom post has?
I've trying to search high and low for this but am having a really hard time.
Essentially, I have a custom post type called `locations` with taxonomies. The posts in "locations" are categorized under several taxonomies called `markets`, `products`, `size`, `country`, etc."
I just need to know how I can get it so my custom post type on the front end displays what taxonomies the post is categorized into. Does anyone know how I can do that?
To clarify, I just basically need to emulate this page to a tee (which is a drupal site) where you can see what categories the post if under.
> <
Would greatly appreciate ANY guidance or feedback. | As there's multiple Taxonomies, you will need to loop through all of the assigned taxonomies of that post type. `get_object_taxonomies` is the function which returns array of post type taxonomies.
global $post;
foreach ( get_object_taxonomies( $post ) as $tax_name ){
$taxonomy = get_taxonomy( $tax_name );
$label = $taxonomy->labels->name;
the_terms( $post->ID, $tax_name, $label . ': ', ', ' );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, terms"
} |
Save post to category with gravity forms (post_data)
I'm trying to save my posts, generated with gravity forms, to a specific category. However whatever I try, it's not working. The post must be saved to sepecific category, dependent from a gravity forms field.
What I've tried so far:
add_filter("gform_post_data", "change_post_category", 10, 3);
function change_post_category($post_data, $form, $entry){
$cat_entry = $entry["6"];
$catslug = get_category( $cat_entry );
$post_data["post_category"] = $catslug->slug;
return $post_data;
}
I did also try to change save it with the category id, or by full name. Nothing works. It did however changed from 'no category' to - (nothing).
Thanks. | The post_category needs to be passed as an array of category IDs (even if you're only adding one category).
Try this:
$post_data["post_category"] = array( $catslug->ID ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins, categories, save post, plugin gravity forms"
} |
Why isn't my multiple loops working?
I would like a multiple look to display `the_content` from the current page, & from another page. My multiple loo doesn't seem to be working. Can anyone advise, please?
while( have_posts() ): the_post();
the_content();
endwhile;
$id=40;
$post = get_post($id);
$title = apply_filters('the_title', $post->post_title);
echo $title;
$content = apply_filters('the_content', $post->post_content);
echo $content;
endif;
endwhile;
Please can someone advise? Thank-you! | **This seems to work:**
while( have_posts() ): the_post();
the_content();
endwhile;
$my_query = new WP_Query('page_id=40');
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate = $post->ID;?>
<div class="entry">
<?php the_content('read more »'); ?>
</div>
<?php
endwhile; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "loop"
} |
Database Name Change
I read it was more secure to use something else besides wp_ as the database prefix, so I downloaded my .sql file replaced all instances of wp_ with tsi_ and then dropped the wp_ tables and imported my .sql file.
The prefix is now correct, so then I went to my wp_config file and changed the prefix table from wp_ to tsi_ and I thought everything was good.
Well, all my posts were still there, but the images are missing. I say missing because when you look in the uploads folder they are there, correctly sorted and everything, but in the media library, they appear as grey icons instead of the previews and they are missing from all my posts. Is there any way to get the images to display correctly?
*The domain name did not change or any of my settings, I just changed the database prefix and that's it.
The grey icons in the media library:
!enter image description here
The posts without images:
!enter image description here
Thanks,
Josh | Ok...
So after some more research I found: < which explains that you can't just do a find and replace in a text editor and be good to go.
Fortunately, I still had the original database, so I dropped all the tables in the tsi_ database and restored the original wp_ database.
All my images were restored and the site was back to normal, now to change the database prefix properly...
I found a plugin called Change DB Prefix: < it allows you to put in the old prefix wp_ and replace it with a new one tsi_.
The plugin safely changed my database prefix and updated my wp_config file in less than a second! All my images are fine and everything is now up and running correctly with the new database prefix!!
Hope this helps someone!
Thanks,
Josh | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, media library"
} |
Add_query_arg + two times the same argument?
I'am trying to filter my archive page by clicking links. When clicked they execute the add_query_arg command.
Everything works fine so far.
But now i want to add combinations within the same custom taxonomy.
ex: < '?events=test&events=test2'
now the question, how to add two times the same argument with add_query_arg without overwriting the first one ? And how to get them again ?
Hope someone can help me out here.
Best regards | Nilambar's comment solved this for me.
> "You can pass two values as comma separated in a single parameter events. And later parse value correctly in your page. – Nilambar"
I use this to get posts with tag1 OR tag2:
echo '<a href="'.esc_attr(add_query_arg( 'events', 'tag1,tag2')).'">Linkname</a>';
And to get all posts with tag1 AND tag2 simply use "+" instead of ",":
echo '<a href="'.esc_attr(add_query_arg( 'events', 'tag1+tag2')).'">Linkname</a>';
Thanks Nilambar ! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "url rewriting, urls, multi taxonomy query"
} |
WP_query taxonomy + get all posts with two terms from same taxonomy
This is a follow up question to Add_query_arg + two times the same argument?
I want to get the post count from all posts tagged with 2 different tags from same taxonomy
$args2 = array(
'post_type' => 'custom',
'tax_query' => array( 'relation' => 'AND' )
);
$args['tax_query'][0] = array(
'taxonomy' => 'events',
'field' => 'slug',
'terms' => 'tag1'
);
$args['tax_query'][1] = array(
'taxonomy' => 'events',
'field' => 'slug',
'terms' => 'tag-2'
);
$query = new WP_Query($args);
echo $query->post_count;
With this code I only get the post_count for one of these tags. How i do get both? I couldn't find an answer at Wordpress codex.
Help is much appreciated. | You don't need to 2 array for tax query. You can try this scenario:
$args2 = array('post_type' => 'custom',
'tax_query' => array(
array( 'taxonomy' => 'events',
'field' => 'slug',
'terms' => array( 'tag1', 'tag-2')
)
)
);
$query = new WP_Query($args);
echo $query->post_count;
You can see the Codex for better understanding. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "wp query, advanced taxonomy queries"
} |
Get the search element only on 404
I know `get_sidebar( );` is used to get the widget sidebar , but how do I request one element from it?
For instance, if I want to show the search or most read only? I know there is a way to specify the sidebar for page like `get_sidebar('404' );` for example
How do I do this? I've created the `404.php` page. Do I have to register other sidebar or do I have to create "404_sidebar.php"?
So, how do I get the "search" element only when my website return error 404? | You can include the search form in your `404.php` file using the `get_search_form()` function.
Using `get_sidebar( '404' );` would look for a file called `sidebar-404.php` and fall back on `sidebar.php` if needed. `get_sidebar()` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "search, sidebar, 404 error"
} |
How to hide a HTML element based on user role
I have a login top bar I use for general users on the website front end and the admin like to use the wordpress admin bar. I am trying to find a way of hiding the login top bar for admin so they just use the wordpress admin bar (this is only enabled for admin). I would also like to change the CSS of the main container if admin is logged in.
I have been looking for code on Git hub and the web but can't find anything that has worked for me. Does anyone know if this is even possible? | You could use something like this if you have jquery included in your page:
<?php
if ( is_super_admin() ) {
?>
<script type="text/javascript">
$( document ).ready(function() {
$("#IDofDivHoldingUserTopBar").css("display", "none"); // ID of user top bar
// ............................. OR
$(".ClassofDivHoldingUserTopBar").css("display", "none"); // class of user top bar
});
</script>
<?php
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "user roles"
} |
Adding Read More to Custom excerpts
I've added the following code to my functions.php:
function new_excerpt_more($more) {
global $post;
return '<strong><a class="moretag" href="'. get_permalink($post->ID) . '">... Read More</a></strong>';
}
add_filter('excerpt_more', 'new_excerpt_more');
This adds a read more link to excerpts that have been automatically generated, i.e. an author hasn't specified anything in the excerpt field when posting an article.
So far so good.
However I would also like this to appear when something has been specified in this box, currently it only displays in the first instance.
Thanks | To show your custom excerpt more text when a post has a manual excerpt, you can filter the excerpt using the `get_the_excerpt` filter, use `has_excerpt()` (< to determine whether the post has a manual excerpt or not, and append the output of your already-existing custom excerpt more function to the excerpt if not. Here's some code that I tested with your custom excerpt more function above, which does the trick:
function excerpt_more_for_manual_excerpts( $excerpt ) {
global $post;
if ( has_excerpt( $post->ID ) ) {
$excerpt .= new_excerpt_more( '' );
}
return $excerpt;
}
add_filter( 'get_the_excerpt', 'excerpt_more_for_manual_excerpts' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, excerpt"
} |
Display a category name automatically using code in the functions.php file
Any idea how I could edit this code to show a post's category title instead of the post's time?
At the moment it adds
> This post is in 12.34pm
to the top of the post content.
function add_before_content($content) {
return '<p>This post is in ['.get_the_time().']'.preg_replace('/<p> /','',$content,1);
}
add_filter('the_content', add_before_content); | Would each post only be in one category?
You'd first need to get all the categories associated with the post, and then output only first. Here is an untested example:
function add_before_content($content) {
$post_cats = get_the_category();
return '<p>This post is in the ' . $post_cats[0]->cat_name . ' category</p>' . $content;
}
add_filter('the_content', add_before_content);
Reference: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
Add management screens to post type
I am looking to build a theme that has an integrated resume, using custom post types. I have had a look at this question with regards to inserting post types within post types in the admin menu. The structure that I am planning is:
Resume
* View Employment
* Add Employment
* View Qualifications
* Add Qualification
* View Memberships
* Add Membership
* Options
How would I insert links to the appropriate post management screen in the menu?
**[EDIT]**
I have tried to create this in my local site, and have noticed that the menu only displays the post management page, not the editor (the opposite of what I assumed). I would like both to be displayed. Is this possible? | The good news is I have found a solution. The (kind of) bad news is that the menu has to be created manually. It would use a combination of the add_menu_page and add_submenu_page functions. The codex pages have the format for the functions.
The menu would be
add_action( 'admin_menu', 'register_my_custom_menu_page' );
function register_my_custom_menu_page(){
add_menu_page('My Custom Page', 'My Custom Page', 'manage_options', 'my-top-level-slug', '', '', 28);
add_submenu_page( 'my-top-level-slug', 'My Custom Page', 'My Custom Page', 'manage_options', 'my-top-level-slug');
add_submenu_page( 'my-top-level-slug', 'My Custom Submenu Page', 'My Custom Submenu Page', 'manage_options', 'my-secondary-slug');
}
Then, in the custom post type, the `'show_in_menu'` variable would be set to `false` for each custom post type and the slugs posted into the appropriate variables in the function. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "custom post types, admin menu"
} |
How to obtain the current website URL in my theme?
I am working on a custom theme and I have the following doubt about how to correctly insert the link to some section of my website into the theme.
If you open this link you can understand what I need to do: `
As you can see under the header slideshow I have 3 boxes that are links.
I need to link the second box (the one named **Archivio** ) to this page: `
I know that I can simply put this URL into the href attribute of my a tag but this is not a smart idea because then I have to moove the website on my remote webserver.
So I am thinking that should exist something like a wordpress function to retrive the current URL of the website.
What is the best way to implement this thing?
Tnx | bloginfo('url') should get you the URL for the installation.
EDIT:
I guess you could also use get_permalink() | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, plugin development, functions, theme development, customization"
} |
List of users inside custom taxonomy
So I'm trying to get a list of terms inside a taxonomy that is related to users. Inside each term (think a sub list) should be a list of the users for that term. Here is the code I've been working with. But it returns several errors for the query and non-object issues. Help?
<?php $disciplines = get_terms('disciplines');
foreach($disciplines as $discipline) {
echo '<li><a href="#">' . $discipline->name . '</a></li>';
$post_args = array( 'post_type' => 'users', 'disciplines' => $discipline->term_id);
$posts = get_posts( $post_args );
foreach( $posts as $post ){
echo 'post title: ' . $post->post_title . '<br />';
}
}
?> | get_terms and get_posts return arrays not objects.
Try this:
<?php $disciplines = get_terms('disciplines');
foreach($disciplines as $discipline) {
echo '<li><a href="#">' . $discipline['name'] . '</a></li>';
$post_args = array( 'post_type' => 'users', 'disciplines' => $discipline['term_id']);
$posts = get_posts( $post_args );
foreach( $posts as $post ){
echo 'post title: ' . $post['post_title'] . '<br />';
}
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom taxonomy, users"
} |
Get posts from 2 or more categories
I'm trying to get posts from 2 or more categories, so far I discovered:
$args = array(
'category__in'=>array( implode(ot_get_option("beautiful_categories"), ",") )
);
$query = new WP_Query( $args );
I'm using OptionTree and that will return categories ids with "," between them. and then I get post with while loop, but it just return posts of first category.
How can i fix it? | that was my error, OptionTree for this input type(radio in my case) itself returns an array and we don't need to convert it. and category__in needs an array so i just change it to:
$args = array(
'category__in' => ot_get_option( 'beautiful_categories' )
);
$query = new WP_Query( $args );
and it worked perfectly. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories"
} |
After updating WP keeps nagging about a newer version. Why?
I updated WP to version 3.9.2 (currently the latest) via Git which works fine. However, in the admin it keeps on telling me “a newer version is available”. After some digging somehow it appears to be related to the language pack. I’ve got `WPLANG` set to `nl_NL`.
In the `wp-includes/update.php` file `wp_version_check()` checks against the WordPress server for newer versions using a URL like this:
Click it and you’ll notice it offers a response with the status “upgrade”, yet the version is the same!? If you remove locale argument at the end or leave it empty (URL below), you’ll see it will answer with a status value of “latest” and thus not triggering update nags.
I tried flushing the WP cache (update transients) but nothing changes. Anybody gets what is going on here? Thanks. | The issue is, there is no value for `local_package` in the URL.
At first I thought this might be a bug. Similar issues have been reported before (see here and here.
I then stumbled on comment in trac ticket 8729 where user nbachiyski explains how localization should work:
> There are two ways to localize WordPress:
>
> 1. Drop some translation files.
> 2. Install localized package.
>
>
> Whenever possible we try to enforce the 2nd way.
>
> So, here is how the whole thing works:
>
> 1. Both the current locale and the current localized package, installed, are sent to the API.
> 2. If a localized package for the user's locale is available and the user doesn't have the localized package, the user is prompted to upgrade or to hide updgrade.
>
You can either install the Dutch version of WordPress or hide the updates for it (`/wp-admin/update-core.php`> Hide this update). | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 8,
"tags": "updates, localization"
} |
Why I can't change the permalink of this page?
I have the following problem with a permalink: if I open this page (it is implemented as a static page) on my local website: `localhost/wordpressAsper/archivio` it automatically change it into `
Going into the administration panel ---> pages ---> All pages ---> **Archivio** and editing it I can see that the related permalink is `
So I tried to change it in from **archivio-2** to **archivio** but I can't because when I confirm the change it return to **archivio-2** (but I can change it any other values)
I think that this could depend by an old **Archivio** page (that I have delete) that had **archivio** as permalink. So I think that WP have registered the old permalink of the old page (that not exist yet) or something like this.
How can I fix it and have **archivio** as permalink instead **archivio-2**. Can I reset the old permalinks in some way? | after you delete a page ,on the "all pages" section, on the top, after the "drafts", there is link to trash, go there and delete it permanently, after this you can change the slug name. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "permalinks, pages, wp admin, admin menu, options"
} |
Serialize $_POST global in wordpress
I'm new here in the community, and I would like to ask if it is best practice to do this in Wordpress?
`maybe_serialize( $_POST );` and then store it to the db?
I'm a newbie in using Wordpress, so please bear with me. | Depending on the exact functionality you should use different techniques. If you're allowing post data you would do post meta options (Get_post_meta). User data would be user_meta..
Most all the wordpress database actions are done by submitting through various types of WordPress functions. Sadly without knowing your goal I can't be more specific. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, posts"
} |
Translation not working in sprinf variable
I have a function to get the taxonomy term name like this:
function get_term_name($taxo){
$terms = get_terms($taxo);
$html= '';
foreach($terms as $term ) {
$html .= sprintf( __( '%s', 'twentyfourteen' ), $term->name ); $html .= '<br>';
}
return $html;
}
The problem is the return string not translated. What am I done wrong? | You can not translated dynamic strings with he translation API, you can translate only static strings that you know in advance. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multi language, translation, localization, language"
} |
how to show the data from a myqsl database in a post
im new with using wordress. I am trying to make a website that would show the data table from my mysql database. or is there any free plugin that will be able to do this? | use: $myrows = $wpdb->get_results( "SELECT id, name FROM mytable" );
then use $myrows in for or foreach loop.
Reference WP wpdb class:
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -3,
"tags": "plugins, mysql"
} |
Wordpress Categories from Plugin
I've got the Owl Carousel plugin installed, inside of it I can create some categories.
Now I'd like to have these Owl Carousel categories displayed on the site, not the regular categories. What you see on the site right now is the regular categories such as 'Uncategorised' which is created from within the POSTS area of wp-admin.
i tried using this but still just shows the wrong list of cateogies:
<?php wp_list_categories(
$args = array(
'post_type' => 'owl-carousel'
)
); ?>
!enter image description here
Regular categories page - !enter image description here
Owl Carousel Categories page
!enter image description here | I can't find any argument of `post_type` in wp_list_categories()
You should use `taxonomy` instead
wp_list_categories(
$args = array(
'taxonomy' => 'Carousel' //Carousel is the taxonomy name your plugin use
)
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, categories"
} |
How to add a class to Buddypress avatars in the Activity stream?
I'm in the process of trying to integrate bootstrap with Buddypress and am trying to add a class of "media-object" to Buddypress avatars. I could do this by mimicking the Bootstrap CSS, but in the interest of learning new things is there a way to add a class, perhaps by using a filter?
The bp_loggedin_user_avatar is where the image is created. How can I hook into it and add a class?
<div id="whats-new-avatar media">
<a class="pull-left" href="<?php echo bp_loggedin_user_domain(); ?>">
<?php bp_loggedin_user_avatar( 'width=' . bp_core_avatar_thumb_width() . '&height=' . bp_core_avatar_thumb_height() ); ?>
</a>
</div> | When calling bp_loggedin_user_avatar(), you can set the 'html' attribute to false and it will return just the URL of the avatar (instead of the full HTML). Then you can style it how you want.
Something like:
$avatar_url = bp_loggedin_user_avatar( 'html=false' );
echo '<img class="media-object" src=' . $avatar_url . ' width="' . bp_core_avatar_thumb_width() . '" height="' . bp_core_avatar_thumb_height() . '"/> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "filters, hooks, buddypress"
} |
get_terms - only top level
I am trying to get only top level term:
$cat_args = array(
'parent ' => 0,
'number' => 10,
'hide_empty' => false,
);
$categories = get_terms( 'question_category' , $cat_args);
But this query return all childterms too, I tried everything but it always get child terms too.
I am trying since last 5 hours and can't find whats wrong in my code, is this a WP bug or there is something wrong in my code ?
Thanks for helping. | Your code is correct, well almost correct. On first view, I must confess, I missed it too.
You have two syntax errors in your code. If you look closely, `'parent '` and `'parent'` is not the same. You should not leave blank spaces between single quotes (`'`) and arguments.
Also, you don't need to add a `,` after your last argument.
This should work
$cat_args = array(
'parent' => 0,
'number' => 10,
'hide_empty' => false
);
## EDIT 15-06-2016
As from WordPress 4.5, the syntax has changed for `get_terms()`. The `taxonomy` parameter is now included in the array or args, so the new use will look like this
$args = [
'taxonomy' => 'my_tax',
'parent' => 0,
'number' => 10,
'hide_empty' => false
];
$terms = get_terms( $args ); | stackexchange-wordpress | {
"answer_score": 27,
"question_score": 18,
"tags": "custom taxonomy, terms"
} |
Admin encoding problem
My breadcrumbs plugin is taking blog name as starting point:
blog name > category title > post title
The problem is if I set the blog name in cyrillic characters it is desappearing as soon as "save" button is pressed. So in admin it looks like an empty field. On the site the question characters are shown where blog name should be. Check here k-gayduk.ru
Any help appreciated. | Make sure you have the appropriate character set in your `wp-config.php` file. utf8 is a safe bet.
define('DB_CHARSET', 'utf8'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin, encoding"
} |
Where can I access my custom page template?
I understand that to create a new page template, all I have to do is create my custom template (in this case, `page-custom.php`) file, and save it in `wp-content/themes/mytheme/`.
However, where can I access this newly created template file? I want to edit it now... but it does not show up the page editor's Page Attributes options as an available template to use.
This what I see on the page editor:
!enter image description here
My newly created `page-custom` template isn't there. How can I make it appear as an option under Templates? | May be something is wrong on your page template file. Have your added page template name at top of the page like this:
<?php
/*
Template Name: My Custom Page
*/
Try with this and check once again. You can check WordPress document for creating custom page template. Check this link: Page Templates | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, pages, templates, page template"
} |
Why WordPress architecture is not pure object oriented and it don't use MVC pattern?
I am pretty new in WordPress and PHP development (I came from Java and C#) and I am a bit
astonished about how WP is structured.
Coming from Java and C# I'm used to work on totally object oriented architectures and now, working on WP, it seems to me that it is not totaly object oriented.
For example the **function.php** file ino every theme is not a class but is a simple php file containing some functions, so it respect the old procedural model.
At the same time it seems to me that WP don't use MVC pattern
My question is: why WordPress (that is a modern CMS) don't use a totally Object Oriented paradigm and don't adopt the MVC model? | WordPress as a project has extreme commitment to backwards compatibility. Whatever new things you add the old things need to work still. Whatever things you change still need to work in old _way_ as well.
So regardless of how WP started as non–MVC application, it cannot become one without retaining all of its non–MVC ways. Which makes it pretty pointless direction.
Coming from formal background MVC might seem like a baseline and "naturally" preferable way to organize. Coming from self–taught background (or lack of programming background entirely) it's mostly overblown abstraction which even people who like it cannot agree on.
WordPress largely targets _users_ , not _developers_. Any complicating of the learning curve will just be shooting its strong sides for little gain. | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 2,
"tags": "php, plugin development, theme development, customization, development strategy"
} |
Custom MySQL Query for Post and Post Meta
I have a custom table called "tags" that contains a `charity_id` that is a reference to a post ID ... I need to query the "tags" table to grab this `charity_id` and then pull in the post title and a few of the meta data.
Ideally, the end result would produce the following:
tags.serial_number, post.title, post_meta_data.post_title, post_meta_data.location_city, post_meta_data.location_state, post_meta_data.location_country | You have to use `JOIN` for that. Try it like this:
$wpdb->get_results("SELECT tags.*, $wpdb->posts.*, $wpdb->postmeta.*
FROM tags
INNER JOIN $wpdb->posts ON tags.charity_id = $wpdb->posts.ID
INNER JOIN $wpdb->postmeta ON tags.charity_id = $wpdb->postmeta.post_id
WHERE tags.charity_id = $charity_id"
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "query, post meta, mysql"
} |
Get multiple tags by slug
The following code works fine for me:
$term = get_term_by('slug', ‘foo’, 'post_tag');
$args = array (
'posts_per_page' => 5,
'paged' => $paged,
'post__not_in' => get_option( 'sticky_posts' ) ,
'tag__not_in' => $term
);
I'd now like to `get_term_by` multiple tags, e.g., 'foo' and 'bar' (I'm trying to display all posts _except_ those tagged 'foo' or 'bar').
I realize this is probably elementary, but I'm not sure how to go about it.
Ideas? | I've come up with a better way than in my previous answer:
First you need to set up an array containing the slugs of the tags you want to exclude. Then loop over that array, and on each term, use `get_term_by()` to get the tag, saving its ID to another array. That is what you can pass through to your query.
$tag_slugs = array(
'foo',
'bar',
);
$tag_ids = array();
foreach( $tag_slugs as $slug ) {
$tag = get_term_by( 'slug', $slug, 'post_tag' );
$tag_ids[] = $tag->term_id;
}
$args = array (
'posts_per_page' => 5,
'paged' => $paged,
'post__not_in' => get_option( 'sticky_posts' ),
'tag__not_in' => $tag_ids,
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "tags"
} |
uploading problem of wordpress theme
I have found a free theme for wordpress. But the problem is , when I try to upload it in my wordpress site, the site says that style.css is not found. But in the zip file it is available. Where is the problem and how it activate this theme?
< | That isn't a WordPress theme -- it's a theme for Question2Answer, which is a totally different project. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, themes"
} |
Can I use $wpdb for my custom tables in the WordPress database?
I am building a custom application based on WordPress. I have my custom tables in the WP database. Can I use $wpdb to work with them, or is that class solely for the WP related tables?
For example, If I have a database that keeps up with dogs and cats, and I create a custom table named animals (animalid, animal_type, etc.). Do I use $wpdb?
I don't know if "interacting with the WordPress database" with $wpdb is intended solely for the stock tables or not.
EDIT: I created the tables by hand with MySQL Workbench. They were tables upsized from Microsoft Access. I have not "informed" WordPress of their existence or know if I should. | Yes you can. Straight from the codex
> The $wpdb object is not limited to the default tables created by WordPress; it can be used to read data from any table in the WordPress database (such as custom plugin tables). For example to SELECT some information from a custom table called "mytable", you can do the following.
$myrows = $wpdb->get_results( "SELECT id, name FROM mytable" ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "customization, database, wpdb"
} |
Page that links to category content
I have a page called: fruit...then I have three child pages called cherry, lemon, and peach. I also have a category called fruit, and three child categories called cherry, lemon, and peach. What I am trying to do is when a user clicks on one of the child pages IE: "Cherry" the user gets a category page with all posts associated to the "Cherry" category.
Normally this wouldn't be a big deal, I'd manually do an `<?php if (is_page("cherry")) { ?>` in my template, but what I'm looking for is a way to do it dynamically so that if someone creates a new child page and a matching child category then everything will be good to go without having to manually adjust the template.
I guess it would be taking the page and redirecting to it's corresponding category page, but is that possible?
Thanks,
Josh | You can do something like this
global $post;
//Get the page name
$term = get_post( $post )->post_name;
//If a category with the same name exists, then show the posts from that category
if( term_exists( $term, 'category') )
{
//Show posts from $term category
}
I hope you get the idea. You can modify it any way to suit your need. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, child pages, template redirect"
} |
Redirect 301 www.my-site.com/page/n to www.my-site.com/
How to make redirection on WordPress site with .htaccess to redirect this:
<
to home page:
<
I do not wish to list previous post on site on first page of site, I removed paginated links from bottom of index.php but it is possible to open those pages typing address in browser location bar, or to find already indexed links by search engines... | It looks as though what you're asking is to redirect /page/n to the homepage, this can be accomplished with the RedirectMatch directive.
So:
RedirectMatch 301 ^/page/(.*)
would redirect all traffic from /page/n to the homepage. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "redirect, htaccess"
} |
Javascript not included
I have tried to include my javascript file in the following way:
function theme_scripts()
{
wp_enqueue_scripts( 'custom-script', get_template_directory_uri() . '/js/menu-fix.js',array('jQuery'), true);
}
add_action('init', 'theme_scripts');
This file is included in `functions.php`
But for some reason the script does not get included.
I have got `wp_head()` in `header.php` and `wp_footer()` in footer.php.
## Edit
So I changed my script to:
function theme_scripts()
{
wp_enqueue_scripts( 'custom-script', get_template_directory_uri() . '/js/menu-fix.js',array('jquery'), '1.0',true);
}
add_action('wp_enqueue_scripts', 'theme_scripts');
But still it isn't loaded.
This is how my `footer.php` looks like:
<script src="
<script src="<?php bloginfo('template_url'); ?>/js/bootstrap.min.js"></script>
<?php wp_footer();?> | You're mixing up the singular `wp_enqueue_script`, which adds a script, with the plural `wp_enqueue_scripts` which is an action and a function that triggers that action. I think you want
function theme_scripts()
{
wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/js/menu-fix.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'theme_scripts');
i.e. register against the enqueue_scripts-plural action that calls enqueue_script-singular. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "javascript, wp enqueue script"
} |
How can I make my Blog category unindexed in Google?
My Blog posts can break my SEO, as they're not about the themes my website discusses. So how do I avoid this? | Add the `<meta name="robots" content="noindex">` meta tag within your `<head>`.
Then look into is_category() to add it specifically to your category pages.
Or alternatively, you can check if `$cat_id` is available:
$cat_id = get_query_var('cat');
If it is available, then it is a category page.
**EDIT** Just add it in an IF statement:
if (is_category()){
<meta name="robots" content="noindex">
}
**EDIT 2** You can add this code to your category.php file which you can find within your theme's folder. Add it within the `<head>` tag. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "blog, seo"
} |
How do I Make a custom post type get a custom post template in a plugin
I am writing a plugin in which I am adding a custom post type(called 'events') using register_post_type. Additionally I want it to use single-event.php instead of the regular single.php. The current structure of the plugin folder is :
* plugin-main-file.php
* single-event.php
I know its possible if I place it inside my theme directory, but I want it to be placed inside the plugin and utilize it. How do I do it? Any custom function for that? | function get_custom_post_type_template($single_template) {
global $post;
if ($post->post_type == 'events') {
$single_template = dirname( __FILE__ ) . '/single-event.php';
}
return $single_template;
}
add_filter( 'single_template', 'get_custom_post_type_template' );
Source
Or you could use:
add_filter( 'template_include', 'single_event_template', 99 );
function single_event_template( $template ) {
if ( is_singular('event') ) {
$new_template = locate_template( array( 'single-event.php' ) );
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
}
Source
Or you could use `locate_template` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "custom post types, plugin development, page template"
} |
Grab values from the query string to fill in hidden fields in ninja forms
I've added a custom page template where I pull out a list of available jobs from the database.
The page displaying the jobs is called `jobs`.
I'm using the `Ninja forms` plugin to add a form on a page called `apply.php`, which has fields for a job application.
Now for each job title offered on the jobs page, I want it to be a link that the user can click on to apply, and be redirected to `apply.php`, where I can grab the job id and save in a hidden field on `apply.php`.
This is so that when I save the applicant's submission, I can get it saved together with the job they applied to.
I've added the link alright - as follows:
?page_id=18&jid=2
where 18 is the id of the apply page, the page that I've got the ninja form on.
But how can I grab the jid from the query string and use it in the ninja form fields? | @Eric Allen's answer worked perfectly.
However, I'd gotten in touch with the Ninjaforms folks too, and their answer worked as well, so I'm posting it here too.
They referred me to this: <
So adapting it to my problem, the solution was this:
function filter_fetch_jid( $data, $field_id ){
if( $field_id == 27 ){
$job_id = $job_id = $_REQUEST['jid'];
$data['default_value'] = $job_id ;
}
return $data;
}
add_filter( 'ninja_forms_field', 'filter_fetch_jid', 10, 27); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "forms, query string, plugin ninja forms"
} |
Unwanted "crawl delay: 10" line added to my robots.txt
I've noticed that when I make a request to my `robots.txt` page, I get it with a `crawl delay: 10` line added to it. I double-checked the file, and it doesn't have that line, so why does it appear? Is it maybe a strange behaviour of some plugins? | For those who are using WordPress as CMS for their site, you can bypass your web hosting server rules by simply removing your robots.txt file and instead modifying the virtual one generated by WordPress. You just have to add a filter to the functions.php file of your theme.
Here's the code snippet:
//* Append directives to the virtual robots.txt
add_filter( 'robots_txt', 'robots_mod', 10, 2 );
function robots_mod( $output, $public ) {
$output .= "Disallow: /wp-content/plugins/\nSitemap:
return $output;
}
All you have to do is modify the $output with your own directives. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "robots.txt"
} |
How to add images to taxonomies?
**Q:** Is it possible to add images to all of my taxonomies (default and custom ones)?
**Note:** I do not want to use any plugins (not my favourite solution for design related matters).
**Usage:** I want to create really practical custom post type portfolio with custom taxonomies. For example, custom taxonomy - clients, so if multiple projects from same customer/client would be realted and at the same time I could use the taxonomy as showcase of my clients. The similar usage would go with almost of my taxonomies (whether to have taxonomy archive with image and description on).
Any good practice advice here? Thanks in advance
**Clarification:** I want to add images to the terms of my custom taxonomies. Example, custom post type 'portfolio' with custom taxonomy 'clients', where each 'client' term (lets say Adidas) would have its logo attached. | Starting from Wordpress 4.4, you can use add_term_meta function to store metadata for a term. This is basically a key-value pair information which is stored in `wp_termmeta` table.
**Original Answer(Prior to WP 4.4)**
Wordpress doesn't have the option to add extra information to taxonomies. There isn't any `taxonomy_meta` table. So, you have two options.
* Create a new custom table and save the extra information(image link) there.
* You can also use `options` table to store the information.
You can follow this post of as it shows how to implement what you are trying to do: < | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 9,
"tags": "custom taxonomy, images, taxonomy, advanced taxonomy queries, multi taxonomy query"
} |
How to add a rel attribute to images that contains their categories?
I've added categories to images, so that I can use them to filter images within a portfolio page. Now I'm thinking I need to add the rel attribute to each image that contains its assigned categories. Is this the right approach? If so, how do I add add rel with the applicable categories? | This should work for the `rel` attribute:
/**
* Create a rel attribute from the image categories
*
* @see
*/
add_filter( 'get_image_tag',
function( $html, $id )
{
$rel = array();
foreach( (array) get_the_category( $id ) as $cat )
{
$rel[] = $cat->slug;
}
return str_ireplace(
'<img ',
sprintf( '<img rel="%s" ', join( ' ', $rel ) ),
$html
);
}
, 10, 2 );
where we use the `get_image_tag` filter to modify the inserted image HTML.
_Ps_ : I just tested this successfully on my WordPress 3.9.2 install, where I used the following code snippet:
add_action( 'init',
function()
{
register_taxonomy_for_object_type( 'category', 'attachment' );
}
);
to activate the _categories_ for _attachments_. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions, images, attachments, categories, customization"
} |
Show post title words one by one
How to show post title words one by one, but to exclude words with 3 or less characters. Also it would be nice to be able to exclude some words, for example to make some list of words to exclude from showing.
Point is to show post title words one one but to exclude common words with 3 or less characters such as: the, is, at, and, on, it... And also to have option to make list of any unwanted words.
This is what I have so far, it gets title words, one by one, but without excluding any word.
<?php
$title = get_the_title();
$parts = explode( ' ', $title );
echo $parts[0];
echo $parts[1];
echo $parts[2];
//...
?> | Create a function in functions.php to see if your title part is in an array of 'banned' words:
function check_word( $word )
{
$blacklist = array('the', 'it', 'and', ...);
if ( !in_array( $word, $blacklist ) && strlen( $word ) > 3 ) {
return $word;
}
else {
return '';
}
}
Run your title words through it. It'll only print a word if it's not in the blacklist.
$title = get_the_title();
$parts = explode( ' ', $title );
echo check_word( $parts[0] );
echo check_word( $parts[1] );
echo check_word( $parts[2] );
Tweak to taste. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "title, get the title"
} |
Redirect if not logged in?
I've tried this to redirect people who aren't logged in to certain page. It ultimately shouldn't matter what front end page they visit, but should redirect to whatever page is chosen as the landing page (which I'm assuming would be the URL in the wp_redirect). I still need access to wp-login and dashboard etc...
I placed the following code in my functions.php, but did not work.
function my_redirect() {
if ( $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] == 'mybigfatsite.com/' ) {
if ( ! is_user_logged_in() ) {
wp_redirect( 'mybigfatsite.com/landing/' );
exit;
}
}
}
add_action( 'init', 'my_redirect' );
Thanks for any help! | The `is_login_page()` function is taken from here
function is_login_page() {
if ( $GLOBALS['pagenow'] === 'wp-login.php' && ! empty( $_REQUEST['action'] ) && $_REQUEST['action'] === 'register' )
return true;
return false;
}
function my_redirect() {
//if you have the page id of landing. I would tell you to use if( is_page('page id here') instead
//Don't redirect if user is logged in or user is trying to sign up or sign in
if( !is_login_page() && !is_admin() && !is_user_logged_in()){
//$page_id is the page id of landing page
if( !is_page($page_id) ){
wp_redirect( get_permalink($page_id) );
exit;
}
}
}
add_action( 'template_redirect', 'my_redirect' ); | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 2,
"tags": "functions, wp redirect"
} |
Change Author Name to Sitename on Frontend
How can I change the author name on the frontend to be the sitename instead without modifying theme?
I am basically looking for something that I can package as plugin on my site that will no longer show the authors name whatsoever on the posts or pages on the frontend. | You could modify it through the `the_author` filter:
/**
* Set the author name as the site title.
*/
! is_admin() && add_filter( 'the_author',
function( $author )
{
return get_bloginfo( 'name' );
}
);
where we change the _author name_ to the _site name_ on the frontend with the help of the `get_bloginfo()` function. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, multisite, pages, author"
} |
Adding Metabox Value Using the content filter
I am able to show repeater metabox on index and single post .Now I want to show this using
add_filter( 'the_content', 'theme_slug_filter_the_content' );
My code to get meta value
<?php
$data = get_post_meta($post->ID,"repeatable_fields",true);
echo '<ul>';
if (count($data) > 0){
foreach((array)$data as $p ){
if (isset($p['name']) || isset($p['select'])|| isset($p['url'])){
echo '<li>Number: '.$p['name'].' Description: '.$p['select'].' Price: '.$p['url'].'</li>';
}
}
}
echo '</ul>';
?>
I guess My code will be
function theme_slug_filter_the_content( $content ) {
$custom_content = 'YOUR CONTENT GOES HERE';
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'theme_slug_filter_the_content' ); | Did you try this ?Hope this will work.
add_filter( 'the_content', 'cd_display_quote' );
function cd_display_quote( $content )
{
// We only want this on single posts, bail if we're not in a single post
// if( !is_single() ) return $content;
// We're in the loop, so we can grab the $post variable
global $post;
$data = get_post_meta($post->ID,"repeatable_fields",true);
echo '<ul>';
if (count($data) > 0){
foreach((array)$data as $p ){
if (isset($p['name']) || isset($p['select'])|| isset($p['url'])){
echo '<li>Number: '.$p['name'].' Description: '.$p['select'].' Price: '.$p['url'].'</li>';
}
}
}
echo '</ul>';
// Return the values: quote first, then the content
return $content;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, metabox"
} |
How to create a custom shortcode based on the layout?
Hi I am developing a custom post type plugins. Which has shortcode support. Already i have created a shortcode which is going to use for default layout design. Again i have to create a onemore shortcode for another layout design.
My current shortcode **[testimonial]**
i want the shortcode something like this **[testimonial style="fancy"]**. How can i do it.can any one suggest me .
Thanks | You need to capture the attributes that passed to a shortcode. You can do that like this
add_shortcode('testimonial', 'testimonial_shortcode_func');
function testimonial_shortcode_func( $atts ) {
$atts = shortcode_atts( array(
'style' => 'default_value_if_no_value_is_provided',
), $atts );
if( $atts['style'] == 'fancy' ) {
//do something
} else if ( $atts['style'] == 'something_else' ) {
//do something
}
//And so on
//finally return content, don't echo just return
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, plugin development, wp query, shortcode"
} |
admin-ajax.php slow, how to speed it up?
admin-ajax seems incredible slow compared with an own and custom service entry point (site.com/wordpress/wp-content/myplugin/rpc.php?....).
In our custom service entry, we actually load only : wp-config.php & wp-load.php and then our RPC handler = 120ms for a RPC request.
When going over admin-ajax.php its 950ms for the same request. Is there anything we can do to speed it up ? IE, can we disable filters, plugins which have nothing to do with our request?
We'd like to switch to admin-ajax but with this performance its simply aweful for user experience.
well, any idea is welcome.
thank you! | Ajax endpoint is known to be relatively slow, but that primarily comes from loading WordPress core.
If you are seeing drastic difference between two endpoints (native Ajax vs yours custom) that both perform core load, then something is doing something that degrades Ajax endpoint on top of it.
I would profile Ajax endpoint to have better idea of what is actually taking that much time. Without that it's impossible to make good guess for situation described. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "ajax"
} |
How to use conditional statement with custom field
I think it is a simple thing but I am not good on php so :( can you guys tell me how I can use an if condition with my custom filed. Below is my current code.
<div class="courtesy"><?php echo post_custom('courtesy'); ?></div>
I want **courtesy** to show if it has a value. Right now if there is no value then a blank div is shown. I don't want a blank div. | I think what you are looking for is `get_post_meta()`
$courtesty = get_post_meta( get_the_ID(), 'courtesy', true );
// check if the custom field has a value
if( ! empty( $courtesty ) ) {
echo '<div class="courtesy">' . $courtesty . '</div>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, post meta"
} |
Plugin update not reflected in Wordpress plugin page
I've created a plugin and added it to WP plugins repository.
Later, I've seen few mistakes on `readme.txt` file. So I've fixed it and commited the changes:
svn add --force trunk/readme.txt
svn ci -m 'Fix readme.txt'
Then, the changes have been reflected on WP plugin page.
I've done a few more changes on the same file and commited them again, but the last change is not updated on the WP plugin page.
As you can see here, the SVN repository has the last update, but it is not reflected on WP plugin page (look at "Description").
Here is shown the last update ("Fix 4 readme.txt").
As it is my first WP plugin, I'm not sure if I just have to wait some more, or there is something wrong on my last update. | The marked answer is wrong. Changing the version doesn't cause this to happen.
The directory updates quickly, but not instantly. There is a delay and you need to account for that or just be patient. There is more than one server and not all of them update at the same time.
Regarding your plugin, you have a couple of problems with it now:
1. Your readme.txt is now incorrect, stating the plugin is version 1.0.1 while the plugin itself states that it is version 1.0. The wrong plugin version is here: <
2. Your Stable Tag in the readme.txt is incorrect, because you do not have any tagged versions. The Stable Tag should either be set to "trunk" or the line should not exist at all, unless you're using tagged builds. No tagged versions here: < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "plugin development, svn"
} |
Force [wordpress_social_login] shortcode to display where it is embedded
The WordPress Social Login plugin contains a `[wordpress_social_login]` shortcode that can be used in posts and pages. The problem is, no matter where I place it in the body of the post, it always renders as the very first thing on the page. I am using the Salient theme and I have been looking through one of the plugin functions called `wsl_render_login_form()` which seems to render it but it isn't obvious how it is placing it on the page first.
How can you make the shortcode render where you actually place it? Seems like this should be the default but it is annoyingly not the case. | If you have a function that you cannot change to prevent the premature output, you can still override the shortcode handler:
add_shortcode( 'wordpress_social_login', 'wordpress_social_login_fix' );
function wordpress_social_login_fix( $attributes, $content ) {
ob_start();
wsl_render_login_form();
return ob_get_clean();
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, shortcode, login"
} |
Filtering the Comment Form Allowed Tags
How can I remove some of the allowed HTML tags in comments/posts? For whatever reason, the following code, placed in my theme's `functions.php`, didn't work:
add_action('init', 'my_html_tags_code', 10);
function my_html_tags_code() {
define('CUSTOM_TAGS', true);
global $allowedposttags, $allowedtags;
$allowedposttags = array(
'strong' => array(),
'em' => array(),
'pre' => array(),
'code' => array(),
'a' => array(
'href' => array (),
'title' => array ())
);
$allowedtags = array(
'strong' => array(),
'em' => array(),
'a' => array(
'href' => array (),
'title' => array ())
);
}
Tags such as `<div>` or `<pre>` are still available when commenting. | There's a filter-hook that allows you to run some checking before comment is posted so you could use it too :
add_filter('preprocess_comment', 'wpse_158147_check_new_comment');
function wpse_158147_check_new_comment($commentdata){
$commentdata['comment_content'] = preg_replace("/<tag(.*?)>(.*)<\/tag>/", "$2", $commentdata['comment_content']);// or str_replace
return $commentdata;
}
Here "tag" would be stripped (to be replaced here with your specific tag). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "allowedtags"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.