question
stringlengths 0
34.8k
| answer
stringlengths 0
28.3k
| title
stringlengths 7
150
| forum_tag
stringclasses 12
values |
---|---|---|---|
i went to upgrade my plugins and it never came back .. now when i go to my blog i get an error stating: <code> The service is unavailable. </code> i tried renaming the "upgrade" folder under wp-content but that didn't seem to do anything. Any suggestions?
|
This is definitely not error message produced by WordPress, so it comes from server software. Please check server logs (if you have access and skills) and ask your hosting support to look into it. It is hard to make a good guess from this little information.
|
WordPress crashes with "The service is unavailable." after trying to upgrade plugins
|
wordpress
|
For some reason, my posts content (the content placed outside of the shortcodes I have set up) is only displaying below all the shortcodes, no matter where I place content in the post. For example, I could set up a post like this: <code> [boxes cat="Features"] </code> <code> test content here </code> <code> [boxes cat="Reviews"] </code> And the test content will display below the Features AND the Reviews. Why would it do that? Some of my shortcodes use the php <code> include </code> . Here's an example of one of my shortcodes: <code> function free_ms_cms( $atts, $content = null ) { $free_ms = TEMPLATEPATH . '/get-free-ms.php'; include($free_ms); } add_shortcode( 'free-ms', 'free_ms_cms' ); </code> Anyone able to help? Thanks!
|
Are your shortcodes setup correctly? This usually means that your shortcode handling is echoing the shortcode content instead of returning it as a string. For your case, while you are including a file in your shortcode, I doubt that you have the file setup to return the output instead of echo'ing it. Try this instead: <code> function free_ms_cms( $atts, $content = null ) { $free_ms = TEMPLATEPATH . '/get-free-ms.php'; ob_start(); //start an output buffer to capture any output include($free_ms); return ob_get_clean(); //return the current buffer and clear it } add_shortcode( 'free-ms', 'free_ms_cms' ); </code>
|
Post Content Displaying Below ALL Shortcodes Content
|
wordpress
|
If possible I want to insert the ID of a post(from a custom post type) into the html of the post itself when its loaded in the viewport. The scenario is that the content of the custom post type is surrounded by a <code> <div> </code> . I want to append an 'id' to the <code> <div> </code> that includes the ID of the post. For example if the custom post type is glossary and the post ID is 351 then the resulting html would be: <code> <div id="glossary351"> Post content </div> </code> I looked at the conditional statements and googled on the subject but found that A lot of applications of finding the Post ID were to do with showing the ID on the page, as opposed to inserting it into the html. My almost non existent PHP skills were not up to fathoming out how to use the conditionals to get the result I need. I'd appreciate any pointers regarding: Is this possible Any examples of how to approach the problem Thanks
|
Try: <code> <div id="<?php the_title(); ?>-<?php the_ID(); ?>"> </code> This should give you a result of: <code> <div id="Post Title-PostID"> </code> Giving you a unique wrapper for each post.
|
Is it possible to read the ID of a post and then insert it into the html of the post?
|
wordpress
|
I am attempting to resolve a problem I continue to have with the media library. Essentially, what I am looking to do is "automatically" assign media which is uploaded from a custom post type "edit post" page to a predefined category. Based on other answers on this site I have found various people discussing solution (one of these links is below) which allow you to "manually" assign a category to media library elements. My aim however is to somehow define specific post types and the associating category which should be applied. At the same time I would also like the ability to restricting a "specific post type" so when the media library lightbox is requested from the edit post page that the "media library" ONLY shows items within the categories I define. I know this might sound a bit confusing so let me provide a quick example. Let's say I have a custom post type called "employee news". Now let's say that someone proceeds to add/edit a post within this custom post type. Let's further assume that he now uses the editor to add content and now want to add one/more images. As expected he would select the "add media" button above the editor and either (a) upload a new image or (b) select an image from the media library. THESE are the two areas I am talking about. What I need is the correct code to put into my functions.php file so that either one or both of the following can be set individually: (a) Ability to specify a custom post type and define the hidden category name to be associated with any file uploaded to the media library. (b) Ability to specify a custom post type and define the "restricted categories" to be used when presenting the files available for the user to select from. How can this be achieved correct? Related Question related to Category assignment of media elements: stackexchange-url ("Can I add a Category Metabox to attachment?") Related Question related to conditional logic related to the media library: stackexchange-url ("Conditional add_filter?")
|
I think you can go about the filter <code> list_terms_exclusions </code> , but i don`t tested. example: <code> function fb_list_terms_exclusions($args) { if ( 'media-upload-popup' != $where ) return $where; if ( !current_user_can('manage_categories') ) $where = " AND t.slug NOT IN ('uncategorized', 'category-2')"; // slug of categories return $where; } add_filter( 'list_terms_exclusions', 'fb_list_terms_exclusions' ); </code> update for the comments to this asnwer: an example to find the post types; at first a small example to use the default variables and after this an funtion for return an value: <code> /** * Include my scripts * * $pagehook for check, if this the right page * $post_type for check, if this the right post type */ function fb_post_type_script($pagehook) { global $post_type; $pages = array( 'edit.php', 'post.php', 'post-new.php' ); if ( in_array( $pagehook, $pages ) && $post_type == 'my_post_type' ) { wp_enqueue_script( 'my_script_example_key', plugins_url( 'js/my_example_script.js', __FILE__ ), array( 'jquery', 'my_other_example_script_key' ), '1.0.0' ); } } add_action( 'admin_enqueue_scripts', 'fb_post_type_script' ); </code> alternative you use a custom function to find the post type: <code> /** * Return post type * * @return string $post_type */ private function get_post_type() { if ( !function_exists('get_post_type_object') ) return NULL; if ( isset($_GET['post']) ) $post_id = (int) $_GET['post']; elseif ( isset($_POST['post_ID']) ) $post_id = (int) $_POST['post_ID']; else $post_id = 0; $post = NULL; $post_type_object = NULL; $post_type = NULL; if ( $post_id ) { $post = get_post($post_id); if ( $post ) { $post_type_object = get_post_type_object($post->post_type); if ( $post_type_object ) { $post_type = $post->post_type; $current_screen->post_type = $post->post_type; $current_screen->id = $current_screen->post_type; } } } elseif ( isset($_POST['post_type']) ) { $post_type_object = get_post_type_object($_POST['post_type']); if ( $post_type_object ) { $post_type = $post_type_object->name; $current_screen->post_type = $post_type; $current_screen->id = $current_screen->post_type; } } elseif ( isset($_SERVER['QUERY_STRING']) ) { $post_type = esc_attr( $_SERVER['QUERY_STRING'] ); $post_type = str_replace( 'post_type=', '', $post_type ); } return $post_type; } public function example() { $post_type = $this->get_post_type(); // FB_POST_TYPE_1 is defined with my post type if ( FB_POST_TYPE_1 == $post_type ) { // tue etwas, wenn wahr } } </code>
|
How do I modify the "Insert Media" lightbox in the admin to only show media items from a category?
|
wordpress
|
I found a plugin called Multiple Post Thumbnails and followed the directions in getting it set up. Everything shows up correctly in the admin dashboard (i.e. shows two sections to upload two separate thumbnails) but after I set the two thumbnails for each post and view the page which displays those posts, only the first post I set the thumbnails for show up. This is the code I used in my theme's functions.php: <code> $thumb = new MultiPostThumbnails( array( 'label' => 'Larger Image', 'id' => 'image2', 'post_type' => 'projects' ) ); </code> And here is my Projects page which is the page where the posts are displayed: <code> <section id="content"> <section id="projects-list"> <?php $c=0; $i=1; $temp = $wp_query; $wp_query = null; $wp_query = new WP_Query(); $wp_query->query('post_type=projects' . '&paged=' . $paged . '&posts_per_page=6'); while ( $wp_query->have_posts() ) : $wp_query->the_post(); $c++; ?> <article class="post<?php if($i%3 == 0) { echo ' right'; }; $i++; ?>" id="post-<?php the_ID(); ?>"> <section class="entry"> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"> <?php if (class_exists('MultiPostThumbnails') && MultiPostThumbnails::has_post_thumbnail('projects', 'secondary-image')) : MultiPostThumbnails::the_post_thumbnail('projects', 'secondary-image'); endif; ?> </a> </section> <section class="description"> <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2> <time class="post-date" datetime="<?php the_time('c'); ?>"><?php the_time('F j, Y'); ?></time> </section> </article> <?php endwhile; wp_pagenavi(); $wp_query = null; $wp_query = $temp; wp_reset_query(); ?> <?php if( $c < 6 ) : for ($dummy= $c; $dummy < 6; $dummy++) : ?> <article class="post<?php if($i%3 == 0) { echo ' right'; }; $i++; ?>" id="post-<?php the_ID(); ?>"> <img src="<?php bloginfo('template_url'); ?>/images/dummy-post.gif" alt="Post coming soon!" /> </article> <?php endfor;?> <?php endif;?> </section> <section id="map"> <img src="<?php bloginfo('template_url') ?>/images/interactive-map.jpg" alt="Interactive Map" /> </section> <section id="youtube-subscribe"> <iframe id="fr" src="http://www.youtube.com/subscribe_widget?p=mysteryguitarman"></iframe> </section> </section> </code> Here is a screenshot of what the page looks like. Note only "Project 6" has the thumbnail showing (Project 6 was the first post I uploaded a second thumbnail to) when I uploaded second thumbnails for each of those posts. Does anybody have experience with this plugin? Also, would anyone suggest an alternative no-plugin way to achieve the same thing? Basically, I just want to be able to upload two separate thumbnails for each post in the Projects post type so one shows on the home page and another (larger) one shows on the Projects page. An ideal setup would be to have just one large image I upload which gets shown on the Projects page and it would automatically get cropped into a smaller thumbnail which I can then use for the home page. Anyhow, any advice/help would be much appreciated. Thank you for reading this long post!
|
Dude, you're doing this the hard way. You can do what you want totally with a single 'featured post thumbnail'. Read the documentation about thumbnail sizes in themes. You can inject custom thumbnail sizes in your themes funcitons.php and then give them as a parameter to the (get_)the_post_thumbnail() function. Please just read the documentation at the Codex - start with the function reference page for <code> the_post_thumbnail() </code> , maybe - and you'll see. Wordpress does automatically resize and crop the image for you, if only you tell it to do so.
|
Multiple featured image thumbnails for post types (Multiple Post Thumbnails plugin)
|
wordpress
|
I have a widget area on my posts category pages and am wondering if there is a way to dynamically add a link to the first post as well as the current post of the category. I think the first post can be hardcoded since it will never change, but the current one will. I wonder what sort of php madness that can do this? I know I know, you are asking why not just use the post navigation that already comes right... Well clients being what they are. Any help is greatly appreciate and will very much aid in my not walking of a cliff.
|
you can use wp-pagenavi and set the "number of pages to show" to 3 so you will get [first] [6] [ 7 ] [8] [last] now if you just need the names of the post then you could do something like this: <code> global $wp_query; //curent post $thePostID = $wp_query->post->ID; $my_query = new WP_Query(array('cat' => get_query_var('cat'))); $count = 0; $curent_count = 0; if ($my_query->have_posts()){ while ($my_query->have_posts()){ $no_repeat = array(); $my_query->the_post(); $count = $count + 1; if ($count = 1 ){// the first post in the category if (!in_array($post->ID,$no_repeat){ echo '<a href="'.the_permalink().'">'.the_title().'</a> '; $no_repeat[] = $post->ID; } } if ($count = ($thePostID -1) ){//previous post if (!in_array($post->ID,$no_repeat){ echo '<a href="'.the_permalink().'">'.the_title().'</a> '; $no_repeat[] = $post->ID; } } if ($count = $thePostID){//Current post if (!in_array($post->ID,$no_repeat){ echo '<a href="'.the_permalink().'">'.the_title().'</a> '; $no_repeat[] = $post->ID; } } if ($count = ($thePostID + 1)){//Current post if (!in_array($post->ID,$no_repeat){ echo '<a href="'.the_permalink().'">'.the_title().'</a> '; $no_repeat[] = $post->ID; } } } } </code> Hope this helps.
|
Post Navigation
|
wordpress
|
I have a previously created thread here, but was recommended to make a new one: stackexchange-url ("I need basic help with custom post types.") Basically here's my project: I have to create a back-end wordpress gui user input section. The user will enter details about their projects like name, location, what it is, some other details. A page will display the top 9 recent or so in a 3x3 grid. There will be a search bar to search projects for related tags. I need to set it up where only certain user accounts can access this post type to upload projects. I have currently: used functions.php to setup my post type and it works used simple forms plugin to create forms on the add new page Background: I am a pretty entry level person in wordpress, and slightly overwhelmed right now. But, it's slowly coming together. Any input on structure or anything would be appreciated. Update: I have created the forms, but I need to know what to put in the single-projects.php to display the content from the forms. Thank you so much
|
There are several user access plugins available, including one called Members . The settings panel for the Members plugin is in Settings > > Members Components. From there you can enable what you want. To edit roles you have to enable the Edit Roles component, then go to Users > > Roles. Click on the role you want to edit. You will see a list of all available capabilities with the ones that are enabled checked and in bold. There are six text boxes at the bottom of the page allowing you to add six capabilities at a time. Just type in the names there and they will be added to that role and to the list of capabilities. To add them to another role, just select them in the list.
|
create a back-end wordpress content submission using custom post type
|
wordpress
|
I'm using the following code I got from the Wordpress codex : <code> <?php // Displaying Child pages of the current page in post format $mypages = get_pages('child_of='.$post->ID.'&sort_column=post_date&sort_order=desc'); $count = 0; foreach($mypages as $page) { $content = $page->post_content; if(!$content) continue; if($count >= 20) break; $count++; $content = apply_filters('the_content', $content); ?> <div class="content-block"> <h2><a href="<?php echo get_page_link($page->ID) ?>"><?php echo $page->post_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(); ?></a> <?php echo $content ?> </div> <?php } ?> </code> I tried the following code to get the featured image of the page: <code> <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(); ?></a> </code> and this one too: <code> $thumbnail = apply_filters('the_post_thumbnail', $thumbnail); </code> But it doesn't get the featured image. Any suggestions?
|
You're not inside a regular loop, or at least not one where global post variables are set, so <code> the_post_thumbnail </code> does not have an ID to fetch a thumbnail for.. Use <code> get_the_post_thumbnai( $page->ID ) </code> instead and it should work fine.
|
Displaying Child pages of the current page in post format and their thumbnails (featured image)?
|
wordpress
|
I have a custom post type called 'projects' ( pastebin ) and I have a page called Projects set up in my dashboard which is set to display the Projects template. ( pastebin ) The problem is when I use WP_PageNavi to incorporate pagination and click on page 2, I get an error 404. I read somewhere that this is because custom post types and pages can't have the same name. And I've found that to be true because I tried changing the page name to "Projects 2" and it worked. But when I change the name of the custom post type, that gets reflected in the url. So if I change the custom post type to 'projects2' instead of just 'projects', the url now looks like this: mysite.com/projects2/single-post I have my custom permalinks set to /%category%/%postname%/ by the way. Likewise, I can't change the name of the page to 'Projects 2' for aesthetic reasons. So how would I get around this? This has been driving me crazy for many hours. I would really appreciate any helpful advice!
|
As you can see in the rewrite analyzer, <code> /projects/page/2/ </code> sets <code> projects=page&page=/2 </code> instead of <code> pagename=projects&paged=2 </code> as we would like. So you just need to add a rewrite rule for this special case (in the <code> register_projects() </code> function, after you register your custom post type, would be a good place): <code> add_rewrite_rule( 'projects/page/([0-9]+)/?$', 'index.php?pagename=projects&paged=$matches[1]', 'top' ); </code> Remember to flush your rewrite rules, by visiting the Permalinks page or by some other way.
|
Custom post type archive with pagination?
|
wordpress
|
I am displaying a post gallery inside a custom post type, using the following in my single-custom.php template: <code> <?php echo do_shortcode('[gallery id="'.$post->ID.'" link="file" columns="5" orderby="menu_order"]'); ?> </code> One of the things included in the output is <code> title="filename" </code> in the <code> <img> </code> tag, like so: <code> <img width="150" height="150" src="http://mydomain.com/wp-content/uploads/DSC_0036-150x150.jpg" class="attachment-thumbnail" alt="DSC_0036" title="DSC_0036" /> </code> I do not want to output the title attribute. Mostly, I don't want crappy filenames in the hover-over text, but there are hundreds of images and I'm not prepared to go into the Media Gallery and edit the title for each one. I'd prefer to also change the <code> alt </code> attribute to the post name, perhaps. Is there a way to filter the gallery to output the post name in the alt and title attributes, instead of the filename?
|
The <code> [gallery] </code> shortcode is parsed by <code> gallery_shortcode() </code> , which calls <code> wp_get_attachment_link() </code> , which in turns calls <code> wp_get_attachment_image() </code> . This latter function writes the <code> <img> </code> tag with the <code> title </code> attribute. You're lucky, because the attributes are filtered through <code> wp_get_attachment_image_attributes </code> , so you can hook into that and remove the <code> title </code> . To do this, you attach the hook before you call the shortcode and remove it after you did this. You can either do this in your template if it's a one-off, or, if you are more advanced, you "hijack" the <code> [gallery] </code> shortcode with your own function that adds the hook, calls the original <code> gallery_shortcode() </code> function, and removes the hook.
|
How do I filter title and alt attributes in the gallery shortcode?
|
wordpress
|
I would like to manually edit the code my my wordpress pages. The WP interface only allows me to individually edit the CSS or PHP. The Page Edit feature gives me access to a certain part of the code, excluding the Body Tag. Kindly help me locate my files on the server. Thanks for your help! :)
|
WordPress stores content in the database, there are not any physical files with the content of the pages(or posts). The theme's template files control how to render and display your site, you can find those files in <code> wp-content/themes/YOUR-ACTIVE-THEME-NAME-HERE </code> .. You can find lots of information on themes and their development here. http://codex.wordpress.org/Theme_Development Additional information and guidance can be found through the other documentation listed in the resources section of the above linked page, here it is for quick reference. http://codex.wordpress.org/Theme_Development#Resources_and_References A quick search of the WordPress forums would have also provided you with the information needed(just something to note). http://wordpress.org/search/where+is+content+stored?forums=1 Hope that helps.
|
In which directory do I find the HTML file of my wordpress pages?
|
wordpress
|
I have a wordpress custom theme that started giving a weird error out from the blue. Every time you post a comment it will return a javascript alert with all the content of the page. I haven't made any changes to the theme that would have effect in this so I have no idea why is this happening, I tried removing all the javascript of the theme, updating the comments related files in the server (the same error happens locally) and replacing the comments.php with a generic template or using <code> <?php comment_form(); ?> </code> instead of <code> <?php comments_template(); ?> </code> . You can test it in http://www.faf.fi/uutiset/faf-international-ohjaajakoulutukset-alkavat-pian/ (text in Finnish, Nimi = Name, Sähköposti = Email). Any ideas?
|
I tried removing all the javascript of the theme, updating the comments related files in the server (the same error happens locally) The problem is a result of this file(you obviously didn't disable that one in testing). http://www.faf.fi/wp-content/themes/faf/scripts/js/functions.js Blocking that script in my browser resolves the issue, but i think it's this area of the script specifically that's failing.. <code> $('form').submit( function(){ var form = $(this); if ( validateForm( this ) ) { $.post( form.attr('action'), //url A string containing the URL to which the request is sent form.serialize(), //data A map or string that is sent to the server with the request. //success A callback function that is executed if the request succeeds function(response, status, request){ // do something with response alert( stripTags(response) ); } //dataType The type of data expected from the server (text, xml, json) ); } //Prevent default return false; }); </code> The alert you're seeing is generated by that function. I have no idea what the cause of your issue is nor how to resolve it(i'm no JS expert), but i'm pretty certain this function is the source of your problem. Hope that helps.
|
Comment form in wordpress theme returns a javascript alert
|
wordpress
|
I have a friend who has a background in graphic design. She has taken a particular interest to web design. I am a software developer/system administrator, not a web developer, and I'm certainly not a designer; I couldn't design a good-looking site to save my life. However, I am aware of the technologies involved and the skills that she would need to acquire. For the first book, I have recommended Head First HTML with CSS & XHTML for it's non-threatening, yet practical approach to teaching. This book introduces the reader to the modern technologies which are used by the browser to display web pages, and explains how to use them. As most of you know, that is only the tip of the iceberg. Most sites today rely on some sort of back-end (CMS, et cetra). So, any web designer should be able to work with at least one kind of CMS. I think WordPress would be a great place to start (and who knows, maybe even specialise in) because it is highly scalable, yet easy to use for developers, designers, server administrators, and end users alike. It is used by individuals, small businesses, and enterprise. At the same time, it is simple enough to design for that I don't think it would scare her off with too much programming. Disclaimer: I use WordPress for most of my personal sites, so I am more than a tad bias. However, I'm not sure which book/tutorial to recommend to her for WordPress design. Below is a list of books which I have found, and my thoughts on them: Head First WordPress: A Brain-Friendly Guide to Creating Your Own Custom WordPress Blog - It explains in plains in plain English what WordpPess is, how it works, and how to use it. I love the format for this purpose, but it has a very short theme chapter. It may be good for supplementary reading. Smashing WordPress: Beyond the Blog (Smashing Magazine Book Series) - It is well laid out, and up to date. It has an entire section on WordPress theme development. But, I would prefer a book which specialises in theme development. WordPress 2.8 Theme Design - This book is written to be a step-by-step guide to designing, building, and tweeking a WordPress theme. But, it's a bit out of date. Could this be a problem? Build Your Own Wicked Wordpress Themes - I have mixed feelings about this book. Is moderen, design orientated, and nice to look at. However, it bases much of of the work on the Automattic theme framework. On one hand, this minimises hand-coding, making it easy to learn and use, especially for someone without a background in programming. On the other hand, I'm concerned that such an approach might not prepare one for the "real world" of theme development, if one ends up applying for work at a design company, rather than doing freelance work. Is this a valid concern? How widely are frameworks used? As I said, web design/development is not my field, so I don't know much about the industry. Any help is appreciated.
|
I thought Build Your Own Wicked Wordpress Themes was really helpful. Note that the book actually uses the Thematic Framework for point of reference and example code. A book that has been fantastic, and therefore I recommend, is called Digging Into WordPress.
|
Which WordPress books should I recommend to a beginning web designer?
|
wordpress
|
I have <code> <?php $folioPosts = get_posts(array('category_name' => 'portfolio', 'numberposts' => 3)); if ($folioPosts->have_posts()) : foreach ($folioPosts as $folioPost) : setup_postdata($folioPost); ?> <article class="col3"> <?php if (has_post_thumbnail()) : ?> <p><a href="<?php the_permalink() ?>"><?php the_post_thumbnail() ?></a></p> <?php endif; ?> <p><a href="<?php the_permalink() ?>"><?php the_title() ?></a></p> </article> <?php endforeach; else : ?> <p>No folio posts to display ...</p> <?php endif; ?> </code> I am getting Fatal error: Call to a member function have_posts() on a non-object ... I think its because my args to get_posts are wrong. Did I do something wrong?
|
get_posts() </code> returns an array, not a <code> WP_Query </code> object. If you want to use <code> have_posts() </code> and related functions, use a "raw" <code> WP_Query </code> object.
|
Am I using get_posts wrong?
|
wordpress
|
I have installed wordpress for my site. I am trying to insert posts using function <code> wp_insert_post() </code> from my self-made script. <code> content of my post contains video-embed code of google. <object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/-T9omX2XD2s?fs=1&hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/-T9omX2XD2s?fs=1&hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object> </code> when I am running script to insert this content in my post, by my surprise this code got stripped out from post. I have surfed the internet and wordpress forum, I found that It is a SECURITY feature of wordpress. I want to remove this security feature from my own wordpress site. so what should I do to opt-out this stripping function? so that I can add above html code as a content of a post. Please give me the function name which is stripping out this codes from my content, so I can stop it working. My complete code. <code> <?php require('./wp-blog-header.php'); $contactObject['postTitle'] = $_POST['post_title']; $contactObject['videoCode'] = $_POST['videoCode']; $contactObject['description'] = $_POST['description']; $categoryIds = $_POST['categories']; insertPosts($contactObjects,$categoryIds); function insertPosts($contactObjects,$categoryIds) { $videoCode = $contactObject['videoCode']; $videoEmbedCode = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/'.$videoCode.'?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'.$videoCode.'?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>'; $content = ''; if($contactObject['description'] != '') { $content .= '<p>'.$contactObject['description'].'</p></br>'; } $content .= $videoEmbedCode; // Create post object $my_post = array( 'post_title' => $contactObject['postTitle'], 'post_content' => $content, 'post_status' => 'publish', 'post_author' => 1, 'post_category' => $categoryIds, ); // Insert the post into the database $postId = wp_insert_post( $my_post ); } ?> </code>
|
I'm only guessing but it sounds like your insert method is tripping up on one of WordPress's filter functions (e.g. wp_filter_kses ). If you need a more exact answer, please update your question to include some of the code you're using to insert the post content.
|
want to stop stripping out from my post content
|
wordpress
|
My single.php file has the following code: <code> <?php // Set and display custom field $intro_image = get_post_meta($post->ID, 'Intro Image', true); ?> <div class="block-1"> <img src="<?php echo $intro_image; ?>" alt="" /> </div> <?php ?> </code> The user will have to type Intro Image (once) in the 'Name' field in order to see it next time in the drop-down list. I think it would be better if the user can see 'Intro Image' right after installing my Wordpress theme (I feel that the user should select options that are available, not write them down themselves). I'm not sure if what I'm saying make sense. But how to have those 'Names' available in the drop-down list before writing them?
|
your best option is to create a custom meta box with-in your theme and then the user will have it no matter if he typed it once before. <code> // Hook into WordPress add_action( 'admin_init', 'add_custom_metabox' ); add_action( 'save_post', 'save_custom_intro_image' ); /** * Add meta box */ function add_custom_metabox() { add_meta_box( 'custom-metabox', __( 'Intro Image' ), 'intro_image_custom_metabox', 'post', 'side', 'high' ); } /** * Display the metabox */ function intro_image_custom_metabox() { global $post; $introimage = get_post_meta( $post->ID, 'intro_image', true ); ?> <p><label for="intro_image">Intro Image:<br /> <input id="siteurl" size="37" name="intro_image" value="<?php if( $introimage ) { echo $introimage; } ?>" /></label></p> <?php } /** * Process the custom metabox fields */ function save_custom_intro_image( $post_id ) { global $post; if( $_POST ) { update_post_meta( $post->ID, 'intro_image', $_POST['intro_image'] ); } } </code> Hope This Helps
|
Making custom field's 'Name' available in the dropdown list by default in a theme?
|
wordpress
|
Let's say I have a single.php file with a certain layout (graphic intensive). I want to create a sort of plain-text version of the same page that is only called when the user clicks the provided link. I can create single-plaintxt.php but how would I go about generating a link and/or function that would only load the page contents using that file when clicked? Thanks!
|
you can do it like this: <code> //add my_print to query vars function add_print_query_vars($vars) { // add my_print to the valid list of variables $new_vars = array('my_print'); $vars = $new_vars + $vars; return $vars; } add_filter('query_vars', 'add_print_query_vars'); </code> then add a template redirect based on that query_var: <code> add_action("template_redirect", 'my_template_redirect_2322'); // Template selection function my_template_redirect_2322() { global $wp; global $wp_query; if (isset($wp->query_vars["my_print"])) { include(TEMPLATEPATH . '/my_print_themplate.php'); die(); } } </code> create a new file in your theme directory named "my_print_themplate.php" an paste this code there. <code> <?php define('WP_USE_THEMES', false); echo "<h1>printer friendly version:</h1>\n"; query_posts('p='.$_GET['pid']); if (have_posts()){ while ( have_posts() ) { the_post(); the_content(); } }else{ echo 'nothing found'; } ?> </code> and now all you have to do is create a link with ?my_print=$post_id in your regular single loop. hope this helps
|
Load post with a different template?
|
wordpress
|
In the script below, the post__not_in argument does not appear to be working unless I hardcode the post ids inside the array(). Anything stand out? If an item is in the category, but also in the post__not_in, what get's precedent? get_option('sticky_posts') is a single item array with var_dump = array(1) { [0]=> int(6) } <code> $myposts = get_posts( array('cat' => "$cat,-$catHidden", 'post__not_in' => array($post->ID, get_option('sticky_posts')), 'numberposts' => 10; ) ); foreach($myposts as $idx=>$post){//do something} </code>
|
try: <code> $not_in = get_option('sticky_posts'); $not_in[] = $post->ID; $myposts = get_posts( array('cat' => "$cat,-$catHidden", 'post__not_in' => $not_in, 'numberposts' => 10; ) ); foreach($myposts as $idx=>$post){//do something} </code> hope this helps
|
What's wrong with this post__not_in argument?
|
wordpress
|
I currently have my blog at <code> alexangas.com </code> and would like to move it to <code> www.alexangas.com </code> . Is this as simple as changing the WordPress Address and Site Address in Settings? How can I ensure that users hitting <code> alexangas.com/someblogpost </code> are automatically redirected to <code> www.alexangas.com/someblogpost </code> ?
|
Yes. I just did an experiment on my own site to verify that changing those settings will redirect between www and non-www as you specify.
|
How do I redirect my blog posts to a subdomain?
|
wordpress
|
How can i get wordpress posts content by post id?
|
Simple as it gets <code> $my_postid = 12;//This is page id or post id $content_post = get_post($my_postid); $content = $content_post->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]&gt;', $content); echo $content; </code>
|
Get wordpress post content by post id
|
wordpress
|
Could somebody help me make a custom page template? I'd like to have a basic page (with sidebars, header and footers) and a table for data. I'd like the data to be taken from custom fields. Something like this: Name: (name key) Location: (location key) etc...
|
Ok, first step is to create a page template, this is the easy part, and there's no query manipulation needed here, you're not changing the query, simply looking at the page that's already in the query, so that's a simple case of creating a basic loop, like so...(noting that i've placed a special page template comment at the top of the code). NOTE: When you save this file in your theme's folder, make sure not to give it the name of a theme template file, so don't call it category.php or archive.php (any filename native to WordPress themes), instead use something unique, eg. customfields-template.php (or whatever you like). <code> <?php /** * Template Name: CustomField Table */ get_header(); ?> <div id="container"> <div id="content"> <?php if( have_posts() ) : ?> <?php while( have_posts() ) : the_post(); ?> <h2><?php the_title(); ?></h2> <?php // Array of custom fields to get(so enter your applicable field keys here) $fields = array( 'field-one', 'field-two' ); // Array to hold data $custom_fields = array(); // Loop over keys and fetch post meta for each, store into new array foreach( $fields as $custom_field_key ) $custom_fields[$custom_field_key] = get_post_meta( $post->ID, $custom_field_key, true ); // Filter out any empty / false values $custom_fields = array_filter( $custom_fields ); // If we have custom field data if( !empty( $custom_fields ) ) $c = 0; ?> <table> <thead> <tr> <th>Field</th> <th>Value</th> </tr> </thead> <tbody> <?php foreach( $custom_fields as $field_name => $field_value ) : $c++; ?> <tr<?php echo ( $c % 2 == 0 ) ? ' class="alt"' : '' ; ?>> <td><?php echo $field_name ?></td> <td><?php echo $field_value ?></td> </tr> <?php endforeach; ?> </tbody> <tfoot> <tr> <th>Field</th> <th>Value</th> </tr> </tfoot> </table> <div <?php post_class(); ?>><?php the_content(); ?></div> <?php endwhile; ?> <?php endif; ?> </div> </div> <?php get_sidebar(); ?> <?php get_footer(); ?> </code> Since you're looking for particular keys and expect singular values, the easiest and most suitable function i feel to use would be <code> get_post_meta </code> , this function can select multiple or single values for a single custom field key(and automatically excludes private meta keys that you'd otherwise get with the <code> get_post_custom_ </code> functions. More on those functions can be found here. http://codex.wordpress.org/Custom_Fields#Function_Reference Create a simple array of the custom field keys to select data from, then loop over them calling <code> get_post_meta </code> with each iteration. Gather that meta data and place it into a new array so it can later be easily filtered of empty/false results(rather then repeated <code> if( $var ) </code> or <code> if(!empty()) </code> calls). Next check the new array has some data, output a table and loop over the new array to build the rows of data. Only thing you need change is this line(these are my test field names).. <code> $fields = array( 'field-one', 'field-two' ); </code> So for example, to get custom fields with the keys, name, gender, job and description.. <code> $fields = array( 'name', 'gender', 'job', 'description' ); </code> NOTES: I took the liberty of adding alternating classes to the table rows I assumed you'd want post title and content to(remove if not needed) HTML markup is based on the TwentyTen theme, if your theme uses different markup you'll need to update the HTML as needed(or you can link me to one of your webpages and i'll refactor the sample code for you) I wasn't sure how you wanted the data displayed in the table, so if you had a different idea about how to layout the data in the table, let me know and i'll refactor the code for you. Let me know if you have any questions regarding the code. :)
|
Custom Page Template
|
wordpress
|
get_terms allows me to get all taxonomy values, but how do I limit this to a certain post? I don't see anyway to feed a specific post ID to get_terms: http://codex.wordpress.org/Function_Reference/get_terms Perhaps there is another way to achieve this?
|
Ahah! I need to use get_the_terms instead, as this will accept a post ID. http://codex.wordpress.org/Function_Reference/get_the_terms
|
How do I get terms as a list for a specific post?
|
wordpress
|
I'm using WPML for multi-language website. It works really well except for custom taxonomies. In admin, I can only join foreign posts to foreign taxonomies (which is exactly what it should do) but on the public area, when retrieving taxonomies it seems that the current language is ignored: I get all taxonomies. Any help would be greatly appreciated ! Thanks.
|
I found out that when retrieving the taxonomy you have to do this : <code> $args = array( 'hide_empty' => true, 'taxonomy' => 'projet_thematique' ); $thematiques = get_terms('projet_thematique', $args); </code> The thing was done by adding the 'taxonomy' as an argument as well. I hope it will be usefull for others ;)
|
WPML taxonomies not translated
|
wordpress
|
I need to showing message in post , but after one month from publish date. I try to make it before ask you, but I can't this is my code <code> $publish_date = $post->post_date_gmt; $today = date('d-m-Y h:i:s'); $nextMonth = mktime(0 , $publish_date('m')+1 , 0 , 0 , 0,0); echo 'Publish Date:'.$publish_date.'<br/>'; echo 'Today Date:'.$today.'<br/>'; echo 'Next Month:'.$nextMonth; if($today => $nextMonth){ echo 'One Month or more for publish post'; } else { echo ''; } </code>
|
Custom conditional I wrote for my theme (mostly to kick some widgets and ads from newer posts), works nicely: <code> function is_old_post( $days = 14 ) { if( !is_single() ) return false; $id = get_the_ID(); $date = get_post_field( 'post_date', $id ); if( strtotime( $date ) < strtotime( "-{$days} days" ) ) return true; return false; } </code>
|
I want to print a message in post " After one month from publish date"
|
wordpress
|
I am using the wordpress menus on a website, but the problem is that one of the links on that menu is www.homepage.com/#order So, when I am on the homepage, both "home" and "order" links on the menu contain the class current_page_item, which with my css it makes them appear both as the active button. How can I make it so the #order link never contains that the current_page_item class? Here's a screenshot of how the menu looks when visiting the homepage and how I set it up on the admin panel: http://img87.imageshack.us/img87/7666/screenshotrq.png On the firebug panel you can see that both www.homepage.com and www.homepage.com/#order menu links contain the current_page_item class. This is the php code I am using to display the menus: <code> <?php $args = array( 'menu' => 'Top Menu', 'sort_column' => 'menu_order', 'container_class' => ' ' ); wp_nav_menu($args); ?> </code>
|
a bit hacky, but it works: <code> add_filter('nav_menu_css_class', 'remove_some_menu_classes', 420 ,3); function remove_some_menu_classes($classes, $item, $args){ if(strpos($item->url, '#order') !== false) // in the 2nd array put the classes you want removed return array_diff($classes, array('current_page_item', 'current-menu-item')); return $classes; } </code>
|
Wordpress menu: How to make www.link.com/#name never contain current_page_item class?
|
wordpress
|
How can I get the post id from a permalink like "http://localhost/wordpress/animals/cat" in functions.php, I have tried url_to_postid() and get_page_by_path() but none seem to work.
|
Hi @Tirithen: Have you tried (which assumes your custom post type is <code> 'animal' </code> and not <code> 'animals' </code> ): <code> $post = get_page_by_path('cat',OBJECT,'animal'); </code>
|
How to get the post id from a permalink?
|
wordpress
|
I'm probably missing something unless it's really not possible, for some reason I can't get my function to only execute on the new and edit page of a custom post type (the new not being a problem): I'm currently using: <code> if ((isset($_GET['post_type']) && $_GET['post_type'] == 'events') || (isset($post_type) && $post_type == 'tf_events')) { add_action('admin_init', "admin_head"); } </code> However this only works for adding a new post where the URL is: <code> /post-new.php?post_type=events </code> But for editing a post it doesn't work, where the URL is: <code> /post.php?post=12&action=edit </code> (although the post type isn't added to the link attribute) WORKING CODE (See Mark's response below): <code> // 7. JS Datepicker UI function events_styles() { global $post_type; if( 'tf_events' != $post_type ) return; wp_enqueue_style('ui-datepicker', get_bloginfo('template_url') . '/css/jquery-ui-1.8.9.custom.css'); } function events_scripts() { global $post_type; if( 'tf_events' != $post_type ) return; wp_deregister_script('jquery-ui-core'); wp_enqueue_script('jquery-ui', get_bloginfo('template_url') . '/js/jquery-ui-1.8.9.custom.min.js', array('jquery')); wp_enqueue_script('ui-datepicker', get_bloginfo('template_url') . '/js/jquery.ui.datepicker.min.js'); wp_enqueue_script('custom_script', get_bloginfo('template_url').'/js/pubforce-admin.js', array('jquery')); } add_action( 'admin_print_styles-post.php', 'events_styles', 1000 ); add_action( 'admin_print_styles-post-new.php', 'events_styles', 1000 ); add_action( 'admin_print_scripts-post.php', 'events_scripts', 1000 ); add_action( 'admin_print_scripts-post-new.php', 'events_scripts', 1000 ); </code>
|
Ok, total revision on my original answer, which just turned into a mess. The issue with your code is that you're firing on init, this covers every admin page, and additionally it's too early to check admin vars to work out the current page(though you could just check <code> $_GET </code> if you really need to run code that early). You want to specifically hook to the post edit pages, though you've not indicated you need to run on the post listing to(edit.php), so i'll exclude that from the examples that follow. You can hook to a few different actions that occur inside the admin head, and do whatever you need to do there and be able to reliably check the post type by giving <code> $post_type </code> scope inside your callback function. So your callback would go a little something like this.. <code> function mycallback() { global $post_type; if( 'events' != $post_type ) return; // Do your code here } </code> What action you want that hooked onto is down to what you want to run at that point, if you're not doing anything in particular but want to execute something, then perhaps the generic admin head hook will be suitable.. <code> add_action( 'admin_head-post.php', 'mycallback', 1000 ); add_action( 'admin_head-post-new.php', 'mycallback', 1000 ); </code> If you're loading a script, then you might use.. <code> add_action( 'admin_print_scripts-post.php', 'mycallback', 1000 ); add_action( 'admin_print_scripts-post-new.php', 'mycallback', 1000 ); </code> If you're loading a stylesheet, then possibly.. <code> add_action( 'admin_print_styles-post.php', 'mycallback', 1000 ); add_action( 'admin_print_styles-post-new.php', 'mycallback', 1000 ); </code> Else i'll need to know more about what you're doing... :)
|
Selecting New & Edit Page for Custom Post Types
|
wordpress
|
I have a wordpress site running on one domain that has the main 'client' domain for the site redirecting to it. I've got my Wordpress Address/Site Address entered correcting in Wordpress, and the .htaccess is formatted properly afaik. Everything else seems to work properly other than this issue. So I have Janrain Engage, SimpleModal Jainrain Engage and SimpleModal Login. Everything was working fine when we were building the site on the hosted domain. When it came time to switch the live sites and redirect the published URL to our host, things went all screwy. So, basically; If you go to www.publishedurl.com and attempt to login with your Wordpress user/pass the loggin in progress bar appears and just hangs indefinitely. If you try and loging with your Facebook ID it appears to successfully log you in, but on www.publishedurl.com it shows you as not logged in. If you then go to www.backendurel.com/wordpressinstall/ it will show you logged in with Facebook -- and back there, if you attempt to log-in, that works fine as well. I've updated Wordpress and the plugins, I've scoured the wp_options table in the database for a setting that might be wrong. I completely uninstalled and reinstalled everything, created new Jainrain and Facebook widgets. ATM I have the files and folders of all 3 plugins set to 775 permission. We also use Mingle and a few other widgets that block users from viewing the WP backend daskboard and allow front-end posting. PS. Actually, during the course of this whole re-install I've now broken everything at the www.backendurl.com/wordpressinstall... same action... endless "loggin in" progress bar... had to pull the php redirect off my wp-login page... ugg.. help please! =D
|
Can you try this fix and see if it resolved your issue?
|
Janrain/Simple Modal under Redirected Domain
|
wordpress
|
<code> $args = array( 'post_type' => 'attachment', 'numberposts' => null, 'post_status' => null, 'post_parent' => $post->ID ); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $attachment) { echo apply_filters('the_title', $attachment->post_title); the_attachment_link($attachment->ID, false); } } </code> In the code above, theres exist a way to get: All attachments links except featured image. All PDF attachments links only. I was reading: http://www.wprecipes.com/how-to-show-wordpress-post-attachments http://johnford.is/programmatically-pull-attachments-from-wordpress-posts/
|
For the first one, you can add <code> 'exclude' => get_post_thumbnail_id() </code> as a parameter (as shown here). For the second one, you can add <code> 'post_mime_type' => 'application/pdf' </code> , but I'm not sure that would always work, afaik, pdfs have more than one mime type.
|
Get all post attachments except featured image
|
wordpress
|
What is the best way to strip *the_content* of html tags and needless spaces on the front end? I'm building a special use theme that needs to allow users who can edit_post to make changes on the front end, but I only want this text area to support plain text. My current code: <code> <?php if ( !current_user_can( 'edit_post', $post_ID ) ) : the_content('Read more on "'.the_title('', '', false).'" &raquo;'); else: ?> <textarea class="grid_22"> <?php the_content('Read more on "'.the_title('', '', false).'" &raquo;'); ?> </textarea> <?php endif ?> </code> produces this: How can I make it look like normal text? Users who edit copy on the front end will not use the backend WYSIWYG editor so I don't have to worry about formats being over written.
|
You will have to worry about formats beeing over written. Ex. <code> <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. ____Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua._____ At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> </code> Ends up with having the part between the "_" over written. Even if you edit it as plain text, you will loose the closing and opening paragraph, so two paragraphs become only one. Everything else you asked for can be done with filters on the_content or get_the_content (please take a look at the codex for further explanation). You'll need to use str_replace or preg_replace (native php functions, please see php.net for explanation) inside those filters.
|
Best way to strip the_content of html on the front end?
|
wordpress
|
Based on the passion engendered with the responses to this question. It appears that the answer is a resounding "Nothing!" or "leave it to plugin developers to handle, WP is already secure enough"... So I guess I'm way off base with the question? It appears to have stirred a hornet's nest and that was not the intent. Never the less, here's the real world outcome... I just got an email from one of my customers who had 12 of his sites hacked because an attacker cracked his password. His comments opened my eyes a bit to the possibilities for some very easy options that could be added to the WordPress core in order to help make WP sites less prone to these kinds of attacks. The simplest thing a user can do is to change the default username. I would guess that over 90% of live WP sites have an "admin" user profile that may or may not be used, but that obviously has full rights and permissions. An attacker's job is already half done! But WP core could be enhanced with some very simple security options too. How hard would it be to add... Failed login attempts lockout (user defined setting) Regulate the time between failed login attempts (user defined setting in seconds) IP range restriction (set a list of IPs from which logins are accepted) These are just a few things off the top of my head. I'm sure you guys have some better options too. And the point of my question is not what "users" should do to enhance security, that's a whole other question. I'm asking what steps WP could take to provide some OPTIONS, nothing mandatory, but things that plugin developers are currently having to fill gaps where stuff should be part of every default WP installation (IMHO). Are any of these kinds of enhancements planned for near term WP releases?
|
RE: Username - admin Since version 3.0 the installer asks the user to provide a username for the main account, you obviously won't get this option if you upgrade from an older version(because it's not a new installation). You can see an image of this here: http://codex.wordpress.org/Installing_WordPress#Step_5:_Run_the_Install_Script RE: Blocking malicious users There's no real effective way to do it, because any information you can obtain and hold about a user can be spoofed and changed within moments, you run the risk of blocking legitimate users. RE: Failed login attempts This could be useful, but there's always the possibility a malicious user locks out an admin(or another user) from their own installation simply by purposely trying to login to that user's account with invalid login credentials. Regulating the time between login attempts might help but in honestly any smart hacker would automate the procedure anyway and this becomes a moot point to some degree(but yeah sure, it will stop a few). That's just my opinion on those specific points, take it as you will.. :)
|
Should WordPress Add Options to Enhance Security or Leave it to plugin developers?
|
wordpress
|
I have a custom post type "Listing" and I want to get all Listings that have a custom field <code> gateway_value != 'Yes' </code> , and order the results by another custom field, <code> location_level1_value </code> . I can get the queries to work separately, but I can't combine them: Query 1 (sort by location): <code> $wp_query = new WP_Query( array ( 'post_type' => 'listing', 'post_status' => 'publish', 'posts_per_page' => '9', 'meta_key' => 'location_level1_value', 'orderby' => 'location_level1_value', 'order' => 'ASC', 'paged' => $paged ) ); </code> Query 2 (custom field value != Yes): <code> $wp_query = new WP_Query( array ( 'post_type' => 'listing', 'posts_per_page' => '9', 'post_status' => 'publish', 'meta_key' => 'gateway_value', 'meta_value' => 'Yes', 'meta_compare' => '!=', 'paged' => $paged ) ); </code> Combined query: I looked at the codex for help with this, but the following query does not work: <code> $wp_query = new WP_Query( array ( 'post_type' => 'listing', 'posts_per_page' => '9', 'post_status' => 'publish', 'meta_query' => array( array( 'key' => 'gateway_value', 'value' => 'Yes', 'compare' => '!=' ), array( 'key' => 'location_level1_value' ) ), 'orderby' => "location_level1_value", 'order' => 'ASC', 'paged' => $paged ) ); </code> What am I doing wrong with the combined query? [UPDATE]: So now that 3.1 has been released, the combined query above still does not work. I do get results, just not sorted correctly. [UPDATE]: <code> var_dump($wp_query->request) </code> gives the following: <code> string(527) " SELECT SQL_CALC_FOUND_ROWS wp_7v1oev_posts.* FROM wp_7v1oev_posts INNER JOIN wp_7v1oev_postmeta ON (wp_7v1oev_posts.ID = wp_7v1oev_postmeta.post_id) INNER JOIN wp_7v1oev_postmeta AS mt1 ON (wp_7v1oev_posts.ID = mt1.post_id) WHERE 1=1 AND wp_7v1oev_posts.post_type = 'listing' AND (wp_7v1oev_posts.post_status = 'publish') AND wp_7v1oev_postmeta.meta_key = 'gateway_value' AND CAST(wp_7v1oev_postmeta.meta_value AS CHAR) != 'Yes' AND mt1.meta_key = 'location_level1_value' ORDER BY wp_7v1oev_posts.post_date DESC LIMIT 0, 9" </code>
|
You could use the query to filter the content as you intended by using the 'meta_query' with filtering options, and for the order part, just add/modify the following parameters: 'orderby' => 'meta_value' 'meta_key' => 'location_level1_value' 'order' => 'ASC' <code> $wp_query = new WP_Query( array ( 'post_type' => 'listing', 'posts_per_page' => '9', 'post_status' => 'publish', 'meta_query' => array( array( 'key' => 'gateway_value', 'value' => 'Yes', 'compare' => '!=' ) ), 'orderby' => 'meta_value', // this means we will be using a selected // meta field to order 'meta_key' => 'location_level1_value', // this states which meta field // will be used in the ordering, // regardless of the filters 'order' => 'ASC', 'paged' => $paged ) ); </code>
|
Filter by one custom field, order by another?
|
wordpress
|
<code> wp_delete_attachment() </code> is very comprehensive and wipes every trace of attachment from database and disk. Is there easy way to keep original file? Forking under another name is not an option, because other functions like <code> wp_delete_post() </code> will still call original version.
|
Year and some later with much improved skills, behold: <code> Keep_Deleted_Attachment_File::on_load(); /** * Keep original file when deleting attachments. */ class Keep_Deleted_Attachment_File { static private $file; static function on_load() { add_action( 'init', array( __CLASS__, 'init' ) ); } static function init() { add_action( 'delete_attachment', array( __CLASS__, 'delete_attachment' ) ); } /** * @param int $post_id attachment being deleted */ static function delete_attachment( $post_id ) { self::$file = get_attached_file( $post_id ); add_filter( 'wp_delete_file', array( __CLASS__, 'wp_delete_file' ) ); } /** * @param string $file path to file being deleted * * @return string|bool no change or boolean false to prevent file deletion */ static function wp_delete_file( $file ) { if ( ! empty( self::$file ) && self::$file == $file ) { remove_filter( current_filter(), array( __CLASS__, __FUNCTION__ ) ); return false; } return $file; } } </code>
|
How to cleanly delete attachment but retain original file?
|
wordpress
|
Not much noticeable when working with individual posts, but when you create or delete multiple thousands in bulk and by code - process is quite slow. Are there any good tweaks to apply and corners to cut? Context: <code> wp_insert_post() </code> with categories and tags passed; add several custom fields; create and associate attachments (from existing files).
|
When updating post taxonomies, you can call <code> wp_defer_term_counting( true ) </code> before you do your mass operation, and then <code> wp_defer_term_counting( false ) </code> to update the term counts only once per term.
|
Optimize post insert and delete for bulk operations?
|
wordpress
|
I have a form that allows any registered user to submit a post (it's a custom post type - forum related), and I'm using <code> wp_insert_post() </code> to insert it into the db. From what I've seen in this function a sanitize_post() function is run automatically, but I think this only handles db escaping and such. So how do I sanitize the input data the same way as the wp-admin editor does? I mean apply the kses filter and all the other stuff...
|
When a post is created/edited from the admin, edit_post() is called. This function simply collects all the $_POST arguments and passes them to wp_update_post(). wp_update_post() then does some more logical checks and passes the data along to wp_insert_post(). wp_insert_post() calls sanitize_post(), which does all the heavy duty sanitization. So, yes, wp_insert_post() is the correct way to do it.
|
Submitting posts from the front end - sanitizing data
|
wordpress
|
I am creating a child theme using twentyten as my base. I am looking for a way to remove the features of adding custom header and background without touching <code> functions.php </code> file in the parent theme. no luck with this :( <code> function my_child_theme_setup() { remove_theme_support('custom-background'); remove_theme_support('custom-header'); } add_action( 'after_setup_theme', 'my_child_theme_setup' ); </code>
|
Both the header and background image features setup some globals in order to work, unsetting those globals seems to have some effect, and at the least removes them from the administration side. <code> add_action('after_setup_theme', 'remove_theme_features', 11 ); function remove_theme_features() { $GLOBALS['custom_background'] = 'kill_theme_features'; $GLOBALS['custom_image_header'] = 'kill_theme_features'; } class kill_theme_features { function init() { return false; } } </code> There's expectations for a class name to be provided as a callback for both of these features, and both expect the given class to have an init method. The solution was to create a dummy class that does nothing and update the globals, which effectively kills off the theme background and header pages in the admin area. Hope that helps..
|
Removing custom background and header feature in child theme
|
wordpress
|
This question is mainly to get some clarification on best practice for setting up a WordPress Multi-Site. As I have not done this before. I have outlined the scenario below. All help is greatly appreciated. Two Sites with very similar front-ends and an almost identical press section that is managed by WordPress. Site One : US Version of the site built in WordPress templates files. Press section managed from WordPress. Site Two: UK Version of the site, some pages eliminated and a portion of the press from the US site will be the same on the UK site. I see this being the correct application for WordPress Multisite. I see this running with 2 domains (site.com, site.co.uk) and running all the press clips off of one DB in Multisite with denoting a checkbox or category to apply the US clips to the UK site. I would like to know what would be the best approach for this and if the overall consensus is that this is the proper fit for WP Multi Site. Thank you in advance! JN
|
Multisite does not have cross-posting built in. you can do what you want with one of these: http://wordpress.org/extend/plugins/threewp-broadcast/ http://wordpress.org/extend/plugins/multipost-mu/
|
WordPress Multi Site Best Practice
|
wordpress
|
A theme is in development that echo's fields from the users account on their themed account page. This is the standard format. <code> <?php echo $current_user->user_lastname;?> </code> Thats all well and good. But there are 13 additional fields added via the plugin register plus. How do we echo them? This for example does not work. <code> <?php echo $current_user->user_post_code;?> </code> Any help appreciated, marvellous.
|
Hi @Robin I Knight: Have you tried this? <code> <?php echo get_user_meta($current_user->ID,'user_post_code',true);?> </code>
|
Display additional user fields
|
wordpress
|
I am trying to call plugins on a theme page. Specifically I am after the 'User Avatar' theme but their will be other later. How do I call a plugin on a theme? Presumable something linke <code> <?php </code> ...plugin name... <code> ;?> </code> but that isn't it. Any ideas. Marvellous
|
You must check the documentation of the plugin. Is it supporting shortcodes? Do sometingh like <code> <? do_shortcode('[plugin_shortcode]'); ?> </code> Has function to call in the theme? Do something like <code> <? my_plugin_function(); ?> </code>
|
Calling a plugin in theme development
|
wordpress
|
Looking for a little help getting to grips with a quote, part of which is producing quarterly reports consisting on all the posts from that quarter. My question is two fold - Is there a plugin that can do this sort of thing? Or of not, any clue as to where to start coding it? Cheers
|
You are looking for a mailing plugin that can send mails in digests. One example is Subscribe2 , which can be set from once hourly to weekly, but you can probably modify the code so it extends to quarterly mailings.
|
Send batch of posts as HTML Email?
|
wordpress
|
I need to completely replace WP's login form with the login form of an external service. The actions and filters I've found (eg login_form, login_head) seem to rely on WP's login process starting. I suppose I could do a redirect from here, but is there a cleaner way of sending a user to another URL if they attempt to browse to a WordPress login page.
|
Short and simple: No. You'll find a lot of stuff for wp-login.php on trac, but it seems that it won't change.
|
Completely replacing the login form
|
wordpress
|
I'm having an issue with using wp_insert_post. I'm adding the ability for a post of one type to create a post of another type with the first post as the post parent. I was testing out a few things using the save_posts filter. I created a function that simply creates a post and then hooked that function to the save_posts filter. The problem I'm having is that it is adding posts exponentially to my mySQL table. The longer I let it run before I put a freeze on the server, the more posts get added. Is there a better way of doing this? Example code: <code> public function save() { $my_child = array( 'post_title' => $this->_child_type, 'post_content' => "test content", 'post_status' => 'publish', 'post_type' => "video", 'post_parent'=> 55 ); $nindex = wp_insert_post($my_child); } add_action('save_post', array(&$this, 'save')); </code>
|
you can check what post type is calling the 'save_post' action try: <code> public function save() { global $post; if (!$post->post_type = 'video'){ $my_child = array( 'post_title' => $this->_child_type, 'post_content' => "test content", 'post_status' => 'publish', 'post_type' => "video", 'post_parent'=> 55 ); $nindex = wp_insert_post($my_child); } } add_action('save_post', array(&$this, 'save')); </code>
|
Problems wp_insert_post and save_posts filter
|
wordpress
|
Every time I attempt to upload a plugin or theme, I am asked for the FTP password. Is there a way to save this within Wordpress, or do I have to enter it every time? Thanks.
|
You can save this information on your wp-config.php file: <code> define('FTP_HOST', 'ftp_host'); define('FTP_USER', 'ftp_username'); define('FTP_PASS', 'ftp_password'); </code> More info (WordPress Codex)
|
How to save Admin FTP password
|
wordpress
|
In the administration under Your Profile, which is where I suspect it would be, I can't find anything relating to gravatar
|
The only place that gravatars are administered in WordPress core (without plugins, that is) is on the discussion settings page: If you want to access YOUR gravatar, go to http://gravatar.com and set up your profile. WordPress is set to automatically interface with gravatar using your user's email address to identify you with gravatar.com.
|
How do I accesss gravatar?
|
wordpress
|
I have typical parent and child categories setup as follows: Food potatoes corn beats Sports soccer football hockey etc. In my index.php template I'd like to list the categories of the specific post. The problem is, when I use the_category() it lists the parent categories twice. I'm using the following code: <code> <php echo '<dt>', the_category(', ', 'multiple'), '</dt>', "\n"; ?> </code> And it prints out: <code> Food:corn, Food, Food:potatoes </code> I believe it is listing the child category "corn" as "Food: corn" followed by the parent category "Food" just as "Food." Is there a way to exclude the parent categories? The way I'd like it to read is: <code> Food:corn, Food:potatoes </code> Thank you.
|
Have you tagged the post in Food, Food:Corn, and Food:potatoes? Try categorizing it in Food:corn and Food:potatoes only. I do not believe that there is a means to exclude categories from the_category() function. You will have to use another function to create a custom query to do so. Try some of these .
|
Exclude parent categories from the_category() within the loop
|
wordpress
|
How can I load regular post tags as values for autocomplete field? What I have now is pretermined values like this: <code> var data = {items: [ {value: "1", name: "Siemens"}, {value: "2", name: "Phillips"}, {value: "3", name: "Whirlpool"}, {value: "4", name: "LG"} }; $("#input_1_3").autoSuggest(data.items, {selectedItemProp: "name", searchObjProps: "name"}); </code> I'm using Drew Wilson's Autocomplete plugin found at: http://code.drewwilson.com/entry/autosuggest-jquery-plugin . Any help would be most apreciated.
|
<code> if(isset($_GET['get_tags'])): $output = array(); foreach(get_terms('post_tag') as $key => $term): // filter by $_GET['q'] here if you need to, // for eg. if(strpos($term->name, $_GET['q']) !== false)... $output[$key]['value'] = $key; $output[$key]['name'] = $term->name; endforeach; header("Content-type: application/json"); echo json_encode($output); die(); endif; </code> in this case your js would be something like: <code> $("#input_1_3").autoSuggest( "http://yoursite.com/?get_tags=1", {selectedItemProp: "name", searchObjProps: "name"}); </code>
|
Tags as autocomplete values
|
wordpress
|
This is a continuation of stackexchange-url ("this post"). I've built my form and managed to get the correct taxonomy terms listed as a dropdown, but I'm wondering what action I should be using in my form and how I can recall the options selected in the same form on the results page? This is the code I've written so far which sets query_posts() so that it fetches the custom posts 'ftevent' that have the taxonomy terms 'type', 'period' and 'duration' set to something the user chooses: Pastie link And this is the function osu_list_terms() that you'll see in that code which tries to recall the options selected in each dropdown: <code> function osu_list_terms($osu_tax, $osu_recall) { // list terms in fttype taxonomy $taxonomy = $osu_tax; $tax_terms = get_terms($taxonomy); foreach ($tax_terms as $tax_term) { echo '<option' . $osu_recall . '>' . $tax_term->name . '</option>'; } } </code> Now, this is a work in progress, so I'm sure there are a few other problems I'll come up against (such as ordering the custom posts by the custom field 'StartEventDate'), but at this point, I'm trying to work out how Wordpress works with something like this form. I'm used to using <code> <?php echo $_SERVER['PHP_SELF']; ?> </code> for forms so that the form submits to the same page. I was hoping I could do the same with this, but Wordpress redirects to a URL like this and uses the archive.php template instead of the current page template I've inserted this form into: <code> /?fttype=Group+walks&ftperiod=Weekday&ftduration=Half-day&showfilter=true </code> Is there a 'correct' way to do this? I'm a little confused as to how I can style a template for the search results as well as the results are displayed using the archive page (which is also used by tag-cloud results). Any tips you can offer? Thanks, osu
|
If you leave the <code> action </code> attribute empty, the form will post back to the current URL. However , if your <code> method </code> attribute is <code> get </code> , the form will post back to current URL, minus the current query string . If you want to keep the current query string, you can use hidden inputs to replicate the current parameters. And never trust PHP_SELF !
|
Correct way to use a form to to filter custom posts by taxonomy terms?
|
wordpress
|
I must be annoying your with all these permalink questions :) The code I'm using for the loop is: <code> // hijack stupid WP globals to get pagination working... global $wp_query; $temp = $wp_query; $paged = get_query_var('paged') ? get_query_var('paged') : 1; $wp_query = new WP_Query(); $wp_query->query(array( 'post_parent' => get_the_ID(), 'post_type' => 'topic-reply', 'posts_per_page' => 10, 'order' => 'ASC', 'paged' => $paged, )); if($wp_query): wp_pagenavi(); while ($wp_query->have_posts()): $wp_query->the_post(); get_template_part('topic-reply'); endwhile; wp_pagenavi(); endif; $wp_query = $temp; wp_reset_query(); </code> The pagination works fine if permalinks are set to defaults, when clicking on page 2 link the URL I get is like: <code> http://localhost/wp/?topic=sometopictitle&paged=2 </code> The problem comes when I set the permalinks to a custom structure; when clicking on page 2, I get the first page URL: <code> http://localhost/wp3/forum/general-discussion/topic/sometopictitle/ </code> instead of <code> http://localhost/wp3/forum/general-discussion/topic/sometopictitle/page/2/ </code> (A live example <code> here </code> ) Does anyone know the rules I should add to set paged permalinks for the "topic-reply" post type?
|
When you use <code> paged </code> on a single post, it's checking for a paginated post, not pages of posts. Because your topics don't have paginated content, it's assuming it's a mistake and redirecting to the 'first' page of the topic, long before your custom loop is ever touched. So, in this instance, <code> paged </code> is always going to return as 1. As a workaround, I'd register an EP Permalink for the topic. Something like this: <code> add_rewrite_endpoint( 'tpage', EP_PERMALINK ); </code> Then, instead of checking for <code> get_query_var( 'paged' ); </code> , check for <code> get_query_var( 'tpage' ); </code> and pass the value for that along to the custom query. Setting up that rewrite endpoint means that all permalinks compatible with the <code> EP_PERMALINK </code> bitmask (your topics are compatible) will accept a <code> /tpage/XXXX </code> structure added to the end of the url, where XXXXX can be anything you want (in this instance, you'd want to typecast it as an integer, probably an absolute one at that). EDIT Something like this should work to get you an array of paginated links: <code> $links = paginate_links(array( 'base' => trailingslashit( get_permalink( $temp->post->ID ) ) . '%_%', 'format' => 'tpage/%#%', 'type' => 'array' )); </code> From there, you could do something like this: <code> <div class="page-navi clear-block"> <?php foreach( $links as $link ){ if( false !== strpos( $link, " class='page-numbers'" ) ) $link = str_replace( " class='page-numbers'", " class='page page-numbers'", $link ); echo $link; } ?> </div> </code> I'm pretty sure that'd get you the same styles and the 'current' style for the links.
|
Pretty paged permalinks in custom post type loop
|
wordpress
|
Basically here's my project: I have to create a back-end wordpress gui user input section. The user will enter details about their projects like name, location, what it is, some other details. A page will display the top 9 recent or so in a 3x3 grid. There will be a search bar to search projects for related tags. I have currently: used functions.php to setup my post type and it works used simple forms plugin to create forms on the add new page Background: I am a pretty entry level person in wordpress, and slightly overwhelmed right now. But, it's slowly coming together. Any input on structure or anything would be appreciated. Update: I have created the forms, but I need to know what to put in the single-projects.php to display the content from the forms. Thank you so much
|
Hi @jeff: This list of plugins should give you what you need: Custom Post Type Plugins UPDATE Try this plugin as it lets you set up fields for the user to enter into: Simple Fields
|
I need basic help with custom post types
|
wordpress
|
Right now the title of a post page on my blog reads like this... Blog Name > > Blog Archive > > Post Title I don't see the need for "Blog Archive" to be in there and would like to remove it. I've looked in single.php and style.css and I'm not seeing any reference to "Blog Archive" in there that I can remove. Any suggestions? Much appreciated. Eddie
|
I just realized that you're talking about the browser "title" at the top; that wasn't clear from your original post Go into your <code> header.php </code> and at the top look for this line <code> <title><?php bloginfo('name'); ?> <?php if ( is_single() ) { ?> &raquo; Blog Archive <?php } ?> <?php wp_title(); ?> - <?php bloginfo('description'); ?> </title> </code> and remove <code> <?php if ( is_single() ) { ?> &raquo; Blog Archive <?php } ?> </code>
|
Lose "Blog Archive" from page title
|
wordpress
|
I have a Multisite Wordpress installation with 7 different blogs. I want to show an aggregate of the summaries of posts from those 7 blogs in the main blog. Do you know a good way to do this?
|
A couple of plugins, depending what you wanted. http://wordpress.org/extend/plugins/wordpress-mu-sitewide-tags/ Despite the name, it pulls in all posts to the main blog or a blog called 'tags'. http://wordpress.org/extend/plugins/diamond-multisite-widgets/ Give a list of the latest posts network-wide, all in a handy widget.
|
Aggregate Summaries of Posts of Different Blogs in Multisite Instance
|
wordpress
|
I have a custom post type named Reportage, added in functions.php: <code> add_action( 'init', 'create_post_type' ); function create_post_type() { register_post_type( 'reportage', array( 'labels' => array( 'name' => __( 'Reportage' ), 'singular_name' => __( 'Reportage' ) ), 'public' => true, 'taxonomies' => array('category'), 'query_var' => true ) ); register_taxonomy_for_object_type('category', 'reportage'); } </code> Now I want to use this custom url structure: "/%posttype%/%category%/%postname%", but the permalinks gets generated as (and redirected to when visited) "/%posttype%/%postname%". How do I change the permalinks structure to "/%posttype%/%category%/%postname%"? I need to have "/%posttype%" to route to a regular page with the same name as the posttype (Reportage), this works fine now. I also need to "/%posttype%/%category%" to route to something like the category.php file. How can I make this work?
|
My plugin Custom Post Permalinks does this. http://wordpress.org/extend/plugins/custom-post-permalinks
|
Get a permalink structure of /%posttype%/%category%/%postname%
|
wordpress
|
Is there a plugin or another easy way to get debug versions of the external Javascript libraries? ("External" because they were not written by the WordPress team, not because they come from Google or another CDN). If I define the <code> SCRIPT_DEBUG </code> constant to <code> true </code> , I get debug (non-minified) versions of most Javascript files in WordPress. However, some external libraries are still using the minified versions (check <code> wp_default_scripts() </code> for the scripts that don't have the <code> $suffix </code> part in their URL). I am creating a TinyMCE plugin and thus it would be handy to have the full TinyMCE source code when stepping up and down the call stack while debugging. (I know TinyMCE is loaded in an even more special way, but I'm also thinking of the jQuery library, which uses the standard <code> wp_register_script() </code> method.) I know that TinyMCE can be loaded as a compressed or a non-compressed Javascript, but both of these versions have been minified first, so that is not what I want. I want to load a non-minified version of TinyMCE, and possibly also the non-minified versions of the plugins.
|
I created a version for TinyMCE, it was not too hard. The trick was to hijack <code> includes_url </code> , this was the only way to change the path to the TinyMCE script. I created a plugin that has non-minified versions of TinyMCE 3.2.7 (WP 2.9 and 3.0) and 3.3.9.3 (WP 3.1). You can download it via Dropbox , let me know what you think!
|
Using development versions of jQuery, TinyMCE, ...?
|
wordpress
|
I have a favicon that is a remnant of a disactivated wordpress theme. I can't find the favicon file in the theme folder, or the wordpress or server root. I have added my own reference to a new favicon, but the old one is still displayed. <link rel="icon" type="image/png" href=" http://www.steve.doig.com.au/wordpress/wp-content/themes/grid-focus-public-10/images/favicon.ico "> My site is here . Edit: Favicon is
|
The default favicon location on your server gives a 404: http://www.steve.doig.com.au/favicon.ico Your blogs homepage source-code related to linking to another location is: <link rel="icon" type="image/png" href="http://www.steve.doig.com.au/wordpress/wp-content/themes/grid-focus-public-10/images/favicon.ico"> Note: The file suffix is .ico which normally stands for an Microsoft Icon file. But names are not interesting for that. The <code> type="image/png" </code> is correct here, it's a PNG file. Your blogs server does return the following mime-type header for that linked favicon: Content-Type: image/x-icon Note: That information is wrong. The file's mime content type is acutally <code> ìmage/png </code> . Please reconfigure your server, rename the file to .png or convert the image in that file into the <code> image/x-icon </code> type (you can choose only one of these three options, the last one is the one I would do). Suggestions Use a program that is able to properly save the microsoft ico file-format. Don't use a PNG, use a true ICO. Place your favicon.ico file then into the root of your server. Modify the links' href to the new location. Delete any old favicon.ico files from your server, delete your browsers chache, it's history etc. . Then restart your computer. The old favicon should be gone next time you visit your page on that computer. You'll find more details in stackexchange-url ("How to change the WordPress favicon?")
|
Can't delete unwanted favicon
|
wordpress
|
I have written a basic gallery plugin that uses wp_enqueue_style to include a stylesheet on the page. I'd like for the WordPress theme to be able to override the style of the plugin which means I'd like to my plugin to play nice and output the css file before the theme css file. wp_enqueue_style has a <code> deps </code> parameter for exactly this requirement. My question is what value should I use for the <code> deps </code> parameter if I want to say "I depend on the themes css file"? The current plugin code is incorrect because it uses <code> false </code> for the <code> deps </code> parameter: <code> // Enqueue a CSS style file - see http://codex.wordpress.org/Function_Reference/wp_enqueue_style wp_enqueue_style('bitvol_galleria_css', BITVOL_GALLERIA_URL . '/bitvolution-image-galleria.css', false, $this->bitvol_galleria_version, 'all' ); </code>
|
First issue - you have dependency backwards. Depending on something means loading after dependency, while you want earlier. Second issue - theme's stylesheet doesn't actually use enqueue, it is usually codded directly in <code> header.php </code> file of theme. And since it seems to come before <code> wp_head() </code> call - you have no hook to ensure your stylesheet is above it. So this is commonly handled like your stackexchange-url ("workaround") - queued stylesheet with option to disable it by code or option in admin.
|
What parameter should I pass to wp_enqueue_style to depend on the themes stylesheet?
|
wordpress
|
I have had a small number of users on my blog whiching to change thier username. I was reading that is in stored in the DB but where is it and how do I change it.
|
You can look at the <code> user_login </code> column at the <code> wp_users </code> table. You can edit these values using any database tool (my favorite is PHPMyadmin http://www.phpmyadmin.net/home_page/index.php ),
|
Changing a username
|
wordpress
|
Using the Wordpress default theme 2010 1.1, shortcodes work on the main blog page and individual post pages, but are being stripped out on category and archive pages. For example, stick in the theme's functions.php: <code> add_shortcode('tsc', 'tsc_process_shortcode' ); function tsc_process_shortcode($atts, $content = null) { return 'INSERTED TEXT ' . $content; } </code> INSERTED TEXT isn't generated from [tsc] in post content shown on category and archive pages. How do I get shortcodes to function on category and archive pages?
|
Shortcodes are stripped from the excerpt before filters are applied. Try something more like this: <code> function tsc_execute_shortcodes_in_excerpts( $text, $raw_text ){ if(empty($raw_text)){ $text = get_the_content(''); $text = apply_filters('the_content', $text); $text = str_replace(']]>', ']]&gt;', $text); $text = strip_tags($text); $excerpt_length = apply_filters('excerpt_length', 55); $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]'); $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY); if ( count($words) > $excerpt_length ) { array_pop($words); $text = implode(' ', $words); $text = $text . $excerpt_more; } else { $text = implode(' ', $words); } } return $text; } add_filter( 'wp_trim_excerpt', 'tsc_execute_shortcodes_in_excerpts', 10, 2 ); </code> That basically re-runs <code> wp_trim_excerpt() </code> on the content (minus shortcode stripping) if it was trimmed to begin with. If you want to target your shortcode only, you could do something like this after <code> get_the_content('') </code> : <code> $text = str_replace( '[tsc', '{tsc', $text ); $text = strip_shortcodes( $text ); $text = str_replace( '{tsc', '[tsc', $text ); </code> Hope that helps.
|
stop shortcode stripping in category and archive pages
|
wordpress
|
I need to apply unit testing for one of my plugins. I recently re designed it into classes, so unit testing should be easier to apply now. What are some effective strategies to unit test my plugin? I need a way to use WordPress' functions used in the plugin, but I shouldn't need a running WordPress site (just test data on the DB AFAIK), right? I have a hard time figuring out how to just unit test the plugin and not the plugin in the site's context. I could use Selenium for this, but right now I just want to focus on unit testing the plugin classes functionality, so that I don't break them with each update.
|
As an ex-software engineer building large business types who landed in an interactive agency let me give you a few thoughts on testing when developing for Wordpress: Your Unit Testing should test the smallest amount of behavior that a class can perform. Each class should be able to be tested independently of Wordpress. If you have a Wordpress dependency consider creating mock objects and/or methods in your test to work around this. Ultimately, this will change how you write your code a bit -- but it will be far more testable. As usual no free lunch. When you get up to the level of functional testing this is where you can test you code with Wordpress dependencies. This is where you would actually test that your plugin actually performs a service it is supposed to. Depending on what your plugin does -- consider using Selenium-based tests which test for the presence of data in the DOM by using IDs. Its reasonably robust and it is a lot less likely to break version to version. Again, the trick here is to think of testing as part of your software development lifecycle. Large changes in the code will cascade down to large changes in your tests. All part of the cost of doing business. If you need any assistance with any of the tools to accomplish this -- I would be happy to answer if you open up a new question. I make use of both PHPUnit and its selenium extension in the work I do.
|
Unit testing for plugin development
|
wordpress
|
I'm trying to add my plugin interface to the Category Editor. I've easily attached it to the post and page editor using the add_meta_box() filter, but there does not appear to be an add_meta_box hook on the category editor. So, since I'm already adding some extra fields to the category edit screen using add_filter('edit_category_form', 'my_category_editor_function', 1) I'm wondering if I can just call my plugin script from within that function? Example: <code> add_filter('edit_category_form', 'my_category_editor_function', 1); function my_category_editor_function($tag) { $tag_extra_fields = get_option('my_category_editor_function');?> <!--This is where I would call my plugin interface--> <div style="float:right;top:0;right:0"> <?php /* load my widget here. May have to use some funky css to get it to float to the right of the cat editor just like it does in the post editor */ ?> </div> <!--This is my current fields added with the filter--> <table class="form-table"> <tr class="form-field"> <th scope="row" valign="top"><label for="_my-categoryTitle">Category Title</label></th> <td><input name="_my-categoryTitle" id="_my-categoryTitle" type="text" size="40" aria-required="false" value="<?php echo $tag_extra_fields[$tag->term_id]['my_cat_title']; ?>" /> <p class="description">The title is optional but will be used in place of the name on the home page category index (when in list view) and on the category landing page.</p> </td> </tr> <tr class="form-field"> <th scope="row" valign="top"><label for="_my-categoryKeywords">Keywords</label></th> <td valign="top"><input name="_my-categoryKeywords" id="_my-categoryKeywords" type="text" size="40" aria-required="false" value="<?php if(isset($tag_extra_fields[$tag->term_id]['my_cat_keywords']))echo $tag_extra_fields[$tag->term_id]['my_cat_keywords']; ?>" /> <p class="description">Optional: If you want to add a keywords metatag to the category landing page and keywords in the Category image's alt tag.</p> </td> </tr> <tr class="form-field"> <th scope="row" valign="top"><label for="_my-categoryImageLink">Image Link</label></th> <td valign="top"><input name="_my-categoryImageLink" id="_my-categoryImageLink" type="text" size="40" aria-required="false" value="<?php if(isset($tag_extra_fields[$tag->term_id]['my_cat_imageLink']))echo $tag_extra_fields[$tag->term_id]['my_cat_imageLink']; ?>" /> <p class="description">Optional: If you want to link the <b>category landing page image</b> to an affiliate or CPA offer, place your link here.</p> </td> </tr> <tr class="form-field"> <th scope="row" valign="top"><label for="_my-categoryAds">Hide Ads?</label></th> <td><input name="_my-categoryAds" id="_my-categoryAds" type="checkbox" style="width:30px;float:left;"<?php if(isset($tag_extra_fields[$tag->term_id]['my_cat_ads'])) echo ' checked="checked"'; ?>" /> <p class="description"><label for="_my-categoryAds">Check this to remove ads from this category's landing page. (Does not affect ads placed in widgets)</label></p> </td> </tr> </table> </code>
|
you can do that as long as <code> <!--This is where I would call my plugin interface--> </code> outputs the HTML form fields.
|
Can I attach a plugin via my add_filter callback contents?
|
wordpress
|
I'm trying to get a list of roles and filter them by a specific capability (custom). I've ran across stackexchange-url ("this post"), but I'd like to filter the roles by whether they're capable to, say, <code> edit_post </code> . -Zack
|
Untested, but should be easily extendable(or something you can take ideas from). <code> function roles_have_cap( $roles = false, $cap ) { global $wp_roles; if( !isset( $wp_roles ) || !isset( $cap ) ) return false; if( !$roles ) $roles = array_keys( $wp_roles->roles ); if( !is_array( $roles ) ) $roles = array( $roles ); $hascap = array(); foreach( $roles as $role ) { if( !isset( $wp_roles->roles[$role]['capabilities'][$cap] ) || ( 1 != $wp_roles->roles[$role]['capabilities'][$cap] ) ) continue; $hascap[] = $role; } if( empty( $hascap ) ) return false; return $hascap; } </code> First argument takes either a singular role name(string) or an array of roles to check have a particular cap. Second argument takes a singular capability to check for(string). Example usage: <code> $role_can_edit_pages = roles_have_cap( 'administrator', 'edit_pages' ); // Result // array( 0 => administrator ) </code> If the function returned false you'd know the role(s) does not have the cap, ie.. <code> if( !$role_can_edit_pages ) // Role cannot not edit pages </code> Else, the result is an array of roles that do have the cap(whether you passed in a single role or several). You could trim it down and just have a return value if that's preferred, but you mentioned wanting a list of roles that have a cap, so i naturally assumed an array would be a logical choice.. Converting an array to a string is fairly easy, and you can even use your own seperator, simply call <code> implode() </code> , like so...(using the example variable from earlier).. <code> echo implode( ' | ', $role_can_edit_pages ); // | (pipe is the example seperator here) </code> You could also move the implode into the function to avoid having to do implodes when calling the function, and do note, implode will work correctly on a single item array to(ie. you'll get a string with no seperator). I hope that's helpful in anycase... :) EDIT: Function will now look at all the roles if the first arg($roles) is set to false.
|
Filter list of rules based on a capability
|
wordpress
|
I created a 'forum' taxonomy, using these rules: <code> register_taxonomy( 'forum', array('topic'), array( 'public' => true, 'name' => _a('Forums'), 'singular_name' => _a('Forum'), 'show_ui' => true, 'show_in_nav_menus' => true, 'hierarchical' => true, 'labels' => array( 'name' => _a('Forums'), 'singular_name' => _a('Forum'), 'search_items' => _a('Search Forums'), 'popular_items' => _a('Popular Forums'), 'all_items' => _a('All Forums'), 'parent_item' => _a('Parent Forum'), 'parent_item_colon' => _a('Parent Forum:'), 'edit_item' => _a('Edit Forum'), 'update_item' => _a('Update Forum'), 'add_new_item' => _a('Add New Forum'), 'new_item_name' => _a('New Forum Name'), ), 'query_var' => true, 'rewrite' => array('slug' => 'forums', 'with_front' => false, 'hierarchical' => true), ) ); </code> In the front-end the URLs looks like: <code> forums/general-discussion/sub-forum </code> How can I remove the front slug ("forums")? Ie, change the URLs to: <code> general-discussion/sub-forum </code> If I pass a empty slug argument to register_taxonomy() it works, but that causes issues with the permalinks of the post type associated with this taxonomy
|
URL Design has been important to be for well over a decade; I even wrote a blog about it several years back. And while WordPress is sum is a brilliant bit of software unfortunately it's URL rewrite system is just short of brain dead (IMHO, of course. :) Anyway, glad to see people caring about URL design! The answer I'm going to provide is a plugin I'm calling <code> WP_Extended </code> that is a proof of concept for this proposal on Trac (Note that proposal started as one thing and evolved into another, so you have to read the entire thing to see where it was headed.) Basically the idea is to subclass the <code> WP </code> class, override the <code> parse_request() </code> method, and then assign the global <code> $wp </code> variable with an instance of the subclass. Then within <code> parse_request() </code> you actually inspect the path by path segment instead of using a list of regular expressions that must match the URL in their entirety. So to state it explicitly, this technique inserts logic in front of the <code> parse_request() </code> which checks for URL-to-RegEx matches and instead first looks for taxonomy term matches, but it ONLY replaces <code> parse_request() </code> and leaves the entire rest of the WordPress URL routing system intact including and especially the use of the <code> $query_vars </code> variable. For your use-case this implementation only compares URL path segments with taxonomy terms since that's all you need. This implementation inspects taxonomy terms respecting parent-child term relationships and when it finds a match it assigns the URL path (minus leading and trailing slashes) to <code> $wp->query_vars['category_name'] </code> , <code> $wp->query_vars['tag'] </code> or <code> $wp->query_vars['taxonomy'] </code> & <code> $wp->query_vars['term'] </code> and it bypasses the <code> parse_request() </code> method of the <code> WP </code> class. On the other hand if the URL path does not match a term from a taxonomy you've specified it delegates URL routing logic to the WordPress rewrite system by calling the <code> parse_request() </code> method of the <code> WP </code> class. To use <code> WP_Extended </code> for your use-case you'll need to call the <code> register_url_route() </code> function from within your theme's <code> functions.php </code> file like so: <code> add_action('init','init_forum_url_route'); function init_forum_url_route() { register_url_route(array('taxonomy'=>'forum')); } </code> What here is the source code for the plugin: <code> <?php /* Filename: wp-extended.php Plugin Name: WP Extended for Taxonomy URL Routes Author: Mike Schinkel */ function register_url_route($args=array()) { if (isset($args['taxonomy'])) WP_Extended::register_taxonomy_url($args['taxonomy']); } class WP_Extended extends WP { static $taxonomies = array(); static function on_load() { add_action('setup_theme',array(__CLASS__,'setup_theme')); } static function register_taxonomy_url($taxonomy) { self::$taxonomies[$taxonomy] = get_taxonomy($taxonomy); } static function setup_theme() { // Setup theme is 1st code run after WP is created. global $wp; $wp = new WP_Extended(); // Replace the global $wp } function parse_request($extra_query_vars = '') { $path = $_SERVER['REQUEST_URI']; $domain = str_replace('.','\.',$_SERVER['SERVER_NAME']); //$root_path = preg_replace("#^https?://{$domain}(/.*)$#",'$1',WP_SITEURL); $root_path = $_SERVER['HTTP_HOST']; if (substr($path,0,strlen($root_path))==$root_path) $path = substr($path,strlen($root_path)); list($path) = explode('?',$path); $path_segments = explode('/',trim($path,'/')); $taxonomy_term = array(); $parent_id = 0; foreach(self::$taxonomies as $taxonomy_slug => $taxonomy) { $terms = get_terms($taxonomy_slug); foreach($path_segments as $segment_index => $path_segment) { foreach($terms as $term_index => $term) { if ($term->slug==$path_segments[$segment_index]) { if ($term->parent!=$parent_id) { // Make sure we test parents $taxonomy_term = array(); } else { $parent_id = $term->term_id; // Capture parent ID for verification $taxonomy_term[] = $term->slug; // Collect slug as path segment unset($terms[$term_index]); // No need to scan it again } break; } } } if (count($taxonomy_term)) break; } if (count($taxonomy_term)) { $path = implode('/',$taxonomy_term); switch ($taxonomy_slug) { case 'category': $this->query_vars['category_name'] = $path; break; case 'post_tag': $this->query_vars['tag'] = $path; break; default: $this->query_vars['taxonomy'] = $taxonomy_slug; $this->query_vars['term'] = $path; break; } } else { parent::parse_request($extra_query_vars); // Delegate to WP class } } } WP_Extended::on_load(); </code> P.S. CAVEAT #1 Although for a given site I think this technique works brilliantly but this technique should NEVER be used for a plugin to be distributed on WordPress.org for others to use . If it is at the core of a software package based on WordPress then that might be okay. Otherwise this technique should be limited to improving the URL routing for a specific site . Why? Because only one plugin can use this technique . If two plugins try to use it they will conflict with each other. As an aside this strategy can be expanded to generically handle practically every use-case pattern that could be required and that's what I intend to implement as soon as I either find the spare time or a client who can sponsor the time that it would take to build fully generic implementations. CAVEAT #2 I wrote this to override <code> parse_request() </code> which is a very large function, and it is quite possible that I missed a property or two of the global <code> $wp </code> object that I should have set.. So if something acts wonky let me know and I'll be happy to research it and revise the answer if need be. Anyway... UPDATE Since writing this WordPress core has added the <code> 'do_parse_request' </code> hook that allows URL routing to be handled elegantly and without the need to extend the <code> WP </code> class. I covered the topic in-depth in my 2014 Atlanta WordCamp talk entitled " Hardcore URL Routing " ; the slides are available at the link.
|
Remove taxonomy slug from a custom hierarchical taxonomy permalink
|
wordpress
|
This question might seem a little silly but I was wondering what is the differences between WP.com and WP.org? I know the main differences like you can't edit a them file without paying for it, you might get some ads and you get a youname.wordpress.com domain but what are the little features that make the difference.
|
WordPress.com is web service . WordPress.org is software product . Think bus vs car. You can ride both, but bus is owned by someone else and what you can do with it is limited.
|
WordPress.com vs WordPress.org
|
wordpress
|
Is there a fast way to get the count (number) of post children of a certain post? (The post has a custom post type) I don't want to use WP_Query for this because I don't need all the extra data... LE: based on wyrfel's answer I ended up using: <code> function reply_count($topic, $type = 'topic-reply'){ global $wpdb; $cache_key = "{$type}_{$topic}_counts"; $count = wp_cache_get($cache_key, 'counts'); if(false !== $count) return $count; $query = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_parent = %d AND post_type = %s"; $count = $wpdb->get_var($wpdb->prepare($query, $topic, $type)); wp_cache_set($cache_key, $count, 'counts'); return $count; } </code>
|
<code> class MyClass { ... function post_count_filter($where) { global $wpdb; str_replace("WHERE", "WHERE ".$wpdb->posts.".post_parent = ".$this->count_parent." AND", $where); return $where; } function count_children($post_id) { $this->count_parent = $post_id; add_filter('query', ( &$this, 'post_count_filter') ); $stats = wp_count_posts('myposttype'); remove_filter('query', ( &$this, 'post_count_filter') ); unset($this->count_parent); return array_sum( (array)$stats ); } // example of use function xyz() { global $post; ... $child_count = $this->count_children($post->ID); ... } ... } </code> The only issue with that is that wp_count_posts() caches its results and since your filter bypasses the cache you might have to devalidate the cache, first. Or (better), copy the wp_count_posts() function and modify it to your needs, so you don't have to use the filter, don't have to sum up the results and avoid having the rest done that it does.
|
Get the post children count of a post
|
wordpress
|
I'm looking for a way to import tweets into Wordpress as posts. In fact, I want to display tweets about a certain topic on a page in Wordpress. So page A would contain tweets about hashtag x, and page B would contain tweets hashtag y. There is at least one plugin that imports tweets (Tweet-Import), but it can only import tweets by a certain user, not by hashtag. Is there any way that this can be done? Cheers!
|
I wrote a shortcode function based on "Twitter Hash Tag Widget" plugin just copy this function to your themes functions.php file <code> function tweets_by_hashtag_9867($atts, $content = null){ extract(shortcode_atts(array( "hashtag" => 'default_tag', "number" => 5, ), $atts)); $api_url = 'http://search.twitter.com/search.json'; $raw_response = wp_remote_get("$api_url?q=%23$hashtag&rpp=$number"); if ( is_wp_error($raw_response) ) { $output = "<p>Failed to update from Twitter!</p>\n"; $output .= "<!--{$raw_response->errors['http_request_failed'][0]}-->\n"; $output .= get_option('twitter_hash_tag_cache'); } else { if ( function_exists('json_decode') ) { $response = get_object_vars(json_decode($raw_response['body'])); for ( $i=0; $i < count($response['results']); $i++ ) { $response['results'][$i] = get_object_vars($response['results'][$i]); } } else { include(ABSPATH . WPINC . '/js/tinymce/plugins/spellchecker/classes/utils/JSON.php'); $json = new Moxiecode_JSON(); $response = @$json->decode($raw_response['body']); } $output = "<div class='twitter-hash-tag'>\n"; foreach ( $response['results'] as $result ) { $text = $result['text']; $user = $result['from_user']; $image = $result['profile_image_url']; $user_url = "http://twitter.com/$user"; $source_url = "$user_url/status/{$result['id']}"; $text = preg_replace('|(https?://[^\ ]+)|', '<a href="$1">$1</a>', $text); $text = preg_replace('|@(\w+)|', '<a href="http://twitter.com/$1">@$1</a>', $text); $text = preg_replace('|#(\w+)|', '<a href="http://search.twitter.com/search?q=%23$1">#$1</a>', $text); $output .= "<div>"; if ( $images ) $output .= "<a href='$user_url'><img src='$image' alt='$user' /></a>"; $output .= "<a href='$user_url'>$user</a>: $text <a href='$source_url'>&raquo;</a></div>\n"; } $output .= "<div class='view-all'><a href='http://search.twitter.com/search?q=%23$hashtag'>" . __('View All') . "</a></div>\n"; $output .= "</div>\n"; } return $output; } </code> then turn it into a short code by adding the next line to your themes functions.php file: <code> add_shortcode("hashtag_tweets", "tweets_by_hashtag_9867"); </code> Then all you have left to do is create a new,page or post and enter a shortcode for example: <code> [hashtag_tweets hashtag="YOUR_TAG" number="NUMBER_OF_TWEETS_TO_GET"] </code> change YOUR_TAG to your hashtag and change NUMBER_OF_TWEETS_TO_GET to the nuber of tweets you want to get. Hope this helps.
|
Importing Tweets with certain hashtags into Wordpress
|
wordpress
|
I've got a php script that is called when the user is editing the category. However, although the page renders fine for the most part, at the point where the image upload button should appear, I'm seeing this message: Rendering of admin template /home/site/public_html/wp-content/themes/mytheme/folder/subfolfer/admin/file.php failed What are the likely causes for this error in this one site? Other sites are processing this fine? THe site has PHP version 5.2.16 THe site has WP version 3.0.5
|
Looks like an error related to the HeadSpace2 plugin, see. http://urbangiraffe.com/support/topic/rendering-of-admin-template-failed-2 http://urbangiraffe.com/support/topic/rendering-of-admin-template-failed-continued Perhaps the plugin has template support which you've enabled but not created the appropriate file for in the theme? I have no idea, i don't use the plugin, just thinking out loud.. Hope that helps.
|
"Rendering of admin template [path to template] failed"
|
wordpress
|
I'm trying to pass error messages or regular messages from a page that processes a form post request to the page it then redirects to (after processing). Since i want to get rid of the POST request header (you know...browsers trying to repost on page reload), i need to redirect (no include or using same page, possible). Or can i somehow get rid of the POST request header? I'm wondering if there's any non-visible way of passing my messages to the next page, since i can't use $_SESSION and don't want to use GET request parameters. Thanks.
|
Hehe, got it meself, just a little too late, unfortunately, now i have to change half the stuff again... set_transient(), get_transient() and delete_transient() will be my friends Edit: More on this...i now realized that my wp_options table is full of _transient_xyz records, coming from WP itself. So that indicates that WP is using the db to store these transients, which isn't ideal. Haven't done the research, yet, but i hope WP cleans this up in regular intervals.
|
Is there any way to pass messages from a script to a redirect target in a hidden fashion?
|
wordpress
|
I know how to get a custom field value for a specific post. <code> get_post_meta($post_id, $key, $single); </code> What I need is to get all the values associated with a specific custom post key, across all posts . Anyone knows of an efficient way to do this? I wouldn't want to loop through all post id's in the DB. Example: 4 posts all with different values for a custom field called 'Mood'. 2 posts have the value 'happy', 1 post have 'angry' and 1 post has 'sad' I want to output : across all posts we have: two happy, one angry and one sad author(s). But for LOTS of posts. What I'm looking for is either: a WP function to get this. or a custom query to get this as efficiently as possible.
|
One possible approach would be to use one of the helper methods in the WPDB class to do a more refined meta based query. The caveat to using some of these functions however, is that you don't usually get back a simple array of data and usually have to make needless references to object properties, even if you're only calling for one column or row. Of course, not all functions are the one and the same, and a purposeful mention goes out to the WPDB method, <code> get_col </code> which returns a simple flat array of the data queried for, i make this mention specifically because the example following will call upon this method. WordPress - WPDB Selecting a column of data $wpdb-> get_col() Here's an example function which queries the database for all posts of a chosen post type, post status and with a specific meta key(or custom field to the less technically minded). <code> function get_meta_values( $key = '', $type = 'post', $status = 'publish' ) { global $wpdb; if( empty( $key ) ) return; $r = $wpdb->get_col( $wpdb->prepare( " SELECT pm.meta_value FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = '%s' AND p.post_status = '%s' AND p.post_type = '%s' ", $key, $status, $type ) ); return $r; } </code> So for example, if you like to find out which posts have a meta key of rating , for the post type movies and you'd like to store that information inside a variable, an example of such a call would be.. <code> $movie_ratings = get_meta_values( 'rating', 'movies' ); </code> If you wanted to do nothing more than print that data to screen, PHP's implode function can quickly splice that simple array into lines of data. <code> // Print the meta values seperate by a line break echo implode( '<br />', get_meta_values( 'YOURKEY' )); </code> You can also use the returned data to work out how many posts have these meta values by doing a simple loop over the returned data and building an array of the counts, for example. <code> $movie_ratings = get_meta_values( 'rating', 'movies' ); if( !empty( $movie_ratings ) ) { $num_of_ratings = array(); foreach( $movie_ratings as $meta_value ) $num_of_ratings[$meta_value] = ( isset( $num_of_ratings[$meta_value] ) ) ? $num_of_ratings[$meta_value] + 1 : 1; } /* Result: Array( [5] => 10 [9] => 2 ) // ie. there are 10 movie posts with a rating of 5 and 2 movie posts with a rating of 9. */ </code> This logic could be applied to various kinds of data, and extended to work any number of different ways. So i hope my examples have been helpful and simple enough to follow.
|
getting all values for a custom field key (cross-post)
|
wordpress
|
I transferred a website to VPS and when I open that website, the home page takes too long to load, for me its taking 30-35 secs just to display the home page, but when I navigate the internal pages it loads in normal speed, I also tried this when all of my plugins were deactivated, but no change, it was taking time to load.
|
There was a thread on wp-hackers in December which could be related: Avoid query_post on frontpage on wp initialization . You may give Sergey Biryukov’s code a try: I was able to cancel the initial query with this code in the active theme's functions.php file: <code> function cancel_first_query() { remove_filter('posts_request', 'cancel_first_query'); return ''; } add_filter('posts_request', 'cancel_first_query'); </code>
|
homepage loading too slow
|
wordpress
|
I'm developing a web application with user submissions, i'm not too hot on mod-rewrite and was hoping there is a way to utilise WordPress' amazing rewrite engine and incorporate this somehow into my PHP/AJAX web application?
|
I suggest you don't try to take out the <code> WP_Rewrite </code> class and re-use it in your application, but look at other frameworks instead. Many MVC frameworks have nice rewrite engines, that not only offer more flexibility in handling incoming URLs, but also generating internal links according to these formats. The WordPress rewrite system is tightly coupled to the rest of the code, and for all the effort it would take to rip it out, you can just as easily have learned how to use a "real" framework.
|
Use WordPress' URL rewrite engine
|
wordpress
|
I've been using a custom YOURLS system to create my own URL shortener for my blog network for a while now. Everything works just great with only a few exceptions (bugs already reported to the developer). But I'm aiming for something a bit more complicated that's not included in the existing WordPress YOURLS plug-in. Currently Right now, when a post is published, WordPress automatically logs in to YOURLS, creates a short URL, and pushes a notification to Twitter. It works well and keeps track of everything for me (the short URL is memorized by WordPress and inserted into appropriate <code> <meta> </code> tags as well). What I want to do I schedule my blog posts for 8am Pacific Time. This works well if you're on Twitter at 8am. But some people are browsing at lunch. Some in the evening. I want to schedule automated re-tweets of my short URL from within WordPress. Some posts I want pushed out once ... others I want pushed out at 2 or 3 strategic times during the day. How would I go about doing this?
|
I would probably go about this way: The plugin has a function called: <code> wp_ozh_yourls_send_tweet($tweet); </code> as you can see it accepts the tweet message and posts it to twitter, also it has another function called: <code> wp_ozh_yourls_geturl( $post_id ); </code> which accepts a post id and returns a shorturl as string. so after knowing that I would use these two in conjunction with wordpress's <code> wp_schedule_single_event </code> and create my own function to use the plugins functions. Now after that is said knowing how OZH codes his plugins i bet you can find hooks somewhere in there that will make you life a lot easier. Hope this helps.
|
Advanced Integration - WordPress + YOURLS
|
wordpress
|
I just changed my header from a background to an image, as that seemed to be the easiest way to link the entire header to my main page (after a whole lot of trial and error with other methods). The one problem is that the image is now overlapping my sidebar instead of the other way around. It's also overlapping some of my menu bar, but it's a part that I can live with or possibly fix myself. Here's my site with the header going over the sidebar. How do I get it back under the sidebar like it was before? And now that I think of it, is the whoe header being linked going to cause problems with the various links and buttons in the area where the sidebar overlaps it?
|
I'm not much of a CSS guru myself, but I think the z-index property might be helpful here. Check this link on Smashing Magazine: The Z-Index CSS property: A comprehensive look .
|
Header image is overlapping sidebar?
|
wordpress
|
In my website there are many authors who can publish posts but some of them are uploading images bigger than 1M , and I want to reduce the max upload size to 500 kb.
|
You can forbid uploads of a specific size (or for other reasons) in the <code> wp_handle_upload_prefilter </code> hook that is used in the <code> wp_handle_upload() </code> function . It get's the file array passed, it's a single item in the PHP standard superglobal <code> $_FILES </code> one that is documented in the PHP Manual: POST method uploads. Just create a function and add it to the filter. Inside your hook, check for the filesize and set <code> $file['error'] </code> to your error message like "Files larger than X bytes are prevented from uploads". <code> add_filter('wp_handle_upload_prefilter', function($file) { $size = $file['size']; if ($size > 500 * 1024) { $file['error'] = '"Files larger than X bytes are prevented from uploads.'; } return $file; }); </code> This method does not technically permit the upload which means, your server is still receiving the upload data of the file from the users browser. It's just thrown away afterwards. To prevent uploads of certain size at the server level, you need to configure your server accordingly for that which depends on what you use.
|
How to Reduce the Maximum Upload File Size?
|
wordpress
|
I've got a plugin that attaches itself to both the post and page editors to read and write to the post_content object. I'd like to also attach my plugin to the category manager edit screen. In the code below, lines 1 and 2 attach it to the post and page editor, but line 3, a shot in the dark, is not yet doing the trick. Any ideas on the proper way to do it? <code> if ( function_exists('add_meta_box') ) { add_meta_box('My-plugin', __('My plugin'), 'My_plugin_callback', 'post', 'side', 'high'); add_meta_box('My-plugin', __('My plugin'), 'My_plugin_callback', 'page', 'side', 'high'); //??? add_meta_box('My-plugin', __('My plugin'), 'My_plugin_callback', 'category', 'side', 'high'); } </code>
|
I'm pretty sure that even if you add that meta box at the bottom of the category edit you will still have the problem of meta table for categories, and i bet that your meta_box 'save' function saves as postmeta data table. However this can be done using the options table here is an how to add extra fields to categories Hope this helps
|
add_meta_box() to Category Edit Screen?
|
wordpress
|
I am generating a navigation menu on my website using the wp_list_pages() function and I also am using a couple of custom post types with a post type archive function. How would I go about adding a link to the wp_list_pages function to also include a link to my post type. The menu is as follows: Home Tour & Arrival Information Getting Around About Us Contact Us These are all pages and as such, are automatically found and placed into the list_pages function. I have a custom post type called sponsors which is a page that lists sponsors of the site. How do I add a link to /sponsors? Can you make Wordpress treat a custom post type as a page and link to it? I did try and use the Wordpress menus functionality, but it couldn't see my post type. I understand that the wp_list_pages uses internal functions to get pages with the post type of 'page' and that I need to use another function to accomplish what I am trying to do, however, I am stuck. I don't want to display posts using the post type 'sponsors' I just want to display a link to /sponsors that says sponsors, but allow the client to rearrange the order of the navigation which leads me to believe that I need to use a menu. Sorry if I didn't provide enough information, just ask if I didn't. I'm very busy at present and probably didn't describe myself properly.
|
I solved this issue a different way. I created a page called 'sponsors' and then created a custom page template that ignored any content entered into the editor and used some custom Wordpress queries to get content from my custom post type. It's so simple and works so well as well. The benefit is I have a page that is merely a proxy for other content and the menu order can be adjusted as if it were a normal page (well, it is).
|
Including link to custom post type in 'wp_list_pages' function
|
wordpress
|
I'm having trouble setting up permalinks for a custom post type. Below is the code from my init function: <code> register_post_type('topic', array( ... 'hierarchical' => true, 'query_var' => true, 'rewrite' => false, ... )); if(get_option('permalink_structure')!= ''): global $wp_rewrite; $wp_rewrite->add_rewrite_tag('%topic%', '(.+?)', 'topic='); $wp_rewrite->add_permastruct('topic', '%forum%/%topic%/', false, EP_PERMALINK); endif; </code> Basically I'm trying to set up permalinks my own way because I want to append a custom taxonomy term before the post title. Instead of: <code> topic/whatever </code> use: <code> general-forum/sub-forum/whatever </code> This is the function that changes the link, which seems to work ok: <code> add_filter('post_type_link', 'topic_link', 10, 4); function topic_link($link, $post){ if($post->post_type != 'topic') return $link; global $wp_post_types; $terms = get_the_terms($post->ID, 'forum'); if(!is_wp_error($terms) && !empty($terms)): usort($terms, '_usort_terms_by_id'); $forums = $terms[0]->slug; if(!empty($terms[0]->parent)): $parent_item = $terms[0]->parent; while(!empty($parent_item)): $parent = get_term($parent_item, 'forum'); if(!is_wp_error($parent) && !empty($parent)) $forums = $parent->slug.'/'.$forums; $parent_item = empty($parent->parent) ? false : $parent->parent; endwhile; endif; endif; return str_replace('%forum%', $forums, $link); } </code> So the modified URL is displayed fine, the only problem is that I get a 404 error :) What am I doing wrong in my init code? LE: the 'forum' taxonomy: <code> register_taxonomy( 'forum', array('topic', 'reply'), array( 'public' => true, 'name' => _a('Forums'), 'singular_name' => _a('Forum'), 'show_ui' => true, //'show_tagcloud' => true, 'show_in_nav_menus' => true, 'hierarchical' => true, 'labels' => array( 'name' => _a('Forums'), 'singular_name' => _a('Forum'), 'search_items' => _a('Search Forums'), 'popular_items' => _a('Popular Forums'), 'all_items' => _a('All Forums'), 'parent_item' => _a('Parent Forum'), 'parent_item_colon' => _a('Parent Forum:'), 'edit_item' => _a('Edit Forum'), 'update_item' => _a('Update Forum'), 'add_new_item' => _a('Add New Forum'), 'new_item_name' => _a('New Forum Name'), ), 'query_var' => true, 'rewrite' => array('slug' => 'forums', 'with_front' => false, 'hierarchical' => true), //'update_count_callback' => 'my_custom_count_callback', ) ); </code>
|
My plugin Custom Post Permalinks does this sort of thing for you: http://wordpress.org/extend/plugins/custom-post-permalinks If you'd rather use your own solution, I'll need a bit more information, such as the registration code for the forums taxonomy. Just guessing, I'm thinking the regex for a forum looks identical to the regex for a topic to the rewrite engine. EDIT Looking at your code, it looks like you're using 3.1. The <code> $args['rewrite']['hierarchical'] </code> bit for taxonomies wasn't in 3.0. Basically, what that argument does is changes the regular expression for the <code> %forum% </code> tag from <code> ([^/]) </code> to <code> (.+?) </code> . This means that WordPress' rewrite engine gets a match for this regular expression first: <code> @/(.+?)/(.+?)/?$ </code> Which, for something like <code> /generic-forum/specific-forum/specific-topic </code> , will parse to this: <code> index.php?forum=generic-forum&topic=specific-forum/specific-topic </code> To test if this is really what's causing the 404, change the taxonomy's rewrite args so that <code> ['rewrite']['hierarchical'] </code> is either not set or set to false, flush the rewrite rules, and modify your topic link function not to add parents to the link; Then test to see if the new links work. If this is the cause of the problems, there are a couple of ways to fix this. The easiest would be to add a bit of plain text to the permastruct, like this: <code> %forum%/topic/%topic% </code> . That would give you links like this: <code> /general-forum/sub-forum/topic/whatever </code> . Another way would be to add another rewrite tag like this: <code> $wp_rewrite->add_rewrite_tag( '%post_type_topic%', '(topic)', 'post_type=' ); </code> then change the permastruct to '%forum%/%post_type_topic%/%topic%'.
|
Custom post type permalinks giving 404s
|
wordpress
|
Is there anyway to show different information shown about custom post types in their list in the admin, wp-admin/edit.php?post_type=myposttype ? Obviously I could rip it apart by adding php or js to the admin_head action, but is there a core wp way.
|
If you mean change the columns that show op on the list of posts/custom post types the there is a "WordPress way" to do that, take a look at http://shibashake.com/wordpress-theme/add-custom-post-type-columns and stackexchange-url ("jan answer to a similar question") Hope this Helps
|
Change headers in admin posts list
|
wordpress
|
I recently moved a blog from one host to another and now have a problem with a permalink - rather than opening up a page, it now opens an attachment. The blog is using WP 3.0.4, running on PHP 5 and IIS 7.0. The permalinks are set to use "/%postname%/" and the web.config is as suggested in the Codex . The blog was moved using the WP export and import tools. Previously http://site/blog/map opened up a page called map, but it is now opening http://site/blog/?attachment_id=xx . Does anyone know how to change this behaviour? Thanks, Jon.
|
Attachments are stored with their filename (minus extension) as the post name. So if you uploaded an attachment that's called map.xyz, it would have the same name as your page. So first, check your Media Library if you have a 'map' attachment. Secondly, check if your 'map' page still exists and still has the same slug. When wordpress tries to resolve your request, it can't figure if your are referring to a post(/attachment) or a page. I would imagine that wordpress also does some slug mingling in the process of importing an export to avoid duplication of post names. It may have imported the attachment first and the page after and mingled your page name into something else. Try using /posts/%postname%/ for your permalinks, this will distinguish them from pages. Also read: http://codex.wordpress.org/Using_Permalinks#Structure_Tags
|
Permalink opens attachment instead of page
|
wordpress
|
i've downloaded a wordpress web to my local machine and tried setting it up. the problem: when trying to login, wordpress will always redirect to the online url. the only way i found was changing the siteurl manually in phpmyadmin to my local machine's ip address. is there a better solution? the problem about doing that is that permalinks won't work anymore locally. thanks
|
Open up your <code> wp-config.php </code> file try adding the following to it: <code> define( 'WP_SITEURL', 'http://localhost/your_wordpress_folder' ); define( 'WP_HOME', 'http://localhost/your_wordpress_folder' ); </code>
|
Wordpress on a local machine redirecting to online url
|
wordpress
|
I am having a problem. I am running WP 3.05 with one custom taxonomy. Here is the code to create the taxonomy: <code> function create_property_taxonomies() { // Add new taxonomy, make it hierarchical (like categories) $labels = array( 'name' => _x( 'Property Types', 'taxonomy general name' ), 'singular_name' => _x( 'Property Type', 'taxonomy singular name' ), 'search_items' => __( 'Search Property Types' ), 'all_items' => __( 'All Property Types' ), 'parent_item' => __( 'Parent Property Type' ), 'parent_item_colon' => __( 'Parent Property Type:' ), 'edit_item' => __( 'Edit Property Typee' ), 'update_item' => __( 'Update Property Type' ), 'add_new_item' => __( 'Add New Property Type' ), 'new_item_name' => __( 'New Property Type' ), 'menu_name' => __( 'Property Type' ), ); register_taxonomy('property_type',array('sbproperty'), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'query_var' => true, 'rewrite' => true, )); global $wp_rewrite; $wp_rewrite->extra_permastructs['property_type'] = array('%property_type%', EP_NONE); } </code> I have used the extra permastruct so the taxonomy just appears on the base url like site.com/taxonomy-slug instead of site.com/taxonomy/taxonomy-slug I am also using the top-level-cats plugin to do the same for original taxonomies. But this is causing a conflict with my pages. When I remove the permastruct the page loads on the pretty permalink, but with my permastruct on it does not, it gives a 404 for all top level pages.
|
Sorry guys, this is becoming a habit, but I found a solution, as follows: set rewrite to false in taxonomy registration: register_taxonomy('property_type',array('sbproperty'), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'query_var' => true, 'rewrite' => false )); And create my own rule <code> add_filter('rewrite_rules_array','wp_insertMyRewriteRules'); add_filter('init','flushRules'); function flushRules(){ global $wp_rewrite; $wp_rewrite->flush_rules(); } function wp_insertMyRewriteRules($rules) { $newrules = array(); $newrules["([a-z]+)-in-turkey-for-sale/?$"] 'index.php?property_type=$matches[1]-in-turkey-for-sale'; return $newrules + $rules; } </code>
|
Permalink Problems
|
wordpress
|
The function get_users_of_blog() is to be deprecated in WP 3.1.0 but the current production release is 3.0.5. Does it make since to have the documentation reflect a nightly change when the production version of get_users_of_blog() is still the primary function used to fetch a list of users? Or is it fine so long as the version it is deprecated is listed on the article? I reverted the page back to reflect that it was not deprecated but it was reverted quickly back to it's original state. I'm probably just missing something and was hoping someone would shed some light on this. EDIT @kaiser pointed out that the codex is a wild-west of sorts, some articles are up-to-future to 3.1, up-to-date with 3.0.5, and others are very outdated. Refocusing my question, what should be the best practice for documentation on a popular framework like Wordpress that does have public nightly builds?
|
The codex is some kind of a mess. General behavior is to let users (re)write it and then go over it and change what they (whoever this is) think. Ex. The Codex lacks a lot of functions in the function reference. On some places you already got the 3.1 explanations, on other completely outdated stuff. Sometimes you'll find two versions (current and future) or existing empty pages for template tags coming in the future .
|
Codex Version Focus on Production or Nightly?
|
wordpress
|
My server has 756m of RAM. Every few days I get [error] server reached MaxClients setting, consider raising the MaxClients setting
|
Just to break cycle of "doesn't belong here". WordPress basically has no specific requirements for web server itself (which doesn't even have to be Apache), aside from permalinks. The message you are getting seems to be performance-related and may or may not be connected to you using WordPress. For starters check if your traffic had recently increased and ask your hosting if they recommend specific Apache configuration for your hardware and traffic.
|
What are some good Apache settings to use with wordpress?
|
wordpress
|
I want to be able to customize the WordPress edit posts screen to filter based on a custom field (or whatever). Unfortunately I'm not sure what filter or hook to use here, and instead of opening the code myself, figured I'd throw the question out here. Just to be clear, I'm talking about this screen. Essentially I want to be able to add a new "tab" next to Drafts, Pending, etc. Update After testing this, here's the solution: <code> add_filter( 'parse_query', 'filter_post_edit_screen' ); function filter_post_edit_screen($query) { global $pagenow; if (is_admin() && $pagenow=='edit.php'){ $query->query_vars['category__not_in'] = array(120,9999); } return $query; } </code> That's it. Just paste that into a plugin. Obviously you'd tweak the category IDs or add some more substantial code.
|
You need a to use a few hooks for that take a look at stackexchange-url ("mike's answer") to a similar question. Hope this Helps
|
Is There a WordPress Hook to Filter the Edit Posts View?
|
wordpress
|
I'm trying to create a forum system using WP's custom post types - two post types as Topic/Reply and a Forum taxonomy. I have created a singular template for the topic post type, in which I added a reply form. The problem is that when I submit the form I get a 404 page. This is the form template: <code> <div class="topic-reply-form"> <form method="post" name="topic-reply-form" class="topic-reply-form clear-block" action="<?php echo home_url('/'); ?>"> <p><?php _ae("Add reply"); ?></p> <fieldset> <textarea id="reply-content" name="content" cols="50" rows="6"></textarea> <input type="hidden" name="topic" value="<?php the_ID(); ?>" /> <?php wp_nonce_field('new-topic-reply'); ?> <input type="submit" value="Publish" id="reply-submit" name="reply-submit" /> </fieldset> </form> </div> </code> Any ideas why this is happening?
|
it was the "topic" name field. It seems you can't use reserved terms in $_POST, and "topic" is a post type name, so its probably one of them...
|
404 Error on form submission within custom post type
|
wordpress
|
I need to find if a post with a custom field X equal to Y exists in a wordpress installation. Should I do it with a simple sql query or is there something build in that can help me achieve it?
|
You can use the WP_Query (); to check that like this: <code> $my_query = new WP_Query(); $my_query->query(array( 'meta_key' => 'X', 'meta_value' => 'Y')); if ( $my_query->have_posts() ){ //it exists } else { //it's not here } </code> Hope this helps.
|
How to find if a post with custom_field == X exists?
|
wordpress
|
I know I can control the length of excerpts using a filter , however it sets the length globally. In my case I have different lengths of excerpts on three different pages. This is what I have now. I'd like to improve it so it doesn't truncate words. <code> $content_to_excerpt = strip_tags( strip_shortcodes( get_the_content() ) ); $pos = strpos($content_to_excerpt, ' ', 160); if ($pos !== false) { echo "<p>" . substr($content_to_excerpt, 0, $pos) . "...</p>"; } </code>
|
Set the filter dynamically based on the page you are loading. If category archive pages have a 100 word excerpt, but posts have a 10 word excerpt, and everything else uses the default: <code> function my_custom_excerpt_length( $orig ) { if( is_category() ) { return 100; } elseif( is_single() ) { return 10; } return $orig; } add_filter( 'excerpt_length', 'my_custom_excerpt_length' ); </code> You can get even more specific, giving specific categories a different length. In response to Rarst, a new template function <code> the_excerpt_length() </code> for outputting the excerpt with a specific number of words: <code> // Excerpt with a specific number of words, i.e. the_excerpt( 100 ); function the_excerpt_length( $words = null ) { global $_the_excerpt_length_filter; if( isset($words) ) { $_the_excerpt_length_filter = $words; } add_filter( 'excerpt_length', '_the_excerpt_length_filter' ); the_excerpt(); remove_filter( 'excerpt_length', '_the_excerpt_length_filter' ); // reset the global $_the_excerpt_length_filter = null; } function _the_excerpt_length_filter( $default ) { global $_the_excerpt_length_filter; if( isset($_the_excerpt_length_filter) ) { return $_the_excerpt_length_filter; } return $default; } </code> This would be used in your template file, i.e.: <code> <div class="entry"> <?php the_excerpt_length( 25 ); ?> </div> </code>
|
Excerpts that don't truncate words
|
wordpress
|
How can I find out if I am on the 1st page of my home page. I have my page setup like below where I want to display the 1st 2 posts taking up full width. then the rest 1/2. But I want this behaviour on the 1st page only, how can I do that? What condition do I use?
|
I'm assuming that you're talking about the "home page" when you say "1st page only". Or are you talking about the first "paginated" page of your posts? If its the prior, you'd probably want to use the "is_front_page()" conditional if you're using a single page.php template. Or maybe it'd be easier to make a "page-home.php" template and do some sort of new query of your posts...just for that page. Would that work?
|
How to know if I am on 1st page
|
wordpress
|
The default WP media manager does not appear to offer the ability to change an image's filename. Are there any plugins available that allow this functionality?
|
Try the Media File Renamer .
|
Any way to change the actual filename of an image from media manager?
|
wordpress
|
The other day, I switched from 2010 default them to Semiologic, then back. When back to the 2010, all my appearance/widgets had gone back to the default. Does this often happen? What is the best practice? Should I always do a database backup before trying new themes, then restore if I don't like it? Or is there something simple I might have missed?
|
Storing widgets is complex topic. Basically it is such a multi-level-array-mess on the inside that very few people try to make sense of it (and even fewer succeed). :) As far as I understand it myself while we can manipulate cute sidebar names on the surface, deep inside it is getting deconstructed to numerical IDs. So when you switch between themes amount and order of available IDs shift and widgets go haywire. In theory any widget that can't find its designated place is supposed to land in "Inactive Widgets" area. In practice - who knows. I experienced widgets disappearing, appearing, duplicating and whatever. So if you have any kind of complex widget setup I highly recommend not to experiment with themes on it. I have stockpiled idea to do reliable widget import/export, but it will take me plenty more time to gather enough courage to touch that. Did I say it is a mess inside? :)
|
Switching themes without losing widgets?
|
wordpress
|
I'm building a custom homepage for a client where they want to have a few changeable boxes to link to specific pages, or posts, within the site. I've added custom fields to the homepage so that they need only enter the page/post ID, and then it will display the proper post or page. And I'd like it to be flexible enough that they can do a post or page. Right now, my code for the box is <code> <?php query_posts('p='.$topright); ?> <?php while (have_posts()) : the_post(); ?> {title and featured image} <?php endwhile; ?> </code> where $topright is a variable already defined. (I've tested the variable with an echo and it is returning the proper ID number.) Unfortunately, WordPress seems to require that I use p=ID if it is a post, and page_id=ID if it is a page. So, if I designate the ID for a post, it is working fine, but not if I desingate the ID for a page. Is there an alternative syntax I could use? Or, it there a conditional of some kind that might look a the ID and recognize if it is a post or a page so I could run the query with an IF ELSE?
|
Try this: <code> query_posts(array( 'p' => $topright, 'post_type' => array('post', 'page'), )); </code>
|
use query_posts to return a post OR a page by ID
|
wordpress
|
I'm looking for a way to change the WordPress favicon. Any hints how to do this?
|
You should add it on your theme's header.php file with this code (W3C standard code): <code> <link rel="icon" type="image/png" href="http://yourblog.com/favicon.png"> </code>
|
How to change the WordPress favicon?
|
wordpress
|
I'm setting up a simple web site for a member of my family, using wordpress as a CMS. I've already registered a domain name and I'm about to set up wordpress. I want them to be able to edit the site content online (using wordpress's admin interface) and view the site, but I don't want the site to be available to the public while it's in the editing stages. Can anyone suggest a good way to prevent access to the public (for example a "coming soon" page, but access to the main site via a password; or perhaps put the wordpress installation in a subdirectory while the site is in the editing stages, and then use url rewriting to redirect the root directory to the subdirectory when the site goes live). I should mention that I'm relatively new to wordpress, so if this kind of functionality is built in I apologise for asking the question.
|
I also have had problems with the maintenance plugins. What you can do instead (if you are familiar with HTML) is create a simple "Closed for Maintenance" page. Save the page as xindex.html . Upload the xindex.page to the same directory as your WordPress installation. You Wordpress installation comes with two files index.html and index.php. While you are working or doing maintenance to your site, first rename the existing index.html file as realindex.html then rename the xindex.html that you uploaded as index.html. This will replace the Wordpress homepage with your maintenance page. When you are finished working and are ready to display your site, reverse your steps. Rename the current index.html back to xindex.html and change realindex.html back to index.html. Sounds more complex than it is in practice, but it entirely avoids buggy plugins. Here's a link to my maintenance page. You can copy the source. Closed for Maintenance
|
Wordpress CMS - hide content from public while in editing stages
|
wordpress
|
Today morning on valentines I received a shocking mail from my WordPress site, Don't know what to do, Can anyone help me out in this Subject: [Online MBA] High memory usage notification Sent: Feb 13, 2011 11:33 PM WordPress memory usage exceeded 64 MB WordPress peak memory usage: 114.87 MB Number of database queries: 173
|
This mail seems to come from the TPC! Memory Usage plugin . The description includes Send e-mail notification if memory usage reaches threshold setting , and it seems that is what happened here. Either change your plugins so they use less memory, increase the notification limit, or remove this plugin.
|
Notification mail about high memory usage?
|
wordpress
|
How can I implement pagination like shown in the title perhaps something similar to most sites
|
I can across this awesome tutorial just the other day: http://design.sparklette.net/teaches/how-to-add-wordpress-pagination-without-a-plugin/ which is a modified version of this one: http://www.kriesi.at/archives/how-to-build-a-wordpress-post-pagination-without-plugin
|
How to implement pagination eg. newer - 3 - 4 - 5 - 6 - 7 - older
|
wordpress
|
I just tried an automatic upgrade of List Category Posts plugin to version 0.17.2 on WordPress 3.0.5. I think I had 0.17.1 before. It installed but failed to activate: <code> Plugin could not be activated because it triggered a fatal error. Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /hsphere/local/home/carrollp/clanecommunity.ie/wp-content/plugins/list-category-posts/include/CatListDisplayer.php on line 10 </code> If I understand correctly author has requested issues be posted here. I've never debugged WordPress before. Appreciate any help. My site home page is relying on this plugin. Thanks!
|
Yes, I've asked for issues to be reported here, so that you can get answers from the larger community of WordPress users and developers at WordPress Answers. Regarding the issue, other user also reported it, and it is due to the webhost using PHP 4. Line 10 of CatListDisplayer.php declares a private attribute. PHP 4 doesn't have public, private or protected accessors. Is there a way to ask your webhosting provider to update your server to PHP 5? The other possible solution is to download the previous version of the plugin: 0.16, which doesn't use Object Oriented PHP.
|
List Category Posts plugin upgrade fails with fatal error
|
wordpress
|
If I have a loop running from a category query like : <code> <?php $the_query = new WP_Query('cat=1&showposts=50&orderby=title&order=asc');?> <ul> <?php while ($the_query->have_posts()) : $the_query->the_post();?> <li>.. </li><?php wp_reset_query(); ?> <?php endwhile; ?> </ul> </code> How would I create an if clause that breaks the list at a certain interval, and starts a new one. So for example at the 10th post, return a <code> </ul> </code> and start a new one <code> <ul> </code> at 11. This is incorrect but to illustrate my objective: <code> <?php $count =0; while($count <=50){ if ($count == 9){ echo "<li><a href='<?php the_permalink(); ?>'> <?php the_title(); ?></a></li></ul>"; } elseif ($count == 10){ echo "<ul><li><a href='<?php the_permalink(); ?>'> <?php the_title(); ?></a></li>"; } else { echo "<li><a href='<?php the_permalink(); ?>'><?php the_title(); ?></a></li>"; } </code> What is the correct way to include this logic into the loop?
|
Create Columns for your query and easy display In themes is probably more useful to have something that fits well into template tags and the loop. My first answer didn't focus on that much. Additionally I thought it's a bit too complicated for a quick adoption. An easier approach that popped into my mind was to extend "the loop" with columns and came to this solution so far: A WP_Query_Columns object "extends" any standard WP query with colums that can be easily iterated over. The first parameter is the query variable and the second parameter is the number of items to be displayed per column: <code> <?php $the_query = new WP_Query('cat=1&showposts=50&orderby=title&order=asc');?> <?php foreach(new WP_Query_Columns($the_query, 10) as $column_count) : ?> <ul> <?php while ($column_count--) : $the_query->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul> <?php endforeach; ?> </code> To use it, just add the WP_Query_Columns class from this gist to your themes function.php. Advanced Usage If you need the column number you're currently displaying (e.g. for some even/odd CSS classes, you can get that from the foreach as well: <code> <?php foreach(new WP_Query_Columns($the_query, 10) as $column => $column_count) : ?> </code> And the total number of columns is available as well: <code> <?php $the_columns = new WP_Query_Columns($the_query, 10); foreach($the_columns as $column => $column_count) : ?> <h2>Column <?php echo $column; ?>/<?php echo sizeof($the_columns); ?></h2> <ul>... </code> Twenty Ten Example I could quickly hack twenty ten theme for a test and adding headlines above any loop this way. It's inserted into loop.php, the beginning is the theme's code: <code> <?php /* If there are no posts to display, such as an empty archive page */ ?> <?php if ( ! have_posts() ) : ?> <div id="post-0" class="post error404 not-found"> <h1 class="entry-title"><?php _e( 'Not Found', 'twentyten' ); ?></h1> <div class="entry-content"> <p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'twentyten' ); ?></p> <?php get_search_form(); ?> </div><!-- .entry-content --> </div><!-- #post-0 --> <?php endif; ?> <!-- WP_Query_Columns --> <?php ### Needs WP_Query_Columns --- see stackexchange-url $query_copy = clone $wp_query; // save to restore later foreach( new WP_Query_Columns($wp_query, 3) as $columns_index => $column_count ) : ?> <ul> <?php while ( $column_count-- ) : the_post(); ?> <li><h2 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></h2></li> <?php endwhile; ?> </ul> <?php endforeach; ?> <?php $wp_query = $query_copy;?> <?php /* Start the Loop. ... </code> For a longer answer: (that is basically how I came to the stuff above, but explains better how to actually solve the problem with simple mathematic operations. My new solution is to iterate over something pre-calculated.) It depends a bit how much you actually need to solve the problem. For example, if the number of items per column equals one, this is very simple: <code> <?php $the_query = new WP_Query('cat=1&showposts=50&orderby=title&order=asc');?> <?php while ($the_query->have_posts()) : $the_query->the_post();?> <ul> <li>.. </li> <ul> <?php endwhile; wp_reset_query(); ?> </ul> </code> Even with that simple code, it can be seen that there are multiple decisions to be made: How many items are in one column? How many items are there in total? Is there a new column to start? And is there a column to end? The last question is pretty interestering for HTML output as you probably want to enclose not only items but also the column with html elements. Luckily with code, we can set all these in variables and create code that always computes to our needs. And sometimes even, we can not even answer every question from the beginning. For exmaple, the count of total items: Are there any, some, multiple, an exact count that matches up with an integer number of columns in total? Even Jan Fabry's answer might work in some cases (as my example above does for the one-item-per-column scenario), you might be interested in something that works for any number of items returned by WP_Query. First for the math: <code> // // arithmetical example: // # configuration: $colSize = 20; // number of items in a column $itemsTotal = 50; // number of items (total) # calculation: $count = 0; // a zero-based counter variable $isStartOfNewColum = 0 === ($count % $colSize); // modulo operation $isEndOfColumn = ($count && $isStartOfNewColum) || $count === $itemsTotal; // encapsulation </code> That code doesn't run, so let's put that up into a simple text example <code> // // simple-text example: // $column = 0; // init a column counter for($count=0; $count<= $itemsTotal; $count++) { $isStartOfNewColum = 0 === ($count % $colSize); // modulo $isEndOfColumn = ($count && $isStartOfNewColum); $isStartOfNewColum && $column++; // update column counter if ($isEndOfColumn) { printf("/End of Column: %d\n", $column-1); } if ($isStartOfNewColum) { printf("<start of Column: %d\n", $column); } printf(" * item %d\n", $count); } if ($count && !$isEndOfColumn && --$count === $itemsTotal) { printf("/End of Column: %d\n", $column); } printf("Done. Total Number of Columns: %d.\n", $column); </code> This actually runs and does some output already: <code> <start of Column: 1 * item 0 * item 1 * item 2 * item 3 ... * item 17 * item 18 * item 19 /End of Column: 1 <start of Column: 2 * item 20 * item 21 * item 22 ... * item 37 * item 38 * item 39 /End of Column: 2 <start of Column: 3 * item 40 * item 41 * item 42 ... * item 48 * item 49 * item 50 /End of Column: 3 Done. Total Number of Columns: 3. </code> This simulates already pretty well how it could look like in a wordpress template: <code> // // wordpress example: // $count = 0; // init item counter $column = 0; // init column counter $colSize = 10; // column size of ten this time $the_query = new WP_Query('cat=1&showposts=50&orderby=title&order=asc'); $itemsTotal = $the_query->post_count; ?> <?php while ($the_query->have_posts()) : $the_query->the_post();?> <?php # columns display variables $isStartOfNewColum = 0 === ($count % $colSize); // modulo $isEndOfColumn = ($count && $isStartOfNewColum); $isStartOfNewColum && $column++; // update column counter if ($isEndOfColumn) { print('</ul>'); } if ($isStartOfNewColum) { printf('<ul class="col-%d">', $column); } ?> <li> ... make your day ... </li> <?php endwhile; ?> <?php if ($count && !$isEndOfColumn && --$count === $itemsTotal) { print('</ul>'); } // You don't have to do this in every loop, just once at the end should be enough wp_reset_query(); ?> </code> (I have not executed the last example in a WP environment, but it should be at least syntactically correct.)
|
How to split a loop into multiple columns
|
wordpress
|
I'm using the theme Starkers which is based on twentyten. My twenty ten theme do place child pages below its parent page. But the new theme (based on Starkers) I'm developing doesn't (it just place it in the first level). My theme header.php: <code> <div id="access" role="navigation"> <?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?> </div><!-- #access --> <div id="branding"> <h1> <?php if (get_option(THEME_PREFIX . "logo_image_enabled")) { ?> <a href="<?php bloginfo('url'); ?>" title="<?php bloginfo('name'); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/<?php echo get_option(THEME_PREFIX . 'logo_image'); ?>" /></a> <?php } else { ?> <a href="<?php bloginfo('url'); ?>"><?php echo get_option(THEME_PREFIX . "logo_text"); ?></a> <?php } ?> </h1> </div><!-- #branding --> </code> twentyten's: <code> <div id="access" role="navigation"> <?php /* Allow screen readers / text browsers to skip the navigation menu and get right to the good stuff */ ?> <div class="skip-link screen-reader-text"><a href="#content" title="<?php esc_attr_e( 'Skip to content', 'twentyten' ); ?>"><?php _e( 'Skip to content', 'twentyten' ); ?></a></div> <?php /* Our navigation menu. If one isn't filled out, wp_nav_menu falls back to wp_page_menu. The menu assiged to the primary position is the one used. If none is assigned, the menu with the lowest ID is used. */ ?> <?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?> </div><!-- #access --> </code> My theme's output: <code> <div id="access" role="navigation"> <div class="menu"> <ul> <li class="current_page_item"><a href="http://localhost/bf3/" title="Home">Home</a></li> <li class="page_item page-item-23"><a href="http://localhost/bf3/?page_id=23" title="Blog">Blog</a></li> <li class="page_item page-item-63"><a href="http://localhost/bf3/?page_id=63" title="Home sub">Home sub</a></li> </ul> </div> </div><!-- #access --> </code> twenty-ten's: <code> <div id="access" role="navigation"> <div class="skip-link screen-reader-text"><a href="#content" title="Skip to content">Skip to content</a></div> <div class="menu-header"> <ul id="menu-custom-menu" class="menu"> <li id="menu-item-66" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-66"><a href="http://localhost/bf3/?page_id=23">Blog</a></li> <li id="menu-item-67" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-2 current_page_item menu-item-67"><a href="http://localhost/bf3/">Home</a> <ul class="sub-menu"> <li id="menu-item-65" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-65"><a href="http://localhost/bf3/?page_id=63">Home sub</a></li> </ul> </li> </ul></div> </div><!-- #access --> </code> (Twenty-ten adds a unordered list with the class <code> .sub-menu </code> ). (My functions.php was directly taken from twentyten's). Does anybody know which file and section makes the child pages sub-menus in the <code> wp_nav_menu </code> part of the header?
|
Check the twenty ten themes function file, there should be a function to register menus. After adding it to your theme you'll have a new tab in your admin panel under appearance called menu where you can set the menu's items and sub items. Line 96 in the functions.php file <code> // This theme uses wp_nav_menu() in one location. register_nav_menus( array( 'primary' => __( 'Primary Navigation', 'twentyten' ), ) ); </code>
|
Child pages don't become submenus (as in the twenty-ten theme)?
|
wordpress
|
I'm working on a shortcode function that returns a category image, a link to the category, the last three posts in that category, and another link to the category. See my code below: <code> add_shortcode('caticons_listing','bm_caticons_listing'); function bm_caticons_listing($atts) { extract( shortcode_atts( array( 'include' => '', 'exclude' => '', 'small' => 'true' ), $atts ) ); if ($atts['include']) $include = "&include=".$atts['include']; if ($atts['exclude']) $exclude = "&exclude=".$atts['exclude']; if ($atts['small'] == 'false') $small = "&small=false"; $listing_code .= '<table class="cat-nav">'; foreach(get_categories("orderby=name&order=ASC&hide_empty=0".$include.$exclude) as $category) { if (category_description($category->cat_ID)) { $desc = category_description($category->cat_ID); } else { $desc = "Coming soon!";} if ($category->count > 0) { $seemore = '<br /><a href="'.get_category_link( $category->term_id ).'">See more.</a>';} else {$seemore = '';} query_posts('cat='.$category->term_id.'&showposts=3'); $listing_code .= '<tr><td>'.get_cat_icon("echo=false".$small."&class=caticon&cat=".$category->cat_ID).'</td><td valign="top" style="padding: 5px;"><a href="'.get_category_link( $category->term_id ).'"><h2 style="font-size: 130%;">'.$category->cat_name.'</h2></a>'.category_description($category->cat_ID).'<br />'; //$listing_code .= "I think I need a loop here."; $listing_code .= $seemore.'</td></tr>'; } $listing_code .= '</table>'; return $listing_code; } </code> My issue is, with the way the WP loop examples are written, I can't figure out a good way to output the three latest posts as links in a manner that can be stored as a variable (to be returned as the shortcode output). Any help would be appreciated. Thanks!
|
First, need to lose <code> query_posts() </code> - it should never be used for secondary loops. Try something like this: <code> $posts = get_posts( array( 'cat' => $category->term_id, 'numberposts' => 3, )); foreach( $posts as $post ) { $listing_code .= get_permalink( $post->ID ); //or whatever } </code>
|
Output loop to function return?
|
wordpress
|
How should I handle post thumbnails? Do most people put them in custom fields? Use a plugin? How do themes on ThemeForest handle this? Also different theme will have different size requirements? So moving from 1 theme to the next could cause alot of problems? Thumbnails may come in different sizes too
|
Since WordPress 2.9, you can add thumbnail support to your theme by adding this to the theme's functions.php file: <code> if ( function_exists( 'add_theme_support' ) ) { add_theme_support( 'post-thumbnails' ); } </code> When this is done, you'll be able to add a feature image to your post on Posts, Pages or Custom Post Types. You'll see the "Featured Image" box when creating a new post. You can set the thumbnail size also in your functions.php file. You can use WordPress' "thumbnail", "medium" and "large" sizes, create your own or specify a size with pixels: <code> the_post_thumbnail('thumbnail'); // Thumbnail (default 150px x 150px max) the_post_thumbnail('medium'); // Medium resolution (default 300px x 300px max) the_post_thumbnail('large'); // Large resolution (default 640px x 640px max) the_post_thumbnail( array(100,100) ); // Specify resolution //Add your own: add_image_size( 'category-thumb', 300, 9999 ); //300 pixels wide (and unlimited height) </code> Example of how to use this new Post Thumbnail size in theme template files. <code> <?php the_post_thumbnail( 'category-thumb' ); ?> </code> You should check Codex's page on Post Thumbnails for more info. There you'll also find how to style your thumbnails and more details on this code.
|
How to handle thumbnails
|
wordpress
|
We are currently in development on a new site. Categories (& tags) are pretty much meaningless for us because we've implemented custom posts & taxonomies. By default, because I have enabled pretty permalinks, if I create a post titled, "Mubarak steps down" without selecting a category, Wordpress will give me this: domain.com/uncategorized/mubarak-steps-down. Today, I installed the custom permalinks plugin which enables me to make the permalink virtually anything I want. I have a custom taxonomy called countries and one of the terms is Egypt so I re-wrote the above permalink to be domain.com/countries/egypt/mubarak-steps-down. domain.com/egypt/mubarak-steps-down would be better but there's nothing there & writing a re-direct for all countries would be a major pain. The pros, as I see them, in doing this: 1) A reader may realize that by removing the post title and re-submitting the url in the browser that they will see more content on the parent subject most relevant to the individual post, in this case, Egypt. Of course, this can also be done by making a link to the Egypt section on the page easy to see. 2) I think* it could be an effective white hat SEO strategy for communicating something more relevant in the url than 'uncategorized' or something else generic like 'events' or 'news.' What are the pros and cons of doing this with respect to WP database performance, etc.?
|
For the SEO part you might get better answers on stackexchange-url ("the Pro Webmasters Stack Exchange"). I will focus on the performance. From your example I assume your permalink structure was <code> %category%/%postname%/ </code> . Because of the way WordPress parses the incoming URL, this will result in verbose page rules , which means that each page (not post) you create gets their own set of rewrite rules. If you don't have many pages this does not matter much, if you have a lot of pages (say, above 50), this can be a serious performance hit or even stop your site from working. You use the Custom Permalinks plugin, but a quick look at the code makes me doubt it will scale well when you have a lot of posts. I'm not a MySQL expert, but I think the database can't use an index effectively to speed up that query it does at every URL request. If you want to use the same structure for every post ( <code> %custom-taxonomy%/%postname%/ </code> ), I suggest you modify the rewrite rules to match this. I believe you can even do this by setting the permalink structure to <code> %category%/%postname%/ </code> and filtering the <code> post_rewrite_rules </code> by replacing <code> category </code> with your custom taxonomy slug. But if you don't use categories, wouldn't it be easier to re-use this taxonomy so it fits your needs? You can stackexchange-url ("change the labels of the default taxonomies") so they look like your custom taxonomies. The benefit is that categories have very strong support everywhere in WordPress, while the custom taxonomies are still new and can't always do everything (as easy) as categories can.
|
Pros and cons of using [taxonomy name] in place of [category name]?
|
wordpress
|
I'm wondering what the preferred method is for dealing with AJAX calls. Should one use the same plugin php file to process the POST or a separate one? Which is cleaner or safer?
|
the "safer and cleaner" way would be to use admin-ajax.php that comes with wordpress and <code> wp_ajax </code> hook to call you processing function from your plugin file and use wp-nonce to check the integrity of the call. for example: your ajax JQuery call would be <code> <script type="text/javascript" > jQuery(document).ready(function($) { var data = { action: 'ACTION_NAME', Whatever: '1234', _ajax_nonce: '<?php echo wp_create_nonce( 'my_ajax_nonce' ); ?>' }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php // If you need it on a public facing page, uncomment the following line: // var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; jQuery.post(ajaxurl, data, function(response) { alert('Got this from the server: ' + response); }); }); </script> </code> the in your plugin file add <code> //if you want only logged in users to access this function use this hook add_action('wp_ajax_ACTION_NAME', 'my_AJAX_processing_function'); //if you want none logged in users to access this function use this hook add_action('wp_ajax_nopriv_ACTION_NAME', 'my_AJAX_processing_function'); </code> *if you want logged in users and guests to access your function by ajax the add both hooks. *ACTION_NAME must match the action value in your ajax POST. then in your function just make sure the request came from valid source <code> function my_AJAX_processing_function(){ check_ajax_referer('my_ajax_nonce'); //do stuff here } </code> Hope this Helps
|
What's the preferred method of writing AJAX-enabled plugins?
|
wordpress
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.