INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Limiting post list by taxonomy I currently have the following code pulling the 10 latest posts from a specific category, I would like to filter those posts to a certain custom taxonomy which I've set up called article type. What do I need to modify to incorporate this filter? <div id="btcc" class="main-headline-box"> <h2>Features</h2> <?php $btcc_query = new WP_Query('category_name=btcc&showposts=10'); ?><ul> <?php while ($btcc_query->have_posts()) : $btcc_query->the_post(); ?> <li><a href="<?php the_permalink() ?>" title="Permanent Link to: <?php the_title_attribute(); ?>"> <?php the_title(); ?></a></li> <?php endwhile; ?><li class="read-more"><a href="">Read more from the BTCC Archive</a></li></ul> </div>
A simple search in codex shows how to do that : $args = array( 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'people', 'field' => 'slug', 'terms' => 'bob' ) ) ); $query = new WP_Query( $args ); **EDIT:** do not use `showposts`, it's deprecated.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, custom taxonomy, wp query" }
Get query result before posts are displayed? If I want to modify the query, I can use `pre_get_posts` filter. But what if I want to loop through the queried posts before they are ran through the `The Loop`? Is there a filter/action hook for that? I want to find out if all the queried posts belong to same `term` and then do something if they are not. Please note that creating a custom `Query` is not an option.
You can use the `the_posts` filter to loop through the results before they get returned. Proof of concept: function test_the_posts($a) { var_dump($a); die; } add_action('the_posts','test_the_posts'); I am fairly certain (though I haven't tested it) that you could pretty easily break pagination and probably other things by fiddling with that, so be careful.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, query, pre get posts" }
How to rename wp-includes folder? Is there a way that we could rename wp-includes folder I have found out there are ways to do for other folders. But how do we do it for wp-includes folder? <
Unfortunately not at the moment. If you look in `wp-includes/default_constants.php`, the `WP_CONTENT_DIR` and other constants all have a `if ( ! defined(constant) )` check before them. `WPINC` (the `wp-includes` constant) does not. It's defined in `wp-settings.php`, and has no `if ( ! defined(WPINC) )` check, so defining it before hand (in your `wp-config.php`) would just result in an error. Also, altering core you could do this, but as soon as you update WordPress, Core files would be reverted, and therefore it would revert back to `wp-includes`. I suggestion just masking your site with WordPress in a subdirectory (call it `xadw` or something nobody would guess) and just set the home URL to be the actual domain. Then put your `wp-content` folder in another folder, so it won't be obviously when people look at uploads, etc.
stackexchange-wordpress
{ "answer_score": 3, "question_score": -2, "tags": "include" }
automatic title through filter the template of my customer looks bad if the user doesn't add an title at the top of every page. I want to write a function to add an H1 tag automatially if H1 tags are not present. **This doesn't work!** function auto_dummy_titles($content) { if (strpos($content,'<h1>') == false) { echo '<h1>PLEASE ADD H1 TITLE TO THE PAGE</h1>'; } return $content; } add_filter( 'the_content', 'auto_dummy_titles'); **It does work just if I write 'h1' instead of ''** Why?
I don't understand why your "titles" are in the post body content, but you should not be `echo`ing content from that filter. You should be creating and returning a string. function auto_dummy_titles($content) { if (strpos($content,'<h1>') === false) { $content = '<h1>PLEASE ADD H1 TITLE TO THE PAGE</h1>'.$content; } return $content; } add_filter( 'the_content', 'auto_dummy_titles'); The function does work though. I can't help but think that the problem is that you should be checking the actual post title for a title and not the post content.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters" }
Custom Dashboard Home Screen Options I want to make the entire Homepage on the Dashboard empty and add in my own custom screen options. How do I go about doing this? Do I create one from scratch or edit what's already there? Is there some kind of codex for this, I'm not even sure what they're called... For example, If I just wanted to add a small message to the Dashboard Homepage `"Hello World"` how would I go about doing this?
Replacing the dashboard and adding to the current one are both accomplished with plugins. Fortunately, some pretty smart folks have already figured it out for us... To completely rewrite the Dashboard, you'll need to create a new page and redirect requests to the built-in dashboard page to your custom one. Fortunately, someone has already figured this out and wrote an excellent post about how to do it over at < Your second question (adding a small message) also has a good answer already in the Codex (the official WordPress documentation). It'll take you through the steps to add a new widget to the existing dashboard to display your message. <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "customization, admin, wp admin, dashboard" }
Archive template for custom post type only lists first 10 Here is my template for archive-people.com: It currently only shows the first 10 people. I'd like it to show everyone, not just the first 10 people. <?php get_header(); ?> <div id="content" class="clearfix row-fluid"> <div id="main" class="span12 clearfix" role="main"> <?php if ( have_posts() ) : while (have_posts()) : the_post(); ?> <div class="person-card"> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'thumbnail' ); ?><br /> <?php the_title(); ?></a> </div> </div> <?php endwhile; endif; ?> </div> </div> <?php get_footer(); ?> If I want it to display everyone, is that something I change in the template? Or is that something that I add to the functions.php file?
In `function.php` add_action('pre_get_posts','show_all_people'); function show_all_people( $query ) { if ( $query->is_main_query() && is_post_type_archive('people') ) { $query->set('posts_per_page', -1); } } See Codex docs for `pre_get_posts` hook
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, pagination, archive template" }
Echo custom taxonomy slug I feel like I'm _this close_ but can't figure out if it's a synax or variable thing. I'm tring to echo the slug to auto-populate the corresponding image. <?php $terms = get_the_terms( $post->id, 'series', array( 'parent' => 0 ) ); $terms_slugs = array(); foreach( $terms as $term ) { $terms_slugs[] = $term->slug; } if( !empty($terms_slugs) ) : echo "/assets/products/" . $terms_slugs. "/logos/" .$terms_slugs . "-logo.png" ; endif; ?>
Here's the correct syntax for what you're trying to do, if there's just the single value for the 'series' custom taxonomy slug that you're trying to retrieve. You were passing the whole array to your echoed string. I made a new variable $series which pulls the first/only value in the $terms_slugs array. And simplified a few other things you didn't need in there. :) <?php $terms = get_the_terms( $post->ID, 'series' ); if ($terms) { $terms_slugs = array(); foreach ( $terms as $term ) { $terms_slugs[] = $term->slug; } $series = $terms_slugs[0]; echo "/assets/products/{$series}/logos/{$series}-logo.png"; } else { echo "nothing to see here"; } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, slug, terms" }
Can YOAST SEO fields be removed from custom post type The Yoast SEO plugin is great, but it seems to appear in more places then wanted (columns, custom post type pages, etc.). I want to remove this option because as it stands even when I ignore the fields if I save my custom post type I get several fields added to my database. _yoast_wpseo_google-plus-description _yoast_wpseo_linkdex _yoast_wpseo_opengraph-description _yoast_wpseo_redirect _yoast_wpseo_canonical _yoast_wpseo_sitemap-html-include _yoast_wpseo_sitemap-prio _yoast_wpseo_sitemap-include _yoast_wpseo_meta-robots-adv _yoast_wpseo_meta-robots-nofollow _yoast_wpseo_meta-robots-noindex _yoast_wpseo_metadesc _yoast_wpseo_title So the goal is to not have them appear on the admin page at all so that they are not entered as values. Thanks in advance for any help with this
So as noted in the comments above, I found a solution and used this code to do it: function remove_yoast_metabox_reservations(){ remove_meta_box('wpseo_meta', 'reservation', 'normal'); } add_action( 'add_meta_boxes', 'remove_yoast_metabox_reservations',11 ); In this instance, "reservation" was my custom post type. And "wpseo_meta" was the ID of the metabox. So the same code can be used on any meta box on a post, page, cpt, etc. Also credit belongs to Mamaduke for his post here: <
stackexchange-wordpress
{ "answer_score": 23, "question_score": 9, "tags": "plugins, seo" }
WP Super Cache All Pages I didnt find it but is it possible to run at night all pages so the next morning the whole website is cached? Or are there other plugins who does this job? I hope someone can help me! Thanks!
Plugins such as WP Super Cache have a setting for that. It's called "pre-load", it allows you to pre-load pages and you can set an specific interval to regenerate cache. If you publish at least 3 or 4 times a week a good configuration could be every 4000 minutes.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "cron, plugin wp supercache" }
How do I find the version of WordPress I have from the source code? Given a copy of WordPress installation, how do I find out what version it is from the source code?
You can find the version in `wp-includes/version.php`, the `$wp_version` variable. It can also be found in the `readme.html` file in the root of the WordPress folder.
stackexchange-wordpress
{ "answer_score": 22, "question_score": 16, "tags": "debug, wordpress version" }
Replace category name with article id in wordpress urls I would like to know, using wordpress, how to replace the category name with the article id in the url ? For example, I have a url of this kind : And I would like to change it into : Is there anybody who know to do it ?
Try turning on Pretty Permalinks and setting it to `%post_id%/%postname%`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls" }
Passing arguments in add_action inside search template I'm trying to pass a argument to the function. But it is not transmitted. var_dump produces `string'' (length = 0)` What am I doing wrong? $map_vars = 'Test'; function map_data($data) { var_dump($data); } add_action('wp_footer', 'map_data', 10, 1); do_action( 'map_data', $map_vars );
The footer doesn’t run in the global context, so the variable `$map_vars` is not in the correct scope. To keep the variable and the callback in the same scope, you could use a class: class Map_Var_Example { public static $map_vars; public static function map_data() { var_dump( self::$map_vars ); } } Map_Var_Example::$map_vars = 'Test'; add_action( 'wp_footer', array( 'Map_Var_Example', 'map_data' ), 10, 1 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "actions" }
Implications of changing wordpress.com associated with Jetpack Our corporate blog has the Jetpack plugin and it is associated with my personal wordpress.com account. I'd like to change it to our corporate wordpress.com account. If I do that then will I lose the site statistics from before the switch?
Your stats and subscribers are stored on WordPress.com, and associated to your site URL. The WordPress.com account used to connect Jetpack to WordPress.com doesn't matter. If you disconnect Jetpack from WordPress.com and then reconnect with another WordPress.com account, all the data associated to that site URL will be back in your dashboard. You won't lose any data.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wordpress.com hosting, plugin jetpack" }
Different coloured navigation links in Twenty Eleven themes I'm working on a website for a friend with small changes. She's running Twenty Eleven theme an she wants to make each link's bottom border (that I'll be putting in soon) a different colour. However with the CSS I'll be putting in, I only know how to make all of them a singular colour like this - < Is there a plugin or some extra code I can put into the navigation code of this theme to allow for this effect?
You can add custom html classes to each menu item and then use those classes to add the bottom border. In the Admin Dashboard, under Appearance, click on Menus. Select your menu and click the small down arrow to the right of the menu item box. If the CSS Classes box is missing, Click the Screen Options tab at the top of the page and check the `CSS Classes` option. In the CSS Classes box add the class for the color of the bottom border you want to used. For example `nav-yellow`, `nav-green`, etc. In your style sheet, add the corresponding class styles: .nav-yellow { } .nav-green { }
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "navigation, theme twenty eleven" }
Where to place PHP for shortcodes My custom plugin is broken into two parts: a frontend.php and admin.php for loading code conditionally. Here is a rough outline of the code: <?php /* My plugin info here */ if (is_admin()) { include_once('admin.php'); } else { include_once('frontend.php'); } ?> I have written several shortcodes for use in pages and posts. In which file (admin.php or frontend.php) should code related to shortcodes be placed?
Shortcodes are processed on display so the code must be available on the front end when the shortcode is processed. Superficially, that means `frontend.php`. I have never tried to split shortcode code in this way. You may have trouble splitting it off from the backend. The `add_shortcode` function is in `wp-includes/shortcodes.php` which loads for both back and front, suggesting that it is at least possible that it is needed on the back end. I'd have to run some experiments...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, shortcode" }
Can't remove a widget from admin I've just updated to WP 3.6, and I have also just turned off network mode on a Wordpress website. I cannot remove a widget I created. It is a text widget. I can't remove a search widget either. I am logged into WP with the same username that create the widget. Any ideas?
This symptom was caused by the plugin "Widget Logic Visual". Deactivating this plugin resolved the issue.
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "widgets" }
How to get posts and comments amount per hour, per year and per month? I have this snippet: function count_user_comments_today( $uid ){ global $wpdb; $today = date('Y-m-d'); $tomorrow = date('Y-m-d', time() + 86400); $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->comments} WHERE user_id = %d AND comment_date >= %s AND comment_date < %s ", $uid, $today, $tomorrow )); return $count; } But this get's the comments per day and that for a specific user. I want it to be generic, for the whole site and per hour, per year and per month.... Is this possible? Of course also the posts and not only the comments.
For comments: function count_comments_in_period( $date_from, $date_to ){ global $wpdb; $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_date >= %s AND comment_date < %s ", $date_from, $date_to)); return $count; } Just use dates in `yyyy-mm-dd` format. For posts: function count_posts_in_period( $date_from, $date_to ){ global $wpdb; $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_date >= %s AND post_date < %s ", $date_from, $date_to)); return $count; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, query, get posts, comments" }
Remove wp-mediaelement.css from wp_head I´m customizing the new core audio/video player via CSS in my _styles.css_. I tried to remove the _wp-mediaelement.css_ with the following code in functions.php, because I don´t need it anymore. function custom_deregister_styles() { wp_deregister_style( 'mediaelement'); } add_action( 'wp_print_styles', 'custom_deregister_styles', 100 ); The problem is, that this function removes the call of _mediaelementplayer.min.css_ and _wp-mediaelement.css_. The following doesn´t work, too. function custom_deregister_styles() { wp_deregister_style( 'wp-mediaelement'); } add_action( 'wp_print_styles', 'custom_deregister_styles', 100 );
Move those declarations out of the action. Simply paste both of them in the functions.php file and it will work (tested). wp_deregister_script('wp-mediaelement'); wp_deregister_style('wp-mediaelement');
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "php, functions, video player" }
Error: call_user_func_array() expects parameter 1 to be a valid callback I have issue after upgrading my wordpress to 3.6 see below for errors which displays on wordpress admin panel not on front of website. > Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘regis_options’ not found or invalid function name in wp-includes/plugin.php on line 406 > > Warning: Cannot modify header information – headers already sent by (output started at wp-includes/plugin.php:406) in wp-includes/option.php on line 571 > > Warning: Cannot modify header information – headers already sent by (output started at wp-includes/plugin.php:406) in wp-includes/option.php on line 572
Somewhere in your theme or plugins is a line like this: add_filter( 'something', 'regis_options' ); Could also be `add_action()`. Find that piece of code and remove or fix it. The other errors are a result of the first one. The printed error message causes output and hence HTTP headers, so PHP/WP cannot send other headers anymore. They will go away when you fix the first error.
stackexchange-wordpress
{ "answer_score": 13, "question_score": 10, "tags": "plugins, errors" }
How can I show custom field according to taxonomy? How I can show custom fields in my theme according to category? For example in Laptop category show some custom fields and in Motherboard category show another fields.
In your loop use `has_term( $term, $taxonomy, $post )`. 1. Check if the post has the term you are searching for. 2. Check if there is a value for the custom field. 3. Print the value, but don’t forget to escape it. if ( has_term( 'blue', 'product_color', $post ) ) { $field = get_post_meta( $post->ID, 'field_name', TRUE ); if ( ! empty ( $field ) ) echo esc_html( $field ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, custom field, post meta" }
Display Search Result Count Until now I have been using below code to get the number of results when someone searches and to display that count. <?php /* Search Count */ $allsearch =& new WP_Query("s=$s&showposts=-1"); $count = $allsearch->post_count; echo $count . ' '; wp_reset_query(); ?> But this does not seem like valid code. It shows below error: Deprecated: Assigning the return value of new by reference is deprecated Can anyone please suggest the proper way in which I get get the search count. The above code is placed in the heading of my index.php file of theme within a conditional statement to display different heading based on what type of page a user is on.
If you are within the search template i.e Search query is your main query. You should then be able to get search results from global `$wp_query` without running an additional query. global $wp_query; echo $wp_query->found_posts.' results found.'; **Edit 1** If you have to get count out of search context. You can combine both techniques to get efficient result. It wont fetch all the post but you can get the search count. $allsearch = new WP_Query("s=$s&showposts=0"); echo $allsearch ->found_posts.' results found.'; **Your Error** About the error you are getting, it lies here $allsearch =& new WP_Query("s=$s&showposts=-1"); Remove the "&" beside the equal sign to get rid of the error. So it will look like this $allsearch = new WP_Query("s=$s&showposts=-1");
stackexchange-wordpress
{ "answer_score": 43, "question_score": 21, "tags": "theme development" }
Making a thumbnail if there exist a link with. jpg or .png extension in Wordpress I have changed my question. I was wrong. Check it out I'd say. Is this possible to make a thumbnail if a link contains a `.jpg` (or `.png`) extension? I want to make it a thumbnail automatically if there is a link like < \--> make this a thumbnail. If it's possible, how can I do this and solve the problem? I have found this, but it's not for `Wordpress`, I guess. $extension = pathinfo($filename, PATHINFO_EXTENSION); // Read source image if ($extension == ('jpg' || 'jpeg')) { $source_image = imagecreatefromjpeg($filename); return '1'; } else if ($extension == 'png') { $source_image = imagecreatefrompng($filename); return '2'; } else { return 'error'; }
1) Check out: < 2) I found that WP function to be somewhat limited to I wrote my own wrapper class/method. If you want to do the same you're going to need PHP's copy() function < as well as WP's wp_insert_attachment() < Unfortunately, I haven't pushed my code to GitHub just yet, so for now you'll have to put something together yourself.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, post thumbnails, links, thumbnails" }
how to create my own edit.php admin page code or template for my custom post type Most plugins try to hide the components of the edit.php screen on wp admin and replace it with meta boxes to create the needed layout and fields for the custom post type. But this means that there is still unnecessary code on that edit.php page not used and increases the page load. Also, Not everything can be done using meta boxes. Is there is a way where i can create my own edit.php page from scratch for my custom post type? maybe hide the custom post type UI and make a new admin page and use it to insert the custom posts or update it? is this possible on admin pages?
When you register the CPT set `show_ui` to false. For example: $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => false, // <-- here 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'book' ), 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => null, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ) ); You will now _have to_ construct an interface for the CPT just as you'd construct one for a admin plugin page. You are _not_ reconstructing or editing `edit.php`. Your interface will have a different address as given when you register the admin page.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom post types, wp admin" }
Add social media icon in header area I have installed the Swift Theme. I want to know how to put a social media button on the right of the logo. I have not much knowledge of theme editing.
This thread seems to answer your question < 1) Enable header ad 2) Insert some HTML to render the social media links and icons
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, social sharing" }
How do I show sticky posts on a static front page that also contains content? In my theme, I'm using `front-page.php` for the static front page. I'm also using a page to store the content on the static front page. The `front-page.php` file is set up to show the content from that page. However, in the `front-page.php` file, I also want to show all of my blog's sticky posts below that content. How would I do that?
Something like this should work: $sticky = get_option( 'sticky_posts' ); if ( !empty( $sticky ) ) { // don't show anything if there are no sticky posts $args = array( 'posts_per_page' => -1, // show all sticky posts 'post__in' => $sticky, 'ignore_sticky_posts' => 1 ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { $query->the_post(); // display your sticky post here (however you like to do it) } } You should place this in your `front-page.php` file. It will select all sticky posts and show them.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "theme development, frontpage, sticky post" }
wp_enqueue doesn't load dependencies I'm trying to load style.css but rest.css should be included first. I don't understand why reset.css is not included function addMyScript() { wp_register_style('style', get_template_directory_uri().'/style.css'); wp_register_style('reset', get_template_directory_uri().'/reset.css'); wp_enqueue_style('style', get_template_directory_uri().'/style.css', array( 'reset' ), ); } add_action('wp_head', 'addMyScript'); Also I've seen on some blogs that people often don't register the stylesheet or javascript before to enqueue... is that ok?
You have to define the dependencies for either styles or scripts when you register them. Or, if you're avoiding the registration completely, then it's ok to stuff them into the queueing process. See more on the Codex page. wp_register_style( 'reset', get_template_directory_uri().'/reset.css' ); wp_register_style( 'style', get_template_directory_uri().'/style.css', array( 'reset' ) ); wp_enqueue_style( 'style' ); Also avoid single `,` inside a function argument definition. This will not work. Better turn on Debugging stuff in your `wp-config.php`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp enqueue script, wp enqueue style, wp register script, wp register style" }
How could I write a get_categories_by_year() function? I need to write **a function to get all the categories for a given year**. Since the creation date of a taxonomy isn't stored in the database, I'm not really sure what to do. My initial thought was to get all posts for a given year and somehow find all categories associated with those posts, but I'm not sure how to do that and it sounds horrifically slow. Perhaps I could just write some SQL but I'm much more well versed in PHP. So again back to the function, I imagine it would like something like: function get_categories_by_year($year) { // Do stuff... return $array_of_categories_in_year; } This is actually for a custom taxonomy but since categories are the default hierarchical taxonomy I decided to use it as an example. I'm happy to provide more info on what the output is supposed to look like if it's relevant. Thank's for the help!
I would do this with SQL query. Doing it in PHP will be a little bit slow, I guess. This function should do the job: function get_categories_from_year($year) { $sql = "select term.* from {$wpdb->terms} term inner join {$wpdb->term_taxonomy} tax on (term.term_id = tax.term_id) inner join {$wpdb->term_relationships} relation on (tax.term_taxonomy_id = relation.term_taxonomy_id) inner join {$wpdb->posts} post on (relation.object_id = post.ID) where tax.taxonomy = 'category' and YEAR(post.post_date) = %d"; return $wpdb->get_results( $wpdb->prepare($sql, $year) ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, custom taxonomy, taxonomy" }
Why links are not linked if edited comment? I am using the plugin `front end editor` to edit posts.. This works very well in posts, where all links are perfectly visible if I have edited a post. For some reason, if I edit a comment and there are links in the post, I can't see the links and can't click on them because it's not linked. I must refresh the page to see the comment linking to where they were linking... Is there a solution without having to refresh the page? Why is this happening at all?
The plugin author has solved the issue. He says: > I have encountered this bug before, but I just now realized what's causing it: the 'comment_text' filter is not applied on the updated comment content. The make_clickable() function, which makes the links in the content clickable, is hooked to this 'comment_text' filter. > > Anyway, it's fixed now: < > > You can try out that fix by downloading the Development Version (2.3.2-alpha).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, comments, urls, links, comments template" }
Wordpress 3.6 - archive.php doesn't get triggered I made a custom theme and just created an archive.php file. When I try to access ` for example it just triggers my index.php template. The link was generated by `wp_get_archives()` and should be right. What am I doing wrong?
Generally this is a plugin that causes this. Best way is to disable them one by one. Maybe the plugin has a template which is overriding it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "archives, wp get archives, archive template" }
Animate like Stack exchange frequently asked questions < As you scroll down the page, images and text slowly fading. Is there a plug-in origin jquery like string that I should be looking for?
The most common method is based on scroll position and if the item is visible. When it becomes visible they fire an event. Here's an answer with a bit of code I'd check out. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "plugins, jquery" }
How to center oEmbedded content I understand you have to paste the link that you're embedding without any code wrapping around it, but how do I force the embedded content to be centered? Currently, the default is aligning to the left. I could modify the core file, but it's highly discouraged, so I'm asking to see if there's any hook or filter to get around this. Thanks!
After some Googling, I found a solution that was originally done for a Twitter embed, but I modified it to work with all oEmbed contents. Keep in mind that for this to work on existing posts, you'll need to do an "update" for the oEmbed content to refresh from the cache. add_filter('oembed_result','center_oembed',10,3); function center_oembed($html, $url, $args) { $html = '<p style="text-align: center;">' . $html . '</p>'; return $html; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "filters, hooks, formatting, css, oembed" }
As a plugin developer, how to deal with theme developer loading jquery from google? Theme developers like to deregister wordpress jquery and load jquery from google instead. I've been told it is for speed and I agree. This usually is not a problem **for me** since I always use **jQuery** instead of **$**. But I do see some plugins try to use **$** , well, it generates javascript error and also makes my plugin not working. As a result, clients blame on innocent me. Sometimes my js code depends on the version of wordpress jquery but theme developers tend to load **a specific version** from google. Even though the theme is updated, they may not update the jquery version, not to mention an old theme. **What should I do in such situations?** Actually, I'm thinking about, maybe I should use Zepto.js instead and include it in my js code. p.s. good news, wordpress 3.6 doesn't allow deregister jquery in its backend.
Any Theme developer that dequeues core-bundled jQuery in order to enqueue some other version - _any_ other version, bundled, CDN, etc. - is `_doing_it_wrong()`, period. Core, active Theme, and active Plugins all rely on a _known version_ of jQuery being available. What to do about it? 1. Tell the Theme developer that he's `_doing_it_wrong()`, and ask for a fix. 2. Tell your Plugin users to use a Theme hosted in the official WordPress Theme directory, since every Theme hosted there is prohibited from dequeueing core-bundled jQuery 3. Instruct your Plugin users how to override the Theme's jQuery override, via a site functionality Plugin that dequeues the _Theme's_ custom jQuery, and _re-enqueues_ core-bundled jQuery 4. Instruct your Plugin users how to patch the Theme's incorrect jQuery implementation, by adding _no-conflict wrappers_
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "jquery" }
What is the difference between Null vs Empty (Zero Length) string? In a shortcode context, is there any difference here? array( 'slideshow' => '', ), and array( 'slideshow' => NULL, ), Is there a best practice for that?
If the 'slideshow' key is normally supposed to contain a string value, but you want to give it an empty value, then give it the empty string. The empty string is still a string data type, so it is more likely to react the way you expect in a string function. The null value is not a string, and if you don't have more information on how it is used, may or may not behave the way you want it to.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, plugin development, shortcode" }
How to prevent a function from running based on host (ie web vs local)? I am using LiveReload to refresh my browser and compile my SASS. The browser extensions are not working so well for me, so I am adding the script to my footer. I'm trying to think of a way to prevent the function that adds it from running if it is on a live web server opposed to my local production environment XAMPP (in OSX 10.6.8). This is what I have now: if (! function_exists('_sf_live_reload') && ! is_admin() ) : function _sf_live_reload() { ?> <script>document.write('<script src=" + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1"></' + 'script>')</script> <?php } add_action('tha_body_bottom', '_sf_live_reload'); endif; Yes, I know I could just remember to manually delete it before uploading, but lets assume I forge things from time to time. Plus deleting and recreating this over and over again isn't the best solution anyway.
$whitelist = array('127.0.0.1'); if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){ // not valid } For more info on how it works. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, server, xampp" }
What is the best way to include a template file within a shortcode? I'm writing a shortcode for a child-theme. I want to load a php template file to generate my HTML and then output this HTML in a string to return this string. But I don't know the best way to do this. The Codex mentions the `ob_start` function but it seems to me a bit dirty. Are there any template functions (like those in PHP frameworks when you load a view) to do this?
WordPress doesn't bundle any "templating engine" libraries like Mustache or Smarty, as far as I am aware, and frankly I have not been sold on the need for them. (Yes, I know its all the rage.) Concatenate your own strings, use PHP native functions like `ob_start` or `sprintf`, or load your own templating library. I have seen plugins do that. I just recently saw one that loaded Mustache, and there is a WordPress plugin purporting to make Smarty available.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode" }
Custom post types: change "read more" text I'm developing a website that has a blog section as well as a "free monthly download" section set up as a custom post type. On the home page I'm displaying excerpts with "read more" links for both the most recent blog post and the most recent monthly download (these are in separate loops). The read more link is generated automatically by this code in my functions.php file: function excerpt_read_more_link($output) { global $post; return $output . '<a class="more-link" href="'. get_permalink($post->ID) . '">Read more</a>'; } add_filter('the_excerpt', 'excerpt_read_more_link'); This is working fine, but I'd like "read more" for the custom post type excerpt to read "Get it now". Any suggestions for how to have different "read more" text for the blog post excerpts and the custom post type excerpts? Thanks in advance.
Hmm, and what is the difficulty in here? You already have `global $post` variable in your function. Just use it. function excerpt_read_more_link($output) { global $post; $text = 'Read more'; if ( $post->post_type == 'MY-CUSTOM-POST-TYPE' ) // change MY-CUSTOM-POST-TYPE to your real CPT name $text = 'Get it now'; return $output . '<a class="more-link" href="'. get_permalink($post->ID) . '">'. $text .'</a>'; } add_filter('the_excerpt', 'excerpt_read_more_link'); Of course you can put multiple such if statements in there.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, read more" }
Get author id from url I am trying to get the authors `user_id` on a page linked to by using `get_author_posts_url(),`. For example where `John Smith` is `user_id` is `23`. I need to get `23`.
On an "author" page `get_query_var('author')` will give you the ID. `get_queried_object()` will get you considerably more author information. $author = get_queried_object(); echo $author->ID; // var_dump($author); // to see all of the information available. For retrieving custom author data follow the Codex.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "author template, users" }
Church hope them issue I'm using the church home theme and can't figure out how to modify the three images under the download button page. < they say life groups , New here, Every Penny helps The appear on my home page and its the default content.
Your theme calls these "Teasers," and they are set by using shortcodes on your home page. More info can be found on your theme's online documentation.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "themes, theme options" }
Wp_redirect and sending variables How to send some variables with wp_redirect() from function.php file in my theme folder? if ( $post_id ) { $variable_to_send = '1'; wp_redirect( home_url(), $variable_to_send ); exit; } And on homepage I will catch the variable in if-else condition to show some confirmation or not depending if `$variable_to_send` = '1' or not. How to do that in WordPress?
I'm afraid that you can't do it this way. `wp_redirect` is a fancy way to send header `Location` and the second argument of this function is request status, and not custom variable. (404, 301, 302, and so on). You can send some variables as get parameters. So you can do something like this: if ( $post_id ) { $variable_to_send = '1'; wp_redirect( home_url() .'?my_variable='.$variable_to_send ); exit; } Then you can use these variables as `$_GET['my_variable']` or register it as custom get variable.
stackexchange-wordpress
{ "answer_score": 14, "question_score": 15, "tags": "wp query, redirect" }
Admin ToolBar not being displayed at top of site Not sure what's going on, but even when I checked the "Show Toolbar when viewing site" and on functions.pho placed: `if (! current_user_can('manage_options')) { add_filter('show_admin_bar', '__return_false'); }` I can see the space where the admin bar is supposed to be placed but it is empty, a white bar, nothing on it, checked the source code and found this: `<style type="text/css" media="print">#wpadminbar { display:none; }</style> <style type="text/css" media="screen"> html { margin-top: 28px !important; } * html body { margin-top: 28px !important; } </style>` So not sure what else to do, any help? Thanks! A.
It sounds like your theme does not use `wp_footer()` the way it should. That function should occur right before the closing `</body>` tag. The admin bar runs on a hook fired by that function. Without it, I get exactly what you describe. For reference, in Twenty Thirteen, it looks like this: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, theme development" }
The best way to collision check in WP E.g. I have a random number generated by a PHP code `$random` And I need to make a check if this number doesn't exist in any of my posts in DB in my meta field called `unique_code` What is the preffered way in WP to check if this value(random number) exist or not?
I don't think there is a built in mechanism for searching the meta table for a `key`/`value` pair other than a full blown post search with `WP_Query`. I'd consider that overkill. Just query the table: $unique = $wpdb->get_var( "SELECT meta_id FROM {$wpdb->postmeta} WHERE meta_key = 'unique_code' AND meta_value = '{$random}' LIMIT 1" ); I can't help but think that more detail in the question might point to a better way to proceed
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, wp query, query" }
How Does Wordpress Remember Metabox Positions? I was wondering how Wordpress remembers the position of metaboxes: session basis, user basis, computer basis? Does it set a cookie? Is it saved in the database?
WordPress saves them in the databas in wp_usermeta as serilized array. For the dashboard all are registered in **meta-box-order_dashboard** if the meta-box(s) are in **metaboxhidden_dashboard** they will _not_ be shown. The order will be as saved in database and if not in **metaboxhidden_dashboard**. Example the dashboard: **KEY** : meta-box-order_dashboard **VALUE** : Array ( [normal] => dashboard_right_now,dashboard_recent_comments,dashboard_incoming_links,dashboard_plugins [side] => dashboard_quick_press,dashboard_recent_drafts,dashboard_primary,dashboard_secondary [column3] => [column4] => ) **There are also these meta_key(s):** * meta-box-order_dashboard * metaboxhidden_dashboard * meta-box-order_page * metaboxhidden_page * metaboxhidden_nav-menus * meta-box-order_{custom_post}
stackexchange-wordpress
{ "answer_score": 10, "question_score": 8, "tags": "metabox" }
Set posts per page for parent category and it's all children I am trying to use the following function to set the number of posts per page for a specific category and all it's children: function hbg_category_query( $query ) { if( $query->is_main_query() && $query->is_category()) { if (is_category( '14' ) || cat_is_ancestor_of( 14, get_query_var('cat'))) { $query->set( 'posts_per_page', 32 ); } } return $query; } It works for the parent category and it works if I specify the ID(s) of the child categories, but I am trying to catch all the child categories (even new ones). Can anyone clarify what I am misunderstanding about how this works? Thank you, Greg
You want `get_term_children`. function hbg_category_query( $query ) { if( $query->is_main_query() && $query->is_category()) { $categories = get_term_children(1,'category'); $categories[] = 1; // add your special category if (is_category($categories)) { $query->set( 'posts_per_page', 32 ); } } return $query; } add_action('pre_get_posts','hbg_category_query'); Barely tested, but I think that will work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "query, pre get posts" }
Theme Check gives: Required: This theme doesn't seem to display tags? I am testing my theme with _Theme Check plugin_ and it shows this message: > Required: This theme doesn't seem to display tags? Picture: !enter image description here How can i fix this?
You need to be using one of these functions to display a list of tags associated with the post: * `the_tags()` * `get_the_tag_list()` * `get_the_term_list()` Otherwise the check will fail. If you're building this theme for use with a project that doesn't need tags, don't bother adding support. If you're intending on uploading it to WordPress.org for review, then you need to add support for tags.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "theme development, tags, testing" }
Recent post on single page from specyfic category i have problem. I use this code before comment form. <?php global $post; $args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); ?> <?php the_permalink(); ?><?php the_title(); ?> <?php endforeach; ?> I have in `single.php`: 1 -- post content 2 -- recent post 3 -- form comment But when i comment something my comment is not on post but was added to last **recent post**. How can i do this? I tried to use this: <?php $args = array( 'posts_per_page' => 1, 'category__not_in' => array( 23, 24 ) ); $recent_posts = get_posts( $args ); foreach ( $recent_posts as $recent ) { echo '<a href="' . get_permalink( $recent ) . '">Latest Post</a>'; } ?>
You should add `wp_reset_postdata` after outputting your recent posts.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "recent posts" }
Loop not showing first post I've set up the following loop on a page, but it is missing out the first post. Does anyone know why this might be? <div class="gallery"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="gallery-item"> <a href="<?php esc_url( the_permalink() ); ?>"> <?php the_post_thumbnail('thumbnail'); ?> <div class="view-item"> <span> <h2><?php the_title(); ?></h2> <p>View project</p> </span> </div> </a> </div> <?php endwhile; ?> </div> <?php bones_page_navi(); ?> <?php endif; ?> </div>
It looks OK to me. There is nothing wrong with this part of your code. Maybe some earlier part is doing something strange with your `$wp_query` variable. You can try to add `rewind_posts()` before your loop - it should help. Just place `rewind_posts();` just before `if (have_posts())...`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, loop" }
Show content if page is a grandchild of top level page I'm looking to show a certain block of content if the current page is a grandchild of a top level page. This is my current page heirarchy; - Top Level Page - Child Page - Grandchild Page - Grandchild Page - Grandchild Page - Child Page - Grandchild Page - Grandchild Page - Grandchild Page - Child Page - Grandchild Page - Grandchild Page - Grandchild Page So the top level page has 3 children, each of which have 3 children of their own. How can I target ONLY the grandchildren?
Check how many ancestors the page has via `get_post_ancestors`: // grandchild pages will have two or more ancestors if( 2 <= count( get_post_ancestors( $post->ID ) ) ){ echo 'grandchild page'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, query, conditional tags" }
Wordpress uploads folder path. how it is decided? I know that if we are adding a new media in the month of August, it will be uploaded to `/08` folder under `/uploads`. But here i am facing a new issue. I wrote a page in the month of June(6th month). Today, that is in August I am trying to upload a new image to that page by clicking "Add media" button. I get the media uploader popup. I can select the file and click on upload. Then what happens is that the uploader shows this error message: > "The uploaded file could not be moved to /var/www/vhosts/ ** _*_ ** _*_ ** _*_**.com/httpdocs/wp-content/uploads/2013/06" Why it is trying to move to the path `/06` when i am trying to upload the file in the month of August. Also, why is the uploading failing?
When you uploaded an image within the Edit Page screen for a page with a date of 06/01/2013, the media uploader will use the date of the page to set the sub-directory within the uploads folder. This is expected behavior because the media uploader passes the post_date to the wp_upload_dir() function. See < If you were to upload the image using just the media uploader, but NOT within a page or post, the file would be moved into the appropriate folder for the current date. Check the permissions on the uploads folder and the 06 sub-folder. The uploads folder and included sub-folders should be set to 755.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "uploads" }
Wordpress use of @ in core files I am studying twenty_eleven theme and have some quesions. What is * @package WordPress * @subpackage Twenty_Eleven * @since Twenty Eleven 1.0 */ What is the use of @ mean. And again. * @uses load_theme_textdomain() For translation/localization support. * @uses add_editor_style() To style the visual editor. * @uses add_theme_support() To add support for post thumbnails, automatic feed links, custom headers * and backgrounds, and post formats. * @uses register_nav_menus() To add support for navigation menus. * @uses register_default_headers() To register the default custom header images provided with the theme. * @uses set_post_thumbnail_size() To set a custom post thumbnail size. * * @since Twenty Eleven 1.0 */
The @ in header comments is the PHP Documentor meta data style. This syntax allow you to specify different kind of information: * package and subpackage with @package and @subpackage allow you to define what is the context for the current file (used for PHP 5.3 namespaces like in the Java syntax) * author with @author, copyright with @copyright and licence with @licence to specify how can be used the given source code * description with @description and version with @version to follow library details * deprecated with @deprecated to prevent API modifications Here the PHP Documentor reference: < These comments are also used by wordpress to extract and import meta data as you can see in the style.css file of your studied theme but it's not the same syntax (only labels and colon without @)
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "themes" }
How to use the bbPress import tool I have used example.php to create a custom importer for Social Engine 3 to bbPress Forums but I don't seem to be having any success using it. What am I doing wrong? I enter server ip, name, port, username, and password but the import never gets past "Starting Conversion". When I select another platform's importer, I get errors saying there is no forum to import (which would be right because the table names/fields don't exist). What should I try? My attempt at the custom importer is here: < Edit: Firebug shows that starting conversion caused 500 Error.
< This post has helped me greatly. Thanks Steven.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "bbpress, forum" }
Getting the Product object in a custom loop I am currently building a Theme for a site that is using `WooCommerce` to provide a Shop to Customers. I have just started on it, and I am currently working on the Product Category pages. I have hit a road block trying to fetch the WooCommerce Product object. I have read that using the variable `global $product` should return the WC_Product object, but when I do `the_post(); var_dump($product)`, `NULL` is returned. I tried to then create a Product object by doing `the_post(); $product = new WC_Product(get_the_ID())`, but when I did the `var_dump($product)` on that, it gave me general information about the product (`post_name`, `post_description`, etc), but nothing further than if I called `get_post()`. Can someone tell me what I have missed please?
Sorry, I have almost instantly found the solution. Thought about deleting the question, but in case others have the same problem, I will leave it here. To get the Product object with all the required attributes, you need to call `get_product()` after `the_post()`, and that will return the Product object for you to use.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins" }
Remove comment section from new page I am taking over a wordpress website at work. All of the pages currently do not have a 'Leave a Reply' comment section. When I make a new page, this section exists on the new page. How do I remove it? As far as I can see all of the options as far as the page goes are the same. I have already tried to uncheck 'Allow people to post comments on new articles' but it didn't do anything
If you want to be rid of comments on your site, one option is to remove the code from your theme files. You would need to search single.php, home.php, page.php, _etc._ within `wp-content/themes/*your-active-theme*` and find: <? php comments_template(); ?> Remove that and the comments section should disappear. _NOTE: this change will be undone if you update the theme files. Modifying a child-theme is a much better practice._
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pages, comments, page template" }
JavaScript Libraries in WordPress I understand that in order to use a JavaScript library in WordPress, such as jQuery, we have to use the following code to prevent conflicts: function my_scripts_method() { wp_enqueue_script( 'jquery' ); } add_action('wp_enqueue_scripts', 'my_scripts_method' ); But how do I go about using a library that is not in the list of defined WordPress libraries. I am in particular interested in using the library at pikachoose.com which depends on jQuery, and must be intialized after jQuery. How do I go about that?
This is how you should do this: function my_scripts_method() { wp_enqueue_script( 'pikachoose', // this is your custom name for this JS lib get_stylesheet_directory_uri() . '/js/pikachoose/jquery.pikachoose.min.js', // this is the url address of it's file (let's say you put it in your theme directory under /js/pikachoose/ directory array( 'jquery' ) // it depends on jquery ); } add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); You can find full reference of `wp_enqueue_script` here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, wp enqueue script, scripts" }
[class*="content"]:before css styles in TwentyThirteen i found this css style in css stylesheet od TwentyThirteen theme, i search a lot in WP forum and w2schools and even w3c but i can't find any thing like that. what that means
It is a CSS3 Substring matching attribute selector. See section 6.3.2. Substring matching attribute selectors in the W3C document: Selectors Level 3. Quote: > [att*=val] > Represents an element with the att attribute whose value contains at least one instance of the substring "val". If "val" is the empty string then the selector does not represent anything.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "css, theme twenty thirteen" }
Catchable fatal error on 3.6 update Trying to debug the situation. Getting close, but will need a little help!! Here is the error: Catchable fatal error: Object of class WP_Error could not be converted to string in /home/website/public_html/wp-content/themes/Alexia/lib/functions/common.php on line 97 And my code from the error: // no cache files - let's finally resize it $new_img_path = image_resize( $file_path, $width, $height, $crop ); line 97--> $new_img_size = getimagesize( $new_img_path ); $new_img = str_replace( basename( $image_src[0] ), basename( $new_img_path ), $image_src[0] ); // resized output $vt_image = array ( 'url' => $new_img, 'width' => $new_img_size[0], 'height' => $new_img_size[1] ); return $vt_image; } // default output - without resizing Thanks in advance NINJAS!!
`image_resize` (deprecated) is returning an error object so really, the problem is here: `$new_img_path = image_resize( $file_path, $width, $height, $crop );` Something is wrong with that line and you are not checking whether the return value is an error object or a string before trying to use the return value as a _string_. You did not post any code that might help me work out what is wrong with `$new_img_path = image_resize( $file_path, $width, $height, $crop );` but at the very least you should do: $new_img_path = image_resize( $file_path, $width, $height, $crop ); if( !is_wp_error()) { $new_img_size = getimagesize( $new_img_path ); // ... Converting to use `WP_Image_Editor` would be wiser though.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, wp error" }
Twenty Eleven Theme I have edited the pages and categories to all look the same and have a right sidebar, so when I click to a page or category they are same layout and also search results and archives and tag archives. However when I click on the post title or posted on date the layout is different (no sidebar). Does anyone know how I can make this look the same as other pages/categories with the right sidebar or which file I need to edit in the directory?
Add <?php get_sidebar(); ?> to `single.php` in the same place as the other files, i.e. right before <?php get_footer(); ?> You also need to go to style.css, and remove the margins for .singular and .singular #content, .left-sidebar.singular #content. In version 1.5 of this theme css only has, .singular #content, .left-sidebar.singular #content Plus you need to take the margin: and width: set for #primary{} ID and copy/paste to .singular #primary{}
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, pages" }
Why do Metabox use Nonces? Why is it advised for admin panel metaboxes to use nonces? Every example I see of creation and saving metabox data there are nonces involved but aren't nonces a bit unnecessary in this case?
WordPress nonces are meant to prevent unauthorized execution of code. In the case of meta boxes, they are protecting you against malicious users potentially adding unauthorized meta-information to your posts and pages by forging POST requests. Why _wouldn't_ you want to use nonces?
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "metabox, wp admin, security, nonce" }
Display Custom Field for a Specific Role, but not for Admin How do I display a custom field for a specific role, but not display it on the profile page of the admin? When admin goes to edit a profile user that this role, the field will visible. I created two fields for Subscriber role, but the fields appears on admin profile page. I need to display these fields only if admin goes to the profile page of subscribers. function show_custom_field_for_subscriber(){ if( current_user_can('administrator') || current_user_can('subscriber') ) { //code html for display the fields } add_action( 'show_user_profile', 'show_custom_field_for_subscriber' );
You can use the `WP_User` class and the `has_cap($role)` method. The `show_user_profile` action passes a `WP_User` object as a parameter to the called function. < add_action('show_user_profile', 'my_add_extra_profile_fields'); function my_add_extra_profile_fields($user) { if ($user->has_cap('subscriber')) { //Code here } }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "custom field, user roles, profiles" }
Custom Taxonomy as checkbox or dropdown I have registered a custom tax to my CPT. On the edit screen the tax meta box appears with an autocomplete field. Is it possible to display it as checkboxes or dropdown instead?
You probably did not set the 'hierarchical' argument to true in your register_taxonomy. This would mean that it defaults to false, which gives you a tag-like interface. Add `'hierarchical' => true` to your register_taxonomy.
stackexchange-wordpress
{ "answer_score": 21, "question_score": 14, "tags": "custom post types, custom taxonomy, metabox, taxonomy" }
Creating Featured Content Boxes I know there are plenty of plugins to do sliders out there but I'm looking for something slightly different and I've come up with no luck for a solution. Basically, what I am trying to accomplish is to have a set of images (thinking of around 4) that sits statically above my content. Preferably it would pull the featured image and the title from posts with a specific tag or category and list them up there. Basically, a slider that doesn't slide I suppose. I've included a screenshot of what I mean. Does anyone know of a plugin that would achieve this or a good tutorial on creating something like this? !Example
What you are describing can be accomplished with Featured Image and a simple wp_query call. These are very core elements of a WordPress theme. You'd need to define a size with add image size, and then call it up using the aforementioned post_thumbnail. Your loop might look something like this: $args = array( 'post_type' => 'post', 'posts_per_page' => 3 ); $loop = new wp_Query($args); while($loop->have_posts()) : $loop->the_post(); echo '<a href="'.get_permalink().'">'; echo get_the_post_thumbnail($post->ID, 'my_size'); echo '</a>'; endwhile; wp_reset_query();
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, customization, navigation" }
Displaying posts based on category I recently got some help here on getting a few posts to display in block format. I was wondering if someone could assist me with modifying the code to limit the posts that show up either by category or by tag. I've listed the code below: <div id="mini_stream"> <ul> <? $args = array( 'post_type' => 'post', 'posts_per_page' => 4 ); $loop = new wp_Query($args); while($loop->have_posts()) : $loop->the_post(); echo '<a href="'.get_permalink().'">'; echo get_the_post_thumbnail($post->ID, 'category-thumb'); the_title( '<h6>', '</h6>' ); echo '</a>'; endwhile; wp_reset_query(); ?> </ul> </div>
Add `category_name or cat` in your `arguments` (args) array. <div id="mini_stream"> <ul> <? $args = array( 'post_type' => 'post', 'posts_per_page' => 4, 'category_name'=>'html', ); $loop = new wp_Query($args); while($loop->have_posts()) : $loop->the_post(); echo '<a href="'.get_permalink().'">'; echo get_the_post_thumbnail($post->ID, 'category-thumb'); the_title( '<h6>', '</h6>' ); echo '</a>'; endwhile; wp_reset_query(); ?> </ul> </div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, categories, functions" }
How to join tables? I know many posts is on the site about this but I can't understand how it work. This SQL works. SELECT wp_category.id, wp_ogloszenia_kupione.kategoria, klient_id FROM wp_category JOIN wp_ogloszenia_kupione ON (wp_ogloszenia_kupione.kategoria = wp_category.id); How this translate to Wordpress `$wpdb`?
There are few things you should remember when you're using SQL in WordPress. The most important, I guess, would be table prefix. So your query should look something like this: global $wpdb; $sql = "SELECT kategorie.id, ogloszenia.kategoria, klient_id ". "FROM {$wpdb->prefix}category kategorie ". "JOIN {$wpdb->prefix}ogloszenia_kupione ogloszenia ON (ogloszenia.id = kategorie.id)"; $results = $wpdb->get_results( $sql );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "join tables" }
Woocommerce - Hide “add to cart” on free products im using Woocommerce and searching for a way to hide the "Add to cart"-Button on a single-Product page **IF** the product is for free - I'm making a big CSV-Import and some product-prices are set to zero - i just want to hide the "add to cart" button on these products, so these are not buyable. already asked this on the support page, but no success Greets
Look at the beginning of the add to cart templates in WooCommerce. At the beginning there is a check to determine whether the product is purchasable. Inside the `is_purchasable()` method in the product class is a filter. By default the product is not purchasable if there is no price set at all, but that can be extended to cover products for which the price is set to 0. function wpa_109409_is_purchasable( $purchasable, $product ){ if( $product->get_price() == 0 ) $purchasable = false; return $purchasable; } add_filter( 'woocommerce_is_purchasable', 'wpa_109409_is_purchasable', 10, 2 );
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "plugins, csv" }
How to upload image without post ID using the new media uploader? In the past when using thickbox to upload images, an image could be uploaded without having the post ID 'attached' to it by simply using the code below : jQuery('.upload_slider_button').click(function() { tb_show('', 'media-upload.php?post_id=&type=image&amp;TB_iframe=true&amp;referer=matrix-settings'); return false; }); However, how can I achieve the same thing using the new Media Uploader which was introduced since WP3.5? I have spent the whole day searching in the internet but there isn't much resources available on this new media uploader. Most of it are focused on utilizing it in theme options / plugins. Or perhaps there are other ways of uploading an image without having the post ID 'attached' to it and yet not using any plugins? Thanks a lot for helping.
Well, I have finally figured it out. Using Mike's example here, I just need to put this code `wp.media.model.settings.post.id = 0` at this place : event.preventDefault(); wp.media.model.settings.post.id = 0; // If the media frame already exists, reopen it. if ( file_frame ) { file_frame.open(); return; } This will cause the image to be uploaded as 'Unattached'. Hope this helps someone facing this problem in the future.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "images, uploads, attachments" }
remove support for 'Categories' for a custom post type How would I go about removing support for Wordpress 'Categories' for a custom post type? I've created a custom taxonomy for the post type, so there is no need for the standard categories. Oddly, I thought this would be easy to find out how to do via Google but I can't find anything on it. Any help appreciated!
In the array of arguments to register_post_type() there is a parameter "taxonomies". If category is not specified there, then it shouldn't appear with that post type.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "custom post types, categories, custom taxonomy" }
Theme files and imagesnot loading on a mobile device I am just setting up my site but I have run in to a weird issue where the site seems to load perfectly fine on my computer but when I view it on a mobile device (iPhone/iPad) it appears to have none of the template files and none of the images are attached to posts etc. Any thoughts what could be wrong? I might add incase it helps I built this on a local set up and it's my first time using this process so there may be something in that I did wrong. But I checked the uploads folder and themes folder and they both have '755' permissions. This is the site: <
I managed to solve this problem. Turns out when switching my site over from local to live I missed a few links in the DB (I did run a script to check but it obviously didn't pick up all the links). So simple fix corrected the links and the site works.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, themes, errors, css, mobile" }
is_post_type_archive not working in feed I'm trying to alter a feed for my plugin's custom post type to add lines for podcasting. Here is the code I've got right now: add_action ('init', 'my_plugin_init'); function my_plugin_init() { if ( is_post_type_archive('my_plugin_custom_type') ) { add_action('rss2_ns', 'my_plugin_podcast_ns'); } } function my_plugin_podcast_ns() { echo 'xmlns:itunes=" } The archive for this post type is located at ` and I'm getting the feed at ` However, my extra line is not showing up. What am I doing wrong?
`'init'` is probably too early to get a meaningful result from `is_post_type_archive()` which depends on the the query having been run. `'template_redirect'` is probably the earliest action you could run it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, custom post type archives, podcasting" }
Wordpress subdomain wp-admin redirects to main domain we have a wordpress installation running on address www.example.com. We wanted to have a development site for it as a subdomain, so we created a subdomain dev.example.com on cpanel. Created a duplicate of its database and replicated the files to the directory root of dev.example.com. Then modified wp-config.php to point to the duplicate db. Now the problem is, when we try to access dev.example.com/wp-admin, it redirects to Anybody can help me with this?
Based on Charles Clarkson's comment, I directly changed the `siteurl` and `home` options in the `wp_options` table to be ` and this fixed the problem for me.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wp admin, redirect, subdomains" }
remove <p> tags from the_content I've got a post format of Image, and I am running into an issue where the image is being wrapped by a `<p>` tag. I want to get rid of that tag (specifically on the `single.php` version) of those post types. How can I get inside the formatting in a theme and remove the `<p>` tags, or create any format that I want for the output of this type of post, without affecting posts of a different post format?
By default, WordPress adds paragraph ** **tags to category descriptions. Stop this by adding the following to your **functions.php** file // Remove p tags from category description remove_filter('term_description','wpautop'); **Simple and easy (codeless).** Thank you
stackexchange-wordpress
{ "answer_score": 4, "question_score": 7, "tags": "loop, content, the content, formatting" }
Is it possible to have screenshots in any other section rather than the screenshots section? At WordPress.org plugin, is it possible to have screenshots in any other section rather than the screenshots section? For example. Can I create a section called "Manual" and then have some screenshots there?
In the readme.txt file, the "Screenshots" section is a special section. The WordPress plugin repository checks your Assets folder (or the folder containing readme.txt) for images named in a certain way and corresponds them to the entries in this section. I don't believe it is possible to attach images in the same way in any other section. Markdown does provide a syntax for including images: !Alt text However, I tried to make this work in the WordPress readme.txt validator, and I couldn't. It looks like the plugin repo strips these out, but I haven't actually tried it in a plugin's readme.txt and committed it to see what would happen.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "plugins, wordpress.org" }
how can I change the background color of all posts on my server? The default for the theme I'm using is to have a white background for any post (the part with the text, not the background that forms the border around it) on my wordpress installation. Is there a way I can set the the background for all pages in one shot. I've tried adding the following css: p { background: #91C3C1; } but it only changes the background color for the paragraphs. What element should I be changing? (in this case I'm using the "Responsive" theme from CyberChimps)
The solution for me was to add the following .grid { background: #91C3C1; } .page { background: #91C3C1; } although, the border around the posts are still the default color; but I'll start a new question for that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, themes, css" }
How to prevent meta data from being edited in a post? I need to add a 'poll' to every single post automatically, and wish to do this without having to manually create a poll each time using a plugin, so I had an idea to store the poll results as meta data in the post. So each time someone votes, it saves their vote as a custom field meta value in the post. This should work in theory, however one problem I've discovered early on is that when editing the post which contains a poll, if someone votes while I am editing and then I press Update, the results are reset back to whatever they were before I started editing, because the custom field is being saved along with the post. Is there any way to stop a certain custom field from being saved when I update a post? Or to make it retrieve the latest value before saving it?
I would recommend you to remove custom fields meta box from the post editing page. You can do it by using `remove_meta_box()` function. add_action( 'admin_menu' , 'wpse8170_remove_post_custom_fields' ); function wpse8170_remove_post_custom_fields() { remove_meta_box( 'postcustom' , 'post' , 'normal' ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom field, save post" }
facebook Page Publish 2 I am using acebook Page Publish 2 plugin . which is working fine. but i want to POST feature image on fb page. but it doesnot showing anything on facebook page. Does anybody tel me how to POST feature image on fb page Thanks
Use Add Link to Facebook instead of facebook page publish 2 plugin.It is quite simple plugin.It creates add link to facebook menu under Tools in wordpress admin menu. following link below:- <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Limit comments per user per post I use this code to limit the comments to 1 for registers users and works fine. The problem is that when i click to "go back" button in the browser i can comment again. Is there any effective way to limit the comments? Thank you! global $current_user, $post; $args = array( 'user_id' => $current_user->ID, 'post_id' => $post->ID ); $usercomment = get_comments( $args ); if ( 1 <= count( $usercomment ) ) { echo 'disabled'; } else { comment_form(); }
I think that hook `pre_comment_approved` should be perfect in this case. Something like this should do the job: function my_pre_comment_approved($approved, $commentdata) { // you can return 0, 1 or 'spam' if ( $commentdata['user_ID'] ) { $args = array( 'user_id' => $commentdata['user_ID'], 'post_id' => $commentdata['comment_post_ID'] ); $usercomment = get_comments( $args ); if ( 1 <= count( $usercomment ) ) return 0; } return $approved; } add_filter('pre_comment_approved', 'my_pre_comment_approved', 99, 2); Your filter should return: * `0` (i.e. 'false') if the comment should be disapproved * `1` (i.e. 'true') if the comment should be approved * `'spam'` if the comment should be marked as spam
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments" }
How to close tab automatically if URL has specific word? help me today. Is it possible to close the tab automatically after loading/few seconds after checking if URL address has specific words? e.g; ` Here `?deleted=1` is the word I'd like to check. I'm on wordpress. Thank you.
You will need Javascript to do this. You can use `window.close()`. So adding this script to your page should do the job: function check_if_should_close(url) { if ( PUT YOUR CONDITION HERE ) // i.e. url.match(/\?deleted=1/) return true; return false; } if ( check_if_should_close(document.location.href) ) { window.close(); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls" }
How can I add another option to this custom post function? I'm currently developing a games database for my wordpress site and one of the custom functions is entering a review score for a game, we have a 1-10 based rating system but I wish to add another option to this loop "No Review", how can I do this? <select style="width: 100px" name="games_database_rating"> <?php // Generate all items of drop-down list for ( $rating = 10; $rating >= 1; $rating -- ) { ?> <option value="<?php echo $rating; ?>" <?php echo selected( $rating, $game_rating ); ?>> <?php echo $rating; ?>/10 <?php } ?> </select>
You just need to add a static `<option>` element before you start your loop. <select style="width: 100px" name="games_database_rating"> <option value="none">No Rating</option> <?php // Generate all items of drop-down list for ( $rating = 10; $rating >= 1; $rating -- ) { ?> <option value="<?php echo $rating; ?>" <?php echo selected( $rating, $game_rating ); ?>> <?php echo $rating; ?>/10 <?php } ?> </select> Now your `select` will start out with "No Rating", and you can still choose a number. When you submit the form, just check for "none" or the number.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, rating" }
return unformatted content in encosing shortcode I've written a little shortcode, following basic instructions on Wordpress Codex: function myshortcode( $atts, $content = null ) { extract( shortcode_atts( array( ..., ), $atts ) ); return some_html _code_here . $content; } When I put [myshortcode] this is a test content [/myshortcode] in a post, I obtain the following output: this <br /> is <br /> a <br /> test <br /> content <br /> How can I avoid the inserting of br / tags?
The `<br />` tags are being added to the content by the `wpautop()` function. If you run your shortcode before it runs they will not be there. It is added in `\wp-includes\default-filters.php` with the default priority of `10`. add_filter( 'the_content', 'myshortcode', 1 ); function myshortcode( $atts, $content = null ) { return $content; } wpautop() can also add other markup besides `<br />` tags.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "shortcode, formatting" }
Category page with gallery for each post I'm looking for a bit of direction on how to set up a category page (for a real estate company). What would be the best way to have a gallery of images (1 large photo and several thumbnails) listed for each post on a category page.
install an image gallery plugin like this one < and have a gallery set in each of your posts, then edit your theme's category template and have a look at the loop, if it uses `the_excerpt()` then you have to alter it to `the_content()`. This way, you will have a gallery list in the category list view. You may want to use another plugin, but keep the same idea.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, images, themes, gallery" }
Capture post content before page renders I'm trying to mesh Mustache Templating Engine with WordPress. So far, I have been very successful using the_content as a filter to parse my template tags e.g. `{{ something }}`. However, if let’s say, a developer hardcodes the template tags directly into the page template e.g. loop-page, the_content doesn’t capture the hardcoded tags. Is there a filter that will allow me to capture the content of the whole page template including the content?
WordPress does not concatenate the entire page into a string before printing it which is what would have to happen to "capture" the whole page template. Much of the page `echo`s as it occurs-- think about template tags like `the_content` and `the_title` which don't return strings. The just `echo` them. You'd have to use output buffering to do this. That is pretty easy if you are writing the template-- `ob_start` at the beginning or `header.php` and `ob_get_contents` (or `ob_get_clean`) at the end of `footer.php`. But there are no hooks specifically at those locations. You should be able to capture most of the page with `ob_start` on a `wp_head` filter and `ob_get_contents` on a `wp_footer` filters. I'd have to play with things to dial it in. There may be a slightly better hook for `ob_start`. I doubt there is a better one for `ob_get_contents`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "filters, hooks, actions" }
How to add meta slider lite or other slider to main page header in pinboard theme Slider is created using Meta Slider Lite v2.2.1. Meta Slider shows it usage as Shortcode [metaslider id=449] Template Include <?php echo do_shortcode("[metaslider id=449]"); ?> Pinboard theme is used. Text module is added to its header element. Text element contains [metaslider id=449] <?php echo do_shortcode("[metaslider id=449]"); ?> slider does not appear. View source shows that [metaslider id=449] <?php echo do_shortcode("[metaslider id=449]"); ?> are rendered literally. How to show slider in header ?
I suspect _Meta Slider Lite v2.2.1_ is a plugin and that the instructions are telling you to either use a shortcode in the WordPress editor or the PHP code in a template file. They are not likely to be telling you to use both at the same time. I don't know what a _text module_ is, but I suspect it is a modified text widget. By default, text widgets do not expand shortcodes or a run PHP code. Check the Pinboard documentation (or with their support) to find a _module_ that will expand shortcode or run PHP code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, slideshow" }
Show two random posts from custom post type I've set the code below to show info from the latest two posts of a custom post type (it also loops through and adds a class of first to alternate items for layout purposes). How would I amend this to show two random posts? <?php $counter = 1; $args = array( 'post_type' => 'custom_advert', 'posts_per_page' => 2 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); echo '<div class="sixcol '; if ( $counter % 2 == 1 ) { echo 'first'; } echo '"><a href="[using custom meta to get link address here]"><img src="[using custom meta to show image here]"></a></div>'; $counter++; endwhile; ?>
You need an `orderby` argument. $args = array( 'post_type' => 'custom_advert', 'posts_per_page' => 2, 'orderby' => 'rand' ); That should pull posts in a random order and stop after retrieving the first two, hence two random posts.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 3, "tags": "wp query, loop" }
Count > 1 Navigation Slider I have a post type `slider`, when you have more than one post to display navigation. My code: <?php $count_slider = wp_count_posts('slider'); echo $count_slider->publish; ?> <?php if($count_slider > 1): ?> <div id="slideshowcontrol" class="clearfix"> <div id="button_prev"><a href="#" id="slideshowprev"><img src="x.gif" alt="Prev" /></a></div> <div id="button_next"><a href="#" id="x.gif" alt="Next" /></a></div> </div> <?php endif; ?> But it doesn’t work. Why?
This is a basic PHP error, you need to turn on debugging. `$count_slider` is an _Object_ and not an _Integer_ which is what you are checking for, since you seem to want to compare published posts anyhow , write it like: <?php if($count_slider->publish > 1)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, navigation" }
how do I get the date in a date archive page In archive.php, if it is a date archive, can I get the date using a function? Consider a url like this: myfirstsite/2013/08 - I want to get the 2013/08
Use `get_query_var()` to get the date parts: $year = get_query_var('year'); $monthnum = get_query_var('monthnum'); $day = get_query_var('day'); In `wp_title()` a call to `get_query_var('m')` is used for the month too, but I got always just a `0` as value even on an URL like `/2008/09/05/`. If you want to print the month name, use: $GLOBALS['wp_locale']->get_month($monthnum); The month name will be translated by WordPress then. There are also four conditional functions you can use: is_year() is_month() is_day() is_date()
stackexchange-wordpress
{ "answer_score": 10, "question_score": 2, "tags": "archives, date" }
Highlight current tag using get_tags() I'm nearly there with this, but I need to highlight the current tag link/archive being viewed: <ul id="blog-tags"> <?php $tags = get_tags(); if ($tags) { foreach ($tags as $tag) { echo '<li><a href="' . get_tag_link( $tag->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . '>' . $tag->name.'</a></li>'; } } ?> </ul> I'd like to apply `<li class="active-tag">` to the list item that contains the active tag in the code above - can anyone help me with that please? Many thanks Osu
Compare `$tag->term_id` with the value from `get_queried_object_id()`. You have to cast the former to integer, because it is provided as a string for no good reason. <ul id="blog-tags"> <?php $tags = get_tags(); if ( $tags ) { foreach ( $tags as $tag ) { echo '<li>'; if ( (int) $tag->term_id === get_queried_object_id() ) echo "<b>$tag->name</b>"; else printf( '<a href="%1$s">%2$s</a>', get_tag_link( $tag->term_id ), $tag->name ); echo '</li>'; } } ?> </ul>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "tags, archives" }
How to redirect logged out users to specific page? I have a question and a technical issue in wordpress. That is, i have a login form on my website to allow visitors to login to see special content. The question goes here, when the time they log in, i am managed to redirect them to a targeted page. When the time they logging out from the member zone, i am out of idea how to send them to a different targeted page. In my function.php file, I have this code: add_action('wp_logout',create_function('','wp_redirect(home_url());exit();')); How to add the page url that i want to redirect them to this code above? I am just beginner in php. Hope to get some guidance.
`home_url()` will accept a parameter that will be used in the creation of the URL. The bare minimum solution would be: add_action( 'wp_logout', create_function( '', 'wp_redirect(home_url("/path/to/page"));exit();' ) ); `site_url()` will also accept the same parameter and may be (probably is) a better choice. I believe that using either of those will make the link dependent on permalink settings. I don't think that those function will translate between different settings, though I have not tested that. I would suggest using `get_permalink()` with an explicit page/post ID. add_action( 'wp_logout', create_function( '', 'wp_redirect("'.get_permalink(1).'");exit();' ) ); Note that you don't need `home_url()` or `site_url()` since `get_pemalink()` will generate the complete URL.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "redirect, logout" }
get_posts - get all posts by author id I want to get all posts by certain author id (current user). Later, I want to pick the first post made by this user (ASC). I guess I do not use the right arguments in get_posts, am I? $current_user_posts always contains an Array with all blog posts in multiple different WP_Post Objects. global $current_user; get_currentuserinfo(); $args = array( 'author' => $current_user->ID, // I could also use $user_ID, right? 'orderby' => 'post_date', 'order' => 'ASC' ); // get his posts 'ASC' $current_user_posts = get_posts( $args );
I'm a bit confused. If you want to get onlya element from the posts array you can get it like this: * reset($current_user_posts) - first post * end($current_user_posts) - lat post But if you want to get just one post with the `get_posts()` you can use the `posts_per_page` argument to limit the results. $args = array( 'author' => $current_user->ID, 'orderby' => 'post_date', 'order' => 'ASC', 'posts_per_page' => 1 ); More info about parameters you can get on WP Query Class Reference page (`get_posts()` takes same parameters as WP Query).
stackexchange-wordpress
{ "answer_score": 25, "question_score": 14, "tags": "get posts" }
Hide Pages WooCommerce I would like a condition such as the following: 1) User is logged. Select Page Shop and displays all content. 2) If user is not logged. Select Shop page, they are redirected to another page, for example Sign Up page. I hope it is possible. I have tried many plugins but failed. At the moment the only one that works with WooCommerce is s2Member, but it is overkill for my purpose. Thanks in advance for any help.
You can do this by using 1) is_shop fx 2) template_redirect action hook 3) wp_safe_redirect fx add_action('template_redirect','ravs_shop_for_login_user'); function ravs_shop_for_login_user(){ //check user in shop page and not login if( is_shop() && ! is_user_logged_in() ) wp_safe_redirect( home_url() );// enter your url here where you want to redirect page if user on shop page and not registered } **Note** paste this code in `functions.php`.currently visiter redirect to home page if not registered,provide any url in wp_safe_redirect fx where you want to user redirect.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins" }
How do I use wp_get_recent_posts? I'm trying to display the title and excerpt of the most recent 8 posts on the sidebar. I'm getting a list where: * All items link to the oldest post * All titles are "id number of a post that should be displayed"+"oldest post title" * All excerpts are from the oldest post * * * <?php $args = array( 'numberposts' => '8' ); $recent_posts = wp_get_recent_posts( $args ); $noticias_highlight = true; foreach( $recent_posts as $recent ){ ?> <div class="entry <?php if ($noticias_highlight) echo 'highlight'; $noticias_highlight = !$noticias_highlight; ?>"> <div class="title"><p><a href="<?php the_permalink($recent["ID"]); ?>"><?php the_title($recent["ID"]); ?></a></p></div> <div class="subtitle"><?php the_excerpt($recent["ID"]); ?></div> </div> <?php } ?>
Don't use the 'helper' methods, they tend to cause more trouble than they're worth. Any time you want to grab posts, be it the latest, the oldest, in a category etc, use a `WP_Query` loop, here is its standard form: $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); // do stuff } wp_reset_postdata(); } else { // none were found } This is what `wp_recent_posts` will be doing internally, although it isn't doing it very well. So save the above to an autocomplete macro in your editor
stackexchange-wordpress
{ "answer_score": 11, "question_score": 0, "tags": "recent posts" }
Updating from Wordpress 3.5.2 to 3.6 Errors When trying to update from 3.5.2 to 3.6 the following error occurs: Warning: touch(): Unable to create file /tmp/wordpress-3.tmp because No such file or directory in /home/yaznetx1/public_html/wp-admin/includes/file.php on line 179 Warning: unlink(/tmp/wordpress-3.tmp): Operation not permitted in /home/yaznetx1/public_html/wp-admin/includes/file.php on line 503 Download failed.: Could not open handle for fopen() to /tmp/wordpress-3.tmp Installation Failed Anyone know how to fix this?
Thanks for your comments guys, I was over on the WPMU and was told to manual update, worked like a charm. Will do that with any issues in the future.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "updates" }
Editing Theme Files on Wordpress.com-hosted Site I'm doing some work for a client on her Wordpress.com-hosted site. I'm used to only working on self-hosted WP sites, and I know how to edit the theme files there, but I'm not sure if it is possible to do this on a Wordpress.com-hosted site. I'm trying to change the way that blog posts are displayed when listing posts from a given category, which I would usually do by going into the theme and editing the relevant php file. Is this not possible with this type of site? Thanks!
With WordPress.com you can edit a theme's CSS styles* _, fonts_ *, or other display options offered under the theme's Appearance->Customize menu. You do not have access to edit any of the theme's php or template files. **notes premium feature
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, themes, wordpress.com hosting" }
View category in the preview of Theme Customizer I am building a theme which Theme customizer changes colors, sizes, etc. and has also the option to choose a category and style that category specifically. How can I display that category in the preview (only when the user is changing the corresponding options) instead of the default home/front page displayed by default? **EDIT** I can access the preview window with customize_preview_init, but I can not apply wp_redirect, which I guess could be a way.
I ended up with this solution: 1.Require an extra file that will contain the hooks only in the theme preview function mytheme_customizer_live_preview() { require_once('library/preview.php'); } add_action( 'customize_preview_init', 'mytheme_customizer_live_preview' ); 2.What I had to do is modify the query as I would normally do in the page, so just do it in the preview (inside preview.php): function modify_query($query) { $category = get_theme_mod( 'mytheme' )['categories'][0]; $query->set('cat', $category); return $query; } add_filter('pre_get_posts', 'modify_query', 10);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "categories, customization, theme customizer, previews" }
How to add wordpress pagination i must use pagination. Where can i found good tutorial? ` $wpdb->get_results("SELECT * FROM wp_ogloszenia_kupione WHERE klient_id = $current_user->ID"); `
Your question is quite vague but if it's documentation you are looking for then a good place to start would be: < <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "pagination, wpdb" }
Query parsing only author ids I need array only all author ids from the loop, each one only once if possible and out of all posts in the loop. Any suggestions?
Assuming that you have an array of post objects in `$my_posts`... $authids = array_unique(wp_list_pluck($my_posts,'post_author')); What you will get are the post authors for the _current page of posts_ , not the post authors for all of the posts. If you want the authors for all of the posts you will have run another query. To run a new query based on the main query in `$wp_query`... $this_query = array_unique($wp_query->query_vars); $this_query['posts_per_page'] = -1; $new_query = new WP_Query($this_query); $authids = array_filter(wp_list_pluck($new_query->posts,'post_author')); var_dump($authids); // debug _**I caution you against this.**_ You could be querying hundreds or thousands of posts. That could be very inefficient or even cause server failures, depending on the server and the load. I am almost certain that there is a better way to do this if you think it through and alter your architecture. # Reference: < <
stackexchange-wordpress
{ "answer_score": 2, "question_score": -3, "tags": "query, author, array, id" }
Insert a Woocomerce product in specific product category I'm a bit new to Woocomerce plugin and have a problem. I need to create products from code not from admin page. Probably I will insert them with `wp_insert_post( $product )`. The problem is I don't know how to set the category for this product. I know it's name, not the ID (in fact I know ID but it can change). How can I add the product to that category?
You can use wp_set_object_terms fx > From Codex: > > This function relates an object (post, link etc) to a term and taxonomy type (tag, category, etc). Creates the term and taxonomy relationship if it doesn't already exist. wp_set_object_terms( 'id of product', 'term name', 'product_cat', true );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, wp insert post" }
How to create custom variables in the wp-config I would like to add some custom config variables in the `wp-config.php` file (not in the `functions.php`). Then, I need to access to these variables in my templates. What is the way to do that ?
Why do you need this? In wp-config you can set defines. They will be accesible everywhere without needing to use globals. Define something: `define('MY_DEFINE_NAME', 'THE_VALUE');`. Then in your templates you can show the value like this: `echo MY_DEFINE_NAME;` Or set the value to a variable: `$var = MY_DEFINE_NAME;`.
stackexchange-wordpress
{ "answer_score": 14, "question_score": 5, "tags": "variables, wp config" }
Facebook Like Button in Jetpack I'd like to have a Facebook Like Button (not a Facebook share, which is available) through Jetpack. There is a "Add a new service" and I've tried various parts of code from all over but always gets an "An error occurred creating your new sharing service - please check you gave valid details." Anyone knows howe to do this?
1. Go to Settings > Sharing in your dashboard 2. Sroll down until the "Button Style" option. 3. Choose "Official Buttons". The Facebook Share button has now changed into a Facebook Like Button. Save your changes, and you'll be good to go! If you want to add a Facebook Share button next to the Like button, you can use the "Add a new service" option: * In "Service Name", type in "Facebook" * In Sharing URL, enter ` * In Icon URL, enter a link to the Facebook icon of your choice. And save changes.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "facebook, plugin jetpack" }
How to display a widget on a page with no theme? I would like only a widget to appear on a page, is this possible? As in if I created a page, I am wondering if I can make a page just display the widgets contents with no headers, sidebars, just blank. Essentially if there was no widget added it would be a blank page. Is this possible?
You should read this. It's completely possible, but you have to go through the right process. First you should register a new "sidebar" and call it whatever you want to call that page you want the widget to display on. Then you need to call that sidebar into the page's template file, after which you can add and remove widgets from your dashboard. This all hinges on you having access to the code, if you don't I am afraid the answer is probably not. If you can alter the code, then all you have to do what I said above, and create a new page using the page template you created.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, themes, widgets" }
Edit Buddypress Groups Activity Page Text I am setting up a Wordpress site with Buddypress functionality for a client. The client wants the "What's new" text under the "Activity" tab changed to something else. I feel like this should be editable in the Buddypress theme files, but I can't seem to find it. Here's a screenshot with the text I'm talking about: < Anyone know which file generates this text?
You shouldn't edit that file. You should over-ride it. Create a folder called 'buddypress' in the root of your theme folder. Place a copy of post-form.php in that folder - using the same dir structure as bp-templates/bp-legacy/buddypress/ Then you can update buddypress without losing your changes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, buddypress" }
Remove /author/ from the author profile url I'm trying to figure out the best way to remove /author/ from the profile URL of my users. I tried using the method in the link below and although it worked, it also prevented me from accessing any of my other pages that used a page template. So not sure if there's a tweak I need to make to the code? I would like to do this through the functions file and not use a plugin so any guidance is much appreciated. add_action('init', 'cng_author_base'); function cng_author_base() { global $wp_rewrite; $author_slug = ''; // change slug name $wp_rewrite->author_base = $author_slug; }
Essentially, you can't do that because you've overlapped the "page" and "author" sections in the namespace. See, with your setup, then given a URL like < WordPress has no way to distinguish whether "whatever" is an author or a Page. To do this, you'd need to add a lot more code to add extra querying during the rewrite parsing, basically. Which means that you should use a plugin to do it, if you still want to do it at all.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "author, profiles" }
Safe to say WordPress security releases don't have database upgrades Since all security releases are based on last released codebase + security patch, I think its safe to say WordPress security releases don't have database upgrades, but I figured I will ask my fellow developers here. Does anyone know of a security release which had one? Or can anyone think of a case where it might have a database upgrade code within it?
All the database upgrades can be seen in the code, in the wp-admin/includes/upgrade.php file. And yes, some of the point releases (including 3.5.2) contained "database upgrades". Now, it is only very rarely that the actual database _schema_ changes, but there are minor bugfixes in every point release, and sometimes they require a little database action. So while 3.5.2 had seven security related patches, it also contained a fix for multisite installs to fix an invalid site-option. This required a minor bit of code to change the data in the database. Actual big DB operations almost always are limited to major releases, such as 3.5.0 or 3.4.0 and such, but some minor little bugfixes happen all the time.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "security" }