question
stringlengths 0
34.8k
| answer
stringlengths 0
28.3k
| title
stringlengths 7
150
| forum_tag
stringclasses 12
values |
---|---|---|---|
I want to develop a plugin that generates a page and embeds the page link in pages menu in the client part at the time of plugin activation. Please help me with this.
|
You can create the page using wp_insert_post() and make sure you send post type as 'page'. and if the user nav menu uses wp_list_pages the page will be added to the nav menu automatically and to run it on activation you can have you plugin check if it exists and save its id so it will only create it once. <code> $my_page = get_option('my_plugin_page'); if (!$my_page){ // Create post/page object $my_new_page = array( 'post_title' => 'My page', 'post_content' => 'This is my page content.', 'post_status' => 'publish' ); // Insert the post into the database $my_page = wp_insert_post( $my_new_page ); update_option('my_plugin_page',$my_page); } </code>
|
How can I develop a plugin that generates a page dynamically
|
wordpress
|
I set <code> add_filter( 'http_request_redirection_count', array($instance,'SetDirectionCount')); </code> to 0 I try to get 'http://boards.ign.com/The_Vestibule/b5296/' or 'http://www.informationweek.com/story/' but that gives me: <code> WP_Error Object ( [errors] => Array ( [http_request_failed] => Array ( [0] => Maximum (0) redirects followed ) ) [error_data] => Array ( ) ) </code> The head does not show me a redirection: <code> Array ( [headers] => Array ( [connection] => close [date] => Mon, 14 Mar 2011 01:40:19 GMT [server] => Microsoft-IIS/6.0 [p3p] => Array ( [0] => CP='NOI ADMa OUR STP' [1] => CP="TST" ) [x-powered-by] => ASP.NET [cluster-server] => \ ignprdappw64212 [x-aspnet-version] => 2.0.50727 [pragma] => no-cache [x-aspnetmvc-version] => 1.0 [set-cookie] => BoardCookieV3%5Fboards%2Eign%2Ecom=dc=no&ra=False; expires=Wed, 14-Mar-2012 01:40:19 GMT; path=/; HttpOnly [cache-control] => private [expires] => Wed, 14 Mar 2001 01:40:19 GMT [content-type] => text/html; charset=utf-8 ) [body] => [response] => Array ( [code] => 200 [message] => OK ) [cookies] => Array ( [0] => WP_Http_Cookie Object ( [name] => BoardCookieV3%5Fboards%2Eign%2Ecom [value] => dc=no&ra=False [expires] => 1331689219 [path] => / [domain] => [httponly] => ) ) ) </code> Now... what I would have liked is information back from the head request that a 301 or 302 would be happening or even a 404, so that I could wp_remote_get that one instead. Am I doing something wrong? FYI: I need to manually redirect because I need to determine the base_href of an image if none is given in the HTML source (code: http://plugins.trac.wordpress.org/browser/wp-favicons/trunk/includes/class-http.php ) or some more background: http://wp.leau.co/2011/03/18/handling-redirects-for-wp-favicons-with-redirects-set-to-0-with-wordpress-wp_remote_get/
|
Taking a look at the WordPress HTTP API, it seems there ain't no simple way to do this. In fact, it might even be a calling for a trac ticket. See, although it allows you to specify the maximum number of redirects, there's no abstract option to control if redirects should even be followed . So setting a max redirect count of 0, the HTTP API will simply fail with something like 'Maximum redirects followed'. For the time being, you'll need to examine the <code> request </code> method of each HTTP transport class ( <code> WP_Http_Curl </code> , <code> WP_Http_ExtHttp </code> ...) and look for ideal filters and actions you can use to set the 'nofollow' option for that particular transport. On further inspection, I believe only the cURL component of the API is affected; <code> function __set_curl_nofollow( &$handle ) { curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false ); } add_action( 'http_api_curl', '__set_curl_nofollow' ); </code> As I mentioned about submitting to trac, I think there should be another option for the API, such as 'follow_redirection', that will then do what it is intended - abstract and take out the hassle! Trac ticket 16855
|
Wp Remote get with manual redirect
|
wordpress
|
I am reading the book Professional Wordpress, and have code like <code> $title = apply_filters('widget_title', $instance['title']); $name = apply_filters('widget_name', $instance['name']); ... </code> I wonder if there really are filters like <code> widget_xxx </code> ? What do they do?
|
For example, it makes them editable using the Front-end Editor plugin. All the cool widgets are doing it: http://core.trac.wordpress.org/browser/trunk/wp-includes/default-widgets.php
|
Is there a need to do apply_filter('widget_title', $instance['title']) or any other 'widget_xxx' filters?
|
wordpress
|
I read the following tutorial, which mentions moving your config file out of an HTTP-accessible folder. http://codex.wordpress.org/Hardening_WordPress#Securing_wp-config.php I did this, and it works fine. And when I visit http://mysite.com/wp-config.php , I see a blank page, as expected. However, when I visit http://mysite.com/wp-settings.php , I receive the following error: Warning: require(ABSPATHwp-includes/load.php) [function.require]: failed to open stream: No such file or directory in /home/{my user name}/mysite.com/wp-settings.php on line 19 Fatal error: require() [function.require]: Failed opening required 'ABSPATHwp-includes/load.php' (include_path='.:/usr/local/lib/php:/usr/local/php5/lib/pear') in /home/{my user name}/mysite.com/wp-settings.php on line 19 I'm new to WordPress and PHP, but not new to programming. Obviously, having my shell user's name output to the web if someone were to hit my wp-settings file is a no-no. So, can you have your config file out of the web directory, as I have here, without files like wp-settings resulting in sensitive information leaked to the screen? Am I going about this all wrong?
|
Hm, core WP files are usually die properly if opened directly. It probably slipped developers to include check in this one or something. The simple ways to fix this (and not really WP-specific) would be to: configure PHP on server to not display errors by default; restrict access to file with .htaccess or other means.
|
Securing wp-config leads to sensitive information leak on wp-settings
|
wordpress
|
I have a custom post type Holiday associated with a taxonomy Country. On my single-holiday.php, I use the taxonomy to display in the title. For example Holiday in Spain (Spain being the tax) Rarely, but it can happen, a holiday can be in 2 taxonomy terms. Creating a problem for my title display as I use get_the_terms. Somebody has better solution for me. My code is as follow <code> $taxonomy = 'country'; $terms=get_the_terms($post->ID,$taxonomy); if($terms) { foreach( $terms as $termcountry ) { ?> <h1>Holiday in <?php echo $termcountry->name;?></h1>}} </code>
|
you can change you code a bit : <code> $taxonomy = 'country'; $terms=get_the_terms($post->ID,$taxonomy); if($terms) { echo '<h1>Holiday '; $total_count = count($terms); $country_count = 1; foreach( $terms as $termcountry ) { if ($country_count = 1){ echo 'in '.$termcountry->name; }else{ if ($total_count = 2){ echo ' And '.$termcountry->name; }else{ echo ', '.$termcountry->name; } } $country_count = $country_count + 1 ; } echo '</h1>'; } </code> This will output in case of one term: <code> <h1>Holiday in Spain</h1> </code> in case of two terms: <code> <h1>Holiday in Spain And Japan</h1> </code> and in case of more then two terms: <code> <h1>Holiday in Spain, Japan, England</h1> </code> hope this helps
|
Get_the_terms restrict output
|
wordpress
|
Is there a list of the ID's and Classes I can give HTML elements in the admin panel in order to closely mimic the wordpress look and feel?
|
Onextrapixel's blog post How To Design And Style Your WordPress Plugin Admin Panel isn't an official reference, but it is a nicely detailed one.
|
Wordpress Plugin Look & Feel
|
wordpress
|
I've removed "Title" from a custom post type that I created. Which makes it that all new posts gets the name "Auto Draft". To get around this I want to be able to fetch a value/post name from a meta box and save that as the new title. Is this possible? This is what I'm using, and the value of this meta should be the new title <code> function save_title_meta($post_id, $post) { // verify this came from the our screen and with proper authorization, // because save_post can be triggered at other times if ( !wp_verify_nonce( $_POST['meta_noncename'], plugin_basename(__FILE__) )) { return $post->ID; } // Is the user allowed to edit the post or page? if ( !current_user_can( 'edit_post', $post->ID )) return $post->ID; // OK, we're authenticated: we need to find and save the data // We'll put it into an array to make it easier to loop though. $project_meta['_title'] = $_POST['_title']; // Add values of $project_meta as custom fields foreach ($project_meta as $key => $value) { // Cycle through the $project_meta array! if( $post->post_type == 'revision' ) return; // Don't store custom data twice $value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely) if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value update_post_meta($post->ID, $key, $value); } else { // If the custom field doesn't have a value add_post_meta($post->ID, $key, $value); } if(!$value) delete_post_meta($post->ID, $key); // Delete if blank } } add_action('save_post', 'save_title_meta', 1, 2); // save the custom fields ?> echo '<input type="hidden" name="meta_noncename" id="meta_noncename" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />'; // Get the location data if its already been entered $title = get_post_meta($post->ID, '_title', true); // Echo out the field echo '<input type="text" name="_title" value="' . $title . '" class="widefat" />'; ?> </code>
|
Even though you've disabled <code> title </code> for your custom post type, if you use the post name <code> post_title </code> for your own title input, WordPress will still use it and update the post title accordingly.
|
Automatically set post title to same value as a meta box
|
wordpress
|
Is there a way to make Wordpress' "Remember Me" login checkbox work for a really long time, like a year? Currently I think it only works for a few days or a week max, usually I am not remembered.
|
I think I'll wait for such a plugin Save this code in a file named <code> set-cookie-expire.php </code> and upload it your plugins folder. The plugin will give you the ability to set a time (in days) that cookies expire within the WordPress Settings admin. <code> <?php /** * Plugin Name: Set Cookie Expire * Version: 0.1 * Description: Set the expire time for cookies in <a href="options-privacy.php">Settings &raquo; Privacy</a>. * Author: WordPress Answers * Author URI: stackexchange-url */ if ( is_admin() ) : /** * Register settings. */ function __set_cookie_expire_admin() { foreach ( array( 'normal' => 'Normal', 'remember' => 'Remember' ) as $type => $label ) { register_setting( 'privacy', "{$type}_cookie_expire", 'absint' ); add_settings_field( "{$type}_cookie_expire", $label . ' cookie expire', '__set_cookie_expire_option', 'privacy', 'default', $type ); } } add_action( 'admin_init', '__set_cookie_expire_admin' ); /** * Setting field callback. */ function __set_cookie_expire_option( $type ) { if ( !$expires = get_option("{$type}_cookie_expire") ) $expires = $type === 'normal' ? 2 : 14; echo '<input type="text" name="' . $type . '_cookie_expire" value="' . intval( $expires ) . '" class="small-text" /> days'; } endif; /** * Filter in our user-specified expire times. */ function __set_cookie_expire_filter( $default, $user_ID, $remember ) { if ( !$expires = get_option( $remember ? 'remember_cookie_expire' : 'normal_cookie_expire' ) ) $expires = 0; if ( $expires = ( intval( $expires ) * 86400 ) ) // get seconds $default = $expires; return $default; } add_filter( 'auth_cookie_expiration', '__set_cookie_expire_filter', 10, 3 ); ?> </code> Also submitted on Pastie.
|
Make my wordpress blog remember my login "forever"
|
wordpress
|
WordPress has a built in function to display a list of all of your site’s authors. But there is no option to display their avatars, so all you really get is a text list that links to the author’s page, if you have an author.php file in your theme, that is. thus turning the internet I found this nice tutorial bavotasan.com with a little piece of code that seems to do the trick. On my site all users can write articles and list of contributors is long. It’s possible set 10 users for page ? Using this solution: Paginate result set from stackexchange-url ("$wpdb-> get_results()") I did make my code for Authors list functions as follow: <code> function contributors() { global $wpdb; $authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users WHERE display_name <> 'admin' ORDER BY display_name"); $authors_per_page = 10; $page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1; echo paginate_links( array( 'base' => add_query_arg( 'cpage', '%#%' ), 'format' => '', 'prev_text' => __('«'), 'next_text' => __('»'), 'total' => ceil($total / $authors_per_page), 'current' => $page )); foreach ($authors as $author ) { echo "<li>"; echo "<a href=\"".get_bloginfo('url')."/author/"; the_author_meta('user_nicename', $author->ID); echo "/\">"; echo get_avatar($author->ID); echo "</a>"; echo '<div>'; echo "<a href=\"".get_bloginfo('url')."/author/"; the_author_meta('user_nicename', $author->ID); echo "/\">"; the_author_meta('display_name', $author->ID); echo "</a>"; echo "<br />"; echo "SitoWeb: <a href=\""; the_author_meta('user_url', $author->ID); echo "/\" target='_blank'>"; the_author_meta('user_url', $author->ID); echo "</a>"; echo "<br />"; echo "Twitter: <a href=\"http://twitter.com/"; the_author_meta('twitter', $author->ID); echo "\" target='_blank'>"; the_author_meta('twitter', $author->ID); echo "</a>"; echo "<br />"; echo "<a href=\"".get_bloginfo('url')."/author/"; the_author_meta('user_nicename', $author->ID); echo "/\">Visita il Profilo di "; the_author_meta('display_name', $author->ID); echo "</a>"; echo "</div>"; echo "</li>"; } } </code> but still does the trick ..... Please help me to find out the error and its rectification. Thanks a lot.
|
I have modified WP_LIST_AUTHORS to paginate. I don't know if its very sexy, and seems to require some sort of Caching plugin otherwise this particular page can start to load pretty slowly. The full code of my paginated function is in this thread: stackexchange-url ("Modifying WP_LIST_AUTHOR Functions to output all users in a grid (and Paginate)") If you just want to look directly at the pagination code I used you can go here: http://www.phpfreaks.com/tutorial/basic-pagination
|
Authors list Pagination?
|
wordpress
|
i'm using wordpress v3.1 and i'm requiring 2 extra fields for external url + youtube-link. is it possible? in case it's not - i was considering using own tags for the post-content and filter it out. btw. what's the easiest way to implement youtube videos (via link) directly into the post? thx
|
http://voodoopress.com/2011/03/adding-meta-boxes-to-your-post-screen/ Is a post I wrote the other day about adding meta boxes. I use it to put links in to change the link some of my post titles use. I'm not sure if this is what you are looking for exactly, as I'm not quite sure what you mean by 'extra fields'
|
extra post fields for url + youtube video / implementation
|
wordpress
|
I'm currently using the_post_thumbnail(); to display featured images in my pages. Is it possible to set a fallback placeholder image in the event a featured image hasn't been set?
|
You can use <code> has_post_thumbnail() </code> as condition and change output accordingly. Example from Codex: <code> if(has_post_thumbnail()) { the_post_thumbnail(); } else { echo '<img src="'.get_bloginfo("template_url").'/images/img-default.png" />'; } </code>
|
Featured image/thumbnail fallback placeholder image
|
wordpress
|
<code> <?php $post_type = get_post_type( $post->ID ); if $post_type == 'project' : echo 'Work'; ?> </code> How can I make the above work? I want it so that if the post type is 'projects', then it echoes 'Work'. Also, I want to add another <code> if post type is 'movies' then it echoes 'Film' </code> on top of that.
|
Well, as far as I can tell you've got a syntax error there. Try this: <code> <?php $post_type = get_post_type( $post->ID ); if ($post_type == 'project') echo 'Work'; ?> </code> Also, make sure to check out what eileen.carpenter said in the comment to your question.
|
How do I echo the post type?
|
wordpress
|
I'm trying to optimize my header and I was wondering which plugin would call jquery. Is there a debugging tool to know which plugin is doing what in the header ? Thanks !
|
Plugins and themes tend to use <code> wp_enqueue_script() </code> to queue up scripts for the <code> <head /> </code> of your theme. I would rarely advise this, but since you only need to do it temporarily, you could modify WordPress core and run a debug backtrace for every call to this function. In <code> wp-includes/functions.wp-scripts.php </code> , drop the following code inside the end of the <code> wp_enqueue_script() </code> function (starts at line 96). <code> global $_script_callers_backtrace; if ( !$_script_callers_backtrace ) $_script_callers_backtrace = array(); $backtrace = debug_backtrace(); $_script_callers_backtrace[] = array( $handle, $backtrace[0]['file'] ); </code> Now pop the following in your theme's <code> functions.php </code> ; <code> function __save_script_callers() { file_put_contents( WP_CONTENT_DIR . '/callers.' . date('d-m-Y-H-i-s') . '.log', print_r( $GLOBALS['_script_callers_backtrace'], true ) ); } add_action( 'shutdown', '__save_script_callers' ); </code> Now whenever you load a page on your website, a log gets generated in your WordPress <code> wp-content </code> folder that'll contain a list of the script handlers and the files that triggered them. Remember! Undo the changes once you've found out what you need!
|
Know which plugin is calling JS in wp_head()?
|
wordpress
|
My site is using a short vanity URL and https (for admin logins). This is working across all of the custom theme pages in every browser except Internet Explorer. Specifically in IE7, every page I visit in the site presents this warning message: Security Information This page contains both secure and non-secure items. Do you want to display the nonsecure items? Do you think the site being https is causing this? Anything I can do to fix this?
|
Yes, your page(s) are loading images, CSS, or JS files that are called in the HTML via non secure mode (http versus https). Install the Firebug extension on your Firefox browser and look at your URLs that are loading in network tab. Screenshot: https://skitch.com/noelsaw/rww31/fullscreen Or you could use Pingdom tools to see what URLs are being loaded. Example: http://tools.pingdom.com/?url=chase.com&treeview=0&column=objectID&order=1&type=0&save=true I think you'd have to edit your posts/pages, theme files to specifically call https:// for images, css, and js files.
|
Internet Explorer "Security Information" on every page in https site
|
wordpress
|
The following code should read: If the current custom post type (bbp_forum), is the one being displayed, assign the class 'current' to its respective <code> <li> </code> tag. But for some reason the class 'current' (to highlight the current <code> bbp_forum </code> link) is being displayed in all the <code> <li> </code> tags: <code> <body <?php body_class(); ?>> <div id="wrapper" class="hfeed"> <div id="header"> <div id="masthead"> <div id="branding" role="banner"> <h1><a href="<?php echo home_url( '/' ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> </div><!-- #branding --> <div id="access" role="navigation"> <?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?> </div><!-- #access --> </div><!-- #masthead --> <ul id="forums"> <?php global $post; $cat_posts = get_posts('post_type=bbp_forum'); foreach($cat_posts as $post) : ?> <li <?php if($post->ID == get_the_ID()){ ?>class="current" <?php } ?>> <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> </li> <?php endforeach; ?> </ul><!-- #access --> </div><!-- #header --> <div id="main"> </code> Any suggestions?
|
The expression will always be true. Take a look at <code> get_the_ID() </code> ; <code> function get_the_ID() { global $post; return $post->ID; } </code> So your code is effectively running as; <code> if ( $post->ID == $post->ID ) // always true! </code> Instead, cache the ID of the main post in a variable, then compare that instead. <code> <?php global $post; /** * @var int Current post ID. */ $the_post_ID = $post->ID; /** * @var array All posts for bbp_forum. */ $cat_posts = get_posts('post_type=bbp_forum'); ?> <?php foreach ( $cat_posts as $post ) : ?> <li<?php if ( $post->ID == $the_post_ID ) echo ' class="current"'; ?>> <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> </li> <?php endforeach; ?> </code>
|
Conditional if statement ($post-> ID == get_the_ID) not working
|
wordpress
|
I have 2 customs post type : "Artist" and "Concert", the "Concert" custom post type is the child of the "Artist" custom post type, the "Artist" custom post type has a "genre" taxonomy. What I'm trying to do (for instance): list all the concerts which belong to artists of the "pop" genre. Here is the query of my dream: <code> SELECT * FROM posts WHERE post_type = "concert" AND post_parent_term = "pop" </code> I think currently there is no such thing as post_parent_term , hope I'm wrong ... (I know i can add the "genre" taxonomy to the "Concert" custom post type and voilà! But I'm really curious to know if there is another way to achieve that). Thanks by advance.
|
What I'm trying to do (for instance): list all the concerts which belong to artists of the "pop" genre. You can do it in two steps: <code> // 1. Get all the pop artist IDs $artist_ids = get_posts( array( 'fields' => 'ids', 'post_type' => 'artist', 'genre' => 'pop' ) ); // 2. Get all the concerts associated to those artists $artist_ids = implode( ',', array_map( 'absint', $artist_ids ) ); $concerts = $wpdb->get_results( " SELECT * FROM $wpdb->posts WHERE post_type = 'concert' AND post_status = 'publish' AND post_parent IN ({$artist_ids}) ORDER BY post_date DESC " ); </code> There's a post_parent argument in WP_Query, but it doesn't accept an array , hence the direct query.
|
How to get the parent's taxonomy?
|
wordpress
|
Now that wordpress 3.1 is out, where is the documentation for grouping custom post types together in the wp backend?
|
If you are wondering how to group multiple post types under one menu, you can easily do this with the <code> show_in_menu </code> argument when setting up your menu. See below: <code> $args = array( 'public' => true, 'show_ui' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'show_in_menu' => 'your-custom-menu-slug.php', 'menu_position' => null, 'supports' => array('title','editor','custom-fields'), 'has_archive' => true ); register_post_type('your-post-type',$args); </code> Note: For this to work, <code> show_ui </code> must also be set to true. Then you would create a menu using the <code> add_menu_page </code> function. <code> function add_your_menu() { add_menu_page( 'Multiple Post Types Page', 'Multiple Post Types', 'manage_options', 'your-custom-menu-slug.php', 'your_menu_function'); // add_submenu_page() if you want subpages, but not necessary } add_action('admin_menu', 'add_your_menu'); </code> In the same fashion, you can also attach post types to any existing menu. For example, it might be useful to attach certain post types to 'Posts' and others to 'Pages', while others might belong in 'Tools'. If you attach to an existing menu, you can ignore the <code> add_menu_page </code> function above and just modify the <code> $args </code> when registering your custom post type.
|
Now can I group custom post types together?
|
wordpress
|
OK, I can create the code to add custom widgets to the widgets manager. Check. My next challenge is to, in the same plugin, during activation, check for the existence of my theme, and if active, pre-populate the widget areas with the custom widgets I've just created. I hope this makes sense. If I can do this, it will save a ton of time from configuring (and explaining how to configure) my default theme setup, which relies heavily on custom widgets. Things like an optin email form, custom slider widget, etc... Thanks in advance if anyone can help me here. Here are my theme's default sidebars... <code> if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Home Sidebar', 'id' => 'home-sidebar-widget', )); if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Home Header Area', 'id' => 'home-header-widget', )); if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Inside Header Area', 'id' => 'inside-header-widget', )); if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Home Footer Area', 'id' => 'home-footer-widget', )); if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Inside Footer Area', 'id' => 'inside-footer-widget', )); if ( function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Inside Sidebar', 'id' => 'inside-sidebar-widget', )); </code>
|
Sidebars are registered in the option <code> 'sidebars_widgets' </code> . To see what’s in and what not, try this: <code> add_action( 'wp_footer', 'show_my_sidebars' ); function show_my_sidebars() { $sw = get_option( 'sidebars_widgets' ); print '<pre>' . htmlspecialchars( print_r( $sw, TRUE ) ) . '</pre>'; } </code> Sample output: <code> Array ( [sidebar-footer-left] => Array ( [0] => archives-3 ) [sidebar-footer-right] => Array ( [0] => recent-comments-3 )[array_version] => 3 ) </code> So check the option in per activation hook and insert your widgets if they aren’t already in there. And stop using <code> if ( function_exists('register_sidebar') ) </code> . Do you really want to support four years old WP versions?
|
My plugin creates custom widgets, How can I programatically add them to existing sidebar widget areas?
|
wordpress
|
I love markdown, and I have the Wordpress markdown-for-wordpress-and-bbpress parsing markdown in my posts and comments. However, I've noticed that Wordpress saves the comments rendered in html format. This makes it more difficult to go back and edit comments. How can I get wordpress to save comments in markdown format? I couldn't find a plugin for it. Maybe there's an easy php hack? (Cross posted from stackexchange-url ("stackoverflow") I hope that's ok)
|
This is a tricky one, but very doable. After looking at Mark's Markdown on Save plugin which does the exact thing you want but for posts content instead of comments i started thinking, that saving the comment content as Markdown would be bad because you would have to render the Markdown to HTML on-the-fly for each comment you display so the idea behind that plugin is that it saves the Markdown version as postmeta data and only displays it on the edit screen. So that is exactly what you need to do and i can help you in getting started. First you need to save the Markdown version of the comment content in the comment meta table using <code> update_comment_meta </code> and hooking it into <code> wp_insert_comment </code> which fires right after the comment is inserted in to the database: <code> //on comment creation add_action('wp_insert_comment','save_markdown_wp_insert_comment',10,2); function save_markdown_wp_insert_comment($comment_ID,$commmentdata) { if (isset($_GET['comment'])){ $markdown = $_GET['comment']; }elseif (isset($_POST['comment'])){ $markdown = $_POST['comment']; } if (isset($markdown)){ update_comment_meta($comment_ID,'_markdown',$markdown); } } </code> Then you need to show it on the comment edit screen using <code> get_comment_meta </code> and we hook it into <code> comment_edit_pre </code> filter which fires before the edit comment screen is displayed: <code> //on comment edit screen add_filter('comment_edit_pre','load_markdown_on_commet_edit',10,1); function load_markdown_on_commet_edit($content){ $markdown = get_comment_meta($comment_ID,'_markdown',true); if (isset($markdown) && $markdown != '' && $markdown != false){ return $markdown; } return $content; } </code> And Last we once again need to save the new Markdown version of the comment as comment meta data using once again <code> update_comment_meta </code> and we hook it into <code> edit_comment </code> which fires after a comment is updated/edited in the database: <code> //after comment edit screen add_action('edit_comment','save_markdown_after_edit',10,2); function save_markdown_after_edit($comment_ID){ if (isset($_POST['content'])){ update_comment_meta($comment_ID,'_markdown',$_POST['content']); } } </code> Now I'm not sure how safe and secure this is or if this even works but it looks right to me and i'll leave this as a community wiki so everyone who knows better is welcome to correct me.
|
How can I get Wordpress to save comments in markdown format?
|
wordpress
|
I'd like to be able to automatically uninstall certain plugins if they're detected (specifically Akismet and Hello Dolly), either by writing another plugin to do so or via my theme's functions.php file. Is that possible?
|
Sure, just call the delete_plugins() function, found in <code> wp-admin/includes/plugin.php </code> - you have to manually require() it.
|
Is it possible to uninstall one plugin from within another plugin?
|
wordpress
|
I set up my blog so that some of my posts get linked to a page outside of Wordpress. For these posts that get linked outside of Wordpress, I'd like to still include my header and footer so the page looks like it's still a part of my site. What would be the best way to do this? I tried adding <code> <?php include("/path/to/header.php"); ?> </code> and <code> <?php include("/path/to/footer.php"); ?> </code> but obviously it wouldn't work since my header and footer files contain Wordpress conditional tags.
|
You'll either need to load in WordPress , which can be considered computationally expensive if your 'other' pages are also powered by another webapp (not to mention the conflicts it may bring). If they're just regular PHP files, you should be OK. To load WordPress, include the file <code> /path/to/wordpress/wp-load.php </code> , then you'll be able to use WordPress as you would normally, including things like <code> get_header() </code> and <code> get_footer() </code> . However , whilst perhaps not the most 'compact' solution, my best advice would be to create header and footer files for these other pages that replicate the HTML of your theme without WordPress-specific PHP functions, and include them instead.
|
making posts linked outside of Wordpress still use the same header and footer
|
wordpress
|
I am working on a Wordpress site that heavily uses image uploading and whatnot, I have defined the image sizes in my functions.php and I have hard crop mode turned on which ensures that my images are always cropped to the exact size that I want. The problem with hard cropping is that peoples faces in images and other artefacts are cropped out and the images look ridiculous. Is there a way to have soft cropping mode turned on and have images always be an exact size? I find that when I use soft cropping mode, images vary in height and width. So an image I want to be 110x110 in soft crop mode can vary and sometimes be 110x96 or whatever and because that makes the layout look crappy and some photos look landscape, what is the best way to solve this issue?
|
It depends on the source image, aspect ratio is not magic, it must be maintained in order to lessen the proportional distortion. You best option is to upload images that will maintain the same aspect ratio. You can tweak your CSS to get a more consistent image size but be aware that doing so will create distortion the further it moves away from the proper aspect ratio.
|
Need To Resize Images Exactly Without Losing Image Details
|
wordpress
|
I'm writing a plugin that modifies the default behavior when uploading a file for a post or to the media library. I'm setting $overrides in wp_handle_upload() with a custom $unique_filename_callback. Once I added that, it tripped the following check inside wp_handle_upload(), because $_POST['action'] wasn't set. (I'm not sure why it wasn't, but it wasn't). <code> if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) ) return call_user_func($upload_error_handler, $file, __( 'Invalid form submission.' )); </code> So, I set $overrides['test_form'] = false, and now it's working. I'm wondering if that could be a potential security issue, though. Would that allow someone to post a form from a remote source or something? It seems like it's normal to disable it when you're creating your own upload fields, but I'm using the built-in post upload form, so I want to make sure.
|
I wouldn't say security concern - since you're using this plugin within the admin (I presume after the user has been authenticated i.e. after <code> admin_init </code> ), then already you've got protection against any Jon Doe posting a form to your script. What it does provide, is an additional layer of authentication. All it really boils down to is sending a 'secret' along with the form, and then checking for it's existence (and that it matches) before continuing. For an attacker, they'd need to know this secret in order to breach, for example, using CSRF or XSS . This is the very nature of how WordPress nonces work. In fact you'd be a lot better off using these instead of test_form. They go one step better in that they're secrets that expire , so the window for an attacker is made even smaller. Check out Jaquith's article on Nonces .
|
Is disabling test_form in wp_handle_upload a security concern?
|
wordpress
|
For some reason this custom field is not being shown in the page. This is the template file: <code> <?php /** * Template Name: bbPress - Topics (Newest) * * @package bbPress * @subpackage Theme */ ?> <?php get_header(); ?> <div id="container"> <div id="content" role="main"> <?php do_action( 'bbp_template_notices' ); ?> <?php while ( have_posts() ) : the_post(); ?> <div id="topics-front" class="bbp-topics-front"> <div class="entry-content"> <div id="page-intro"> <?php the_content(); ?> </div> <?php get_template_part( 'loop', 'bbp_topics' ); ?> </div> </div><!-- #topics-front --> <?php endwhile; ?> <?php if ( get_post_meta($post->ID, 'note', true) ) : ?> <div id="note"> <p><?php echo get_post_meta($post->ID, 'note', true); ?><p/> </div> <?php endif; ?> </div><!-- #content --> </div><!-- #container --> <?php get_sidebar(); ?> <?php get_footer(); ?> </code> As you can see everything is set:
|
You're doing it outside of The Loop there, so $post is undefined at that point. Put it above the <code> endwhile </code> and it should work.
|
Value from custom field is not being displayed?
|
wordpress
|
I have a Wordpress site that relies on relationships quite heavily. It's a record label website where artists can be related to tours, reviews, album releases and store items throughout the site. I found the plugin Posts to Posts by Scribu which seems to do what I want, but I don't understand how to use it properly. Scribu has posted example code, but for some reason I just cannot understand it. Here is an example of what I want to do with the site I am working on. Tours Page. A tour item has a title and a custom meta field called 'tickets_link' Upon loading the tours page, all tours will be shown with their assigned artist and if it has a tickets link, then show that as well. If someone here can understand the code posted on Scribu's site for the plugin and then explain it to me, I would gratefully appreciate it. Here is my code from the functions.php file registering the connections: <code> function my_connection_types() { if ( !function_exists('p2p_register_connection_type') ) return; p2p_register_connection_type( 'tours', 'artists' ); p2p_register_connection_type( 'homepage_carousel', 'artists' ); p2p_register_connection_type( 'duka', 'artists' ); p2p_register_connection_type( 'products_carousel', 'artists' ); } add_action('init', 'my_connection_types', 100); </code> Pseudo code to show what I want to do in my code: Fetch all tours in my tours custom post archive using a loop that gets all tours added to the site. Each tour is related to an artist, so display all tours for a particular artist. Items are in the form of a heading (artist name) and each item is a tour that has been related to a particular artist in the backend using the metabox that shows as a result from registering a connection. Further update along with code I am using and print_r values. I have the related artists showing up in my print_r contents of my query where before I didn't. When I do a print_r I get the following that shows up, but no way of accessing the data. <code> [connected_connected] => Array ( [0] => stdClass Object ( [ID] => 245 [post_author] => 1 [post_date] => 2011-03-10 13:55:23 [post_date_gmt] => 2011-03-10 13:55:23 [post_content] => [post_title] => 1200 Techniques [post_excerpt] => [post_status] => publish [comment_status] => closed [ping_status] => closed [post_password] => [post_name] => 1200-techniques [to_ping] => [pinged] => [post_modified] => 2011-03-10 13:55:23 [post_modified_gmt] => 2011-03-10 13:55:23 [post_content_filtered] => [post_parent] => 0 [guid] => http://localhost/testdev/?post_type=artists&p=245 [menu_order] => 0 [post_type] => artists [post_mime_type] => [comment_count] => 0 [p2p_id] => 2 [p2p_from] => 215 [p2p_to] => 245 </code> The code I am using to relate artists with tours is the following: <code> $connected = new WP_Query(array( 'post_type' => 'tours', 'nopaging' => true, 'each_connected' => array( 'post_type' => 'artists', 'nopaging' => true, ), 'suppress_filters' => false )); while( $connected->have_posts() ): $connected->the_post(); the_title(); echo "<br />"; endwhile; print_r($connected); // Print_r for showing contents of post object. </code> Update for Scribu: <code> $args = array ( 'post_type' => 'tours', 'nopaging' => true, 'suppress_filters' => false ); $connected = new WP_Query($args); while($connected->have_posts()): $connected->the_post(); the_title(); echo "<br />"; foreach ($connected->connected AS $tour_item) { echo get_the_title($tour_item->ID); echo "<br />"; } endwhile; </code>
|
Ok, so the idea is that you have an outer loop, that displays the tours. And then you have an inner loop, that displays each artist. The way The Loop works is that it populates a lot of global variables, such as <code> $post </code> , so it looks like magic. Let's look at a more uniform approach: <code> $tours = get_posts( array( 'post_type' => 'tours', 'nopaging' => true, 'each_connected_to' => array( 'post_type' => 'artists', 'nopaging' => true, ), 'suppress_filters' => false ) ); // outer loop foreach ( $tours as $tour ) { echo get_the_title( $tour->ID ); echo get_post_meta( $tour->ID, 'ticket_link', true ); // inner loop foreach ( $tour->connected_to as $artist ) { echo get_the_title( $artist->ID ); echo '<br/>'; } } </code> Update: This answer is obsolete; for a current example, see https://github.com/scribu/wp-posts-to-posts/wiki/Looping-The-Loop
|
How Do I Use The Wordpress Plugin Posts 2 Posts by Scribu?
|
wordpress
|
This is a second navigation menu I'm using: <code> <ul id="forums"> <?php $custom_posts = new WP_Query(); ?> <?php $custom_posts->query('post_type=bbp_forum'); ?> <?php while ($custom_posts->have_posts()) : $custom_posts->the_post(); ?> <li><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></li> <?php endwhile; ?> </div><!-- #access --> </code> Is a custom loop which list a custom post type called Forum. I would like to highlight the current Forum link, like this: Any suggestions?
|
So, if I understand correctly, when you're on a single post page, you want to have a navigation menu with all the posts of post_type bbp_forum. I had a similar case (without the post_type, but it's not a problem to add it), and I used code that I found that talked about posts of same category, on single post pages . The code goes as follows (with customization for post_type): <code> <ul> <?php global $post; $cat_posts = get_posts('post_type=bbp_forum'); foreach($cat_posts as $post) : ?> <li <?php if($post->ID == get_the_ID()){ ?>class="cur_post" <?php } ?>> <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> </li> <?php endforeach; ?> </ul> </code> I hope that's what you meant. P.S - I also see that you have an opening <ul> tag, but a closing <div> tag....
|
Highlighting the current page in a navigation menu which links are generated with a custom loop?
|
wordpress
|
hey guys, The "mingle forum plugin" provides the following shortcode [mingleforum]. When I paste this into a page the forum is shown. My forum is using a specific page-template called forum.php. Is it possible to already include this shortcode in the page-template itself, so I don't have to paste it in the wordpress backend anymore. So that when I use the forum.php page template the forum is always automatically embedded? Thank you for your tipps and info.
|
To use shortcode in a PHP file (outside the post editor) you have the handy little function do_shortcode(); so in your case you use: <code> <?php do_shortcode('[mingleforum]'); ?> </code> Update: following the first comment, I figured its publicly known for some reason, if you are expecting output from the shortcode then echo it out . <code> <?php echo do_shortcode('[mingleforum]'); ?> </code>
|
Adding a post shortcode to a page template?
|
wordpress
|
I'm a noob at this so please bear with me. I have the following code to return post title as links within categoryID 6, which is working fine: <code> <?php global $post; $cat_posts = get_posts('numberposts=10&category=6'); foreach($cat_posts as $post) : ?> <?php $postTitle = get_the_title(); if($title != $postTitle) :?> <li><a href="<?php the_permalink(); ?>">&rsaquo;&rsaquo; <?php the_title(); ?></a></li> <?php endif ;?> <?php endforeach; ?> </code> However, the category ID is a variable, e.g. $catID, can I use this in the above code? Thanks in advance!
|
Have you tried the following code? <code> $cat_posts = get_posts('numberposts=10&category='.$catID); </code>
|
With get_posts(), how can I put a category as a variable
|
wordpress
|
How do I have my plugin pop up with that <code> New version available. Upgrade Automatically </code> dialog to appear when my plugin has a new version? Specifically for plugins not hosted on the WP.org repository.
|
This library integrates auto-updates for privately hosted plugins. Looks great.
|
How to auto-upgrade my plugin?
|
wordpress
|
I'm using the twentyten theme with the bbpress plugin. I have the following in my header.php (twentyten): <code> <div id="masthead"> <div id="branding" role="banner"> <h1><a href="<?php get_site_url(); ?>">TaiwanTalk</a></h1> </div><!-- #branding --> <div id="access" role="navigation"> <?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary' ) ); ?> </div><!-- #access --> </div><!-- #masthead --> </code> <code> get_site_url </code> doesn't return anything. Any suggestions?
|
The functions that start with "get_" return the value to what's calling it. So you would do <code> <a href="<?php echo get_site_url(); ?>"> </code> instead to print out the URL.
|
get_site_url is not returning anything?
|
wordpress
|
I have created some pages (not post) in wordpress related to my college notes. I would like to display a copyright message of the college on this pages, but I don't want do this manually every time. So is there any plug-in or tweak available to achieve this?
|
You could add a custom field to the pages you want to show the copyright on and have your page.php (or header.php or index.php or whatever) look for it. Example: Set a custom field of "show_copyright" to "1" in the page editor. In your page.php, right above <code> <?php endwhile; endif; ?> </code> , add this: <code> <?php if ( get_post_meta($post->ID, 'show_copyright', true) ) { ?> <div class='copy'> This is your copyright notice. </div> <?php } ?> </code> Now, that said, there's another way you could do it. Make a copy of your page.php, index,php, whatever, to a new name like "copyright.php". Add your copyright message into that, and at the very top of the file, add this: <code> <?php // Template Name: Copyright Notice ?> </code> Then, when editing your page, change the Page Template on the right to "Copyright Notice". The trouble with this second method, though, is if you decide to change something in your website, you'll need to edit both your page.php file (or index, blah blah) as well as your copyright.php.
|
Copyright messages for a particular set of pages
|
wordpress
|
I've created a custom post type with my own custom meta boxes. Now I want to move the title box to the side or simply remove it and place the same content in a custom meta box. How do I go about to do this? Thanks
|
When you register your post type, use the <code> supports </code> argument to explicitly set which core meta boxes to use. <code> register_post_type('my_type', array( 'supports' => array( 'editor' ) // if "title" isn't in this array, it won't appear on the edit post page // other arguments )); </code>
|
Move title "meta box" in post mode
|
wordpress
|
Hey! I have added a wp_loginout() to my header using a snippet in my functions.php: <code> add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2); function add_login_logout_link($items, $args) { ob_start(); wp_loginout('index.php'); $loginoutlink = ob_get_contents(); ob_end_clean(); $items .= '<li>'. $loginoutlink .'</li>'; return $items; } </code> The thing is that it shows the login link in every one of my three menues: <code> function register_main_menus() { register_nav_menus( array( 'primary-menu' => __( 'Primary Menu' ), 'secondary-menu' => __( 'Secondary Menu' ), 'footer-menu' => __( 'Footer Menu' ), ) ); }; </code> I would like to target the wp_nav_menu_items filter to only include the login link in the primary menu. Ideas? Thanks in advance
|
See this stackexchange-url ("related question"). I guess in your case you'd wrap your code in <code> if( $args->theme_location == 'primary-menu' ) </code> .
|
Targeting specific menu with wp_nav_menu_items
|
wordpress
|
Been fiddling around, trying to remove the "path" info that's shown when you create/edit a post in wordpress. Been able to remove word count and the saving draft info, but not the path thingie This is what I'm talking about: http://dl.dropbox.com/u/3618143/Sk%C3%A4rmavbild%202011-03-13%20kl.%2001.08.11.png Also, the autosave-info that shows up on posts that's being edited. "Last edited by admin" etc. Can't seem to find that either. Any ideas?
|
Use the filter <code> tiny_mce_before_init </code> to customise the default configuration; <code> function __my_tiny_mce( $config ) { $config['theme_advanced_path'] = false; return $config; } add_filter('tiny_mce_before_init', '__my_tiny_mce'); </code> Check out all the options available on the Tiny MCE documentation .
|
Remove path from the create/edit a post view
|
wordpress
|
I have a 'media' category page that pumps in videos / image galleries. I'm looking to have a smaller size video display (vimeo / youtube) on the category page, and the full size video on the single page. How do I change the size of the video embed on the fly for the both scenarios? Here's the loop for selecting anything in the "videos" category. <code> <?php $videos = new WP_Query('category_name=video'); ?> <?php while ( $videos->have_posts() ) : $videos->the_post(); ?> <?php the_content(); ?> <?php endwhile; ?> </code> Videos are entered into the post's main tinymce content editor. Am I being to vague?
|
The best solution here is to use the built-in filter for embed parameters: <code> <?php function mytheme_embed_defaults( $defaults ) { return array( 'width' => 100, 'height' => 100 ); } add_filter( 'embed_defaults', 'mytheme_embed_defaults' ); ?> </code> This code can be added to your theme's functions.php file and you can change the numbers to reflect the sizes that you desire. You can add conditionals as needed. Maybe something like: <code> <?php function mytheme_embed_defaults( $defaults ) { if ( is_category() ) { $defaults = array( 'width' => 100, 'height' => 100 ); } return $defaults; } add_filter( 'embed_defaults', 'mytheme_embed_defaults' ); ?> </code> Would work best for you.
|
Different size video display for category page (smaller) & detail page (larger)
|
wordpress
|
Is there a way to limit search to post titles? I know I can modify query.php core file but there must be a way to do it with hooks right? Thanks in advance!
|
Here's a filter that'll do the trick. Drop it into your theme's <code> functions.php </code> or a plugin. <code> /** * Search SQL filter for matching against post title only. */ function __search_by_title_only( $search, &$wp_query ) { global $wpdb; if ( empty( $search ) ) return $search; // skip processing - no search term in query $q = $wp_query->query_vars; $n = ! empty( $q['exact'] ) ? '' : '%'; $search = $searchand = ''; foreach ( (array) $q['search_terms'] as $term ) { $term = esc_sql( like_escape( $term ) ); $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')"; $searchand = ' AND '; } if ( ! empty( $search ) ) { $search = " AND ({$search}) "; if ( ! is_user_logged_in() ) $search .= " AND ($wpdb->posts.post_password = '') "; } return $search; } add_filter( 'posts_search', '__search_by_title_only', 500, 2 ); </code> Most of the code is just copied from the <code> WP_Query </code> class, except with the <code> post_content LIKE </code> 's removed. UPDATE: This code has been updated for WordPress 3.2.1. I'm surprised it even worked before as <code> $wpdb </code> wasn't global!
|
how to limit search to post titles?
|
wordpress
|
I have a Worpdress blog on a hosting company (it's remote and existing). I would like to load it to Netbeans. How do I do that? Thanks,
|
File > New Project Categories select 'PHP' Project select 'PHP Application from Remote Server' click 'Next' and give the project a name and specify where local/downloaded files will be stored. click next Enter Project URL, and upload path on remote server (this probably be just / if WP is installed at root of the domain) Here you'd need to specify how you will be connecting to remote server. Click 'Manage' button next to 'Remote Connection' click 'Add' button to create a new remote connection and enter all the FTP/SFTP details and click OK Click next until the end of the wizard
|
Loading a remote WP website to Netbeans
|
wordpress
|
I'm having some problems getting the WP Subtitle plugin to work. After inserting the <code> <?thesubtitle()?> </code> or <code> <?getthe_subtitle($id)?> </code> into the index.php template I get a 'call to undefined function' error - inside or outside the loop doesn't seem to matter! Thanks in advance //Update In most pages the following now works thanks to toscho's updated syntax <code> <?php get_header(); ?> <div class="title-posts-container"> <h2 class="title-posts"><?php the_title(); ?></h2> <p class="title-posts-strap"><?php the_subtitle(); ?></p> </div> <div class="content"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> </code> But no such joy in index.php where the following fails <code> <?php get_header(); ?> <div class="title-posts-container"> <h2 class="title-posts"><?php the_title(); ?></h2> <p class="title-posts-strap"><?php the_subtitle(); ?></p> </div> <div class="content"> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> </code>
|
Try the correct syntax : <code> <?php the_subtitle(); ?> <?php get_the_subtitle( $id ); ?> </code>
|
WP Subtitle Plugin Problem
|
wordpress
|
I have a question about moving wordpress sites around. I've read most of the Support Docs about moving a wordpress site. My question is this, what would you guys recommend in regards to moving only certain posts from one site into a totally different domain. My current domain is a tech/blog installation. The past year or so, I've been posting my technical stuff to a different domain, and my current domain is collecting quite a bit of dust. What I'm wanting to do is turn my current domain into a personal blog and move only my technical articles over to the new blog. Obviously, there's probably an easy way to move posts and comments over (i haven't looked into it but i'm pretty sure I can do this pretty easily). The true question is how I would present these posts on the current site once they are moved over to the new domain? Do I keep them on the current domain? Should I redirect users to the new domain automatically on only these posts? Should I remove them from the current site? These type of questions I'm wondering and if you guys have an pointers please let me know.
|
I would try the following: <code> site #1 == source site #2 == destination </code> On the Site #1: on all the post you want to move/migrate allocate them a category say 'moved' export them using 'Tools' > 'Export' (select 'Posts' and specify categories 'moved') On site #2: Import your exported file using 'Tools' > 'Import' > 'WordPress' and follow the on screen instructions. You might also want to import related media or attachments. remove 'moved' category in the category editor: 'Pots' > 'Categories' back to site #1: put a redirect on migrated posts install 'Redirection' WordPress plugin now configure all the redirects for each post or moved category to redirect to your new site/posts.
|
Moving Some Articles to new site
|
wordpress
|
I'm trying to call multiple JQuery scripts using wp_enqueue_script. The call to JQuery works perfectly but the second call to cufon doesn't. I'm not a php or javascript expert - could anyone lend a hand, is there a best practice method for this? <code> function my_init_method() { if (!is_admin()) { wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js'); wp_enqueue_script( 'jquery' ); } } add_action('init', 'my_init_method'); function my_init_method2() { if (!is_admin()) { wp_deregister_script( 'cufon' ); wp_register_script( 'cufon', 'http://mydomain.com/wp-content/themes/simplefolio/js/cufon-yui.js'); wp_enqueue_script( 'cufon' ); } } add_action('init', 'my_init_method2'); </code>
|
I'm not good at this, but it could be because Cufon is not included in Wordpress? So, you are deregistrating a script that is not included.. http://codex.wordpress.org/Function_Reference/wp_enqueue_script#Default_scripts_included_with_WordPress
|
Calling multiple scripts using wp_enqueue_script
|
wordpress
|
One of my wordpress blog is protected by the wordpress password plugin. however, I would like provide rss features. I found how to configure wordpress plugin to make rss work. But, by default, it seems that all the content of a post is sent by the feed. I would like to limit the information available by rss. Ideally, I would like to provide only the title of a post by rss. I have pictures and video (by vimeo) that have not to be available by rss ! Any help ? Thanks
|
I have found two solutions : 1) First one, very easy, just select summary in the feed options of wordpress. Since this option is activated, neither pictures nor videos are displayed. 2)The second one is adding this piece of code in your theme's functions.php <code> add_filter('excerpt_length',create_function('$a','return 0;')); </code> ref : stackexchange-url ("stackexchange-url With this solution, only the title of each post is available by rss ! Exactly what I want !
|
restricted rss feed
|
wordpress
|
How are you? I have a blog which have 20 authors. I want to write code to show the 5 author who have more posts. like this: Adam (10 Posts) Khal (8 Posts) Yous (5 Posts) Moha (3 Posts) Yousef (1 Post) but I don't know how can do it that
|
Are you using WordPress 3.1+? There's a nice <code> get_users() </code> function that'll do the trick! However, you will need a little magic to boot: <code> add_action( 'pre_user_query', 'wpse_11832_pre_user_query' ); /** * Adds "post_count" to the SELECT clause. Without this, the "post_count" * property for users will be undefined. * * @param object $wp_user_query */ function wpse_11832_pre_user_query( $wp_user_query ) { if ( $wp_user_query->query_vars['orderby'] == 'post_count' ) $wp_user_query->query_fields .= ', post_count'; } </code> And example usage: <code> <?php foreach ( get_users( 'order=DESC&orderby=post_count&number=5' ) as $user ) : ?> <?php echo $user->display_name; ?> (<?php echo $user->post_count; ?> Posts) <?php endforeach; ?> </code> Important : You must order by <code> post_count </code> , otherwise it will be undefined.
|
List top 5 authors with most posts
|
wordpress
|
i have a custom post type 'events'. Each event (post) can have multiple dates. The dates (date, time, location) are stored as array. I need a query that creates a chronological list of all events from the meta data (events can occur multiple times). The custom-meta-box looks like this: The resulting database entry in wp_postmeta has the <code> meta_key </code> '_events_termine' with the following <code> meta_value </code> (using WPAlchemy): <code> a:1:{s:12:"termin_group";a:2:{i:0;a:3:{s:11:"termin_date";s:10:"2011/03/14";s:11:"termin_time";s:5:"19.30";s:15:"termin_location";s:15:"Max-Reger-Halle";}i:1;a:3:{s:11:"termin_date";s:10:"2011/03/15";s:11:"termin_time";s:5:"20.00";s:15:"termin_location";s:15:"Max-Reger-Halle";}}} </code> I display the dates for a single event with the following code: <code> <table> <?php global $events_meta_termine; $meta = get_post_meta(get_the_ID(), $events_meta_termine->get_the_id(), TRUE); foreach ($meta['termin_group'] as $termin) { ?> <tr> <td><?php echo mysql2date('D', $termin['termin_date'], true); ?></td> <td><?php echo mysql2date('j. F Y', $termin['termin_date'], true); ?></td> <td><?php echo $termin['termin_time']; ?> Uhr</td> <td><?php echo $termin['termin_location']; ?></td> </tr> <?php } ?> </table> </code> The output looks like this: So everything works fine except i have no idea how to create a page that lists all events (title, date, location) in chronological order where a single event can occur several times. Any help is highly appreciated! (i'm sorry i asked a similar question before, but i came to a dead end and had to start over.)
|
Here's the code that finally worked for me: <code> <?php global $events_meta_termine; $today = getdate(); $my_query = new WP_Query('post_type=events&posts_per_page=-1&monthnum='.$today["mon"]); $events=array(); while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID; $meta = get_post_meta(get_the_ID(), $events_meta_termine->get_the_id(), TRUE); foreach ($meta['termin_group'] as $termin) { $event=array(); $event['title']=get_the_title(); $event['date']=$termin['termin_date']; $event['time']=$termin['termin_time']; $event['location']=$termin['termin_location']; $events[]=$event; } endwhile; wp_reset_query(); $i=0; usort($events, "cmp"); function cmp($a, $b){ return strcmp($a['date'],$b['date']); } ?> <table> <?php $current_month=''; foreach ($events as $event){ if ($current_month!=mysql2date('F Y', $event['date'], true)) { $current_month=mysql2date('F Y', $event['date'], true); echo '<tr><td colspan="5">'.$current_month.'</td></tr>'; } ?> <tr> <td><?php echo $event['title']; ?></td> <td><?php echo mysql2date('D', $event['date'], true); ?></td> <td><?php echo mysql2date('j. F Y', $event['date'], true); ?></td> <td><?php echo $event['time']; ?> Uhr</td> <td><?php echo $event['location']; ?></td> </tr> <?php } ?> </table> </code>
|
Custom Post Type 'Event': Chronological list of recurring events from meta_values in array
|
wordpress
|
Update: I'm now trying to find a way to echo the metadata of a custom taxonomy's value. I'm trying to create some PHP to use in a plaintext widget that'll display information in my sidebar. Because some of the information will be identical across some of the parts of the site instead of storing the information in custom fields I'm trying to store it in a MYSQL table. What I'd like the code to do is to identify the post taxonomy, lookup the id field in my table, find the row with that shares the id with the taxonomy and then echo the values of other fields on that row. I have my taxonomy setup as well as my table but I can't find much of a precedent for this and therefore I'm struggling to know where to start. So far I'm trying to call the current post taxonomy's value but I can't get it to work outside the loop <code> <?php $current_tax = get_query_var('game'); echo $current_tax; ?> </code>
|
First of all, what you're calling $current_tax would more appropriately be named $current_term. The taxonomy is 'game'. Secondly, what you're trying to do is basically adding term metadata. There already are several plugins that provide the custom table and functions for that. I recommend Simple Term Meta .
|
Returning info from MYSQL table via custom taxonomy
|
wordpress
|
I'm trying to apply this tutorial to my blog. I'm using Woothemes' Bueno Theme . I'm adding this code to my theme's functions.php file : <code> function ymc_add_meta_settings($comment_id) { add_comment_meta( $comment_id, 'mailchimp_subscribe', $_POST['mailchimp_subscribe'], true ); } add_action('comment_post', 'ymc_add_meta_settings', 1); function ymc_subscription_add( $cid, $comment ) { $cid = (int) $cid; if ( !is_object($comment) ) $comment = get_comment($cid); if ( $comment->comment_karma == 0 ) { $subscribe = get_comment_meta($cid, 'mailchimp_subscribe', true); if ( $subscribe == 'on' ) { update_comment_meta($cid, 'mailchimp_subscribe', 'off'); ///////////////////////////////////// ///////MailChimp//////////////////// /////////////////////////////////// $apikey = 'MYAPIKEY-us2'; $listid = 'MYLISTID'; $endpoint = 'http://us2.api.mailchimp.com/1.3/?output=php'; $request = array( 'apikey' => $apikey, 'id' => $listid, 'email_address' => strtolower( $comment->comment_author_email ), 'double_optin' => true, 'merge_vars' => array( ' <merge tag for name> ' => $comment->comment_author, 'OPTIN_IP' => $comment->comment_author_IP, ) ); $result = wp_remote_post( $endpoint.'&method=listSubscribe', array( 'body' => json_encode($request) ) ); ///////////////////////////////////// ///////MailChimp Ended//////////////////// /////////////////////////////////// } } } add_action('comment_approved_','ymc_subscription_add',10,1); add_action('comment_post', 'ymc_subscription_add', 60,1); </code> Also this code added to comments.php file of theme (below <code> </form> </code> ) : <code> <input style="width: auto;" type="checkbox" name="mailchimp_subscribe" id="mailchimp_subscribe"/> <label for="mailchimp_subscribe"> Subscribe </label> </p> </code> But when i trying to send a comment, i'm getting this error : <code> Warning: Missing argument 2 for ymc_subscription_add() in /home/content/blabla/themes/bueno/functions.php on line 36 Warning: Cannot modify header information - headers already sent by (output started at /home/content/blabla/themes/bueno/functions.php:36) in /home/blabla/html/wp-comments-post.php on line 95 Warning: Cannot modify header information - headers already sent by (output started at /home/blabla/html/wp-content/themes/bueno/functions.php:36) in /home/content/blabla/wp-comments-post.php on line 96 Warning: Cannot modify header information - headers already sent by (output started at /home/blabla/html/wp-content/themes/bueno/functions.php:36) in /home/content/blabla/wp-comments-post.php on line 97 Warning: Cannot modify header information - headers already sent by (output started at /home/contentblabla/html/wp-content/themes/bueno/functions.php:36) in /home/content/blabla/wp-includes/pluggable.php on line 897 </code>
|
The last two hooks should specify 2 accepted arguments, not 1; <code> add_action('comment_approved_','ymc_subscription_add', 10, 2); add_action('comment_post', 'ymc_subscription_add', 60, 2); </code>
|
Error While Sending Comment
|
wordpress
|
<code> <div class="menu"> <ul> <?php wp_list_pages('exclude=&title_li='); ?> </ul> </div> </code> creates the following output... <code> <div class="menu"> <ul> <li><a href="#">Page 1</a></li> <li><a href="#">Page with Subpages</a> <ul class="children"> <li><a href="#">Page with another subpage</a> <ul class="children"> <li><a href="#">subsubpage</a></li> </ul> </li> </ul> </li> <li><a href="#">Page 3</a></li> <li><a href="#">Page 4</a></li> </ul> </div> </code> All pages with children have a <code> ul class="children" </code> applied. Is it possible to create any function (or any other way) to append a classname to all pages THAT HAVE CHILDREN? In my example above only the "Page with Subpages" and it's first child-page "Page with another subpage" should have a <code> li.parent </code> applied. Is that possible on the serverside? I'm able to do it with javascript, however I wonder if there is a better and cleaner way to do it serverside? thank you
|
Phew! Bit more complex than I would've liked - if only the filter <code> page_css_class </code> passed back <code> $args </code> it would save a lot of effort (may submit this to trac). Since 3.3 it's as easy as this! <code> function add_parent_class( $css_class, $page, $depth, $args ) { if ( ! empty( $args['has_children'] ) ) $css_class[] = 'parent'; return $css_class; } add_filter( 'page_css_class', 'add_parent_class', 10, 4 ); </code> For those on pre WordPress 3.3, here's the workhorse: <code> /** * Extend the default page walker class to append class names for pages that * are parents. * @uses Walker_Page */ class My_Page_Walker extends Walker_Page { /** * Filter in the classes for parents. */ function _filterClass( $class ) { $class[] = 'parent'; // change this to whatever classe(s) you require return $class; } /** * This is effectively a wrapper for the default method, dynamically adding * and removing the class filter when the current item has children. */ function start_el( &$output, $page, $depth, $args, $current_page ) { if ( !empty($args['has_children']) ) add_filter( 'page_css_class', array( &$this, '_filterClass') ); parent::start_el( $output, $page, $depth, $args, $current_page ); if ( !empty($args['has_children']) ) remove_filter( 'page_css_class', array( &$this, '_filterClass') ); } } </code> I'd advise placing the class in your <code> functions.php </code> , then it's available wherever you'd like to use it. To use it, call <code> wp_list_pages() </code> like so; <code> // You need to pass the walker argument to wp_list_pages(). You must use an // array to do this. wp_list_pages(array( 'walker' => new My_Page_Walker, 'title_li' => '' )); </code>
|
class="parent" for wp_list_pages?
|
wordpress
|
I have a custom taxonomy called 'game'; posts have a taxonomy value, i.e. Halo, which then has seven different fields; game_name, game_genre etc. I'm trying to echo the meta data for a given post's custom taxonomy albeit without much luck. The small piece of PHP that I tried to use to echo the metadata for the field game_name (designed to be run in a PHP widget) doesn't appear to work. It uses a custom hook created by the plugin Simple Term Meta <code> <?php global $term; echo get_term_meta($term->ID, 'game_name', true); ?> </code> Any help in sorting this out would be appreciated, I didn't realise it'd be this complicated.
|
I assume you're trying to use this when viewing a single post? For example, in <code> single.php </code> ? If so, you'll need to grab the terms first, then grab your meta. <code> global $post; if ( $terms = get_the_terms( $post->ID, 'game' ) ) { // $term = $terms[0]; // WRONG! $terms is indexed by term ID! $term = array_shift( $terms ); // RIGHT! Will get first term, and remove it from $terms array echo get_term_meta( $term->term_id, 'game_name', true ); } </code> UPDATE Since the level of code has increased, you'd be much better off wrapping it in a function. Place the following in your <code> functions.php </code> ; <code> /** * Get the game box image for a post. * * @param int|object $post * @return string */ function get_game_box_image( $post = 0 ) { if ( ( !$post = get_post( $post ) ) || ( !$terms = get_the_terms( $post->ID, 'game' ) ) ) return ''; // bail $term = array_shift( $terms ); if ( $box = get_term_meta( $term->term_id, 'game_box', true ) ) { $rel = str_replace( content_url(), '', $box ); if ( is_file( WP_CONTENT_DIR . '/' . ltrim( $rel, '/' ) ) ) return '<div style="text-align: center;"><img src="' . $box . '" alt="" /></div>'; } return ''; } </code> Then to display the game box image, call it like so; <code> <?php echo get_game_box_image(); ?> </code> You can optionally pass a post object or ID argument to the function to get a game box image for a specific post.
|
Echo Custom Taxonomy Field Values Outside the Loop
|
wordpress
|
WP 3.1 has everyone excited, if somewhat confused, about post formats. Enabling new post formats The issue of enabling post formats has been covered at length. It's as simple as adding this line to functions.php: <code> add_theme_support( 'post-formats', array( 'aside', 'gallery' ) ); </code> Displaying Posts of a certain Format But the issue of displaying these posts has hardly been covered at all. Lets document the process of displaying/querying posts of a certain format using an example: Let's say we want to put a Twitter-like status update in the sidebar. It's easy to enable the <code> status </code> post format, but how to I actually query for those posts to make them show up in the sidebar? I've done quite a bit of searching and haven't found an answer to this problem, all are welcome to contribute. If we come up with a good answer, I think it would be the first to document this issue. With thanks!
|
You have a lot of options for displaying using the "Post Formats" feature: for example in an index.php loop you can decide what to show based on the post format using has_post_format() function : <code> if ( has_post_format( 'aside' )) { echo the_content(); } elseif ( has_post_format( 'chat' )) { echo '<h3>'; echo the_title(); echo '</h3>'; echo the_content(); } elseif ( has_post_format( 'gallery' )) { echo '<h3>'; echo the_title(); echo '</h3>'; echo the_content(); } elseif ( has_post_format( 'image' )) { echo '<h3>'; echo the_title(); echo '</h3>'; echo the_post_thumbnail('medium'); echo the_content(); } elseif ( has_post_format( 'link' )) { echo '<h3>'; echo the_title(); echo '</h3>'; echo the_content(); } elseif ( has_post_format( 'quote' )) { echo the_content(); } elseif ( has_post_format( 'status' )) { echo the_content(); } elseif ( has_post_format( 'video' )) { echo '<h3>'; echo the_title(); echo '</h3>'; echo the_content(); } elseif ( has_post_format( 'audio' )) { echo '<h3>'; echo the_title(); echo '</h3>'; echo the_content(); } else { echo '<h3>'; echo the_title(); echo '</h3>'; echo the_content(); } </code> Using get_template_part() and get_post_format() to get a defferent loop based on the format, This is assuming that you have made a format loop.php (say format-status.php) file for each format used in your theme so you just call it : <code> get_template_part( 'format', get_post_format() ); </code> And you can also query posts based on their format: <code> $args = array( 'tax_query' => array( array( 'taxonomy' => 'post-format', 'field' => 'slug', 'terms' => array( 'post-format-quote' ) ) ) ) $query = new WP_Query( $args ); </code> and last (for now) you can use "post_class();" function to style based on CSS <code> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> </code> this will output something like: <code> <div id="post-id" class=”post format-status”> </code> Hope this helps getting started
|
Display/query post formats
|
wordpress
|
I'm having pretty heavy (lots of images) Wordpress website with around 20-30k unique users per day (1,000,000 monthly). German hosting that I use works fine in Europe, but many visitors from the USA, Asia and Australia complain about loading times. Do you know any good, affordable hosting companies that provide fast browsing to people from the USA > Australia > the UK > the rest of Europe > the rest of World (in this order) as most of my visitors are from these places? :) My current site "eats around 600 GB bandwidth monthly. I was thinking about MediaTemple, but I have mixed feelings, many people say it totally sucks and even more love it. I'd love the ability to buy additional bandwidth and using a few different WP blogs using one account.
|
Saw that you and a few others had their doubts about Media Temple. First off, if you have any questions feel free to ask. We have a good amount of customers with different experiences, be it bad or good. The shared service gets a lot more grief than our VPS , which many of our customers are very happy with. I see many people recommending VPS hosting, and if that's what you are looking for you may give our new (dv) 4.0 a look. Depending on your price range, we may or may not be the right place for you. @saltcod We do indeed have times where are we do fall short in providing consistently fast service. We are constantly working on improving our shared service to run as quickly as possible. At times the slowness is definitely our fault. At other times we find that customers are running sites that are either too big for what they have, or they are inundated with things that are making the site run slow (plugins, themes, etc.) Finally, not all customers that carry that logo are sponsored, some of those customers are also using our referral program. We make the badges publicly available on our website. Please feel free to let me know if you have any other questions regarding our services.
|
Best hosting for Wordpress blog(s)?
|
wordpress
|
I am designing a frontend for users, where they can submit an article/post from. But i am worrying if someone puts javascipt code, or SQL injection, or other malicious code. Is there a plugin or some sort of scripts which can help me to filter the post contents from security point of view. I'll appriate if someone can suggest me some code/script/plugin which can help to define rule over submmited contents like No. of external hyperlinks No. of Images Length of content etc. Although i can do it manually. So the lower part of the question is less important.
|
If your really worried I would probably create custom write panels or custom meta boxes tied into custom post types. That way you can make the custom post types based on user role and control what shows up very easily. For instance you can make a custom post type called "tweens" with the user role of "contributor" so they can write posts but not submit them. Using custom meta box's with a custom post type will give you complete control over what kind of data is submitted. For instance if you want to limit the above post type "tweens" to 5 images you only supply 5 image meta boxes, or limit the amount of words per text box, or strip urls or js, or remove the wysiwyg, etc ( anything really). Some references: http://codex.wordpress.org/Roles_and_Capabilities#Contributor http://codex.wordpress.org/Function_Reference/register_post_type http://codex.wordpress.org/Function_Reference/add_meta_box
|
Stop Authors from submitting spam post
|
wordpress
|
I'm trying to create a Thematic child theme that uses BuddyPress. First, I tried using BuddyMatic -- which currently doesn't work with WP3. Next, I tried the BuddyPress compatibility pack -- which totally works! Except for one thing: when I select "Activity Feed" as an option for the front page, I get a Not Found error. Going to /activity/, /groups/, /members/, and all other BuddyPress pages, however, works fine. Any idea what the issue might be? Thanks!
|
I figured out how to make it work, but it's a bit hacky. Essentially, I coped the index.php from activity into the the main index.php of my Thematic child theme, adding the Thematic actions afterwards. Same error persists if I leave it on "Activity Stream" for the front page, but when I return it to the default "Most recent posts", my modified index.php in the root takes over. I'll post my code in a few days if nobody answers my question with how I can get it to work through that option -- I'm building this as a high-end in-house repeated use theme, rather not resort to what I did. (Redid as answer since no response.)
|
Not Found when using activity stream as front page with BuddyPress
|
wordpress
|
I see a number of posts on various plugins for doing an Event Calendar that work with Wordpress, but the free hosted version does not allow me to use these. Are there any solutions that would work for hosting a calendar of events for an organization that I volunteer for? Even embedding a Live/Google calendar would work, although I understand that iframes are also not allowed. Thanks!
|
It may be time to give up WordPress.com. There is little day to day difference in managing a self-hosted version, but there is a world of opportunities that will open with a few well selected plugins. You mentioned you're volunteering for an organization. If the issue is paying for hosting, Dreamhost and HostGator offer free lifetime hosting for US based 501(c)3 non-profits. Dreamhost's process is the easier of the two. (Disclosure, I'm an affilate for both...but look ma, no links). Between free hosting and plugins, your organization's events should get all the attention they need.
|
Event Calendar on hosted wordpress?
|
wordpress
|
I am just creating a simple contact form, but I notice that it seems to post to an invalid page. The url in the browser is correct but the title of the page is "Page not found" on the top of the page <code> $emailed = false; if (isset($_POST['submit'])) { wp_mail('[email protected]', $_POST['subject'], $_POST['content']); $emailed = true; } </code> below ... the HTML: <code> <form action="<?php the_permalink(); ?>" method="post" id="contactform"> <div class="formelem"> <label for="name">Name</label> <input type="text" name="name" class="required" /> </div> <div class="formelem"> <label for="email">Email</label> <input type="text" name="email" class="required email" /> </div> <div class="formelem"> <label for="subject">Subject</label> <input type="text" name="subject" class="required" /> </div> <div class="formelem"> <label for="content">Content</label> <textarea name="content" cols="30" rows="10" class="required"></textarea> </div> <input type="submit" value="Submit Message" name="submit" value="submit" /> </form> </code>
|
I could be wrong, but I vaguely remember that: name, email get hijacked by WordPress to do post comments, if you renamed the form elements to be contact-name and contact-email, do you get the same issue?
|
Why when I submit a form in wordpress it loads a 404 page though URL is correct
|
wordpress
|
I updated my plugin, Export to Text , to 1.3 and committed it to the WordPress SVN repository yesterday. The 1.3 download button was available pretty quickly, but a day later the read me text is not rendering on the plugin page and the download update reminder is not working in the WP UI for users with earlier versions installed. How long does it typically take for plugins to be fully loaded by the WordPress.org website?
|
A readme update may take a week or more. Sometimes it helps to update just the readme file again. The Last Updated field is … dead. One of my plugins still shows the date 2010-12-24, but I had three updates in the mean time, the last one a week ago. The whole system feels like an old windows. :)
|
How long should it take for a plugin to fully load into the WordPress.org plugin repository?
|
wordpress
|
First time experimenting with wordpress and looking for advice on the correct way to add a block of html to a sidebar. This doesn't seem like a custom widget to me as there is no functionality involved, other than displaying an image. I want to position it above a sidebar menu which exists there already - instead of just lobbing the html directly into the template file, should i be doing something else with it? Thanks for any help!
|
You should simply add the html block to the built in text widget. And as for positioning it above the menu just use the drag n' drop functionality of the sidebar widgets.
|
Correct way to add a block element to sidebar layout
|
wordpress
|
Im trying to make different querys in my category like one with a offset of post and one that shows one post but while it continues to go through the loop, this is what i have but the loop keeps repeating itself i almost think im not doing it correctly. Anyone know whats wrong? <code> <?php if (have_posts()) : $count = 0; ?> <div id="featured-category"> <div class="heading"><h2 class="recent-post-title"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2></div> <?php query_posts('showpost=1'); ?> <?php while (have_posts()) : the_post(); ?> <div class="FC-image"> </div> </div> <?php endwhile ?> <?php wp_reset_query(); ?> <div id="recent-posts"> <!-- Post Starts --> <div class="post"> <?php query_posts('showpost=4&offset=1'); ?> <?php while (have_posts()) : the_post(); ?> <div class="post-img"> </div> <div class="heading"><h2 class="recent-post-title"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2></div> <div class="recent-post-content"> <?php get_the_excerpt_limit( 200, '...&nbsp;Read More&nbsp;&raquo;' ); ?> </div><!-- /.heading --> </div><!-- /.post --> <?php endwhile ?> <?php wp_reset_query(); ?> <?php query_posts('offset=4'); ?> <?php while (have_posts()) : the_post(); ?> <div class="post"> <div class="heading"><h2 class="recent-post-title"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2></div> <div class="recent-post-content two"> <?php get_the_excerpt_limit( 200, '...&nbsp;Read More&nbsp;&raquo;' ); ?> </div><!-- /.heading --> </div><!-- /.post --> <?php endwhile ?> <?php wp_reset_query(); ?> <?php endwhile ?> </code>
|
That's a really inefficient way to do it. Just use the $count variable you declared at the top, without any query_posts(): <code> $count = 0; while ( have_posts() ) : the_post(); if ( $count < 1 ) { // first post } elseif ( $count <= 4 ) { // next 4 posts } else { // rest of the posts } $count++; endwhile; </code> Also, it's 'showposts' not 'showpost'. Or use the newer 'posts_per_page'.
|
Query the Loop without breaking it
|
wordpress
|
Just getting into wordpress and learning a lot! I know how to create a custom field and use it for basic purposes. I'm trying to do a little more now...I'm hoping someone can help me. Here is the scenario: I have businesses and events section on my website. Businesses use the default "posts" from wordpress, "events" are a custom post type. I want to create a custom field to use for events that populates a dropdown list of the business posts the current user is the author of, effectively linking the two together. This way the user can only see the business posts they've created in the list and can not create events and link them to random businesses. I've tried utilizing the "LittlePromoBox" class found stackexchange-url ("in this post"). But have had no luck...I've tried to understand the logic but its too advanced for me at this point..can anyone help me out?
|
here: What you need is to create a meta box so first you use the add_meta_box() <code> // Hook into WordPress add_meta_boxes action add_action( 'add_meta_boxes', 'add_Businesses_custom_metabox' ); /** * Add meta box function */ function add_Businesses_custom_metabox() { add_meta_box( 'custom-metabox', __( 'Businesses' ), 'Businesses_custom_metabox', 'events', 'side', 'high' ); } </code> here you can see that i used "events" as the post type i want to register this meta box to and that my callback function is: <code> Businesses_custom_metabox() </code> and its the function that actually displays the metabox, so we define it like this: <code> /** * Display the metabox */ function Businesses_custom_metabox($post) { global $post,$current_user; //remember the current $post object $real_post = $post; //get curent user info (we need the ID) get_currentuserinfo(); //create nonce echo '<input type="hidden" name="Businesses_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />'; //get saved meta $selected = get_post_meta( $post->ID, 'a_businesses', true ); //create a query for all of the user businesses posts $Businesses_query = new WP_Query(); $Businesses_query->query(array( 'post_type' => 'posts', 'posts_per_page' => -1, 'author' => $current_user->ID)); if ($Businesses_query->have_posts()){ echo '<select name="a_businesses" id="a_businesses">'; //loop over all post and add them to the select dropdown while ($Businesses_query->have_posts()){ $Businesses_query->the_post(); echo '<option value="'.$post->ID.'" '; if ( $post->ID == $selected){ echo 'selected="selected"'; } echo '>'.$post->post_title .'</option>'; } echo '<select>'; } //reset the query and the $post to its real value wp_reset_query(); $post = $real_post; } </code> I tried to comment ever bit of it so you can understand better. And the last thing you have to do is process the metabox when a post is saved: <code> //hook to save the post meta add_action( 'save_post', 'save_Businesses_custom_metabox' ); /** * Process the custom metabox fields */ function save_Businesses_custom_metabox( $post_id ) { global $post; // verify nonce if (!wp_verify_nonce($_POST['Businesses_meta_box_nonce'], basename(__FILE__))) { return $post_id; } // check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } // check permissions if ('events' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return $post_id; } } elseif (!current_user_can('edit_post', $post_id)) { return $post_id; } if( $_POST ) { $old = get_post_meta($post_id, 'a_businesses', true); $new = $_POST['a_businesses']; if ($new && $new != $old){ update_post_meta($post_id, 'a_businesses', $new); } } } </code>
|
Populate a custom field dropdown with post titles by author
|
wordpress
|
How would you resend the login & password to a user who has forgotten his password? In this case they don't want to go to the "password" forgotten page. Additional Q: Mass re-sending of passwords. I understand that it's nearly impossible to resend the password, so reset is also ok. but i need a way to click select some users and then send them the reset link mail. Current Solution: I list my users (ordered by role) in a table & simply added a little lost password form with a button. It works but is the opposite of ... nice. If you want to resend a password, you click the button and open a blank tab/window. This saves me from going back all time, but re-sending 200 password mails still is a pain. Plus: It's impossible to resend the password. The user just receives a link to click to reset the password. <code> <td id="<?php echo $user->ID; ?>;user_pass;<?php echo $wpdb->users;?>"> <form name="lostpasswordform" id="lostpasswordform" action="<?php echo site_url('wp-login.php?action=lostpassword'); ?>" method="post" target="_blank"> <input type="text" name="user_login" id="user_login" class="input hide" value="<?php echo $curuser->user_login; ?>" size="15" tabindex="10" /> <input type="submit" name="wp-submit" id="reset-pass" class="margin-null" value="send" tabindex="100" /> </form> </td> </code> Thank you!
|
To reset the passwords for all users use the plugin Bulk Password Reset . It offers a nice interface with some useful options. For example: You can choose the users by their role or add a custom message to the reset email.
|
resend user login & password with custom button
|
wordpress
|
Not sure if the title makes sense sorry, but at the moment on my blog there is a long list of posts (with the thumbnail custom field) - the text next to the thumbnail is just the first characters from within the post. How exactly do I change that to something else? Thanks!
|
See this . You should be able to control that text by altering your Post's excerpts. You may need to click "Screen Options" at the top right of your Dashboard to have the Excerpt box be displayed when you create or edit posts. HTH.
|
On the post list, how do you show different text to the main content?
|
wordpress
|
I have a created a custom post type and have attached some custom fields to it. Now I would like for the search that authors can perform on the custom post list screen (in the admin backend) to also be performed on the meta fileds and not only look in the title and content as usual. Where can I hook in and what code I have to use? Example image Stefano
|
I solved filtering the query by adding the join on the postmeta table and changing the where clause. tips on filtering the WHERE clause (often require regular expression search&replace) are here on codex: <code> add_filter('posts_join', 'segnalazioni_search_join' ); function segnalazioni_search_join ($join){ global $pagenow, $wpdb; // I want the filter only when performing a search on edit page of Custom Post Type named "segnalazioni" if ( is_admin() && $pagenow=='edit.php' && $_GET['post_type']=='segnalazioni' && $_GET['s'] != '') { $join .='LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id '; } return $join; } add_filter( 'posts_where', 'segnalazioni_search_where' ); function segnalazioni_search_where( $where ){ global $pagenow, $wpdb; // I want the filter only when performing a search on edit page of Custom Post Type named "segnalazioni" if ( is_admin() && $pagenow=='edit.php' && $_GET['post_type']=='segnalazioni' && $_GET['s'] != '') { $where = preg_replace( "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*('[^']+')\s*\)/", "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where ); } return $where; } </code>
|
Extending the search context in the admin list post screen
|
wordpress
|
My site is using a short vanity URL. This is working across all of the custom theme pages. The only problem is when I logout in the admin it redirects to the long URL, which then 404s. My General Settings (which I can't change) are: WordPress address (URL): The long URL Site address (URL): The short URL Looks like the logout link is generated from wp-includes/general-template.php, but I hate to edit core, non-theme, WordPress files. Any ideas how to solve this logout 404 problem is greatly appreciated.
|
The quickest way to do this is through an Apache rewrite via mod_rewrite . You'll also have to tell WordPress where to points its login links using the login_url and logout_url filters. <code> return apply_filters('login_url', $login_url, $redirect); return apply_filters('logout_url', $logout_url, $redirect); </code>
|
Change admin logout URL
|
wordpress
|
Recently getting into wordpress plugin development, I started to investigate how to make my code backward compatible to php 4+. I've focused only on php 5.1+ for the past 5 years, so this was an ordeal. Anyway, when looking at some plugins, one of them had this description: IMPORTANT: This plugin is not compatible with PHP 4. If you try to install it on a host running PHP 4, you will get a parse error. WordPress is ending support for PHP 4 as of version 3.2 Is it true that wordpress is going to stop supporting php prior to php 5?
|
Yes, version 3.1 is the last version to support PHP 4. For WordPress 3.2, due in the first half of 2011, we will be raising the minimum required PHP version to 5.2. Why 5.2? Because that’s what the vast majority of WordPress users are using, and it offers substantial improvements over earlier PHP 5 releases. It is also the minimum PHP version that the Drupal and Joomla projects will be supporting in their next versions, both due out this year. Based on that announcement page, I'd actually expect 3.2 to be released a little later this year (i.e. early Q3), since 3.1 ended up a few months later than that page projected (not a knock on the dev team, FYI - just conjecture on my part).
|
Wordpress to end support for PHP 4?
|
wordpress
|
I have a div wrapper around my comments pagination. I have the comments set to paginate in the Wordpress admin at 10 comments per page. I want to hide the div wrapper if there are less than 10 comments (i.e. the pagination links aren't shown). I can't figure out how to do this. I know how to hide the div wrapper if pagination is turned off altogether, but I don't know how to check to see if the comments don't span to a second page when pagination is turned on. Here is my code: <code> <div class="comment-nav-wrapper"> <div class="left-cap">&nbsp;</div> <div class="comment-nav"> <?php paginate_comments_links($args); ?> </div> <div class="right-cap">&nbsp;</div> </div> </code> I would like to hide the comment-nav-wrapper altogether if the comments don't span to a second page. Is there some sort of Wordpress function for this, or do I need to come up with a bit of custom code?
|
Use the comments number function or the more native get_comments_number function and combine it with the page comments option <code> if ( get_option( page_comments ) == TRUE ) // do stuff </code>
|
If paginated comments don't span to a second page, how do I hide the div wrapper?
|
wordpress
|
I'm adding TinyMCE buttons to my plugin and they're working, but I only want these buttons to show up for a certain custom post type. I followed this tutorial if it helps: http://www.tutorialchip.com/wordpress/wordpress-shortcode-tinymce-button-tutorial-part-2/ How can I have that check if they are editing/posting a post in a custom post type of lets say, <code> newpages </code> ?
|
If you followed that tutorial you linked then look at the function that registers the buttons: <code> function mylink_button() { if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages'){ return; } if ( get_user_option('rich_editing') == 'true' ) { add_filter( 'mce_external_plugins', 'add_plugin' ); add_filter( 'mce_buttons', 'register_button' ); } } </code> and you change it a bit to check for the post type: <code> function mylink_button() { if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages')){ return; } if ( get_user_option('rich_editing') == 'true' ) { global $typenow; if (empty($typenow) && !empty($_GET['post'])) { $post = get_post($_GET['post']); $typenow = $post->post_type; } if ("newpages" == $typenow){ add_filter( 'mce_external_plugins', 'add_plugin' ); add_filter( 'mce_buttons', 'register_button' ); } } } </code> this way you only register the buttons on your "newpages" type
|
Check if on Custom Post Type for TinyMCE buttons
|
wordpress
|
I am having problems looking for info on the codex on how to query for child pages. It seems to be missing the reference for the available parameters
|
Yeah they've moved the parameters to WP_Query . You're looking for the post_parent parameter.
|
query_posts for child pages
|
wordpress
|
I read the wordpress codex and professional wordpress. It seems both use something like <code> if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) { </code> to determine if the table exists. Is there any reason why <code> CREATE TABLE IF NOT EXISTS ( ... ) </code> is not used? It will check and create the table in 1 query, won't it be better? Or am I missing something?
|
If you use "IF NOT EXISTS" then the dbdelta script will not upgrade your database with delta's appeared after the initial creation of the database. (assuming you want to re-use the same sql script) at least... that is what i think
|
Checking if Database Table exists
|
wordpress
|
I have 2 WordPress MultiSite installs (on different accounts, but under the same HostGator reseller a/c) and both seem to have been compromised. I say "compromised" because the user_logins have been modified (somehow) and "hidden users" are being shown via WP Admin. I attempted to login to the installs which are both up-to-date (3.1) MultiSites. I use 1PassWord (with 50 character alpha + numerical + symbolic passwords) so weak passwords are not the hole. My logins (which I use every day) were rejected so I knew there was trouble. I can access phpMyAdmin and sure enough the user_logins and user_email had been modified. And if I change them via phpMyAdmin, 5mins later they were re-edited (now it seems I can't even do this). * Interestingly, I don't think you can change a username in WP Admin (it is ghosted and uneditable). Does this mean they are hacking in external to WP Admin in order to change this? Also, in the User Dashboard, 3 users are displayed, but the count (up the top) indicates there are 5 users in total. Super Admin is a simular story - it shows the tally as "3 Super Admins" but only 1 is displayed. (I have checked the source code and used Web Dev tools to try and find hidden content in these admin pages, but no joy). I had hoped to add new Super Admin and delete old super admin (after porting posts to new user admin user). But I am unable to delete the original Super Admin user (ID=1) even after creating new Super Admin and removing Super Admin privileges from ID=1. When I click "delete" (on hover of User ID=1) nothing happens; the page simply refreshes. HostGator have been suprisingly helpless, arguably hopeless, and VERY slow to deal with this matter. Which is ongoing. Can anyone give me some advice or help in any way.
|
I would first of all change the password for phpMyAdmin because I think they moust be getting though the DB next thing is if that doesn't work , but the bullet and do a clean install but backup all the post and maybe the comments if you want ot.
|
Has anyone experience w/ WordPress (MultiSite) hidden users (possibly hacked)?
|
wordpress
|
I am trying to use jQuery to display the comment-section of my Wordpress-pages, but without requiring that jQuery be present on all pages that allows comments. Basically, I need the following: A generic javascript implementation of the 'in view' jQuery-plugin (http://remysharp.com/2009/01/26/element-in-view-event-plugin/) A method of activating jQuery (core) when the div containing the comments come into view. This would then load jQuery, which in turn would load the comments-section of the page, but only when that section became visible through the browser viewport. The problem seems to be that I really cannot use 'wp_enqueue_script' (Wordpress' generic way of adding scripts) for this, as it is a PHP-function. Is there some method that would allow me to implement a functionality as described above (without breaking Wordpress/jQuery-functionality)? EDIT: I need to enable jQuery only when the reader decides he wants to read comments (as opposed to only opening a page, seeing the title and leaving) - much in the style of Disqus. Disqus appears to be activated only when visible in the viewport, and I am assuming, at the same time the controlling Javascript is activated. How would I do something like that in regular Javascript (activating jQuery), and then porting it to Wordpress?
|
After a LOT of googling, trying to find a solution at the same time as keeping up with the earthquake-situation in Japan, I found a way: Two scripts for Wordpress Using wp_enqueue_script , I added a DeferJS ( https://github.com/BorisMoore/DeferJS ), which allows scripts to be loaded onEvent. Also, a I added a custom-script that looks like this: <code> function gingah_comments_onLoad() { var element = document.getElementById("comments"); var current = document.body.clientHeight+document.body.scrollTop; var target = element.offsetTop; if (current >= target) { $.defer("jquery-1.5.1.min.js", { bare: true }).done(console.log('jquery-1.5.1.min.js loaded')); window.onscroll = null; } } window.onscroll = gingah_comments_onLoad; </code> Which basically does a quick check every time the viewer scrolls the page, to see if the target element ("comments") is reached. When it is in fact visible in the viewport, DeferJS loads jquery-1.5.1.min.js (and also drops a quick line into the console.log for verification). Also, when it became visible, the effect from scrolling was removed. At this point, jQuery will be loaded and ready to use. This method does not, however, allow for use of the wp_enqueue_script -function to load jQuery (but it should be quite possible to extend it to not try to load it if already present). This is because of the obvious separation between PHP and JS. I owe a lot of thanks to kaiser for his comments and suggestions on the method, so thank you very much for the help.
|
How do I activate jQuery/script on demand?
|
wordpress
|
I have two custom post types: event and contact: http://acicafoc.josoroma.com/contactenos http://acicafoc.josoroma.com/eventos Both of them uses a custom taxonomy: country I just created a template named: taxonomy-country.php But I Need two separated templates, one for events who uses countries and another one for contacts who uses countries. For example, to display all events in United States or all contacts from Costa Rica. This is my actual code of taxnomy-country.php, but only for events who uses countries. <code> <?php /** * The template for displaying Countries Taxonomy. * */ get_header(); $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); //print_r($term); $args = array(); $args['post_type'] = 'event'; $args['taxonomy'] = $term->taxonomy; $args['term'] = $term->slug; query_posts($args); ?> <div id="container"> <div id="content" role="main"> <h1 class="page-title"><?php printf( __( 'Archives: %s', 'twentyten' ), '<span>' . $term->name . '</span>' ); ?></h1> <?php $category_description = category_description(); if ( ! empty( $category_description ) ) echo '<div class="archive-meta">' . $category_description . '</div>'; /* Run the loop for the category page to output the posts. * If you want to overload this in a child theme then include a file * called loop-category.php and that will be used instead. */ get_template_part( 'loop', 'category' ); ?> </div><!-- #content --> </div><!-- #container --> <?php get_sidebar(); ?> <?php get_footer(); ?> </code> Thanks in advance.
|
You use get_query_var('post_type') to set the post type in your args array <code> $args['post_type'] = get_query_var('post_type'); </code> and also include the right loop part based on that for example: <code> if (get_query_var('post_type') == "event"){ get_template_part( 'loop', 'event' ); }else{ get_template_part( 'loop', 'other' ); } </code>
|
A shared custom taxonomy between two custom post types
|
wordpress
|
Is it possible to block user registration based on the referring URL? I have an open registration WP site (configured so users can post ads and events) and while I typically don't get a lot of spam registrations (there is a reCaptcha involved), I was listed on a site as an example of the capabilities of the theme I'm using, and it generates a lot of "test" type of traffic. I like the traffic, but I don't like people registering just to post false test posts just to see how the site works, so I'd ultimately like to simply block registration from that referring URL. Thanks!
|
You can use <code> "register_post" </code> hook that happens just before the user is saved to the database or you can use <code> "register_form" </code> hook and check the referring URL for a match and die();
|
Block registration by URL referrer?
|
wordpress
|
As far as I know, there's not a simple function that will return true if a post has an attachment. With that in mind, what's the best way to determine if a post has an attachment (or even better, has an image attachment)? I'm automatically inserting a shortcode on posts, but would like that to only happen if there is actually an image attached to the post.
|
I think this should work: <code> $attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image') ); if ( $attachments ) { // do conditional stuff here } </code>
|
How can I determine if a post has an image attachment?
|
wordpress
|
I have a child theme based on Twenty Ten. I have split out the sidebar and secondary side bar so they can be used on different pages. sidebar.php file: <code> <div id="primary" class="widget-area" role="complementary"> <ul class="xoxo"> <?php /* When we call the dynamic_sidebar() function, it'll spit out * the widgets for that widget area. If it instead returns false, * then the sidebar simply doesn't exist, so we'll hard-code in * some default sidebar stuff just in case. */ if ( ! dynamic_sidebar( 'primary-widget-area' ) ) : ?> <li id="search" class="widget-container widget_search"> <?php get_search_form(); ?> </li> <li id="archives" class="widget-container"> <h3 class="widget-title"><?php _e( 'Archives', 'twentyten' ); ?></h3> <ul> <?php wp_get_archives( 'type=monthly' ); ?> </ul> </li> <li id="meta" class="widget-container"> <h3 class="widget-title"><?php _e( 'Meta', 'twentyten' ); ?></h3> <ul> <?php wp_register(); ?> <li><?php wp_loginout(); ?></li> <?php wp_meta(); ?> </ul> </li> <?php endif; // end primary widget area ?> </ul> </div><!-- #primary .widget-area --> </code> sidebar-2.php <code> <?php // A second sidebar for widgets, just because. if ( ! dynamic_sidebar( 'secondary-widget-area' ) ) : ?> <div id="secondary" class="widget-area" role="complementary"> <ul class="xoxo"> <?php dynamic_sidebar( 'secondary-widget-area' ); ?> </ul> </div><!-- #secondary .widget-area --> <?php endif; ?> </code> I want to display sidebar-2 (the secondary sidebar) in my post pages. I call them using: <code> <?php get_template_part(‘sidebar’,2); ?> </code> (in the following files: archive.php, post.php, author.php, category.php) instead of <code> <?php get_sidebar(); ?> </code> I've set my 'Settings' for 'Reading' so that the page is for displaying 'Posts'. When I visit the page, it displays the primary sidebar. You can see for yourself at http://akhomehealth.com/newsletter/ Sidebar should show search, archive, category and recent posts.
|
try this instead <code> <?php get_sidebar(2); ?> </code>
|
Twenty Ten child theme has post on an inner page. Cant get that page to use my desired template
|
wordpress
|
On the site I am developing I have a few custom post types set up (Press Releases, Articles, Podcasts). I also have the Tag Cloud widget enabled in my sidebar. I have tagged a post with 'Testtest', and I've also tagged a Press Release with 'Testtest'. The problem I have is when I click the 'Testtest' tag on my tag cloud, it only shows the 'Post' that I tagged, and not the Press Release. Any idea why this would be, or a solution? Thanks!
|
you can add them using pre_get_posts filter: <code> function myTagFilter($query) { $post_type = $_GET['type']; if (is_tag()){ if (!$post_type) { $post_type = 'any'; } $query->set('post_type', $post_type); } return $query; }; add_filter('pre_get_posts','myTagFilter'); </code>
|
Wordpress 3.1 - Tag page not showing posts from custom post type
|
wordpress
|
How do I identify that a page is a grandchild page?
|
use get_page twice like this handy little function <code> function get_grandpapa($page_id){ $current_page = get_page( $page_id ); if ($current_page->post_parent > 0){ //has at least a parent $parent_page = get_page($current_page->post_parent); if ($parent_page->post_parent > 0){ return $parent_page->post_parent; }else{ return false; } } return false; } </code> This function returns the grandparent page ID or false if there is no grandparent.
|
Identify that a page is a grandchild page
|
wordpress
|
It's an inconvenience to have to customize your theme just to use BuddyPress. It'd be much nicer if it simply used the wordpress page system for example, to inject content into standard WP pages. This way no theme editing is necessary, just activate BP and go. The idea would be that BuddyPress would just work in TwentyTen with off the shelf wordpress install + BuddyPress. Is there a solution?
|
There is actually a plugin for that (bptemplate pack). It works pretty well! http://wordpress.org/extend/plugins/bp-template-pack/
|
Is there a plugin or something that allows you to use BuddyPress without having to create a BuddyPress-ready theme?
|
wordpress
|
I have a custom post-type "model", and I want to be able to export certain values (eg Name, Height, Shoe Size, etc) and a set number of images from the gallery, from each Model to a PDF. Ultimately, what I want to be able to do is: From the Admin backend, click an "options tab" or some such select a number of Models, enter an email (or multiple, comma separated emails) Click a "send" button and have the PDFs generated and emailed off without further intervention. Is this at all possible in WordPress? Or is this too complex? Surely you can do anything with PHP and WordPress ;)
|
To answer your questions: Yes, it is possible. Depends on what you consider to be "too complex". No, you cannot do anything... For example, WordPress and PHP will not bring your deceased loved ones back.
|
Is it possible to create an "export to PDF" option?
|
wordpress
|
Is there a way to fetch the URLs of ALL images in the media gallery? I think this would be an easy way for a website to have a Pictures page that just pulls all of the images from the media gallery, granted it would only be necessary in certain scenarios. I don't need instructions on how to create a Pictures page, just how to pull all of the image URLs. Thanks!
|
<code> $query_images_args = array( 'post_type' => 'attachment', 'post_mime_type' =>'image', 'post_status' => 'inherit', 'posts_per_page' => -1, ); $query_images = new WP_Query( $query_images_args ); $images = array(); foreach ( $query_images->posts as $image) { $images[]= wp_get_attachment_url( $image->ID ); } </code> All the images url are now in <code> $images </code> ;
|
Get All Images in Media Gallery?
|
wordpress
|
I'm just beginning to work the "Custom Menu" functionality that was introduced in 3.0 into my theme. I like everything about this new capability and API, with one exception: Why no posts? I can create menus containing pages, categories, even tags, but where is the posts selector? I know I could use the "Custom Links" tool as a workaround, by pasting in the URL to a given post, but I'd rather not expect my users to do that without creating a ton of support issues. I'd rather just add a menu box called "Posts" that has the same functionality as "Pages". Has anyone done this and if so can you share the code? Alternately, and I know I'm dreaming on this one, what about a single box with tabs for selecting between pages and posts?
|
OK, I found the answer to this one and its surprisingly simple but maddeningly frustrating at the same time. All you have to do is click "Screen Options" while viewing the "Custom Menu" manager and place a check beside "Posts" to show the elusive hidden "Posts" widget. Now you can add "Posts" to your custom menus. Who knew anyone would ever want to do that? Why this is not part of the default screen options, while "Tags" is, escapes me, but that's the default none the less. Also, just to get a few more bytes out of this rant.. Whoever decided that "Excerpt" should no longer be visible on the post editor screen should have to answer at least one of the 5 emails I get per day with on the topic of "What happened to the excerpt field, it was there, now its gone". Brilliant.
|
How to add posts to custom menus?
|
wordpress
|
We're setting up a site to showcase a series of archival recordings. We have the custom post types sorted out thanks to all the help from this site (many, many thanks): <code> add_action( 'init', 'create_radiotalks' ); function create_radiotalks() { register_post_type( 'radiotalks', array( 'labels' => array( 'name' => __( 'Radio Talks' ), 'singular_name' => __( 'Radio Talk' ), 'add_new' => __( 'Add New' ), 'add_new_item' => __( 'Add New Radio Talk' ), 'edit' => __( 'Edit' ), 'edit_item' => __( 'Edit Radio Talk' ), 'new_item' => __( 'New Radio Talk' ), 'view' => __( 'View Radio Talk' ), 'view_item' => __( 'View Radio Talk' ), 'search_items' => __( 'Search Radio Talks' ), 'not_found' => __( 'No radio talks found' ), 'not_found_in_trash' => __( 'No radio talks found in Trash' ), 'parent' => __( 'Parent Radio Talk' ), ), 'public' => true, 'taxonomies' => array( 'category', 'post_tag' ), ) ); } </code> (I think my syntax is correct, but I'll take any critiques:) It turns out we want to add some more info to each of the individual custom posts. Namely, we'd like to make use of excerpts and custom fields--they aren't showing up on the 'add new radio talk' entry. I've dabbled a bit w/the supports tag, but no luck so far. Additionally, we'd like to enter a recording ID#, total run time (TRT), # of CDs per set and year of recording for each entry. Is the best approach to register custom taxonomies for this data? Or does it make more sense to make use of custom-fields? Thanks in advance for all your help.. Don.
|
Add supports to your array like so <code> 'supports' => array('title','editor','author','thumbnail','excerpt','comments') </code> As for the additional data per each recording if you need to filter or search by it the create a custom taxonomy if not then a custom fields would be just fine.
|
custom post data - how to
|
wordpress
|
There was a news item today possibly of interest to those who self-host WordPress: Automattic unveiled the Jetpack plugin. I hadn't heard of it before, but going off the announcement and the site FAQ, it looks as if it's going to provide multiple bits of functionality in one package (WP.com Stats, Twitter widget, shortcodes, etc). My issue is wondering whether this might be overkill. Wouldn't it make more sense to use a few small specific plugins that do what you need, rather than installing some big assembly when you only have a few specific needs?
|
Hi @Grant Palin: I think the decision is your own. As said Automattic is merging its plugins into JetPack and encouraging users with older versions to upgrade. If you want to continue using those plugins you likely will not have a choice but to upgrade to JetPack with the alternate being to switch to other plugins. I do expect the JetPack to be of high quality given the paid staff of Automattic maintains it. And as a counter to the "overkill" concerns I'd rather have fewer plugins listed in my plugin directory (fewer to update, fewer to have to understand, etc.) so I'd prefer to use JetPack instead of individual ones if I wanted to use more than one of the enclosed features because there is almost no overhead of significance to having the other functionality installed; certainly very little additional overhead on page load. However, at the time I write this , you cannot use JetPack on localhost . This makes using it for a professional solution that requires development, testing staging and live servers for deployment not really an option (vs. just by a blogger for their own blog.) If they do not address this limitation (which they might ) I expect we might see people forking the functionalities in JetPack. In summary, Caveat emptor .
|
When would it make sense to use Jetpack?
|
wordpress
|
Is it possible to control the length of the content or excerpt for a specific query/loop? I have come across the following code, but this changes the length for all excerpts, I want it focused on a specific custom query. <code> add_filter('excerpt_length', 'my_excerpt_length'); function my_excerpt_length($length) { return 20; } </code>
|
Try this: http://pippinspages.com/tutorials/better-wordpress-post-excerpt-revamped/
|
Content/Excerpt length control for a specific loop?
|
wordpress
|
I've never really been comfortable with the on-board image editor in WordPress, and here's a good example of why: I'm just setting up a vanilla WP installation and am using the TwentyTen theme. I've uploaded an image, rotated it 90 degrees (using the Edit Image feature), saved it and have used it as my Featured Image. The image that appears in my header and featured image area is still the original, rotated version. When I go back to the Gallery for this page, by clicking on the Featured Image in the Edit Posts section, the image is rotated correctly. But back on the Edit Posts section, or on the actual site the image is not rotated. I've hit "Save all changes" a dozen times, I've switched sizes a few times, and I'm using "Apply changes to: All image sizes" in the Edit box. I'm running out of options. Can someone walk me through the correct process to upload, rotate, and set a featured image? thanks!
|
AFAIK, the featured image ignores all on-site edits. It just takes your base image, and applies crop/resize based on your add_image_size defs.
|
Using the on-board image editor for featured images: edits are not being used
|
wordpress
|
Hi I run a site gaming review site www.co-opreviews.com . I'm trying to display info about the games in a sidebar on the right hand side of the page. (You can view a mockup of the sidebar here: http://i.stack.imgur.com/u3s5b.png ) I'm currently doing this through multiple sidebars (which my theme allows) and using a plaintext widget displaying the info through some rough HTML. However for 50+ games I'd require 50+ different sidebars and I'd have to replace the date, rating etc. all manually-- a cubersome and also fairly crude solution. I believe there is a way to make inserting the information easier with custom post types but all my current reviews are simply normal posts. Any help with my problem would be appreciated!
|
You don't need CPT's to display custom information. You could use custom fields (you may need to enable them in the screen options at the top of the post edit window). You'd just need to include the custom fields in your loop but position them so they appear over the sidebar. Their information would be related to the post their on and you wouldn't need to create a new sidebar for each post. The same thing could be achieved with custom meta boxes. I've heard good reviews on the plugin below but haven't used it myself. http://wordpress.org/extend/plugins/verve-meta-boxes/ Adding to what you have mentioned below it is possible to add a description to a tag so you could just format all of the extra information in the description field and use get_the_tags to call the information you want. Then you'd just have to add the tag you wanted to the post. Taking it a step further you're probably better off registering a new taxonomy (Game) setting it up so it works like a tag and calling the description of that. Then you won't be cluttering up your normal post_tags with the game names and it will be easier to call the description on only that taxonomy instead of all tags (and trying to exclude the ones you don't want). This would also let you use the new taxonomy in other spots in the site and thus relate multiple types of content (if you ever decided to add a new content type).
|
Displaying info in a sidebar
|
wordpress
|
For starters I am using this GREAT answer to achieve custom post types as well as a custom way to insert those post types into other pages, you can view that answer here: stackexchange-url ("Custom field/meta populated by dropdown of existing posts?") I am running into a problem however when wordpress auto saves itself, it clears whatever metadata i have put into the forms. EXAMPLE: I select the 3 drop downs I want from my metabox and hit update. The page reloads and the 3 choices are still selected. In phpMyAdmin i can look up the metadata and see the array in place as it should be. I now wait for wordpress to auto save. As soon as this happens i can either refresh the page (not update, just refresh) and the metadata is lost, or i can look up the metadata in phpMyAdmin and it will display nothing (ie: its gone). I'm guessing that this has something to do with needing to tie into another hook (some sorta auto update hook) or something, but even then it doesn't make sense that it would actually delete your metadata (rather than just not auto updating it). Last note: If you copy and paste Mikes code into functions.php, you should be able to recreate my error (in wordpress 3.1) very easy.
|
Well, as always I feel like a dummy, but after searching the internet for hours and seeing that it seems like lots of people are having this question and I cant seem to find an an answer anywhere, I guess im not THAT slow! the important code is something along these lines: <code> add_filter('wp_insert_post_data',array(__CLASS__,'filter_wp_insert_post_data'),10,2); static function filter_wp_insert_post_data($data, $postarr) { update_post_meta($postarr['ID'],'_offices',$postarr['offices']); return $data; } </code> what was happening is this code gets run, but there is no $postarr['offices'], so it inserts blank data instead! so the quick solution to this is: <code> if(isset($postarr['offices'])) update_post_meta($postarr['ID'],'_offices',$postarr['offices']); </code> If the data you want to insert isn't set, it wont update! I'm not sure why wordpress doesn't pass these variables in on an auto save but it does on the real save, but either way this works so I'm happy!
|
post meta data clearing on autosave
|
wordpress
|
I'd really love to be able to conditionally apply a CSS class to link elements of images embedded into posts, but I can't seem to figure this one out. Basically what I'd like to achieve is to replace the default embedded image link that links the image to the full size version of itself to opening it in a colorbox. I know I can achieve this with a bit of Javascript-trickery, but I'd love to figure out how to do this in the server side and then just attach the colorbox functionality in a straightforward manner. So, is there a filter I should add or what's the route to take here. Ideally I'd love to be able to write the code so that if a user embeds an image, the link opens the full size version in a colorbox but if the user specifies a custom link, it'll work like a regular link. This shouldn't be that hard. Thanks a lot for any help in advance!
|
Thanks a LOT to user stackexchange-url ("t31os") for the tip on where to find my solution! Also thanks to user stackexchange-url ("orionrush") for pointing out a dumb mistake I had made! :) Here's how I got what I wanted: <code> function add_colorbox_class_to_image_links($html, $attachment_id, $attachment) { $linkptrn = "/<a[^>]*>/"; $found = preg_match($linkptrn, $html, $a_elem); // If no link, do nothing if($found <= 0) return $html; $a_elem = $a_elem[0]; // Check to see if the link is to an uploaded image $is_attachment_link = strstr($a_elem, "wp-content/uploads/"); // If link is to external resource, do nothing if($is_attachment_link === FALSE) return $html; if(strstr($a_elem, "class=\"") !== FALSE){ // If link already has class defined inject it to attribute $a_elem_new = str_replace("class=\"", "class=\"colorbox ", $a_elem); $html = str_replace($a_elem, $a_elem_new, $html); }else{ // If no class defined, just add class attribute $html = str_replace("<a ", "<a class=\"colorbox\" ", $html); } return $html; } add_filter('image_send_to_editor', 'add_colorbox_class_to_image_links', 10, 3); </code>
|
Applying automatic link class to images embedded to posts
|
wordpress
|
I am having a unmanaged VPS, where my wordpress site is hosted, I am also using WP-ROBOT 3 plugin for auto posting, I want it to do auto post through cron jobs, According to the documentation of the plugin, I entered this code through SSH command <code> wget --post-data='mincamp=2&maxcamp=3&chance=50' -O /dev/null http://myURL/ </code> and it worked, but I want to set regular intervals, so that it autoposts everyday, how to do that? I want it to post after every 6 hours, what should be the cron commands
|
You can do this via wp_cron by using the following, <code> function more_reccurences() { return array( 'sixhourly' => array('interval' => 21600, 'display' => 'Every 6 hours'), ); } add_filter('cron_schedules', 'more_reccurences'); </code> then find the function that does the autopost and call it by <code> if ( !wp_next_scheduled('autopost_function') ) { wp_schedule_event(time(), 'sixhourly', 'autopost_function'); } </code> If you want to use linux cron should be something like: * 6,12,18,24 * * * /some-command -new edit: 28-3-2011 I think things are getting mixed up here, let me clarify. This * 6,12,18,24 * * * /some-command goes into your crontab file, which is completely outside your webserver and wordpress. This cannot be used in php. If you want to schedule it in wordpress you will need the functions that I gave. I'm not very familiar with wp-robot but i can give try to help. wp-robot is premium so I cant check the code. the code I gave at the top executes the autopost function every six hours. You need to write the autopost_function yourself or find a function in wp-robot you can trigger. ill give some examples: example ssh command: <code> function autopost_function() { $cmd = escapeshellcmd('wget --post-data='mincamp=2&maxcamp=3&chance=50' -O /dev/null http://myURL/'); exec ($cmd); } </code> Please note that using exec() is considered very dangerous in PHP, if not done correctly your entire server can be compromised/hacked and it may not run correctly if your server is running in safe-mode. You could try opening the page with curl which would better but your server would need curl support. Instead of the above I would use the following function to add posts programmatically. But this has nothing to do with wp-robot. example wp function: <code> function autopost_function() { // Create post object $my_post = array( 'post_title' => 'My post', 'post_content' => 'This is my post.', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array(8,39) ); // Insert the post into the database wp_insert_post( $my_post ); } </code> this function simply adds a post to the database, you can pass a lot of parameters to it. Look up wp_insert_post() on the codex for more information. Doing it like this is much safer , and easier. You can use the above code outside wp-robot, so you wont have to change the core files. All examples I have written are untested so they might contain some syntax problems. Hope this helps get you going.
|
How to set intervals in cron jobs?
|
wordpress
|
My system emails on my linux server have been getting "message undelivered" emails which appear to be sent from the Contact Form 7 widget I have on my website. The odd thing is, there is no "to:" field in the widget - just "from" and "message". And yet the "undelivered messages" include random to:addresses. I have Akismet set up, and I have tested that it works successfully (I get the spam failure message when I test with their test-spam-email address). Clearly, they are somehow highjacking some sort of php mailer (don't know what contact form 7 uses - built in wp_mail?). How do I stop it? I've contacted my host but they are unable to help me, other than to say "Disable Contact Form 7". Email message below. The bottom bits were bits I added to my contact form in my WordPress installation, which is the only reason I figured out it was coming from my Contact Form 7 widget: From: Mail Delivery System To: [email protected] Subject: Undelivered Mail Returned to Sender Date: Sun, 16 Jan 2011 02:13:01 -0800 (PST) Message-Id: [-- Attachment #1: Notification --] [-- Type: text/plain, Encoding: 7bit, Size: 0.6K --] This is the Postfix program at host pants.dreamhost.com. I'm sorry to have to inform you that your message could not be be delivered to one or more recipients. It's attached below. For further assistance, please send mail to If you do so, please include this problem report. You can delete your own text from the attached returned message. The Postfix program : host e.mx.mail.yahoo.com[67.195.168.230] said: 554 delivery error: dd This user doesn't have a yahoo.com account ([email protected]) [-5] - mta1038.mail.ac4.yahoo.com (in reply to end of DATA command) [-- Attachment #2: Delivery report --] [-- Type: message/delivery-status, Encoding: 7bit, Size: 0.5K --] Reporting-MTA: dns; pants.dreamhost.com X-Postfix-Queue-ID: DBA1514C005 X-Postfix-Sender: rfc822; [email protected] Arrival-Date: Sun, 16 Jan 2011 02:12:56 -0800 (PST) Final-Recipient: rfc822; [email protected] Action: failed Status: 5.0.0 Diagnostic-Code: X-Postfix; host e.mx.mail.yahoo.com[67.195.168.230] said: 554 delivery error: dd This user doesn't have a yahoo.com account ([email protected]) [-5] - mta1038.mail.ac4.yahoo.com (in reply to end of DATA command) [-- Attachment #3: Undelivered Message --] [-- Type: message/rfc822, Encoding: 8bit, Size: 1.5K --] From: floppyk2011 To: [email protected] Subject: [Out In Africa] Date: Sun, 16 Jan 2011 10:12:57 +0000 Message-ID: X-Mailer: PHPMailer (phpmailer.sourceforge.net) [version 2.0.4] Message body: �èñòåìà àêòèâíîé ðåêëàìû. �àðàáîòàòü â ñåòè. �ïëàòà çà ÷òåíèå ïèñåì è êëèêè. �àñêðóòêà ñàéòîâ - óâåëè÷åíèå ïîñåùàåìîñòè, íèçêèå öåíû äëÿ ðåêëàìîäàòåëåé!he system of active advertising. Earn online. Payment +for reading emails and clicks. Site promotion - increase attendance, lower prices for advertisers!ôëóïèê.ðô -- This mail is sent via contact form on Out In Africa (www.oia.co.za), from IP address: 80.58.205.99
|
It seems Contact Form 7 allows you to specify the recipient via a select dropdown . This means that the recipient e-mail address is stored in the form and sent to the server, which then just reads it. Unless the server then verifies the recipient address was one of the options you specified, this can be a "security hole" to send spam to other e-mail addresses. It would work like this: the server is prepared to read the <code> recipient </code> select field, in case you specified one. But even if you did not specify one, the spambot can send a <code> recipient </code> field value to the server, tricking it into thinking it came from a real HTML dropdown. This allows it to specify any value it wants there. It is possible that Contact Form 7 prevents this kind of attack, but you should check this yourself, I have no further experience with Contact Form 7.
|
Contact Form 7 being hijacked to send spam?
|
wordpress
|
The following is a tutorial to Sort Posts by Vote (for the Vote it Up plugin): I haven't found it anywhere so i put it here. This is a new function which add posibilities to sort post on index page by vote. Add this in votingfunctions.php : <code> function ShowPostByVotes() { global $wpdb, $voteiu_databasetable; mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error()); mysql_select_db(DB_NAME) or die(mysql_error()); //Set a limit to reduce time taken for script to run $upperlimit = get_option('voteiu_limit'); if ($upperlimit == '') { $upperlimit = 100; } $lowerlimit = 0; $votesarray = array(); $querystr = " SELECT * FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC "; $pageposts = $wpdb->get_results($querystr, OBJECT); //Use wordpress posts table //For posts to be available for vote editing, they must be published posts. mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error()); mysql_select_db(DB_NAME) or die(mysql_error()); //Sorts by date instead of ID for more accurate representation $posttablecontents = mysql_query("SELECT ID FROM ".$wpdb->prefix."posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT ".$lowerlimit.", ".$upperlimit."") or die(mysql_error()); $returnarray = array(); while ($row = mysql_fetch_array($posttablecontents)) { $post_id = $row['ID']; $vote_array = GetVotes($post_id, "array"); array_push($votesarray, array(GetVotes($post_id))); } array_multisort($votesarray, SORT_DESC, $pageposts); $output = $pageposts; return $output; } </code> and in your index.php page add: <code> <?php $pageposts = ShowPostByVotes(); ?> <?php if ($pageposts): ?> <?php foreach ($pageposts as $post): ?> <?php setup_postdata($post); ?> </code> Attention! Code above is something like: <code> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> </code> so in foreach loop you can use statements like in standard "The Loop" for example the_content, the_time(). To end this add: <code> <?php else : ?> <h2 class="center">Not Found</h2> <p class="center">Sorry, but you are looking for something that isn't here.</p> <?php include (TEMPLATEPATH . "/searchform.php"); ?> <?php endif; ?> </code> The guy who wrote the code went directly to the MySQL, so this code may break in future Worpdress releases. How to make this code to follow better Wordpress practices? EDIT: GetVotes function: <code> //Returns the vote count function GetVotes($post_ID, $percent = false) { global $wpdb; //prevents SQL injection $p_ID = $wpdb->escape($post_ID); //Create entries if not existant SetPost($p_ID); //Gets the votes $votes_raw = $wpdb->get_var("SELECT votes FROM ".$wpdb->prefix."votes WHERE post='".$p_ID."'"); $sinks_raw = $wpdb->get_var("SELECT usersinks FROM ".$wpdb->prefix."votes WHERE post='".$p_ID."'"); $guestvotes_raw = $wpdb->get_var("SELECT guests FROM ".$wpdb->prefix."votes WHERE post='".$p_ID."'"); $guestsinks_raw = $wpdb->get_var("SELECT guestsinks FROM ".$wpdb->prefix."votes WHERE post='".$p_ID."'"); /* Deprecated $uservotes_raw = $wpdb->get_var("SELECT votes FROM ".$wpdb->prefix."votes_users WHERE user='".$u_ID."'"); $usersinks_raw = $wpdb->get_var("SELECT sinks FROM ".$wpdb->prefix."votes_users WHERE user='".$u_ID."'"); */ //Put it in array form $votes = explode(",", $votes_raw); $sinks = explode(",", $sinks_raw); $guestvotes = explode(",", $guestvotes_raw); $guestsinks = explode(",", $guestsinks_raw); /* Deprecated $uservotes = explode(",", $uservotes_raw); $usersinks = explode(",", $usersinks_raw); */ $uservotes = 0; $usersinks = 0; $initial = 0; //Initial no. of votes [will be placed at -1 when all posts receive votes] //The mathematics if ($percent == true) { // make $votecount into a percent $totalcount = count($votes) + count($sinks) + count($guestvotes) + count($guestsinks) + count($uservotes) + count($usersinks) + get_option('voteiu_initialoffset') - 6; // the -6 is because count('') returns 1, so if there is no votes at all, 1 is returned. -6 offsets that $forcount = count($votes) + count($guestvotes) + count($uservotes) + get_option('voteiu_initialoffset') - 3; $againstcount = count($sinks) + count($guestsinks) + count($usersinks) - 3; if ($totalcount > 0) { $votecount = number_format(100*($forcount / $totalcount), 0) . "%"; } else { return false; } return $votecount; // uncomment this line below if you want to test //return count($votes) . " " . count($sinks) . " " . count($guestvotes) . " " . count($guestsinks) . " " . count($uservotes) . " " . count($usersinks) . " " . get_option('voteiu_initialoffset') . " " . $p_ID; } else { // wihtout percent mode, $votecount is number of total positive votes (votes minus sinks) $votecount = count($votes) - count($sinks) + count($guestvotes) - count($guestsinks) + count($uservotes) - count($usersinks) + $initial; return $votecount + get_option('voteiu_initialoffset'); } } function GetPostVotes($post_ID) { global $wpdb; //prevents SQL injection $p_ID = $wpdb->escape($post_ID); //Create entries if not existant SetPost($p_ID); //Gets the votes $votes_raw = $wpdb->get_var("SELECT votes FROM ".$wpdb->prefix."votes WHERE post='".$p_ID."'"); //Put it in array form $votes = explode(",", $votes_raw); return $votes + get_option('voteiu_initialoffset'); } </code>
|
I can't figure out how to setup this code. I've been dabbling with PHP for a while, but I'm only recently trying to go deeper into how all the WordPress stuff works. I don't understand what "Attention! Code above is something like:" means. Does that mean we put the previous code below it? Would you be able to do a quick newbie explanation of all the steps? That would be highly appreciated! Also, is there a way to make it so instead of showing the top posts from the entire site, it shows the top posts in each category? Thanks again@
|
How to fix/improve this 'bad coded' function that sort posts by votes (for the Vote it Up plugin)?
|
wordpress
|
I am using the Thesis theme with my WordPress multisite installation. I also changed the permalink settings from the Super Admin settings to remove /blog/ from the path. But now my menu links are broken. The permalink structure now is /%postname%/ and my pages have the links mydomain.com/about/, mydomain.com/contact/ etc. When I try and navigate to these pages, it gives me a 404 error. Can someone please help me out on how to resolve this issue? Thanks. Some additional info I checked the error logs and don't understand why the following log statements show up when I try to access the pages (if this helps in resolving the issue) <code> [Thu Mar 10 12:29:18 2011] [error] [client xxx.xxx.71.55] File does not exist: /var/www/html/about, referer: http://mydomain.com/ [Thu Mar 10 12:32:44 2011] [error] [client xxx.xxx.71.55] File does not exist: /var/www/html/contact, referer: http://mydomain.com/ </code> Shouldn't it be looking for the files in the wp-content/themes/thesis folder? ADDITIONAL INFO The content of the .htaccess is here (is the same as that in Network Settings) <code> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # uploaded files RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*) $1 [L] RewriteRule ^[_0-9a-zA-Z-]+/(.*\.php)$ $1 [L] RewriteRule . index.php [L] </code> Also, I am using the steps here for using Thesis with multisite installation
|
The solution posted here resolved the issue. The links work as expected now even when I use custom permalink structures!
|
WordPress multisite installation broke menu links
|
wordpress
|
I added a menu item to the Admin Bar that executes some Javascript to show debug information. The problem is that clicking this item also reloads the page. How can I prevent this? I was trying to speed up my debug & dev stuff and wanted to add a class to my main wrapper div using jQuery. Step 1: Add styles to your head <code> function my_admin_bar_script_def( $script ) { $script = ' jQuery(document).ready( function() { jQuery("li#wp-admin-bar-showdebug").click( function() { jQuery(".wrap").toggleClass("showdebug"); } ) } ); '; return print $script; } add_action( 'wp_head', 'my_admin_bar_script_def', 11 ); </code> Step 2: Add a admin bar menu item: <code> function my_admin_bar_class_switch() { global $wp_admin_bar; $wp_admin_bar->add_menu( array( 'parent' => 'theme_options' ,'title' => __( 'showdebug', TEXTDOMAIN ) ,'href' => '' // **interesting problem over here** ) ); } add_action( 'admin_bar_menu', 'my_admin_bar_class_switch', 70 ); </code> Problem: Every time you trigger your toggle function you'll fire up the link and reload the page. Therefore you'll get the initial trigger again. Replacing the link is not possible, because in the <code> $args </code> array for the <code> add_menu() </code> function you only define the <code> href </code> and the link will be printed anyway. Filters or hooks? Not available.
|
If you <code> return false </code> in that Javascript function the click will not be propagated and the page will also not reload. Even better, you can specify a <code> onclick </code> attribute for a menu item . So you definition would become this: <code> function my_admin_bar_class_switch( &$wp_admin_bar ) { // $wp_admin_bar is passed by reference, you don't need the global var $wp_admin_bar->add_menu( array( 'parent' => 'theme_options' ,'title' => __( 'showdebug', AHF_LANG ) ,'href' => '' // This can stay empty ,'meta' => array( 'onclick' => 'jQuery(".wrap").toggleClass("showdebug"); return false;' ) ) ); } add_action( 'admin_bar_menu', 'my_admin_bar_class_switch', 70 ); </code> In that case you don't need to hook up the <code> onclick </code> event yourself. I see two other possible errors there: <code> wp_head </code> is an action, not a filter, so by returning the script it won't be printed. Also, you depend on <code> showdebug </code> being part of the <code> id </code> , but because you don't specify the ID it is generated from the title. If that string is translated this ID won't stay the same.
|
Admin Bar menu item that executes Javascript but does not reload the page?
|
wordpress
|
I have a custom post type of items set up. I also have a taxonomy set up with items called categories . functions.php code: <code> regsiter_post_type('items', array('labels' => array ( 'name' => 'Items', 'singular_name' => 'Item' ), 'public' => true, 'rewrite' => array ( 'slug' => 'items' ), 'supports' => array ( 'title', 'excerpt', 'editor', 'comments', 'revisions', 'thumbnail' ), 'taxonomies' => array ( 'categories', 'tags' ) )); register_taxonomy ( 'categories', 'items', array('hierarchical' => true, 'label' => 'Item Categories', 'rewrite' => array ( 'slug' => 'categories', 'hierarchical' => ture ))); require 'rewrites.php'; // load rewrite class Rewrites::init(); // call init function in rewrite class </code> rewrites.php code: <code> class Rewrites { // Start class methods public static function init() { // Rewrite urls add_action ( 'generate_rewrite_rules', array( __CLASS__, 'rules' ) ); add_filter ( 'query_vars', array( __CLASS__, 'vars' ) ); } public static function rules ( $wp_rewrite ) { $new_rules = array(); $new_rules['categories/(.+?)/view/(.+)/?'] = 'index.php?categories=$matches[1]&view=$matches[2]'; return $new_rules + $wp_rewrite->rules; } // End class methods } </code> So when looking at posts in the taxonomy of categories the url would be: /categories/%name_of_taxonomy%/ I need to also append to the url to add in query_vars /categories/%name_of_taxonomy%/view/%type_of_view%/ %type_of_view% would be a couple different options. list, grid etc. Here is my rewrite rule: <code> [categories/(.+?)/view/(.+)/?] => index.php?categories=$matches[1]&view=$matches[2] </code> But when I go to the url /categories/%name_of_taxonomy%/view/grid/ it redirects back to /categories/%name_of_taxonomy%/
|
Found the solution. The rewrites were getting added to the db after the system was reading them from the db. Moved the code and it worked!
|
Taxonomy Rewrite Rules Redirecting Instead of Masking
|
wordpress
|
I have another dumb question, but I can't get one thing :) I've found this very good article on creating custom post types: http://thinkvitamin.com/code/create-your-first-wordpress-custom-post-type/ I'm not sure how Step 4 works. This guys writes: <code> add_action("manage_posts_custom_column", "portfolio_custom_columns"); add_filter("manage_edit-portfolio_columns", "portfolio_edit_columns"); function portfolio_edit_columns($columns){ $columns = array( "cb" => "<input type=\"checkbox\" />", "title" => "Portfolio Title", "description" => "Description", "year" => "Year Completed", "skills" => "Skills", ); return $columns; } function portfolio_custom_columns($column){ global $post; switch ($column) { case "description": the_excerpt(); break; case "year": $custom = get_post_custom(); echo $custom["year_completed"][0]; break; case "skills": echo get_the_term_list($post->ID, 'Skills', '', ', ',''); break; } } </code> I have two different post types ('books' and 'movies'). And I can't get how to link this code with right one! I'm sure I'm missing something (most likely in the code), but I didn't see him including "portfolio_edit_columns" anywhere in the code. I have found this in WP Codex: http://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column and it seems like manage_edit-${post_type}_columns does the magic, but I've tried both manage_edit-books_columns and manage_edit-movies_columns and nothing! :) So how to create two separate column layouts for different post types?
|
The code from ThinkVitamin is right. I think the problem came from else where in your code. Actually, the hook <code> manage_edit-${post_type}_columns </code> takes an argument <code> $columns </code> which is an array of all registered columns. To add a new column, just add a new element to this array, like this: <code> add_filter('manage_edit-film_columns', 'my_columns'); function my_columns($columns) { $columns['views'] = 'Views'; return $columns; } </code> This post has more details that might help you.
|
How to add custom columns to Custom Post Type admin screen
|
wordpress
|
I know there is alot of discussion about the CPT and permlinks together with the 404. I did not found a solution though I am close. It would be great if someone could assist me to get it working. Ok what I did is: <code> function post_type_services() { register_post_type( 'services', array( 'label' => __('Services'), 'singular_name' => __( 'Service' ), 'capability_type' => 'post', 'rewrite' => array('slug' => 'service','with_front' => FALSE), 'public' => true, 'show_ui' => true ) ); flush_rewrite_rules( false ); } add_action('init', 'post_type_services'); </code> I added a CPT for services. I added a slug and I also added <code> flush_rewrite_rules(false) </code> as suggested in many blog posts. I turned on Permlinks with the settings <code> /%year%/%monthnum%/%postname% </code> I added a file <code> single-services.php </code> which contains following content <code> <?php get_header(); ?> <div class="content"> <div class="content_resize"> <div class="mainbar"> <?php query_posts('post_type=services'); ?> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <div class="article"> <h2><?php the_title(); ?></h2> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '' . __( 'Pages:', 'twentyten' ), 'after' => '' ) ); ?> <?php edit_post_link( __( 'Edit', 'twentyten' ), '', '' ); ?> </div> <?php endwhile; ?> </div> <div class="sidebar"> <div class="gadget"> <h2>Auswahl</h2> <div class="clr"></div> <?php wp_nav_menu( array( 'sort_column' => 'menu_order', 'menu_class' => 'sb_menu', 'theme_location' => 'leftmain' ) ); ?> </div> <?php get_sidebar(); ?> </div> </div> <div class="clr"></div> </div> <div class="fbg"> <div class="fbg_resize"> <div class="footer"> <?php get_footer(); ?> </div> </div> </div> </code> So far so good. What I want is. if I navigate to http://www.mydomain.com/service I would like to see my list of services and when I click on a single service I want to display the single service. What I do get right now is when I navigate to http://www.mydomain.com/service . I get a 404 but when I visit http://www.mydomain.com/service/my-first-service I see the list of services... What did I do wrong? How can I get a list of services when I visit http://www.mydomain.com/service ? P.S.: I use the starkers base template to generate my own...
|
You need to add the following to your <code> register_post_type() </code> array: <code> 'has_archive' => 'service' </code>
|
WP 3.1 custom post type permlinks
|
wordpress
|
This is the topic loop of the bbPress plugin . How can I make it stop when it reaches two posts? (Topics custom post types)? <code> <?php /** * Topics Loop * * @package bbPress * @subpackage Theme */ ?> <?php if ( bbp_get_query_name() || bbp_has_topics() ) : ?> <?php get_template_part( 'pagination', 'bbp_topics' ); ?> <table class="bbp-topics" id="bbp-forum-<?php bbp_topic_id(); ?>"> <thead> <tr> <th class="bbp-topic-title"><?php _e( 'Topic', 'bbpress' ); ?></th> <th class="bbp-topic-voice-count"><?php _e( 'Voices', 'bbpress' ); ?></th> <th class="bbp-topic-reply-count"><?php _e( 'Replies', 'bbpress' ); ?></th> <th class="bbp-topic-reply-count"><?php _e( 'Votes', 'bbpress' ); ?></th> <th class="bbp-topic-freshness"><?php _e( 'Freshness', 'bbpress' ); ?></th> <?php if ( ( bbp_is_user_home() && ( bbp_is_favorites() || bbp_is_subscriptions() ) ) ) : ?><th class="bbp-topic-action"><?php _e( 'Remove', 'bbpress' ); ?></th><?php endif; ?> </tr> </thead> <tfoot> <tr><td colspan="<?php echo ( bbp_is_user_home() && ( bbp_is_favorites() || bbp_is_subscriptions() ) ) ? '5' : '4'; ?>">&nbsp;</td></tr> </tfoot> <tbody> <?php while ( bbp_topics() ) : bbp_the_topic(); ?> <tr id="topic-<?php bbp_topic_id(); ?>" <?php bbp_topic_class(); ?>> <td class="bbp-topic-title"> <a href="<?php bbp_topic_permalink(); ?>" title="<?php bbp_topic_title(); ?>"><?php bbp_topic_title(); ?></a> <p class="bbp-topic-meta"> <?php printf( __( 'Started by: %1$s', 'bbpress' ), bbp_get_topic_author_link( array( 'size' => '14' ) ) ); ?> <?php if ( !bbp_is_forum() || ( bbp_get_topic_forum_id() != bbp_get_forum_id() ) ) printf( __( 'in: <a href="%1$s">%2$s</a>', 'bbpress' ), bbp_get_forum_permalink( bbp_get_topic_forum_id() ), bbp_get_forum_title( bbp_get_topic_forum_id() ) ); ?> </p> </td> <td class="bbp-topic-voice-count"><?php bbp_topic_voice_count(); ?></td> <td class="bbp-topic-reply-count"><?php bbp_topic_reply_count(); ?></td> <td class="bbp-topic-reply-count"><?php DisplayVotes(get_the_ID()); ?></td> <td class="bbp-topic-freshness"> <?php bbp_topic_freshness_link(); ?> <p class="bbp-topic-meta"> <?php bbp_author_link( array( 'post_id' => bbp_get_topic_last_active_id(), 'size' => 14 ) ); ?> </p> </td> <?php if ( bbp_is_user_home() ) : ?> <?php if ( bbp_is_favorites() ) : ?> <td class="bbp-topic-action"> <?php bbp_user_favorites_link( array( 'mid' => '+', 'post' => '' ), array( 'pre' => '', 'mid' => '&times;', 'post' => '' ) ); ?> </td> <?php elseif ( bbp_is_subscriptions() ) : ?> <td class="bbp-topic-action"> <?php bbp_user_subscribe_link( array( 'before' => '', 'subscribe' => '+', 'unsubscribe' => '&times;' ) ); ?> </td> <?php endif; ?> <?php endif; ?> </tr><!-- #topic-<?php bbp_topic_id(); ?> --> <?php endwhile; ?> </tbody> </table><!-- #bbp-forum-<?php bbp_topic_id(); ?> --> <?php get_template_part( 'pagination', 'bbp_topics' ); ?> <?php else : ?> <div id="topic-0" class="post"> <div class="entry-content"> <p><?php _e( 'Oh bother! No topics were found here! Perhaps searching will help.', 'bbpress' ); ?></p> <?php get_search_form(); ?> </div><!-- .entry-content --> </div><!-- #post-0 --> <?php endif; ?> </code>
|
I think including a counter like this would do the trick. Does this help? <code> <?php $showposts=2; $counter=0; while ( bbp_topics() ) : bbp_the_topic(); $counter++; if(counter<=$showposts) { ?> /*** Do stuff ***/ <?php } else { break; } endwhile; ?> </code>
|
How to make the following loop break/stop when it reaches 2 posts (custom post types called Topics)?
|
wordpress
|
I have added an image size with <code> add_image_size('gallery-thumb', 48, 48); </code> Why when I do <code> array_slice(wp_get_attachment_image_src($firstimg->ID, 'gallery-thumb')) </code> I get the link to the full sized image? UPDATE Somehow it appears that even when I do <code> wp_get_attachment_image_src($photo->ID, array(48,48)) </code> I get the thumbnail image (150, 150)
|
Does the 48x48 thumbnail file exist? If not, you can use a plugin like Regenerate Thumbnails.
|
Why is wp_get_attachment_image_src not working with my custom size (add_image_size)
|
wordpress
|
Essentially what I'd like to do is have the same effect as the wp_list_authors tag, but instead of just listing the name or their post count, I want to be able to do a loop with the IDs. Ultimately I'd like have to a page with every author, with their name, description, avatar and link. I can figure out the specifics, I just need a way to do something like: <code> foreach $author as $author->ID </code> Thanks in advance, Pete
|
Looks like you'll want to use get_users and you might want to take a look at the source code behind wp_list_authors to info on how to use it.
|
Custom Author Loop
|
wordpress
|
I'm looking for something, but don't exactly know what. I have a shortcode, let's call it [shortcode]. Users will input HTML tags inside, mostly images, but also links, images in links, etc., for example: <code> [shortcode] <img src="http://www.site.com/myimage.jpg" /> <a href="http://www.blabla.com"><img src="http://www.site.com/myimage2.jpg" /></a> (...) [/shortcode] </code> The point is I want to format URLs, differently, I want every img src to start with files/myimagescript? So the code above should output: <code> <!--- shortcode code before input --> <img src="files/myimagescript?http://www.site.com/myimage.jpg" /> <a href="http://www.blabla.com"><img src="files/myimagescript?http://www.site.com/myimage2.jpg" /></a> (...) <!-- shortcode code after input --> </code> So basically I need to simply change src of images. And it should work for any number of images, from 1 to unlimited. I'm thinking about foreach PHP loop, but I'm not sure how to grab each img src line from shortcode and process it before displaying?
|
you can use regex to find your the src and use that to append your "files/myimagescript?" to it: <code> function append_myimagescript($attr, $content){ $pattern = '/src="([^"]*)"/i'; $replacement = 'files/myimagescript?${1}'; return preg_replace($pattern, $replacement, $content); } </code>
|
Shortcode content filter?
|
wordpress
|
I've taken this line from header.php of TwentyTen where its loading the custom menus... <code> <?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' ) ); ?> </code> I understand their fallback plan, but for mine, if no custom menu has been assigned to my custom menu selector, I don't want to return anything. What's the function to determine if my custom menu has an assigned menu?
|
From looking at the Codex , you should be able to just pass the fallback_cb parameter as false to have wp_nav_menu return nothing. So something like: <code> <?php wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'primary', 'fallback_cb' => FALSE ) ); ?> </code>
|
if (has_custom_menu())?
|
wordpress
|
I need some help with restyling my alternate widget areas. I've created some new widget areas, and placed one into the main content of my index.php . This works just fine, however i want to style it differently. WordPress: 3.0.4 Theme: Twenty Ten Child (twentyten-child) Server: Local/MAMP I've tried creating new style definitions for this particular widget area, mainly wanting to get rid of the list bullets. I've also tried <code> list-style: none </code> with every one of the widget css definitions in my child theme's stylesheet, this doesn't appear to be working . Firebug shows that the widget has a class of <code> xoxo </code> so i removed reference to that class in my file sidebar-content.php and there’s no such string in either the parent or child theme's functions. The widget I’m calling to the area is WP's default blogroll widget . Is there any way to remove the xoxo class attached to this widget from within the theme twentyten, perhaps using a filter? How can I resize the widget widths to allow them to fill up the custom widget area – or will they automatically do so? The sidebar html for this widget area as follows: <code> <?php /* Theme:twentyten-child-kw Alt Sidebar containing the content widget areas. @package WordPress @subpackage Twenty_Ten @since Twenty Ten 1.0 */ ?> <div id="content" class="alt-widget-area" role="complementary"> <?php /* When we call the dynamic_sidebar() > function, it'll spit out the widgets for that widget area. If it instead returns false, then the sidebar simply doesn't exist, so we'll hard-code in some default sidebar stuff just in case. */ if ( is_active_sidebar( 'alt-content-widget-area' ) ) : ?> <?php dynamic_sidebar( 'alt-content-widget-area' ); ?> <?php endif; // end content widget area ?> </div><!-- #content .alt-widget-area --> </code> In my child theme's style sheet, created definitions for the class <code> alt-widget-area </code> are based on the parent theme's definitions for <code> widget-area </code> , however, the class <code> xoxo </code> is taking precedence over everything. Any suggestions please?
|
you can either use the !important property or ensure that your style definition has precedence by making it more specific. http://www.google.com/search?q=css+specificity
|
Customized widget area - how to override or filter class xoxo?
|
wordpress
|
I am trying to upload java files to my word press blog but it does not let me upload any files with .java extension. It says ".java” has failed to upload due to an error *File type does not meet security guidelines. Try another.* So how do I add .java extension so that it allows me to upload java source code. I am using wordpress version 3.0.4. Thanks.
|
Use filter ' upload_mimes '. <code> <?php add_filter('upload_mimes','add_java_files'); function add_java_files($mimes) { // Add file extension 'extension' with mime type 'mime/type' $mimes['java'] = 'text/x-java-source'; return $mimes; } </code>
|
Adding file types in wordpress
|
wordpress
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.