INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How do I get the permalink of a custom post type?
I can get the permalink of a specific post tag or category, but what if I want to get the permalink of a custom post type? I can't find anything in the Codex or anywhere else about how to do this. | How about `href="<?php echo get_post_type_archive_link( $post_type ); ?>"`, where `$post_type` is your post type?
Further reading: Codex | stackexchange-wordpress | {
"answer_score": 32,
"question_score": 20,
"tags": "custom post types, permalinks"
} |
How can I abstract code out of a template by using functions.php
I'm creating a template, and one of the files is getting overloaded with pig-ugly mixed html and php.
At first I thought that maybe I should cut out chunks of the code, and call them using include().
Then I thought - maybe there is a wordpress way to do things. Perhaps I should abstract out my logic from the templates, by putting the custom loop in functions.php, and then calling it somehow from the template.
How do I do this? | This is personal preference and there are many ways it can be done. I like to keep my templates as clean as possible and use get_template_part() to include the various parts.
For parts of code that is used often I like to create functions and call the functions in the templates. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "templates"
} |
How to insert an array of terms using wp_insert_term?
WP provides a function to insert terms:
<?php wp_insert_term( $term, $taxonomy, $args = array() ); ?>
I have 60 $terms, each has its own $args, I want to prepare the 60 terms as an array, then, insert them at once. Is this posible? How? | As far as the codex for wp_insert_term says, it is not possible to insert an array directly. Put all your terms in an array, then foreach over it and inside every turn, call `wp_insert_term` once per term. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom taxonomy, terms"
} |
Reusing pictures in gallery from other posts
I have two pages where I want to use galleries with the same pictures (those pages are in different languages). Is there any way to create a gallery with already uploaded images in the other post. By default it's not possible. maybe there is a plugin for this purpose?
Thanks! | You can use the default Gallery Shortcode within your post by specifying a post ID.
[gallery id="123"]
ID == the original post the photos to which the photos are attached.
Hope this helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin recommendation, gallery"
} |
Display posts in row Horizontally
On index.php page, I am showing only thumbs and two custom fields. How can I set specific number of posts in one row like this one; < | **Step 1** : build a Loop that loads the posts you want. Note: you can number the limit of results using the `posts_per_page` parameter.
**Step 2** : style the posts using CSS. Give each post box a width and float them to the left. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -3,
"tags": "posts, get row"
} |
Add a new page to wordpress programmatically
Is there a function in the wordpress api that lets me programatically add pages ?
something on the lines of :
add_page($title,$content)
Is there such a function ? | Yes, it's `wp_insert_post()`. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "pages, api"
} |
How To View Site from Non-Logged-In User's Perspective
I am working on anew blog. I am logged in as administrator, and above every post there is a option to 'edit this entry'.
Can I have WordPress set up so that even is I am logged in as administrator, I will still view the front end of the website as if I was not logged in. This was I can see how the user would see the page.
One option is to just view the website in another browser, but I guess there has to be another page. | See this related question. You should be able to add this code to your themes functions.php
add_filter( 'edit_post_link', '__return_false' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 3,
"tags": "admin, options"
} |
How to rename wordpress Widget
I want to rename "Widget" to something else
Like "Block" or something else.
please help me.
**EDIT**
Per the user's comment below, she wants to change `class="widget"` to `class="block"` (or any arbitrary class name) in the rendered, sidebar Widget. | The classes assigned to rendered Widgets are specified by the argument array passed to the `register_sidebar()` call used to register the sidebar. e.g.:
<?php
$args = array(
'name' => sprintf(__('Sidebar %d'), $i ),
'id' => 'sidebar-$i',
'description' => '',
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>' );
?>
See the `before_widget` parameter:
'before_widget' => '<li id="%1$s" class="widget %2$s">'
...change it accordingly, e.g. to:
'before_widget' => '<li id="%1$s" class="block %2$s">' | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "widgets"
} |
Add existing images from Media Library in to custom gallery
I have `[gallery]` inside the post, and I'm interested in a way to add already existing images from media library in to this gallery? once I trying add any image I have only one option - insert into post.
Thanks in advance, Dmitry | By default, you can't. Galleries are tied to posts, and only to posts.
Options:
1. Insert the gallery from any arbitrary post, via `[gallery id="123"]` where `123` is the ID of the post.
2. Create a custom filter for the `gallery` filter hook, whereby you query/include the images that you want, perhaps by some post custom metadata (that you would also have to create)
3. Insert images individually, rather than as a gallery
4. Duplicate the images by uploading/attaching them also to the new post, so that they can be output via `[gallery]` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 5,
"tags": "posts, images, gallery"
} |
How to make a Post Tag primary?
We are trying to rethink how a blog is laid out, by using Tags as primary headers for each post, instead of Categories.
In order to do this, we have to set a Tag for the post as Primary.
So, we are trying to read the Tags as they are input into the Post Tags widget in the Post Admin, by using Javascript to read the AJAX output printed to the page. We have accomplished that part of the equation.
What we haven't be able to do, is then use document.write after printing the tags using .ready to another widget we created, so that the end user may select one of the Tags as primary.
For some reason, it does not seem to like the document.write statement and we're not sure why.
Any suggestions? | Looks like someone on on of my listserves provided the answer:
He said to, "use innerHTML() within your ajax callback function. It looks like you're using jquery, so use the .load() function."
I checked on the jquery site and it said .innerHTML is .html in jQuery, so we'll go with that then and see if we can pull the AJAX data and print it somewhere else using that function. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "tags, javascript"
} |
Is there a way to have the view link on manage posts page to open in a new window or tab?
Hi I am trying to figure out on how to get the "view" link on the manage posts / custom post types and pages to open in a new tab or window.
!A screenshot of what I am talking about.
I know it is probably possible to do via the functions.php file of the theme and would much rather go that route than using a plugin.
Any help with this would be appreciated. Thank you. :) | _Late answer_
WP core offers a function for that case, that makes it much easier and future proof: Simply map it on each item.
## Wrapped up in a plugin
Best used as mu-plugin.
<?php
/* Plugin Name: (#32093) »kaiser« Open "action"-links in post type list screens in new windows/tabs */
function wpse32093_link_target_blank( $actions, $post )
{
return array_map( 'links_add_target', $actions );
}
// Add to each post type
foreach ( array( 'post', 'page' ) as $post_type )
add_action( "{$post_type}_row_actions", 'wpse32093_link_target_blank', 20, 2 );
The plugin is tested and works seamlessly. You can adjust the post types where you want to have it active in the array inside the foreach loop. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, posts, customization, admin, views"
} |
Add Content to Content()
**The Question** ::: This is a strange question but I need to add content to `content()` in `page.php`. How do I do this?
**The Why** ::: You see there's a plugin that uses the [plugin id="1337"] and I am linking this id with user ID so the ID needs to be dynamic and then added to the content of the page. This way each user will see something different from the plugin it will be cool I swear.
I tried added it directly to the html but no luck it has to be added to `content()` somehow. No luck finding anything online either.
**Installation** ::: I'm running wordpress version 3.2.1 and using the TwentyEleven Theme | // Hook into the_content filter here
function append_to_the_content($content){
ob_start();
// Start doing stuff here ...
// End doing stuff here ...
$new_content = ob_get_clean();
return $content.$new_content; // Append new content
return $new_content.$content; // Prepend new content
} // function append_to_the_content($content)
// 11 priority avoid wpautop() that messes custom HTML
add_filter('the_content', 'append_to_the_content', 11);
Regards. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, pages, users, content"
} |
Standard permissions for wordpress; Plugin installation asks for FTP credentials
I'm on a server that does not have FTP installed and will not have FTP installed. I have another website that I've been able to install plugins in before, including the one I'm trying to install now (WP-PageNavi).
Does anyone have a list of standard permissions for WordPress that they use themselves so that they don't run into this issue?
I've read the WordPress article on the topic and looked at other questions on this website.
Any help is appreciated. | Standard permissions for most WordPress installations is 755 for directories and 644 for files.
For media uploads, auto plugin installation and updates the directories need to be owned by the same user PHP is running under. Usually this is nobody:nobody or www-data:www-data. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugins, permissions, filesystem, ftp"
} |
Wordpress won't let me use a page slug of 'feed'
I want to make a custom feed page* with the slug of 'feed', but when I try to save, Wordpress changes it to 'feed-2'.
Is there a way I can force Wordpress to let me use a slug of feed—or, if it's better practice, to hook my custom feed template* into the default Wordpress RSS feed generator? If the latter, what code do I need to substitute my own feed template for the default?
* The custom feed template I'm using is based on the useful code here: < | That's because "feed" is a reserved term (actually wp_unique_post_slug will match your page name against the rewrite rules).
You might be able to change this by removing the WP feed on `init`:
unset($GLOBALS['wp_rewrite']->feeds[array_search('feed', $GLOBALS['wp_rewrite']->feeds)]);
(maybe flush the rewrite rules after) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "rss, feed"
} |
How to add a link(href) so when i click it, it renders (shows all) posts of custom post type (rich_media), from the current category?
I am trying to set up an image menu to show "all posts", "all videos" (custom post type: rich_media). I want to have an individual image for each post type, and by clicking it I want to show all posts in the current category of the chosen post type.
All post_types share the common categories taxonomy.
I managed to list all regular posts from current category by simply linking to current category, not sure how to do the trick with the custom post. | function add_post_type_to_archives($query) {
if(is_archive() and empty($query->query_vars['suppress_filters'])){
$query->set('post_type', array('post', 'rich_media'));
}
return $query;
}
add_filter('pre_get_posts', 'add_post_type_to_archives');
For a custom post type to be shown in archives, it needs to be added to the $query. Like above. It's up to you to refine the situations where you want it added. Like:
if(!empty($query->query_vars['custom_tag_query_var'])){
$query->set('post_type', array('post', 'rich_media'));
}
This will add the rich_media post type to the loop if the *custom_tag_query_var* is present (custom_tag_query_var archive). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types"
} |
Include template before a loop
This is my category / archive page
i want to include a template before loop
but i cant get posts based on category, it showing latest post only on every page.
when i removed this line before the loop
<?php include( TEMPLATEPATH . '/includes/tb/hot_posts.tpl.php' ); ?>
it work smoothly, but i need this template before the loop
this is code (archive / category )
<div class="Hot_post">
<?php include( TEMPLATEPATH . '/includes/tb/hot_posts.tpl.php' ); ?>
<?php if (have_posts()) : $count = 0; ?>
* * *
and this is code from template (includes/tb/hot_posts.tpl.php)
<?php query_posts('meta_key=post_views_count&order=DESC'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
please guide me | try and add
<?php wp_reset_query(); ?>
at the end of your template. < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories"
} |
What difference does it make if I enable support for video post format?
I am sorry if this is stupid. I can't seem to figure out what special things it does. If I embed a youtube video(embed/iframe) it works for both standard and video format. Surely, I am missing something... | **Couple of things to point out actually:**
1. It will add a class on `post_class()` so you can use different formatting via css.
2. In the case of Post Formats, the taxonomy is `post_format` and the terms are `post-format-{format}`. i.e. `taxonomy-post_format-post-format-link.php` <
3. In `single.php` file you can use conditionals to have complete different html for each post format.
4. Hopefully there are more but can remember right now ;) | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 6,
"tags": "post formats"
} |
How to add user registration and signup in WordPress and create members only page?
I'm trying to add a user login system in my WordPress as like regular PHP sites. when a user logged in then , i wanna show the specific page content otherwise no. Is there any process to add nice registration and login system in WordPress and no back end access also ?
thanks | To block users from WordPress back office, you may use this plugin. To show specific page content after login, you need to hook through the redirection filter after login and redirect them to that page directly. If you don't want to write code for it, there is a plugin also. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "user registration, membership, signup"
} |
Displaying icon image for WordPress post formats, is there a cleaner way to do this?
The code I am currently using in the loop is in this code snippet: <
This just seems messy, and long.
I am thinking the best method would really be to use CSS sprites and the post class, but for some reason I cannot put my brain around how to do this.
I created another gist of the output of my WP loop, so you can see the post format is added to the class of the article. Not sure if that is the easiest method to address this, and am appreciative of any help: < | Using CSS and image sprites is exactly what I do in Oenology. (See it in action here.)
Mine is a bit tricky, because I change the post container based on post-format type (some have post headers/titles, others don't; some have left/right margins added; etc. - also, I have dark and light icon sets, based on the color scheme selected). But, here's my code for dynamically generating the CSS (lines 418-598). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development, php, css, post formats"
} |
What function can I use consistently to escape possible HTML for editing and display?
I'm very new to WP, and from following books and online examples, I have several different 'esacping' functions in my first plugin. I would like to know if there is one function, or a minimal set of functions, I can use to prevent malicious HTML stored in my DB from doing anything bad. I would, however, always like to store text exactly as it is captured, and only sanitize it when presenting it. | Well, I would start with the one called **`esc_html()`**.
**EDIT**
Longer answer:
You should perform _sanitization_ on _input_ , and _escaping_ on _output_.
To **sanitize HTML** content on _input_ , I would use one of the `kses()` family of filters - particularly, **`wp_kses_post()`**, which will filter all but the HTML tags allowed via the Post Editor.
To **escape HTML** content on _output_ , I would use **`esc_html()`**, which escapes HTML blocks for output. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, plugin development"
} |
WP-PageNavi not working on Custom page Template
this is my code in Custom page Template
<?php query_posts('showposts=8'); ?>
<?php
$count = 1;
if (have_posts()) : while (have_posts()) : the_post(); if($count == 1) : ?>
& this is wp_pagenavi code
<div class="more_entries">
<?php if (function_exists('wp_pagenavi')) wp_pagenavi(); else { ?><?php } ?></div>
</div>
page numbers showing but navigation not working | Looks like **Old Famous Problem** with `paged`
try this for `quey_posts();`
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(array(
'posts_per_page' => 8,
'paged' => $paged
)
); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugin wp pagenavi"
} |
Is there a maintenance mode in Wordpress core?
If I want to put a Wordpress (3.2.1) site into Maintenance mode, is it still necessary to use a plugin? If so, is this a good option? | Yes there is. But it is primarily meant for short interruptions (such as during upgrades) and not very user-friendly. WP creates `.maintenance` file in root (with timestamp info about time) to trigger it and removes after it is done.
See WordPress Maintenance Mode Without a Plugin for reference.
In practice using a plugin is usually more convenient and functional. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "plugins, maintenance, offline"
} |
How to display custom style based on theme option select box
How can I display a different style snippet if a user selects and option from my theme options page select box.
For example. To show the sidebar on the right a user would select "Right" and the default stylesheet would be used. However, if they chose "Left" to display it on the left, a small style snippet would appear that overrides the default stylesheet.
This is how I do it for checkboxes if that helps.
<?php if ( of_get_option('show_post_sidebar', false ) ) { ?>
<!-- default styles would be used -->
<?php } else {?>
<style type="text/css" media="screen">
.post{width:720px}
</style>
<?php } ?> | Just put your dynamic CSS inside of a callback function, hooked into `wp_print_script`, e.g.
function mytheme_custom_css() {
?>
<script type="text/css">
<?php if ( of_get_option('show_post_sidebar', true ) ) { ?>
.post{width:720px}
<?php } ?>
</script>
<?php
}
add_action( 'wp_print_scripts', 'mytheme_custom_css' );
Add as few, or as many, conditional CSS rules as you need. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "css, options, select"
} |
How to use a custom comments template
My wordpress makes use of custom post templates. I'm now trying to create a custom comments template as well.
I noticed that the comments template is called via this function `<?php comments_template( '', true ); ?>`
I checked in my functions.php and comments.php but don't see the function being declared anywhere. Can someone please advise on how to go about introducing a custom comments template? | The `comments_template()` template tag sets up the commenting variables and functions, and includes the `comments.php` template-part file. So, to create a custom comments template, use `comments.php`.
From there, you will need to get comfortable with the arguments, filters, and callbacks for `wp_list_comments()`, which is used to output the comment list, and `comment_form()`, which is used to output the comment-reply form. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "comments"
} |
Define orderby in url
is there a way to set the order of posts via the url?
/orderby/date/order/desc/
i have tried several things with add_rewrite_rule whiteout success.
add_action( 'init', 'wpse13483_init' );
function wpse13483_init()
{
add_rewrite_rule( 'category/(.+?)/orderby/([^/]+)/order/([^/]+)(/page/?([0-9]{1,}))?/?$', 'index.php?category_name=$matches[1]&paged=$matches[5]&orderby=$matches[2]&order=$matches[3]', 'top' );
}
best, Dan. | adding this in the functions.php file works. Just **remember to re-save your permalinks** & empty the cache a few times to see the changes.
add_action( 'init', 'wpse13483_init' );
function wpse13483_init() {
add_rewrite_rule( 'category/(.+?)/orderby/([^/]+)?/?$', 'index.php?category_name=$matches[1]&orderby=$matches[2]&order=asc', 'top' );
add_rewrite_rule( 'category/(.+?)/orderby/([^/]+)/order/([^/]+)?/?$', 'index.php?category_name=$matches[1]&orderby=$matches[2]&order=$matches[3]', 'top' );
// with pagination;
add_rewrite_rule( 'category/(.+?)/orderby/([^/]+)/order/([^/]+)/page/([0-9]{1,})?/?$', 'index.php?category_name=$matches[1]&orderby=$matches[2]&order=$matches[3]&paged=$matches[4]', 'top' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "url rewriting, urls, order"
} |
Multisite: should /blog go to a 404 page?
I have a WP multisite installation. All the posts for the default blog are in the subdirectory /blog. All those URLs are fine, all the category and archive links work well. However, visiting the "www.domain.com/blog/" URL leads to a 404. Is this expected behaviour?
I thought it might be something to do with my particular install, but I checked another and it seems to be the same.
I'm running version 3.2.1 | Normal.
Make a page called "blog" and use a blog page template and it works.
Proof: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite, permalinks"
} |
hook a functions to change wp-config from functions.php
is there a way to hook / filter or add action that would be printed in the wp-config file? lets say i want to add some simple command like "empty the trash" aka
define('EMPTY_TRASH_DAYS', 1 );
This should be changes in the wp-config but i want it to go with theme..
Any way to do that? | There is, as far as I know, no way to hook into `wp-config.php` from a Theme. For one, `wp-config.php` shouldn't be writeable; for another, `wp-config.php` is executed well-before a Theme's `functions.php` file is parsed. For a great overview of how WordPress boots, have a look at this two-part post by Theme.FM (part 1, part 2) or this Explanation with a flowchart by @Rarst.
You might want to look into removing the `define()` from `wp-config.php`, and moving it into the Theme? I'll have to look to see where it gets used, but there's a good chance that WordPress won't have looked for it before `functions.php` gets parsed.
**EDIT**
As per @ChristopherDavis' comment below, `EMPTY_TRASH_DAYS` gets defined at `wp-settings.php`, via `default-constants.php`. So, you _have_ to define it in `wp-config.php`, if you want to override the default.
**p.s. why would you want to define the number of trash days in a _Theme_ , anyway?** | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 5,
"tags": "functions, wp config"
} |
How to use "offset" to paginate get_users?
Is is possible to paginate the get_users function with the "offset" parameter?
I have complete my custom query of users for my list and now I need to paginate the results into multiple pages.
Here is my sample code:
<ul>
<?php
$args = array(
'meta_key' => 'jabber',
'meta_value' => 'User Name',
'meta_compare' => 'LIKE',
'order' => 'ASC',
'count_total' => true,
'fields' => 'all',
);
$blogusers = get_users($args_1);
foreach ($blogusers as $user) {
$user_id = $user->ID;
$user = get_userdata($user_id);
echo '<li class="provider-list prov-list-gradient">' . $user->display_name . '</li>';
}
?>
</ul>
If there's anyone you can give some advice I would appreciate it.
Thanks in advanced. | $args = array("role" => "subscriber", "number" => 10);
get_users($args); //First 10 Users with the Role Subscriber
$args['offset'] = 10;
get_users($args); //10th to 20th Users with the Role Subscriber
and so on.
Offset = page * number | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "pagination, list, users"
} |
Cannot upload themes. Error: "The uploaded file could not be moved to /var/www/wp-uploads/localhost/2011/10."
The uploaded file could not be moved to /var/www/wp-uploads/localhost/2011/10.
That's the error message I get when I try to upload a wordpress theme. This is my current permission status of my folder.
$ sudo ls -la /var/www/wp-uploads/localhost
total 12
drwxrwxr-- 3 root www-data 4096 2011-10-27 16:44 .
drwxr-x--- 3 root www-data 4096 2011-10-27 15:45 ..
drwxrwxr-- 3 www-data www-data 4096 2011-10-27 16:44 2011
Is there a terminal command I can use to allow wordpress to have permission to write things in this folder?
I use LAMP and Ubuntu 11.04.
Thank you. | From quick search of source for this error message, it is likely to be triggered by failed `move_uploaded_file()` function call, which is native PHP and not WordPress.
Documentation says that it has some restrictions, related to `safe_mode` and `open_basedir` so that might be your issue.
Since WP suppresses error output from this function with `@` directive I'd try to emulate such file move or un-suppress error (as far as I know this is not possible natively, but possible with xdebug and possibly other debuggers). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "uploads, permissions"
} |
How to set privilege to wordpress subscriber for private page
I am having private page.I want to show this page only when "subscriber" logged in."Editor" should not access this page.How can i set the privilege. | Without a plugin something like this should work
//functions.php
function get_user_role() {
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
return $user_role;
}
//page template
$role = get_user_role();
if($role == "subscriber"){
//cool you can see this
}
else {
//sorry not allowed
}
A BETTER way would be to use something like the Members Plugins which lets you have custom roles and check roles and such. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "user access, private, privileges"
} |
How to add post of custom type to a category with custom type capabilities
I have created a custom post type 'shows'. And I am using the capabilities argument to create my own custom capabilities. My aim is to have a user (`show_manager`, say) who can only edit/create shows and nothing else.
I have managed this, but the `show_manager` is unable to add their (show) post to a category. The metabox appears, but the choices are disabled. I don't need (in fact don't want) them to be able to create / delete categories, but just to select one they want the show to go into.
I have noticed, giving the `show_manager` the `edit_posts` capability allows them to select a category - but also allows them to edit posts (something I don't want).
How can I give the `show_manager` the ability to assign a category to their term without allowing them to `edit posts`? | I have found the cause of this problem. The reason is due to the capabilities argument in the `category` taxonomy. i.e.
array(
'manage_terms' => 'manage_categories',
'edit_terms' => 'manage_categories',
'delete_terms' => 'manage_categories',
'assign_terms' => 'edit_posts',
);
So one work around (though not a very good one - and certainly not for use in plugins!) is to _redefine_ the Category taxonomy, mapping the 'assign_terms' to some other capability (maybe a custom defined one). This capability can then be given to anyone who I want to be able to assign categories. See the Codex page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, capabilities"
} |
Can I change the "Home" text in the menu?
I’m pretty sure this can be done with a filter or some kind of find and replace, but I’m not sure how.
I have a page called “Home” like so:
!Screenshot
When the link is displayed in my template it says “Home”. I’d like it to say “About Us”.
I want the user to know which page the homepage is in the Page Overview panel, but I’d like to be able to name it whatever I like in my template without displaying the word "Home". Any ideas? | What I did was really simple...In the admin panel I left the name as home, then I used conditional statements to change the name.
For the navigation I used:
<ul>
<li <?php if ( is_home() ) { ?>class="current_page_item"<?php } ?>><a href="<?php bloginfo('url') ?>">About Us</a></li>
<?php $args = array("exclude" => "".page_name('Homepage').", "title_li" => ""); wp_list_pages( $args ); ?>
</ul>
For the title I used:
<?php if ( is_home() ) { ?>
<h2>About Us</h2>
<?php } else { ?>
<h2><?php the_title(); ?></h2>
<?php } ?>
I'm sure there are other ways to do this, but this is how I was able to solve it!! Hope this helps someone :) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "pages, filters, title, customization, homepage"
} |
Hide featured post from second page
This is my category page code
<\--Featured Post start-->
<?php
$count = 1;
if (have_posts()) : while (have_posts()) : the_post(); if($count == 1) : ?>
<a href="<?php the_permalink() ?>" rel="bookmark" title=""><?php the_title(); ?></a>
<--Featured Post start-->
<?php else : ?>
<\--Rest of Posts -->
<a href="<?php the_permalink() ?>" rel="bookmark" title=""><?php the_title(); ?></a>
* * *
<?php if (function_exists('wp_pagenavi')) wp_pagenavi(); else { ?>
<?php } ?>
i dont want featured post to be display after first page, how to prevent ? | if($count == 1 && !is_paged() ) :
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "featured post"
} |
Log Author Actions
Is there a place where actions like post creation/deletion, page creation/deletion, modification, etc. is saved? Is this stored in the Apache logs?
If this is not saved, is there a way (plugin?) to do this? | There is a plugin called Audit Trail. It will pretty much log all actions for your wordpress backend such as page creation / deletion, post creation / deletion, logging in / logging out.
You can find it here: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "server, logging"
} |
How to force "remember me" users to login again?
My question is how to force the users that are auto-logged in because they previously checked "remember me" to log in again?
It may be something with cookies, but is there anything I can change/modify to do this ?
Thank you.
**UPDATE**
Generally, using jQuery cookie plugin, the code that checks for a cookie in user's system looks like this.
$(document).ready(function(){
if(!$.cookie('name-of-cookie')){
$.cookie('name-of-cookie', 'true', { expires: 2});
.
.
}
Is there any similar in Wordpress to handle this? | You can reset the security keys, forcing all cookies to expire and all users to log back in. Edit wp-config.php and change even one character in any of the security strings.
There's a plugin that allows you to set the expiry time on your user's cookies. I haven't personally used it, so proceed with caution: Cookie Timout
Sending the user back to `/wp-login.php?reauth=true` removes the cookie and logs the user out, even if he was previously logged in with a cookie.
Finally, if you're developing a plugin or theme, you can call `wp_clear_auth_cookie();` and the currently-logged-in user's cookie will be cleared. This will not necessarily log the user out, but it will remove the cookie for the next time the user visits the site. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "login, cookies"
} |
Are Nonces Useless?
This is probably a noob question BUT hear me out - isn't the point of using Nonce to protect from things like scrappers (phpcurl scrappers etc.)? But my Nonce prints out in the head of the document like so:
/* <![CDATA[ */
var nc_ajax_getpost = {
...stuff...
getpostNonce: "8a3318a44c"
};
/* ]]> */
So if I was building a quick scrapper I would just get the nonce value from that page and then use it in my POST...making the whole exercise of using a Nonce useless...
What am I missing here? | Nonces are unique to each logged-in user. You can't scrape a logged-in user's nonces unless you have their cookies. But if you have a user's cookies, you've already stolen their identity and can do whatever you want.
Nonces are meant to protect against users being tricked into doing something they didn't mean to do, by clicking a link or submitting a form. So they, themselves, perform this action (unintentionally), not the attacker. | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 11,
"tags": "security, nonce"
} |
Is it possible to use github:gist with Wordpress?
I have a wordpress blog i.e. bruno.wordpress.com I would like to use github:gist.
I paste my code in gist and get a link like: <
Is there a way to show this code in my blog? (rather than just a link to the code.) | No.
As scribu mentions, you can do this on a self-hosted WordPress site with a plugin. In WordPress.com, though, you don't have access to these plugins and must depend on the oEmbed support WordPress.com extends you by default.
Your best bet is to contact their support team directly and ask if/when they'll have support for Gist via oEmbed. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "wordpress.com hosting, code, embed"
} |
widgetlogic and permalinks
I'm trying to use widgetlogic to conditionally display menus on certain pages. Each menu uses a tag like `is_page(array("Page Name", "Page Name 2" ...))`, and works perfectly until I try to change permalinks (whereupon all the menus disappear from their respective pages).
Am I doing something wrong? Is there a workaround? | Changing permalinks should have absolutely no affect whatsoever on the parameters passed to `is_page()`. Are you perhaps changing the **Page Titles** instead?
Regardless, try passing the **Page ID** instead of the **Page Title** to your `is_page()` array. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "widgets, permalinks"
} |
Translate Navigation Menu & Sidebar Widget Titles
Is there any plugin to translate navigation menu & sidebar widget titles ? | Anyway, I found my answer.
I used `qTranslate` to translate menu wordings as well as widget titles. Free & useful. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "translation"
} |
How do I insert an already uploaded video file into my Media Library?
I'm having problems with the WP uploader (hosting issue); WP is pooping out after uploading files that are relatively large (> 32MB).
**My idea was to upload the video file via SFTP to the server and then try to get WP to insert it into the Media Library. How do I do this?**
I know that it isn't as simple as just putting it into `wp-content/uploads/<date-path>/` because there is some meta-data to add to the back-end DB.
I've seen some posts for `media_sideload_image` but looking at the code, it looks like this is specifically for images. I looked at `media_handle_sideload` but I'm not sure how it works or how to create a solution to insert this file where it needs to go. For example, the comments say:
> @param array $file_array Array similar to a {@link $_FILES} upload array
What does `{@link $_FILES} upload array` mean? | Add From Server will do this for you | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "uploads"
} |
Adding submit or update button to custom metabox?
I have alot of custom meta boxes, and the user has to scroll to the top everytime he wants to save the meta info.
Is there a way to put submit buttons at every meta box that does that same as the update button? | Don't know if i agree with EarnestoDev answer which is more of an opinion then an answer based on facts and not true in all cases, since you can use jQuery to trigger the submit event when a different element is clicked, so just add this js code once
<script>
jQuery('.metabox_submit').click(function(e) {
e.preventDefault();
jQuery('#publish').click();
});
</script>
and in each metabox add:
<input type="submit" class="metabox_submit" value="Submit" /> | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 3,
"tags": "metabox, buttons"
} |
WP Query get only 1 post (sticky, not sticky etc)
I'm using WP Query & want to only return 1 post in a category.
Either the most recent sticky else the latest post.
Is this possible?
Thanks, George
<?php
$category1 = new WP_Query();
$category1->query( array('showposts' => 1, 'category_name' => 'hapless ' ));
while ($category1->have_posts()) : $category1->the_post(); ?>
<h3><a href="<?php the_permalink() ?>" rel="bookmark" title="Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<?php the_post_thumbnail(); ?>
<?php endwhile; ?> | Why don't you use a fat-free **$wpdb->get_var()** for the task?
global $wpdb;
$ID = $wpdb->get_var("SELECT `ID` FROM {$wpdb->posts}
WHERE `post_type`='post' AND `post_status`='publish'
ORDER BY `post_date_gmt` DESC LIMIT 1;");
$post = $ID ? get_post($ID) : null; // Now get the actual post
This is way more efficient and light-weight. Without all the bells and whistles of the get_posts() or WP_Query().
Regards.
**UPDATE** : _(more in context)_
function get_last_published_post(){
global $wpdb;
// Get the ID of the last published post (by date)
$ID = $wpdb->get_var("SELECT `ID` FROM {$wpdb->posts}
WHERE `post_type`='post' AND `post_status`='publish'
ORDER BY `post_date_gmt` DESC LIMIT 1;");
return $ID ? get_post($ID) : null; // Now get the actual post
}
// Should print out the Post object
var_dump(get_last_published_post()); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, loop"
} |
Posts 2 Posts plugin: best way to change connection field value?
I have started to use posts-to-posts plugin by scribu, and now I need to change vaues for connection fields. Particularly, I've created 'person' and 'piece', connection 'role' in between and defined possible values for role as 'composer', 'conductor' -- but now I think that I need rather 'author', not 'composer'.
Please, how to do that? I could experiment with phpmyadmin, but I wouldn't like to loose anything in progress.
Thanks! | So, in my case this way hepled: 1) I've replaced `'composer'` with `'author'` in `functions.php` (in that part where connections are being registered) and 2) "edited" data in `${wpdb}_p2pmeta` using phpmyadmin (`UPDATE <yourprefix>_p2pmeta SET meta_value = "author" WHERE meta_value = "composer"` or manually or like that).
Please, backup your data, please test in any way etc. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, plugin posts to posts"
} |
Duplicate homepage to show posts from 1 category
I'm trying to accomplish the following:
I wan't to display all posts from a certain category on a page that has the same layout as the homepage of the actual blog.
I found the following online to display posts for the category
`<?php $recent = new WP_Query("cat=797&showposts=30"); while($recent->have_posts()) : $recent->the_post();?>`
but I don't know
a) should I just take my index.php and edit the loop to the above
b) where should I place this new file? in the root of my WP install or in the themes folder?
EDIT 1:
My homepage is a regular "archive" showing the latest posts for any category
The current loop starts with
<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
<?php global $ar_ID; global $post; $ar_ID[] = $post->ID; ?>
Entire index.php is here | **This should help you, the second diagram... this one.**
Just copy the `index.php` code to the properly named `category-*.php` file and see if it works. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, themes, homepage"
} |
After installing JetPack, can I delete the WordPress stats plugin?
After running the WordPress stats plugin for many years, I've decided to upgrade to JetPack. The installation went smoothly, I connected and authorized my blog with Wordpress.com, and I'm seeing stats.
Is it safe to deactivate and delete my old WordPress stats plugin now? Or do I need to keep it in order to preserve my historical data?
I'm a bit shocked that WordPress hasn't provided a step-by-step upgrade guide for this. | Yes, you can safely deactivate the old wordpress.com stats Plugin. Once you verify that your historical data have been retained, you can safely delete the Plugin. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin jetpack"
} |
Add class to last 3 posts in loop
I have this code so far, which adds the classes first, second, and third to every first, second and third post in the loop. It also adds a class to the first 3 posts in the loop. But how can I make it so that it adds another class to the final 3 posts?
if (have_posts()) :
while (have_posts()) :
the_post();
$classes = array('themeview');
$classes[] = $style_classes[$counter % 3];
if ($counter < 3) $classes[] = 'top';
$class = sprintf('class="%s"', implode(' ', $classes));
$counter++
?>
<li <?php echo $class?>>
Thanks! | WP_Query seems to set two variables, $posts and $post_count when running(according to the source over at < ). You can access these two and work something out to figure out if you're in the last three posts.
var_dump those two to see if there's a count, add in your own counter and you should be good to go.
Edit: it's actually $post_count and $current_post that will be useful to you. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "loop, php"
} |
How can I limit functionality in one version of a plugin?
I am busy writing a plugin with a free version and a paid, Pro version. For our initial release of both versions, I want to keep things as simple as possible, so I would rather defer using a strategy of a very extensible free version, with hooks implemented in a Pro version; I will give this direction some attention for later releases. My next avenue is to simply have two completely separate builds that include some core, shared components, and some components specific to the Pro or Free versions.
The purpose of my question here is to try and gather some advice on my third angle, that of using checks in code that only perform actions etc. if a certain version is running, i.e. if the client calling core services is Free or Pro. What should I be looking at to attempt this avenue of feature limiting? | You alluded to this in your comments, one way is to provide an API key for your plugin, that way your clients are actually paying for support and updates and not code, it's really one of the only decent ways to go about this. For example if their API key is not valid or expires they do not get access to your private forum or any plugin updates ( you would need of course to provide a API for a unique key, external update request and authentication). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "plugins, plugin development, actions, customization, content restriction"
} |
How to prevent certain usernames from being registered?
How can i prevent or blacklist a list of usernames that i don't want users to register with?
And can I add a message if they try to register with one of those names that says 'this username has been reserved'
Is this possible? | Yes there are plugins that do this, for example, < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "user registration, username"
} |
single category widget with conditional terms
iam working on my first wp theme and iam new to php and wordpress. i need to create a single category widget that displays at least five posts from specific category. inside this post loop i need a conditional function to make the first post different from the rest. to be clear iam using a plugin that gives me all the needed option except conditional function that makes the first post different from the others. is there any one could help me By editing the plugin file to add this conditional function . or showing me the entire code from scratch.thanks | To make the first post different you could add a post counter and change the output on the first loop.
$counter = 0
while ( $cat_posts->have_posts() ) {
$cat_posts->the_post();
$counter++;
if ( $counter == 0 ) {
// Out put the different loop
}
//Normal loop output | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, widgets"
} |
Getting rid of the #038; when string replacing content
I'm trying to add some string replacements to the_title() -
function format_title($content) {
$content = str_replace('&','&<br>', $content);
$content = str_replace('!','!<br>', $content);
return $content;
}
add_filter('the_title','format_title',11);
When I try and replace ampersands I get an additional "#038;" after the replacement (ASCII for ampersand), I'm not sure as to why this occurs (security reason?) or how to create a workaround. I've tried replacing "&" with "& amp ;" but with no effect.
The goal is to add line breaks at certain points of a title to create a better flow in the typography. Both the database and the site has UTF8 encoding. | `&` is essentially synonym of `&`. In `the_title` filter `wptexturize()` runs with priority `1` (important!) and makes this replacement.
So by the time it gets to your `format_title()` at priority `11` \- instead of replacing lone `&` symbol you replace (and break) chunk of `&` character entity.
So you can:
1. move your function to priority `0` and it will run before texturize
2. leave priority at `11` but replace `$#38;` instead of just `&` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "customization"
} |
Custom Post Formats for Custom Post Types
The weight of opinion seems to favour using custom post types _instead of_ custom post formats.
I have several custom post types that I want to style in 4 different formats in a way that is not public ie not a category, tag or custom taxonomy.
Custom post formats would seem to provide an ideal solution for this - they're built-in functionality, easily implemented, come with handy meta box, easily applied with conditional statements etc.
The major draw back being they are not readily customisable - I could rename them for the sake of clarity.
So given the prevailing thought, what would be a better approach to creating the same functionality. | You have several options here so I will clarify what you can do.
1. Create a custom post type template page using something like `single-customposttype.php` and take advantage of the template hierarchy, <
2. Use a conditional query for your styling in the loop ( or whatever you're using), along the line of `if (post type= your custom one) style it this way;`. or use some other WordPress conditionals. <
3. Use a taxonomy for back-end organization, custom taxonomies do not have to be public.
4. Use post formats for your custom post type, CPT's can support `post-formats`, <
Most people go with option one, but it depends on what you're trying to do. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 4,
"tags": "custom post types, post formats"
} |
How do i replace the sidebar to use pages instead of blogs?
I want to use wordpress as a CMS and not as a blog. I am using the default twentyeleven theme and i would like to remove 'archive' (the blog ToC) and 'Meta' (login) and replace it with a sidebar seen on a traditional site. The part i am having trouble is how do i do it in a way were i can add pages to the sidebar from within the admin area rather then hardcoding in php?
I also would like it to be in the format below where the heading is not clickable and the entries i can add/remove from the admin area.
# About
person one
person two
# Services
Service A
Service B | An alternative method to what @Tanmoy gave above is to make an additional navigation menu (Appearance - Menus) and call it something like Sidebar-Pages.
Then you can add the headers with a "link" like #. Add the sub-pages you want and save when you're done.
Then go to widgets (Appearance - Widgets) and there you will see a widget called "Custom Menu". Drag that into Main Sidebar and select the menu you just created. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "sidebar"
} |
Wordpress programming video tutorials
I am a beginner in Wordpress programming. I am basically looking out for video tutorials that teach Wordpress programming and specifically creation of plugins and such advanced things. Are there any good video tutorials which teach such sort of stuff? or any courses from training companies like pluralsight. I know pluralsight is not into PHP but are there any other sites? I am even willing to pay for videos. The video tutorials need not be free however free is always welcome.
Thanks in advance :) | Couple of sites I can refer:
1. Start with wordpress codex <
2. < you may find good starting point there.
3. Search Youtube you can find some good ones there too.
4. And if you feel like paying for it try some tutorial series from <
5. Search google. I think its the best way to go :) there are hundreds of sites out there publishing written and video tutorials for beginners and advanced. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins"
} |
Create password automatically for new users?
Is it possible to automatically create a password for a new user?
Ideally, I'm looking for a plugin that, if the password is not given on user creation, would generate one and optionally email it to the user if the checkbox for this is selected. If not, then maybe just show the password after the creation of the user.
Does anyone know if there is a plugin with this behavior or similar behavior? | I was looking for the same thing and I found this plugin:
Simple User Password Generator (by Jake Goldman) - Allows administrators to generate a secure password when adding new users.
!generate password | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "plugin recommendation, users"
} |
Store JSON in a custom field
I have a drawing canvas on some of my Wordpress' post pages, where users can draw on. Upon drawing, my JS code currently sends the user's drawing to a php file. This is where I store the array in JSON format in .txt files. Whenever the page is loaded by someone else, JS loads these JSON files on start, so you see other people's sketches and you can draw on it as well - where the txt files get altered etc etc.
But is it possible to use Wordpress' custom fields? So every post has their own variable where the drawing array is stored. I have no idea what type of custom field to use.. Or whether there is a plugin out there that might be helpful with helping me achieve what I want. Or maybe not a good idea at all to do it this way.
Thanks in advance. | Yes! Yes you can!
You can use this code to retrieve a stored option:
$value = get_post_meta($post->ID,'customfieldname',true); // where true means only return 1 custom field by this name
You can use this code to save a stored option:
update_post_meta($post->ID,'customfieldname',$valuetobestored);
The above code will need to be inside the post loop, though you can supply a post ID from elsewhere, say a GET variable etc and avoid another query
You can also store multiple values with the same custom field name. The value to be stored is a string value, as such a json string is good. The same is true of get_option and update_option for global values.
You can also use meta boxes to customize the UI for showing these values. Custom fields whose names start with `_` will not be shown in the custom fields meta box in the back end ( which is how wordpress hides its own internal custom fields from the end user ) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, javascript"
} |
Save page data to an xml file
Is it possible to continually update an xml file on the server with data from a wordpress page? If so, how could I do it?
I use this plugin < to create the custom data. Would I be able to save this to an xml file?
It's important that this xml file is updated every time a new page is created or edited. | The `save_post` hook gets called each time a post is created or updated. Just hook into that. There you can do something like `fputcsv('/tmp/' . $post_id, $post)` or output to XML/JSON.
== EDIT ==
add_action( 'save_post', 'wp239s5_post_to_xml', 10, 2 );
function wp239s5_post_to_xml( $post_id, $post ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
//convert $post to xml here
} | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 2,
"tags": "custom field, xml"
} |
Custom post type pagination like "previous current/all next"
I have custom post type `works` with custom taxonomy `work_category` I want to build such pagination while viewing `single.php`
**previous 2/25 next**
[`link to previous post in custom tax`] [`current post number`]/[`all post number from custom tax`] [`next post in custom tax`]
Currently i can't get `current post number` | I've solved it
For previous/next use Ambrosite Next/Previous Post Link Plus
To get current/all use following code inside the loop
$query = new WP_Query( array(
'post_type' => 'works',
'post_status' => 'publish',
'posts_per_page' => '-1',
'tax_query' => array(
array(
'taxonomy' => 'work_category',
'field' => 'slug',
'terms' => 'design'
)
),
'order' => 'ASC'
) );
$all = $query->post_count;
foreach( $query->posts as $key => $p )
if( $post->ID == $p->ID ) $current = $key + 1;
echo $current.'/'.$all; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pagination"
} |
Rewrite a category
How do I rewrite a category url that has a number at the end, to a url with no number using wordpress url rewriter? and... Why is there a number appended to all category url's?
< | You cannot use the same term for a category, page, tag as they need to be unique.
When you do, you'll get a number next to the slug
To fix them you'll need to fix the tag or page slug otherwise edit the category slug last
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories, url rewriting, urls"
} |
Custom Meta Box calling JS function twice
I have a plugin adding a custom meta box to the comments editing page:
function on_admin_init() {
add_meta_box(
'commentrating',
__( 'Voto recensione', FB_DT_TEXTDOMAIN ),
array( &$this, 'meta_box_voto' ),
'comment', 'normal', 'high'
);
}
function meta_box_voto($data) {
...
?>
<script>
jQuery(document).ready(function() {
alert("ah!");
});
</script>
<?php
} ...
But the alert is called twice! Is this a WP or jQuery bug? Am I making any mistake?
Thanks!
P.S. If I put the alert into the first function it is only called once... | Put the JS in the `admin_footer`. If the Widgets are moved, your JS tag code can be duplicated hence called twice. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "metabox"
} |
How to include post count in this "get_tags" snippet
Can anyone tell me how I can show a post count in this code snippet?
<?php $tags = get_tags();
if ($tags) {
foreach ($tags as $tag) {
echo '<li><a href="' . get_tag_link( $tag->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . '>' . $tag->name.'</a> </li> ';
}
};?> | where exactly? example below is for the count getting shown in brackets after the tag name, outside the link:
<?php
$tags = get_tags();
if ($tags) {
foreach ($tags as $tag) {
echo '<li><a href="' . get_tag_link( $tag->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . '>' . $tag->name.'</a> ('.$tag->count.') </li> ';
}
};
?>
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "tags, query, array"
} |
Using same slug name for a page and category
I know it isn't good practice but I'm considering using same name slugs for some pages and categories on a site that I'm working on. It's a small site and it doesn't seem to affect anything in particular. I added one slug and page with the same name and they worked fine, but when creating a second WP forced me to rename the page (being created after the category) with an additional "-2" being added to the slug. Is there a particular order to create the pages and categories in order to avoid this? I've created similar structures before without this appearing. Also checked trash for old pages that might be using the original slug. | I used to do the same thing - create a page with the same name as a category to use as a faux index page.
I think I used this No Category Base plugin to remove the /category/ bit from the URL. (I _think_ it was this plugin.)
> [...] this plugin will completely remove the mandatory 'Category Base' from your category permalinks ( e.g. myblog.com/category/my-category/ to myblog.com/my-category/ ). | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "categories, pages, slug"
} |
Dynamically add / duplicate custom meta in custom post types
I am using Custom post types in one of my themes
I have one custom post type called "accommodation" with meta boxes to add details such as type of rooms (single, twin, double...); each room has a price according to different season (high season, low season, peak season - each could be ). However the room types could differ among individual "accommodation" post entries (suppose one has a room called "de luxe", another has a room type "budget", not just single, twin double), and not all entries have the same rooms (ie some could not have a "dorm" type), therefore the admin should be able to manually insert different types of rooms. Each room should have a price too. And each room could have price variation according to season. Season period should be defined with a range date picker. Additionally, there could be multiple high/low season within the year.
How would you arrange this?
thanks a lot for any help! | I will answer myself after some research :)
while there might be appropriate ways of coding this with some custom function, for me there's no need to reinvent the wheel when there's a neat plugin that does the job
it's called "advanced custom fields"
<
it has a "repeater" to let admins add more fields dynamically
it also manages datepicks and fieldsets... basically everything I need!
hope this is helpful to others | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, custom field, customization, metabox"
} |
Localization: I want the backend: english and frontend in defined language
I'd like to have the backend of Wordpress in English and use a different locale for the frontend
so far I figure out perhaps I could do it by setting in the wpconfig the locale I want to use in the frontend, then add in functions.php something like this:
add_filter('locale', 'mytheme_backendlocale');
function mytheme_backendlocale($locale) {
if ( is_admin() ) {
return 'en_US';
}
return $locale;
}
is this the best practice to achieve what I want or should I do it differently? | Install the plugin WP Native Dashboard. Then you can set one language for the front-end in your `wp-config.php` and each user can choose another one for the back-end.
See Change language of comments template for details and a screenshot. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 9,
"tags": "customization, multi language, front end, translation, localization"
} |
Need a wordpress plugin to show tutorial difficulty
In my blog, I sometimes post "how to" style tutorial posts. I would like to show a difficulty gauge next to the post title like 'assumed knowledge', 'time to complete', 'frustration level', 'cost' etc. They should show up in excerpts, the main page and in posts too.
Unfortunately googling with keywords "wordpress tutorial difficulty plugin" gave me irrelevant result (pages of plugin making tutorials, or plugin installation difficulties.)
The only relevant thing I found is this abandoned stack overflow post: <
Anyone know a plugin that can be used for this? | You don't need a plugin to do this. Why not just use the wordpress custom fields feature to add your custom meta data to the posts.
<
You can create a custom field for each that the person adding the tutorial fills in. Then take that value that is entered and add it as a class to the difficulty html on the front end which you can use to style it.
Eg, you have a div that outputs the difficulty
<div class="difficulty beginner">beginner</div>
The value "beginner" added in the div above is what was selected by the user when filling out the tutorial post.
In the post page, it would be something like this
`<?php $difficulty = get_post_meta(get_the_ID(), 'difficulty');?>`
`<div class="difficulty <?php echo $difficulty ?>"><?php echo $difficulty ?></div>` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, plugin recommendation"
} |
How can i manually relate pages?
I've got a custom post type called Products, which underneath i've got a related products section using a plugin called <
I need to be able to create some more post types for example called Accessories and Supplies. I need to be able to relate some accessories to products. How can i make it so when i add an accessory or supply i can say this relates to a certain product and shows in the related products section. | 2 possible solutions spring to mind, both fairly straightforward:
1. Use a custom taxonomy to create groups then add the accessories and main product to the same group
2. Add an interface that updates the post_parent field to mark items as accessories for a specific product
With either of these approaches you get a fairly easy way to group the products together although the taxonomy approach allows for more flexibility if there are accessories that could be used for multiple products. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
What is wrong here? Issue with post_id and meta_value
I'm trying to create a loop to read all the meta_value records from a given post_id. The idea is to gather all the meta_value's data from wp_postmeta table related to post_id number and print them as a list. But so far, I couldn't make this work. The issue is my 'custom_fields' variable. There I need to put my meta_key. But I have several meta_key per post_id. For example, the post_id 2171 has data2,date3,data4,data5.. data19 as meta_key. So, how can I get this working?
function jb_applicant() {
global $wpdb;
$custom_fields = get_post_custom(2171); //2171 is the post_id that I'm trying to gather the data from
$my_custom_field = $custom_fields['data2'];
$op = '';
foreach ( $my_custom_field as $key => $value ) {
$op .= $key . " => " . $value . "<br />";
}
return $op;
}
add_shortcode('applicant', 'jb_applicant');
Thanks | You're close, but not quite. Try it like this:
function jb_applicant() {
$custom_fields = get_post_custom(2171);
$op = '';
foreach ( $custom_fields as $key => $value ) {
$op .= $key . " => " . $value . "<br />";
}
return $op;
}
add_shortcode('applicant', 'jb_applicant'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, table"
} |
Get page ID of page that is set as the posts page
In WordPress settings you can set a page as the `Posts Page`. This can be found:
WP-Admin->Settings->Reading Settings->Front page displays
!Front page displays settings
How do I retrieve the page ID that is set in this setting? | Use the `page_for_posts` option:
<?php
$page_for_posts = get_option( 'page_for_posts' );
?>
This will return the ID of the Page assigned to display the Blog Posts Index. | stackexchange-wordpress | {
"answer_score": 110,
"question_score": 65,
"tags": "posts, options, id"
} |
Hiding a Categories content on just the Homepage 'Posts'?
Is there a way I can hide a certain categories content from just the homepage Posts section of my Wordpress Site? So, those posts are still posted and live; just not visible nor accessible from the homepage posts area. I'm calling the category twice on the homepage; once in the header within a plugin I'm using, and the other where the posts are created by default by Wordpress. How can I hide my 'featured' category in the main page content of recent posts on the homepage? | Okay, it sounds like you'll want to modify the primary Loop using `query_posts()`, but only on the **Site Front Page**.
I don't think TwentyTen includes a `front-page.php` template file, so we'll modify `index.php` directly. Add the following code to `index.php`, anywhere _before the Loop output_ :
<?php
// Determine if we're on the site Front Page
if ( is_front_page() ) {
// Globalize $wp_query
global $wp_query;
// Create argument array in which we
// exclude desired category IDs. Categories
// are listed as a comma-separated string.
// e.g. '-3', or '-1,-2,-3'
$exclude_cats = array( 'cat' => '-3' );
// Merge custom arguments with default query args array
$custom_query_args = array_merge( $wp_query->query, $exclude_cats );
// Query posts using our modified argument array
query_posts( $custom_query_args );
} // is_front_page()
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories"
} |
Sanitatizing when using the posts_where hook
I am altering the WordPress query, using the `posts_where` hook, when a (custom) query variable is set as follows:
add_filter('posts_where', 'my_posts_where' );
function my_posts_where( $where ){
global $wp_query;
if( isset( $wp_query->query_vars['customvar'] )) {
$custom_Var = $wp_query->query_vars['customvar'];
$where .= " AND wp_MyTable.Column ='".$custom_Var."' ";
}
return $where;
}
This works well, but I want to **sanitize** it. In particular, I've tried using `$wpdb->prepare()` method:
$where .= $wpdb->prepare(" AND wp_MyTable.Column = %s", $custom_Var);
But this doesn't work (I just get a blank page). Why is this and is there another / better way of sanitizing the variable? | Your last `prepare()` snippet should work just fine, check that you have `$wpdb` declared as global in your function.
Also blank page seems extreme, enable `WP_DEBUG` if not yet and see if there are any specific errors that cause it. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "sanitization"
} |
How do I include background images in my stylesheets in a plugin?
I'm trying to specify a background image in a style in a plugin I'm making. I was just outputing tags from the php, but realized I should probably be using enqueue_style... But how do I put a line of code like this:
.star.half {
background:url(<?php echo plugins_url(); ?>/my-plugin/images/star-half.png) no-repeat 0px 0px;
}
Into a plain .css file? What do I put where it says `<?php echo plugins_url(); ?>`? | Just add a **STYLE** tag in `'wp_head'`.
// Anonymous function, PHP 5.3+, extract function for 5.2
add_action('wp_head', function(){
echo '<style type="text/css">';
// Add background style here
echo '</style>';
});
Add this in your `functions.php`. Don't stuff too much CSS in it, just the dynamic bg image you need.
It's not the easiest thing to create a dynamic CSS file so, just for a bg image, use this method. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugin development, css"
} |
Gallery Shortcode: using size="full" doesn't call the actual thumbnail image size
I have my Media settings set up so that my thumbnail size is 60x60 pixels and the "Crop thumbnail" box is checked. I can see in the /uploads folder that there are in fact perfect square 60x60 thumbnails being generated for all the images are being uploaded.
However, when I use the gallery shortcode like this:
[gallery size="thumb"]
It's not actually calling that image thumbnail file. What it is outputting instead is the originally uploaded image source file and scaling it down using width="" and height="" attributes creating a proportional scale down to 60 pixels in width like this:
`<img width="60" height="45" src="/uploads/original-source.jpg" />`
But I need it to be doing this:
`<img width="60" height="60" src="uploads/original-source-60x60.jpg" />`
Has anyone else run into this problem? | Is it thumb or full that is the problem?
Firstly, here is the codex page about the [gallery] shortcode
<
Notice that thumb is actually "thumbnail"
So its [gallery size="thumbnail"] for the thumb image.
If you are having issues with [gallery size="full"] then my initial thinking is that there are no images uploaded after you set the size in the post.
Try open the post again and upload fresh images and see if that works. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, gallery"
} |
Unix timestamp for post comment
Is there any function/code snippet to retrieve the unix time stamp of the comment on a post? The WordPress default function `comment_time();` returns the time of the post in 12hr format (not helpful). | Use:
global $comment;
$timestamp = strtotime("{$comment->comment_date_gmt} GMT");
Regards. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments"
} |
Extend WordPress search to include user search
There is many a WordPress plugin out there that enhances WordPress search but I have yet to find a plugin that will add user search.
Search Everything used to have the functionality but was removed when WP moved to version 2.8. I suspect this was due to the way WP changed how authors were stored.
The reason why I'm after user search is because all users on the WP site are staff members with their own profile. We have an author page that lists all staff by surname that is separated by 20 members per page. If you only know the first name of a member of staff then trying to find that member is very hard. I want to extend WP search so you can simply enter a name and the corresponding member shows up.
This site is an intranet so using an external search engine is out of the question.
Just want to be clear that I'm wanting to search for users not search for posts by author.
How can I get staff member search added? | You can't achieve this easily with WP's built-in search system. Even if you managed to build a complicated query that pulls data from the user table, it would be incredibly slow.
Search Unleashed had this functionality, but I'm not sure about compatibility with WP 3.2.
I used it in the past as inspiration to add better search functionality on my site. Basically it gathers data on content publishing hooks, which then gets indexed and stored somewhere for faster accessing, for example a custom db table, or in special files if you're using the Lucene search engine.
If you really want to go the WP way, see this question. You need to join $wpdb->users on post_author. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 9,
"tags": "search, author"
} |
How-to show last 5 posts
How-to show last 5 posts that are published after current post?
Explained on image below:
IMAGE FOR EXPLAINE | global $wpdb, $post; // Uses current POST here
$IDs = $wpdb->get_col("SELECT `ID` FROM {$wpdb->posts}
WHERE `post_type`='{$post->post_type}' AND `post_status`='publish' AND `ID`<{$post->ID}
ORDER BY `ID` DESC LIMIT 5;");
This function lists the 5 posts with IDs lower then `ID 176` that are of `post_type='post'` and `post_status='publish'`. Change post_type if you use a custom post type to whatever you need. You can also order by `post_date_gmt` if you want.
Regards. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts"
} |
Retrieve post info within AJAX helper function
I have a button within a post which a user can click. Once clicked, an AJAX call is made.
My question is, within my PHP AJAX helper function (located in my theme's function.php) how can I retrieve, for instance, the ID of the post that the request was sent from.
I can get the ID from the markup and pass it in the AJAX call but it seems messy, i.e.
<article id="post-12">
<!-- article content -->
</article>
// JS
var postID = $("article").attr("id");
Is there a better way? Some kind of global that is accessible perhaps? | Use `wp_localize_script()` to declare globals.
**Example:**
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
You could store your query results there and access them later. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "jquery, ajax, front end"
} |
Is it possible to search authors by profile field?
Yeah, is there a way to add a search function that only searches through author profiles?
For example, if someone is searching for authors called John Smith, is there a way to have a search form that ONLY searches in author.php? | You can use Relevanssi \- Uncheck all boxes except for "Index and search your Authors" - see screenshot below.
!Relevanssi Screenshot | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "search, author"
} |
Creating author profiles with extra fields and exporting that data?
I'm trying to find a way to let my subscribers sign up to my site and enter details in their author pages to confirm their attendance at an event. In order to create the additional fields, I've been following this excellent tutorial by Justin Tadlock:
<
However, I need a way to export that information - is there a plugin that would let me do that? Or a useful resource for building something that would let me export that info as a csv file?
Thanks for any pointers,
Osu | Free (also has details at < allows one to define the data in a user list and then export to csv that list. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field, author"
} |
When developing a distributable Theme, does it HAVE to be "inheritable"?
I'm currently developing a complex Theme (or framework, if it can be called that) for my own personal use.
However, in the event that it becomes appreciated to the public - does it necessarily _HAVE_ to be inheritable (the ability to have **Child Themes** derive from it)?
Am I right in guessing that there is some publicly available **Themes** that are filed under some sort of "non-extendable" category? | > However, in the event that it becomes appreciated to the public - does it necessarily HAVE to be inheritable (the ability to have Child Themes derive from it)?
While you can certainly make life difficult on users who try to use your Theme as a template for a Child Theme, it is all but impossible to _prevent_ your Theme from being used as such.
> Am I right in guessing that there is some publicly available Themes that are filed under some sort of "non-extendable" category?
What do you mean by "filed under"? Who's file system? Who's categorization? WordPress itself makes no such categorization. It simply uses Themes if they exist, and are valid - whether stand-alone Themes, or Child Themes using a template.
Is there any particular reason that you would _want_ your Theme to be unable to be used as a Child Theme template? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "theme development, child theme, framework, directory, customization"
} |
Get page permalink without wpurl
I currently have an ID of a page that I want to use its permalink as the front of a permastruct of a CPT I'm setting up.
Now I can use get_permalink() but that returns the full URL:
`
but all I want to return is `imapage/subpage/subsubpage`
Is there a function that can do this or do I have to device something that can subtract the non-needed part of the url? | There's nothing built in to return the bit you want but it should be as easy as using the home_url() function and removing it's output from the full url eg:
function get_relative_permalink( $url ) {
return str_replace( home_url(), "", $url );
} | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 10,
"tags": "permalinks"
} |
wp_nav_menu: show menu only if one exists, otherwise show nothing
I'm trying to use wp_nav_menu to only display a menu if one exists, otherwise, display nothing.
If I delete the menu, it will output a list of the pages.
My functions.php file contains:
if (function_exists('register_nav_menus')) {
register_nav_menus (
array('main_nav' => 'Main Navigation Menu'));}
How can I use wp_nav_menu to only display a menu if one exists, otherwise show nothing? | Use `has_nav_menu()`, and test for `theme_location`, rather than `menu_id`:
<?php
if ( has_nav_menu( $theme_location ) ) {
// User has assigned menu to this location;
// output it
wp_nav_menu( array(
'theme_location' => $theme_location,
'menu_class' => 'nav',
'container' => ''
) );
}
?>
You can output alternate content, by adding an `else` clause.
**EDIT**
You need to replace `$theme_location` with your _actual_ `theme_location`:
<?php
if ( has_nav_menu( 'main_nav' ) ) {
// User has assigned menu to this location;
// output it
wp_nav_menu( array(
'theme_location' => 'main_nav',
'menu_class' => 'nav',
'container' => ''
) );
}
?> | stackexchange-wordpress | {
"answer_score": 24,
"question_score": 14,
"tags": "menus, pages, list"
} |
Knowledgebase / Docs: Custom Post Type, Pages or as a Post Category?
I'm trying to decide on how to organize a new site/theme.
It has the standard sections: Home, About, Contact, Blog but also an (admin-only editable) Knowledgebase/Documentation area.
My first thought was to create a custom post type to separate out the documentation area but it could more easily be done as parent/child pages or even separated out by tag/category in the blog.
Just wondering if anyone has built something like this in the past. | There's the following: ` To me it looks like only a clever combination of archive display.
You'll have to copy/paste the link to your browser as I don't link to commercial themes from inside answers. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, documentation"
} |
Configuring WordPress permissions for easy updates
I've been tasked with configuring a LAMP stack on a dedicated server to run multiple WordPress sites. Each site is attached to it's own SSH account.
I'm having trouble setting permissions that'll allow each user to easily perform updates, plugin installs and updates, and the like from within WordPress.
Normally I'd configure www-data to own the files, but that's not an option, and setting the www-data group as group owner of the files doesn't seem to work either. Nor does it seem to work when I install the SSH2 extension for PHP, and frankly I'd prefer to go around that. I can get it to work for plugin installs and updates if I install this plugin, but there's got to be a way around that.
Does anyone have any experience with this? I haven't really been able to find any helpful articles via Google or WordPress' own forums. | Yes have a look at SuPHP < this should be on serverfault, not really a WordPress question. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permissions, ssh"
} |
How to show Home Page link in Wordpress Menu and how to add an icon to this?
I tried with this code:
function home_page_menu_args( $args ) {
$args['show_home'] = true;
return $args;
}
add_filter( 'wp_page_menu_args', 'home_page_menu_args' );
but gives me this error: `Error 404 - Not Found`
I would like that when I click on "Home Page" menu appears the recent posts.
And I would like to place an **icon** instead of "Home Page" writing.
Thank you! | To add a home link to menus that you create via the menus admin area:
1. go to the **Pages** box,
2. click the 'View All' tab
3. 'Home' will appear, check the box and click 'add to menu'
!enter image description here | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "menus, homepage, icon"
} |
Set featured image size for a custom post type
I have a custom post type, and I'm adding support for thumbnails (featured image)
register_post_type('cp_companies', array(
'labels' => array(
'name' => __('Companies'),
'singular_name' => __('Company')
),
'public' => true,
'has_archive' => true,
'supports' => array('thumbnail', 'title', 'editor')
)
);
This is not a theme. This is a plug-in. What I want to do is simply limit (120x120) the size of the featured image. | From what I understand, you just want to have a thumb created at 120 x 120 when an image is uploaded using the new post type. Then use that image as the featured image on the custom post pages.
Just add a new image size
add_image_size( 'companies_thumb', 120, 120, true);
Then in the post type template for companies you just call the thumb you defined.
<?php the_post_thumbnail('companies_thumb'); ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "post thumbnails"
} |
Can we able to post blog on another Wordpress blogsite?
I am relatively new to Wordpress.
When we check techcrunch.com which is built on Wordpress platform, they have few official bloggers and tons of comment posters which is usually authenticated through facebook.
How do a Wordpress Blogging site manage other Bloggers to Blog / Post blog on their Blogging site ?
Whether Wordpress allows an Admin User and non-admin users to blog on a Website ? | Read up on Roles and Capabilities | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "multisite"
} |
Is it possible to Hook/Filters Attachment Creation?
Is it possible to hook or filter the attachment creation process? More specifically is it possible to hook into the attachment creation so that I may parse the attachment’s filename, populate the attachment’s Meta data (title) with a filtered version of its filename?
If not, are hooks and filters planned for the media library with future updates to core? | You can hook into the 'add_attachment' action from wp-includes/post.php Line:3738.
It passes in the post_id and from there you can get the file name and then update the post meta with anything you need to. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "filters, attachments, hooks"
} |
show only sub categories if available?
Hii i want that when i click on category link that show sub category if available instead of posts list If No Sub category available then show normal posts how to do this that if available sub categories only show just sub categories not any other posts Mean which extra code i add in my archive page that show sub categories if available otherwise show posts Thanks | use a conditional statement, for example:
$sub_cats = get_categories('parent='.get_query_var('cat'));
if( $sub_cats ) :
//show list of child categories, for instance with wp_list_categories()
echo '<ul>;
wp_list_categories('title_li=&child_of='.get_query_var('cat'));
echo '</ul>';
//or possibly using $sub_cats and a foreach loop//
echo '<ul>';
foreach( $sub_cats as $sub_cat ) {
echo '<li><a href="'.get_category_link($sub_cat->term_id).'">'.$sub_cat->name.'</a></li>';
}
echo '</ul>';
else:
//the 'normal' LOOP of category.php//
endif;
<
edit: list code for sub categories added | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, archives, customization"
} |
Remove "You are using Wordpress 3.2.1" from Right Now Dashboard Widget
I'm looking for a to hide the text on the dashboard that says "You are using WordPress 3.2.1" in the Right Now widget. Not that we don't love WordPress, but for our use-case (where we'll be providing this WP install to dozens, if not hundreds of people), I'd like to get as much stuff out of there that's not needed (and that could eventually confuse them). I saw that the Right Now Dashboard is in /wp-admin/includes/dashboard.php -- but can't figure out how to change/remove that text. Thanks! | There is a trick to get rid of this using the `gettext` filter for translations.
This basically replaces it with nothing.
add_filter('gettext', 'remove_admin_stuff', 20, 3);
function remove_admin_stuff( $translated_text, $untranslated_text, $domain ) {
$custom_field_text = 'You are using <span class="b">WordPress %s</span>.';
if ( is_admin() && $untranslated_text === $custom_field_text ) {
return '';
}
return $translated_text;
}
Be aware that the version also shows in the footer and several other places, if you want a good breakdown check out the source of this plugin, it seems to have covered more or less all of it, < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "theme development, functions, dashboard"
} |
delete uploaded file
I have a function wp_handle_upload() for uploads files.
$file = $_FILES['attachment_icon-' . $i];
$upload = wp_handle_upload($file, array('test_form' => false));
what is a function for delete a uploaded file? | Use `wp_delete_attachment( $post_id )` if you have used `wp_insert_attachment()` before.
`$post_id` is the attachment ID.
If you haven’t used `wp_insert_attachment()` a simple …
unlink( $upload['file'] );
… will do it. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "functions, uploads, filesystem"
} |
How to execute a shortcode?
I have a WordPress option that stores some data, like:
<h1>Header</h1>
<p>Paragraph</p>
[shortcodesomething/]
[shortcode]Contents[/shortcode]
I'm displaying this option's value using `echo get_option('my_option'));`.
Of course the shortcodes doesn't work, and I'm wondering how to force them to do what they are supposed to do?
`echo do_shortcode(get_option('my_option'));` doesn't work either (I know this is an absolutely wrong approach, but I don't know any other way of displaying them). | Well, as Christopher Davis mentioned - do_shortcode works fine with extra stuff included, so I decided to reset my server and `echo do_shortcode(get_option('my_option'));` started to work perfectly.
So I guess the answer has always been here, execute shortcodes with `do_shortcode`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "shortcode"
} |
Viewing category pages without the word 'category' in URL
1. When I view a static page its url is like: `
2. When I view a category page its url is like: `
For SEO, I want some modification so that I do not have to use the word `category` to view category pages. e.g. it should be ` instead of `
* How can this be done?
* I see a potential problem that WordPress engine may not be able to differentiate between pages and categories. Is it so?
* What are other pros and cons? | Basically a duplicate of this question. It comes up a lot, and the remove category base functionality probably should be an option in WordPress to be honest.
Here was my answer from there:
> No Category Base plugin to remove the /category/ bit from the URL.
:)
* * *
If you have a page with the same name as a category, the page will be shown instead the category archive, but the URLs of posts won't be affected. At least, that used to be the case. I _think_ I heard news of a recent change in the way WP calculates permalinks (for the better). | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "categories, pages, urls, rewrite rules, seo"
} |
how to get the categories for a single post in a hierarchical way
The question is simple.
Imagine that I have a post named 'Single Post' which is inside the category 'sub-cat' which is a child of 'parent-cat' which is a child of 'super-cat'. What I need to do is to display all the related categories within the post page in the following order:
super-cat > parent-cat > sub-cat > Single Post | <?php
the_category( ' > ', 'multiple', $post->ID);
echo ' > ';
the_title();
?>
This works correctly when the post is in just one category. But if it's in multiple categories, or if the category parents are also selected — in your case, if the post is also in super-cat and parent-cat — then it displays those categories twice.
So this is probably not going to do it for you.
I suspect some of the breadcrumb type plugins might have solved this though. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "categories, hierarchical"
} |
Redirect page for a custom post type
I have the following custom post type
register_post_type('cp_clients', array(
'labels' => array(
'name' => __('Clients'),
'singular_name' => __('Client')
),
'public' => true,
'has_archive' => true,
'supports' => array('thumbnail', 'title', 'editor')
)
);
I want to output custom content when the user calls < It's a plug-in and not a theme.
Any ideas how I can redirect to a custom page/output for this URL? | I don't think you need a redirect. You are missing the rewrite rule for your custom post type.
register_post_type('cp_clients', array(
'labels' => array(
'name' => __('Clients'),
'singular_name' => __('Client')
),
'public' => true,
'has_archive' => true,
'supports' => array('thumbnail', 'title', 'editor')
'rewrite' => array('slug'=>'companies')
);
You should now be able to create and use single-cp_clients.php, and archive-cp_clients.php template files. And your urls will look like example.com/comapnies and example.com/comapnies/acmecorp | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom post types"
} |
How can I increase the post count for custom post types only?
I have the page count set to the default 10 in my reading settings menu.
screenshot-with-shadow.jpg
However, I use my template `archive.php` file for all post types, including `posts` and `books`
How can I change the loop so that when searching `books` it will show 30 books in the archive page instead of showing the default 10? | I think something like this should work:
add_action('parse_query', 'wpse32932_parse_query');
function wpse32932_parse_query( $wp ){
if( $wp->is_post_type_archive ):
$wp->query_vars['posts_per_page'] = 30;
endif;
return $wp;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, php, loop, archives, options"
} |
how to remove description from menu buttons?
I just installed Wordpress into my server and I am currently using the "graphene" theme to test my wordpress blog. I have two pages in addition to the front page, which is "about us" and "sample page". I noticed that if I'm using a custom menu order that is created from the "menu" section under the "Appearance" options in the dashboard, the text "this is the 'about us' page." appears under the "about us" button in the navigation menu. Removing all page text from the "about us" page didn't remove the description from the menu button.
Without custom menu, the navigation button looks like this :
|About Us|
With custom menu, the navigation button has description :
|About Us
|this is the "about us" page.| | I just inatalled it and used the Custom menus and i get no description
**Never the less.. This theme have a "disable description in Header Menu" feature.**
On Your wordpress menu go to:
Graphene Options >> Display >> Navigation Menu Display Options..
Click the "disable description in Header Menu"
And your done.. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "menus, navigation, dashboard, description"
} |
Pause plugin option page until all data manipulation is complete
I have an option on my plugin page where I load content into all the posts in the blog. Now this takes some time, esp when there are a log of posts.
Now the way is it set up now, when you press submit, the form success page is already presented, but you can see that the browser is still working.
How can I have the plugin wait until the whole loop is finished, and then present the error or success page. | You can only do this by "loading content into all the posts in the blog" asynchronously (in the background).
So, move the processing inside a function that you hook on **wp_ajax_** _your_action_tag_.
Then call this function with javascript by requesting WP to fire "your_action_tag". There's a example on the linked page...
If you want to display completion status, like a percentage bar, you might want to send an additional query variable besides the "action", like the offset from where the processing should continue. This offset would be increased in your processing function and sent back to the javascript, which calculates the status. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, admin menu, settings api"
} |
Get a list of commas separated categories inside a loop
I want to get the list of categories of a post inside the loop. Normally, I would use
the_category(', ');
But this does output a link, and I only want the category name. Any ideas? | Should be easy enough i think..
<?php
foreach((get_the_category()) as $category) {
//this would print cat names.. You can arrange in list or whatever you want..
echo '<span>'.$category->cat_name .'</span>';
}
?>
.
Hope This Helps ;) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "categories, loop"
} |
How to delete all the options in an option group
I have created a few options with with the `register_setting` function:
<?php register_setting( $option_group, $option_name, $sanitize_callback ); ?>
Is there a way to clear the whole content of the `$option_group`, and even the group itself. | Usually, the Codex is a good resource for doing research on things like this ... and there are functions related to `register_setting()` listed directly on it's page in the Codex.
The function you're looking for is `unregister_setting()`. From it's Codex page:
> ## Description
>
> Allows clean de-registration of registered settings. Should be used mostly in deactivation hooks.
>
> ## Usage
>
> `unregister_setting( $option_group, $option_name, $sanitize_callback );` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugin development, settings api"
} |
Admin top level menu, pointing to an external url
I want to create a entirely new top level menu in the admin menu section, and have that be an external link, is this even possible with the current system?
The solution that t31os provides in this thread works if you put the link as a submenu under, for example, the dashboard. But this is not what I want to do.
Adding an Arbitrary Link to the Admin Menu? | Just add your custom item into `$menu` instead of `$submenu`.
Use here as a reference for parent menu structure.
<
Eg.
add_action( 'admin_menu' , 'admin_menu_wpse32975' );
function admin_menu_wpse32975() {
global $menu;
$menu[9999] = array( __('My Menu'), 'manage_options', ' '', 'open-if-no-js menu-top', '', 'div' );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp admin, admin, menus, admin menu, dashboard"
} |
WPML - Change the language of large number of posts
I need to change the language of some 500 posts in a site that uses WPML. Currently all of them are set to English, but are in fact in Spanish.
What is the fastest way to do so? It is possible to get the IDs of all of the posts. | I've done it with this bit of code:
global $wpdb;
$posts = get_posts(array('post_type'=>'...', 'posts_per_page'=>-1));
foreach($posts as $post) {
$wpdb->update('wp_icl_translations', array('language_code'=>'es'), array('element_id'=> $post->ID));
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "plugin wpml"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.