question
stringlengths 0
34.8k
| answer
stringlengths 0
28.3k
| title
stringlengths 7
150
| forum_tag
stringclasses 12
values |
---|---|---|---|
What action or filter do I have to check or compare against $pagenow? In the admin area, I need to let non admin and editor users only to access: <code> index.php (dashboard) upload.php (attachments management) media.php (attachments management) media-new.php (attachments management) </code> Thanks in advance.
|
that depends on if you want to redirect users away the you should use <code> init </code> hook since no output or headers are sent before that hook. or if you want to display a nice "You Don't have the right permissions to access this page" message then you can use the <code> wp_head </code> action hook: <code> //display meassage add_action('admin_head','my_restrict_access'); function my_restrict_access_meassage(){ global $pagenow; if ($pagenow == 'upload.php' && !current_user_can( 'upload_files' )){ echo '<div class="wrap"><br /> <div id="message" class="error">You Dont have the right permissions to access this page</div> </div>'; exit(); } } //or redirect add_action('init','my_restrict_redirect'); function my_restrict_redirect(){ global $pagenow; if (!is_admin()) return ''; if ($pagenow == 'upload.php' && !current_user_can( 'upload_files' )){ wp_redirect( home_url() ); die(); } } </code>
|
Restrict access in wp-admin area?
|
wordpress
|
What is the best practice for adding google conversion tracking code to a specific page?
|
User needs it in his footer so I think you should use conditional page logic . Something like: <code> If ( is_single(postID)) { //insert tracking code } </code> You can also use the post title or post slug, but id is the most reliable. Old Answer I would consider writing a shortcode . Add the following to your functions.php file. You can specify input parameters. In this case I specify id and target. <code> add_shortcode( 'signup', 'signup_shortcode' ); function signup_shortcode( $atts ) { extract( shortcode_atts( array( 'id' => '', 'target' => '', ), $atts ) ); $HTML = 'hello world'.$id; return $HTML; </code> } Then call it in your post like so: <code> [signup id="1234" target="goog"] </code>
|
google conversion code
|
wordpress
|
i have a custom post type name 'business' and taxonomy 'business-category'. now i want to show posts for some specific terms suppost, term1, term2, term3 etc. The following code is working for me but for only one term. <code> $args=array( 'taxonomy' => 'business-category', 'term' => 'term1', 'post_type' => 'business', 'orderby'=> 'rand', ); query_posts($args); </code> I need to pass array of terms. When i try to pass array of terms instead of one term it not working :( <code> $args=array( 'taxonomy' => 'business-category', 'term' => array('term1', 'term2', 'term3'), 'post_type' => 'business', 'orderby'=> 'rand', ); query_posts($args); </code> I also want to know how can i show post if i want to show from multiple taxonomy as well. Thanks! Resolved: the query args will be: <code> $args=array( 'tax_query' => array( array( 'taxonomy' => 'business-category', 'field' => 'slug', 'terms' => array( 'bars', 'restaurants' ) ) ); </code> Thanks!
|
I believe the array will work using terms, rather than term (plural) http://codex.wordpress.org/Function_Reference/WP_Query#Taxonomy_Parameters Has a lot of useful info for mutiple terms/multiple taxonomies but basically look into the tax_query item, specifically AND or OR operators. It's all explained there pretty well
|
Showing posts by collection of specific terms and texonomy
|
wordpress
|
It's been a while since I've done a bounty challenge, so here's another. Same basic rules: 1 answer per person, most creative/useful/helpful/entertaining answer wins. This time around, the award will be 50 reputation points via a stackexchange-url ("Bounty"). This challenge is for my in-development plugin, Crossfire . Plugin Purpose Allows authors of multiple sites on a multisite network to cross-post their content from one site to another. How it Works Authors write a post as usual on the primary site. Then they select the sites to cross-post from a meta box. WordPress uses a custom post type to keep track of the cross-posted content on the sister sites. Endgame Visitors to both the main site and the sister sites will see the new post at the top of the page. Comments on one site are automatically mirrored to all the others. Feed subscribers will only see the new post in the original site's feed. As I said, the plugin will be called Crossfire , but I need a creative name for the custom post type used on sister sites (where the post content is imported). Calling them "posts" isn't accurate since they won't show up in the site's feed. So, give me your best ideas and the best of the best will be awarded 50 reputation points! Contest ends Friday, April 23 at 19:00 UTC (12:00 Pacific).
|
Ricochet After all, this custom post type is kind of rebounding off one network site to another. Plus it's a bit of a play on words based on your plugin's name.
|
The Great Plugin Nomenclature Contest of 2011
|
wordpress
|
I'm trying to create a plugin that alters the Add New Post page so the Visibility field says "Private" by default: <code> Status: Draft Visibility: **Private** Publish immediately [Publish] </code> ...as opposed to what WordPress normally assumes: <code> Status: Draft Visibility: **Public** Publish immediately [Publish] </code> At the moment, I'm using the "wp_insert_post_data" filter, and that is allowing me to change any posts with a post_status of "auto-draft" to "private". While this works, there is an unintended side-effect: Changing the post_status to "private" seems to publish the post automatically, changing the button in the editor to "Update". Furthermore, if the user saves before specifying a title, the post will be published with the title "Auto-Draft". Is there any way I can simply change Visibility to Private by the default, in a manner that doesn't auto-publish the post, and change the button to "Update"? In vanilla WordPress, users can manually change the visibility to Private, and the button remains as Publish... I just need to achieve that via a plugin. I also want to ensure that "public" can still be selected by the user, should they desire to. Thanks!
|
since you're developing a plug-in, I assume you don't want to touch any files outside of wp-content/plugins or ../themes for that matter. However, if that's not the case, follow along: Go to wp-admin/includes/meta-boxes.php and find: <code> $visibility = 'public'; $visibility_trans = __('Public'); </code> Now change it to the obvious: <code> $visibility = 'private'; $visibility_trans = __('Private'); </code> Again, this affects the meta-boxes.php file which is outside of the plugins folder. Nonetheless, I think the approach you should be taking is creating a new meta box, adding your custom visibility setting (i.e. private) and make the latter override the default WP visibility setting . Best, Chris
|
How can I make it so the Add New Post page has Visibility set to Private by default?
|
wordpress
|
Hey Guys, I'm trying to build a right aligned, wrapping capable wp_nav_menu powered menu. Is there a way to have it rendered backwards, so that float: right; would work and not mess up the order? I was hoping for something like this: <code> <?php wp_nav_menu( array('sort_order' => 'DESC' )); ?> </code> Thanks!
|
I just found this handy little function that ads the ability to reverse the menu output order. it might come in handy: <code> /** * Enables a 'reverse' option for wp_nav_menu to reverse the order of menu * items. Usage: * * wp_nav_menu(array('reverse' => TRUE, ...)); */ function my_reverse_nav_menu($menu, $args) { if (isset($args->reverse) && $args->reverse) { return array_reverse($menu); } return $menu; } add_filter('wp_nav_menu_objects', 'my_reverse_nav_menu', 10, 2); </code> All you need to do is ad <code> 'reverse' => true </code> as one of the wp_nav_menu parameters. :) this is the source: https://gist.github.com/1291914
|
wp_nav_menu sort order?
|
wordpress
|
Using BP theres a way to: <code> 1. On login redirect to member profile. 2. On logout redirect to facebook.com </code> Thanks in advance.
|
heres how you login to the profile page. <code> /*Add a filter to filter the redirect url for login*/ add_filter("login_redirect","bpdev_redirect_to_profile",100,3); function bpdev_redirect_to_profile($redirect_to_calculated,$redirect_url_specified,$user) { /*if no redirect was specified,let us think ,user wants to be in wp-dashboard*/ if(empty($redirect_to_calculated)) $redirect_to_calculated=admin_url(); /*if the user is not site admin,redirect to his/her profile*/ if(!is_site_admin($user->user_login)) return bp_core_get_user_domain($user->ID); else return $redirect_to_calculated; /*if site admin or not logged in,do not do anything much*/ } </code> and heres to logout to facebook <code> add_filter('allowed_redirect_hosts','allow_ms_parent_redirect'); function allow_ms_parent_redirect($allowed) { $allowed[] = 'facebook.com'; return $allowed; } <a href="<?php echo wp_logout_url( 'http://facebook.com' ); ?>" title="Logout">Logout</a> </code>
|
BuddyPress - Redirects on Login and Logout
|
wordpress
|
I am using WordPress Custom Menus . I have links like Home - Rendered using <code> home.php </code> Blog - Rendered using <code> page-blog.php </code> with <code> WP_Query </code> to get blog posts Services - Page Portfolio - Rendered using <code> page-portfolio.php </code> to get all posts of the Custom Post Type "Portfolio" Contact - Page I will like to determine which link is current and style them. How will I do that? WordPress wont know which is selected when I am in a simple blog post for example <code> single.php </code>
|
for category: li.current-category-ancestor li.current-cat for menu: li.current-menu-item for page: li.current_page_item li.current-page-ancestor for post: li.current-post-ancestor For more details: http://codex.wordpress.org/Dynamic_Menu_Highlighting
|
Determining the "current_page" in WordPress Custom Menus
|
wordpress
|
I read that you can use session_start() in config.php, but that it is not recommended. I have a form where a user fills out their name and submits. On confirmation of the submission they land on a new page that says 'Thank-you First Last.' What is the preferred way of passing this information from page1 on to page2?
|
I would recommend using <code> $_GET </code> or <code> $_POST </code> variables ... the same way you submit the form. This has nothing to do with session. Basically, when the user fills out the form, you're populating <code> $_POST </code> with information. When the user submits the form, you process the information in <code> $_POST </code> and display a thank you page ... you'll have access to the first and last name at this time.
|
Can you keep session data for visitors?
|
wordpress
|
I'm wondering how to do make a multi-site network with wordpress. The best example I have is the cheezburger network.
|
http://codex.wordpress.org/Create_A_Network Have you looked through the basics? You can set up subdomains, site.domain.com or subdirectories domain.com/site Or you can even route domains to the sub sites. Check out that stuff first, as multisite is built in to WP since 3.0 If you had more specific questions you maybe rephrase your question?
|
How do I create a multi site network?
|
wordpress
|
I've got page with metabox called "something". It can have two values "value" and "value2". I'm using a shortcode at this page and want it to display something's value. The problem is I don't know how to access global variable in a shortcode? Example, I have this in page.php: <code> if($something == "value") { global $one, $two; $one = 120; $two = 240; } </code> Now I want to access these variables in my shortocde (functions.php file), but <code> echo $one; echo $two; </code> Gives no output. Any ideas?
|
Meta data is save in postmeta table and to get them you can use <code> get_post_meta($post_id,'meta_key_name',true); </code> so in your shortcode function globilaize $post object and get you value like that <code> if($something == "value") { global $post; $one = get_post_meta($post->ID,'value_name'true); $two = get_post_meta($post->ID,'value2_name'true); } </code>
|
Wordpress global variables?
|
wordpress
|
One of the sites I currently maintain have approximately 2000 individual pages, broken down into departments and other such categories. Some of these pages contain "dynamic" content, such as a list of documents that are updated or added to on a monthly basis. We're thinking of migrating to WordPress for this site, but I'm trying to track down a list of sites that are serving the capacity of documents/information that we currently are to see how they do it, and maybe look at any plugins/themes they are running. Is there a list or does anybody know of sites at that capacity?
|
Just take a look here: http://vip.wordpress.com/clients/ http://wordpress.org/showcase/
|
What are examples of large sites running WordPress?
|
wordpress
|
I wonder if its a good idea to use <code> add_image_size </code> or is it just a convinence feature. I say this as I think <code> add_image_size </code> creates images of various sizes regardless of what the usage if the image maybe eg. I may want a thumbnail of 500x200 in my portfolio pages only. but WordPress will create images of 500x200 for all images I upload right? If I have a bunch of <code> add_image_size </code> , it will clutter up my uploads with useless images I will never use? Is there a better solution? Resize before upload, maybe alittle troublesome?
|
For image formats that are only used for a small fraction of the images, I suggest using an on-the-fly image resizer. Preferrably one that caches the images so that you only have to resize them once. I use TimThumb for a number of projects, and it's been good enough for me.
|
add_image_size creating lots of images (of various sizes)
|
wordpress
|
I am having a problem where my markup is rendered incorrectly (more space because of <code> <br /> </code> ) as WordPress adds <code> <br /> </code> everywhere theres a line break eg. <code> [x] [y]Hello world[/y] [y]A test[/y] [/x] </code> In the handler for <code> x </code> the <code> $content </code> looks like <code> <br /> [y]Hello world[/y] <br /> [y]A test[/y] <br /> </code> Am I suppose to strip out all the line breaks? UPDATE I notice that no line breaks <code> [x][y]Photoshop[/y][y]Notepad++[/y][/x] </code> <code> [y]Notepad++[/y] </code> will not be rendered as a shortcode. I must have a space like <code> [x][y]Photoshop[/y] [y]Notepad++[/y][/x] ^ </code> Isit?
|
before you register your shortcode, add the filter to the content for unautop: <code> add_filter( 'the_content', 'shortcode_unautop' ); </code> Do this also for the areas, maybe excerpt or widget, when your shortcode add to this areas.
|
WordPress adds br in between my shortcode
|
wordpress
|
I have different widget areas. One is a horizontal area that may contain eg. 4 widgets next to each other. My Question is how would i add a different eg. <code> $param['widget_title'] </code> to widget number <code> $n </code> (via a filter)? I already tried using <code> wp_registered_widgets(); </code> function and te different globals, but with no result.
|
The <code> dynamic_sidebar_params </code> filter is called before each widget is displayed, so multiple times in the same sidebar. It filters the <code> $args </code> and <code> $instance </code> parameters that will be passed to the widget. If you only want to execute it for the third widget of a specific sidebar, you should check for the sidebar ID (found in the <code> id </code> value of the <code> $args </code> array, which is passed first), and then count the widgets until you arrive at n . There are different ways to do this: you can get all widgets of the current sidebar and compare the ID of the n -th with the one you are filtering now, or you can just count it in your filter, resetting the count when you get a new sidebar name. Or you could replace <code> dynamic_sidebar() </code> in your template with a call to a function of your own that will first reset the widget count and then start filtering. This is an example of the second type: counting widgets in the function, resetting the count each time we start a new sidebar: <code> add_filter( 'dynamic_sidebar_params', 'wpse15024_dynamic_sidebar_params' ); function wpse15024_dynamic_sidebar_params( $params ) { // These are the targets. Modify them here: $targeted_sidebar = 'sidebar-bottom'; $targeted_widget = (int) 3; static $widget_counter = array(); static $current_sidebar = null; $args = $params[0]; $instance = $params[1]; if ( $current_sidebar != $args['id'] ) { $current_sidebar = $args['id']; $widget_counter[$current_sidebar] = 0; } if ( $current_sidebar == $targeted_sidebar && $widget_counter[$current_sidebar] == $targeted_widget ) { $args['before_widget'] = '<div id="'.@$args['widget_id'].'" class="span-6 last">'; } $widget_counter[$current_sidebar]++; return array( $args, $instance ); } </code>
|
Widget Area: Modify $param['xy'] from widget-$n
|
wordpress
|
I want a separate production and test/dev instance. Is it possible to have two installs of wordpress multi on the same server, using different databases or do I need 2 servers, one for test and one for production? I want to have a test instance where I can try out plugins, setting changes etc, without affecting my production instance
|
Yes, it's possible to have 2 WP MultiSite installs on the same server - just treat them as 2 separate virtual hosts, put the WP files in separate folders and use separate databases (although you can use the same database server)
|
muliple wordpress multisite installs on the same sever
|
wordpress
|
I'm trying to create a custom comments page with pagination. I have non-hierarchical custom type "apartments". It makes urls like: <code> /apartments/ - for acrhive /apartments/%id%/ - for post page /apartments/%id%/comments-page-X/ - for comments (X is some number) </code> How do I create page <code> /apartments/%id%/questions/ </code> for comments? And remove <code> /apartments/%id%/comments-page-X/ </code> if possible. I would like to make this url structure for comments: <code> /apartments/%id%/questions/ - first page of the comments /apartments/%id%/questions/page/X/ - pagination for comments (X is some number) </code> What is the solution?
|
<code> $args = array('post_id'=>get_the_ID(), 'status'=> 'approve'); $all_comm = get_comments($args); $per_page = get_option("comments_per_page"); if(!$per_page) $per_page = 4; $cpage = get_query_var("cpage"); if(!$cpage) $cpage = 1; if(round(count($all_comm)/$per_page) == 0) $total = 1; else $total = round(count($all_comm)/$per_page); $args_comments = array( 'base' => add_query_arg( 'cpage', '%#%' ), 'format' => "", 'total' => $total, 'current' => $cpage, 'echo' => false, 'add_fragment' => '#reviews' ); $pagi_comments = paginate_comments_links($args_comments); $args = array('post_id'=>get_the_ID(), 'status'=> 'approve', 'number' => $per_page, 'offset' => $per_page*($cpage-1)); $all_comm = get_comments($args); if($all_comm) foreach($all_comm as $as){ print_r($as); } echo $pagi_comments; </code> I hope it helps lot to you.
|
Custom comments
|
wordpress
|
I used a plug in to retrieve all the post from a category. The post is displayed in an unordered list <code> <ul><li> </code> and everything if fine, even the <code> <a> </code> tags to the post. Now, for more usefulness (it's a word?), I would like, on hover of the link, to display the first image of the nextgen gallery found in this post. I do not have enough know-how to retro engineer the ngg plugin, but there should be a way to get, let's say the thumbnail of a post and set it as a tooltip.
|
I just forget the idea. Doing it with NGG is way too complicated. I am looking for a different solution. Magic gallery (PRO) look good to me
|
Retreive post thumbnail and display it as tooltip on hover?
|
wordpress
|
How to add a logout option to the main nav menu (not to the top bar) in BuddyPress?
|
Google is your friend . Here is a snippit I found I didn't test it but seems logical. <code> // functions.php function add_login_logout_link($items, $args) { if(is_user_logged_in()) { $newitems = '<li><a title="Logout" href="'. wp_logout_url('index.php') .'">Logout</a></li>'; $newitems .= $items; } else { $newitems = '<li><a title="Login" href="'. wp_login_url('index.php') .'">Login</a></li>'; $newitems .= $items; } return $newitems; } add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2); </code> Source
|
BuddyPress - How to add logout in nav menu
|
wordpress
|
hey guys, didn't know that, but the attachement page (i'm using attachment.php as template) is actually looping through ALL ever uploaded attachments to my blog! I just want to use it in order to view the images of a gallery etc. So I just want to loop through the images that are specific to the current post. Any idea how to solve that? attachment.php <code> <div class="posts-container"> <?php get_template_part( 'loop', 'attachment' ); ?> </div> <!-- posts-container --> </code> loop-attachment.php <code> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <article <?php post_class() ?> id="post-<?php the_ID(); ?>"> <div class="entry"> <div class="entry-attachment"> <?php if ( wp_attachment_is_image() ) : $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) ); foreach ( $attachments as $k => $attachment ) { if ( $attachment->ID == $post->ID ) break; } $k++; // If there is more than 1 image attachment in a gallery if ( count( $attachments ) > 1 ) { if ( isset( $attachments[ $k ] ) ) // get the URL of the next image attachment $next_attachment_url = get_attachment_link( $attachments[ $k ]->ID ); else // or get the URL of the first image attachment $next_attachment_url = get_attachment_link( $attachments[ 0 ]->ID ); } else { // or, if there's only 1 image attachment, get the URL of the image $next_attachment_url = wp_get_attachment_url(); } ?> <div class="attachment"> <!-- <a href="<?php echo $next_attachment_url; ?>" title="<?php echo esc_attr( get_the_title() ); ?>" rel="attachment"> --> <?php $attachment_width = apply_filters( 'attachment_width', 1068 ); $attachment_height = apply_filters( 'attachment_height', 1068 ); echo wp_get_attachment_image( $post->ID, array( $attachment_width, $attachment_height ) ); // filterable image width with, essentially, no limit for image height. ?> <!-- </a> --> <div class="nav-previous"> <?php previous_image_link( false, '&nbsp;' ); ?> </div> <div class="nav-next"> <?php next_image_link( false, '&nbsp;' ); ?> </div> </div> <?php endif; ?> </div><!-- .entry-attachment --> <div class="entry-caption"> <?php if ( !empty( $post->post_excerpt ) ) the_excerpt(); ?> </div> </div><!-- entry --> </article><!-- post --> <?php //comments_template(); ?> <?php endwhile; // end of the loop. ?> </code>
|
The <code> attachment.php </code> is a specific template in the WordPress template hierarchy . WordPress uses it for a specific purpose, and the default Loop just won't do what you're claiming it's doing. (The behavior you're describing would be analogous to the <code> single.php </code> template file looping through all Posts.) I'm guessing your <code> attachment.php </code> template file has a custom Loop. As Baiternet asked above, can you post or link the markup of your <code> attachment.php </code> template file?
|
attachment page template? only show attachments for current post?
|
wordpress
|
I guess the title of this question is not clear. I'm asking for a plugin, which only superadmins can use, that shows which (or, at least, how many) blogs use each plugin installed on the network. I've searched a lot for this, but found nothing. Is anybody who knows any such plugin?
|
You mean something like: Active Plugins which is a plugin that Generates a list of plugins that are currently in use and Does not include primary blog, network activated plugins, or plugins with 0 users.
|
Plugin to list active plugins across networked sites
|
wordpress
|
Basically, I want to show non-logged in users a page that says 'register or log in.' But I want to show logged in users a standard homepage will all my posts.
|
Rarst's solution is indeed the simplest way to do it and the Members plugin also has heaps of other advantages. You can also do it without a plugin, by using the is_user_logged_in() function More info on http://codex.wordpress.org/Function_Reference/is_user_logged_in and http://codex.wordpress.org/Function_Reference/get_currentuserinfo#Parameters
|
How do I show a different homepage to logged in and non-logged in users?
|
wordpress
|
I'm currently developing some plugins. Due to the fact that they should also be available via the wp.org plugin repo, i need to license them properly. My decision so far is to use a modified MIT/Expat license, which is compatible to the GNU GPL license. I modified/extended the license in two places (bold quote parts). I now would like to know if This could conflict with the GNU GPL license. The grammar, vocabulary and else is correct. (c) Copyright 2011 - by ... me Area of jurisdication: Austria. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice, and every other copyright notice found in this software, and all the attributions in every file, and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. I'm aware that none of you is a lawyer, so it's more about your opinion. If you got additions (of any kind), feel free to tell me. Thank you! EDIT: So far I got to the point that I can't write anything about "legal content" and the area of jurisdication says nothing about any right restrictions and therefore is ok & non conflicting with the GPL. About "and every other copyright notice" does not conflict, because it's no restriction. It's (in my case) mostly about css & graphics.
|
A popular choice is the Duel license BOTH GPL AND (non-modified) MIT. The non-modified MIT license is on the list of Compatible licenses though (See:Expat License) Area of jurisdiction: Austria. This is interesting to me, I'm not sure that line violates any license but to me part of Open Source is just giving up some rights. and every other copyright notice found in this software, and all the attributions in every file, Copyright in the source code is protected however, requiring public copyright notices violates both licenses. The Software may be used to publish and/or display legal content. This is implied with the MIT/GPL as you aren't limited in what you can do with the software so there should be no need to state that they can use it for legal content
|
extended MIT license
|
wordpress
|
More of an open discussion than a question, really, because I know adding custom arguments to the post type object does work, but I'm wondering if it is technically wrong in any way. Basically, when registering a post type: <code> $labels = array( 'name' => _x('Drews', 'post type general name'), 'singular_name' => _x('Drew', 'post type singular name'), 'add_new' => __('Add New'), 'add_new_item' => __('Add New Item'), 'edit_item' => __('Edit Item'), 'new_item' => __('New Item'), 'view_item' => __('View Item'), 'search_items' => __('Search Items'), 'not_found' => __('No Items found'), 'not_found_in_trash' => __('No Items found in Trash'), 'menu_name' => 'Archives' ); $rewrite = array( 'slug' => 'drews' ); $args = array( 'labels' => $labels, 'public' => true, 'show_in_menu' => true, 'query_var' => 'drews', 'rewrite' => $rewrite, 'has_archive' => true, 'hierarchical' => false, 'supports' => array('title','editor','author','comments'), '_drew_made_this' => true ); register_post_type('drews',$args); </code> Make note of the very last line in my $args array, '_drew_made_this' set to 'true'. This allows me to condition against this in several useful ways, sort of how you would filter against '_builtin' when using get_post_types(). Like I said, I know this works because I'm using it, but is there any potential for this to break WordPress in any weird way.
|
You can add as many arguments as you want to the <code> register_post_type() </code> $args as they are all save in <code> $wp_post_types </code> global in an array (ex: $wp_post_types[type] = $args), but i'm not sure if that is the best way to go since this could easily be changed in the future and then your functions will break, a better way to go would be to create your own option in the options table and use that, what i mean is that you could use <code> get_post_types() </code> and save them as an array in a type => $args manner and that way you are not depending on the core functionality to stay in the current state. Hope this makes scene.
|
Is it a good practice to include custom options when registering a post type?
|
wordpress
|
I'm trying to redirect to a specific post based on a GET parameter. The value of the GET parameter is the value of a specific custom field. For example: http://somedomain.com/wordpress/?fid=xyzzy I have this working when a post matches. But, it's not working properly when there is no match. <code> add_filter('query_vars', 'fid_query_vars'); function fid_query_vars($vars) { // add fid to the valid list of variables $new_vars = array('fid'); $vars = $new_vars + $vars; return $vars; } </code> and <code> add_action('parse_request', 'fid_parse_request'); function fid_parse_request($wp) { // only process requests with "fid" if (array_key_exists('fid', $wp->query_vars) && $wp->query_vars['fid'] != '') { $args = array('post_type' => 'faculty_profile', 'meta_key' => 'wid', 'meta_value' => $wp->query_vars['fid'] , 'numberposts' => 1); $redirect_to_post = get_posts($args); if (!empty($redirect_to_post ) ) { foreach ($redirect_to_post as $p) { $link = get_permalink($p->ID); wp_redirect( $link , 301 ); exit; } } else { $url = 'http://cnn.com/'; wp_redirect( $url , 404 ); } } </code> I'd expect this to redirect to cnn.com with a 404 error, if there is no match. But, instead, I get the blog's homepage, with a status of 200. Any ideas? thanks.
|
remove the else after the foreach: <code> add_action('parse_request', 'fid_parse_request'); function fid_parse_request($wp) { // only process requests with "fid" if (array_key_exists('fid', $wp->query_vars) && $wp->query_vars['fid'] != '') { $args = array('post_type' => 'faculty_profile', 'meta_key' => 'wid', 'meta_value' => $wp->query_vars['fid'] , 'numberposts' => 1); $redirect_to_post = get_posts($args); if (!empty($redirect_to_post ) ) { foreach ($redirect_to_post as $p) { $link = get_permalink($p->ID); wp_redirect( $link , 301 ); exit; } } $url = 'http://cnn.com/'; wp_redirect( $url , 404 ); exit; }else{ return $wp; } } </code>
|
Redirecting to a post based on a GET parameter and a custom field
|
wordpress
|
If I am pushing a new version (v0.2) of my plugin (v0.1) on the repo, what does I do with the stable tag in readme file? Change it to v0.2? What should come here? Clarifications please :)
|
Yes. You need to: Change stable tag to 0.2 Commit (or copy/branch) new version to <code> /tags/0.2 </code> Don't forget to update version to 0.2 in plugin's header
|
Stable tag of plugin in the readme file
|
wordpress
|
I'm coding a very complex plugin which it's organized as a parent "container" class and several subclasses, where each subclass is an optional/mandatory element which usually (but not always) maps to his own add_submenu_page. Basically, it's a plugin with his private set of let's call them "subplugins". Every subclass/subplugin has its own (big) set of add_action and add_filter. So, technically speaking, my plugin's subplugin is a valid WP plugin, simply it's not called directly by WP itself. Since i planned...actually tons of add_action...I'm wondering if i should refactor my plugin using a 'private' Observer/Mediator pattern ie. collect all relevant add_actions to my parent class only and baking up a pattern to notify/forward subclasses of events, reducing the impact of my plugin to WP event ques. Is it a good idea or it's absolutely not necesssary? Can u help me with some code for the class refactoring? tnx in advance for help, gabriele
|
I'm wondering if i should refactor my plugin using a 'private' Observer/Mediator pattern ie. collect all relevant add_actions to my parent class only and baking up a pattern to notify/forward subclasses of events, reducing the impact of my plugin to WP event ques. The event queue is fundamental to WP, so it's pretty fast and getting faster all the time. So, I don't think it makes any sense, performance wise, to make your own sub-queues. Refactoring your code so that you don't have to make each add_action() call manually is a different matter.
|
Plugin Architecture/Design Pattern - is better to use a private Observer/Mediator Pattern for plugin subclasses or WP add_action?
|
wordpress
|
I am using the Boldy theme from Site5 on a v3.1.2 site . The way this theme works, is that there is a portfolio, (which I am using as a case studies gallery ) that pulls in posts from a specific category you define under the themes settings (id=98) This is fine if you also set the blog up as per the Boldy instructions, where all blog posts come under a category called blog, but this wasnn't going to give me the slugs I wanted, so stackexchange-url ("I adopted to use a static page") called blog to show my posts on. This all works fine, apart from the fact that the posts I create for my portfolio/case studies gallery (category = case studies) now appear in my blog as well. Is there a way to hide posts within a specific category within the blog, but for it not to have the same affect in my case studies gallery? --EDIT-- With some help from Wyck via the comments, made some progress. Here is a txt version of my themes default index.php file. If I insert the following onto Line 2: <code> <?php query_posts($query_string . '&cat=-98'); ?> </code> = This results in no posts being shown on my Downloads page, but all posts still appearing on my Blog page. I need the vice versa of this. I am sure I am close, but perhaps I need to modify which line I put this on? --EDIT x2-- Now using the download monitor for my downloads gallery. But using the portfolio for my case studies. So some of the links above have changed, but the problem is exactly the same.
|
You want the category 98 to be excluded only on the blog page, right? They should be accessible on the category page directly (your downloads page), correct? Can you try this? Let me know if its not what you want, we can modify it to suit your needs. Right not it only excludes the category on where you show your blog posts. <code> add_action('pre_get_posts', 'block_cat_query' ); function block_cat_query() { global $wp_query; if( is_home() ) { $wp_query->query_vars['cat'] = '-98'; } } </code>
|
Hide Category from Blog?
|
wordpress
|
Theres a way to convert links like: http://www.localhost.lh/?attachment_id=41 into: http://www.localhost.lh/attachment/id or: http://www.localhost.lh/author/attachment/id
|
here a simple WordPress rewrite rule to get the job done: <code> add_action('generate_rewrite_rules', 'attachment_rewrite_rule_14924'); function attachment_rewrite_rule_14924($wp_rewrite){ $new_rules = array(); $new_rules['attachment/(\d*)$'] = 'index.php?attachment_id=$matches[1]'; $wp_rewrite->rules = $new_rules + $wp_rewrite->rules; } </code> just add this code to your theme's functions.php file and save. *note: the index.php is regardless of your existing URL structure.
|
Pretty URLs or permalinks for attachments
|
wordpress
|
I use MathJax to blog my mathematical thoughts. Is it possible to convert my WordPress posts (with plenty of math) into a LaTeX document? The plugin should prompt me to select posts for the paper, and should do the rest automatically.
|
WPTeX allows you to convert your WordPress blog to a LaTeX document. If it does not already contain support for inline LaTeX, it should be really easy to add it.
|
Export blog posts with MathJax to LaTeX document?
|
wordpress
|
Building my first site. Running v3.1.1 with the Boldy theme from Site5. Boldy makes use of prettyPhoto Lightbox. If you refer to the instructions for setting up Boldy (bottom of page) For adding Lightbox behaviour to a link just add rel="prettyPhoto" to the image Link Rel I have just imported about 100 blog posts from Wordpress.com. 2 questions (although very related: How do I batch update all previous pictures to load by default with the prettyPhoto i.e. Apply a 'prettyphoto' tag to each pictures rel. I have about 15 authors for the blog. I know they will forget to manually set this prettyPhoto tag = Is there a way to make it default to this?
|
You can create a <code> content_filter </code> that will update on the fly meaning that you don't have to update all previous pictures and it will be the default so you don't have to worry about your authors. something like this: <code> function autoadd_rel_prettyPhoto($content) { global $post; $pattern = "/(<a(?![^>]*?rel=['\"]prettyPhoto.*)[^>]*?href=['\"][^'\"]+?\.(?:bmp|gif|jpg|jpeg|png)['\"][^\>]*)>/i"; $replacement = '$1 rel="prettyPhoto['.$post->ID.']">'; $content = preg_replace($pattern, $replacement, $content); return $content; } add_filter("the_content","autoadd_rel_prettyPhoto"); </code>
|
Apply a tag to every images 'Link Rel'
|
wordpress
|
I'm running into an issue for a client whereby I keep getting the same error over and over again whilst trying to import an exported file (into an IIS environment): <code> Sorry, there has been an error. The uploaded file could not be moved to D:\www\www514\obtecfoundcom/wp-content/uploads/2011/04. </code> Anybody know what might be going on here (besides the weird slashes)? Thank you! Noel Technical Info http://wl17www502.webland.ch/php5/info.php Attempts so far Googled the hell out of the error, nothing with a real solution. Permissions changed to 777 all the way up to /wp-content/ (recursive) Manually adding the file to ../2011/04
|
Have you verified permissions on the upload_tmp_dir (C:\Temp)? It's possible that the upload is actually failing there rather than in the destination directory.
|
Using the Importer on an IIS Server
|
wordpress
|
It appears that I can only use an ID for the param <code> post_parent </code> whether in <code> WP_Query </code> or <code> get_children </code> Is there a way to query for children via postnames which are more readable.
|
Try using the <code> get_page_by_path() </code> function ( Codex ref ). So, something like: <code> $mypage = get_page_by_path( 'page-slug' ); $mypageid = ( $mypage ? $mypage->ID : '0' ); </code> Then, the <code> post_parent </code> argument becomes: <code> 'post_parent' => $mypageid </code>
|
How to query children by post name/slug
|
wordpress
|
I have a site that has a few custom post types. When a customer searches it shows a combination of all the different posts. I'd like to segment the two on the same page resulting in something that looks like the example below. Any help would be appreciated. Showing results for: really cool search Video Management from a central location. Radius offers interactive map capability, and multiple monitor support. Designed for a multiple monitor environmen... http://openeye.net/products/software/video-management Knowledge Base Entries: Repairing your device from a central location. Radius offers interactive map capability, and multiple monitor support. Designed for a multiple monitor environmen... http://openeye.net/?faq=video-management-repair Example of my loop from loop-search.php <code> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h4 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h4> <?php if ( is_archive() || is_search() ) : // Only display excerpts for archives and search. ?> <div class="entry-summary"> <?php the_post_thumbnail; ?> <?php if (function_exists('relevanssi_the_excerpt')) { relevanssi_the_excerpt(); }; ?> <a href="<?php the_permalink(); ?>"><?php the_permalink(); ?></a> </div><!-- .entry-summary --> <?php else : ?> <div class="entry-content"> <?php the_post_thumbnail; ?> <?php the_content( __( 'Continue reading', 'twentyten' ) ); ?> <?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?> <a href="<?php the_permalink(); ?>"><?php the_permalink(); ?></a> </div><!-- .entry-content --> <?php endif; ?> </code> my changes to search.php <code> <?php if ( have_posts() ) : $posts_per_page = 20; ?> <span style="font-size:18px;" class="page-title"><?php printf( __( 'Showing results for: %s', 'twentyten' ), '<span>' . get_search_query() . '</span>' ); ?></span> <?php /* Run the loop for the search to output the results. * If you want to overload this in a child theme then include a file * called loop-search.php and that will be used instead. */ get_template_part( 'loop', 'search' ); ?> <?php else : ?> <div id="post-0" class="post no-results not-found"> <h2 class="entry-title"><?php _e( 'Nothing Found', 'twentyten' ); ?></h2> <div class="entry-content"> <?php if (function_exists('relevanssi_didyoumean')) { relevanssi_didyoumean(get_search_query(), "<p>Sorry, but nothing matched your search criteria. Please try again with some different keywords. Or you can also try ", "</p>", 5); }?> <?php related_searches(); ?> </div><!-- .entry-content --> </div><!-- #post-0 --> <?php endif; ?> </code>
|
You can group posts by type using <code> posts_groupby </code> filter hook: <code> add_filter('posts_groupby', 'group_by_post_type' ); function group_by_post_type( $groupby ) { global $wpdb; if( !is_search() ) { return $groupby; } $mygroupby = "{$wpdb->posts}.post_type"; if( !strlen(trim($groupby))) { // groupby was empty, use ours return $mygroupby; } // wasn't empty, append ours return $groupby . ", " . $mygroupby; } </code> Then in your loop of do something like this: <code> $last_type=""; $typecount = 0; while (have_posts()){ the_post(); if ($last_type != $post->post_type){ $typecount = $typecount + 1; if ($typecount > 1){ echo '</div>'; //close type container } // save the post type. $last_type = $post->post_type; //open type container switch ($post->post_type) { case 'post': echo "<div class=\"post container\"><h2>posts search result</h2>"; break; case 'page': echo "<div class=\"page container\"><h2>pages search result</h2>"; break; case 'custom_type_name': echo "<div class=\"custom container\"><h2>custom post type search result</h2>"; break; //add as many as you need. } } //... // do your loop //... } </code>
|
Seperating Custom Post Search Results
|
wordpress
|
I badly need to create an .XML file inside my theme every time user comes to my site. But I can't. This code in header: <code> <?php $ourFileName = "testFile.txt"; $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file"); fclose($ourFileHandle); ?> </code> Just does nothing. It doesn't display "can't open file", but it doesn't create the file as well. I'm testing it at my /localhost machine and this code works perfectly everywhere there (so file permissions are alright), but not in Wordpress. Why is it happening? :(
|
File system access is tricky thing between different possible server configurations. If you need to implement it reliably in WP you should look into its API for such. See Using the WP_Filesystem .
|
Is fopen() forbidden in WP?
|
wordpress
|
I have a site that has pages being indexed in Google in the form... <code> site.com/?p=1 site.com/?category_name=uncategorized site.com/?author=1 site.com/?m=201103 </code> And since the permalinks of the site have been set to postname since the site was created, I'm trying to determine how these links are being created and where I might be able to find the source file that created the link index. I realize its possible that the site was indexed prior to the permalink update, but just trying to determine if there is a script I'm not aware of that might be accessible to a search engine spider. Any insights?
|
There are two places bots would look: your sitemap (if you submitted one to google), and your robots.txt. WordPress itself doesn't put anything in robots.txt (unless you set your site to private, then it tells the bots not to index anything), nor does it create xml sitemaps that google would use. There are a few plugins that will do this for you, though. I know Google XML Sitemaps is popular, and works for me. Yoast's SEO plugin also creates sitemaps for you. I think the easiest way to get Google to start indexing correctly is to create a sitemap with one of those two plugins and then submit it to google using google webmaster tools.
|
Permalinks set to /%postname%/ but still have links being indexed in the form ?p=x
|
wordpress
|
Wondering if anyone can help. I'm putting together a site which features music reviews, amongst other things. The set up is built on a custom post type and a number of associated taxonomies. Post type: my_albumreviews Taxonomies: artist label release date On a page displaying an album review ( <code> my_albumreviews </code> post type ), under the main content I need a section which shows "Other reviews from this artist" . I think I'm along the right lines with this but just can't get it to work. <code> $artistname = get_the_terms($post->ID, 'artist'); $args = array( 'post_type'=>'my_albumreviews', 'tax_query'=>array(array('taxonomy'=>'artist', 'field'=>'id', 'terms'=> '$artistname' )) ); $artist_reviews = new WP_query($args); </code> This is then followed by.. <code> while ($artist_reviews->have_posts()) : $artist_reviews->the_post(); </code> ..which returns nothing to the page. Any help would be much appreciated.
|
@Frederik , @Bainternet & Otto Thanks for your help, guys. A thousand thanks for your help! The key lied in stripping the taxonomy's slug out of <code> wp_get_post_terms() </code> . Here's my final, fully functioning code: <code> $artist_taxo = wp_get_post_terms( $post->ID, 'artist' ); //Fetch terms from taxonomy 'artist' $artistname = $artistslug[0]->slug; //Pull slug from $artist_taxo into $artistname $args = array( 'post_type' => 'cdx_albumreviews', //Specify custom post name 'numberposts' => -1, //Return all posts 'artist' => $artistname //Taxo 'artist' is equal to $artistname ); $artist_reviews = new wp_query($args); while ($artist_reviews->have_posts()) : $artist_reviews->the_post(); the_title(); endwhile; </code> A massive thanks. Mathew
|
How to pull a number posts from a specific Taxonomy within a Custom Post type
|
wordpress
|
I'm trying to create a versatile Wordpress network . In order to speed up development, I imagine I'll need to channel projects to different themes at an early stage. At the core of my network install I'd like to have three or four themes, pre-configured to handle a specific class of website. What's more, I'd like each of these themes, though configured differently (as far as content-types, page templates, and layouts), to use the same basic functions, markup and general best practices (think html 5 boilerplate). In essence, each of these core themes should be a child theme of some parent that fits my basic technological requirements. The problem is that when it comes time to actually create specific websites, I would like them to each be a child of an appropriate core theme. In essence, I'm running into the problem of granchild themes as brought up in this article: http://justintadlock.com/archives/2010/08/16/frameworks-parent-child-and-grandchild-themes If you're not familiar with it, it argues that a lot of parent themes are wrongly considered frameworks, and that Wordpress is not built to accommodate grandchild themes. So my question is this: Is it better to duplicate a theme (no parent-child relationship) to create my few core themes and deal with updating them manually as needed, or should I have each core theme be a child theme of some parent and create an artificial (not wordpress native) grandchild inheritance system for the actual websites I create. I look forward to hearing your thoughts
|
There are a lot of specific to figure out, but your basic options are to handle it: In runtime. Stuff common core into plugin or just load it from same directory for all core themes. In development. Set up a version control, make a script that will check out common files to all core themes.
|
Grandchild themes and optimal network architecture
|
wordpress
|
I'm developing a website using the WPML plugin. And I would like to know which is the better option, or even the correct way to change classes or IDs between the languages. Sample code: <code> <ul id="<?php _e('menu-topo'); ?>"> <ul id="<?php if ($lang = 'en') { echo "menu-topo-en"; } else { echo "menu-topo"; } ?> </code> I'm not sure that the <code> _e </code> function is supposed to be used this way so if someone could clarify this for me it would help me a lot, thanks.
|
_e() will translate the text passed as a argument to the language your site is currently set up to use (if the translation exists). Anyway, don't do that. Use it for text visible on the website, not for IDs/classes etc. To create context based css rules, simply add the WPML language ID as a body class: <code> add_filter('body_class', 'wpml_body_class'); function wpml_body_class($classes){ return array_push($classes, ICL_LANGUAGE_CODE); } </code> then style the elements you need to using something like: <code> .en .menu-top{ ... } </code> It's faster, and you keep your code easy to maintain.
|
What is better for wordpress performace?
|
wordpress
|
Is it possible to remove a default attachment field from the attachment editor, for example the "Caption" field ? To give you some context, I'm trying to build a custom attachment editor page. I found how to add custom fields , now I'd like to remove some of the default ones I don't need.
|
Use the attachment_fields_to_edit filter to remove the fields you don't want displaying from the array. <code> function remove_caption($fields) { unset($fields['post_excerpt']); // See wp-admin\includes\media.php line 1071 return $fields; } add_filter('attachment_fields_to_edit','remove_caption'); </code>
|
How can I remove fields in the attachment editor?
|
wordpress
|
I am the admin for a blog with around 20 authors contributing articles. Have just migrated from Wordpress.com. The problem that started to happen at WP.com, was different authors would use tags differently. i.e Some would pick just basic tags, others would list out every key word possible. It would appear that for WP roles, all the ones that allow people to submit posts, they can also tag their posts with as many tags as they want. So, my question is - What is best practice for Tag Management for a blog that has multiple authors? - I guess the answer to this could be subjective. But I really need experienced advice on this, and Wordpress-Answers is where I am going to find this. - Happy to convert to Community Wiki?
|
I manage a blog with 3 editors and 8-10 contributors. In my experience, the best way to manage tags is to simply instruct contributors not to add tags to their own articles, and instead have the editors be responsible for tagging articles. You can then work with editors to agree on what the purpose of tags are on for your site and make sure they enforce those policies. I use the Simple Tags plugin for adding tags to articles which replaces the default tag entry system. When you type in a tag, it automatically searches existing tags and displays them in an AJAX-y dropdown display, which is very helpful to avoid dupes and to see what similar tags exist. I hadn't always managed tags so diligently, so I used the Terms Management Tool plugin to merge similar/duplicate tags together. We had a lot of things like "Firefox" and "Mozilla Firefox", so I combined those into a single tag, and Simple Tags helps avoid problems like that in the future.
|
Efficient Tag Management?
|
wordpress
|
I need some help with robots.txt. Under Privacy Settings, I selected "I would like my blog to be visible to everyone, including search engines..." As I understand it, WordPress automatically creates a robots.txt file. But, I need to exclude one page from the automatically generated robots.txt file. Let's say the page is called, "myPage". How do I keep myPage from being indexed? If I make my own static robots.txt will it be overwritten by WordPress' dynamic one? Also, does WordPress' auto-generated robots.txt exclude files like wp-admin, that shouldn't be indexed? Thank you! -Laxmidi
|
you can just make a file in your root named robots.txt if you don't already have one User-agent: * Disallow: /myPage is the format for that one page there is no allow, only disallow. disllowing pages you follow the above format WP may not have generated a robots.txt, I believe it only would have if you wanted your site not indexed I'm not sure if WP has inbuilt mechanism for not indexing your admin stuff....but mine's never been indexed. If you are worried, to block entire directories you add Disallow: /wp-admin/ it's one entry per line/disallow
|
Questions about Robots.txt
|
wordpress
|
I have a hierarchical custom post type (missions) setup. I want to create a few child pages for it (discuss, petition, educate), but I want each of those child pages to display a different template. There does not appear to be a way to use a selected template, like on a normal page, so I thought maybe I could just have the child custom post type pages display content based on their slug. So the permalinks would appear as: <code> /mission/mission-01/ - /mission/mission-01/discuss/ - /mission/mission-01/petition/ - /mission/mission-01/educate/ /mission/mission-02/ - /mission/mission-02/discuss/ - /mission/mission-02/petition/ - /mission/mission-02/educate/ </code> Since they are children, and the Discuss pages could all use the same slug, maybe a function that gives all pages with slug /discuss/ the page-discuss-template.php from my theme directory. Thanks for any help!
|
There are two approaches to my question, that are both useful. They were provided by @goldenapples and @Bainternet. stackexchange-url ("Custom Post Type Data in Sidebar widgets?") stackexchange-url ("How to quickly switch custom post type singular template?")
|
Custom Post Type Template Based on Page Slug?
|
wordpress
|
in the functions.php of a parent theme, I would like to check for wheter the theme is being run directly, or it is run via a child theme. Is there a conventional way of doing this? I cant find the is_childtheme() function I would have liked to have found.. so whats the best way? Check for theme name and compare it to parent theme's maybe? how can this be done?
|
As One Trick Pony said, there's a dedicated function (since WP 3.0): is_child_theme()
|
something like is_childtheme()
|
wordpress
|
I am trying to retrieve all custom post types created by the current user. I have this piece of code: <code> wp_get_current_user(); $args_my_items = array( 'posts_per_page' => 10, 'post_type' => 'mycustomposttype', 'post_author' => $current_user->ID); query_posts($args_my_items); </code> What ends up being returned are all posts of type "mycustomposttype". It does not filter by post_author. Am I using the wrong query parameters? How can I filter by the current user? Thanks.
|
You must specify the <code> author </code> parameter as described here . Try to use: <code> $args_my_items = array( 'posts_per_page' => 10, 'post_type' => 'mycustomposttype', 'author' => $current_user->ID ); query_posts($args_my_items); </code>
|
Retrieve posts by author
|
wordpress
|
Is there a way to count the amount of empty fields of a post (or the fields of a plugin as they relate to the different)? For example, I have 1,500 posts on my site. Each post has important fields (information) needed for the proper functionality and user accessibility (i.e. city, state, zip code, address, etc), but not every post has all of these fields filled out. So what I want to do is know how many posts are missing certain fields. For example, how many posts are missing the city field and so forth. Is there a plugin or a function that can count the amount of fields are missing? I would really appreciate any help or advice with this. This would be very helpful for multiple reasons. Thanks in advance, Gary
|
You can do custom query loop for that particular meta box for an empty value. Something along the lines of <code> $check_city_value = get_post_meta($post->ID, 'city_box'); ?> if (empty($check_city_value)) { echo '$check_city_value is either 0, empty, or not set'; } </code> You would have to loop through all the posts to do this and for multiple meta box checking it might just be better to use a more direct database query using <code> $wpdb </code> , http://codex.wordpress.org/Function_Reference/wpdb_Class
|
Counting post fields
|
wordpress
|
I have to create a hundred of content pages that share the same structure. For example: <code> [Title] - [Subtitle] [Description] [Specs] - [Spec-A] - [Spec-B] - [Spec-C] [Features] - [Image-A][Feature-A] - [Image-A][Feature-B] - [Image-A][Feature-C] </code> I would like to store this information in some DB tables so that if I need to change the template content positions or style, I can do it once for all pages. But unfortunately I am not very good at PHP, so I don't know where to start. Which features of Wordpress or plugins can I use to reach the result? Thank you in advance
|
You might want to consider creating a Custom Post Type for this product (I assume it's some sort of product), and then adding custom metaboxes, that will store the custom data (specs, features, etc.) as metadata for each Post. Then, your custom template file becomes "single-.php" (e.g. "single-product.php"), and you can structure the markup however you need. Storing the custom data (specs, features, etc.) as post metadata allows you to retrieve these data using <code> get_post_meta() </code> ( Codex ref ) or <code> get_post_custom() </code> ( Codex ref ).
|
How to create a page template that retrieves content from db?
|
wordpress
|
I am creating a plugin that resides at http://localhost/test/wp-admin/options-general.php?page=my-plugin I am trying to add a query string to this page so that it can be used in my plugin such as http://localhost/test/wp-admin/options-general.php?page=my-plugin?myVar=cool The problem is that this prompts wordpress to display the "You do not have sufficient permissions to access this page." page. How can I add a query string to my plugin URL? Is this documented someplace? thanks for the help.
|
When you don't know if query string was started or not you can use add_query_arg which it knows how to deal with that and adds the " <code> ? </code> " or " <code> & </code> " marks (which ever one is needed) to the query string. Update By popular demand I'm adding a few examples that are from the codex: Using get_permalink: Since get_permalink() returns a full URL, you could use that when you want to add variables to a post's page. <code> // This would output whatever the URL to post ID 9 is, with 'hello=there' appended with either ? or &, depending on what's needed echo add_query_arg( 'hello', 'there', get_permalink(9) ); </code> more general: Assuming we're at the WordPress URL <code> "http://blog.example.com/client/?s=word"... </code> <code> // This would output '/client/?s=word&foo=bar' echo add_query_arg( 'foo', 'bar' ); // This would output '/client/?s=word&foo=bar&baz=tiny' $arr_params = array ( 'foo' => 'bar', 'baz' => 'tiny' ); echo add_query_arg( $arr_params ); </code> Or for use with any link you have you can pass the link uri: <code> //say your link is: stackexchange-url use: echo add_query_arg( 'hello', 'world','stackexchange-url </code> to get <code> stackexchange-url </code> Example plugin page URL with extra query args: <code> $query_args = array( 'page' => 'your-plugin-page', 'foo' => 'bar' ); echo add_query_arg( $query_args, admin_url( '/options-general.php' ) ) // outputs // http://example.com/wp-admin/options-general.php?page=your-plugin-page&foo=bar </code>
|
Add query string to plugin URL
|
wordpress
|
I really hope I've got a simple issue in front of me here, as it's sort of driving me up a wall. Short story: submitting a simple form on the front end of the site results in a <code> 302 Found </code> redirect, totally stripping the <code> $_POST </code> data in the process. Scenario: Create a page in the admin called Edit Create a custom template file (ie, <code> my-edit-template.php </code> ) and apply it to Edit <code> my-edit-template.php: </code> <code> <?php /** * Template Name: My Edit Template */ if ($_POST['action']) { var_dump($_POST); } get_header(); ?> <form action="" method="post"> <input name="my-ornery-field" value=""> <input type="submit" value="submit"> <input type="hidden" id="action" name="action" value="update-profile"> </form> <?php get_footer(); ?> </code> Now, when I submit the form, I get two requests to the same page, first, the <code> POST </code> , with the form data intact, and second, a <code> GET </code> (status code <code> 200 </code> ), obviously stripped of the <code> $_POST </code> global, or anything useful to me. I'm sure this is a total oversight, but I'm at a loss; utterly confused. I've tried: All plugins disabled Flushing rewrites back to basic defaults <code> POST </code> ing via Javascript/ <code> XHR </code> Help? I'm sorry if the details are sparse, I'm sort of in class right now, but I'll follow-up with anything else relevant, later.
|
There's nothing wrong with that code. I just did it on a local install and it worked fine, exactly how you'd expect. Check for conflicting plugins.
|
Phantom 302 status code when sending a POST requests on pages
|
wordpress
|
I am new to wordpress, and trying to get my head around the idea of sessions and all. I read in a lot of places that session concept is not used in wordpress. Anyway, I downloaded the my-login-theme plugin. My question is, when a user navigates to some secured area, I want to check if that user is logged in or not. Once I check that, I want to get user details like email, and full name. Is this possible in wordpress? Thanks
|
Use the <code> is_user_logged_in() </code> conditional tag ( Codex ref ) to determine if the current user is logged in. Use the <code> get_userdata() </code> function ( Codex ref ) to return user data.
|
determining if the user is logged in
|
wordpress
|
Use case is somewhat simple - here goes: Five people share a single wordpress install - not multi-user Each person blogs and puts their posts in a their own unique category Each person has their own domain name All domain names are pointed or parked to same WP install folder Each person's domain name only shows the posts from their category, i.e. http://blogger1.com would return category archive of Blogger1's posts, http://blogger2.com would return category archive of Blogger2's posts, etc. Google friendly indexing for each domain name Prefer rewrite solution rather than redirect but redirect is acceptable A"master" account would be able to post or edit any of the bloggers posts via the "main" domain login. Bonus - if this could be extended to custom post types Environment One installation of latest version of WP (not multi-user) Pretty Permalinks Cpanel - to set up domain parking No subdomains Access to <code> .htaccess </code> Access to <code> functions.php </code>
|
Hi @aj martin: Here's two different solutions (editing the specifics for your use case) : Doing a Redirect: 1.) At the top of your <code> /wp-config.php </code> file add the following: <code> if ( is_yoursite_blogger_domain( $_SERVER['SERVER_NAME'] ) ) { $domain = str_replace( 'www.', '', $_SERVER['SERVER_NAME'] ); define( 'WP_SITEURL', 'http://' . $domain ); define( 'WP_HOME', 'http://' . $domain ); } else if ( ! is_main_domain( $_SERVER['SERVER_NAME'] ) ) { header( "Location:http://{$yoursite_main_domain}", true, 301 ); exit; } function is_main_domain( $domain ) { $domain = str_replace( 'www.', '', $_SERVER['SERVER_NAME'] ); return strpos( $domain, 'maindomain.com' ) !== false; } function is_yoursite_blogger_domain( $domain ) { $domain = str_replace( 'www.', '', $_SERVER['SERVER_NAME'] ); return in_array( $domain, array( 'blogger1.com', 'blogger2.com', 'blogger3.com', 'blogger4.com', 'blogger5.com', 'uncategorized.dev', // Only here for use on my own test site ) ); } </code> 2.) Then add this to your theme's <code> functions.php </code> file: <code> add_action( 'template_redirect', 'yoursite_template_redirect' ); function yoursite_template_redirect() { $path = $_SERVER['REQUEST_URI']; if (strpos($path,"/category/") === false) { $domain = str_replace( 'www.', '', $_SERVER['SERVER_NAME'] ) ; $category = str_replace( '.com', '', $domain ); $category = str_replace( '.dev', '', $domain ); // Only for my own test site $location = "http://{$domain}/category/{$category}/" ; wp_safe_redirect( $location ); exit; } } } </code> The above will do a 302 redirect to <code> http://blogger1.com/category/blogger1/ </code> when a request is made of any URL <code> http://blogger1.com </code> other than one that starts with <code> http://blogger1.com/category/ </code> (you made need to make some changes to support other URLs.) Doing a "Rewrite": What the above does not support is "rewrite" vs. a "redirect" solution. If you want to that it is a little more complicated. The following code will result in the category page being loaded in the root path for any domain that is mapped in your <code> is_yoursite_blogger_domain() </code> function. Of course your <code> is_yoursite_blogger_domain() </code> function could be validating against existing categories but I don't know the full criteria so I just hard coded it. You can copy this code into your function's <code> theme.php </code> file or put into a <code> .php </code> file of a plugin you might be writing. Note that this code also requires the code in the <code> /wp-config.php </code> file above: <code> add_action( 'category_link', 'yoursite_category_link', 11, 2 ); function yoursite_category_link( $category_link, $category_id ) { // Make sure any blogger category links are truncated to the root $parts = explode( '/', $category_link ); if ( is_yoursite_blogger_domain( $parts[2] ) ) { // if %category% in http://%domain%/category/%category%/ // equals %domain% minus the 'com' extension if ( "{$parts[4]}." == substr( $parts[2], 0, strlen( $parts[4] ) + 1 ) ) { $category_link = "http://{$parts[2]}/"; // Strip 'category/%category%/' } } return $category_link; } add_action( 'init', 'yoursite_init' ); function yoursite_init() { // Remove the canonical redirect to the category page // if %category% in http://%category%.%ext%/ is a blogger category. if ( is_yoursite_blogger_domain( $_SERVER['SERVER_NAME'] ) ) { $parts = explode( '/', strtolower( $_SERVER['REQUEST_URI'] ) ); if (count($parts) > 1) { $category_base = get_option( 'category_base' ); if ( empty( $category_base ) ) $category_base = 'category'; if ( $category_base == $parts[1] ) { remove_filter( 'template_redirect', 'redirect_canonical' ); } } } } add_action( 'template_redirect', 'yoursite_template_redirect' ); function yoursite_template_redirect() { // Redirect any http://%category%.%ext%/category/%category%/ to http://%category%.%ext%/ if ( is_yoursite_blogger_domain( $_SERVER['SERVER_NAME'] ) ) { $category_base = get_option('category_base'); if (empty($category_base)) $category_base = 'category'; $parts = explode( '/', strtolower( $_SERVER['REQUEST_URI'] ) ); if ( $category_base == $parts[1] && "{$parts[2]}." == substr( $_SERVER['SERVER_NAME'], 0, strlen( $parts[2] ) + 1 ) ) { wp_safe_redirect( "http://{$_SERVER['SERVER_NAME']}/", 301 ); exit; } } } add_action( 'request', 'yoursite_request' ); function yoursite_request($query_vars) { // If %category% in http://%category%.%ext%/ is a blogger category set the // 'category_name' query var to tell WordPress to display the category page. $domain = $_SERVER['SERVER_NAME']; if ( is_yoursite_blogger_domain( $domain ) ) { $path = $_SERVER['REQUEST_URI']; if ( strpos( $path, "/category/" ) === false ) { $domain = str_replace( 'www.', '', $domain ) ; $category_name = substr( $domain, 0, strrpos( $domain, '.' ) ); $query_vars = array( 'category_name' => $category_name ); } } return $query_vars; } </code> And here's a screen shot to show the second example in action: Another probably better way to approach this would be with a custom taxonomy instead of categories, or even better yet, map the domain to a user name instead. That way it's less work on the authors and you don't have to worry about maintaining the blogger list in code or in a separate taxonomy list. As for you "bonus" , sorry but I don't follow what you want there.
|
Multiple Domain Names - One WP Install (non-Multisite) - Default Each Domain name to Category Archive
|
wordpress
|
I'm about to migrate from an old Expression Engine website to a new WordPress site on the same domain. Is there anything I should be aware of with respects to redirecting old links? The old site is quite well indexed in Search engines and linked to from other sites, but because the domain name is the same, I'm unsure of how to redirect all those old links in EE to the homepage of my new WP site without having to copy-paste all the existing individual URLs in .htaccess 301 redirects. Any ideas? Thanks, osu
|
Good plugin: http://urbangiraffe.com/plugins/redirection/ You can import CSV files of URLs to redirect, so use the string site:mydomain.com in Google to grab all your indexed URLs, get them into a file and when the WP site is live, import the file and then select the new target WP pages. The plugin has good 404 logging, too.
|
Redirecting all old links from previous EE site to new WP site in one go?
|
wordpress
|
I've some trouble getting nonces working with my ajax submit form. First of all i create a nonce and pass it to my registered script, i'll later send it to ajax-handler packed with my form fields: <code> wp_localize_script( 'roll_script', 'Roll', array( 'postRollNonce' => wp_create_nonce('nonce-roll'))); </code> In my ajax-response handler i verify the nonce, do my stuff and try to create a new nonce to send back to js, for later submit: <code> function on_ajax_roll(){ if (!wp_verify_nonce($_POST['postRollNonce'], 'nonce-roll' )) die ('No allowed!'); // nonce is valid! do some stuff... $r = array('postRollNonce' => wp_create_nonce('nonce-roll')); $response = json_encode($r); header( "Content-Type: application/json" ); echo $response; die(); } </code> ...but, back to my js, the new nonce is exactly the same as the old one! Since nonce is supposed to change with time, why a second call to wp_create_nonce return the same string?
|
By default, the lifetime of a nonce is one day. The nonce is generated by concatenating a variable representing the current day, the user id, and the name of the action, and hashing the resulting string. If you want the nonce value to change more frequently, you can filter the 'nonce_life' value. This function, for example, will force nonces to change every hour: <code> function nonce_hourly() { return 3600; } add_filter( 'nonce_life', 'nonce_hourly' ); </code> But this doesn't sound exactly like what you're trying to do, either. You may have better luck generating the kind of one-time nonces you want by using a different name for the "action" value of the nonce, one that will be truly unique to the specific action you're trying to perform. It looks as though you're using "nonce-roll" as the action name for some distinct actions that you want to be able to check separately — maybe you can use a more specific action name for each action you're trying to perform and authorize.
|
ajax - why multiple calls to wp_create_nonce() return same value?
|
wordpress
|
Situation I got a class where i add a meta box to the post edit screen. EDIT: This is the working version now <code> /** * Calls the class on the post edit screen */ function call_someClass() { return new someClass(); } if ( is_admin() ) add_action( 'load-post.php', 'call_someClass' ); /** * The Class */ class someClass { public function __construct() { add_action( 'add_meta_boxes', array( &$this, 'add_meta_box' ) ); } /** * Adds the meta box container */ public function add_meta_box( /* $args */ ) { add_meta_box( 'post_format_box' ,__( 'Post Format Content', self::LANG ) ,array( &$this, 'render' ) ,'post' ,'advanced' ,'high' ); } /** * Render Meta Box content */ public function render( /* $args */ ) { return '<h1>TEST ME NOW</h1>'; } } </code> Problem The meta box is showing, and the meta box callback functions output get's rendered inside my meta box... but inside an error message. Seems that i'm too tired to get around this: Error Message (exact display as in the meta box) Warning: call_user_func() expects parameter 1 to be a valid callback, function ' TEST ME NOW ' not found or invalid function name in R:\development\xampp\htdocs\wordpress\wp-admin\includes\template.php on line 963
|
Your callback function is wrong implemented <code> add_meta_box( 'post_format_box' ,__( 'Post Format Content', self::LANG ) ,@$this->render() ,'post' ,'advanced' ,'high' ); </code> Should be <code> add_meta_box( 'post_format_box' ,__( 'Post Format Content', self::LANG ) ,array($this, 'render) ,'post' ,'advanced' ,'high' ); </code>
|
meta box & callback function
|
wordpress
|
I'm trying sort through the morass that is WP documentation, and just need someone to clear up the use of the term "The Loop" and how it relates to subloops. My understanding of "The Loop" is that there is, and should only ever be, ONE "The Loop" per page/post - and that The Loop is responsible for iterating through that page/post/archive's content. In particular the_post() will populate a number of global variables with the relevant data extracted from the current position of the query in the main Loop. I also believe I understand that whenever creating a sub-loop (say you want to get a list of all child posts of each post listed in a category archive), you should use a new instance of the WP_Query object, as in: $subQuery = new WP_Query($args); Where I run into confusion with the Codex docs is in the documentation of Wp_Query , specifically $subQuery-> have_posts() and $subQuery-> the_post(). The documentation lists "to be used when in The Loop" for both of those methods, implying (to me) that they manipulate global variables that would affect The (outer) Loop. Is this the case? Or is $subQuery-> have_posts() safe to use (ie: read only)? What about -> the_post()? Does it affect The Loop globals? What's the best practice for iterating through elements of a nested sub-loop that will not interfere with The Loop?
|
First see stackexchange-url ("When should you use WP_Query vs query_posts() vs get_posts()?") My understanding of "The Loop" is that there is, and should only ever be, ONE "The Loop" per page/post - and that The Loop is responsible for iterating through that page/post/archive's content. Yes, it's commonly referred to as "main loop". But "loop" in general can refer to iterating through any set of posts. Or is $subQuery-> have_posts() safe to use (ie: read only)? Yes, it's just a way to check if loop has posts that had not been iterated yet. What about -> the_post()? Does it affect The Loop globals? Yes, it does. After loops that use <code> the_post() </code> (function or method) you need to call <code> wp_reset_postdata() </code> (or more global <code> wp_reset_query() </code> if you was messing with main loop) to cleanup global variables. What's the best practice for iterating through elements of a nested sub-loop that will not interfere with The Loop? This depends if you need to use template tags that rely on global <code> $post </code> , so there are several approaches. You can iterate through new <code> WP_Query </code> object and cleanup afterwards or just fetch array with <code> get_posts() </code> and do something with it.
|
Sub-loop / nested loops Best Practices
|
wordpress
|
On the Reading Settings page you can set a "Front Page" and a "Posts Page". You can check whether the current page <code> is_front_page(); </code> Is there a similar function for the "Posts Page". I have noticed that <code> is_page(); </code> does not work for this special page. Thanks
|
<code> is_home() </code> checks for the "Posts Page", despite the somewhat confusing function name.
|
Determine if page is the Posts Page
|
wordpress
|
In my plugin I'm able to set a cron event like so: <code> wp_schedule_event(time(), 'daily', 'myhookname'); </code> But want I want to do is be able to find out what recurrence I have set for <code> myhookname </code> . The reason why is that I'm offering a setting to allow the recurrence to be changed. What I need to do is check if the recurrence setting has changed from what its currently set as and if so remove the event and reschedule the event with the new recurrence. So if there a function like this: <code> $recurrence = wp_current_event_recurrence('myhookname'); // returns hourly/daily/etc </code>
|
I think I've found it: <code> wp_get_schedule('myhookname') </code> Edit: yes this works as I want it.
|
WordPress Cron how to find out my event recurrence?
|
wordpress
|
OK, it's more a philosophic question that a programming question, but at the end it will have a huge impact on code... I have 5 main product, a,b,c,d,e those 5 products have options those products can belong to multiple category So the end, i should show the product a, with below, option of product a witch is a1, a2, a3, a4 and below, the other products that belong to the same category as a, so it can be, x, y, z. So it look like a a1 a2 a3 a4 x y z How should i manage categories, should i create a category witch name is option for a or there is a better way. Organising is not my stongest point, but good organization can lead to easy coding.. thanks in advance idea, if i can control the ID of the post created, i will create product a as id=100 and all option as product option a1 : id-101. option a2 : id=201 and so on ..
|
I'm pretty sure i missunderstood you... Approach: Categories & Terms (built in taxonomies) You have got categories (hierarchical built in taxonomy) & terms (non-hierarchical built in taxonomy). You can also assign terms to categories. So i'd say, you can take the following approach using the built in taxonomies: shoes (parent category) boots (child category) sneakers (child category) other shoes (default child category) and then use terms inside additional categories like: color (parent cateogry) cyan (term) magenta (term) yellow (term) black (term) laces (parent category) long (term) medium (term) and so on ... This would give you the ability to list all shoes on a category page. Then you can further list all sneakers on one page. You can also list all shoes that got long laces and red color. Templates Take a look at (for eg.) here for more information about the query for different archive (category/term) pages and how to query/retrieve multiple taxonomies at one page.
|
Structure with category setting
|
wordpress
|
I moved from Wordpress.com to my own Wordpress.org hosting. I had no problems importing all my posts over, and the images were all linked up fine. Since the import, I decided to move my WP install from the root of HTML_public, to a new folder called Wordpress. The posts are all still fine, but the picture links are still pointing to: http://www.dekhoforum.com/wp-content/uploads/2010/12/father-christmas-raymond-briggs.jpg When they should be pointing to: http://www.dekhoforum.com/wordpress/wp-content/uploads/2010/12/father-christmas-raymond-briggs.jpg I am assuming I must have missed out a step and should have not been so hasty in moving things around. Is there an easy way to automatically update all pics in all posts to point to the new URLs? i.e. Add the new wordpress folder into each of the link URLs dekho.com.au/blog/
|
Search RegEx is a good plugin to be able to search and replace with Grep through all posts and pages to fix things like broken URLs. And no need to export the DB and use a text editor; that's overkill for simply adding the /wordpress.
|
Moved WP into new folder. How to fix image links in posts?
|
wordpress
|
I want to setup a user account that only has access to moderate comments - for all posts - but doesn't have access to edit any posts. When I give the user the moderate comments privilege (using an old role manager plugin), it doesn't let them moderate comments on other articles. Is there a plugin that does this, or something I'm doing wrong?
|
Probably not the answer you want to hear, but I'm afraid that is not possible as a user needs the edit_posts Capability in order to access the moderate_comments capability. (source: http://codex.wordpress.org/Roles_and_Capabilities#moderate_comments )
|
How Do I Allow Comment Moderation for Other User's Posts?
|
wordpress
|
I am using <code> body_class(); </code> to style different sections of a wordpress site by their body class. Page styles descend from <code> .page-template </code> , blog styles descend from <code> .single-post </code> and/or <code> .blog </code> etc. I have created a custom post type "Products" for the products section of the site and want to style this section specifically using it's body class, but unfortunately <code> body_class(); </code> is also giving the custom post type single pages the class <code> .blog </code> which is making many of the blog styles override the product styles- very frustrating. Is there a way to take the "blog" class away for my custom post type single pages? Thanks!
|
You can use <code> body_class </code> filter to check if you are on your custom post type, and if so then just remove the <code> blog </code> class like this: <code> function remove_blog_from_cpt_classes($classes, $class){ global $post; if ($post->post_type != "products"){ return $classes; }else{ foreach($classes as &$str){ if(strpos($str, "blog") > -1){ $str = ""; } } } return $classes; } add_filter("body_class", "remove_blog_from_cpt_classes", 10, 2); </code> Hope this helps
|
Custom post type and body_class: Remove "blog" class
|
wordpress
|
hey guys, I'm using the sitewide tags Multisite plugin on my wordpress setup. I'm collecting all blogposts of multiple subblogs on my mainblog. Any idea how I could manage to exclude a certain category from this collection? e.g. If a user is writing a blogpost on a subblog and is adding it to the category "private" the mainblog should not show this post! thank you for your help.
|
You may want to encourage users to instead use the 'Post Visibility' option in the main publishing actions box on the post edit screen. Rather than filing private posts in a category, the user can simply set a post to private. Unless by 'private' you mean private to their individual blog but still public...
|
wordpress multisite... collect all posts on main blog - exclude category?
|
wordpress
|
What are the laws concerning developing WordPress sites using other developers' plugins and then selling the sites?
|
Please read through the following: http://codex.wordpress.org/License http://wordpress.org/about/license/ http://en.wikipedia.org/wiki/GPL http://www.gnu.org/licenses/gpl.html You can't can sell it as software or development, although and/or you can also charge for maintanance and install. Anyway, you should at least donate to the plugin developers, if you make money with their work somehow. EDIT I'm am sorry for my previous lines: I have to admit that GPL code can be sold, even if it's not your code , althought I still recommend donating.
|
Selling WordPress sites?
|
wordpress
|
How does one reduce the number of stored revision (e.g. 5 max) for post types that support revisions?
|
add to your wp-config.php file the following line: <code> // set max post revisions define('WP_POST_REVISIONS', 5); </code> source: http://codex.wordpress.org/Editing_wp-config.php#Post_Revisions
|
How does one reduce the number of stored revisions?
|
wordpress
|
has_post_thumbnail seems to be working fine but the_post_thumbnail returns nothing. here is my code: <code> if ($favorite_post_ids): foreach ($favorite_post_ids as $post_id) { $p = get_post($post_id); echo "<li>"; echo "<a href='".get_permalink($post_id)."' title='". $p->post_title ."'>" . $p->post_title . "</a> "; wpfp_remove_favorite_link($post_id); if (has_post_thumbnail($post_id)) { echo $post_id; the_post_thumbnail($post_id); } echo "</li>"; } </code> Here is the sample output: <code> * Post101 remove 101 * Post97 remove 97 * Post59 remove 59 </code> Most of the code above is irrelevant, I just included it for clarity. I have echoed the $post_id to make sure that it is passing the if (has_post_thumbnail($post_id)), which it does but the_post_thumbnail fails silently. I tried echoing it too but that returns nothing either. I have got post_thumbnails turned on in the theme: <code> if ( function_exists( 'add_theme_support' ) ) { add_theme_support( 'post-thumbnails' ); } </code> any ideas? thanks
|
You're passing an invalid argument to the_post_thumbnail() . Here's your code: <code> the_post_thumbnail($post_id); </code> Here's what <code> the_post_thumbnail() </code> expects: <code> the_post_thumbnail( $size, $attr ); </code> The function is expecting a <code> $size </code> as the first argument. Since <code> $post_id </code> is not a valid <code> $size </code> , the function doesn't know what to output.
|
the_post_thumbnail() returns nothing even though has_post_thumbnail() returns true
|
wordpress
|
I wanted to link images in a gallery to a custom URL. I know I could add an extra field and do it stackexchange-url ("this way") I found this ticket on Trac, though, that modifies the "Link URL" field to accept custom links. I like how that works and I'd like to make that work. Trouble is, I can't seem to figure out how to access the data. I'm using get_children to create an array to loop through. The Link URL is not included in the results. I've tried get_attachment_link - the trouble is, it doesn't just pull it from the field, the function generates the link itself. Any ideas? Thanks!
|
On the Trac ticket you've linked at the bottom there is a solution to make it work <code> function _save_attachment_url($post, $attachment) { if ( isset($attachment['url']) ) update_post_meta( $post['ID'], '_wp_attachment_url', esc_url_raw($attachment['url']) ); return $post; } add_filter('attachment_fields_to_save', '_save_attachment_url', 10, 2); function _replace_attachment_url($form_fields, $post) { if ( isset($form_fields['url']['html']) ) { $url = get_post_meta( $post->ID, '_wp_attachment_url', true ); if ( ! empty($url) ) $form_fields['url']['html'] = preg_replace( "/value='.*?'/", "value='$url'", $form_fields['url']['html'] ); } return $form_fields; } add_filter('attachment_fields_to_edit', '_replace_attachment_url', 10, 2); </code> So after this code you will be able to add your custom links in the "Link URL" field. And to get it you just need the attachment ID and you can get it with: <code> get_post_meta( $post->ID, '_wp_attachment_url', true ); </code>
|
Retrieving a custom link on an attachment
|
wordpress
|
Is there any way to import a basic, exported Wordpress content XML file and have it replace the existing content? What I'm trying to do is synch up two instances of a site (development and staging servers) and all I want to replace is the Page content. When I try to import the XML document it simply states that all the pages already exist and nothing is done. Is it possible to override that warning and replace the content of the pages with the content of the XML?
|
One option might be to export both XML files, merge them using a file merging tool like http://winmerge.org , delete all posts and replace with the merged version.
|
Import and replace existing page/post content
|
wordpress
|
I had this problem on 2 web sites (different versions of WP, different web hosts, different plugins), once in a while some images are disappearing from media library. Is it plugin-related issue, database, web host?
|
"Disappearing" means very little unless you can say the image file really disappeared from the server or if it's just a broken link you're seeing in page source or a bad link in the DB. Little help can be offered unless you look in logs and see errors, ask your host about problems and nail down the similarities and differences between the two instances of missing images, versions of WP and plugins.
|
Why images are disappearing on WordPress web site?
|
wordpress
|
Is there an explicit action hook that will fire when (or just before) the admin Edit page renders for a custom post type? Something similar to {$new_status}_{$post-> post_type}? I'm trying to find the least obtrusive place to insert my add_meta_box() registration so that it's not calling that function on every page refresh, but only when it's needed (ie: the user wants to create a new custom post or edit an existing custom post). Thanks for your thoughts / code snippets!
|
<code> register_post_type() </code> has a registration option called <code> 'register_meta_box_cb' </code> . Set that to a valid callback and it will call that function only when it is compiling the meta boxes for that post type's edit screen. Something like this: <code> register_post_type( 'foo', array( 'public' => true, 'label' => 'foo', 'register_meta_box_cb' => 'bar', )); function bar(){ add_meta_box('blah', 'blah', /* etc */ ); } </code>
|
Action hook on Edit custom post type?
|
wordpress
|
Problem After realizing that post formats are pretty popular, but only a extremly rough drawn concept, i see that users will run into possible traps. Post format ... uses post meta fields & user doesn't remember exact meta key name. takes the link/embed/whatever object from post editor & user inputs wrong data. Both are examples of possible traps a user could hit. Idea The post format has a custom meta box that does only allow to input the expected data. The idea itself isn't that bad, but there's still the problem that the user would have to put data into the correct meta box then select the according post format. Question What i'm searching for is a solution that switches (ajax) the meta box (or just its content) based on the selection a user makes inside the post formats meta box OR... using a ajax/jquery-ui tabs inside the meta box to switch meta box contents and save the according post format on 'save_post' Note: I'm not searching for the exact meta box content. My most interesst is to see the 'surroundings' in different <code> code </code> examples. Thank you!
|
I did something like this once, but when you clicked on a certain category (essentially the same) It certainly isn't a true ajax solution, it just hides and reveals the div with the settings, but It is a solution which works. You'll definitely have to modify this for your needs, but if you have a grasp on jQuery, I'm sure you'll be able to modify this for your needs. If you are a little more specific about your needs, I'd be happy to edit this up to suit what you are looking for more exactly. The Code: I used this in a plugin, but you can just put this into your theme's functions.php <code> function customadmin_testimonial() { if ( is_admin() ) { $script = <<< EOF <script type='text/javascript'> jQuery(document).ready(function($) { $('#testimonial-information').hide(); $('#in-category-3').is(':checked') ? $("#testimonial-information").show() : $("#testimonial-information").hide(); $('#in-category-3').click(function() { $("#testimonial-information").toggle(this.checked); }); }); </script> EOF; echo $script; } } add_action('admin_footer', 'customadmin_testimonial'); </code> Basically what you have here is a jQuery script that initially hides a meta box that I have already set up. The box's ID is #testimonial-information. Then it checks on whether or not the specific category's box is checked, and if it is, shows it. Then it listens for a click on the specific category's box and toggles it's visibility. The Result: A meta box that is visible only when the user has chosen a specific category. All you'll need to do is set up your metaboxes and get all the ID's of the elements you need. You'll need the ID's of the metaboxes as well as the checkboxes in question. Then all you need to do is follow this formula to get what you are looking for. If you have everything set up but are having a hang-up writing the javascript, just provide me the ID's of the metaboxes and corresponding checkboxes and I'd be more than happy to write it up for you.
|
post formats - how to switch meta boxes when changing format?
|
wordpress
|
I am looking for a way to return something like the following: User, email, post title, post status User, email, post title, post status repeated.... Each user on my site has only 1 post. It is a custom post type called Company Listing.
|
You can do that with a simple loop assuming that the users are also the authors of the post, create a template page, and copy the inside of your page.php to it. then replace the loop part with this code: <code> <?php $args = array( 'post_type' => 'company-listing', //change this to your actual CPT name 'posts_per_page' => -1, //-1 to get all or any number you want to use with pagination ); query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> User, email, post title, post status <div class="post company-listing"> <ul> <?php $user_info = get_userdata($post->post_author); ?> <li class="user"> <?php echo $user_info->user_nicename; ?> </li> <li class="email"> <?php echo $user_info->user_email; ?> </li> <li class="title"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a> </li> <li class="status"> <?php echo $post->post_status; ?> </li> </ul> </div> <div style="clear:both"></div> <?php endwhile; ?> <?php else: ?> <p class="no-data"> <?php _e('Sorry, no page matched your criteria.'); ?> </p><!-- .no-data --> <?php endif; ?> </code> and add this little code css to style it right: <code> <style type="text/css"> company-listing ul li{ float: left;padding: 2px;} </style> </code> now you didn't specify what is "USER" so i just showed you how to use user_nicename but after this line <code> $user_info = get_userdata($post->post_author); </code> you can use $user_info with: user_firstname user_lastname ID user_login user_pass user_nicename user_email user_url user_registered display_name and a few more. As for status i assume you are talking about the post_status so you will need to add <code> 'post_status' => array('publish','pending','draft','future','private',....) </code> to your $args. and if you are talking about a custom filed then just call that field with <code> get_post_meta($post->ID,'status_field_name',true); </code> Hope this helps
|
How can I list all WordPress users, their email adress, post title and post status?
|
wordpress
|
I have installed the wp-nivo-slider and am now getting a list of these errors on my /wp-admin/ page. The error is: <code> Warning: Cannot modify header information - headers already sent by (output started at /html/wp-content/plugins/wp-nivo-slider/wp-nivo-slider.php:633) in /html/wp-login.php on line 354 </code> Any ideas?
|
This error is typically from there being extra spaces after the final closing ?> tag in a plugin file, or possibly even your wp-config.php file.
|
WP-nivo-slider Producing Error "Cannot modify header information - headers already sent by ..."
|
wordpress
|
I apologize if this is a very basic question, but I am very new to working with Wordpress. I'm looking into using Wordpress as a CMS for a new site I'm building but I'm not sure I understand some of the best practices for themes. I've heard that a good approach is to use pre-existing themes and modify them to your own purposes using a child theme. Is this the direction in which I should look? Is there another approach that I should look in to? Thanks for your help!
|
If you don't want to develop/maintain your own Theme, then yes: choose an existing Theme, and make modifications to it via Child Theme. If, on the other hand, you are comfortable with developing/maintaining your own Theme, then either create a new Theme, or make a derivative of an existing Theme. Since, as you state, you are very new to WordPress, I would highly recommend using the Child-Theme approach.
|
Themes—Child Themes
|
wordpress
|
I have a hierarchical taxonomy called 'geographical locations'. It contains continents on a first level, and then the countries for each one. Example : <code> Europe - Ireland - Spain - Sweden Asia - Laos - Thailand - Vietnam </code> etc. Using get_terms() I managed to output the full list of terms, but the continents get mixed up with the countries, in one big flat list. How can I output a hierarchical list like above?
|
Use <code> wp_list_categories </code> with the taxonomy argument, it's built for creating hierarchal category lists but will also support using a custom taxonomy.. Codex Example: Display terms in a custom taxonomy If the list comes back looking flat it's possible you just need a little CSS to add padding to the lists, so you can see their hierarchal structure.
|
How to show a hierarchical terms list?
|
wordpress
|
I got a pretty basic theme and just found out my style.css file doesn't get loaded into the <code> <head> </code> . I already searched around but can't find out, why it's not loading. I inspected the <code> global $wp_styles </code> object already but couldn't find anything: <code> function style_test() { $wp_styles = new WP_Styles(); echo '<pre>'; // $wp_styles->enqueue == completely empty print_r( $wp_styles->registered ); echo '</pre>'; } add_action( 'wp_print_scripts', 'style_test', 0 ); </code> Inside the object i also can't find my registered/enqueued stylesheets (they get loaded), so i guess i'm doing something wrong on inspecting this too. Any ideas? Note: If i enqueue it manually, my style.css file get's loaded. Just the automatic loading doesn't work. Further more i can access the file with <code> get_theme_data( TEMPLATEPATH.'/style.css' ); </code> without a problem.
|
Theme stylesheets aren't usually enqueued, they're normally loaded using.. <code> <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" /> </code> So naturally you don't see them(it) in the styles array.. You can of course(if you prefer) use an enqueue instead.
|
Why is style.css not being enqueued?
|
wordpress
|
Most of us are used to installing plugins directly from the WordPress.org plugin repository. This is the "official" list of available add-ins, and everything hosted there is guaranteed to be GPL. But occasionally developers will list beta releases and non-GPL plugins on their own sites. To install these, you have to download a ZIP file, then either upload it to WordPress through the plugin installer or via FTP. For the unaware, it can be a complicated process because there's no one-click setup. So what would be the potential benefits and drawbacks of enabling one-click plugin installation from any site? I'm thinking something along this process: You go to a site hosting a cool plugin. You enter your blog's address ( <code> http://mycoolwordpressblog.com </code> ) in a box somewhere. An oAuth-type box pops up asking you to log in to your blog. Once you're authenticated, the plugin is added to your site automatically and you're given the option to activate it. I suggest oAuth so that you only log in to your site (I don't want to give my admin credentials to someone I don't know), but there might be other ways to do it. Remotely uploading the plugin could likely happen using WordPress' built-in XML-RPC system since it already allows you to upload files. Ideas? Comments? Feedback?
|
Also look into this tool - http://markjaquith.wordpress.com/2010/07/24/plugin-installer-tool/
|
What would be the advantages/disadvantages of remote plugin installation?
|
wordpress
|
I've just updated a website that used <code> .php </code> urls, to a Wordpress 3.1 site, that uses no file type extentions, (custom permalinks). They have a lot of references in their imported content to an old page ending in <code> .php </code> which now goes to an error 404 page. My question is this: What is the rewrite rule I should use in my htaccess file that would redirect someone clicking on a link to <code> www.somesite.com/glossary.php#anchor </code> , to <code> www.somesite.com/glossary/#anchor </code> ? Any help gratefully appreciated, S.
|
Your first order of business should be updating the links in your imported content so that people aren't given links to the old URLs in the first place. This should be pretty easy to do with an SQL replace. For your situation, it'd be something along the lines of: <code> UPDATE wp_posts SET post_content = REPLACE(post_content, '.php', '/'); </code> You gotta be realy careful with find/replaces though, as they sometimes replace things you didn't anticipate. It's a good idea to back up your DB before doing anything like this. As for an htaccess fix: it's definitely a good idea to do 301s for the old URLs if you have a lot of inbound links, which translate to SEO value. But the amount of work you put into this should be proportional to the value of those inbound links. I'm thinking it's not a good idea to try to rewrite ALL .php requests, as Wordpress often needs to make legitimate ones. For example, all requests on the frontend are routed through index.php, and when I tried setting up a rule like the one you asked for, it broke WordPress altogether. Know what I'm saying? An alternative is to set up individual rules for each page you want to 301. Of course, this might be a bad idea if you have a LOT of links--both because it's a hassle, and could impact performance. Hopefully someone else has a tricky htaccess workaround for you, but I'm stumped.
|
Url rewrite with htaccess
|
wordpress
|
I have a couple of pages on my WordPress site that need to run over SSL. I've installed the WordPress HTTPS plugin and configured the pages to use SSL. However, I'm still getting the error message that some of the items are coming over unsecured and that is a concern for some users. I've looked into the generated source code and I can see some items that are still going over non SSL channels, such as the following tags at the top of the page when I view source: <code> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> <head profile="http://gmpg.org/xfn/11"> </code> The browser only gives me the generic error message about mixed content. How do I determine which resources are causing the error?
|
Do exactly what you're doing: view the source of the offending page, and do a text search for "http://". Anything with this protocol is "insecure", and needs to be swapped to https. Common offenders are stylesheets, javascript, and 3rd-party widgets. If you can't find any problems in the source, try using firebug's "net panel". It lists all the requests a page makes, and you can scan through them to look for anything that starts with "http://" (even asynchronous requests). If you're still stuck, post the URL of your problem page and I'll take a look.
|
How do I find non-SSL problems on my SSL page?
|
wordpress
|
I was considering a plugin that inserts itself as a widget in one's sidebar. Trouble is, I don't know what to expect for the minimum width in one's sidebar. Is there a standard?
|
As far as i am aware there is "no" standard each sidebar is defined by the theme itself i would create the elements so that they stretch and wrap in your div and use %'s in your css for associated sizes.
|
Minimum Widget Width for Plugin Development
|
wordpress
|
Basically, I thinking how i could get a mini wp-admin/edit.php view inside the wp-admin/post.php page. does this even make sense to anyone?
|
Try the CMS Tree Page View plugin (my favorite) or the Easily navigate pages on dashboard plugin. Both allow you to have a list of your pages on the Dashboard. Then you should be able to add that panel using this reference: add_meta_box to integrate the box that appears on the Dashboard (see wp_add_dashboard_widget in functions.php of CMS Tree Page View)
|
display list of posts/pages in admin edit post/page
|
wordpress
|
I currently have the following plugins activated in my wordpress installation: row 1: Outbrain row 2: Subscribe via feedburner RSS/email row 3: Topsy tweet widget, FB like widget, WP-Email a friend widget I want to change the order in which they appear. I want widgets in row 3 to appear first, outbrain widget to appear last, in row 3. How do i achieve this? Although I can fiddle a little bit with PHP if the solution requires, I prefer an independent plugin to take care of the ordering if there exists one! Thanks!
|
From your comment it looks like you almost got it, Plugins that add something under your content usually <code> use the_content </code> filter by calling a function using <code> add_filter </code> for example outbarin plugin calls it like this: <code> add_filter('the_content', 'outbrain_display'); </code> so the way your can order them is by passing the priority parameter <code> add_filter('the_content', 'outbrain_display',99); </code> But changing it directly on the plugin's files is not the right way since next time you will update the plugin you will lose these changes, so the right way to do it is to add an action after the plugins were loaded using the <code> plugins_loaded </code> action hook and remove the filters they added and then re add this filters using your desired order: <code> add_action('plugins_loaded','my_content_filters_order'); function my_content_filters_order(){ //first remove the filter call of the plugin remove_filter('the_content', 'outbrain_display'); //... Do that for all filters you want to reorder //... ex: remove_filter('the_content', 'FB_like'); //then add your own with priority parameter add_filter('the_content', 'outbrain_display',99); //... Do that for all filters just removed and set //... the priority accordingly //... Lower numbers correspond with earlier execution //... ex: add_filter('the_content', 'FB_like',98); //... this will run first then outbrain } </code> hope this helps
|
Is there a way to alter the order in which the plugins appear in the page?
|
wordpress
|
I am working with the Role and Capabilities API for the first time today and making use of the the excellent Members plugin . Having tinkered around for some time I notice that the "edit pages" capability does two things: Allow the user to create a new page Allow the user to edit existing pages I am trying to split this capability into two. I want my user to: Not be able to create any new pages Allow the user to edit existing pages I am looking to write some code for my theme that allows this to happen. I can create a new capability very easily. The challenge is then getting WordPress to respond accordingly to it. Any thoughts would be appreciated.
|
Yes, this is indeed a problem. A dedicated 'create_posts' capability is planed: http://core.trac.wordpress.org/ticket/16714
|
User capability of create page/new page
|
wordpress
|
I have used Jeff Star's tutorial for creating my own custom login form http://digwp.com/2010/12/login-register-password-code/ . It works great, but I have one problem. On the reset password form, if someone enters their username incorrectly (so that it doesn't verify), they get kicked to the default wp-login.php?action=lostpassword with the error message. Is there a way to redirect to my own error page? Thanks!
|
The code he posted in that tutorial (very nice BTW) post's the form to the build-in "reset password" module which redirects to the login.php on error, but you can change that and build your own based on the original and add it to the template page, change: <code> <form method="post" action="<?php echo site_url('wp-login.php?action=lostpassword', 'login_post') ?>" class="wp-user-form"> <div class="username"> <label for="user_login" class="hide"><?php _e('Username or Email'); ?>: </label> <input type="text" name="user_login" value="" size="20" id="user_login" tabindex="1001" /> </div> <div class="login_fields"> <?php do_action('login_form', 'resetpass'); ?> <input type="submit" name="user-submit" value="<?php _e('Reset my password'); ?>" class="user-submit" tabindex="1002" /> <?php $reset = $_GET['reset']; if($reset == true) { echo '<p>A message will be sent to your email address.</p>'; } ?> <input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>?reset=true" /> <input type="hidden" name="user-cookie" value="1" /> </div> </form> </code> to: <code> <form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>" class="wp-user-form"> <div class="username"> <label for="user_login" class="hide"><?php _e('Username or Email'); ?>: </label> <input type="text" name="user_login" value="" size="20" id="user_login" tabindex="1001" /> </div> <div class="login_fields"> <?php do_action('login_form', 'resetpass'); ?> <input type="submit" name="user-submit" value="<?php _e('Reset my password'); ?>" class="user-submit" tabindex="1002" /> <?php if (isset($_POST['reset_pass'])) { global $wpdb; $username = trim($_POST['user_login']); $user_exists = false; if (username_exists($username)) { $user_exists = true; $user_data = get_userdatabylogin($username); } elseif (email_exists($username)) { $user_exists = true; $user = get_user_by_email($username); } else { $error[] = '<p>' . __('Username or Email was not found, try again!') . '</p>'; } if ($user_exists) { $user_login = $user->user_login; $user_email = $user->user_email; // Generate something random for a password... md5'ing current time with a rand salt $key = substr(md5(uniqid(microtime())), 0, 8); // Now insert the new pass md5'd into the db $wpdb->query("UPDATE $wpdb->users SET user_activation_key = '$key' WHERE user_login = '$user_login'"); //create email message $message = __('Someone has asked to reset the password for the following site and username.') . "\r\n\r\n"; $message .= get_option('siteurl') . "\r\n\r\n"; $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n"; $message .= __('To reset your password visit the following address, otherwise just ignore this email and nothing will happen.') . "\r\n\r\n"; $message .= get_option('siteurl') . "/wp-login.php?action=rp&key=$key\r\n"; //send email meassage if (FALSE == wp_mail($user_email, sprintf(__('[%s] Password Reset'), get_option('blogname')), $message)) $error[] = '<p>' . __('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...') . '</p>'; } if (count($error) > 0) { foreach ($error as $e) { echo $e . '<br/>'; } } else { echo '<p>' . __('A message will be sent to your email address.') . '</p>'; } } ?> <input type="hidden" name="reset_pass" value="1" /> <input type="hidden" name="user-cookie" value="1" /> </div> </form> </code>
|
Check for correct username on custom login form
|
wordpress
|
I have a question I hope you can help me with. I have a custom taxonomy called locations and on the first level I have the areas (Asia, Europe, etc) and under each area I have countries (England, South Africa). What I would like to do it display a dropdown menu of all the children of that particular parent similar to what was done here, http://wordpress.org/support/topic/terms-of-custom-taxonomy-in-a-dropdown-menu . However, I want the dropdown to only display the children of the parent page I am currently on, not all the terms. So if I am on North America I want it to show the United States and Mexico and if I am on the Europe parent page I want it to show England. Does that make sense? Nick
|
You can use <code> get_query_var( 'term' ) </code> to get the current term and <code> get_query_var( 'taxonomy' ) to get the current taxonomy, then all that is left is to use [wp_dropdown_categories()][1] function with </code> child_of <code> parameter and </code> taxonomy` parameter, so something like this: <code> //first get the current term $current_term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); //then set the args for wp_dropdown_categories $args = array( 'child_of' => $current_term->term_id, 'taxonomy' => $current_term->taxonomy, ); wp_dropdown_categories( $args ); </code> Done!
|
Displaying Custom Taxonomy Children in Dropdown
|
wordpress
|
I'm working on a real-estate site where I need to create a profile for each agent , the initial view when you click on view agents would be to list them alphabetically, ideally from a dropdown you could select a region to view all the agents from that region , or chose a language to view all the agents who speak a given language . My thinking is Agent would be a custom post type, region and language would be a taxonomy. The listing of agents would then be created by showing many posts, just only showing limited details, then when clicked act as a single post, with more details shown? Does this seem like the best way to go about this? Thanks
|
That Sounds about right, I'm just about to finish similar project with the same base (post type, taxonomies) structure, so here are a few notes to get you going: To enable your "view agents" make sure when you register agents post type that you set has_archive to true or use string as archive slug which will make your life much easier. When registering custom taxonomies make sure to set <code> rewrite </code> to <code> true </code> . Create a custom template taxonomy-{taxonomy}.php for each of your custom taxonomies (even if they both show the same thing, trust me on this one) this will save you a lot of time. On your "view agents" template file ( <code> archive-agents.php </code> ) Use wp_dropdown_categories function to generate your region and language dropdowns. And last create your single-agents.php template file to display the full information of the agent.
|
custom post type or taxonomy
|
wordpress
|
Alright so I've got two navigation menus that I've registered with my theme: <code> <?php if ( function_exists('register_sidebar') ) register_sidebar(); add_theme_support( 'menus' ); if ( function_exists('register_nav_menu') ) { register_nav_menu( 'primary_nav', 'Primary Navigation'); register_nav_menu( 'secondary_nav', 'Secondary Navigation'); } ?> </code> Functions.php And then Beyond that I've got two places in my header where I display the navigation menus: <code> <!-- BEGIN: Navigation Menu primary_nav (Primary Navigation) --> <?php if(function_exists('wp_nav_menu')) { wp_nav_menu( array( 'menu' => 'primary_nav', 'container' => '', 'depth' => 1, 'menu_id' => 'menu' ) ); } else { ?> <ul> <?php wp_list_pages('title_li=&depth=1'); ?> </ul> <?php } ?> <!-- END: Navigation Menu primary_nav (Primary Navigation) --> </div> </code> header.php - Location 1 <code> <!-- BEGIN: Secondary Navigation Menu --> <?php if(function_exists('wp_nav_menu')) { wp_nav_menu( array( 'menu' => 'secondary_nav', 'container' => '', 'depth' => 1, 'menu_id' => 'secondary_nav_id' ) ); } else { ?> <ul> <?php wp_list_pages('title_li=&depth=1'); ?> </ul> <?php } ?> <!-- END: Secondary Navigation Menu --> </code> header.php - Location 2 In the admin page for the theme everything shows up just fine, both menus appear in the list both Primary Navigation and Secondary Navigation. And from the admin screen I've added two distinct sets of menu items. However, whenever I load up my theme, for some reason I end up with only the menus from the Primary Navigation appearing twice. Is there something I've forgotten that would cause this behavior?
|
Try <code> theme_location </code> instead of <code> menu </code> in arguments. Too late here to look up specifics, but I remember documentation/code being absolutely confusing about that.
|
Two Navigation Menus in Themes Produce the same menus?
|
wordpress
|
IS it possible to make every Widget on Wordpress in a different .php file? I have one page that contains 12 elements, I want to make each of them a Widget so it would be easier to manage/edit them later on, but it would be better if it's from a php page rather then from a code block on the Admin panel.
|
If the 12 elements are static HTML, you can just create 12 text widgets. If they're not, it depends on what you mean by "easy to manage". I, for one, prefer to be able to easily manage my code via SVN. Using widgets obscures that. If you just want them to be in separate files, just make separate files, put them in their own folder and include them: <code> include './sidebar/part-1.php'; include './sidebar/part-2.php'; </code> If you're sure you really want widgets, wrap the code in the files mentioned previously in classes, as described here: http://codex.wordpress.org/Widgets_API#Developing_Widgets
|
Widgets in PHP files?
|
wordpress
|
I'm trying to get VideoJS plugin to work in a Widget. I tried to add a PHP widget and write, as it said in the manual: <code> [video mp4="http://video-js.zencoder.com/oceans-clip.mp4"] </code> But it just shows the code as is, any ideas?
|
To display shortcodes in widgets , use a regular text widget, and add this line to your theme's functions.php file: <code> // Use shortcodes in text widgets. add_filter('widget_text', 'do_shortcode'); </code> This tells WordPress to render the shortcodes in widgets. and if you want to call your shortcode by php you can use do_shortcode() function <code> // Use shortcode in a PHP file (outside the post editor). do_shortcode('[video mp4="http://video-js.zencoder.com/oceans-clip.mp4"]'); </code> To get a better understanding of shortcodes check out this tutorial which covers: What shortcodes are, How to use shortcodes, ,How to define your own. and How to use them in widgets. Hope this helps
|
VideoJS in a Widget?
|
wordpress
|
I'm creating my first wordpress plugin and I'm struggling to find the correct and best way to make sure jquery and my own JS file is included on my settings page of my plugin. I do not need them to load anywhere else unless on my settings page. What code and where do I put it in my plugin? This is what I have so far as for creating the settings page: <code> add_action("admin_menu", "create_admin_pages"); function create_admin_pages() { add_submenu_page('options-general.php', "MYPLUGIN", "MYPLUGIN", 10, "my-plugin", 'settings_page'); } functions settings_page() { // Settings form is here and I need Jquery and my script loaded for this } </code> EDIT: The code above is somewhat been dumbed down so not to reveal the plugins function until its ready to be released. The Plugin I'm coding is wrapped in a class so its ok that the function names are generic.
|
First use <code> add_options_page() </code> - shorter wrapper, better practice. Second you need to save its return in some (global or static) variable. That is often used thingie and confusingly referenced by different names in documentation. Global <code> $hook_suffix </code> holds such value for current page. <code> function create_admin_pages() { global $my_page; $my_page = add_options_page(... </code> From there it is something like this: <code> add_action('admin_enqueue_scripts', 'enqueue_script'); function enqueue_script($hook_suffix) { global $my_page; if ($my_page == $hook_suffix) wp_enqueue_script('my_script', plugins_url('my_script.js', __FILE__), array('jquery')); } </code>
|
Plugin - Make sure jquery is loaded in my settings page plus my JS file
|
wordpress
|
I have moved a Wordpress install to a client from sub folder to the root folder. Right now, everything works fine, except for the friendly URLs. I currently have to set the Permalink feature in "Common settings" to "Default", which means URLs with ?p=434... At least they work. Otherewise I get a very short 404 not found error message on a white screen. I was following this tutorial, but I found I cannot write an .htaccess to my Yahoo host account and so I could not follow one of the last steps... I wonder if the 404 not found errors have to do with this problem I have had uploading the .htaccess file... I currently do not have any .htaccess file up there... So maybe MOD_REWRITE is disabled... I have just ran phpinfo() and did not find any entry on mod_rewrite. Before moving the website, when it was still on a subfolder, the friendly URLs used to work, but now they don't. Has anyone came accross this experience and has successfully restablished the permalinks feature? Any help is appreciated. Thank you.
|
Yahoo doesn't allow users access to the htaccess file which means that you can't the mod_rewrite rules needed for custom permlinks. The Only way around it that i've heard it works (never tried it myself) is to add /index.php/ to the beginning of your custom structure so: Go to Permalink Settings > Select Custom Structure. And set the value as <code> /index.php/%postname%/ </code> or what ever you want as long as you add /index.php/ before it. Hope this helps.
|
WordPress permalinks Yahoo hosting(no .htaccess allowed)
|
wordpress
|
This is a page that list posts witht he category <code> Content (CDs) </code> : <code> <div id="tagline"> <div class="container"> <?php // Run main loop (The Loop). ?> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <div class="content0"> <?php the_content(); // <- I want to get this ?> </div> <?php endwhile; ?> </div><!-- .container --> </div><!-- #content-bottom --> <div id="content"> <div class="container"> <div id="mainbar"> <?php $custom_posts = new WP_Query(); ?> <?php $custom_posts->query('category_name=Content (CDs)'); ?> <?php while ($custom_posts->have_posts()) : $custom_posts->the_post(); ?> <div class="content-block-4"> <h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2> <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail('large'); ?></a> <p><?php the_content(); ?></p> </div> <?php endwhile; ?> </code> <code> single.php </code> has the following: <code> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <div class="content0"> <?php $parent = get_post($post->post_parent); ?> <?php $parent->post_content; ?> </div> <?php endwhile; ?> </code> But still can't get <code> the_content </code> of the parent page. Any suggestions?
|
I think you need to do two things add ' echo ' to last line <?php echo $parent-> post_content; ?> add ' global $post; ', before accessing the $post. let me know if this does not work.
|
Can't get the_content of the parent page from its single post?
|
wordpress
|
I'm using a loop in the sidebar of my site to show all the posts that are in that category. Now I'd like to include a 'current_post' class to the current post that is being displayed to style that item in the list. I've tried looking for conditional tags or this custom stackexchange-url ("wp_list_post_types function") but both haven't worked. Does anybody know if there's a way to do this? EDIT: Adding Loop from comment below <code> <?php foreach((get_the_category()) as $category) { $postcat= $category->cat_ID; $catname =$category->cat_name; } $args = array( 'cat' => $postcat ); $my_query = new WP_Query(); $my_query->query($args); // Equivalent of query_posts() while($my_query->have_posts()) : $my_query->the_post(); $id=get_the_ID(); $currentClass= ($post->ID == $id) ? "current_post": ""; ?> <a class="<?php echo $currentClass; ?>" href="<?php the_permalink();?>">ni</a> <?php endwhile; ?> </code>
|
You should be able to get the queried object id and use that for comparison inside your custom loop.. Before your existing loop code(what you have posted above), but obviously after the opening PHP tag.. <code> global $wp_query; $current_id = $wp_query->get_queried_object_id(); </code> Then somewhere inside your custom WP loops.. <code> if( $current_id == get_the_ID() ) { // This result is the current one } else { // Not current } </code> Hope that helps..
|
Adding 'current_post_item' class to current post in the loop
|
wordpress
|
This simple tutorial teaches you how to make a voting counter using the post's meta data. I would like to know how to add down-votes to this small script (e.g. -1, -2). In the following way: If the post has 0 votes and it gets down-voted, it ends up with -1. If the post has 1 vote and it is down-voted it ends up with 0 (only one counter). the jQuery part: <code> <?php wp_enqueue_script( 'jquery' ) ?> <?php wp_head(); ?> <script type="text/javascript"> jQuery(document).ready(function() { jQuery(".vote a").click( function() { var some = jQuery(this); var thepost = jQuery(this).attr("post"); var theuser = jQuery(this).attr("user"); jQuery.post("<?php bloginfo('template_url'); ?>/vote.php", { user: theuser, post: thepost }, function(data) { var votebox = ".vote" + thepost + " span"; jQuery(votebox).text(data); jQuery(some).replaceWith('<span class="voted">Voted</span>'); }); }); }); </script> </code> When a member clicks on the vote link, the above code will get the post ID and the member’s user ID and send it to a file called vote.php using a post method. The vote.php file will perform everything we need to add the vote. vote.php: <code> <?php $file = dirname(__FILE__); $file = substr($file, 0, stripos($file, "wp-content") ); require( $file . "/wp-load.php"); $currentvotes = get_post_meta($_POST['post'], 'votes', true); $currentvotes = $currentvotes + 1; $voters = get_post_meta($_POST['post'], 'thevoters', true); if(!$voters) $voters = $_POST['user']; else $voters = $voters.",".$_POST['user']; update_post_meta($_POST['post'], 'votes', $currentvotes); update_post_meta($_POST['post'], 'thevoters', $voters); echo $currentvotes; ?> </code> Once the information is posted to vote.php two custom fields are created. One to count the vote and one to add the voter to a list so that they can’t vote again. functions.php: <code> // voting function function voting($id) { global $user_ID; $currentvotes = get_post_meta($id, 'votes', true); $voters = get_post_meta($id, 'thevoters', true); $voters = explode(",", $voters); foreach($voters as $voter) { if($voter == $user_ID) $alreadyVoted = true; } if(!$currentvotes) $currentvotes = 0; echo '<div class="vote vote'.$id.'"><span>'.$currentvotes.'</span>'; if($user_ID && !$alreadyVoted) echo '<br /><a post="'.$id.'" user="'.$user_ID.'">'.__("Vote").'</a>'; if($user_ID && $alreadyVoted) echo '<br /><span class="voted">'.__("Voted").'</span>'; echo '</div>'; if(!$user_ID) echo '<div class="signup"><p><a href="'.get_bloginfo('url').'/wp-login.php?action=register">'.__('Register').'</a> '.__('to vote').'.</p></div>'; } </code> any suggestions?
|
You will have to make a second button for down voting. Give the upvote button a class of up and the down vote button a class of down. jQuery <code> <?php wp_enqueue_script( 'jquery' ) ?> <?php wp_head(); ?> <script type="text/javascript"> jQuery(document).ready(function() { jQuery(".vote a.up").click( function() { var some = jQuery(this); var thepost = jQuery(this).attr("post"); var theuser = jQuery(this).attr("user"); jQuery.post("<?php bloginfo('template_url'); ?>/vote.php", { user: theuser, post: thepost, updown: 'up' }, function(data) { var votebox = ".vote" + thepost + " span"; jQuery(votebox).text(data); jQuery(some).replaceWith('<span class="voted">Voted</span>'); }); }); jQuery(".vote a.down").click( function() { var some = jQuery(this); var thepost = jQuery(this).attr("post"); var theuser = jQuery(this).attr("user"); jQuery.post("<?php bloginfo('template_url'); ?>/vote.php", { user: theuser, post: thepost, updown: 'down' }, function(data) { var votebox = ".vote" + thepost + " span"; jQuery(votebox).text(data); jQuery(some).replaceWith('<span class="voted">Voted</span>'); }); }); }); </script> </code> vote.php <code> <?php $file = dirname(__FILE__); $file = substr($file, 0, stripos($file, "wp-content") ); require( $file . "/wp-load.php"); $currentvotes = get_post_meta($_POST['post'], 'votes', true); if("up" == $_POST['updown']) { $currentvotes ++; } elseif("down" == $_POST['updown']) { $currentvotes --; } $voters = get_post_meta($_POST['post'], 'thevoters', true); if(!$voters) $voters = $_POST['user']; else $voters = $voters.",".$_POST['user']; update_post_meta($_POST['post'], 'votes', $currentvotes); update_post_meta($_POST['post'], 'thevoters', $voters); echo $currentvotes; ?> </code> Thats all you should need to edit
|
How to enable users to down-vote in this simple voting counter (that uses the post meta)?
|
wordpress
|
As stated in a previous Q, i'm currently getting into post formats and what to do with them. After searching for quite a time through search results and a lot of blog posts, i realized that there's only pretty less written about What to do with the different post format types? Post Formats i'm unclear about what they represent: 1) asides - "twitter" style messages 2) status - "facebook" style messages Ad 1) When i look at facebook messages, then they contain nearly everything (links, images, status, chat, etc.), so currently it doesn't make much sense for me to see "asides" as facebook messages as every other post format would be a sub-post-format of "asides". Ad 2) When i take the fact away, that facebook styled messages could contain content of all other post format types, and see "asides" only as representation of the message part, where is the difference to "status"? Questions: Ad 1) What is the intended usecase of "aside"? and Ad 2) What is the difference between "aside" and "status" Note: I first thought the problem may be that english is not my mother tongue and translated it - with no result. I even translated my local wordpress install into my native language - with no result.
|
I think you have this a bit backward: 1) asides - "twitter" style messages 2) status - "facebook" style messages Think of status as a Tweet or Facebook status update: a text-only or text-and-link-only post of around 150 characters or less (140 seems to be a good number, thanks to Twitter). Think of an aside as a brief post, of one or two paragraphs, usually without a Title. The problem with the term aside is that its use (and nomenclature) is not dictated in any way whatsoever by the historical use of the term "aside" in literature, drama, etc. Instead, the use of the term comes from Matt Mullenweg's personal site. Matt started writing brief, un-titled Posts, which he categorized as "asides". One version of his personal site's Theme (Mazeld, perhaps?) started creating a custom loop for the "asides" and "gallery" categories. These custom loops became the origination for the concept of Post Formats, and unfortunately, the term "aside" was retained as one of the Post Format types.
|
post formats - where's the difference: "aside" vs. "status"?
|
wordpress
|
I would like to be able to associate an image with a custom taxonomy term. Ideally, I'd like to provide the end-user with an interface for managing the image directly on the term itself. I have worked with a plugin that provides this functionality (Ultimate Taxonomy Manager) - it may be what I stick with. I'm after the best practice, though, and would like to know if any of you have worked through this before and what solutions you recommend.
|
Maybe <code> How TO custom taxonomies extra fields </code> is whats you are looking for?
|
Adding An Image To A Custom Taxonomy Term
|
wordpress
|
The following post formats got a specific type of content part that should get displayed: Audio Video Link Questions: A) What is the exact content (element) that is meant to get displayed for video & audio? B) How would you get the relevant part of the post content that represents the post format? C) What would you do with the rest of the content? D) How would you know which format a audio/video player needs as there's nothin built in? Note (ad C): How would a user know that she/he should only post eg. a "link" (post format) and not a link inside a text? Note (ad D): stackexchange-url ("As already asked by @bueltge") there's no player.
|
There is no convention or consensus on any of these questions. In my own Theme, Oenology, I use the standard template tag <code> the_content() </code> to get the content for almost every Post Format type. The exception is Images and Galleries, where I pull the image out separately, and use <code> the_excerpt() </code> as the image caption/gallery description. A) They are intended to display whatever content is added to the Post. B) Use <code> the_content() </code> , just as you would with a "standard" Post C) Display it, either as per normal, or using some creativity for certain post format types. If you develop a Theme that makes certain assumptions about what content applies to specific Post Format types, then provide documentation within the Theme to explain those assumptions. D) You can't know. I just leave the raw link to the audio, and leave it up to the end user to choose an Audio Player Plugin.
|
post formats - how to get the relevant content part?
|
wordpress
|
When trying to update wordpress from 3.1 to 3.1.1 I am getting the error <code> Incompatible Archive.: PCLZIP_ERR_BAD_FORMAT (-10) : Unable to find End of Central Dir Record signature </code> Some searching shows a cause of this can be that the servers disk is full. My disk is not full but it was about a week ago. I believe Wordpress has the disk still flagged as full and not writeable. Does that sound plausible or does any one have any other suggestions? I have three Wordpress blogs on the server and this is only affecting one of them.
|
Sounds like the upgrade download corrupted (probably because of disk space) - just do the upgrade manually.
|
disk was full but wordpress still having issues
|
wordpress
|
OK I'm looking for the best way to attack this. I'm very comfortable with PHP and making custom post types with custom meta fields in WordPress. Here is what I'm looking at doing: User registers and is set at subscriber by default. User requests from admin to have permission to custom post type. Admin assigns user to another permission name like "Shop Owner". User can now see custom post type and can make an entry to this post type. User can only see and edit their own post. I need help on the following: How to create a new "Role" called "Shop Owner", How to give the correct permission to said role to only see and have access to custom post type. Only allow user to see and edit their own posts to this custom post type. Ideally I would prefer this was all done from the wp-admin but I'm guessing that I might need to build a front end for this to get the finite control I'm after. Any input is greatly appreciated. Kind Regards
|
Use Justin Tadlock's plugin "Members". It gives you the ability to create new roles and edit existing roles, as well as add custom capabilities. All that work that you'd have to do can be taken down to a few clicks. I know you said in your comment on ZaMoose's answer that you are 'looking to write the functionality myself so I have full control over everything.' That's missing the whole point of open source software. Justin Tadlock released his plugin so you could use it precisely so you WOULD have complete control over everything. If you really really want to reinvent the wheel, potentially wasting hundreds of hours of your own time I can't stop you, but you could at least save yourself the trouble and use Tadlock's plugin to learn how to do what you want. Once you have a plugin that does what you want, you'll need to change the <code> 'map_meta_cap' </code> flag to <code> true </code> and the <code> 'capability_type' </code> flag in your post type registration function so that it says something other than 'post', 'page', or any other 'reserved' type. Then, duplicate all the capabilities related to posts (e.g. <code> edit_posts </code> , <code> edit_others_posts </code> , <code> publish_posts </code> , etc.), using your capability type instead of posts. Make sure to assign all these permissions to administrators (you won't be able to see the post type until you do this), then create your role, mimicking the 'contributor' role's abilities for your post type. For example, say your capability type was <code> foobars </code> , you would want to give 'shop owners' the <code> edit_foobars </code> , <code> delete_foobars </code> , and <code> read </code> capabilities. That way they can create their own draft foobars, and delete those drafts, but because they don't have <code> publish_foobars </code> capabilities, they have to submit them for approval. Because they don't have <code> edit_published_foobars </code> , all modifications to an approved foobar have to be approved.
|
Allow member to have access to custom post type only. Permission to only edit their own posts
|
wordpress
|
I'm trying to implement pagination on a category page. The pagination is working, but now for some reason the pagination plugin I'm using is noting one extra page of results, when that page is actually empty. I'm pretty sure it doesn't have anything to do with the pagination plugin because I've seen reports of people having the same problem with next_posts_link and previous_posts_link. Anybody have any idea how this could happen? Loop: <code> <?php global $myOffset; $myOffset = 11; $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query(); $wp_query->query('offset='.$myOffset.'&cat=6&posts_per_page=12'.'&paged='.$paged); ?> <?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?> STUFF <?php endwhile; ?> <?php if(function_exists('wp_paginate')) { // get yo paginate on wp_paginate(); } ?> </code> Edit: I am also using this functions.php plugin to enable the offset parameter in a custom wp_query: <code> function my_post_limit($limit) { global $paged, $myOffset; if (empty($paged)) { $paged = 1; } $postperpage = intval(get_option('posts_per_page')); $pgstrt = ((intval($paged) -1) * $postperpage) + $myOffset . ', '; $limit = 'LIMIT '.$pgstrt.$postperpage; return $limit; } //end function my_post_limit </code>
|
I am not sure, but I have a guess that it is because you are using pagination and <code> offset </code> at the same time. Pagination might be calculated for whole set, but you are reducing set size with offset so number of pages becomes overestimated.
|
Pagination gives extra page with no results
|
wordpress
|
I am looking for a way to remove theme, change theme button and WP version from the "right now" admin dashboard, but using only functions. Any help?
|
Ah, one of those things that seem easy until admin dashboard internals throw you into depths of despair. :) Basically there is no easy and intended way to do this, so need to get creative. My idea would be to override temporarily couple of capabilities that control parts of output and kill the rest with filters in translation mechanisms. PS ehm, while I was messing with this it slipped me that you want to change some part and not remove everything. Well you can just remove and produce your own output or build on top of translation filter. See <code> wp_dashboard_right_now() </code> source for what is inside that widget. <code> add_action('right_now_discussion_table_end','turn_off_caps'); add_action('rightnow_end','turn_on_caps'); function turn_off_caps() { add_filter('ngettext','disable_theme'); add_filter('map_meta_cap','disable_caps',10,2); } function turn_on_caps() { remove_filter('ngettext','disable_theme'); remove_filter('map_meta_cap','disable_caps',10,2); } function disable_caps($caps,$cap) { if( 'update_core' == $cap ) $caps[] = 'do_not_allow'; if( 'switch_themes' == $cap ) $caps[] = 'do_not_allow'; return $caps; } function disable_theme($text) { if('Theme' == substr($text,0,5)) return ''; return $text; } </code>
|
Remove theme, change theme button and WP version on "Right Now" admin dashboard?
|
wordpress
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.