INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Forcing frontend login with UI switch
Is there a way to force log-in even for _viewing_ a WordPress blog that the blog's owner can turn on and off by themselves?
I can hardcode it in the template's `header.php` like so:
if ( !is_user_logged_in() ) {
wp_redirect( wp_login_url() );
exit;
}
but this can't be influenced from the blog's administration page.
There is the force user login plugin, but it doesn't work in 3.x blogs. I'll try to patch the plugin for 3.x, but suggestions for other (native?) methods are welcome. | This simple to implement, you could put this into functions.php if you want it tied to a theme, or else create your own plugin from this:
add_action('init','my_force_login');
function my_force_login(){
if ( !is_user_logged_in() && !in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ) ) {
$force_login=get_option('my_force_login');
if($force_login){
wp_redirect( wp_login_url() );
exit;
}
}
}
For this to work you will then need to create an option (either a theme option if this is to be tied to a theme, or otherwise an extra option in an appropriate WordPress page.
In the above, I am assuming there is an option with name 'my_force_login' with value true/false (or 1/0) which determines if the redirect should take effect.
The redirect applies to all logged-out users to all pages except the login/register page. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "login, wp login form"
} |
Change page template programmatically ?
I have two page templates and Qtranslate installed.
I want to choose one or another depending the language selected.
Can I do something like this ?
if($q_config['lang'] == 'en'){
// load page-template_en.php
}else{
// load page-template_de.php
}
Any idea ?
Thanks! | It is possible using the `template_redirect` hook.
Looks something like this :
function language_redirect()
{
global $q_config;
if( $q_config['lang'] == 'en' )
{
include( get_template_directory() . '/page-template_en.php' );
exit;
}
else
{
include( get_template_directory() . '/page-template_de.php' );
exit;
}
}
add_action( 'template_redirect', 'language_redirect' );
Code is untested, but should look like that.
See my similar answer HERE for more help. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 12,
"tags": "pages, templates, language"
} |
Is get_permalink also the canonical URL?
The question says it all. Does permalink equal canonical URL? Or is there another way to get the canonical URL? | Unless you are doing something weird with your URL structure (and maybe even then), the answer is **yes** according to this blog post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "urls, permalinks"
} |
Image URLs stopped working due to Permalinks?
I've been changing my Permalinks and changing my site the the "www" version (Which I think has broken my image and video links). All my images are "red x" now, both inside the library and the posts themselves. I have been looking in my cpanel and all the file paths are correct, but if I try to view them through WP or even just copy the url and try it within my browser, it appears broken.
Is there a way to fix this at all? Other than reload everything back up. :-(
To update: I just re-uploaded an image and it was saved as header1.png, so WP can see that there is another image in there. It's strange because all the paths seem to match in my library to where they are stored within cpanel.
I feel that because I cahnged the permalink structure to %category%/%postname% that that is affecting the image structure which is wp-content/uploads/%year%/%month%/%imagename% by the looks of it. | if you've monkeyed with your www structure you can change the image URLs (since they are hard-coded in the img src) using the following plugin:
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "images, filesystem"
} |
My Calendar Plugin - add output directly in template file
I am using the latest version of the My Calendar plugin by Joe Dolson with the latest version of WP. I want to output an events list in a particular place in my code, but I can't seem to find any way to do this. The only thing I've found regarding output is by using shortcodes in the post/page.
I guess theoretically I could add a new sidebar widget and then add the templates that way. Then put the sidebar where I want in the code, but this poses two problems: 1\. It's a hassle 2\. I don't want my clients to be able to move or change this. I'd like to have it set and stay that way.
I'm having some trouble finding the answers to this question. It seems like it would be possible, because most plugins I've used have an option to add output directly in the template code, but I can't seem to find the answer.
Thanks in advance! | You can use the function do_shortcode in your template to output the content generated by the shortcode that My Calendar provides for listing events.
For an example, to show a list of upcoming events use something like:
<?php echo do_shortcode('[my_calendar_upcoming before="3" after="3" type="event" fallback="No events coming up!" category="General" template="{title} {date}" order="asc" skip="0"]'); ?>
Take note of the use of single quotes for the function and double quotes for the shortcode attributes. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, calendar"
} |
How to add new custom page or post blocks?
I would like to add custom contents to post, such as price, options and some others, I dont like to use the custom fields, because always i have to select from a drop down menu, I want these options to be in a separate area such as title, editor, thumbnail... I think its possible, I have seen this in WP Ecommerce plugin.
Can anyone tell how t do it? | You're looking for custom meta boxes. These allow you to add sections to the WordPress post and/or page screens that look like standard title, editor, category selection, etc. Generally speaking, you determine where they are rendered and what type of input elements are used.
Without knowing exactly what you're trying to do, it's not possible to provide a tutorial but there are a number of resources that will get you started:
* The WordPress Codex has a decent article that explains the API function.
* I've written a two-part article (Part 1, Part 2) that walks you through adding a custom meta box and referencing it in your post and/or pages.
* Here's another solid tutorial (Part 1, Part 2, Part 3) that does an excellent job of providing an introduction and working example of how to create your own custom meta boxes.
Reviewing this articles should provide you with a solid foundation to get started on writing your own functionality. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "custom field"
} |
How to show content without excerpt?
Post contains: `excerpt`, `read more`, `content`. When browsing category page we see post's `excerpt` with `read more` link. When clicking `read more` we see post's `excerpt` \+ `content`.
How to avoid showing excerpt (everything before read more link) on post's page? | As explained in Codex Function Reference, you can set the argument $stripteaser to true in order to not show the excerpt:
the_content( null, true ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts"
} |
How to rewrite custom post type with custom taxonomy urls?
I am working in a WP multisite which runs on a classipress theme and there is a custom post type "`ad_listing`" and custom taxonomy type "`ad_cat`". Now the url is like this
> <
I need to rewrite this URL so it looks like
> <
and categories are nested so it can be nth level.
Please help me how to do that with wp rewrite rules.
Thanks in advance.Any help will be greatly appreciated. | When you are adding a custom taxonomy you are able to declare a rewrite slug -
$labels = array(
'name' => _x('Name', 'taxonomy general name'),
'singular_name' => _x('Singular Name', 'taxonomy singular name'),
'search_items' => __('Search Items'),
'all_items' => __('All Names'),
'parent_item' => __('Parent Item'),
'parent_item_colon' => __( 'Parent Ites:'),
'edit_item' => __('Edit Item'),
'update_item' => __('Update Item'),
'add_new_item' => __('Add New Item'),
'new_item_name' => __('New Item Name'),
);
register_taxonomy(
'ad_category',
array('post-type1', 'post-type2'),
array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'query_var' => true,
'rewrite' => array('slug' =>'new-york-city')
)
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "custom post types, custom taxonomy, rewrite rules"
} |
Trying to put an array into 'post__in' => array() query not working
Slight problem, I have the following code:
$purchaseprodid = $_GET['ids'];
$args = array(
'post_type' => 'prizes',
'post__in' => array($purchaseprodid)
);
query_posts($args);
while (have_posts()) : the_post();
I am getting comma seperated numbers for id's in a url, and they dont seem to be querying the posts. If I manually type the id's in they work no problem, but just not when using a variable $purchaseprodid.
Any ideas?
Thanks! | You need to explode the string you obtain from `$_GET['ids']` into an array, at the moment you a parsing a to string `post__in` rather than an array of IDs.
Try
$purchaseprodid = isset($_GET['ids']) ? explode(',',$_GET['ids']) : array();
However, you can sometimes run into difficulties using `$_GET` with WordPress, it's better to use the API provided and register your variable, see this question. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, query"
} |
How to show custom field's value under post/page title in wp-admin
I'm trying to add the value of a custom field under the post/page title in wp-admin list of posts/pages (much like excerpt mode in posts list) without hooking into the columns process since other plugins are already doing that and it looks like each cancels the other.
Here's a screenshot of what I'm trying to achieve:
!screenshot of pages list
Thanks! | Just like you add new columns you render the title filed your self
add_action( 'manage_posts_custom_column', 'admin_post_data_row', 10, 2);
function admin_post_data_row($column_name, $post_id)
{
switch($column_name){
case 'title':
edit_post_link(get_post_title($post_id), '<p>', '</p>',$post_id);
echo '<br />'.get_post_meta($post_id,'field_name',true);
break;
default:
break;
}
}
and if you have another plugin cancels this then simply set the filter hook priority to something bigger. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom field, customization, admin"
} |
separate categories with comma and srounded by single quote
hello and sorry for yet another beginner question i am extracting wordpress categories form the array but i want them to be separated by comma my code is
<?php
$args=array(
'child_of' => 79
);
$categories=get_categories($args);
foreach($categories as $category) {
echo $category->cat_id;
?>
this will return some thing like 11223344556677
but i want the result like '11,22,33,44,55,66,77'
thank you for your help | Welcome to WPSE faq! This type of question is probably best suited for suited for stackoverflow, rather than here as the question isn't specifically related to WordPress. You just need to get an array of the IDs (a simple foreach loop could do this - or use the Wordpress' `wp_list_pluck`) and then explode that array:
//$categories is the array of category objects
$cat_ids = wp_list_pluck($categories,'term_id');
echo "'".implode(',',$cat_ids)."'";
### Edit
And to incorporate this method into the OP's code example:
<?php
$args=array(
'child_of' => 79
);
$categories=get_categories($args);
foreach($categories as $category) {
$cat_ids[] = $category->term_id;
}
echo "'".implode(',',$cat_ids)."'";
?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "filters"
} |
Saving data for different custom posts
I have three different posts types registered:
register_post_type( 'foo' , $args );
register_post_type( 'bar' , $args );
register_post_type( 'baz' , $args );
When I am creating a new, say, "foo" post, I only want to save the meta box for "foo", what do I do?
add_action('save_post', 'save_details');
So, if my post_type were called "foo_post":
add_meta_box(
$id,
$title,
$callback,
// SPECIFY THE POST TYPE HERE!!!
"foo_post",
$context,
$priority,
$callback_args );
What do I do to save only "foo post" meta box when I am creating / edit a "foo post" page? | Since save_post gives you the post_id of the current post, you simply want to check what post_type it is by using get_post_type($post_id)
like:
add_action('save_post', 'save_details')
function save_details($post_id)
{
$post_type = $_REQUEST['post_type'];
if ('foo_post' == $post_type)
{
// save stuff for foo_post
}
elseif ('bar_post' == $post_type)
{
// save stuff for bar_post
}
}
and so on...
get_post_type() codex page | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types"
} |
Use a shortcode to display custom meta box contents
Is this possible? If so, can someone point me towards a clear tutorial? I have a column of content I want to float right of the_content, so I'd like to be able to use a shortcode to put that content in the post for a page.
I've found the following (but want to modify it for get_post_meta):
function get_custom_field_fn() {
global $post;
$custom_field_value = get_post_meta($post->ID, 'cf_name', true);
return $custom_field_value;
}
add_shortcode('cf_name', 'get_custom_field_fn');
I'm guessing that I need to change a few things but not sure which things to change. My custom meta boxes will have 8 fields. I'm also guessing that my shortcode will need to allow for the post/page ID and I also need to interject some HTML in the function. | yeah, the question is a bit unclear. but i think you need shortcode attributes
function get_custom_field_fn( $atts) {
global $post;
extract( shortcode_atts( array(
'meta' => ''
), $atts ) );
$custom_field_value = get_post_meta($post->ID, $meta, true);
return $custom_field_value;
}
add_shortcode('cf_name', 'get_custom_field_fn');
see the codex: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, customization, metabox, shortcode"
} |
Copy custom post types and admin
I'm copying over a site from a former developer. I've installed a new instance of wordpress and database on new server, copied all but the wp-config from old server to new, but in admin it does not show the custom post types that are showing in old admin. I would think that these settings are in the functions.php, but I'm copying that over. Shouldn't they show? How can I make this work?
Thanks so much! | the custom post types won't show until you call register_post_type.
<
this was either done in a plugin or the theme that you were previously using. if you are no longer using those you will have to activate it again yourself. i suggest making it a plugin (and possibly even an mu-plugin) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
Get the user type of an author
I'm working on a site and I need to get the type of user the author is so I can mark it.
The idea is that if an Admin level user post something it has a [ADMIN] tag or something next to their name. I know how to compare things within php but how do I check to see what user type an author is if possible? I can't seem to find any good documentation on the matter. | One way would be to use the `get_the_author_meta` function and pass it `user_level`
More info on the function: <
Then, see this chart to convert user levels to roles (unless you have created custom roles): <
Example code
$level = get_the_author_meta('user_level');
if($level >= 8) { // Is admin
// do something
} else if ($level > 2 && $level < 8) { // is editor
// do something else
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 3,
"tags": "posts, author, validation"
} |
get_posts seems to be skipping the last Post
I have custom post type (Events) with 6 events.
$posts = get_posts( array('post_type' => 'events') );
echo '<!-- ';
print_r($posts);
echo ' -->';
This code shows the 5 with the most recent published date.
I should perhaps note that we have been changing the published date as a hacky sort of way to change the post display order. I'm not sure when the event started being omitted, or if this is related, but there it is.
Does anyone have any insight as to why this kind of thing would happen? Thanks. | The default nmber of posts returned is `5`.
To return more than 5 posts use:
$posts = get_posts( array('post_type' => 'events', 'numberposts' => 10) );
Or for all of them:
$posts = get_posts( array('post_type' => 'events', 'numberposts' => -1) );
More info about get_posts < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, get posts"
} |
How to create a page that lists custom taxonomies with links?
I want to create a page that lists all the Custom Taxonomies, with each item linking to a page that will list all the terms in a given taxonomy.
I can produce a list of taxonomies using this
<?php
$args=array(
'public' => true,
'_builtin' => false
);
$output = 'names'; // or objects
$operator = 'and'; // 'and' or 'or'
$taxonomies=get_taxonomies($args,$output,$operator);
if ($taxonomies) {
foreach ($taxonomies as $taxonomy ) {
echo '<p>'. $taxonomy. '</p>' ;
}
}
?>
But of course no links.
Looking at the codex there is very little information on the parameters - at least for neophyte like myself.
Any suggestions on how to output a link for each custom taxonomy?
Thanks | Once you get `$taxonomy` you can perform further logic:
$tax = get_taxonomy( $taxonomy );
if( isset( $tax->has_archive ) && $tax->has_archive == true ) {
// do output. archive will be wordpress_url + $taxonomy->name
?>
<p>
<a href="<?php echo site_url( $taxonomy->name ); ?>">
<?php echo $tax->labels->name; ?>
</a>
</p>
<?php
}
This is untested, but you get the idea. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, list"
} |
How do I display something on a particular category page?
How would I display HTML conditional on a particular category page?
Say my permalinks to the category pages are
<
How would I cast the `<?php if ... ?>` to do this, and within what template of my theme?
I'm using WP 3.3.1. If I need to provide more information I'll be happy to. Thanks! | if(is_category('awesome-category')) echo "whoa awesome category here!!;
probably in category.php, but it really depends on the setup of your theme... if you are using a child theme, etc. also you could create a special template just for that specific category.
category-awesome-category.php
see: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "categories, pages, conditional content"
} |
Register User can post video
I have a blog. I need to add a functionality. Where Registered user can upload video and Registered user can view all video and Onclick on Particular video That video display and User can comment on video and total view. Is there any plugin that provide this functionality. or Any demo link or code. | I would either create a custom post type, or a category (depends how you wanna organize it...custom post type would be my goto) to store the videos. With that in place, you can setup a form in your frontend, making it only visible to registered users, where they can do their video uploading (this functionality is covered elsewhere, so I won't talk about how to do that, if you need docs, `wp_insert_post()` is a good place to start).
You'll also need a way of viewing the videos. The archive of a category or custom post type would work well, as would a custom page template...that's sorta your call as to what you want to do...doing the display and what not should be cake for you from within the template. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin recommendation"
} |
Plugin recommendation for member management
I couldn't find any plugin to do that, so I need a help here. This is what I need. One page will have a small form with 6 fields. One field is to upload photo. Another page will show in a matrix layout (2 columns 5 rows) all the users that were registered from my form. On the backend, I just need to be able to see the registered people and manage them (accept, delete, and so on).
Do you know any plugin or tutorial that show me how to achieve that? | Try out < . It has front-end user registration with avatars uploads and user listing.
The one thing that it doesn't have is approve user before activating them on the site, but you can delete and edit users from the backend in the users section. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin recommendation, users, user registration"
} |
Wordpress Related Plugin - only show when related content
I'm using the Wordpress related plugin : <
Which uses the following markup to call the plugin:
<?php echo $related->show(get_the_ID()); ?>
I would like to add a title and a division around the plugin... but would only like this to display if there is a related post/page. How should I modify the code?
This is the result I would like to see, but only when there is related content:
<div class="related"><strong>Related products</strong><br />
<?php echo $related->show(get_the_ID()); ?>
</div> | I don't know for sure if this would work but this is where I'd start:
<?php $related_content = $related->show(get_the_ID()); ?>
<?php if($related_content): ?>
<div class="related"><strong>Related products</strong><br />
<?php echo $related_content; ?>
</div>
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, php"
} |
Get ID of "root-page"
I have an url that looks like this < I want to get the ID of the page "tjanster", how can i do that? | I think what you need is:
<?php
$post_id = $post->ID; //or somehow get the current post ID.
$ancestors = get_post_ancestors($post_id)
//$ancestors is an array of post IDs starting with the current post going up the root
//'Pop' the root ancestor out or returns the current ID if the post has no ancestors.
$root_id = (!empty($ancestors) ? array_pop($ancestors): $post_id);
For more info check: < | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "id"
} |
Gravity Forms Post method
I have a simple form that users will fill out which will in turn become a post on my site. I have 2 problems:
1. I am using the Post title, Post Custom Field elements (for single line text) and Post Body element (for paragraph text). When I submit my test form though, only the title is appearing, none of the data I wrote in the custom field elements.
2. Is there a setting I can use to have the title of fields show up in my post? (i.e, Name field would actually show "Name: Whatever the user typed in" on the post?) When I was able to get one of the body fields to appear on the post, it only had the information I typed in, not the title.
Maybe I am not using the post fields correctly, so any direction/opinions would help!
Thanks | I put together a video for you showing you how to use the content template in Gravity Forms, which is the key to formatting content within the post body.
Take a look here: <
If you find yourself needing to do more advanced work, then you'll probably want to investigate setting up a custom template and pulling in the data from the custom fields directly into the template.
As for question #1, it sounds like the field might not be properly configured. Can you post a screenshot or video of the settings? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, plugin gravity forms"
} |
Can I remove the Rich Text box editor for a specific post?
A few months ago I asked a similar question: Is it possible to remove the main rich Text box editor? and got the following answer:
function remove_pages_editor(){
remove_post_type_support( 'page', 'editor' );
}
add_action( 'init', 'remove_pages_editor' );
This code removes the editor from **all pages**. Can I remove if from specific pages (by post-ID) somehow? Thanks! | There is an `add_meta_boxes` function that fires that you can hook into - it fires whenever the edit post page is rendered.
At that point, you can get the ID of the post being edited using `get_the_ID()`. You can then compare it to the ID for which you want to remove the post editor:
function remove_pages_editor(){
if(get_the_ID() == 23) {
remove_post_type_support( 'post', 'editor' );
} // end if
} // end remove_pages_editor
add_action( 'add_meta_boxes', 'remove_pages_editor' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "functions, admin, tinymce, visual editor"
} |
Separator for custom nav menu
I creating a custom footer navigation in wordpress. I looked all over the wordpress documentation and still haven't found anything. So, what I'm trying to do is add an "|" in the navigation like this:
> Home | Link 1 | Link 2 | Link 3 | Contact
I know there's a way in CSS, but I know this is generated by wordpress so I'm a little stumped on how to do this. | I figured out a way to do this and without using the wp_nav_menu.
Here's the code to do this and hope it might help other (Note: You need to create a menu in the admin panel to have this work).
<p>
<?php
$items = wp_get_nav_menu_items("footer");
$count = count($items);
$i = 0;
foreach($items as $item):
$i += 1;
?>
<a href="<?php echo $item->url; ?>"><?php echo $item->title; ?></a><?php if($i < $count){ echo "<span class='center'>|</span>";} ?>
<?php endforeach; ?>
</p> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "menus, navigation, links, footer"
} |
Limit taxonomy results to a single cpt
I have two cpt's, events and reports, they both share the taxonomy locations, I have my taxonomy-locations.php, but that is showing reports & events for location, I just want to show reports for location. Can someone help me out with how this query should go?
Thanks | Before the loop in your `taxonomy-locations.php` file,
global $wp_query;
$args = array_merge( $wp_query->query, array( 'post_type' => 'report' ) );
query_posts( $args );
You could, alternatively, modify the query using an appropriate hook (this would be the most effecient method) - but since it is run for most queries, you would need to check it's actually a query for which you want to set post type to 'report'. For example:
function my_restrict_to_report() {
//And any other checks
if (!is_admin() && is_tax('location')) {
set_query_var('post_type','report');
}
}
add_action( 'pre_get_posts', 'my_restrict_to_report' );
_Not tested_ | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy"
} |
Why do I have "category" in my permalinks?
I added two category pages to a site I am working on and I found out the permalink in the url is wrong.
I set the permalink as `/%category%/%postname%` and I created two categories "News" and "Offers"
I was supposed to get `mydomain.com/news` or `mydomain.com/offers` (I created the category links using the built-in menu system) but I get this instead: `mydomain.com/category/news` and `mydomain.com/category/offers`
Why do I have "category" in the url? How can I remove it?
Thanks | By setting your permalinks to `%category%/%postname%`, you are setting the permalinks _only for your posts and pages_.
Below the posts and pages permalinks option is another one for your categories. Just set your categories slug to `.` and it will just be the category name. Here's a visual example:
!enter image description here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks"
} |
Automating deprecated call checks?
I've recently started revamping and re-releasing some abandoned (yet important) WordPress plugins. As I walk through the code patching other bugs, my IDE highlights deprecated function calls for me, which is fantastic!
I fix them immediately when I find them and move on.
Anything I _don't_ catch is called out by a Log Deprecated Calls plugin or by setting `WP_DEBUG` to true.
But both of these approaches are highly ineffective. With one, I need to actually open the PHP file and manually scan through each line of code looking for a deprecated call. With the other, I need to wait for the deprecated call to be invoked by WP before it's flagged by the system.
Is there an easier way or some tool I can use that scans through WP plugins and themes and identifies any use of deprecated functionality? | I was inspired by your question to create a plugin that I've been kicking the can on for several months. I'm calling it Deprecation Checker. By default, it scans the plugin and theme directories (recursively) to find deprecated functions. The functions list is sourced directly from the WP deprecated files.
It then outputs a nice list including line number, file path, old function, and recommended function to use in its place.
There are a couple of filters to add custom paths and custom deprecated functions for your own uses. You can also turn off plugin/theme directory scanning easily.
You can download it here: < (will be on WP.org soon)
Once activated, browse to the Tools administration menu. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 4,
"tags": "plugins, automation, deprecation"
} |
Adding an additional menu in Wordpress
I am using wp_nav_menu() and I want to add the search box as a part of the menu.
I am having trouble figuring it out and was hoping for some assistance:
My code:
<?php
$args = array('theme_location' => 'primary', 'container' => false);
wp_nav_menu( $args );
?>
Now I want to add an additional <li> element to the end or the menu <ul> and all I want in the <li> is the output of:
<?php get_search_form();?>
Can this be done? | Ended up using wp_get_nav_menu_items() and got each item individually and then built the li manually as shown in this example: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
Does switch_to_blog support array or other ways to show all posts on a network install?
I have a WordPress network install and I'm looking for a way to display all posts on the front page. I'm using switch_to_blog and it works but it only works for showing one blog. Does switch_to_blog support multiple blogs? If not, what's the best way to show posts from multiple blogs without a plugin? I tried the sitewide plugin and I kept getting errors.
Thanks, Gregory S. | `switch_to_blog` does not support switching to multiple blogs at the same time, instead if you want to list all posts in a network, you'll need to loop through each blog, using `switch_to_blog` and `restore_current_blog`, saving each post in each site into a PHP array, then finally displaying every post in that array once it contains all the posts.
Note that this will require you to understand PHP variables, arrays, and `WP_Query`, the first two of which you can find in any basic PHP tutorial, and the last you can find a good set of slides by Nacin You don't know Query | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite"
} |
Different layout on second page
My homepage has 1 featured post, followed by 4 posts stacked 2 on 2, like this:
!enter image description here
The featured post is only shown on the first page so the second page shows the older posts stacked 2 by 2 as above.
However, I'd like to be able to change the layout on the second page, showing the posts in full width and length. Any way to do this?
tl;dr = How can I make the second page look different from the first page? | To load override WordPress' choice of template you can use `template_include` **filter** and then use the `locate_template` to return the the template file path (if it finds it).
The file-name passed to `locate_template` must be the name of the template file name (which should be in you theme/child-theme directory).
//Loads template customtemplate.php from your theme folder on page 2+ of the 'main page'
function my_second_main_template($template){
if (is_home() && is_paged()){
$alternate_template = locate_template( 'customtemplate.php');
if(!empty($alternate_template))
$template =$alternate_template;
}
return $template;
}
add_filter('template_include','my_second_main_template'); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "pagination, archives, hierarchical"
} |
Dashboard Contact Form
Is there a way to make a dashboard contact form widget?
I just simply want to have it there so users can give feedback directly from their dashboard. | Yes. You can do this by adding a dashboard widget with a contact form function that uses AJAX to submit the form.
function myplugin_dashboard_widget() {
ajax_contact_form();
}
function myplugin_add_dashboard_widgets() {
wp_add_dashboard_widget('myplugin_contact_widget', 'My Plugin Contact Form', 'myplugin_dashboard_widget');
}
add_action('wp_dashboard_setup', 'myplugin_add_dashboard_widgets' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "forms, dashboard, contact"
} |
persist a variable set in header.php all the way down to footer.php
I look up a custom post field value in header.php, and store it in a global variable.
In most of my template files, the includes go like this:
include header
...do a bunch of stuff
include sidebar
include footer
I can not persist the variable into the footer.php file...
is there any way to do this so that I can avoid having to call back to the database again to look up the custom field value again? | You'd have to declare it first above those includes and globalize it within header or footer before getting or setting the value.
however- in the specific context you're speaking of- getting a custom field value, it's only retrieved from the database on the first call, then cached, so subsequent calls won't hit the database again. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, templates, variables"
} |
Upload multiple images and insert them into custom html code
Good evening. :)
Well, my mother is currently using a wordpress installation for her day to day blogging. Often, a post consists of some text and a few images, which are displayed via the very nice flexslider script. Usually, when the post is ready, I handle the flexslider part. However, I'm not always around, so posts get delayed, I get calls... You know. :) I'd like her to be able to do it herself, so I was thinking about writing a quick and dirty little plugin.
Basically, just select some images from the library and paste the code into the editor. Nothing fancy, this shouldn't take longer than a night or so.
The problem is, I've never developed anything wordpress, so some tips would be greatly appreciated. Of course, I'm not afraid of reading the documentation, but I don't have the time to really dive into it right now.
Thanks for your time. :) | Just take a look at the `RW_Meta_Box` library to add a drag and drop interface to add images as post meta data. That's the most easiest approach, plus it uses the new »WP Pluploader«. For more details take a look at this answer on how to customize it and read a little in the TenderApp Knowledgebase for a how-to. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin development, images, uploads, media library"
} |
wp-admin returns 404
I installed theme-my-login and after playing with it decided it wasn't for me. I logged out my dashboard, went to log back in and now my wp-admin returns a 404 error - what do I do? | Well you could have tried this:
try checking your `functions.php` and `wp-login.php` file:- try to see if there is some blank spaces at the end -(after `?>`) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "login"
} |
How to get a buddypress user profile link and a certain user profile field for the current post author?
I want to replace get_author_link() and get_the_author_meta($feld)
with something equivalent to point to the author of the current post Buddypress user profile page and retrieve a specific profile field from his Buddypress page
ie, I just want to show a link to the post user profile and a biography from one of his BP profile fields
I'm not sure which functions I should use for this... BuddyPress documentation is still not very clear unlike the WP Codex...
thanks | For an author's profile link, use
bp_core_get_user_domain( $user_id )
to get the URL, and
bp_core_get_userlink( $user_id )
to get an HTML link element, including display name.
For the xprofile data, use
xprofile_get_field_data( $field, $user_id )
`$field` can be either the name of the field (like 'Biography') or the numerical field id. | stackexchange-wordpress | {
"answer_score": 24,
"question_score": 19,
"tags": "buddypress, author, user meta, profiles"
} |
Output data like WP's plugin installer/updater
I want to update my plugin and have proper feedback, like the WordPress update/upgrade mechanism. How is this effect done?
Essentially I have a script I want to run that has lots of processing, and with each run through the loop, output another line to the screen. Is this done with the output buffer? | Yes, WordPress uses output buffering for displaying these messages. There's a nifty function you can use within your loop called show_message() which utilizes wp_ob_end_flush_all();
function show_message($message) {
if ( is_wp_error($message) ){
if ( $message->get_error_data() )
$message = $message->get_error_message() . ': ' . $message->get_error_data();
else
$message = $message->get_error_message();
}
echo "<p>$message</p>\n";
wp_ob_end_flush_all();
flush();
}
You might wish to abstract this to your own function as there is a feature in the queue to migrate this to a method within WP_Error. It's possible this function will become deprecated in the future. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "php"
} |
How can I list URLs of all audio files within my media gallery?
I have a music player in my theme that generates its playlist from a javascript file that looks like this
var myPlaylist = [
{
mp3:'track url goes here',
title:'title here',
artist:'artist',
}
{
mp3:'track url goes here',
title:'title here',
artist:'artist',
}
etc...
];
How can I query the media library so it will echo the track url, title text and maybe an existing audio parameter like "description" for the artist value?
I know enough about php to put them in the right places once they're queried, I just needto know how to pull them from the wp database! | Welcome to WPSE marctain!
**Edit** There are some critiques on using the guid but no one of the commentators managed to edit this answer to a better one, so I'll do it.
Yes, using guid is a bad idea in the long run, I knew that and I should have pointed that out, I didn't, it was a mistake. I'm sorry, it was a quick and dirty answer.
In my original answer, I would have made usage of wp_get_attachment_url to get the correct url in any case. This adds an extra query, but it is safe to use.
$args = array
(
'post_type' => 'attachment',
'post_mime_type' => 'audio',
'numberposts' => -1
);
$audiofiles = get_posts($args);
foreach ($audiofiles as $file)
{
$url = wp_get_attachment_url($file->ID);
echo $url; // url
echo file->post_title; //title
echo file->post_content; // description
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "media library, audio"
} |
Count user posts by user ID, Post type and Post status
What I am trying to do is modification of this function on codex < Check the title **adding post type support** bottom of the page. The function is:
function count_user_posts_by_type($userid, $post_type='post') {
global $wpdb;
$where = get_posts_by_author_sql($post_type, TRUE, $userid);
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
return apply_filters('get_usernumposts', $count, $userid);
}
What I want is to add post status to the function. So, I assume I have to add a WHERE to the query but not sure how to do it. Any help will be appreciated.
Thanks! | Here is a quick solution to get the post count any kind of filtering you want
function custom_get_user_posts_count($user_id, $args ){
$args['author'] = $user_id;
$args['fields'] = 'ids';
$ps = get_posts($args);
return count($ps);
}
Since this function uses `get_posts` you can filter and use anything that you can with `WP_Query`
So in your case you can use it like this:
$count = custom_get_user_posts_count($user_id, array(
'post_type' =>'post',
'post_status'=> 'draft'
)); | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "query"
} |
Get coordinates of selected area to use in image maps
I am developing a WordPress plugin that allows a user to insert image maps on the image from the WordPress default image editor. I want some JavaScript for it so that when user selects some area on the image it returns the coordinates of the selected area to use within the area tag. | I would suggest looking at this StackOverflow post - Image Map Editor \- particularly the top answer's recommendation: imgAreaSelect.
> imgAreaSelect is a jQuery plugin for selecting a rectangular area of an image. It allows web developers to easily implement image cropping functionality, as well as other user interface features, such as photo notes (like those on Flickr). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development"
} |
Trying to display short code content in template file with do_shortcode()
I installed the WP Issuu plugin on a site and tried to use `do_shortcode()` to render the shortcode in the template file. Strangely it doesn't work, although it does for the `[gallery]` shortcode.
I.e. this works:
echo do_shortcode('[gallery link=file]');
But this doesn't work:
echo do_shortcode('[issuu width=420 height=272 documentId=120118010023-8b7bf623bdd642d98252f310d62f1625]');
After some research, I found that this would work too:
echo apply_filters('the_content', '[issuu width=420 height=272 documentId=120118010023-8b7bf623bdd642d98252f310d62f1625]');
Any idea what's going on and how I can solve this? Thanks | WP Issuu plugin doesn't use the shortcode API. So you can't use it like a regular shortcode. The plugin is a filter for the_content, that's why your solution did work.
If you want to solve this (use do_shortcode) you have to rewrite the plugin so it uses the shortcode API. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "templates, shortcode"
} |
database columns: post_title vs post_name
I changed post_title, post_contents, and post_name to allow for utf by changing collating sequence to: utf8_general_ci
Then using add new post, I type for the title three Hebrew ALEFs.
The post_title is in Hebrew in the database, but the post_name has this value:
%d7%90%d7%90%d7%90
According to Charmap, ALEF has a hex value of 05D0.
So what does the d790 represent? Some other encoding?
I'm looking to write a program to mass upload a bunch of posts, so I need to know what to put in the post_name field, and what it is used for. | it's the URL encoded version of your text.
<?php
echo urldecode('%d7%90%d7%90%d7%90');
?>
outputs:
אאא
`post_name` is the slug, so the characters have to be URL-safe. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "posts, database, multi language"
} |
Loop not displaying comments_popup_link
I cannot get the `comments_popup_link` to display with the posts retrieved by the foreach loop. Only the title and permalink are displayed. Any idea why the comment link is left out?
<?php
if(count($ids)){
echo '<div id="tab-news" class="tab-all"><a id="link-news" class="link-all" href="/news">News</a></div><ul>';
foreach($ids as $id){
echo '<li><a href="'.get_permalink( $id ).'">'.get_the_title( $id ).'</a>';
if ( comments_open() ) :
echo '<p>';
comments_popup_link( '', '<span class="onecomment">1 comment</span>', '<span class="morecomments">% comments</span>', '');
echo '</p>';
endif;
}
echo '</li></ul>';
} | the `comments_popup_link()` function will only work when used within the_loop; a 'foreach' loop using post Ids is not the same.
you could try to build your own link, based on this function: `get_comments_number( $id )`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments, loop, php"
} |
"add from media library" tab is super slow
The add from media tab for wordpress is _super slow_ on my local. It takes at least a full minute for the modal box to load content when I click that tab. I am guessing it is because I have 65 pages of images and WP is loading all 65 pages.
Is there a good plug-in or a hack out there to help speed up content loading when adding feature images to posts from the medial library?
Thanks. | Found: The issue was the Media Library Categories plugin. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "media library"
} |
Empty title on front page/Home
My main problem is around the title. In my index.php, I have specified a title tag and inserted the following:
<?php wp_title(); ?> | <?php bloginfo( 'name' ); ?>
My problem is the it is only printing the blog "name" - wp_title() prints nothing
i.e. This is what is being printed from the above:
> | Wordpress Test Site
NOTE: The Page Title should be: Home
Strangely, when I visit My Sample Page, it presents the following:
> » Sample Page | Wordpress Test Site
And they are both using the same header.php file!
Am I missing a setup somewhere that doesn't work on the home page?
FYI - I've set the Page - Home as the static front page.
Thanks | The title is empty at the front page in WordPress. Yes, that sucks.
Just put the separator into `wp_title()`:
<title><?php
// separator, print immediately, separator position
wp_title( '·', TRUE, 'right' );
bloginfo( 'name' );
?></title>
This prints out just the blog name on the front page and `PAGE NAME · BLOG NAME` on other pages. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "title"
} |
Front-end delete account in Wordpress
is there a way for a registered user in Wordpress to have in his author page an option to **delete** his account along with his posts without going to dahsboard?
I need a front-end option in a form of a button for user to be able to delete his profile :)
Thank You in advance for Your help guys! | take a look at **`wp_delete_user`** , all you need to do is pass the author's id and his posts will be deleted along with its account. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "front end, customization, account"
} |
Comments system doesn't like International domains
Morning all,
I'm trying to work out why the commenting system thinks .au, .ca and a couple of other international email address are being treating as invalid.
Any ideas? | WordPress’ internal email validation is very weak. I’ve written a plugin some time ago to catch _most_ cases where WordPress fails: Extend Email Checks.
It uses PHP’s `filter_var()`. But there are some edge cases, where it doesn’t work good enough. Give it a try. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments"
} |
Use Loop or direct database query?
In one of my form input, the options are a list of posts. I can use the loop to get the posts, but, getting things from database table is faster, right? I see plugins sometimes use db directly, sometimes use loop. I'm confused. | In general I try to avoid custom SQL queries as much as i can and use the native WordPress functions but in some cases its much better/faster to use custom queries.
if the case is just get a list of posts the you can use the WP_Query or get_posts which will work almost as fast as a custom query (as long as you don't need some advan | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop, wpdb"
} |
White-list file types for media upload
I'd like to attach files that aren't on the list of supported file types. In this case I'd like to upload files from the media manager that have the .RWP extension (which is used to package files in the Train Simulator 2012 game). | You can hook the upload_mimes filter to accomplish this:
add_filter('upload_mimes', 'wpse_43657_upload_mimes');
function wpse_43657_upload_mimes($mime_types){
$mime_types['rwp'] = 'application/octet-stream';
return $mime_types;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "uploads"
} |
where is the documentation for add_action() parameters?
I am reading the source of a plugin (gallery to slideshow plugin) to make it behave like i want and it is using an action
add_action( 'the_posts', array( &$this, 'have_gallery' ), 10, 1 );
I want to know what those extra parameters (10,1) mean but i cant find the documentation of this action. Please help | those parameters aren't unique to the_posts, they're parameters for the add_action() function
add_action( $tag, $function_to_add, $priority, $accepted_args );
the 10 is just the default priority and 1 is the default number of accepted arguments. since they're both default, you don't really need either.
< | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "actions, documentation"
} |
Is it possible to get rid of admin new updates notifications?
I am doing projects for clients and sometimes an update messes a lot. So, can we leave error messages and get rid of new updates notifications in wordpress admin side?
Thanks! | Try this: < which seems to work good for 2.9- versions
//Copied from the above referenced article
remove_action('wp_version_check', 'wp_version_check');
remove_action('admin_init', '_maybe_update_core');
add_filter('pre_transient_update_core', create_function( '$a', "return null;"));
For 2.9+ try this: <
add_action('admin_menu','foo_hide_update');
function foo_hide_update() {
remove_action( 'admin_notices', 'update_nag', 3 );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin"
} |
How to add code to Header.php in a child theme?
I'm creating a child theme for the first time and I had a few questions regarding code added to header.
In a non child theme there is certain code I add to my header.php file such as google analytics, google webmaster tools, buy sell ads, Facebook open graph, etc....
How do you do this in a child theme? Do you create a header.php file in your child theme? If so how is this done? Is it the same as the @import as I used on the css?
Thanks. | I would hook into the `wp_head` action. I would place this in a plugin so as to abstract it from your presentation layer. This allows for scalability and changing of themes. This also prevents any analytics collateral damage if a step is missed in migration from one theme to the next.
add_action('wp_head', 'wpse_43672_wp_head');
function wpse_43672_wp_head(){
//Close PHP tags
?>
ADD YOUR PLAIN HTML CODE HERE
<?php //Open PHP tags
} | stackexchange-wordpress | {
"answer_score": 33,
"question_score": 27,
"tags": "child theme, headers, open graph"
} |
buddypress edit profile
I have installed buddypress, I don't see any errors or success message when a person updates their profile details.
Also for some reason it only seems to update admins details, a normal user/subscriber, cannot update its on profile.
has anyone come across this? help please. | I managed to use `$bp->template_message` this was a bit tricky but then I had to go to bp-xprofile-screens.php just under line 77 I added `unset($is_required[1]);` to remove the username update, (as this does not need changing) :)
hope someone else, may find this useful. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "buddypress, profiles"
} |
Create pagination and order according to alphabet
is it possible to create an alphabet pagination? as well as alphabet order of a query post???
I can't a solution on this based on the regular queries.
I would appreciate any help, thanks in advanced.
UPDATED* _*_ *
Well since apparently this hard to understand, I will explain myself better.
I'm looking for a way to query post based on the alphabet order that allow me paginate **NOT** by page but alphabet first letter. In this order I cannot use default order_by = 'title' as some1 suggested.
PD: ifyou are going vote down, at least contribute with something, I don't think that is really hard to understand that more than the 50% of the users of the site don't use english as first language, so even if we do all our best to help the community we can make mistake sometimes. In this order if you are going to say "Explain yourself better" at least give an opinion of what you understood. | i wrote about something similar recently, maybe it could be helpful to you:
<
it was based off of my answer to this question: Group Posts by First Letter of Title
the answer includes both my original posts_where solution and an alphabetical "menu" that for some reason i didn't write about in my tutorial | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "query"
} |
Why is get_the_category() saying that I have two categories?
My post has only one category. The following code:
$categories = get_the_category();
gives me this result:
Array
(
[0] => stdClass Object
(
[term_id] => 22
[name] => Style Guide
[slug] => style-guide
[term_group] => 0
[term_taxonomy_id] => 22
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 2
[object_id] => 391
[cat_ID] => 22
[category_count] => 2
[category_description] =>
[cat_name] => Style Guide
[category_nicename] => style-guide
[category_parent] => 0
)
)
Why is it double up? | I'm guessing you're referring to the
[category_count] => 2
when you say "saying that I have two categories"?
If so, you should understand that category_count is not the number of cateogries that this post has, but rather it is 'the number of uses of this category (also stored as 'count')' - see get_the_category function reference. The fact that there is only one array element in the returned object indicates that there is only 1 category assigned to this post.
count($categories)
... will give you what you are looking for. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 1,
"tags": "categories"
} |
Does the number of widgets installed affect website performance?
Does a website slow down or under perform in any way with a large number of widgets installed? | Put simply: not inherently. If you have a widget that does NOTHING at all...like, literally you add it and there's no code for the widget outside of registering it, you'll see SUCH a small performance hit from adding it that you would need to be looking at `microtime()` numbers to notice anything.
That said, as @cmegown hit on a little, it depends what the widgets do. If you have a widget that calculates pi or solves differential equations or something heinous like that (I can't really think of a good example), then you're gonna start looking at more and more of a performance hit.
Real world, where you're going to see issues is widgets that make HTTP requests, be those feeds, stylesheets, or calls to cURL. The best advice I can give you is to know what your widgets are doing, and make sure they're doing it right. Typically if you do that, everything else falls into place. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 5,
"tags": "widgets, performance"
} |
Get post related on category
it's a catalog website for different product. I need a function that will get the category of the selected product, and get all the product from that category
Let see an example. A table, is in wood category and kitchen. So when display table, under the table i like all the other kitchen product listed as well as all the other wood product... it good for cross selling !...
how do i do that ? | You can use `WP_Query`'s `tax_query` to do this. You would want the args (just on the `tax_query`, I'll leave the rest up to you, you have the documentation) to look something like this:
'tax_query' => array(
'relation' => 'OR'
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'wood'
),
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'kitchen'
)
),
That method will allow you to query as many types of posts as you like. Alternatively, you can have multiple `WP_Query`s and use `wp_get_post_categories()` to get the terms for a `foreach` to feed dynamically generated suggestions, each with its own `WP_Query`. It sorta depends how you want the output to look. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories"
} |
Alter BuddyPress member search to include search on added profile fields
I added a "company" field to member profiles via s2member plugin. However, this field is not included in the "member" search. For instance, when I search on the name of a company (when I know the company name I'm searching for is part of a member's profile info), the search displays "no results".
How do I make added profile fields searchable? | Fields added by S2Member are probably stored in wp_usermeta, while BP's member search searches over data stored in BP's xprofile tables. Probably the most straightforward fix is to use a BP profile field for your 'company' data. If you've already got member data in there, you'd have to write a script that moves (or copies) it over. The alternative is to tap into BP's search queries and join against the usermeta tables. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "search, buddypress, members"
} |
Use of antispambot with $curauth->email
This is probably pretty simple, but...
I want to use the WP function **antispambot** not on **get_the_author_email** but on a value in a field I added to User Profile called **publicemail**. Everything I've tried throws a php error.
This is the **antispambot** usage shown in the WP docs:
echo antispambot(get_the_author_email());
And this is the complete function I'd like to get to work with **antispambot** and have it encode **publicemail** :
<?php
if ( !empty( $curauth->publicemail )){
echo 'Email <a href="mailto:' .$curauth->publicemail.' ?subject=Webmail">
<img src="' . get_bloginfo('template_url') . '/images/email_16.png"></a>'; }
?> | As the Codex states for the `antispambot()` function:
> **Return Values** _(string)_ Converted email address.
You have to do one of the following:
echo antispambot( $curauth->publicemail );
// OR...
print antispambot( $curauth->publicemail );
So your full example would look like the following:
if ( ! empty( $curauth->publicemail ) )
{
echo 'Email <a href="mailto:'.antispambot( $curauth->publicemail ).'?subject=Webmail">
<img src="'.get_bloginfo('template_url').'/images/email_16.png"></a>';
}
### About the difference between echo, print and (just) return
1. `echo` and `print` are just synonyms/alias for each other and actually _display_ something on the screen. The only difference in usage is, that you can't use `echo` in combination with `return`.
2. `return` just gives something back as a functions output. In combination with `print`, a function can actually _display_ something in a template, etc. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, functions, email, users, author template"
} |
WP Query to get all posts (including in draft/pending review)
I currently have the following query:
$args = array(
'post_type' => 'post',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => 10,
);
$my_query = new WP_Query($args);
while ($my_query->have_posts()) : $my_query->the_post(); ?>
This returns all the posts that are published. How can I alter it to show every post whether it's published, pending, or in draft? | You can add post_status to your query, the string 'any' will return all posts no matter the status, or you can use an array to just grab those you want.
$args = array(
'post_type' => 'post',
'orderby' => 'title',
'order' => 'ASC',
'post_status' => 'any',
'posts_per_page' => 10,
);
< | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 4,
"tags": "wp query"
} |
Posting Instagram Photos Automatically
I'd like to post my Instagram photos to my WordPress blog.
I cannot use one of the many existing Instagram plugins, though, because those plugins simply post the images on my blog but they are still hosted by Instagram. I'd like this to be a batch process that will actually upload the Instagram photo to my WordPress media library and then post it.
In summary: How do I automatically _upload and post_ Instagram photos to my WordPress blog ( _not_ via a sidebar widget)? | You'll probably have to do your own integration, but here's how I would approach it:
1. Grab an Instagram PHP wrapper: < OR < OR <
2. Authenticate via an admin option page
3. Iterate through your user images using the `/users/self/feed` method
4. Use the media_sideload_image() function found in wp-admin/includes/media.php to download the images
5. Keep a running cache of downloaded Instagram image IDs in an option to check before downloading an image.
If you want this to work as a WordPress gallery, you could assign a specific post ID to `media_sideload_image` and then include a gallery on that post.
It seems pretty straightforward. Check out the API documentation for self/feed: < | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugin recommendation, automation"
} |
Host Images from Link
Recently, I imported all my post from Blogger, so all the images showing in the post currently reside on Blogger's server. I want to import/put all those images to my server and automatically change each link for each image.
Since there are so many images and so many post I can not go one by one individually.
Please guide me on how to do that or redirect me to a plugin that does this job. | What Chip said; the native importer tool (look in Tools > Import) should have imported everything. But if it didn't, and you already have the rest of the content, you can run this plugin to bring over all your images:
<
Best of luck! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads, media library, import, migration"
} |
Is it possible to import NextGen Galleries into Wordpress Galleries and convert embeds in all posts?
**Let me explain —** Until now, I have been using NextGen Gallery, and since I have a redesigned website that has image.php template (gallery attachments page), I would like to use Wordpress' built-in gallery feature instead.
**Here's the problem —** I can't forever continue to monitor if NextGen Gallery plugin is working as intended on my website, even though my old posts still use it.
Considering that, I would like to import and convert all NextGen galleries into Wordpress galleries.
Is there a way to do this without all the hard work of having to upload gallery-by-gallery, post-by-post (I have close to 250 galleries!)? | Konstantin Kovshenin from Automattic built a small WP plugin hosted here at GitHUB, which does pretty much exactly what you are asking for. It does not seem to solve the whole migration as it works only for `[nggallery]` shortcodes, but anyone can fork it and add some more lines to solve the rest, right? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "gallery, plugin nextgen gallery"
} |
List taxonomy term "Last Name" + "First Name" (taxonomy custom field) in a post loop
I have a few custom fields for a taxonomy "Author". The term title is the Author's last name, and one of the custom fields is his first_name. Now I need, in a post loop, to list all "Authors" of that post by their full name. How can I do this? I'm using Ultimate CMS plugin to manage taxonomy custom fields.
Just to be clear this is a post type "Academic Article" with the authors as a taxonomy. Thank you. | So I decided to go another way. I now have the Author's Full Name as terms in the taxonomy. For the index, for which I need to separate Last Name and First Name, I used PHP string functions.
<?php
$taxonomy = 'autores';
$queried_term = get_query_var($taxonomy);
$terms = get_terms($taxonomy, 'slug='.$queried_term);
if ($terms) {
echo '<div id="indiceAutores-nav"></div> <div id="columns"><ul class="indiceAutores" id="indiceAutores">';
foreach($terms as $term) {
$names=explode(' ',$term->name);
$lastname=array_pop($names);
$firstname= $term->name[0];
echo '<li><a href="'.get_term_link($term->slug, $taxonomy).'">'.$lastname .', ' .$firstname .'.</a></li>';
}
echo '</div></ul>';
}
?>
I also added some jQuery plugins for the final iteration: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom field, taxonomy, templates"
} |
Using nonce external of WP Admin
All, I've got two wordpress pages. One wordpress page displays a form to do some registration stuff for the website. The second wordpress page actually processes the data and inserts it into a custom MySQL table that I have. I'd like to use the nonce functionality inherit to Wordpress. The user doesn't have to be a Wordpress admin or have any type of permissions to be able to do it.
Can anyone give me an example or show me how to do this outside of the WP Admin in a Wordpress page?
Thanks for any advice in advance! | Nonces are not tied to the admin interface. This codex page explains them very well. Essentially, you add :
<?php wp_nonce_field('name_of_my_action', 'name_of_nonce_field'); ?>
in your form (this creates a hidden input field containing an one-time-use token). And where you're doing the form processing you just check if the nonce is correct
if(!wp_verify_nonce($_POST['name_of_nonce_field'], 'name_of_my_action')){
// no permissions
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "nonce"
} |
Content over 10,000 characters won't display with the_content()
A friend of mine just noticed that their site wasn't displaying pages that had a lot of content. For some reason they are just blank, and if he removes some content from the page it will display again. The 10,000 character mark seems to be the threshold - anything above and it goes blank.
I played with his templates and noticed that the content would be displayed if I used `echo get_the_content()` rather than `the_content()`, but then he loses the auto-formatting.
Has anyone run into this issue before? I've googled around and searched this site but haven't been able to find anything. Thanks in advance for any light you can shed on this! | I ran into this problem a year or so ago, and found a fix here.
* Open PHP.INI in a text editor of your choice (normally you can find php.ini in your php install dir)
* Change the recursion limit to 200x normal, that is, set: `pcre.recursion_limit=20000000`
* Change the backtrack limit to 100x normal, that is, set: `pcre.backtrack_limit=10000000`
* Stop and start the Apache (or IIS) service
As a warning note, if you push this too far and your server is underpowered, you may end up crashing PHP as it consumes the entire stack. Your host may not be too happy about that.
If you don't have access to your php.ini, you can set these variables inside wp-config.php. Somewhere before the `require_once(ABSPATH . 'wp-settings.php');`, maybe in the debug area (up to you), add these two lines:
`@ini_set('pcre.backtrack_limit', 10000000);`
`@ini_set('pcre.recursion_limit', 20000000);` | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 5,
"tags": "formatting, the content"
} |
Removing the advanced menu properties
As I'm often involved with people who don't know anything about WordPress, a CMS or even the internet :) I try to hide things irrelevant (for them) as much as possible.
Normally this would involve removing a meta box here and there, but I have to admit, I'm sort of stuck on the WP menu system.
Would anyone know perhaps a way to remove the fields marked in red (picture)?
!enter image description here | As mentioned in a previous comment, I went for a jQuery solution:
add_action( 'admin_footer-nav-menus.php', 'cor_advanced_menu_properties' );
/**
* Hides the `nav-menus.php` 'advanced menu properties'
*/
function cor_advanced_menu_properties() {
?>
<script>
jQuery("h5:contains('Show advanced menu properties')").next('.metabox-prefs').remove();
jQuery("h5:contains('Show advanced menu properties')").remove();
</script>
<?php
}
If someone knows perhaps a better alternative, or if any optimizations to this snippet can be made, I'd be more than happy to listen :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "admin, navigation"
} |
Allow single quote in URLs
I have a WordPress site hosted on a Go Daddy server running Apache. My experience is on Windows IIS, so this might be an easy question, but I can't figure it out. I want to allow URLs at my site like:
<
The problem is two fold.
1) If I enter
<
the URL is fine, but if I enter:
<
the URL is rewritten to:
<
Note the lost single quote is shown in the browser address.
2) The page requires memebr acce3ss. When you browse to it without logging in you are sent to the login page with the URL
/wp-login.php?redirect_to=/biz/Jordan\'s_place/jordan/
Note the added backslash and then after login the page goes to:
<
Is it WordPress or the server that is messing with the single quotes? Am I crazy to want to allow single quotes in my URLs? If so, why doesn't PHP or javaScript encode them? | Wordpress will strip off special characters, since they can cause issues when writing to the database. It's best practice to avoid using special (reserved) characters in URLs, as they can and will break when passing them around. Case in point, see your own post and the cutting off of the URL after the '. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "url rewriting, urls"
} |
Plugin to hide admin menu (vertical menu bar)
I am learning to write WordPress plugin and testing out a simple case: hide the admin bar base on user role. So far I have the following in my plugin file:
$hidemenu= new HideMenu();
class HideMenu
{
function hideMenu() {
add_filter( 'show_admin_bar' , array($this, 'hideAdminBar'));
}
function hideAdminBar() {
if (!(current_user_can("administrator"))
return false;
}
}
This is base on the example given in WordPress reference. Any idea why this is not working? | Have you looked at the WP Custom Admin Bar plugin? At the very least it has some code chunks you can deconstruct to point you in the right direction. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins, plugin development"
} |
How to store page visit counts?
I am working on a project, which requires a page visit count to be shown on the single post.
How can I do this in wordpress, I am guessing, that I have to store them in the same wordpress db? | You can use custom fields for this. What I would suggest is setting up a shortcode you can put on any page you want to show the counter. For an extremely basic example with no HTML formatting, you can do this:
add_shortcode( 'examplecounter', 'counter_shortcode' );
function counter_shortcode( $atts, $content = null ) {
global $post;
if( isset( $post->ID ) ) {
$current_count = get_post_meta( $post->ID, '_counter_custom_field', true );
$new_count = $current_count === '' ? 1 : $current_count + 1;
update_post_meta( $post->ID, '_counter_custom_field', $new_count );
return $new_count;
}
}
And now you can place `[examplecounter]` anywhere in a post and it should start counting for you. :) | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "customization"
} |
Export WordPress from one domain to another domain
From one domain (foo.com), select export as WXR and import to (bar.com), also I manually uploaded wp-contents to the new location.
Everything is working, except the the images in the blog post still using the old domain.
1. How to solve it?
2. I have tried to upload into wp.com and they can auto update the images' location, but this does not work for self-hosted wordpress?
Thanks. | When you **import** the WXR file to the WordPress install on the new domain, be sure to click the " **Download attachments** " checkbox that you are presented during the upload process. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "import, migration, export, domain"
} |
Custom Log In Screen - Disable password recovery
> **Possible Duplicate:**
> Change login error messages
I'm creating a custom log in page on a wordpress install and would like to remove the "Lost your password?" link from the "ERROR: Invalid username. Lost your password?" message that comes up if the user inserts the wrong password.
I've been looking in the wp-login.php but must be missing something, can someone point me to the right file? | I've found the generated text in the `wp-includes\user.php` file so removed it there and done what I was looking for. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "customization, login, password, account"
} |
Determine if only one image attached to a post/page
I'm looking to determine how many images are attached to a post, specifically if there is only one. Basically if there are multiple images I want to display my slideshow script, if there is only one I want to display that image, and not load the slideshow.
I saw this on a similar post which determines if any images are attached:
$attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image') );
if ( $attachments ) {
// do conditional stuff here
}
Can I use something similar to determine if there is only one image?
Thanks! | That code should get the attachments as array which you should be able to use `count()` on to determine the total number of images. Example:
if ( $attachments ) {
if ( 1 == count( $attachments ) ) {
// handle single image
} else {
// handle multiple images
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, images"
} |
Best way to modify content from index.php to single.php?
My blog has simple posts including a youtube videos. For example:
<iframe width="460" height="342" src=" frameborder="0" allowfullscreen></iframe>
and index.php will echo content ( )
I want that the permanent link of this post ( single.php ) displays:
<iframe width="700" height="505" src=" frameborder="0" allowfullscreen></iframe>
.. it's the same video but with different width and height.
What will be the best and easy way?
( should i use and try to work the excerpt and content someway? )
That also leaves to another question: how to show some content in the index.php and different content in the single.php page ?
Many thanks, Pedro | Your best bet is to use custom fields for the YouTube video URL and then use `get_post_meta();` to pull out the URL, then in your template files (index.php, single.php) set up the embed code on each template. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "content, single, read more"
} |
get_the_terms issue
I'm trying to list the custom taxonomy term that is attached to the post in question (which is a custom post type). I want to list it without it being a link, it is in fact a title.
I've tried this, but it clearly doesn't work. What am I doing wrong?
function woocommerce_output_product_brand() {
$terms = get_the_terms( $post->ID, 'brand' );
foreach($terms as $term){
echo $term; }
}
Thanks in advance! | First of all, what is `$post`? If you after the global `$post`, then you have to declare the global in the function. So on the second line you'll need to put `global $post;`.
Secondly, `$term` is an object. If you are after the term's name, use `$term->name`, for it's slug `$term->slug`.
See the Codex for some examples of how to use `get_the_terms` | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom taxonomy"
} |
Sidebar widget: Randomly select text from a given set
I have a sidebar text widget, which displays a nice quote that's related to the blog contents.
I change the quote every now and then, And I'm looking for a way to create a set of quotes and display one of them at random.
Is there a plugin for that? | The plugin repository contains a few options that you could use. At a glance this one looks promising. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, widgets, text"
} |
Add an extra field to the navigation menu box?
Goal: I like to use a subtitle in the navigation bar.
The most logic location, in my opinion, would be Appearance > Menu and add a field below navigation label called subtitle. So the end user can easily add and change a subtitle there for the different menu items.
Looking at `wp-admin/includes/nav-menu.php`, I can't find an action to hook onto, is this correct? Does anyone have an idea to accomplish this? | have you ticked the 'Description' box under 'Show advanced menu properties' in the 'screen options' tab in the **_appearance -> menus_** page?
and have a look at this related post: < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "menus, navigation, options"
} |
Query sub subpages based on specific date?
I have an Events section as follows:
> 1. Page 1)
> 2. ∟ Subpages 2)
> 3. ∟ Sub subpages
>
1) Own template, w/o sidebars, but `query_posts()` and `get_title/excerpt()` from N°2
2) Other subpages are listed in a sidebar left menu - and `query_posts()` N°3
How can I list N°3 titles/excerpt on N°3 subpages, if they are before and after a date? Where, or how, can I set the Date?
Basically, I need a
* "coming events" section
* and a "past events" section
...on every subpage (N°2) with links to N°3 sub subpages of the relevant sub page.
I would then create a sub subpage, give it a date and - on my subpage - (if the date of the sub subpage is in the past) I will list in "past events".
If the date is still later than the current date, I will list it in "coming events". | If you're loading additional posts/pages, it's better to use a new `WP_Query` instance. `query_posts` is only for modifying the main query.
As for the dates, store them in a custom field in the format `yyyy-mm-dd`. You'll use php's `date` to get the current date, refer to WP_Query's custom field parameters for how to query and order based on a field's value.
There are also many similar questions on this site with working code if you search for `custom field date`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "date time, child pages"
} |
How long does a deprecated function live in core?
I'm curious to find out the process/philosophy behind removing deprecated functions from core.
The Codex says this:
> These functions below have been deprecated. That means they have been replaced by new functions or are no longer supported, and may be removed from future versions.
Since 'may be removed' is a bit ominous and somewhat unclear, I have the following questions.
1. What is the criteria for deletion of a deprecated function? (i.e. version gap, time-frame, security risk, etc...)
2. Is the deletion of a function communicated to the public officially?
For example: `get_postdata()` has been deprecated since 1.5.1 and doesn't have an official Codex page. Is there a reason this is still around other than to support older versions of WordPress? | To the best of my knowledge, and having heard Nacin say it explicitly, no deprecated function has ever been removed from WordPress to date.
No guarantees for the future, but it's never happened yet. Still, avoid deprecated functions. | stackexchange-wordpress | {
"answer_score": 12,
"question_score": 22,
"tags": "functions, deprecation"
} |
Change the look and feel of admin pages
I want to change the look and feel of the post edit page without making changes to any of the wordpress core file, which is basically a theme. For example, for any user with role of 'author', i want to display everything in one column and re-arrange the meta boxes. So is it possible to create a theme for one of the admin pages and how could i get started? | The admin area can definitely be themed, using either CSS, a plugin, or a combination of both. To get started, read the Codex page on Creating Admin Themes.
To expand further - any overriding of core WP functions must be done from a plugin. It's fairly simple, and just like any other function override - either adding the content with a new function and `add action` or with a filter to replace the existing function with your new function using `add_filter` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, theme development, admin"
} |
Change how WP e-Commerce calculates price total at checkout
My situation:
I'm selling a few products. I need to get some options at checkout (like Do you want to add installation services?) that will affect the price, and I need to reference a custom database table to do some complex price calculations to get a total order price.
I wanted to use getshopped.org's wp e-commerce shopping cart, but somehow override the checkout page to do what I need, then return my calculated price to wp e-commerce to finish the order up.
How would I do this? Would I use a hook? Should I change some method that calculates the totals (without losing my changes on the next update)? Or do I have to drop the plugin and roll my own completely? Thanks so much. | Some inspiration:
An old colleague of mine did a similar solution. He created a product, in your case called "Installation service", put it as a draft and added it with ajax when customer added it in the shopping cart, and then updated the total price. In that way the product was added to the order and the total price. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin wp e commerce, customization"
} |
Make Custom Field Into A Link On The Front End?
I have set some custom field 'artist' and 'song-name' displaying like:
Artist: <user input>
Song Name: <user input>
My question, how do you make the on artist and song name into a clickable link? Such that when the artist name is clicked for example, it will bring up the page with all posts of that artist name? Thinking about it, its kinda like the_category() or get_category_link, only I am using custom fields. | This is better accomplished by registering a new taxonomy. You get all of the advantages of categories and tags without the hassle of custom fields.
Codex: register_taxonomy
Tutorial: How to Create Custom Taxonomies in WordPress 3 | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "custom field"
} |
Having separate plugins and themes folder for multi-site setup
My multi-site setup uses sub-directory. I am creating one plugin + one theme to customize each of the sites. Is there any way to have separate plugins and themes folder per site like so or something similar:
root
+----wp-content
| +----site1
| +----plugins
| +----themes
| +----site2
| +----plugins
| +----themes
+----mu-plugins
| +----shared-plugin1
| +----shared-plugin2
+----plugins
| +----optional-plugin1
| +----optional-plugin2
The goal is so that each site can only activate/deactivate the plugin/theme intended for it.
**Edit**
Multisite Plugin Manager can be a way to achieve what I want to do logically, though it does not put the plugins in their individual directories. I am still interested to hear other solutions. | There's `register_theme_directory()` to ... well register additional theme directories.
For plugins, we don't know how to get around it (so far). If you want, then you can jump into the discussion here and add your thought, share your try-outs and maybe we all together will come to an solution :) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "plugins, plugin development, theme development, multisite"
} |
Logout redirect to current page - function
I'm looking for a function that can redirect users when they logout to the current page. I'm looking for a code I can use in `functions.php`? | Using this code in the `functions.php` does the trick:
function wpse_44020_logout_redirect( $logouturl, $redir )
{
return $logouturl . '&redirect_to=' . get_permalink();
}
add_filter( 'logout_url', 'wpse_44020_logout_redirect', 10, 2 );
Note - The above code works only on non-admin pages. To make this work on any page you should replace:
return $logouturl . '&redirect_to=' . get_permalink();
With:
return $logouturl . '&redirect_to= . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 5,
"tags": "functions, users, logout"
} |
Is there a way to prevent author change when editor/administrator edits a post?
As an administrator when I change or edit a post of an author (for example add a category through quick edit) the author of the post changes. We do not want this to happen. Is there a way to prevent this? | Both, quick edit and the regular post edit screen, offer an author field. Just take care to set the correct author when you edit something.
!enter image description here
To see this field you have to enable it in the screen option in the upper right corner:
!enter image description here | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "admin, author, quick edit"
} |
Common categories for two custom post types
can I use a category as common for more than one custom post types? In this case same category will have more than one type of posts.. | When you use `register_taxonomy()`, the second argument is the `object_type` argument, which accepts either a string or an array. You can pass this an array of objects to apply the taxonomy to, and it will be common between those. So, for example: `array( 'cpt_slug', 'post' )` would give you a common taxonomy between `cpt_slug` and `post`.
If you want to add the existing taxonomies to a new post type, you can use `register_taxonomy_for_object_type()` | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types"
} |
Custom post types - Use post_id in permalink structure
I'm registering my CPT like so:
$args = array(
'labels' => $labels,
'public' => true,
'hierarchical' => false,
'rewrite' => array(
'with_front' => false,
'slug' => 'news/events'
),
'supports' => array( 'title', 'editor', 'thumbnail' )
);
register_post_type('events',$args);
Now that will generate post permalinks like so: `/news/events/{post_name}/` but I want the following permalink structure: `/news/events/{post_id}/{post_name}/`.
How do I do this? | @Bainternet - your answer didn't fully work but I did some more searching and was able to piece this filter together that did work:
add_filter('post_type_link', 'custom_event_permalink', 1, 3);
function custom_event_permalink($post_link, $id = 0, $leavename) {
if ( strpos('%event_id%', $post_link) === 'FALSE' ) {
return $post_link;
}
$post = &get_post($id);
if ( is_wp_error($post) || $post->post_type != 'events' ) {
return $post_link;
}
return str_replace('%event_id%', $post->ID, $post_link);
}
+1 for getting me most of the way | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 8,
"tags": "custom post types, permalinks, url rewriting"
} |
Custom taxonomy admin page
If you want a custom admin page for a taxonomy, you can set `'show_ui' => false` when you register it to suppress the default admin page and then create a new admin page to replace it.
However `edit-tags.php?taxonomy=taxonomy-slug` still takes you to the 'hidden' default admin page. Is there way of directing it instead to the custom admin page. Or otherwise is there another method than circumvents this issue? | Not sure why I didn't think of this earlier. I suppose I was hoping for a way to 'hijack' the default page to display something else... Anyway following my original method:
> If you want a custom admin page for a taxonomy, you can set 'show_ui' => false when you register it to suppress the default admin page and then create a new admin page to replace it.
You can get round the issue of `edit-tags.php?taxonomy=taxonomy-slug` taking you to the hidden taxonomy page, by simply redirecting the user to your page, using `wp_redirect`:
add_action('load-edit-tags.php','myprefix_redirect_to_custompage');
function myprefix_redirect_to_custompage(){
$screen = get_current_screen();
if($screen->id == 'edit-mytax'){
$url = admin_url('edit.php?page=mypage');
wp_redirect($url);
exit;
}
}
_Assuming`mytax` is the taxonomy name. `$url` should be the url of the custom page replacing the default taxonomy page._ | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "admin, taxonomy"
} |
tag.php pagination and query_posts()
Having some issues on the tag.php page.
Right now it just give me a "nothing to show" If I have no query it shows posts, but I want to change the number of posts per page.
Changing the reading settings in the admin is not an option in this case, so I'm looking for template tag ideas only.
Any suggestions on ways to re-write this properly?
Thanks, sorry if this question is really boring.
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$tags = array(
'posts_per_page' => 10,
'paged' =>$paged
);?>
<?php query_posts($tags); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
Just as an edit: I am looking for some syntax help to write some code for posts_per_page and pagination that is structured for just a plain wordpress loop.
Thanks, sorry if it was a bit confusing. | After some other attempts I Found the syntax solution I was looking for. Just sharing.
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts($query_string .'&posts_per_page=10&paged=' . $paged);
if (have_posts()) : while (have_posts()) : the_post(); ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "pagination, template tags"
} |
Measure and limit file uploads
I want to deliver WordPress powered packages to some users and want them to have:
1. a limitation on disk quota (/each user)
2. A way to measure/show how many MBs they are currently using
Any solution would be appreciated | I would use a multi site installation for this. Give each user their own blog.
Multi Site has built in disk quota functionality, and you can see how much of it is used and such in the admin area of each site. You can set the quota in the network admin: `settings > network settings`.
Combine that with domain mapping allowing your users to have their own domains and you've got a fairly powerful system. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, uploads"
} |
Wordpress Related Plugin - Adding an image
I'm using the Wordpress related plugin which is great but I would like to display the feature picture of the page.
It mentions on < about using a custom code.
Below is what I have so fave but I'm looking to add the feature image thumbnail to the related post.
<?php
$rel = $related->show(get_the_ID(), true);
foreach ($rel as $r) :
echo '<li><a href=' . get_permalink($r->ID). '>' . $r->post_title . '</a>' . '</li>';
endforeach;
?> | Have worked it out and have the following code:
<?php $rel = $related->show(get_the_ID(), true);
foreach ($rel as $r) :
echo '<a href='.get_permalink($r->ID).'>'.get_the_post_thumbnail($r->ID, array(50,50)).'<div class=page-related-title>'.$r->post_title.'</div>'.'</a>'.'<br />';
endforeach;
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php"
} |
How to display a "NEW"-icon on posts from today
I have a videosite based on wordpress. I would like it to show a icon on the posts from today. I've tried googling it, but without any succes at all. Any ideas on how to do it or maybe someone has a link to a tutorial on it?
Thanks in advance :-) | you can use the difference between the post time (`get_the_time()`) and the current time (`date()`) \-
for instance, this snippet added to functions.php of your theme would add a new css class to `post_class()` if the post is less than 24hrs old:
function post_from_today_class($class) {
//add .new-post-today to post_class() if newer than 24hrs
global $post;
if( date('U') - get_the_time('U', $post->ID) < 24*60*60 ) $class[] = 'new-post-today';
return $class;
}
add_filter('post_class','post_from_today_class');
you can use the `.new-post-today` class to style something differently in your post div.
the core idea is:
if( date('U') - get_the_time('U', $post->ID) < 24*60*60 ) { /*do something*/ };
edit: alternatively, direct in a template with its own php tags, use:
<?php if( date('U') - get_the_time('U', $post->ID) < 24*60*60 ) : ?>text<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts"
} |
Control Category of each user can post
i need to know if has some plugin to control category of each user can post.
Exemple:
USER A - Only can post on the category A
USER B - Only can post on the category B
Thanks for TIPS!!! | I actually have a plugin that does just that, it adds a category dropdown to the user profile edit: !enter image description here
Only user who can `manage_options` (admin) can see that field.
and once the user is logged in to post he sees this:
!enter image description here
**Update** Its now in the plugin repository < enjoy. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users, user roles, user access"
} |
A good heatmapping plugin for WordPress? (No 3rd-party services please)
I am hoping someone in this group can help me. We’re interested in obtaining more information on where people click on the site, ideally in as simple a way as possible. I looked up “heatmaps” on WP, and found some plug-ins, we want to avoid third-party services such as Crazyegg, so “WP Super Heatmap” jumped out (five stars, “simple,” etc.). Anyone have experience with this or other click-map plug-ins? | In the past I have used ClickHeat which has (seemingly third party) plugin for it in repository, but I just integrated it manually. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins"
} |
Show Custom Message in Wordpress Admin
I have a custom post type called "Films" that is used to manage an entire film collection. I would like to create a custom box with a message that will sit on top of all of the posts when you click on the Films button in the wordpress admin area. Currently (and by default) there is no messaging, just an index of all the posts in this post type. I want a box to appear above all of the posts with my message.
The purpose of the box is to give admins of the site some direction on how to populate the films section. Any idea how I could go about this in wordpress? It is important to note that this message box should ONLY appear on the films custom post type, not on the dashboard or anywhere else. | add_action('admin_notices', 'my_custom_notice');
function my_custom_notice()
{
global $current_screen;
if ( 'my_post_type' == $current_screen->post_type )
{
echo "<h1>Whatever needs to be said</h1>";
}
}
Put this in your functions.php or plugin file. Replace 'my_post_type' with the name of your post type. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, functions"
} |
PageLines theme: how to change the background color of the main content vs. entire page?
I use PageLines free version, with WordPress 3.3.1, for this website: <
**I want the background color of the whole page to be light green, and the background color of my content area to be white**.
* I configure the **Page Background Color** in the PageLines settings, which affects the whole page. Whereas **Body Background Color** affects what they call the "Page content areas" like the footer.
* But I don't find the setting to change the background of a page body, is it even available in PageLines?
I hope I don't have to go into the CSS files for such a simple thing, but if I do, I appreciate any suggestions regarding which CSS file to modify and which properties to change/add. Thank you! | Looking at your code, this is a very very VERY bloated theme. Seriously, there's no reason a page that simple should take over 4 seconds to fully load. In addition to the "way too many nested DIV's" issue, areas above and below the header menu span the entire page, so you can't actually change just that section of the header to white background.
From the looks of things, this theme creates its CSS dynamically on page load, so chances are it's going to be a hassle to fix. I would really recommend you find a different theme that's easier to CSS edit, because any time you want to change something that's not in the "Theme Options" you're going to run into issues.
I know this isn't the answer you were hoping for, but you've kinda backed yourself into a corner with your theme choice. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "css, theme options, design"
} |
Keep requested/entered url with add_rewrite_rule
I've got url-rewriting partially working. I have this rule:
add_rewrite_rule('^somepage/([^/]*)/([^/]*)/([^/]*)/?','index.php?p=27&target=$matches[1]&arrival=$matches[2]&departure=$matches[3]','top');
When I request a page like this:
The Visitor gets redirected to:
But I'd like to keep the additional parameters of the original url. How can I achieve this?
And I noticed something else. When I generate a link like above from a form via JavaScript I get "page not found" although the url is correct. Now when I refresh that same page I get redirected to the page mentioned above. Why isn't it working on the first try?
I'd appreciate any help.
Kind regards, Denyo | Okay I figured it out. Instead of using this rewrite rule:
add_rewrite_rule('^somepage/([^/]*)/([^/]*)/([^/]*)/?','index.php?p=27&target=$matches[1]&arrival=$matches[2]&departure=$matches[3]','top');
I now use this one:
add_rewrite_rule('^somepage/([^/]*)/([^/]*)/([^/]*)/?','index.php?pagename=somepage&target=$matches[1]&arrival=$matches[2]&departure=$matches[3]','top');
And now everything works like I wanted it to. Obviously using the page id instead of the page name was the problem. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "url rewriting, rewrite rules"
} |
formatting horizontal and vertical images in Settings?
I have several custom media sizes we always use.
vertical: 95x117, 130x160 horizontal: 440x304, 220x152 home: 260x160
Is there anyway to set the thumbnail, medium and large to vertical parameters and horizontal ones? Or is it better to leave the defaults (150x150, 300, 1024) so that I can set the sizes using width and height parameters as needed?
Thanks! Donna | I would **not** alter the core intermediate image sizes. If you have custom image sizes, register them using `add_image_size()`. e.g.
function mytheme_add_custom_image_sizes() {
// Add "vertical" image
add_image_size( 'vertical-a', 95, 117, true );
add_image_size( 'vertical-b', 130, 160, true );
// Add "horizontal" image
add_image_size( 'horizontal-a', 440, 304, true );
add_image_size( 'horizontal-b', 220, 152, true );
// Add "home" image
add_image_size( 'home', 260, 160, true )
}
add_action( 'after_setup_theme', 'mytheme_add_custom_image_sizes' );
Now, your registered custom image sizes can be used in any of the core image-related functions, to return the image in one of your custom sizes. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "media, options"
} |
Twenty ten or Twenty eleven as base for responsive child theme
I'm about to make a new child theme and really would like to learn a bit about making it responsive. The design/changes will be rather small.
I've done some child themes for both Twenty ten and Twenty eleven but not sure which one to choose for trying to learn responsive design. You could argue Twenty eleven is the latest but I've read somewhere Twenty ten is better maintained.
I know there are many barebones/frameworks, but these two I know quite well.
Any thoughts on this? | Both Twenty Ten and Twenty Eleven are being maintained, since both are still bundled with core. However, Twenty Eleven has newer functionality, and a better overall codebase.
I would recommend using Twenty Eleven. The only reason to use Twenty Ten, really, is that the codebase is considerably more simple.
Note: when Twenty Twelve comes out, I would recommend using it. It will focus more on simplicity, and will have some responsiveness baked in. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "child theme, theme twenty eleven, theme twenty ten, responsive"
} |
How do I load a CSS style into WordPress admin area only?
I'm trying to load a CSS file for my WordPress post area, but having no luck. I have read over the wp_enqueue_style function and came up with the code below, but it doesn't load up. Is there a tag or character missing from my code. I have a custom write panel when a user post that I want to style with the CSS file. Any help would be great.
Here is what I have in my themes `functions.php` file:
function mytheme_add_init() {
$file_dir=get_bloginfo('template_directory');
wp_enqueue_style("functions", $file_dir."/scripts/custom.css", false, "1.0", "all");
wp_enqueue_script("rm_script", $file_dir."/scripts/custom.js", false, "1.0");
} | Just hook your callback into `admin_print_styles`, i.e.:
add_action( 'admin_print_styles', 'mytheme_add_init' );
Alternately, you could add an `is_admin()` conditional wrapper inside your callback, and hook into `wp_enqueue_scripts`:
function mytheme_add_init() {
if ( is_admin() ) {
$file_dir=get_bloginfo('template_directory');
wp_enqueue_style("functions", $file_dir."/scripts/custom.css", false, "1.0", "all");
wp_enqueue_script("rm_script", $file_dir."/scripts/custom.js", false, "1.0");
}
}
add_action( 'wp_enqueue_scripts', 'mytheme_add_init' );
But the absolute _best_ approach is to **hook into your Theme's admin page** , via `admin_print_styles-appearance_page_{pagename}`:
add_action( 'admin_print_styles-appearance_page_{pagename}', 'mytheme_add_init', 11 );
This is a custom hook _specifically_ for your appearance page, as defined via your `add_theme_page()` call. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 7,
"tags": "admin, css"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.