question
stringlengths 0
34.8k
| answer
stringlengths 0
28.3k
| title
stringlengths 7
150
| forum_tag
stringclasses 12
values |
---|---|---|---|
Say I have the following taxonomy terms: <code> Term 1 Term 1.1 Term 1.2 Term 2 Term 2.1 </code> How can I get only posts that are assigned to Term 1 and not include those that are assigned to Term 1.1 or Term 1.2? For example: <code> $pages = get_posts(array( 'post_type' => 'page', 'numberposts' => -1, 'tax_query' => array( array( 'taxonomy' => 'taxonomy-name', 'field' => 'id', 'terms' => 1 // Where term_id of Term 1 is "1". ) ) ); </code> is also giving me posts that have Terms 1.1 and 1.2 assigned. Thanks.
|
In looking at the WP_Tax_Query class in /wp-includes/taxonomy.php, I found that there is a 'include_children' option which defaults to true. I modified my original get_posts() call with the following, and it works great: <code> $pages = get_posts(array( 'post_type' => 'page', 'numberposts' => -1, 'tax_query' => array( array( 'taxonomy' => 'taxonomy-name', 'field' => 'id', 'terms' => 1, // Where term_id of Term 1 is "1". 'include_children' => false ) ) ); </code> (Still looking for some complete documentation on the 'tax_query' option...)
|
get_posts assigned to a specific custom taxonomy term, and not the term's children
|
wordpress
|
I'm using Drill Down Ipod Menu and I'm really like the style of showing submenus , but I have two problems with it. 1-when i load a page it shows all submenus open for a second and I experience a Flash of Unstyled Content , it was good for a while when I changed style css but it backed again (i don't know if there's a relation between css file and the problem). my list of active plugins is below (I had some others that i deleted them): 1-Bulk Post Creator Plus 2-Cat + Tag Filter 3-Category Grid View Gallery 4-cforms 5-Custom Field Template 6-ShowID for Post/Page/Category/Tag/Comment 7-SwfObj 8-vSlider 9-wp-jalali how can I prevent showing my menu unstyled ? 2- when I navigate from a submenu to my homepage (from a link outside of menu) menu stay in previous state , i know it use cookies , but is there anyway to show current page instead of using cookies ? if it's impossible to solve this problems what plugin can I use instead to have folding menus from wordpress custom menus (not pages and categories ) ? sorry for my bad english thanks in advancce
|
Your best bet would be to consult the author of plugin since it's using a custom jQuery plugin script. how can I prevent showing my menu un styled? You can add a class of <code> no-display </code> to the elements of the menu that are un styled as the page loads then in css set <code> .no-display {display:none;} </code> Then use jQuery to remove the `no-display' class when the page is loaded right before it calls the plugin javascript. <code> jQuery(document).ready(function($) { $('#parent-div').removeClass("no-display"); }) </code>
|
jQuery Drill Down iPod Menu FOUC and Selecting Current page
|
wordpress
|
I'm looking for a nice way to attach an image as a thumbnail to a category. No plugin that I found does this. I have a category loop and it would nice to display a category thumbnail, not just the name and description.
|
Use the plugin Taxonomy Images by @mfields.
|
Thumbnail for categories / taxonomies plugin?
|
wordpress
|
I am creating my first website in wordpress, and I have noticed some strange behavior. The website is really slow on the initial load. When I open the website after some time of inactivity, let's say an hour, the site loads extremely slow, over 5 sec. After that the website is just fast. Even when I close the browser and open again the website stays fast. When I switch to another browser, I have the same problem. Initial load is slow, after that the page works as usual. Anyone know something I could do. I have disabled all plugins and still the same problem, any know what I can do. Profiling with firebug and Yslow is not really an option, because I can not get good results. I can only test this once every hour.
|
Maybe your PHP is running per CGI or FastCGI in a separate process that shuts down after a while of inactivity. Does it change if you register at an uptime monitoring service ? A cache plugin like W3 Total Cache may help too.
|
My website is slow on the initial load
|
wordpress
|
I'm developing a functionality to let only customers and doctors have access to exam results. But i'm not so sure about the strenght of my code in securing view only to those authorised. I've gotten so far as to create the 'exam' post type to handle the information and added the metabox to save doctor and patient info in every exam (doctor and patient are also custom roles for users, with capabilities similar to subscribers). then i've created this function to check if the user trying to view content is entitled to it: <code> /* * Checks if user is logged in and has access to that specific exam */ function rm_userauth_check() { global $current_user; get_currentuserinfo(); $doctor = get_post_custom_values('doctor'); $patient = get_post_custom_values('patient'); $loggeduser = $current_user->user_login; $nicename = $current_user->display_name; $mainrole = $current_user->roles; if ($current_user->data !== null) { if ($mainrole[0] == 'doctor' && $loggeduser == $doctor[0]) { return true; // this user is a doctor and is assigned to this exam } elseif ($mainrole[0] == 'patient' && $loggeduser == $patient[0]) { return true; // this user is a patient and is assigned to this exam } else { return false; // this user is not assigned to this exam } } else { return false; // user is not logged in } </code> and now i'm calling it on my single-exam.php file as <code> <?php if (function_exists('rm_userauth_check')) : ?> <?php if (rm_userauth_check()) : ?> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'single' ); ?> <?php endwhile; // end of the loop. ?> <?php else : ?> <?php wp_redirect( home_url() ); exit; ?> <?php endif; ?> <?php endif; ?> </code> How does it look to you? Am i going the right way here or should i try another method?
|
The easiest way is to use <code> if ( current_user_can( 'capability' ) ) // do stuff </code> . You'll find more about capabilities in the codex. You can also inspect the data some user has attached with normal <code> var_dump() </code> and else. I also got a pretty old plugin for that. But I'm not sure if it still works with the current WP version. If it does, you'll be presented with close to all user data and some hints & snippets on a new admin page.
|
Restricting access to content
|
wordpress
|
I have a code that call <code> get_the_title() </code> and it works, but <code> get_the_excerpt() </code> return empty. How can i make it work? This code is inside a plugin called "WP Facebook Open Graph protocol". Here's the part i want to change: <code> if (is_singular('post')) { if (has_excerpt($post->ID)) { echo "\t<meta property='og:description' content='".esc_attr(strip_tags(get_the_excerpt($post->ID)))."' />\n"; }else{ echo "\t<meta property='og:description' content='". [?] ."' />\n"; } }else{ echo "\t<meta property='og:description' content='".get_bloginfo('description')."' />\n"; } </code> Here, <code> has_excerpt </code> always fail, and <code> get_the_excerpt($post->ID) </code> don't work anymore (deprecated). So, how can i display the excerpt there? ps: I'm using "Advanced Excerpt" plugin as well
|
got it using <code> my_excerpt($post->post_content, get_the_excerpt()) </code> and using the <code> my_excerpt() </code> function from stackexchange-url ("Using wp_trim_excerpt to get the_excerpt() outside the loop")
|
Get excerpt using get_the_excerpt outside a loop
|
wordpress
|
I do not want to use any existing plugin. For WordPress-less projects, I would specify a PHP file in <code> href </code> <code> <a href="FileOnMySite.php">Click here</a> </code> <code> FileOnMySite.php </code> will be like <code> header('Location: http://www.MyaffiliateLink.com') </code> But I'll definitely get <code> header already sent </code> in WordPress. Is it possible to avoid <code> header already sent </code> ? Any other cloaking method that you know will work best with WordPress? Thanks!
|
I don't see why the same method can't still work in a WordPress site. If you specifically specify a file to link to that is a valid PHP file, available on your server, then it will still hit that file instead of hitting WordPress. If you are having issues with this working, make sure you don't have any rewrite rules interfering in your .htaccess file.
|
Writing a link cloaking plugin
|
wordpress
|
I have a page with the slug <code> blog </code> . Mysite.com/blog correctly renders from the template file page-blog.php. However, it does not execute footer code from my theme that's conditioned on <code> is_page('blog') </code> , nor does it have an "Edit Page" link in the Admin bar. I also have a custom post type called <code> blog </code> , but this page doesn't execute code for <code> is_post_type_archive('blog') </code> either. In the admin bar, there is no "Edit Category" link or "Edit [Anything else]". This is the info the WP Debug plugin gives me when I load the page: <code> Request: blog Query String: pagename=blog Matched Rewrite Rule: (blog)(/[0-9]+)?/?$ Matched Rewrite Query: pagename=blog&page= </code> What could be the problem?
|
The problem was due to a secondary loop in the pageโbefore this loop, the page knows it's a page; but after the loop (and in the footer, where the Admin Bar and my code would be rendered), the page thought it was the last post of the secondary loop. Neither wp_reset_query() nor wp_reset_postdata() worked; I am guessing this has to do with the fact that I use $wp_query as the name of the secondary loop (so that I could use the loop.php template file to display the posts). Here's the code that worked: <code> $temp_query = clone $wp_query; $wp_query = new WP_Query( 'post_type=publication&posts_per_page=5' ); get_template_part( 'loop' ); /* get_template_part( 'loop' ) only seems to work if the query is in $wp_query */ $wp_query = clone $temp_query; ?> </code> Here's the link in the codex that the clone $wp_query technique comes from: http://codex.wordpress.org/The_Loop#Multiple_Loops_Example_2
|
Why doesn't my page know it's a page (won't return true for is_page())?
|
wordpress
|
I'm pretty much a WP newbie, and I've noticed that in a lot of themes, there is the exact same code for displaying posts in three different places (single.php, archive.php, index.php etc) This just bugs me. It doesn't seem right to me, a programmer always trying to code as efficiently as possible. What is the best way to generalize the layout for posts, preferably as a WordPress integrated/native function?
|
you could move the loop content into its own file and share that between the different template files using get_template_part()
|
Isn't the way posts are displayed very unefficient?
|
wordpress
|
From an SEO perspective, i'm trying to add conditional title tags to my WP theme such that it echos a piece of text based on various categories. Assuming that my category id's are 1, 2, 3, 4 Then i'd like to add Title 1 if category id = 1, title 2 if category id = 2 and so on. Could someone assist in the correct php syntax to implement this. Thanks.
|
See codex page for category conditional tags - http://codex.wordpress.org/Conditional_Tags#A_Category_Page You can use them like so: <code> <title> <?php if ( is_category( '1' ) ) echo 'This is the news category'; ?> </title> </code>
|
Help with adding conditional title tags to header.php
|
wordpress
|
I checked this post here stackexchange-url ("Making a plugin file accessible via url rewrite?") which seems to have the same problem as me but its for a plugin. But so far i am getting 404. <code> add_action( 'init', 'my_rewrite' ); function my_rewrite() { global $wp_rewrite; add_rewrite_rule('/$', '/wp-content/themes/econ/adserver/adserver.js.php', 'top'); $wp_rewrite->flush_rules(true); } </code> I have this file path <code> /wp-content/themes/econ/adserver/adserver.js.php </code> and need to show it as <code> http://mysite.com/adserver.js.php </code> UPDATE: The code that Bainternet gave is working good except the rewrite rule part. I can now access the file using <code> index.php?myjs=true </code> . Here is the code in my htaccess file you might wanna take a look. <code> # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress </code>
|
Ok here is a test working solution: <code> <?php /* Plugin Name: wpse26719 Plugin URI: http://en.bainternet.info Description: Need to make a php file inside theme accessible via url Version: 1.0 Author: Bainternet Author URI: http://en.bainternet.info */ // Register a URL that will set this variable to true add_action('generate_rewrite_rules', 'wpse26719_rw'); function wpse26719_rw($wp_rewrite) { $newrules = array(); $new_rules['^adserver.js.php$'] = 'index.php?myjs=true'; $wp_rewrite->rules = $new_rules + $wp_rewrite->rules; } // Add myjs as a query var add_action( 'query_vars', 'wpse26719_query_vars' ); function wpse26719_query_vars( $query_vars ) { $query_vars[] = 'myjs'; return $query_vars; } // If this is done, we can access it later // This example checks very early in the process: // if the variable is set, we include our page and stop execution after it add_action( 'parse_request', 'wpse26719_parse_request' ); function wpse26719_parse_request( &$wp ) { if ( array_key_exists( 'myjs', $wp->query_vars ) ) { include( dirname( __FILE__ ) . '/adserver.js.php' ); exit(); } } </code>
|
Need to make a php file inside theme accessible via url
|
wordpress
|
In the book Beginning WordPress 3 the author advises that changing the default WP table prefixes can provide some slight security advantage (protects from SQL injection scripts). I found several articles that explain how to do this as well. I've also seen people arguing that it's not all that helpful. I thought I would try it on the theory that if it was reasonably doable and even slightly helpful, why not do it? So, for a new project I did a Fantastico Installation, which meant that I had to go into the actual Tables via PHPmyAdmin, which I did. I changed the 11 standard table names, plus a couple of things in wp_options and in wp_usermeta, and finally the table prefix in the wp-config.php. When done I was able to login to the admin and all seems well. My question is: can I now go forward and not worry about needing to change anything when I activate new plugins? Is this something that, once done properly, is done? That seems to be the implication but no one explicitly states this, either in the book, or in the articles I've read. Here's links to 2 articles, for FYI: http://digwp.com/2010/10/change-database-prefix/ http://tdot-blog.com/wordpress/6-simple-steps-to-change-your-table-prefix-in-wordpress Thanks!
|
I do this on every WP site I set up, and while it's no panacea for SQL issues moving forward as it's more obscurity than security, it does make me feel all warm and fuzzy inside. :) I have never had issues with it since I started the practice two years ago. A key to the process is pointed out in both articles you've linked to, changing the <code> $table_prefix </code> value in wp-config.php. If you do this, and if the plugins you are using are properly written, then they will honor that and you should not see any issues. I would feel confident about this change you've made.
|
Changing Table Prefixes - once done, am I good to go going forward?
|
wordpress
|
My server was hacked this weekend. By the Russians! Of the 50+ domains on my server, every single one had a hacked .htaccess file which was redirecting search results and a few other things to a russian site. I'm assuming that one of the many, many wordpress installs has a plugin with a security flaw. Two questions: Is it possible for a security hole in one plugin to allow someone access to other sites on the same server? What would a security flaw look like that might give someone access to the .htaccess file a directory or two above? It's possible that the issue was someone else, that Dreamhost (my host) has bigger issues. But, I'm exploring the option that it's my fault. Thoughts?
|
Personal Opinion: I had the same thing with (mt) mediatemple twice last year. They told me/us that it was a wordpress issue, but it wasn't. I heard the same from dreamhost last year. So: don't think about it too much, just remove the hack and blame your host (again). Anyway: You could stackexchange-url ("read this thread"). If your DB got "infected": There's also a link to the plugin I wrote to remove the inserted links from my database. Give it a try.
|
What does a security risk in a plugin look like?
|
wordpress
|
I know there are a few plugins (Custom Fields Template seems to be the most popular one) that lets me insert custom fields into the new-post.php template. But I'm wondering if I can add in a few fields without using a plugin -- just as a mock-up. Do I have to go into the core?
|
This article will get you there: http://andrewferguson.net/2008/09/26/using-add_meta_box/
|
Inserting custom fields into new-post.php without using the Custom Fields Template plugin?
|
wordpress
|
I have a wordpress network site. I have many sites in my network. Lets say i have two subsites like wordpress.mysite.com,joomla.mysite.com. If the user post wordpress related topic in joomla site then i would like to migrate it from joomla to wordpress. Just like stackoverflow. Is there any good multisite plugin available for this feature?. Thanks
|
I couldn't find best solution for this question. If anyone have this question as mine then you may check this plugin. This is not the best one. But just a recommendation. http://wordpress.org/extend/plugins/multipost-mu/ It actually duplicate the post. Thanks
|
Post migration from one site to another site in a network
|
wordpress
|
I'm trying to style a custom menu here so that I can let other people manage this site alongside myself. What I'm trying to do is remove the text for the top level links while leaving the <code> a </code> as a block so the links are clickable, however when I try and remove the text using <code> text-indent: -999em; </code> (which I know isn't the neatest way of doing it) it recurses down the menu and hides all the the other links. Can anyone suggest any neat ways of hiding the text?
|
I think you can use the text-indent for this level, but you must set the text-indent for all a -tags of the class sub-menu also set to 0, not -999px. Example: <code> #menu-main-navigation .link-experience a { display: block; height: 63px; width: 167px; text-indent: -999px; } .sub-menu a { text-indent: 0px !important; } </code>
|
Custom menu styling
|
wordpress
|
I have the following menu in my header: <code> <?php $args = array( 'menu' => 'Main Menu', 'container' => false, 'depth' => 1, 'items_wrap' => '%3$s', 'walker' => new Bar_List_Walker_Nav_Menu ); wp_nav_menu($args); ?> </code> and I want to make the output look like this: <code> link1 | link2 | link3 | link4 | link5 </code> So I set out to make a walker function here is where I got to: <code> class Bar_List_Walker_Nav_Menu extends Walker_Nav_Menu { public $count; function start_lvl(&$output, $depth) {} function end_lvl(&$output, $depth) {} function start_el(&$output, $item, $depth, $args) { $attributes = ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $item_output .= '<a'. $attributes .'>'; $item_output .= apply_filters( 'the_title', $item->title, $item->ID ); $item_output .= '</a>'; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } function end_el(&$output, $item, $depth) { static $count; $count++; if(!$this->count >= $count) { $output .= " | "; } } function walk( $elements, $max_depth ) { $this->count = count($elements); parent::walk( $elements, $max_depth ); } } </code> This outputs the following error: <code> Warning: Missing argument 4 for Bar_List_Walker_Nav_Menu::start_el() in C:\xampp\DEV\Stace\trunk\wp-content\themes\philosophy\functions.php on line 100 </code> If I remove the function <code> walk() </code> from my walker class it works fine except the count is no longer grabbed and as a result one <code> | </code> too many is added to the end of my navigation. Can anyone work the code to get to my desired output?
|
You can use the menu order inside the item to see if it's not first. If it isn't have it draw the character before the anchor. <code> class Bar_List_Walker_Nav_Menu extends Walker_Nav_Menu { private $separator = " | "; function start_el(&$output, $item, $depth, $args) { if($item->menu_order > 1){ $output .= $this->separator; } $attributes = ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $output .= '<a'. $attributes .'>'; $output .= apply_filters( 'the_title', $item->title, $item->ID ); $output .= '</a>'; } } </code>
|
Bar separated navigation by extending Walker_Nav_Menu
|
wordpress
|
I have the following code <code> $genres= array('action', 'comedy', 'horror'); foreach($genres as $genre){ $ret = wp_set_object_terms( $postId, $genre, 'genres'); } </code> But this code associates only horror as the genre. When I checked the DB too, I don't have a record for action and comedy. How do I associate all the three with my genre? Thanks in advance.
|
You can pass an array of terms to <code> wp_set_object_terms </code> , there is no need for the for each: <code> $genres= array('action', 'comedy', 'horror'); $ret = wp_set_object_terms( $postId, $genres, 'genres'); </code>
|
wp_set_object_terms not working inside loop
|
wordpress
|
need to customise a plugin function but would rather not edit the plugin itself so updates wont remove the custom changes. function iss in a class called UserAccessManager and the function is; <code> public function showGroupMembership($link, $postId) { $uamAccessHandler = &$this->getAccessHandler(); $groups = $uamAccessHandler->getUserGroupsForObject('post', $postId); if (count($groups) > 0) { $link .= ' | '.TXT_UAM_ASSIGNED_GROUPS.': '; foreach ($groups as $group) { $link .= $group->getGroupName().', '; } $link = rtrim($link, ', '); } return $link; } </code> is this possible? OR can i affect it with a filter? Any help appreciated! Dc.
|
I'm afraid you cannot alter the output of this function unless you directly modify the plugin code. The plugin author hasn't given you any filter to use. So what can you do about it? Continue to alter the plugin file and update each time the plugin updates. Ask the plugin author nicely to add a filter to this function. Make a fork of the plugin.
|
overwrite a plugin function in functions.php
|
wordpress
|
I am using timthumb as the image size management script throughout my wordpress site but I just noticed that an empty image tag shows up even when there is no thumbnail. <code> <?php if(has_post_thumbnail()): $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full'); ?> <div class="wp-caption alignright"> <img src="<?php bloginfo('template_url'); ?>/scripts/timthumb.php?src=<?php echo $src[0]; ?>&w=145&h=80&q=100&zc=1" height="80" width="145" alt="<?php the_title(); ?>" class="wp-post-image" /> <p class="wp-caption-text"><?php the_post_thumbnail_caption(); ?></p> </div> <?php endif; ?> </code> I am doing it this way because I wanna show the caption whenever it exists. I also tried doing it all in php. I never do it like this, so I'm not sure if it's correct but It also shows the same thing and also echos the template_url before the image. <code> <?php if(has_post_thumbnail()){ $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full'); echo '<div class="wp-caption alignright"> <img src="'. bloginfo('template_url') .'/scripts/timthumb.php?src='. $src[0] .'&w=145&h=80&q=100&zc=1" height="80" width="145" alt="'. the_title() .'" class="wp-post-image" /> <p class="wp-caption-text">'. the_post_thumbnail_caption() .'</p> </div>'; } ?> </code> Am I doing something wrong here. That img tag is inside the condition right? Still a broken image place holder is showing up with every post. Image below Can anyone tell me what's wrong with the code. Thanks! I appreciate all the help.
|
As commented above, you don't have to use TimThumb at all to get additional image sizes for your uploaded images. WordPress ships with the <code> add_image_size() </code> function. <code> // functions.php add_action('init', 'wpse26655_add_additional_image_sizes'); function wpse26655_add_additional_image_sizes() { add_image_size('thumb200x120', 200, 120, true); } </code> In your template files, you could than query your thumbnail with your desired image size. E.g. <code> <?php // single.php / loop-content.php $thumbId = get_post_thumbnail_id(); if($thumbId) : $thumbSrc = wp_get_attachment_image_src($thumbId , 'thumb200x120'); $thumbUrl = $thumbSrc[0]; $thumbWidth = $thumbSrc[1]; $thumbHeight = $thumbSrc[2]; ?> <div class="post-thumbnail"> <img src="<?php echo $thumbUrl; ?>" width="<?php echo $thumbWidth; ?>" height="<?php echo $thumbHeight; ?>" /> </div> <?php endif; ?> </code> Note: The additional images sizes are generated on image upload. If you want new sizes for existing images inside your medialibray, you have to recreate all thumbnail images. A very good plugin for this purpose is Regenerate Thumbnails .
|
Show post thumbnail only if it exists using timthumb
|
wordpress
|
I'm a bit confused as to why this isn't working - although it must be said I'm not that sure what <code> apply_filters() </code> and <code> add_filter </code> are doing, so any general tips would be great too! I want a query that brings up the five earlier posts on a single post page. I am sending the current post's date off, and want to apply a filter that filters out posts earlier than this. <code> function sw_filter_posts_before( $where = '', $date) { $where .= " AND post_date < '" . $date . "'"; return $where; } </code> How do I correctly apply this? Simply using add_filter or apply_filter before instantiating a new WP_Query object doesn't seem to work correctly. Thanks in advance! Edit: To go into things further, I would like to understand how to pass a variable into the filter, as I can't get $date to pass from another function. Here is said other function (it is an ajax call within wordpress, hence I start by getting the post ID for the current page through a $_POST variable): <code> function create_more_videos_sidebar() { $id = $_POST['theID']; $args = array( 'post_type' => 'videos', 'posts_per_page' => 1, 'p' => $id ); $wp_query = new WP_Query($args); while ($wp_query->have_posts()) : $wp_query->the_post(); $do_not_duplicate = $post->ID; $date = get_the_date('Y-m-d'); endwhile; $args = array( 'post_type' => 'videos', 'posts_per_page' => 5 ); add_filter( 'posts_where', 'sw_filter_videos_before' ); //don't know how to pass $date $wp_query = new WP_Query($args); remove_filter( 'posts_where', 'sw_filter_videos_before' ); //do loop stuff $response = json_encode( array( 'result' => $result ) ); header( "Content-Type: application/json" ); echo $response; exit; } </code>
|
What are you attempting to filter? I'll assume you're trying to add a filter to a filter hook called <code> posts_before </code> . In which case, you need to add your filter to this hook, via <code> add_filter() </code> : <code> function mytheme_filter_posts_before( $where = '', $date) { $where .= " AND post_date < '" . $date . "'"; return $where; } // Add function to the filter hook add_filter( 'posts_before', 'mytheme_filter_posts_before' ); </code> Note that I changed your function name. <code> filter_posts_before() </code> is far too generic of a function name, and very likely to cause a function-naming collision. EDIT And just to clarify: <code> apply_filters() </code> is the filter hook location , is called by core code , and is used to apply any filters that are added to the queue by Themes/Plugins (and core). <code> add_filter() </code> is called by Themes/Plugins (and core), and is used to add filters to the queue to be applied to the hook by core. EDIT 2 Based on your comment above, the hook is <code> posts_where </code> . So, let's take a crack at re-building your callback function: <code> function mytheme_filter_posts_where( $where ) { // Here, we need to figure out how to // determine what date to use. In your // code example, you call get_the_date(), // but this function must be used inside // the Loop. Let's try get_the_time() // instead. You'll just need to come up // with a way to determine what post ID to use. $post = 'some_post_id'; $date = get_the_time( 'Y-m-d', $post ); $where .= " AND post_date < '" . $date . "'"; return $where; } // Add function to the filter hook add_filter( 'posts_where', 'mytheme_filter_posts_where' ); </code>
|
What do add_filters() and apply_filter() do?
|
wordpress
|
After long time am here,I have one question. I Installed my wordpress in localhost and i moved to live,while i forgot the admin password,so i reset it by phpmyadmin(using md5).now i try to login by using with correct password it's redirect to This page and shows You do not have sufficient permissions to access this page. please anyone help me to solve this problem.
|
Occasionally I've seen issues doing a manual reset of the password if salts have changed, or if there was an issue with the account before the reset. Some things to try: Are you sure you reset the password for the main admin account, usually ID #1? Trivial, I know, but has happened to me in the past. Try using the Emergency Password Reset Script , as it works a little better than a manual reset. Try changing the salts in wp-config.php and reset the password again, see if it clears out some cookie issues you may be having. Most likely your problem can be traced to cookie issues if it is accepting the password but not letting you in. Clear all your cookies out as well.
|
You do not have sufficient permissions to access this page
|
wordpress
|
I have some data that I'm pulling from an XML source and would like to display it in Wordpress. One solution would be to take the static markup that my theme generates and spaghetti-code my page with some PHP that grabs the data from the XML and prints it in the page. Easy enough, but now every time I make a change to the theme I have to re-apply it to this page. Is there a more elegant solution that would allow me to inherit the whole site look n' feel and just append my data to it? Thanks
|
I would make a plugin out of the code that you are using to pull the XML. I've done this before for a client that was using a calendaring system that was a set of PHP files. I wrapped the calls to the calendar files in a plugin, and just called what I needed to from there. This preserved the look and feel of the site without extra work there, and used WordPress's native capabilities. It's fairly easy to take an existing set of code and wrap it as a plugin, and then you can use the methods of that plugin in your theme files. You could for example make a page to house the data, make a page-specific theme file that outputs (or not) the content of that page, and also use the theme file to run the methods for pulling in the XML data via your plugin. Resources for writing (or wrapping code into) a plugin: http://codex.wordpress.org/Writing_a_Plugin http://www.slideshare.net/ColinLoretz/creating-your-first-wordpress-plugin http://wpcandy.com/teaches/how-to-create-a-functionality-plugin http://wordpress.tv/2010/04/24/john-hawkins-plugin-development-oc10/
|
Dynamic page outside Wordpress
|
wordpress
|
Is there some guideline or rationale behind why some WP code functions are prefixed with <code> wp_ </code> ? eg: <code> wp_insert_post() </code> vs. <code> update_post_meta() </code>
|
This makes not that impressive answer, but - none . <code> get_ </code> is suffix usually means function returns something, <code> the_ </code> that function echoes something. <code> wp_ </code> doesn't carry technical meaning and inconsistency in naming is from many developers participating and lack of movement to unify (moving forward is considered more important than major cleanups of older stuff to make it neat).
|
Why do some core functions get wp_ while others do not? What's the rule?
|
wordpress
|
I have a query in a custom widget (my first one!) which, if it's of custom post type <code> book </code> , retrieves the post ID. This then gets used in a WP_QUERY to retrieve data about the page. This works perfectly when in the static sidebar.php, but not in either a dynamic PHP Widget or as a custom widget in functions.php. In those, it retrieves the relevant field from all examples of post type <code> book </code> . Here's the offending code. <code> <?php if('book' == get_post_type()) : $ww_book_id = $post->ID; else : $ww_book_id = $default_book; //this is pulled in from the widget admin options form and works perfectly. endif; $testimonial_args = array( 'post_type' => 'book', 'p' => $ww_book_id ); $main_testimonials = new WP_Query($testimonial_args); if($main_testimonials->have_posts()) : while($main_testimonials->have_posts()): $main_testimonials->the_post(); echo the_title(); //I actually do much more stuff than this, but it works for testing purposes. endwhile; wp_reset_postdata(); endif; ?> </code> Many thanks!
|
Solved it! I replaced <code> $ww_book_id = $post->ID; </code> with <code> $ww_book_id = get_the_ID(); </code> I'm not sure why <code> $post->ID; </code> was referencing all the posts in the widgetized version of this code. If anyone can tell me, I'd be very curious.
|
Code in custom widget queries all posts, when it should only query the current post
|
wordpress
|
I'm currently designing a site for a client and I don't want anyone to be able to navigate to the homepage and see it. So currently the site is located in a subfolder of the main domain. Like so: http://gointrigue.com/beta/ What steps do I need to take to move the site to simply http://gointrigue.com/ when we are ready to launch it? Or, is there a way to move it there right now, while I'm still developing it, and simply hide the homepage from the outside world while I can still see it? The only reason I decided to develop it in a subfolder like /beta/ was because I didn't know how to stop other people from seeing the homepage while still allowing myself to see it. What's the easiest, simplest answer here? Your help is greatly appreciated!
|
See Moving WordPress ยซ WordPress Codex , or, keep all WP files (except index.php) in /beta/ and see Giving WordPress Its Own Directory ยซ WordPress Codex. Use WordPress โบ Absolute Privacy ยซ WordPress Plugins to make WP private until launch.
|
Best way to transfer Wordpress install to root of directory when I'm ready to launch?
|
wordpress
|
I've got this category setup that includes several posts. By design it's not a blog, but a staff listing. Currently all of the staff members have their own posts with the category. I'd like to be able to sort the order they are displayed in in their parent category. How do I go about doing this in the most user friendly manner? My client may want to change this sorting order in the future, especially when staff members leave or new ones get hired. Any and all help will be greatly appreciated. http://gointrigue.com/beta/faculty/ To expand on this: In the link I've provided you'll be taken to a category page I made called /faculty/. In this category page I have several posts listed. Wordpress automatically lists them in the order they were created. With the most recently created post being listed first. I want to list them in my own custom order. How do I do this?
|
Now that I have a better understanding of the issue, I would recommend using custom fields to sort your posts. You can have a custom field (e.g., "order") and use it to indicate the order of your posts. You then need to use a custom query to order these posts when they are displayed. You can use a custom query like the following: <code> $args = array( 'meta_key' => 'order', 'orderby' => 'meta_value', 'order' => 'ASC' ); $custom_query = new WP_Query(); $custom_query->query($args); if($custom_query->have_posts()) { while($custom_query->have_posts()) { $custom_query->the_post(); // Do the loop stuff } } </code> Please see the WP_Query class page for more information about all of the arguments that you can use to create custom queries.
|
Setting Custom Sort Order of Posts within a Category
|
wordpress
|
In any SE site, there are suggestions that pop out when you are writing in the Tag field. Is there any way of doing something similar in Wordpress? (a simple vertical list is enough). (Maybe helped with jQuery).
|
It should do this by default if there are tags to suggest, but I think there's a little bit of a delay before the suggestions show. You can also choose from your most used tags, which some might find easier to use.
|
Is there any way of making post tags (or custom post type tags) pop up as suggestion as in StackExchange sites?
|
wordpress
|
I'm about to create my own options pages for my WordPress theme and I'm a bit confused. I've seen a lot of themes that used arrays to generate options pages, it looked like this: <code> $options = array ( array( "name" => "Welcome Message", "type" => "title"), array( "type" => "open"), array( "name" => "Title", "desc" => "Enter a title to display for your welcome message.", "id" => $shortname."_welcome_title", "std" => "", "type" => "text"), ); </code> Plus a few other functions that generated front-end, tables, forms etc. On the other hand, there are "static" options pages from Codex ( http://codex.wordpress.org/Creating_Options_Pages ). They look like: <code> <form method="post" action="options.php"> <?php settings_fields( 'baw-settings-group' ); ?> <?php do_settings( 'baw-settings-group' ); ?> <table class="form-table"> <tr valign="top"> <th scope="row">New Option Name</th> <td><input type="text" name="new_option_name" value="<?php echo get_option('new_option_name'); ?>" /></td> </tr> <tr valign="top"> <th scope="row">Some Other Option</th> <td><input type="text" name="some_other_option" value="<?php echo get_option('some_other_option'); ?>" /></td> </tr> <tr valign="top"> <th scope="row">Options, Etc.</th> <td><input type="text" name="option_etc" value="<?php echo get_option('option_etc'); ?>" /></td> </tr> </table> <p class="submit"> <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" /> </p> </form> </code> What are pros & cons of these approaches and which one should I use/is preffered?
|
I would strongly recommend following the Theme Review guidelines for Theme Settings and Data Security . (If you intend for your Theme to be hosted in the WPORG repository, you will be required to follow these guidelines. Here's a brief summary: Themes are required to prefix all options, custom functions, custom variables, and custom constants with theme-slug (or appropriate variant). Theme are required to implement Theme Options and Theme Settings pages deliberately, rather than relying on copy-and-paste scripts from website tutorials. Themes are required to use the add_theme_page() function to add the Theme Settings Page to the Appearance menu, rather than using add_menu_page() to add a top-level menu. Themes are required to use the edit_theme_options capability for add_theme_page(), rather than rely on a role (e.g. "administrator"), or a different capability (e.g. "edit_themes", "manage_options") for the capability to add the settings page. Themes are required to save options in a single array, rather than create multiple options for its settings page. Use of set_theme_mod and get_theme_mod handles this for you, as does using the Settings API. For checkboxes and select options, Themes are required to use the checked() and selected() functions for outputting checked="checked" and selected="selected", respectively. Themes are required to validate and sanitize all untrusted data before entering data into the database, and to escape all untrusted data before being output in the Settings form fields or in the Theme template files (see: Data Validation) Themes are required to use esc_attr() for text inputs and esc_html() (or esc_textarea() in WP 3.1) for textareas. Themes are required to provide explicit Settings-page nonce checking, if not using the Settings API (see: WordPress Nonces) Themes are recommended to use the Settings API to get and save form input data rather than rely on $_POST and $_REQUEST data directly. References Incorporating the Settings API in WordPress Themes (yours truly) WordPress Settings API Tutorial (Otto) A Sample WordPress Theme Options Page (Ian Stewart) EDIT So, to clarify: you don't have to choose either/or here. The Settings API can handle both approaches simultaneously - and in fact, does so quite elegantly. The <code> add_settings_field() </code> call can be generated dynamically, and can use a single callback, with a switch to output field-type-specific form field markup. Here's how I implement it .
|
Two Ways Of Creating Wordpress Options Pages
|
wordpress
|
By default WordPress prints http:// in front of URLS users add in their profile, which are called using the following code: <code> <?php the_author_meta('user_url'); ?> </code> Could somebody provide me the code to strip these URLS of "HTTP://" by default? (While still working as a link and not touching WP's backend... I assume this could be a function?)
|
Assuming that the author's id is <code> $author_id </code> , the following code should work. You can of course use this to create your own function. <code> <?php $url = get_the_author_meta('user_url', $author_id); ?> <a href="<?php echo $url; ?>"><?php echo str_replace('http://', '', $url);?></a> </code>
|
Removing "HTTP://" From the_author_meta?
|
wordpress
|
I notice that many Wordpress tips websites recommend using wp totalchache and similar plugins. I tried it on one site that gets a relatively small amount of traffic, and hardly notice a difference in load time. Is it smart to set up as a general rule, or does it it really depend on the site traffic? Same question for Content delivery Network.
|
Static page cache is trade-off of resources for speed. The larger and more complex site is, the more resources it takes to cache it. Since there is no such thing as unwanted speed , static cache of small sized site is one of the best performance improvements possible. Especially on shared hosting where other tweaking options are very limited. CDN for serving media images is a little more complex: It makes static resources load faster, by bringing them closer to the visitors. It relieves main server from serving static resources, freeing it up for pages and specialized tweaking. However on shared hosting you don't care much about offloading tasks. You are already sharing resources with multiple sites and less serving media won't make a difference for server overall. Neither you can tweak server stack. Small sites also unlikely to serve enough content to make CDN more cost-efficient than serving from hosting. Overall my perspective is that for small site: static page cache is no-brainer ; CDN for static is resources is extra luxury .
|
Does a low traffic Wordpress site need a caching plugin and a CDN
|
wordpress
|
I'm forced to use manual excerpts on a number of my posts to integrate them with a shortcode plugin. However, this is interfering with how they're being displayed on an archive page (using a page template). Is there a way to force WordPress to display an automated excerpt (ie, the first 80 words) on one page template only?
|
You can utilize the <code> wp_trim_excerpt </code> filter. In your callback function that filters the the excerpt text, you can test for the presence of a certain template; then, if that template is being used, you can go ahead and alter the excerpt in any way that you see fit. In order to determine which template is being used, see this clever solution: stackexchange-url ("get name of the current template file"). Let me know if this helps or if you need more.
|
Force WordPress to NOT display the manual excerpt
|
wordpress
|
I'm working with custom post types to create a custom "product review" type. I'm customizing the UI to have fields for the "Reviewer", "Product", and their "Review". This doesn't really require a post title though, so I've removed that field. This is all working fine, but when I go to look at all Product Reveiws, the titles are completely unhelpful (Auto Draft, Auto Draft 2, etc.). What I want to do is automatically set the post title to be a combination of the Reviewer's name and the product they reviewed; something along the lines of "John Smith, Car Radio". I have a function that hooks into the save_post action, and updates the custom meta fields I have set. I figure I need to add something here to accomplish what I'm trying to do, but I'm not sure what function or process this requires. Thanks in advance!
|
Jeremy, Excellent work not just leaving it at "Auto Draft". It's tricky when these types of CPTs don't have titles. Here is some code I've used to accomplish a similar task. You'll need to adjust this for your situation, but it shows you a way to get this done. In particular, you can use the <code> wp_insert_post_data </code> filter to change the title before you add it to the database. Now, one of the biggest mistakes you can make here is filtering ALL post titles. If you are not careful to test for the right context (e.g., when you are saving and/or editing your "product review" CPT, you will find that ALL titles in your site get mangled. My recommendation is to make use of nonce fields in your meta boxes to detect when the right form is submitted. Here's my code: <code> add_filter('wp_insert_post_data', 'change_title', 99, 2); function change_title($data, $postarr) { // If it is our form has not been submitted, so we dont want to do anything if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return; // Verify this came from the our screen and with proper authorization because save_post can be triggered at other times if(!isset($_POST['my_nonce_field'])) return; // If nonce is set, verify it if(isset($_POST['my_nonce_field']) && !wp_verify_nonce($_POST['my_nonce_field'], plugins_url(__FILE__))) return; // Get the associated term name foreach($_POST['tax_input']['complaint-type'] as $term) {$term_id = $term;} // Get name of term $term = get_term_by('id', $term_id, 'complaint-type'); // Combine address with term $title = $_POST['address']['address1'].' ('.$term->name.')'; $data['post_title'] = $title; return $data; } </code> Don't get caught up in my manipulations of the title. Just realize that you need to set <code> $data['post_title'] </code> and return <code> $data </code> .
|
Automatically generate custom post title based on meta
|
wordpress
|
Is there a plugin to notify commenters of one post to receive emails about new comments made on that post? Only commenters who entered emails will be notified.
|
check this plugin out: http://wordpress.org/extend/plugins/subscribe-to-comments/
|
Notify commenters about new replies
|
wordpress
|
If anybody knows where to find a most popular tags hack, I would be forever grateful. I've searched and searched to no avail.
|
check this plugin: http://wordpress.org/extend/plugins/most-popular-tags/ And/ or see this codex: http://codex.wordpress.org/Template_Tags/wp_tag_cloud
|
Can't Find a "Most Popular Tags" Hack Anywhere
|
wordpress
|
I'm currently building a simple intranet powered by wordpress. I need to show the stats (most read articles, user logins, etc..) to the administrator, but I can't use google analytics as the install is on a VPN without internet access. Do you know any reliable plugin to record and show stats on a local install of wordpress?
|
I would recommend installing Piwik on your intranet using one of their plugins, though it will work just fine as a stand alone. http://piwik.org/ http://piwik.org/blog/2008/06/new-plugin-wordpress-piwik-integration/
|
Stats for a wp powered intranet
|
wordpress
|
http://i.stack.imgur.com/Yr35p.jpg As you can see in the picture above. I got two links for each page. I'm using <code> <div class="pagelink"><?php wp_link_pages('pagelink=Source %'); ?></div> </code> for the top one and the bottom one is automatically appearing because of <code> <!--nextpage--> </code> So how do I remove the links in the bottom. If I remove <code> <!--nextpage--> </code> the top one will dissapear as well. Thanks. Edit: My single.php <code> <?php get_header(); ?> <div id="content_box"> <div id="left_box"> <div id="content"> <div id="content_inner"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h1><?php the_title(); ?></h1> <p class="post_author"><em>by</em> <?php the_author(); ?></p> <div class="pagelink"><?php wp_link_pages('pagelink=Source %'); ?></div> <div class="format_text"> <?php the_content('<p>Read the rest of this entry &raquo;</p>'); ?> <?php link_pages('<p><strong>Pages:</strong> ', '</p>', 'number'); ?> </div> </div> <?php comments_template(); ?> <?php endwhile; else: ?> <h1>Uh oh.</h1> <div class="format_text"> <p>Sorry, no posts matched your criteria. Wanna search instead?</p> <?php include (TEMPLATEPATH . '/searchform.php'); ?> </div> </div> <?php endif; ?> </div> <?php include (TEMPLATEPATH . '/left_bar.php')?> </div> <?php get_sidebar(); ?> </div> <?php get_footer(); ?> </code> My theme is: Neoclassical
|
Your theme is using old and deprecated function <code> link_pages </code> to display page-links for paginated posts. Just replace this chunk of code: <code> <div class="pagelink"><?php wp_link_pages('pagelink=Source %'); ?></div> <div class="format_text"> <?php the_content('<p>Read the rest of this entry &raquo;</p>'); ?> <?php link_pages('<p><strong>Pages:</strong> ', '</p>', 'number'); ?> </div> </code> with this: <code> <div class="format_text"> <?php the_content('<p>Read the rest of this entry &raquo;</p>'); ?> <?php wp_link_pages( array( 'before' => '<div class="page-link">Pages:', 'after' => '</div>', 'pagelink' => 'Source %' ) ); ?> </div> </code>
|
Getting two wp_link_pages output
|
wordpress
|
I'm using the bbpress plugin. It has a custom post type called forums . I used to sort posts by changing its publishing date. But you can't do that with this custom post type. Any suggestions?
|
i used this code to create custom post template for specific post type <code> define(SINGLE_PATH, TEMPLATEPATH.'/single'); function product_single_page_template($product) { global $wp_query, $post; $type = get_post_type(); if ($type==true) if(file_exists(SINGLE_PATH . '-type-' . $type . '.php')) return SINGLE_PATH . '-type-' . $type . '.php'; return $product; } add_filter('single_template', 'product_single_page_template'); </code> you can do the same with categories or for non single pages just as well. hope this helps a
|
What's an easy way of sorting custom post types manually?
|
wordpress
|
I'm trying to make a layered wordpress menu, out of categories. Here's how it's going to look: I have no clue how to develop this, can't do it with <code> get_posts </code> (not sortable by parent/children), or <code> wp_list_categories </code> (can't pull thumbnails). Also, I have to assign thumbnails to categories somehow. Is there an easy way to implement something like this with wordpress?
|
although @roikles offers a way to do it, I don't think it is very flexible as you will have to go back in the code when you want to add a new category. Another way of doing it can be to add the image of the subcategory as the description of the subcategory. To be able to do so, you will first need to allow XHTML in category descriptions. Add this line to your <code> functions.php </code> : <code> remove_filter( 'pre_term_description', 'wp_filter_kses' ); </code> Then you can echo that description with <code> wp_list_categories </code>
|
Implementing a tricky wordpress menu (nested categories + thumbnails)
|
wordpress
|
I have a multiple-site WordPress install. I have decided to centralize as many of my libraries as possible into one spot, for obvious organizational reasons, and in order to reduce bloating. Many of those libraries can be used both in plugins and themes. My first idea is to create a ' myLibs ' (or other name) directory inside wp-content where I would save all those libraries. Anybody has a better idea? Would there be any reasons NOT to do this?
|
I would recommend creating a plugin that holds all of your libraries. In the main plugin file, set a constant that defines the path to the plugin folder so you can easily include the files with your other plugins/themes.
|
Where to save common libraries?
|
wordpress
|
Are there any WordPress specific Javascript functions that could be used as helpers when writing custom code? I am thinking specifically of one that would pull back the base URL of your install, but any helper functions built into WordPress would be nice to know.
|
WordPress installs with a number of libraries/classes/plugins/etc that you can enqueue and use. For base url specifically, or any vars in general you need to access from javascript, use the api php functions, then pass it to your javascript via wp_localize_script .
|
Javascript Helpers
|
wordpress
|
I'd like to be able to enter a post ID into the search box in order for the exact post to be returned in the search results. I'd also like to retain the ability to search the posts/page titles and content. eg, user enters '#123' in the search box, and the search results return just post 123. However, if I were to enter '123' into the search box, it would return any post/page that contains '123' in the content or title. stackexchange-url ("This article") explains how to achieve what i'm after within the Admin - I just need the equivalent for the front-end! Any help is greatly appreciated, thank you.
|
I previously asked and answered my own question about customizing a search. You can find that answer here: stackexchange-url ("The right way to create a custom search page for complex custom post types"). It'll be a good read to help you understand the following code. I'll use the <code> pre_get_posts </code> action to change your search when you are searching for a positive integer. Note that the code I'm providing will not allow you to search for positive integers within your article. <code> function my_search_pre_get_posts($query) { // Verify that we are on the search page that that this came from the event search form if($query->query_vars['s'] != '' && is_search()) { // If "s" is a positive integer, assume post id search and change the search variables if(absint($query->query_vars['s'])) { // Set the post id value $query->set('p', $query->query_vars['s']); // Reset the search value $query->set('s', ''); } } } // Filter the search page add_filter('pre_get_posts', 'my_search_pre_get_posts'); </code> If you want to be able to search for ID and a search string, I would recommend including multiple inputs. You can also use other logic within the function provided to make assumptions about what the user is looking for and alter the query variables accordingly. Note that this code is untested.
|
Search Using Post ID
|
wordpress
|
I have a plugin page created with add_submenu_page. I want to add a new section there but nothing happens: <code> add_submenu_page('parent', 'Foo', 'Foo', 'manage_options', 'foo-settings', 'anothercallback'); add_settings_section('foo-settings-section', 'Settings', 'acallback', 'foo-settings'); </code> What's the right call to use it in a custom page? Do you have a complete example? Thanks.
|
The <code> add_settings_section() </code> function simply registers a form section with a certain slug with WordPress. In order to get the section and all the fields you've added to it to display on a certain menu page, you need to include the <code> do_settings_sections($sections-slug) </code> method in the menu's callback. This is, of course, assuming you are using the Settings API, which <code> add_settings_section </code> is part of. Example: <code> function plugin_admin_init() { //All callbacks must be valid names of functions, even if provided functions are blank register_setting( 'option_group', 'option_name', 'sanitize_callback' ); add_settings_section( 'section_id', 'section_title', 'section_callback', 'section_page_type' ); add_settings_field( 'field_id', 'field_title', 'field_callback', 'section_page_type', 'section_id' ); } add_action( 'admin_init', 'plugin_admin_init' ); function add_menus() { add_menu_page( 'menu_page_title', 'menu_title', 'menu_capability', 'menu_slug', 'menu_callback'); add_submenu_page( 'menu_slug', 'submenu_page_title', 'submenu_title', 'submenu_capability', 'submenu_slug', 'submenu_callback' ); } add_action( 'admin_menu', 'add_menus' ); function submenu_callback() { ?> <div class='wrap'> <h2>Settings</h2> <form method='post' action='options.php'> <?php /* 'option_group' must match 'option_group' from register_setting call */ settings_fields( 'option_group' ); do_settings_sections( 'section_page_type' ); ?> <p class='submit'> <input name='submit' type='submit' id='submit' class='button-primary' value='<?php _e("Save Changes") ?>' /> </p> </form> </div> <?php } </code> I did my best to keep all the parameter names unique, so you should be able to pick them apart and trace where they go. The Settings API gets very specific about what needs to go where, so make sure you have that all right. Also, keep in mind that I omitted all the callback functions from this example, but in reality they are necessary.
|
Add section (add_settings_section) to a custom page (add_submenu_page)
|
wordpress
|
I'm trying to create a custom wordpress title for a posts made under a custom post. Basically, its a version changelog for an application. I would like to only input the version number in the title field, and the output has to be standardized with a string accordingly. My custom post type is 'custom_version' and the title output that I'm looking for is "Application has been updated to version ". I've understood that this can be achieved using add_filter and I've tried playing with this code for days now, but I'm not really a PHP Pro so help is much appreciated :) Here's the code: <code> add_filter('the_title', 'new_title'); function new_title($title) { global $post, $post_ID; $title['custom_version'] = 'Application has been updated to v'.$title; return $title; } </code>
|
The issue is that you are mixing up the <code> $title </code> variables. <code> $title </code> is the parameter passed to the <code> new_title </code> function, but then you use it as an array: <code> $title['custom_version'] </code> . Try this: <code> add_filter('the_title', 'new_title', 10, 2); function new_title($title, $id) { if('custom_version' == get_post_type($id)) $title = 'Application has been updated to v'.$title; return $title; } </code> I'd also highly recommend prefixing your function with a unique prefix because you may run into another plugin/theme using a function called <code> new_title </code> , which will reek havoc!
|
Customizing Wordpress the_title with add_filter
|
wordpress
|
I'm trying to count the number of total posts of a custom post type "jobs". My query just returns "0" when I know there are posts. I don't think it is checking that the post type has posts, but I'm clueless as to why... any ideas? <code> <?php $jobs = new WP_Query(array( 'post_type' => 'jobs' ));?> <?php if ($jobs->have_posts()) { $count_posts = wp_count_posts()->publish; if ( $count_posts == "1" ) { echo "<h2>There is currently one vacancy...</h2>"; } else { echo "<h2>There are currently $count_posts vacancies...</h2>"; } } else { ?> <h2>There are currently no vacancies.</h2> <?php } ?> </code>
|
The <code> wp_count_posts </code> function has parameter <code> $type </code> for post type to count, you should use this parameter if you want to get number of jobs like so: <code> $count_posts = wp_count_posts( 'jobs' )->publish; </code>
|
Counting the number of posts (custom post type) Query problems
|
wordpress
|
I'm trying to activate permalinks on my Wordpress installation. When I activate them my menu links point to page names that have changed sometime ago which result in a 404. I don't really understand how I can configure this. When I edit the menu in the menu settings the names are the current ones. I use qtranslate. Can this be the source of the problem?
|
I found it. The box to edit the title had been invisible. I made it visible with the according checkbox in the options bar on the top.
|
Wordpress: Permalinks link to old names
|
wordpress
|
I have created a custom post type named 'projects' with link custom taxonomy named 'projects'. I have added the five different project categories with this project taxonomy with two level of hierarchy custom post type ui . I tried to find function to get these five categories with taxonomy name 'projects' but i did not get the solution. Can anyone help me out how to get the list of these categories created with taxonomy named 'projects'. Any help will be appreciated. Thanks in advance
|
You will want to use <code> get_terms </code> . The following code show you how to access the terms. Please see the Codex page for get_terms for more information about the args that you can send to the function. I also show all of the data that is returned in the array of objects. <code> // Set your args $args = array( 'hide_empty' => 0 // Show terms that are not associated with any posts ); // Get the terms $projects = get_terms('projects', $args); // Loop through and use terms foreach($projects as $project) { echo 'Term ID ' . $project->term_id; echo 'Name: ' . $project->name; echo 'Slug: ' . $project->slug; echo 'Term Group ' . $project->term_group; echo 'Term Taxonomy ID: ' . $project->term_taxonomy_id; echo 'Taxonomy: ' . $project->taxonomy; echo 'Description ' . $project->description; echo 'Parent: ' . $project->parent; echo 'Count: ' . $project->count; } </code>
|
How to list the categories by custom taxonomy created?
|
wordpress
|
I have a page named http://www.mysite.com/whitepapers/ and it worked fine. I have now added a physical "whitepapers" directory and has since broken my permalink for the page. I realize that it has something to do with content negotiation after reading stackexchange-url ("this post") but the fix did not work.
|
For those still looking for an answer, have a look at stackexchange-url ("WP Page and Subdirectory with same name") Basicalli I will have to rename the folder on my server.
|
Page URL not working due to physical directory
|
wordpress
|
I've been stumped for days wondering why when I submit an empty string as a search term, it redirects to part of <code> loop.php </code> where I have the following code inserted: <code> <?php /* If there are no posts to display, such as an empty archive page */ ?> <?php if ( !(have_posts()) && !(is_search()) ) : ?> <h1 class="notfound-header"><?php _e( 'Not Found', 'twentyten' ); ?></h1> <p class="notfound-content"><?php _e( 'Apologies, but no results were found.', 'twentyten' ); ?></p> <?php elseif ( !(have_posts()) && (is_search()) ): ?> <h1 class="notfound-header-search"><?php _e( 'Not Found Search', 'twentyten' ); ?></h1> <p class="notfound-content-search"><?php _e( 'Apologies, but no results were found.', 'twentyten' ); ?></p> <?php get_search_form(); ?> <?php endif; ?> </code> I'm probably not including the <code> is_search() </code> correctly. But I'm working on this site: http://www.cirkut.net/wp/libertyguide and I want to show the search form when nothing is submitted (i.e. just clicking search from the homepage). Any ideas as to what to do? Thanks for any help!
|
I feel bad for answering my own question on here, but here's what I did. I created a custom search template, a custom <code> searchform.php </code> and changed my <code> header.php </code> to reflect my custom search page. What I did is rename the search box names to <code> search </code> instead of <code> s </code> to get around WordPress automatically running <code> search.php </code> and coming up with a 404 error (still not sure why it happened, probably my fault in <code> search.php </code> ) and then used a new WP_Query while setting my arguments. While my solution does not provide anything more than a search term, it could be easily implemented to pull other key-value pairs into the arguments array. searchform.php <code> <div class="search"> <form method="get" class="search-form" id="search-form" action="<?php bloginfo( 'url' ); ?>/search/"> <div> <input class="search-text" type="text" name="search" id="search-text" value="Search this site" /> <input class="search-submit" type="submit" name="submit" id="search-submit" value="Search" /> </div> </form> </div> </code> search-template.php snippet <code> $s = wp_specialchars(stripslashes($_GET["search"]), 1); $search_query = array( 's' => $s ); $search = new WP_Query($search_query); </code> So essentially <code> s </code> is now <code> search </code> to get around WordPress automatically using <code> search.php </code> . If anyone has any questions, feel free to post a comment.
|
Change loop.php for empty search customization
|
wordpress
|
Customer asks if a specific carousel plugin he uses can be widgetized. That means i should create a widget inside functions.php which calls the plugin's function. That means that the plugin's code has to be loaded first so taht the function be available to wordpress when the functions.php file is loaded, right? Would that work?
|
The plugins are loaded right before theme (yes, I've been looking for excuse to use this): However it is wrong to think about either as point of code execution. For most cases everything should be hooked and executed no earlier than <code> init </code> hook. According to Codex widget registration with <code> register_widget() </code> should be hooked to <code> widget_init </code> . Because of that order of load doesn't matter for this case, you will have everything loaded by the time widget needs it in any case.
|
Between functions.php, widgets and plugins, which is loaded first?
|
wordpress
|
I wish to use a function which is run only when a specific custom field is available. Something like: <code> if (custom_field_x_exists("name_of_the_custom_field")) : <Do some things>; endif; </code> How might it be done?
|
I think this should help <code> if ( get_post_meta( $post->ID, 'name_of_the_custom_field', true ) ) : // Do something endif; </code>
|
Using an "IF" statement based on the existence of custom field
|
wordpress
|
I'm creating a Wordpress site for a client. In the future, my client would like to have a second site that uses Wordpress as well. Ideally, we'd like people that have accounts on the first site to be able to use that same account on the second site. Is this something that can be achieved with Wordpress Multisite? If so, how? The kickers is that each site would need to have it's own domain. For example, http://www.firstblog.com and http://www.secondblog.com would be two different sites sharing the same user accounts. Any help or insight would be greatly appreciated.
|
WordPress multisite only has one table for users, so yes, users can use the same account on both sites. You will just have to be sure to set the appropriate role on each site, as network users are not necessarily users of a given site.
|
Wordpress Multisite - Can 2 domains share a database of users?
|
wordpress
|
I've got the following loop on my index.php template: <code> <div id="new_on"> <?php $args = array( 'meta_query' => array( 'meta_key' => 'is_url', 'meta_value' => 'yes', 'meta_compare' => 'NOT LIKE' ), ); $main_query = new WP_Query( $args ); while ( $main_query->have_posts() ) : $main_query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <div class="clearfix smalltext"><span class="left"><a href="<?php the_author_link(); ?>"><?php the_author(); ?></a></span><span class="right"><?php echo the_time(); ?></span></div> <?php the_excerpt(); ?> <?php endwhile; wp_reset_postdata(); ?> </div> </code> The query should return all posts that do not have the custom field 'is_url' set to 'yes'. It is returning all posts, regardless of the value of is_url. I usually use Custom Post Types for this sort of thing, so I haven't used the meta_query too extensively. Anybody know what I'm doing wrong?
|
I think you're using wrong keys for <code> meta_query </code> array, also it expects nested arrays, even if you only have one query. Code below should help. <code> $args = array( 'meta_query' => array( array( 'key' => 'is_url', 'value' => 'yes', 'compare' => 'NOT LIKE' ) ), ); </code>
|
WP_Query not returning correct result with meta_query parameter
|
wordpress
|
I am using a custom post type name <code> venue </code> and I am using a <code> <select> </code> dropdown on one of the contact form by loading up a custom module in CF7 but when the form is submitted, my data shortcode is not replaced with the data filled by the user. I just see this <code> [selected-venue] </code> . Here is my code for custom module: <code> <?php wpcf7_add_shortcode( 'party-venue', 'wpcf7_venue_shortcode_handler', true ); function wpcf7_venue_shortcode_handler( $tag ) { global $wpdb; $query = "SELECT post_title FROM {$wpdb->posts} where post_type = 'venue' and post_status = 'publish';"; $result = $wpdb->get_col( $query ); if ( $result ) { $output = '<select name="contact_venue" id="contact_venue" class="input-select">'; $output.= '<option></option>'; foreach ( $result as $venue ) { $output.= '<option value="'.$venue.'">'.$venue.'</option>'; } $output.= '</select>'; } return $output; } </code> My contact form's code is <code> <label for="contact_name"><span class="large_contact">name</span><span class="small_contact">Please enter your full name</span></label>[text* your-name class:input-textarea] <label for="contact_email"><span class="large_contact">email</span><span class="small_contact">Please enter a valid email address</span></label>[email* your-email class:input-textarea] <label for="contact_phone"><span class="large_contact">phone</span><span class="small_contact">Please enter a phone number to reach you at</span></label>[text phone class:input-textarea] <label for="contact_friends"><span class="large_contact">party size</span><span class="small_contact">*Min 50 guests for free bottle, 15 guests for buy 1 bottle get 1 free*</span></label>[text party-size class:input-textarea] </p> <label for="contact_venue"><span class="large_contact">venue</span><span class="small_contact">Please select your party venue</span></label>[party-venue selected-venue id:contact_venue] <label for="contact_date"><span class="large_contact">date</span><span class="small_contact">Please enter your party date (mm/dd/yy)</span></label>[text date id:contact_date class:input-textarea] <label for="referal_source"><span class="large_contact">How did you hear about us?</span><span class="small_contact">Please select one of the options</span></label>[select menu-367 class:input-select "" "CitySearch" "Facebook" "Facebook Ad" "Friend" "Google Search" "NYC Daily Deals" "Yelp"] [submit class:input-submit] </code> And here is my message body: <code> From: [your-name] <[your-email]> Subject: Book a party! Message Body: Phone: [phone], Party Size: [party-size], Venue: [selected-venue], Date: [date] How did you hear about us: [menu-367] </code> When I get the email on form submission, <code> [selected-venue] </code> is not replaced with the actual value of the select dropdown. What I am doing wrong?
|
Name of the input field should match with the filler shortcode so that it returns data. I changed <code> $output = '<select name="contact_venue" </code> to <code> $output = '<select name="selected-venue" </code> and it works now.
|
Contact Form 7 Custom module
|
wordpress
|
I know I can use <code> get_num_queries() </code> for the number of queries. However, how can I see what queries Wordpress actually makes? I've tried using $query but that didn't work.
|
See this codex page. in <code> wp-config.php </code> : <code> define('SAVEQUERIES', true); </code> then in your template: <code> if (current_user_can('administrator')){ global $wpdb; echo "<pre>"; print_r($wpdb->queries); echo "</pre>"; } </code> or without the above <code> SAVEQUERIES </code> , you can still see just the main query: <code> global $wp_query; echo $wp_query->request; </code> or to see all of <code> $wp_query </code> : <code> <pre> <?php print_r($wp_query); ?> </pre> </code>
|
view queries made?
|
wordpress
|
I am looking for a simple way to minimize ads on a website I'm developing in WordPress by only showing ads (Google Adsense, to be precise) on the site upon a large influx of traffic. A large influx as defined as, say, more than 2x the normal hourly traffic (though the exact metric used to determine popularity is not that important to me). In other words, if ever the site sees a huge influx of traffic, I would like to begin delivering ads (to attempt to cover the incremental server costs). Otherwise, I would like to keep the site ad-free for the casual visitors. Is there a simple way, or plug-in, to do this in WordPress?
|
There is one wordpress plugin called " Search ads " that lets you do this. You can show adsense ads only to search engine users, which usually click on ads. As for regular readers from sources like bookmarks and manual address typing, ads will not show. Another plugin is " ad injection ". If you wish to do adsense tracking on any website then you have to connect google adsense with google analytics profile. You have to use the tracking code of that profile on site which has adsense enabled.
|
Is there a simple way to only show ads on a WordPress page once it becomes popular?
|
wordpress
|
I'm working on a plugin that was creating a table successfully. However, I decided to test it in a fresh install of Wordpress (on my local server) and now the table is not being created in my activation code. Instead I am getting the error message: The plugin generated 149 characters of unexpected output during activation. If you notice โheaders already sentโ messages, problems with syndication feeds or other issues, try deactivating or removing this plugin. Here is my code: <code> function nc_create_location_table() { // makes the location table global $wpdb; global $simple_location_version; $table_name = $wpdb->prefix . "nc_location"; $installed_ver = get_option( "simple_location_version" ); if( $installed_ver != $simple_location_version ) { $sql = "CREATE TABLE " . $table_name . " ( location_id MEDIUMINT(9) NOT NULL AUTO_INCREMENT, PRIMARY KEY (location_id), name VARCHAR (100), street_no VARCHAR (5), street_name VARCHAR (75), city VARCHAR (75), province_state VARCHAR (75), postal_code VARCHAR(10), country VARCHAR (75) );"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); update_option("simple_location_version", $simple_location_version); } $tmp = get_option('nc_location_options'); if(($tmp['chkbox_reset']=='on')||(!is_array($tmp))) { echo 'setting defaults'; $arr = array( "nc_location_zoom"=>10, "nc_location_width" => "200", "nc_location_height" => "200", "nc_location_drop_down_maptype" => "road", ); update_option('nc_location_options', $arr); } } register_activation_hook(__FILE__,'nc_create_location_table'); </code> When I check my tables, I see that my table hasn't been created, and also I am getting an error message. If anyone can shine a light on why code that was working is now not working (and also, is it possible to see where the unexpected output is...as there's no display as to what the error is other than this message)?
|
<code> if( $installed_ver != $simple_location_version ) { </code> on first run, <code> $installed_ver </code> is an empty string and <code> $simple_location_version </code> is NULL, so this inequality test will fail and your SQL will never be executed. if you check for strict inequality, it will work: <code> if( $installed_ver !== $simple_location_version ) { </code>
|
Problem creating a table with dbDelta
|
wordpress
|
I'm creating a website that has two basic user groups: Subscribers and Editors. Bot can create posts via a custom form using <code> wp_insert_post() </code> , but Editors are allowed to mark a post as private, effectively sharing a single post only among other Editors. As Wordpress already filters private posts out of the loop for anyone lower than Editors, i'm wondering how this will affect my caching because (as far as I understand) I'll have two caches: one showing posts to Subscribers, and one showing posts to Editors which also includes private posts. Within the loop I'm using: <code> current_user_can() </code> : to include or exclude some post content based on Subscriber/Editor/Administrator <code> get_post_status() </code> : to include or exclude some post content based on if the post is "private" or "published" <code> get_post_meta() </code> : to retrieve various custom fields Right now I'm using 26 queries in 0.198 seconds on index.php and 28 queries in 0.193 seconds on single.php. How would one effectively cache this? I don't have any caching plugin yet but I do have access to xCache. Many thanks!
|
So your problem is that you want to cache 2 Loops, WordPress do some stuff behind the hood to cache loops. What you might do is either activate a plugin like W3 Total Cache , but if you really need to perform caching of data for some of functionality there is some function/methods that will allow you utilize theses caching "systems" without needing to dive in to documentation. So there are three basic functions that you might need to check out, first of all you need to <code> wp_cache_set </code> , that will utilize the idea of groups of caching information and keys, so you can retrieve the information later on with the <code> wp_cache_get </code> , and when you are done with that information, and you are sure you will not need it any more later, you can just use <code> wp_cache_delete </code> , to erase that data from your caching "system". Just a heads up, theses functions are not persistent caching, they will be deleted when you do a new request, but they are saved in memory which means they are very fast, so you store information that you will use later from the database there. I've put some links in the text to the trac were this functions are defined, but if you want you can take a look at the <code> WP_Object_Cache </code> reference and check how they can be used, and there is some good recommendations also.
|
Can someone explain Wordpress caching, and what's the best in my scenario?
|
wordpress
|
I'm building a plugin that requires its own set of admin pages. I know how to create the top-level link and how to add sub-menus to it. However, what seems to happen is when I create the top-level link, it also automatically adds a submenu page of the same name if I add another submenu page to it. I'm simply looking for a way to change the name of my first submenu page so that it is different from the parent name. (i.e. in the admin panel, expanding the "Links" menu shows an "All Links" submenu page. Mine would instead say "Links" on top and then "Links" instead of "All Links")
|
You just have set the name of the <code> $menu_slug </code> exactly the same as the parent slug.
|
Naming Admin Menus and Submenus
|
wordpress
|
I've installed a single site WP. In one of my plugins, I have the following code: <code> if(is_multisite) { $upload_dir = get_upload_dir(); $_SESSION['root_image_dir'] = str_replace('\','/',$upload_dir['basedir']); echo 'IS MULTI.'; //<-- this is outputted every time } else { $_SESSION['root_image_dir'] = ''; echo 'IS NOT MULTI'.$_SESSION['root_image_dir']; } </code> For some reason, the <code> echo </code> statement is triggered every time. Why is <code> is_multisite </code> not working?.
|
If that's the code you have in your plugin, you're writing it wrong. You have <code> if(is_multisite) </code> which is treating the string <code> is_multisite </code> as a constant and evalutation to true. Essentially you're writing <code> if(true) ... </code> Remember, <code> is_multisite() </code> is a function . You need the parenthesis at the end for PHP to actually evaluate the function. Change your code to the following: <code> if( is_multisite() ) { $upload_dir = get_upload_dir(); $_SESSION['root_image_dir'] = str_replace('\','/',$upload_dir['basedir']); echo 'IS MULTI.'; //<-- this is outputted every time } else { $_SESSION['root_image_dir'] = ''; echo 'IS NOT MULTI'.$_SESSION['root_image_dir']; } </code>
|
Why is 'is_multisite' returning true when it's a single install?
|
wordpress
|
I have a site based on WordPress. This site has some functions for member only. One of the functions is a external script and I believe anyone can access this without authentication. I can add .htaccess to this script to prevent unauthorized access. But then my users have to login again and it's kind of inconvenient. Is there any solution to add some check to my script that use the same WordPress authentication mechanism, that is, if user already login, he have full access to the script. If not, he will be redirected to WordPress login page. EDIT : My script is written in PHP
|
Just add this at the top of your file: <code> require_once($_SERVER['DOCUMENT_ROOT'].'/wp-blog-header.php'); // If you run multisite, you might nees this to prevent 404 error header('HTTP/1.1 200 OK'); </code> Note that the file must be in the same folder as your theme. Then you can use <code> is_user_logged_in </code> before executing the rest of the script. If use is not logged in, then just trigger the login form or a login plugin.
|
How to use WordPress authentication on non-WordPress page?
|
wordpress
|
I'm working on a new blog which display in a list, on sidebar, some categories and the posts of them. In the index page, in main content, I list some post titles from other category "New". What I need is: when i click on one post link on sidebar to display in main content the post content via ajax or JQuery.
|
You will need to create a WordPress function that loads the post content and hook that into wp_ajax_nopriv. You will also need the jQuery ajax functions to send the $_POST data to your WordPress function via ajax and output the returned content in your empty div where you want it to display. A simple approach would be to use the post ID in the class or id div tag so you can easily pull it out with jQuery. Example using the sidebar code from Steven's answer: <code> echo '<ul id="sidebar-ajax">'; foreach($sidebar_posts as $post): echo '<li id="' .get_the_ID(). '">'; echo '<a class="ajax-click" href="#">.'get_the_title().'</a>'; the_title('<h3>','</h3>'); echo '</li>'; endforeach; echo '</ul>'; </code> Example jQuery (this should be in a separate file and enqueued using <code> wp_enqueue_script </code> so the the ajax url can be defined as a javascript namespace variable using <code> wp_localize_script </code> : Enqueue the script and set the ajax url variable: <code> wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) ); wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); </code> Contents of the ajax.js file: <code> jQuery(document).ready(function($) { $(".ajax-click").click(function() { $("#loading-animation").show(); var post_id = $(this).parent("li").attr("id"); var ajaxURL = MyAjax.ajaxurl; $.ajax({ type: 'POST', url: ajaxURL, data: {"action": "load-content", post_id: post_id }, success: function(response) { $("#empty_div_in_content").html(response); $("#loading-animation").hide(); return false; } }); }); )}; </code> *Note: Add a loading animation graphic where the post will eventually display and and give it a div id of "loading-animation" and set it to display: none. WordPress function to return the post content to the ajax call: <code> add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' ); function my_load_ajax_content () { $post_id = $_POST[ 'post_id' ]; $post = get_post( $post_id, OBJECT); $response = apply_filters( 'the_content', $post->post_content ); echo $response; die(1); } </code>
|
How to load post content on index page using ajax when post title in sidebar is clicked
|
wordpress
|
I have a custom post type <code> announcements </code> which obviously holds posts with weekly announcements. In my theme's header, I want to create a box which has the following semantics: <code> <div id="header-announcements"> <h3>Announcements</h3> <ul> <li><a href="post-permalink">Title</a></li> <li><a href="post-permalink">Title</a></li> <li><a href="post-permalink">Title</a></li> <li><a href="post-permalink">Title</a></li> <li><a href="post-permalink">Title</a></li> </ul> <div><a href="#">View More</a></div> </div> </code> I know I want to use <code> wp_query() </code> and I've found that I should do something similar to <code> ann-query = wp_query('post_type=announcements&posts_per_page=5'); </code> I know I need to do a foreach, but I haven't dived deep enough into wordpress to know what to do after the query. Any help? Thanks!
|
The following should work, but isn't tested: <code> <div id="header-announcements"> <h3>Announcements</h3> <?php $queryObject = new WP_Query( 'post_type=announcements&posts_per_page=5' ); // The Loop! if ($queryObject->have_posts()) { ?> <ul> <?php while ($queryObject->have_posts()) { $queryObject->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php } ?> </ul> <div><a href="#">View More</a></div> <?php } ?> </div> </code>
|
Grab 5 latest posts from custom post type 'announcements'
|
wordpress
|
I have a jQuery ui tabs that load posts via ajax on sidebar. Now in a specific page i want to filter the query post via <code> is_page(); </code> conditional. But in my case its not working. <code> function load_home_classifieds($type){ $query = array( 'post_type' => 'classified', 'posts_per_page' => 5 ); if(is_page('real-estate')){ //echo 'ok'; $query['tax_query'] = array( array( 'taxonomy' => 'classified-category', 'field' => 'slug', 'terms' => array( 'real-estate' ), 'operator' => 'NOT IN' ) ); } if($type == 'latest'){ query_posts($query); get_template_part('loop', 'cfhome'); } elseif($type == 'random'){ $query['orderby'] = 'rand'; query_posts($query); get_template_part('loop', 'cfhome'); } else{ echo 'Invalid request!'; } } </code> Now, my question is how to get the conditional working inside an ajax function?
|
If this is executed within an ajax request, is_page() won't be set. the page you're making the request from was a previous request. you need to set something on the originating page to pass with your ajax request to let it know it's for your special case page.
|
is_page() conditional not working inside an AJAX function
|
wordpress
|
I am using a script to import my vbulletin forum posts into wordpress as posts. One quick issue I ran into is there are numerous forum posts with the same title 'please help me'. When I go into the post edit screen the permalink will show 'please-help-me-2' for the second one, and 'please-help-me-3' for the third one. That is exactly what I expect. However, when you go to view the second one on the front end of the website , instead of having the -2 appended to the end of the url, it simply says 'please-help-me'. If I 'update' the post, then the permalink saves properly and the front end link changes like it should. What I need: Is there a function that I can use to go through the posts database and have it automatically 'update' all the posts so that the permalinks will change properly on the front end? *we're talking 1.25million posts here, so automation is important. thanks
|
There is a function called wp_insert_post that takes a parameter for post ID. If the post ID is an ID that already exists, this function will update the post with the information you pass in the function parameters. I think using that function you could find a way to retrieve all of your post ID's in an array and then use a foreach loop to update each one.
|
What 'function' will 'update' a post?
|
wordpress
|
I am writing a plugin that requires a large chunk of html. Now the way how it is set up now works. <code> return <<<EOT <html> EOT; </code> But I want to split the file into different php files that i can include. Now I tried this, but it does not work: <code> ob_start(); include(plugin_dir_url( __FILE__ ).'file.php'); return ob_get_clean(); </code> Any know how this could be done? ===================== EDIT Ok thanks Chris Carson to I have found the small error, I changed the code to: <code> ob_start(); include(plugin_dir_path( __FILE__ ).'/file.php'); return ob_get_clean(); </code> This is working ok now, except for one small problem. In the previous code I used something like this: <code> $variable = 'Hello!'; return <<<EOT <span>{$variable}</span> EOT; </code> This would have made the following in html: <code> <span>Hello!</span> </code> But now this: <code> $variable = 'Hello!'; ob_start(); include(plugin_dir_path( __FILE__ ).'/file.php'); return ob_get_clean(); </code> This just prints <code> <span>{$variable}</span> </code> Any way to get the code working with variables.
|
When including files you don't want the URL, but the filesystem path instead. So... <code> include(dirname(__FILE__) . "/path/to/myfile.php"); </code> Remember to put the first forward slash in <code> /path/to/myfile.php </code> , since <code> dirname </code> doesn't include the trailing slash.
|
Include content of file into plugin (ob_start();;include;ob_get_clean()) without < < <EOT
|
wordpress
|
Why is http://compassionpit.com/blog/ going through an infinite redirect loop? Here's my nginx conf file. The site is run by a nodejs server on port 8000 and Apache serves up the blog (wordpress) and the forum (phpBB). The forum is resolving just fine, at http://www.compassionpit.com/forum/ ... This webpage has a redirect loop The webpage at http://www.compassionpit.com/blog/ has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer. <code> server { listen 80; server_name www.compassionpit.org; rewrite ^/(.*) http://www.compassionpit.com/$1 permanent; } server { listen 80; # your server's public IP address server_name www.compassionpit.com; index index.php index.html; location ~ ^/$ { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location @blogphp { internal; root /opt/blog/; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/index.php; fastcgi_index index.php; fastcgi_pass 127.0.0.1:8080; } location ~ ^/(forum|blog)/($|.*\.php) { root /opt/; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_index index.php; fastcgi_pass 127.0.0.1:8080; } location ~ ^/(forum|blog) { root /opt/; try_files $uri $uri/ @blogphp; } location ~ ^/(forum|blog)/ { root /opt/; } location @backend { internal; proxy_pass http://127.0.0.1:8000; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location ~ / { root /opt/chat/static/; try_files $uri $uri/ @backend; } } </code>
|
Is WordPress configured to use www or without www? Your server seems to be listening only for the <code> www </code> version and tries to redirect non- <code> www </code> requests to the <code> www </code> version. Considering that you provided a link to the non- <code> www </code> version of the domain above, my guess is that WordPress is trying to hook on to <code> http://compassionpit.com </code> , but your server redirects those requests to <code> http://www.compassionpit.com </code> and WordPress redirects it back to <code> http://compassionpit.com </code> . If that is indeed what's going on, either kill the <code> www </code> redirect on your server or tell WordPress (by setting your options directly through phpMyAdmin) to use the <code> www </code> version of the domain.
|
Blog has an infinite redirect loop
|
wordpress
|
Is there a way to disable archives pages, specifically monthly archives?
|
Check this post by BetterWP. You may need to edit the code as it does not mention about monthly archives.
|
How to disable monthly archive
|
wordpress
|
I'm using this excellent function to automatically add a category to my custom post type "Videos" on publish, if there's no category already chosen. This works great: <code> function add_video_category_automatically($post_ID) { global $wpdb; if(!has_term('','category',$post_ID)){ $cat = array(394); wp_set_object_terms($post_ID, $cat, 'category'); } } add_action('publish_videos', 'add_video_category_automatically'); </code> But, I'd really like to get the category ID via the slug, so that I don't have to change it manually when I'm testing on localhost vs the live site (which may have a different ID for that category as localhost and the live site aren't in sync). I've tried a number of options but all of them result in a category of "394" being assigned to new posts, rather than "Videos". Here's my latest attempt. Can you tell me where I'm going wrong? <code> function add_video_category_automatically($post_ID) { global $wpdb; if(!has_term('','category',$post_ID)){ $category = get_term_by( 'slug', 'videos', 'category' ); $cat = array($category->term_id); wp_set_object_terms($post_ID, $cat, 'category'); } } add_action('publish_videos', 'add_video_category_automatically'); </code> Thank you!
|
<code> wp_set_object_terms </code> Works better with term slug instead of term id so change this line: <code> $cat = array($category->term_id); </code> to: <code> $cat = array($category->slug); </code>
|
Add category to custom post type automatically, using category slug
|
wordpress
|
I build a review site with Wordpress. I created a custom post type called "Reviews", inside this, theres two taxonomy, one called "Genres" and one called "Types". Inside the Genres, i have a couple of subcategory, action, comedy, drama etc... and inside the Types, i have 2 subcategory: Movies and TV Shows I want to create a navigation on my homepage like this: Movies Action Comedy Drama Tv Show Action Comedy Drama And of course, if i click on the Tv Shows/Action, i only want to display all of the reviews inside the Tv Shows category which has an Action genre, and only the TV show, not the movies. What is the easiest solution to do this?
|
The way that I would approach it is using the tax_query to create a query that looks for both the correct genre and type. For example, to query all Movies that are Drama: <code> $myquery['tax_query'] = array( array( 'taxonomy' => 'genre', 'terms' => array('drama'), 'field' => 'slug', ), array( 'taxonomy' => 'type', 'terms' => array('movie'), 'field' => 'slug', ), ); query_posts($myquery); </code> Hopefully that will get you started in the right direction.
|
Review site custom post type structure
|
wordpress
|
For example I have 20 pages on a site. one of them is called bacon another called eggs. on the same site...lets say breakfast.com I have the permalinks set up properly and have used them successfully on all pages, including Eggs by way of this: www.breakfast.com/eggs?cooked=scrambled. This works 100% as it should. However, on a different page of Breakfast.com called sausage...this, does not work. www.breakfast.com/sausage?type=spicy this is causes a 404 error. I don't see why it would as it's the same format. I have verified that the page exists in my pages directory in WP-admin. If I strip away the GET variable the page works. Google is not helping me. Anyone have a similar experience?
|
WordPress has a list of reserved terms that you cannot use for taxonomies. From your question, I gather that "cooked" is a taxonomy that applies to eggs and "type" is a taxonomy that applies to sausage. Unfortunately, "type" is a reserved term in WordPress, so it interprets your query string differently than you expect. The full list of reserved terms is available in the Codex . Just use a different term ... maybe "sausage-type" ... for your taxonomy and you should be in the clear.
|
Why would a GET variable one one page of a site cause a 404 error when a GET variable works on another page of a site?
|
wordpress
|
Is there a quick way to add a list of countries as terms to a custom taxonomy called "Country"? Is there an existing import file, SQL script ect... I don't want to be there all day manually adding them. Any ideas would be great.
|
Try this. Note that I found this country array online and cannot vouch for it's accuracy. Also, I've set the taxonomy to the "country" taxonomy. Change all instances of that if it does not match your specific taxonomy name. You can add this to your functions.php file in your current theme. Reload WordPress and it should add them. Once they are added, delete this code. I did put a check in there to make sure they aren't added twice. <code> add_action('init', 'add_countries', 100); function add_countries() { $country_array = array( 'AF'=>'AFGHANISTAN', 'AL'=>'ALBANIA', 'DZ'=>'ALGERIA', 'AS'=>'AMERICAN SAMOA', 'AD'=>'ANDORRA', 'AO'=>'ANGOLA', 'AI'=>'ANGUILLA', 'AQ'=>'ANTARCTICA', 'AG'=>'ANTIGUA AND BARBUDA', 'AR'=>'ARGENTINA', 'AM'=>'ARMENIA', 'AW'=>'ARUBA', 'AU'=>'AUSTRALIA', 'AT'=>'AUSTRIA', 'AZ'=>'AZERBAIJAN', 'BS'=>'BAHAMAS', 'BH'=>'BAHRAIN', 'BD'=>'BANGLADESH', 'BB'=>'BARBADOS', 'BY'=>'BELARUS', 'BE'=>'BELGIUM', 'BZ'=>'BELIZE', 'BJ'=>'BENIN', 'BM'=>'BERMUDA', 'BT'=>'BHUTAN', 'BO'=>'BOLIVIA', 'BA'=>'BOSNIA AND HERZEGOVINA', 'BW'=>'BOTSWANA', 'BV'=>'BOUVET ISLAND', 'BR'=>'BRAZIL', 'IO'=>'BRITISH INDIAN OCEAN TERRITORY', 'BN'=>'BRUNEI DARUSSALAM', 'BG'=>'BULGARIA', 'BF'=>'BURKINA FASO', 'BI'=>'BURUNDI', 'KH'=>'CAMBODIA', 'CM'=>'CAMEROON', 'CA'=>'CANADA', 'CV'=>'CAPE VERDE', 'KY'=>'CAYMAN ISLANDS', 'CF'=>'CENTRAL AFRICAN REPUBLIC', 'TD'=>'CHAD', 'CL'=>'CHILE', 'CN'=>'CHINA', 'CX'=>'CHRISTMAS ISLAND', 'CC'=>'COCOS (KEELING) ISLANDS', 'CO'=>'COLOMBIA', 'KM'=>'COMOROS', 'CG'=>'CONGO', 'CD'=>'CONGO, THE DEMOCRATIC REPUBLIC OF THE', 'CK'=>'COOK ISLANDS', 'CR'=>'COSTA RICA', 'CI'=>'COTE D IVOIRE', 'HR'=>'CROATIA', 'CU'=>'CUBA', 'CY'=>'CYPRUS', 'CZ'=>'CZECH REPUBLIC', 'DK'=>'DENMARK', 'DJ'=>'DJIBOUTI', 'DM'=>'DOMINICA', 'DO'=>'DOMINICAN REPUBLIC', 'TP'=>'EAST TIMOR', 'EC'=>'ECUADOR', 'EG'=>'EGYPT', 'SV'=>'EL SALVADOR', 'GQ'=>'EQUATORIAL GUINEA', 'ER'=>'ERITREA', 'EE'=>'ESTONIA', 'ET'=>'ETHIOPIA', 'FK'=>'FALKLAND ISLANDS (MALVINAS)', 'FO'=>'FAROE ISLANDS', 'FJ'=>'FIJI', 'FI'=>'FINLAND', 'FR'=>'FRANCE', 'GF'=>'FRENCH GUIANA', 'PF'=>'FRENCH POLYNESIA', 'TF'=>'FRENCH SOUTHERN TERRITORIES', 'GA'=>'GABON', 'GM'=>'GAMBIA', 'GE'=>'GEORGIA', 'DE'=>'GERMANY', 'GH'=>'GHANA', 'GI'=>'GIBRALTAR', 'GR'=>'GREECE', 'GL'=>'GREENLAND', 'GD'=>'GRENADA', 'GP'=>'GUADELOUPE', 'GU'=>'GUAM', 'GT'=>'GUATEMALA', 'GN'=>'GUINEA', 'GW'=>'GUINEA-BISSAU', 'GY'=>'GUYANA', 'HT'=>'HAITI', 'HM'=>'HEARD ISLAND AND MCDONALD ISLANDS', 'VA'=>'HOLY SEE (VATICAN CITY STATE)', 'HN'=>'HONDURAS', 'HK'=>'HONG KONG', 'HU'=>'HUNGARY', 'IS'=>'ICELAND', 'IN'=>'INDIA', 'ID'=>'INDONESIA', 'IR'=>'IRAN, ISLAMIC REPUBLIC OF', 'IQ'=>'IRAQ', 'IE'=>'IRELAND', 'IL'=>'ISRAEL', 'IT'=>'ITALY', 'JM'=>'JAMAICA', 'JP'=>'JAPAN', 'JO'=>'JORDAN', 'KZ'=>'KAZAKSTAN', 'KE'=>'KENYA', 'KI'=>'KIRIBATI', 'KP'=>'KOREA DEMOCRATIC PEOPLES REPUBLIC OF', 'KR'=>'KOREA REPUBLIC OF', 'KW'=>'KUWAIT', 'KG'=>'KYRGYZSTAN', 'LA'=>'LAO PEOPLES DEMOCRATIC REPUBLIC', 'LV'=>'LATVIA', 'LB'=>'LEBANON', 'LS'=>'LESOTHO', 'LR'=>'LIBERIA', 'LY'=>'LIBYAN ARAB JAMAHIRIYA', 'LI'=>'LIECHTENSTEIN', 'LT'=>'LITHUANIA', 'LU'=>'LUXEMBOURG', 'MO'=>'MACAU', 'MK'=>'MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF', 'MG'=>'MADAGASCAR', 'MW'=>'MALAWI', 'MY'=>'MALAYSIA', 'MV'=>'MALDIVES', 'ML'=>'MALI', 'MT'=>'MALTA', 'MH'=>'MARSHALL ISLANDS', 'MQ'=>'MARTINIQUE', 'MR'=>'MAURITANIA', 'MU'=>'MAURITIUS', 'YT'=>'MAYOTTE', 'MX'=>'MEXICO', 'FM'=>'MICRONESIA, FEDERATED STATES OF', 'MD'=>'MOLDOVA, REPUBLIC OF', 'MC'=>'MONACO', 'MN'=>'MONGOLIA', 'MS'=>'MONTSERRAT', 'MA'=>'MOROCCO', 'MZ'=>'MOZAMBIQUE', 'MM'=>'MYANMAR', 'NA'=>'NAMIBIA', 'NR'=>'NAURU', 'NP'=>'NEPAL', 'NL'=>'NETHERLANDS', 'AN'=>'NETHERLANDS ANTILLES', 'NC'=>'NEW CALEDONIA', 'NZ'=>'NEW ZEALAND', 'NI'=>'NICARAGUA', 'NE'=>'NIGER', 'NG'=>'NIGERIA', 'NU'=>'NIUE', 'NF'=>'NORFOLK ISLAND', 'MP'=>'NORTHERN MARIANA ISLANDS', 'NO'=>'NORWAY', 'OM'=>'OMAN', 'PK'=>'PAKISTAN', 'PW'=>'PALAU', 'PS'=>'PALESTINIAN TERRITORY, OCCUPIED', 'PA'=>'PANAMA', 'PG'=>'PAPUA NEW GUINEA', 'PY'=>'PARAGUAY', 'PE'=>'PERU', 'PH'=>'PHILIPPINES', 'PN'=>'PITCAIRN', 'PL'=>'POLAND', 'PT'=>'PORTUGAL', 'PR'=>'PUERTO RICO', 'QA'=>'QATAR', 'RE'=>'REUNION', 'RO'=>'ROMANIA', 'RU'=>'RUSSIAN FEDERATION', 'RW'=>'RWANDA', 'SH'=>'SAINT HELENA', 'KN'=>'SAINT KITTS AND NEVIS', 'LC'=>'SAINT LUCIA', 'PM'=>'SAINT PIERRE AND MIQUELON', 'VC'=>'SAINT VINCENT AND THE GRENADINES', 'WS'=>'SAMOA', 'SM'=>'SAN MARINO', 'ST'=>'SAO TOME AND PRINCIPE', 'SA'=>'SAUDI ARABIA', 'SN'=>'SENEGAL', 'SC'=>'SEYCHELLES', 'SL'=>'SIERRA LEONE', 'SG'=>'SINGAPORE', 'SK'=>'SLOVAKIA', 'SI'=>'SLOVENIA', 'SB'=>'SOLOMON ISLANDS', 'SO'=>'SOMALIA', 'ZA'=>'SOUTH AFRICA', 'GS'=>'SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS', 'ES'=>'SPAIN', 'LK'=>'SRI LANKA', 'SD'=>'SUDAN', 'SR'=>'SURINAME', 'SJ'=>'SVALBARD AND JAN MAYEN', 'SZ'=>'SWAZILAND', 'SE'=>'SWEDEN', 'CH'=>'SWITZERLAND', 'SY'=>'SYRIAN ARAB REPUBLIC', 'TW'=>'TAIWAN, PROVINCE OF CHINA', 'TJ'=>'TAJIKISTAN', 'TZ'=>'TANZANIA, UNITED REPUBLIC OF', 'TH'=>'THAILAND', 'TG'=>'TOGO', 'TK'=>'TOKELAU', 'TO'=>'TONGA', 'TT'=>'TRINIDAD AND TOBAGO', 'TN'=>'TUNISIA', 'TR'=>'TURKEY', 'TM'=>'TURKMENISTAN', 'TC'=>'TURKS AND CAICOS ISLANDS', 'TV'=>'TUVALU', 'UG'=>'UGANDA', 'UA'=>'UKRAINE', 'AE'=>'UNITED ARAB EMIRATES', 'GB'=>'UNITED KINGDOM', 'US'=>'UNITED STATES', 'UM'=>'UNITED STATES MINOR OUTLYING ISLANDS', 'UY'=>'URUGUAY', 'UZ'=>'UZBEKISTAN', 'VU'=>'VANUATU', 'VE'=>'VENEZUELA', 'VN'=>'VIET NAM', 'VG'=>'VIRGIN ISLANDS, BRITISH', 'VI'=>'VIRGIN ISLANDS, U.S.', 'WF'=>'WALLIS AND FUTUNA', 'EH'=>'WESTERN SAHARA', 'YE'=>'YEMEN', 'YU'=>'YUGOSLAVIA', 'ZM'=>'ZAMBIA', 'ZW'=>'ZIMBABWE', ); // Loop through array and insert terms foreach($country_array as $abbr => $name) { if(!get_term_by('name', ucwords(strtolower($name)), 'country')) wp_insert_term(ucwords(strtolower($name)), 'country'); } } </code>
|
Fast way to add countries as a custom taxonomy term?
|
wordpress
|
I am building a custom wordpress theme from a clients mockup. On the homepage there are 2 sliders, and 4-5 areas for recent posts of different types. I would like to have all the content be editable in wordpress what is the best way to create a post, apply some sortof value to it (category,taxonomy,tag,custom post type), and then retrieve more than one loop on a single page or is it best to use feeds? Any suggestions greatly appreciated
|
You can use WP_Query in your template to select groups of posts by type, category, tag, custom taxonomy, meta field, etc., and create additional loops: <code> <?php $news = new WP_Query("post_type=mynews&posts_per_page=1"); while($news->have_posts()) : $news->the_post(); the_title(); endwhile; $events = new WP_Query("cat=2&posts_per_page=3"); while($events->have_posts()) : $events->the_post(); the_title(); endwhile; // etc.. </code> It's up to you how to best organize your content in a way that makes sense as far as how you use your taxonomies and types.
|
Best Practice for Displaying Categorized Posts on Front Page
|
wordpress
|
I've tried everything. I've looked at every. single. question. here, on StackOverflow, the WP help forum, googled 10 pages deep and literally tried EVERY combination of code I could find, for the last 2 days, and can't get anything to work how I want it. Surely it can't be impossible? The goal seems so simple! THE GOAL: Show ALL sticky posts first, and then normal posts after them - WITH PAGINATION. Example: With posts per page set to 10, having 15 sticky posts and 15 normal posts, page 1 would be 10 sticky posts, page 2 would be 5 sticky posts and then 5 normal posts, and page 3 would be 10 normal posts. Ordered by date. I've tried multiple loops, various queries, and have come CLOSE but so far no cigar. Here's what I have so far: <code> <!-- THIS CODE QUERIES ALL POSTS AND RETURNS ONLY STICKY POSTS, DISPLAYED AT TOP OF THE PAGE --> <?php // show only ads within this specific category $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy')); //$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $sticky=get_option('sticky_posts'); $args=array( 'post_type' => 'my_custom_post_type', 'ad_cat' => $term->slug, 'caller_get_posts' => 1, 'post__in' => $sticky, 'posts_per_page' => -1 //'paged' => $paged ); query_posts($args); ?> <?php get_template_part( 'loop', 'post_featured' ); ?> <?php wp_reset_query(); ?> <!-- THIS CODE QUERIES ALL POSTS AND RETURNS ONLY REGULAR POSTS, DISPLAYED BELOW THE STICKIES --> <?php // show only ads within this specific category $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy')); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $sticky=get_option('sticky_posts'); $args=array( 'post_type' => 'my_custom_post_type', 'ad_cat' => $term->slug, 'caller_get_posts' => 1, 'post__not_in' => $sticky, 'paged' => $paged, ); query_posts($args); ?> <?php get_template_part( 'loop', 'post_normal' ); ?> <?php wp_reset_query(); ?> </code> The above shows ALL sticky posts and then (5) normal posts. This is the closest I have gotten, but #1, I don't want to show ALL sticky posts on the first page, I want to adhere to the pagination rules. #2, ALL sticky posts show up on all paged pages. So if I have 50 sticky posts and 50 normal posts, each page shows 55 posts - the first 50 are the sticky posts and the last 5 are normal, which is not my goal (see THE GOAL above). Is there an easy modification to one or both loops? Should I be using a double loop or is there another/better option to do this? I'm open to suggestions as long as I get it to WORK. I should note: I'm using WP 3.2.1 and a slimmed down non-plugin pagination function which was taken from WP-PageNavi (full pagination function can be seen here: http://paste2.org/p/1596821 ). Any help is appreciated!
|
@Chris_O is right... currently sticky posts are not supported in custom post types so it must have something to do with the theme you are using. Now disregarding the CPT problem... and assuming that it does work the same way wordpress stickies do then the goal that you are describing is exactly the way 'sticky' posts are designed to work in wordpress (i.e. show all the sticky posts before showing the normal posts and adhere to pagination), so from what I can tell your problem lies in the fact that you are trying to create two separate loops. In order to display the posts they way you want them to be displayed you should be using only one loop. Have you tried just running one loop (i.e. removing the second query and replacing the first one with something like the below to see if the stickies are automatically added)? <code> $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; $args=array( 'post_type' => 'my_custom_post_type', 'paged' => $paged, 'posts_per_page' => 10 ); query_posts($args); get_template_part( 'loop', 'post_normal' ); </code>
|
Custom loops, sticky posts, and pagination nightmare
|
wordpress
|
I have a very peculiar requirement, hopefully I can explain it without being too confusing. I created a page template where I list some properties I get from an external XML file, so far no problems, let's say the URL is like this: http://www.mysite.com/properties/ Each property has a link that should redirect the user to a "Single Property" page that displays more info about it, what I was wondering is if there's a way to make the link like this http://www.mysite.com/properties/123 ? Where "123" would be the id of the property, basically if I have the url like properties/some_id I want to be able to load a view file (like the single.php or page.php files) but specific to this url condition. Is this possible? Thanks in advance!
|
Add this to your theme's functions.php, or put it in a plugin. <code> add_action( 'init', 'wpse26388_rewrites_init' ); function wpse26388_rewrites_init(){ add_rewrite_rule( 'properties/([0-9]+)/?$', 'index.php?pagename=properties&property_id=$matches[1]', 'top' ); } add_filter( 'query_vars', 'wpse26388_query_vars' ); function wpse26388_query_vars( $query_vars ){ $query_vars[] = 'property_id'; return $query_vars; } </code> This adds a rewrite rule which directs requests to <code> /properties/ </code> with any combination of numbers following to pagename <code> properties </code> , with the query var <code> property_id </code> set. Just be sure to visit your permalinks settings page and save to flush rewrite rules, so this new rule will be included. In your <code> page-properties.php </code> template, <code> get_query_var('property_id') </code> will return the property id if it was set, if it's not then show the default properties page.
|
How to create custom URL routes?
|
wordpress
|
My friend mentioned that there is a simple way to modify what users see in the admin sidebar based on their user role. I have a large number of custom post types, one for each user, and I need to limit these users (currently given the role 'author') access to only their own post type and the Posts (not even Pages). I also want to hide Widgets from them. Is there a bit of PHP I can stick in my functions.php file to accomplish this easily?
|
To anyone else having the same problem as me, I used the Role Scoper plugin , which is recommended by WordPress on their page that describes user roles. It has a very simple UI, and is easy to install and use.
|
WordPress User Roles, Custom Post Types, and Admin views
|
wordpress
|
I'm doing an INSERT into a wordpress table and anything with an apostrophe is coming out <code> It's true </code> I tried using htmlspecialchars but I'm still getting the backslash. Is there any way to write it so that the user sees <code> It's true </code> While the table in the database sees: <code> It's true </code> Below is my insert code: <code> global $wpdb; $table = 'wp_nc_location'; $data = array( 'name' => $name, 'street_no' => $street_number, 'street_name' => $street_name, 'city' => $city, 'province_state' => $province_state, 'postal_code' => $postal, 'country' => $country ); $format = array( '%s', '%s', '%s', '%s', '%s', '%s' ); $wpdb->insert( $table, $data, $format); </code>
|
When you retrieve the data make sure to call stripslashes, or stripslashes_deep if it's an array. <code> $name = stripslashes($name); </code>
|
How to deal with apostrophes
|
wordpress
|
I want to remove the "page" bit from the URL when I use the <code> previous_posts_link </code> and <code> next_posts_link </code> . Right now, it looks like: http://mywebsite.com/page/2 I want it to look like this: http://mywebsite.com/2 How can I do it? Thanks!
|
So yeah, got the tumbleweed badge :(. I ended up doing a 301 with the .htaccess, but If someone has a better idea please share it!
|
remove the 'page' URL parameter in previous/next posts link
|
wordpress
|
My site, http://www.cancer-study.com , has been hacked, and I can't login to wp-admin. Can you say how it has been hacked and what can I do to undo the damage? I have access to the host.
|
If you do a Google search, you will find many topics on this. Here are some links: First read this: http://codex.wordpress.org/FAQ_My_site_was_hacked Then take a look at these links: http://ottopress.com/2009/hacked-wordpress-backdoors/ http://wordpress.org/support/topic/268083#post-1065779 http://smackdown.blogsblogsblogs.com/2008/06/24/how-to-completely-clean-your-hacked-wordpress-installation/ If you have access to your database, login using PHPMyAdmin and change admin username / password, delete users you don't know and change password for rest. Then start the process of backing up data and do a clean install. Note. If you can't find out how they got access to your site, doing a clean install and putting back data, will still leave whatever hole open. Also not that backdoors (links / code) could have been added to your posts, so all content must be checked before you import exported data.
|
How was my WP site hacked
|
wordpress
|
Where should I amend to make this happen? I should add somewhere target="blank_" Regards,
|
in the link tag of course: <code> <a href="<?php the_permalink(); ?>" target="_blank">link title</a> </code> but it is <code> _blank </code> and not <code> blank_ </code>
|
How to make that all permalinks would open in a new window?
|
wordpress
|
I'd like to determine how many times a user has logged in. Does WordPress retain that information or will I have to add a db entry every time they log-in? <code> if(is_user_logged_in() && ($logged_in_times == 2)) { // do something } </code>
|
I don't think so. You will need to do something like this (untested): <code> add_action("wp_login", "my_login_function"); function my_login_function($username){ $userdata = get_user_by('login', $username); $n = get_user_meta($userdata->ID, "my_login_counter", true); if (! is_numeric($n)) $n = 0; $n = intval($n) + 1; update_user_meta($userdata->ID, "my_login_counter", $n); } </code>
|
Find out how many times the user has logged in
|
wordpress
|
I had asked this question in a different way too, but no one replied there! I guess I should rephrase it here. My custom post is 'company'. I'm trying to add a custom rewrite rule. When the 'url http://domain..com/company/company-title-slug/replies ', is accessed, I want redirect to a custom template(applied to a page named 'replies') with all the comments for this custom post listed. If I add the comment id in the url like this 'url http://domain..com/company/company-title-slug/replies/23 ', I want to redirect to another page with a custom template applied for displaying a single comment. This is what I did for accessing the url... 'http://domain.com/replies/reply_id', and it works fine. <code> add_rewrite_rule('^replies/(.*)?$','index.php?pagename=replies&reply_id=$matches[1]','top'); </code> Please guide me in the proper direction, having a real hard time with the url rewrite stuff! Thanks in advance!
|
I haven't tested it, but what about: <code> add_rewrite_rule('^company/(.+)/replies/(.*)?$','index.php?pagename=replies&reply_id=$matches[2]','top'); </code>
|
Need help with a custom rewrite rule - http://domain/custom post slug/replies
|
wordpress
|
Scenario: Page displays a list of titles for a custom post type (video) with a selected "category" (in the taxonomy its called the subject). For example videos with the subject of "creative" Problem If there are titles present that match the the criteria then the list is displayed correctly but if there are no titles then the message "No Titles Found" fails to appear on the page. In other words the echo statement is failing. My Code <code> <?php $subject = $_GET['subject']; if ($subject=="") $subject = 'creativity';?><?php /*If there is no value returned then the loop defaults to searching for items beginning with 'Creativity' since its the first term.*/ ?> <h2>Video Titles For <span class="colorBlack"><?php echo $subject ?></span></h2> <?php /*This needs to be outside of the loop*/?> <?php $loop = new WP_Query( array( 'post_type' => 'video', 'subject' => $subject, 'posts_per_page' => 10 ) ); ?> <?php if (have_posts() ):?> <?php while ( $loop->have_posts() ) : $loop->the_post();?> <div class="glossarybody"> <h2><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2> </div> <?php endwhile; else: echo 'No Titles Found'; endif; ?> </code> Looking at the codex the form of the 'if else is given as: <code> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); // Your loop code endwhile; else : echo wpautop( 'Sorry, no posts were found' ); endif; ?> </code> So I seem to have the correct syntax and since the 'if' section functions correctly I assume it has correct syntax. I'd appreciate any pointers as to where I'm going wrong. Thanks
|
Try <code> $loop->have_posts() </code> on if statement. See if it fixes the issue.
|
if/Else have_posts Else fails to echo message to page
|
wordpress
|
Is it possible to limit a CPT to just one? What I'd like to accomplish is creating a CPT called "Home". It will manage any and all elements on the home page. I want to program it so when the user clicks on the "Manage Home Page" link they will go straight to the edit post screen. They will skip over the "All Post" screen. Does anyone think this is even possible? Or maybe someone has an idea to accomplish this goal a completely different?
|
I would suggest creating a Theme Options page for this purpose. stackexchange-url ("stackexchange-url add_options_page() in Codex. Or is there anything special in the post edit screen that you want to use that would be hard to get into the Theme Options page?
|
how to only have one custom post type post?
|
wordpress
|
I'm trying to load plugins automatically by putting the plugins into <code> mu-plugins </code> folder. But if the plugin is put in a folder, it isn't loaded. I tried some popular plugins such as W3 Total Cache, WordPress SEO By Yoast, but all of them are not loaded. Does WordPress only loads plugins which are just single files in <code> mu-plugins </code> ?
|
Does WordPress only loads plugins which are just single files in mu-plugins? No, they do not need to be single files but you cannot use plugins in their own subfolders as in the standard <code> plugins/ </code> folder. The main plugin file (one with the specified plugin header info) has to be right there in <code> mu-plugins/ </code> . Other files can be put in a subfolder and referenced from there. I used it with my own plugins. I've never tried moving any robust plugin in there. Also note that not all plugins are must-use-compatible see http://codex.wordpress.org/Must_Use_Plugins#Caveats
|
Plugins in mu-plugins folder are not loaded
|
wordpress
|
very strange problem, that happens only in one specific template. part of the part "leaks" into the tag - and I can't figure out why. the "header.php" code: <code> <!DOCTYPE html> <html lang="he"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IT=edge,chrome=IE8"> <title><?php bloginfo('name'); ?> <?php if ( is_single() ) { ?> <?php } ?> <?php wp_title(); ?></title> <meta name="generator" content="WordPress <?php bloginfo('version'); ?>" /> <!-- leave this for stats --> <!-- the site meta data for search--> <meta name="description" content="****" /> <meta name="keywords" content="****" /> <!--end of meta data--> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" /> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="<?php bloginfo('rss2_url'); ?>" /> <link rel="alternate" type="text/xml" title="RSS .92" href="<?php bloginfo('rss_url'); ?>" /> <link rel="alternate" type="application/atom+xml" title="Atom 0.3" href="<?php bloginfo('atom_url'); ?>" /> <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" /> <?php wp_get_archives('type=monthly&format=link'); ?> <?php wp_head(); ?> <!--IE specific bugs some of this doesn't work yet --> <!--[if lt IE 9]> <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script> <style type="text/css" media="screen"> body { behavior:url("<?php bloginfo('template_url');?>/csshover3.htc"); } #booklist li:hover { -moz-box-shadow: 1px 1px 5px #999; -webkit-box-shadow: 1px 1px 5px #999; box-shadow: 1px 1px 5px #999; behavior:url("<?php bloginfo('template_url');?>/PIE.php"); } </style> <![endif]--> <!--google analytics code--> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-****-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!--end of google analytics code--> </head> <body> <div id="container"> <header> <div id="header"> <!-- ืืฉืืื ืืืืืืจ ืืช ืืืืชืจืช ืืชืืืืจ ืืืืื ืืืื ืืืืจืื ืืช ืกืืื ืืืขืจื ืืhtml <h1><a href="<?php echo get_settings('home'); ?>/"><?php bloginfo('name'); ?></a></h1> <h2><?php bloginfo('description'); ?></h2> --> </div> <nav id="menu"> <ul> <li style="zoom:1" class="<?php if (is_home()) { ?>current_page_item<?php } else { ?>page_item<?php } ?>"><a href="<?php bloginfo('url'); ?>" title="Home">ืจืืฉื</a></li> <?php wp_list_pages('title_li=&depth=1'); ?> </ul> <!--<div id="menu"></div>--> </nav> </header> </code> the template code (the relevant part): <code> <!--?php /* Template Name: bookstore*/ ?--> <?php get_header(); ?> <?php get_sidebar(); ?> <div id="content"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post" id="post-<?php the_ID(); ?>"> <!-- ืืฉืืื ืืืืืืจ ืืช ืฉื ืืขืืื ืฆืจืื ืืืื ืืช ืกืืื ืืืขืจื ื# --> <h2><?php #the_title(); ?></h2> <div class="entry"> <!--<h1 style="text-align: center; "> <strong> </strong> </h1>--> <?php the_content('<p>Continue reading &raquo;</p>'); ?> <?php //if page is split into more than one link_pages('<p>Pages: ', '</p>', 'number'); ?> </div> </div> <?php endwhile; endif; ?> <div class="entry"> </code> the leaking part is everthing after the link rel="prev" be glad for any help with this
|
Can you be a little more specific on which part is 'leaking' into the body? It's hard to tell without running any code and having other parts of the theme to look at.
|
wordpress header leaks into body in a specific template
|
wordpress
|
Can I use the theme uint test data in a demonstration site for a commercial theme? Or am I only allowed to use it for internal development? http://codex.wordpress.org/Theme_Unit_Test
|
Everything on the Codex is GPL (or can be considered as GPL-compatible). Insofar as any part of the Theme Unit Test data are copyrightable, unless stated otherwise you may assume that the WordPress Foundation holds the copyright, and that the work is released under the GPL. Feel free to use it however you see fit!
|
how is the theme unit test data licensed?
|
wordpress
|
I'm integrating Mailchimp signup into a WP install and I have 2 questions. What is the best way or best plugin to integrate mailchimp signup? Is it possible to allow the user to select from multiple lists to be subscribed to. I realize the latter is more closely related to MailChimp but I'm hoping that someone has an answer for that as well.
|
The current Mailchimp Plugin for Wordpress does not allow user to select multiple lists. Infact Mailchimp discourage this practice. Instead what they advocate is to create groups within the lists and then use segmenting while sending campaigns. These links might be useful MailChimp Documentation Google Groups discussion
|
MailChimp integration that allows users to select from multiple lists
|
wordpress
|
There is a function in a theme that I am using that does some pagination stuff. I do NOT want that function to show up on my home page (only), so I'm trying to set up an if/else statement but can't for the life of me can't get it to work right. Using the following code, the function shows up not only on the homepage but also on the category pages. I am using this code in my index.php file and my site is setup to show posts from a custom post type. <code> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div>My Loop Stuff Here</div> <?php endwhile; ?> <?php if (!( is_home() || is_front_page() )) : function_to_NOT_show_on_homepage(); endif; ?> <?php else: ?> [else stuffs] <?php endif; ?> <?php wp_reset_query(); ?> </code>
|
Based on your pastes, i think what you're going for is.. <code> function cp_do_pagination() { if( is_home() || is_singular() /* || is_front_page() */ ) return; global $post; // <-- do you need this for something in particular? if( !function_exists('appthemes_pagination') ) return; appthemes_pagination(); } </code> The <code> is_singular() </code> function covers <code> is_page() </code> , <code> is_single() </code> and <code> is_attachment() </code> , so no need for the additional conditionals. Info on that function here, for reference. http://codex.wordpress.org/Function_Reference/is_singular
|
Exclude function from homepage only?
|
wordpress
|
I've just developed a calendar plugin. To display a calendar in a template, I call <code> do_shortcode(args...); </code> . This works fine. But how can I call a function from my plugin that will return data? I don't want to use <code> include_once </code> - I really just want to call a function E.g. <code> $events = calendar->getEvents(args...) </code>
|
As long as the plugin is active, the function will work perfectly fine from any template.
|
How can I call plugin function from a custom template?
|
wordpress
|
I'm working on a plug-in which will override the search results returned by Wordpress, with results from a custom XML feed. However, I'm not looking to do this on a separate page, but to replace the results Wordpress would normally display on the blogs search page with the results from my XML feed. I have been unable to find a filter or hook which would allow me to intercept or override the results wordpress returns, nor can I find one which allows me to override what is displayed on the page. My first thought was to look for something similar to the_content , but I'm unable to locate anything similar to that for use in this situation. The plug-in is going to be used by sales staff, so the plug-in needs to work in such a way that it requires as little work and technical knowledge as possible on the part of installer. My reasoning for wanting to override the results instead of inserting a new widget is that I want the plug-in to use the same search form the theme uses by default. Is this even possible? If so, how would I go about doing it?
|
You can use template_include filter hook to check if the current call is a search call and if so include your own template in which you can do what ever you want : <code> add_filter('template_include','my_custom_search_template'); function my_custom_search_template($template){ global $wp_query; if (!$wp_query->is_search) return $template return dirname( __FILE__ ) . '/my_search_template.php'; } </code>
|
How can I replace the search results displayed by Wordpress?
|
wordpress
|
Is there any way that developing a Wordpress admin panel like this would be possible? http://deanelliott.me/wp-content/uploads/account-backend.jpg My client wants it to be displayed within the website template aswell. I really don't want to have to outsource this, but I'm stumped as to how to achieve this. Any help would be greatly appreciated.
|
I second what @Viruthagiri said. You can also use the plugin Theme My Login if you want to hide the real WordPress control panel from your users and only show them their own profile/edit profile page, themed just like your site. Best of luck!
|
Extending the user profile
|
wordpress
|
Is there a plugin that can access cPanel features from within Wordpress? In particular I'd like to be able to: View bandwidth, quota and other server info from the WP Dashboard Access my webmail Access the file manager to edit files (useful for .htaccess, php.ini and non-WP files) I know I can just open a new tab and log on to my cPanel account, but it would be great if it could be integrated some how. If there isn't a plugin to achieve the above, then I suppose an easier way would be for some links to be added to the Dashboard menu (for example webmail and file manager) which would link directly to those sections in cPanel and perhaps open in an iframe. So, to recap... does a plugin exist to achieve the above (or it easy to make one) or if not, does a plugin exist (or how do I create one) that adds these links to the dashboard. Any ideas from people who use cPanel and WP on a regular basis would be helpful.
|
I do not believe there are any plugins specifically catered to cPanel, however there are a few plugins which will allow you to add an iFrame to your admin pages. I have not used any of these, and agree with the other commenter (Chip) who mentioned that it may pose a security risk. With that said, check out plugins like this: http://wordpress.org/extend/plugins/iframe-admin-pages/ search for similar: http://wordpress.org/extend/plugins/search.php?q=admin+iframe
|
How do I access cPanel features within Wordpress?
|
wordpress
|
Although the accounts on my server generally have a lower memory limit, I've configured my Wordpress user accounts with a memory limit of 32Mb using the php.ini file and <code> memory_limit = 32M </code> Unfortunately I've found that I'm still getting the odd memory error, even on small tests blogs. I've had to increase the limit to 64Mb which in my mind seems a little high for normal usage. What should be a reasonable upper memory limit to have on standard Wordpress installs with popular plugins? For your information some of the plugins that I suspect might be causing memory issues are: W3 Total Cache Role Scoper Smush.it
|
Obviously this question is a little squishy, as YMMV, but I've run several WP sites using W3TC and similar plugins to yours on 32M, and haven't had an issue. That being said, when are you typically running into issues? Is it on post submission? On gallery operations? Looking for a pattern there could be helpful. Let us know if you find one. Also remember that a limit is just that, a limit. The majority of the time your site will not be running at the max of 32 or 64M, especially with a caching plugin like W3TC installed and properly configured. PHP may burst to 64, but so long as your server can handle bursts up to that level, then you should feel comfortable with it. Generally, memory limits can be set a little higher than what you'd expect, and so long as you aren't causing your server to thrash then you are fine. Try running <code> top </code> or <code> free -m -s 5 </code> to examine memory usage over time, and see if you're constantly running close to the limit, or if it will continue fine as it is.
|
What is a reasonable memory limit for Wordpress
|
wordpress
|
I am using Wordpress for my website. I was working on CPANEL yesterday and was browsing <code> public-html/wp-admin folder </code> under the <code> File manager </code> . There were many files and I accidentally deleted the <code> admin-header.php </code> file. Where can I get an another copy of that file so that I can upload it to the same folder from where it got deleted?
|
Couldn't see a download link on the Github page for downloading single files(i don't use it so maybe i'm just not seeing it). Alternatively you can download single files for WordPress from trac. Example: http://core.trac.wordpress.org/browser/tags/3.2.1/wp-admin/admin-header.php Scroll to the bottom of the page(or hit the End key), look for the text " Download in other formats: " click the " Original Format " link below that text to download the single file. Can't hurt to have options right.. ;)
|
Where can I find admin-header.php file online?
|
wordpress
|
I created a taxonomy called "portfolio categories" for my portfolio custom post type. They're hierarchical and supposed to be behave like categories. when i'm editing a single portfolio post... i have a metabox where i can assign the proper portfolio category. It shows all categories at all the depths. but when i am on the Taxonomy page (edit-tags.php?taxonomy=portfolio-cats&post_type=portfolio) then it only shows top level categories and their immediate children... and no further. so grandchild-level categories are missing even though there are portfolio pieces assigned to them. is this default behavior? b/c i can see unlimited depths on the regular Categories page. should a hierarchical taxonomy behave the same? <code> /* * Builds the a tag taxonomies */ function create_portfolio_taxonomies() { // Add new taxonomy, make it hierarchical (like categories) $labels = array( 'name' => _x( 'Portfolio Categories', 'taxonomy general name' ), 'singular_name' => _x( 'Portfolio Category', 'taxonomy singular name' ), 'search_items' => __( 'Search Portfolio Categories' ), 'all_items' => __( 'All Portfolio Categories' ), 'parent_item' => __( 'Parent Portfolio Category' ), 'parent_item_colon' => __( 'Parent Portfolio Category:' ), 'edit_item' => __( 'Edit Portfolio Category' ), 'update_item' => __( 'Update Portfolio Category' ), 'add_new_item' => __( 'Add New Portfolio Category' ), 'new_item_name' => __( 'New Portfolio Category Name' ), 'menu_name' => __( 'Portfolio Categories' ), ); register_taxonomy( 'portfolio-cats', array('portfolio'), array( 'hierarchical' => true, 'labels' => $labels, 'rewrite' => array( 'slug' => 'portfolio','with_front' => true, 'hierarchical' => true ), ) ); //preset some categories my_add_term($postID,'portfolio-cats','Print'); my_add_term($postID,'portfolio-cats','Digital'); } add_action( 'init', 'create_portfolio_taxonomies', 0 ); function my_add_term($id, $tax, $term) { $term_id = intval(term_exists($term)); if (!$term_id) { $term_id = wp_insert_term($term, $tax); $term_id = $term_id['term_id']; } $result = wp_set_object_terms($id, array($term_id), $tax, FALSE); return $result; } </code>
|
Pretty bizarre issue. I popped in that same code and successfully replicated the issue. I then removed the calls to <code> my_add_term </code> , reset my permalinks (not sure if this helped or not but worth mentioning that I did it), added an item, reloaded, and they all showed up in heirarchy as expected. In the calls to <code> my_add_term </code> , you're passing <code> $postID </code> but that isn't defined, so I'm guessing that's where the issue is coming from. Bottom line, you don't need to define Print and Digital as your base categories with every single page load , so that code can reasonably be removed. Let me know if this fixes it for you! Cheers~
|
Edit tags page for hierarchical taxonomy doesn't show taxonomies at all depths
|
wordpress
|
I currently developing wordpress widget for my website. This widget will pull user latest post in my website and show in their blog. In the widget there is option for user to use their css or my css for the widget I use this code in my widget and its work perfectly but this code will always load the css. <code> add_action( 'widgets_init', 'load_my_widgets' ); function load_my_widgets() { register_widget( 'My_Widget' ); wp_register_style( 'my_widget_css', 'http://mydomain.com/css/my-widget.css' ); wp_enqueue_style( 'my_widget_css' ); } </code> The problem is how can I enable the CSS based on the user option? I try something like this but its not working <code> function widget( $args, $instance ) { $own_css = isset( $instance['own_css'] ) ? true : false; if ( ! $own_css ) { wp_enqueue_style( 'my_widget_css' ); } } </code>
|
This is sort of sloppy as the style will still be enqueued regardless. In the code to display your widget, change the CSS selectors based on whether or not the user selected own style: <code> <?php $prefix = $instance['own_style'] ? 'ownstyle_' : 'pluginstyle_'; //then.... ?> <div id="<?php echo $prefix; ?>selector"> ...</div> etc </code> A user would be able to use both a widget with custom style and one with default style this way. Enqueue your style separately in its own function. <code> add_action( 'wp_print_scripts', 'wpse26241_enqueue' ); function wpse26241_enqueue() { if( is_admin() ) return; if( is_active_widget( 'My_Widget' ) ) wp_enqueue_style( 'my_style' ); } </code>
|
Use wp_enqueue_style based on user option in widget
|
wordpress
|
I'm thinking about migrating a client's website from a super-old cms (xoops) to WP. However the site is quite old so I don't want him to lose any SEO juice he acquired through the years (PR: 2). Anything I'd have to consider doing the migration? (I was thinking about setting up WP on a separate folder and then moving it to root for the full migration - anything I have to consider here?) Thanks a lot! Edit: Mike Hudson (comment below) made me aware of an error. I thought PR = Ranking in the results. Meaning: I'm more concerned with the ranking than the PR, so redirect is the way to go! Thanks folks!
|
You should use a sitemap module to generate a list of URLs created by XOOPs [e.g. xSitemap ]. Then you have to set up your .htaccess to 301 redirect each URL to its corresponding page in the new Wordpress instance. Finally, you should consider installing a Wordpress plugin like Redirection to check for 404s and redirect them nicely to the new instance.
|
Migrating from other CMS to WP - losing SEO juice?
|
wordpress
|
I'm adding additional image sizes to my theme: functions.php <code> add_image_size( 'my-thumbnails', 122, 122, true ); </code> I used to get thumbnails URL like this: <code> wp_get_attachment_url(get_post_thumbnail_id($post->ID)); </code> And it works like a charm, but I'm not sure how to display 'my-thumbnails' version of the thumbnail? This doesn't work: <code> wp_get_attachment_image_src( get_post_thumbnail_id($post->ID),'my-thumbnails' ); </code> What's wrong?
|
You should use one of the following: <code> // Thumbnail wp_get_attachment_thumb_file( $GLOBALS['post']->ID ); // Custom wp_get_attachment_image_src( $attachment_id, $size='thumbnail' ); // Or: wp_get_attachment_image( $attachment_id, $size = 'thumbnail' ); </code>
|
Getting custom-sized featured image's URL?
|
wordpress
|
<code> add_action('wp_head','add_gpp_gallery'); function add_gpp_gallery() { if( ( is_single() || is_page() ) && ( !is_page_template('page-blog.php') ) ){ remove_shortcode('gallery', 'gallery_shortcode'); add_shortcode('gallery', 'gpp_gallery_shortcode'); } } </code> Hi All, I pulled the above function out of the plugin's core functions file, and I was hoping to change it to only replace the WP default gallery on my custom post type. So I changed the if statement above to: <code> if (is_single() && is_post_type('post_type'){ </code> So I changed it and put it into my functions.php - but I'm getting an error that stating that I can't redeclare add_gpp_gallery How would I override the plugin's functions without touching the plugin code? thanks EDIT I tried: <code> remove_action( 'wp_head', 'add_gpp_gallery' ); add_action('wp_head','jason_add_gpp_gallery'); function jason_add_gpp_gallery() { if ( is_single() && is_post_type('listings') ){ remove_shortcode('gallery', 'gallery_shortcode'); add_shortcode('gallery', 'gpp_gallery_shortcode'); } } </code> and I get a fatal error - Fatal error: Call to undefined function is_post_type() in /home/hostspro/public_html/movemaine.com/wp-content/themes/movemaine/functions.php on line 269 EDIT #2 I had cross wired my functions, and was forgetting to change out the is_post_type. The following code is working and thanks for the help <code> remove_action( 'wp_head', 'add_gpp_gallery' ); add_action('wp_head','jason_add_gpp_gallery'); function jason_add_gpp_gallery() { if ( is_single() && 'listings' == get_post_type() ) { remove_shortcode('gallery', 'gallery_shortcode'); add_shortcode('gallery', 'gpp_gallery_shortcode'); } } </code>
|
You can change the name of <code> add_gpp_gallery </code> function both in the callback and in the declaration to avoid the conflict between the original and your clone. Something like this... <code> add_action('wp_head','jason_add_gpp_gallery'); function jason_add_gpp_gallery() { if ( is_single() && 'your_post_type' == get_post_type() ) ){ remove_shortcode('gallery', 'gallery_shortcode'); add_shortcode('gallery', 'gpp_gallery_shortcode'); } } </code> ... should work for you. Bonus: You can remove the original plugin action with remove_action() if needed.
|
Override plugin with functions.php
|
wordpress
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.