INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
PHP Wordpress optimization my loop code I'm just learning PHP, and I'm using get_terms to get some text descriptions from the CMS, but i want to assign 3 variables to only 3 of my woocommerce tags. My code works well, but I just want to learn if there's a better way to filter by $tag_descrip->name than using if conditions. This is my code: <?php $tag_descrip = get_terms( 'product_tag', 'orderby=count&hide_empty=0' ); $count = count($tag_descrip); if ( $count > 0 ){ foreach ( $tag_descrip as $tag_descrip ) { if($tag_descrip->name == "parfum_bestof") {$title_new1 = $tag_descrip->description ;} if($tag_descrip->name == "tshirt_bestof") {$title_new2 = $tag_descrip->description ;} if($tag_descrip->name == "child_bestof") {$title_new3 = $tag_descrip->description ;} } } ?> Thanks
Hi there is not better option, but to speed it up little you can use wordpress transient, see documentation: < your code would look like this (and i cleaned it bit and used function empty to check array...): <?php if ( false === ( $tag_descrip = get_transient( 'tag_descrip' ) ) ) { $tag_descrip = get_terms( 'product_tag', 'orderby=count&hide_empty=0' ); set_transient( 'tag_descrip ', $tag_descrip ); } if ( !empty($tag_descrip) ){ foreach ( $tag_descrip as $tag_descrip ) { if($tag_descrip->name == "parfum_bestof") $title_new1 = $tag_descrip->description; if($tag_descrip->name == "tshirt_bestof") $title_new2 = $tag_descrip->description; if($tag_descrip->name == "child_bestof") $title_new3 = $tag_descrip->description; } } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php" }
Javascript included but alert() function not working I've included the javascript by wp_enqueue_script('slider', plugins_url( 'slider.js', __FILE__ ) ); with just a simple $(document).ready(function () { alert("alert"); }); It shows up in the browser but doesn't prompt me with "alert". PS: Forgot to mention I've also included the jquery, but still not working. wp_deregister_script('jquery'); wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null); wp_enqueue_script('jquery'); * * * In addition to the answers, I also had to tell wordpress that my script depends on jQuery wp_enqueue_script( 'slider', plugins_url( 'slider.js', __FILE__ ),array('jquery') );
A few things: 1. The version of jQuery that ships with WordPress is run in noConflict() mode. Meaning you have to use `jQuery` instead of `$` when you make your first reference. 2. Don't register your own version of jQuery when you're developing. You're locking yourself in to a single version that may or may not be compatible with WordPress' other requirements. 3. You can use the browser console to test things. Open your page, then hit F12 to launch the console. Type `jQuery` into the console and see whether or not it returns the correct object.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, javascript" }
I have no images in an activated wp theme With this line everything works fine - (as a **Non-Wordpress** index.php): <link href="style.css" rel="stylesheet" type="text/css"/> When I activate the file as a wp theme and replace above line with: <link href="<?php bloginfo('stylesheet_url');?>" rel="stylesheet" type="text/css"/> everything is ok, except - there are no images. For example - a div with an image: <div id="about"> <img id="thinker01" src="images/thinker01.png" width="120" height="163" /> </div> **images** folder is inside theme's folder.
> images folder is inside theme's folder. But relative URLs do not work that way. They are relative to the URL not to the filesystem path. Your problem is here: `<img id="thinker01" src="images/thinker01.png" width="120" height="163" />` If you look at the request (via HttpFox or other means) you will see that the browser is looking for the image at ` and not at ` Don't use relative URLs like that. Give it a complete path as you did with your stylesheet.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, themes, activation" }
alphabetically order role drop-down selection in dashboard The site I'm working on will have a very large number of unique user roles via a members plugin. Because of that, I'd like to have the Role drop-down selection on the Add New User page to display roles alphabetically, rather than descending order of creation. Is there any way to do this?
Almost the same approach _One Trick Pony_ has chosen, but I am using translated names and `uasort()` (to preserve the keys): add_filter( 'editable_roles', 't5_sort_editable_roles' ); /** * Array of roles. * * @wp-hook editable_roles * @param array $roles * @return array */ function t5_sort_editable_roles( $roles ) { uasort( $roles, 't5_uasort_editable_roles' ); return $roles; } /** * Compare translated role names. * * @param array $a First role * @param array $b Second role * @return number */ function t5_uasort_editable_roles( $a, $b ) { return strcasecmp( translate_user_role( $a['name'] ), translate_user_role( $b['name'] ) ); } As a plugin on GitHub.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 7, "tags": "users, dashboard, user roles, order" }
How is WP Cron Locking implemented? WordPress takes measures to ensure that a cron task doesn't run twice when it should run once, e.g. once every hour when an hourly schedule is given, rather than the occasional twice at the scheduled time. While it's not foolproof, what steps does WordPress take to make sure it happens at the scheduled times, and only once as specified?
A transient is set to reflect the state of the cron, which gets deleted when all tasks complete. Any subsequent requests are ignored if that transient is found...
stackexchange-wordpress
{ "answer_score": 6, "question_score": 7, "tags": "cron, wp cron" }
Get 1st parent category id from post I have this structure for my categories: Issue 4 - News - Supporting our troops - Breaking news <?php $category = get_the_category(); $parent = $category[0]->term_id; ?> This code gets the top level category ID from "Breaking News" which is Issue 4, missing out News its direct parent category. How could I get the category ID for "News", its direct parent category and not the top level category?
You need to use `get_ancestors()`. Assuming your post is only in one category, the following code should work (if it's in multiple you'll need to loop through each of the assigned categories to determine the various hierarchies). $category = get_the_category(); $ancestors = get_ancestors( $category[0]->term_id, 'category' ); $direct_parent_id = $ancestors[0]; If you want to get the entire category hierarchy as an ordered array of IDs (which I like to have available) you'd do: $category = get_the_category(); $hierarchy = array_reverse( get_ancestors( $category[0]->term_id, 'category' ) ); $hierarchy[] = $category[0]->term_id;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, query, categories" }
Cache issues with images not showing up Images are there, but they don't always show up. Could this be a cache problem? Or Timbthumb? Here is an example: < And another: < I sometimes also have trouble getting into WP dashboard, it gives a warning php error, but when I refresh, it goes away and I get inside fine.
If I visit your first link and look at the response, I get a `500 Internal Server Error` when trying to get the following resource: ` so my guess is that your problem is with the `timthumb` plugin. Try disabling the plugin and see if your error goes away.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, cache" }
WP_Query meta compare must include ALL array values I am allowing users to query posts using a form with checkboxes. I want the posts to be filtered by the checkboxes but instead of showing all posts that include the ANY of the meta values selected I want to show posts that contain all of the selected values. Is this possible? Here is what I currently have using the "IN" operator which just checks if the post contains any single value in the array. $the_query = new WP_Query(array( 'post_type' => 'listing', 'posts_per_page' => -1, 'post_status' => 'publish', 'category_name' => 'private_rental', 'orderby' => 'rand', 'meta_query' => array( 'key' => 'row_amenities', 'value' => $amenities, 'compare' => 'IN' ) ));
You can have multiple `meta_query` arguments with the same key and that will produce the results you're seeking. Here's an example: $meta_query = array_map( create_function( '$a', 'return array("key" => "row_amenities", "value" => $a);' ), $amenities ); $the_query = new WP_Query(array( 'post_type' => 'listing', 'posts_per_page' => -1, 'post_status' => 'publish', 'category_name' => 'private_rental', 'orderby' => 'rand', 'meta_query' => $meta_query )); If `$amenities` will have a lot of values (> 10), you should probably take a different approach, because it will join the postmeta table for each meta_query.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, query, post meta, meta query" }
Defining the same price to all WooCommerce Products All of my products on my site are $1 and during an import I did using WooCommerce import it didn't save all the _regular_price & _sale_price values, so there is no way for the user to buy that product. Is there a mysql query that can go through and apply a value to all of the nulls to the $1 value?
Looks like you are not familiar with WordPress Bulk Edit. Change the `Screen Options` to show all the products you have (if there are too many this can be slow, and is better to do it following some 100/200 product per page). ![woocommerce products screen options]( Select all the products, select `Edit` in the Bulk Edit dropdown and `Apply`. Now you can change a batch of product details. ![woocommerce products bulk edit]( _^ click to enlarge ^_
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "mysql, plugins" }
Show posts in category x and y from the 6th most recent post onwards I'm struggling with the query for this in WordPress to display posts in a category from the 6th most recent onwards. Basically, I have a top 5 posts section at the top of a category for featured posts (marked as posts in that specific category AND in a Featured category), then in the page content I don't want any of those top 5 featured posts shown in the regular posts loop. Any help would be greatly appreciated. $query = new WP_Query( array( 'category__and' => array( 2, 6 ), 'offset' => 5 ) );
Without seeing your code, here's a rundown that should work for you. 1. At the top of your template file, start an array, `$featured_posts = array();` 2. In your featured posts loop, in each iteration, add the ID of the post to the array, `$featured_posts[] = get_the_ID();` 3. In your second loop, check to see if the post was already displayed, and if so, skip to the next iteration of the loop: `if ( in_array( get_the_ID(), $featured_posts ) ) continue;`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts" }
Will adding & modifying default Wordpress table index break future Wordpress update I've some specific use case for certain default wordrpess tables, which I need to add a few indexes to certain columns to improve performance. I'm wondering will adding these indexes break future Wordpress update when they choose to add index to the same column?
Adding a `BTREE` or `HASH` index shouldn't break anything, and I imagine that is what you want. At worst you could end up with multiple indexes, or less than optimal ones, which might negatively effect performance. I assume that if you are going to do this you will be evaluating the change to see if it actually does help, rather than hurt. I guess you could run into trouble with a `UNIQUE` index, since WordPress does use a couple of those.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, updates, table" }
pre-upload text and video for the future I want to upload text and a video for a future date. On that future date, a new post/html is added to the site (without me doing anything that day).
Unless I'm misunderstanding you, you should just need to set the publication date of the post in the future and "Publish" it. This should walk you through you what you need to know: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, widgets" }
Displaying Archives List I'm displaying list or archives using <?php get_archives('monthly', '', 'html', '', '', FALSE); ?> and my list displays December 2012 November 2012 etc However I would like to format this to display: 12.12 11.12 10.12 etc Any ideas?
There is but the filter sucks, it only gives you the link HTML: add_filter( 'get_archives_link', 'wpse74891_archives_link' ); function wpse74891_archives_link( $link ) { $link = preg_replace_callback( '/>([A-Za-z]+\s+\d{4})/', function( $matches ) { return '>' . date( 'm.y', strtotime( $matches[1] ) ); }, $link ); return $link; } Using this method you can pass in any date format you want for the link at least.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "archives, sidebar, date, formatting" }
Use Wordpress engine for user registration and management I am building a web app and would like to use the Wordpress Engine only for Authentication and User Management. Is there any good tutorials out there on how I can connect only the back end of wordpress to my simple app?
This may be good starting point for you: < (see function reference for admin-related functions list)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user access, user registration, authentication" }
How to activate/deactivate menu tab and keep the same id? I have a problem here and i cant find/think of any solution yet. I want to have a menu button that can be activated/deactivated and still keep the same id so the CSS will still be applied. Is there any plugin or a way to do that ? I allready managed to create the page and add it to menu and then remove it. That works but the problem is that "special" button i want is supposed to be another color and I cant find any solution for that because the id keeps changing.
If it's all about CSS & you don't mind adding/removing it manually, please consider using a CSS class for that particular menu item. If you don't see the option, click screen options in top-right, then check the option for CSS classes. Then you can write all the CSS on this class instead of the ID. For all other options, you'll go in your theme & use a custom walker for your menu. If the id remains constant, you can add or ignore the particular item from being displayed depending on some condition. It is also possible to add a checkbox(let's say) to every menu item, then check that value in your custom walker & deactivate the menu item accordingly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, menus, wp admin, css" }
Post_count only shows the number of results per page I have a wp_query `$wp_query = new WP_Query($args);` but for some reason the `$wp_query->post_count` only shows the amount of posts on each page. So if I set `'showposts' => '10'` and 12 results are found, page one will say '10 results found' and page 2 shows '2 results found'. Why is this? I can't figure it out. $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' => 'post', 'showposts' => '10', 'paged' => $paged ); $wp_query = new WP_Query($args); echo "Search found ".$wp_query->post_count."results"; if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); // the loop
`$wp_query->post_count` is supposed to work exactly like that. To get the total number of posts that exist in the database, use `$wp_query->found_posts`
stackexchange-wordpress
{ "answer_score": 42, "question_score": 21, "tags": "wp query, pagination, search" }
Change rss title of individual feeds? I want to set a custom title to indiviual rss feeds. Right now my post feed runs under a page called podcasts and the title of my rss feed then becomes `<blog name> » podcasts` because it is the feed of the podcasts page. However I would like to replace the slug `» podcasts` with the subtitle of my blog. How can I replace the title of the feed under posts or category? I have seen the answer RSS Feed Custom Title? here but this does not remove the slug for me ... but appends it! Help is appreciated.
Easy Fix ... since I use feedburner I can use their "burn feed title" service, which does exactly what I want!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, rss, feed" }
Changing the wp-config.php broke the site I added the lines `define( 'WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/blog/wp-content' );` and `define( 'WP_CONTENT_URL', 'example/blog/wp-content';);` in my wp-config.php and then my site broke. Even some of the widgets on the backend do not appear anymore. I immediately removed the above lines from the `wp-config.php` however that did not change anything. PLEASE HELP
There're some things you should _not_ play around with, until you really know core inside out and one of those things are the Path constants that _can_ be set in your `wp-config.php`. Here's how I do it. Note, that it's uncommented, so it doesn't trigger and WP uses its default. # define( 'WP_CONTENT_DIR_NAME', 'wp-content' ); # define( 'WP_CONTENT_DIR', ABSPATH.WP_CONTENT_DIR_NAME ); # define( 'WP_CONTENT_URL', WP_SITEURL.WP_CONTENT_DIR_NAME ); There're dozens of things you shouldn't touch in there, but Path constants and the Proxy settings are those that can get broken most easily. WP uses for nearly everything a default and you should simply let it do its job. Aside from having nothing from a dir name change (maybe security through obscurity) it will let a lot of plugins break that don't consider those things.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp config" }
Allow multiple contributors to one post I have been asked how easy it would be to have multiple contributors being able to submit content that would be brought into one post. The rub is that they wouldn't be allowed to see the main post or edit the post, this would be reserved for the site admins - their role would be mainly around adding their piece of the post into the mix and that would be it. I know this isn't standard functionality, but I don't even know where I would begin looking for a plugin - I could roll my own but if this is a solved problem then I would rather utilise that fact. So I guess my main question is _Is this a common power-user feature and what name does it go by?_ This is essentially to replace the current system that involves people emailing in content that gets copied and pasted into the post.
Perhaps you could use scribu's Posts 2 Posts plugin to relate a Custom Post Type called "Drafts" (or something else to avoid possible conflict with naming conventions reserved for Post Status). It's a very powerful plugin, allows Posts to be related to other Posts. In this way you could bring in the content of the Draft post type **into** the end product. Or just relate them for reviewing purposes. Depends on what you're really trying to do.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts" }
wordpress multisite domain mapping redirects to original subdomain This week I installed Wordpress 3.4.2 (Linux Centos + Apache2) and configured the network option using subdomains. Then I installed the MU Domain Mapping plugin, so I would be able to use it with domain names instead of subdomains. This works for one domain, however the second domain redirects to the subdomain. * base site: multisites.com * two subsites: one.multisites.com and two.multisites.com * two new domains: one.de and two.com.de * one.de works correct (based on one.multisites.com) * two.com.de redirects to two.multisites.com * NB: two.com.de is a subdomain of com.de, and this is similar to the actual situation! Two.com.de should not redirect. I don't see any differences in the setup. What could cause this and do you experience problems like this as well? * * * NB: I changed the domain names in the example to make it more clear.
Check if the Primary option is selected for the second domain under domain mapping settings. It should say Yes under Primary in Settings->Domains for that domain.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, apache, domain mapping" }
Is there anything like admin_notices for front end? I'm new to Wordpress and trying to take advantage of the framework as much as possible. On the front end, I want a centralized message area to display error, success, and general notices similar to how they're handled via admin_notices on the back end. I'm not seeing a similar hook for the front end. I guess I'm asking which action should I be hooking into on the front end to mimic admin_notices?
There is no such action in the front end (in a theme) by default. Simply use a custom action like do_action( 'theme_notices' ); and hook into this one.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 11, "tags": "front end, notices" }
Why does WP recommend against custom favicon functionality in themes? I am developing a WordPress theme, and when reading the Codex article on Theme review, WP recommendeds against allowing custom favicons in a theme. Does anyone know the reason for this recommendation? From the Codex: > Favicons > Themes are recommended not to implement custom favicon functionality. > If implemented, favicon functionality is required to be opt-in, and disabled by default. > If implemented, favicon functionality is required to support user-defined favicon images
Probably because a thing like a favicon is not necessarily tied to the on-page design, but to the branding of a site in general. In other words: it's not specifically part of the "display" of the site. If a theme does choose to implemented it, an ender user might not want it (opt-in only) or they may want to use their own favicon (user-defined) to fit with their branding.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "theme development, codex, favicon" }
How to tell if Jetpack's Photon is active? There are multiple ways to identify if a plugin is active (here's one) but how can we identify if a specific JetPack component is active, for example Photon?
We just committed a new function to Jetpack Trunk, and it should be enabled in the next release, `Jetpack::is_module_active()` \-- < Then you can just call: if( class_exists( 'Jetpack' ) && Jetpack::is_module_active( 'contact-form' ) ) {} Or at least, you will once the next version releases, and the user has their Jetpack updated. :) If you'd like to preserve the backward compatability, you can just do: if( class_exists( 'Jetpack' ) && in_array( 'contact-form', Jetpack::get_active_modules() ) {} It's a slightly tidier way than querying the option directly.
stackexchange-wordpress
{ "answer_score": 12, "question_score": 5, "tags": "plugins, plugin jetpack" }
Where did the "WP-Custom" plugin go? There used to be a plugin called "WP-Custom" in Wordpress plugin base. Does anyone know what its new name or where I can get it? Wordpress shows no sign left of it.
According to the author's website, the plugin has been removed as it is no longer beneficial when custom post types are available. However, if you are so inclined, you can download it from the above page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
How To Export/Import WordPress (MySQL) Database Properly Via Command-Line? Normally, a MySQL database can be exported and imported using these simple SSH commands: **Export:** mysqldump -u USERNAME -p DATABASE_NAME > filename.sql **Import:** mysql -u USERNAME -p DATABASE_NAME < filename.sql But it's not that simple when it comes to WordPress. From what I see, additional parameters need to mentioned, such as `--add-drop-table` for instance. The WordPress Codex does provide some info, but it looks cluttered and not clear enough. It would be great if someone who uses command-line can share the proper commands to export and import a WordPress database, with some explanation (of any new parameters used). Also, are there any reasons why it wouldn't be advisable to use command-line when dealing with database, and instead go with a GUI like phpMyAdmin?
It is that simple for Wordpress too. I use the following to back up my WP sites: mysqldump -u <user> -p<pass> --quick --extended-insert <db-name> > backup.sql The mysqldump document gives the details on all the parameters. `--extended-insert` is quicker when updating a DB from a dump file and makes the dump file smaller. `--quick` makes the creation of the dump quicker. You don't really need to use either of those, just makes things a bit quicker and writing an insert for each row just makes me feel happier - your original dump syntax would be just fine. Don't forget though that there is domain-specific entries in the DB so if you are using this method to backup/restore then you are fine but if you want to move from one.com to two.com then you will need to edit entries in `wp_options` after you restore your dump.
stackexchange-wordpress
{ "answer_score": 14, "question_score": 7, "tags": "database, mysql, import, export, command line" }
Wordpress installation from live site to localhost I just need to know if this is the only way to install wordpress from live to localhost. I downloaded the files and database from live, then push the files folder to my htdocs folder, and uploaded the db through phpmyadmin and change the config file. Upto this point I think im on correct side. After entering ` URL in web browser site loads in correct way, however link seems to be still pointing the old (live site) URLs. So for this I search my live site URLs in the DB like -- ` and replace this with the ` URL. So my question is if this is the correct way i am implementing it on my locals or some more appealing method i am missing.
Update your `wp_options` table. Look for `siteurl` and `home` and change their values to point to your localhost, that is, ` This should be enough to make your site work again. You don't need to find and replace all instances where the old url is present. For example you should not change the `guid` of your posts. Alse read this post on Moving Wordpress.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "installation, localhost" }
How do I park secure.primary.com on top of the multisite ID:1 domain: www.primary.com (primary multisite domain) We have a multisite setup, the primary domain needs to have www.primary.net, and secure.primary.net mapped in wordpress so the primary site's content loads on both. The problem we are facing is secure.primary.com doesn't work. secure.primary.net always ends up at: < The headers returned from the server are as follows: Status: HTTP/1.1 302 Moved Temporarily Date: Tue, 16 Oct 2012 19:55:53 GMT Server: Apache Location: < Content-Length: 0 Connection: close Content-Type: text/html; charset=utf-8 Basically I just need this to work, even if it means ripping into the core Wordpress files and making changes. I've tried various domain mapping plugins and such and nothing works correctly. One of the problems is that they don't allow mapping on the primary network domain. Any suggestions on what I can edit in WordPress or a starting point would be great. Thanks.
Install WordPress MU Domain Mapping _Plugin_, and edit the `wp_domain_mapping` database table. Insert a new row for `blog_id` #1 manually, for example: +------+-----------+----------------------+----------+ | id | blog_id | domain | active | +------+-----------+----------------------+----------+ | 5 | 1 | secure.primary.com | 1 | +------+-----------+----------------------+----------+
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "multisite, domain mapping" }
Is the part "category" fixed to an URL to an archive or post? I'm asked to set up a WordPress-based site, which is not intended to run as blog mainly but anyway we want to use the common article area sometimes. Now my client resents that the URL to an article or archive includes "/category/". He wants to make use of tags but categories are redundant since he only wants to have an area called "news" which holds all stuff written as common articles. So my question is: Can I set my theme to simply make URLs like this: "example.com/news/an-article-about-something"?
By default, the URL to an article does not include "category". Only URLs to category archives do, so it sounds like something has already been re-configured. Anyway, to get the string you want, go to wp-admin->Settings->Permalinks and set the permalink structure to "/news/%postname%/". That will put the blog posts at "/news/" If you also want the blog index at "/news/", create a page named "news" then go to wp-admin->Settings->Reading, click "static page" and set the "posts page" to "news". You will need to set the static front page to some other page or you will get a blog index there too-- same thing in both places. The same "Permalinks" settings page will let you change the "category" and "tag" strings, which show upin category and tag archive URLs. Look down at the bottom.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, permalinks" }
how to refresh index page without reloading browser using ajax the desire i want is similar on how facebook works; when a new content is being published, it pushes down the old post with the new posts on top. * New Content (pushes down previous topics without reloading the page) * Old Content 1 * Old Content 2 * Old Content 3 is that possible in wordpress?
The used term for this is "infinite scroll", there are plugins that may assist you to achieve this behavior, you can check this one: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, ajax" }
How to direct user to actual 404 page when a check is false in single.php? Can someone tell me how to direct a user to the main 404 file instead of having to print an error message saying "file not found" in single.php? For example: <?php if (!$myVar) { // go to 404.php and return an official file not found header } else { // show the following HTML } ?>
You can use the `locate_template()` function to include the 404 template. Remember to do this instead of using `get_header()` or generating any output; otherwise you will have a duplicate. <?php if ( ! $myVar ) { status_header(404); global $wp_query; $wp_query->is_404 = true; locate_template('404'); return; } // otherwise, show the following HTML
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "404 error, single" }
How to: When a bp Group created, automatically create a wp category example: a user creates a group "cats" automatically a category "cats" would be created with the slug "cats" or a user creates a group "Fat Cats" automatically a category "Fat Cats" would be created with the slug fat-cats. I see there is a function wp_create_category : However,to be frank, i'm lost. Have tried, with adding this near end (line310) of child-theme/groups/create.php but no dice Any help or ideas really welcome
There is an action where you can hook in. It is called: 'groups_created_group'. My idea is, that you hook into that and select the last group that was created. In database groups have a field called 'date_created'. So just read the name of the last one and create your group out of that. You have to write this in your functions.php file of your theme: function createCatAfterGroup() { global $wpdb; $group = $wpdb->get_row("SELECT * FROM `wp_bp_groups` ORDER BY date_created DESC"); wp_insert_term($group->name, 'category'); } add_action('groups_created_group', 'createCatAfterGroup');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "buddypress" }
How to store datetime from custom meta box so that it can be sorted by I have a custom meta boxe on a custom post type that has two date time fields. I will need to sort by these fields and also return posts that contain a date between two dates. Will WordPress automatically store these dates as varchars? What will be the best format to save the date in so that I can query them?
Post meta is stored in the `wp_postmeta` table. Values are stored as longtext, not as dates or integers. So your safest bet is to store these datetime fields as Unix timestamps. Then you can sort them using a meta query.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field" }
Wordpress Add New User - Send an Activation Email I edited the Add New User Profile page to add some custom fields (I'm not using multisite). My question is if there is a way to send out an activation/confirmation email to new users once I manually add them in? Thanks!
Solved it by adding this code to save_extra_profile_fields() in add_action ( 'user_register', 'save_extra_profile_fields'); $hash = md5( $random_number ); add_user_meta( $user_id, 'hash', $hash ); $user_info = get_userdata($user_id); $to = $user_info->user_email; $subject = 'Member Verification'; $message = 'Hello,'; $message .= "\n\n"; $message .= 'Welcome...'; $message .= "\n\n"; $message .= 'Username: '.$un; $message .= "\n"; $message .= 'Password: '.$pw; $message .= "\n\n"; $message .= 'Please click this link to activate your account:'; $message .= home_url('/').'activate?id='.$un.'&key='.$hash; $headers = 'From: [email protected]' . "\r\n"; wp_mail($to, $subject, $message, $headers);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "email, profiles, email verification" }
How to get changed post title in my custom plug-in which fires when 'save_post' is called? I created a custom WordPress plug-in that hooks onto 'save_post" using add_filter(). I need to do something with the post titles and whenever a user changes the title, my plug-in cannot get the new title until the post is updated a second time (without changing the title in the admin a second time). For example, I have a post named "WordPress Rocks". I change it to "WordPress is Cool", but my plug-in shows the title as being "WordPress Rocks" using get_the_title($post_id) when updating the post. I go back and make a second update to the post, this time without changing the title. This next time, get_the_title($post_id) shows the title is "WordPress is Cool". How can I grab the updated title (if it's changed) as soon as the post is updated?
The second argument of the `save_post` action contains the post data: do_action('save_post', $post_ID, $post); You can also hook `post_updated` which will let you easily compare the before/after data: do_action( 'post_updated', $post_ID, $post_after, $post_before);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, filters, save post, get the title" }
Track advertisement earnings per blog post and page in wordpress? I have this unique situation (though i doubt it no one has ever asked this before!). I want to track advertisement earnings from a service like Adsense per blog post and per page or per author . Why i want to achieve this ? we are quite a few number number of authors in this new website we are launching .In order to answer any future discrepences that might occur and effective profit sharing. If its not possible with adsense is there any decent enough alternate offers this feature please suggest? Alternatively is there any tracking plugin or some service like google analytics that can be of help? if possible is there any way to export this data also?
Google Analytics offers this feature and pretty much the way you wanted it. In GA, in the Content Section, check the AdSense subsection ... specifically the AdSense Pages report. It tells you page wise which content has generated how much revenues. And yes, these reports are exportable in CSV format which open in Excel. If I were you, I would put the posts and authors in one worksheet, the AdSense Pages report in another and do a vlookup in Excel for finding out the author-wise AdSense earnings.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "google analytics, statistics, adsense, ads" }
Count to how many categories a post belongs to Is there a possibility to count to how many categories a post belongs to?
Use `get_the_terms()` and count the resulting array: print count( get_the_terms( $post->ID, 'category' ) ) . ' categories';
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "posts, categories, count" }
Order posts by price I have a list of products on a page and am trying to order them by a custom field called "price". Unfortunately, $3,950,000 is coming before $349,000. I've used a couple of codes but neither one is working. Does anyone have any suggestions? Thanks. Here's the first code I've tried. $query = new WP_Query( array ( 'post_type' => 'product', 'orderby' => 'meta_value', 'meta_key' => 'price', 'order' => 'ASC' ) ); Here's the other code I've tried. $query = new WP_Query( array ( 'post_type' => 'product', 'orderby' => 'meta_value_num+0', 'meta_key' => 'price', 'order' => 'ASC' ) );
You are storing your "price" (apparently) as human readable formatted currency. That makes it a string. And that means it is going to be sorted alphabetically, more or less, and not numerically as you need it to be. If you can store those values without the punctuation, and use `meta_value_num`\-- your second query above (but I am not sure you need the "+0") -- I think you will have what you want.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "order" }
Set RSS feed update time I want to update my feed just once a day. For example: I want to update the feed every day at 12:00 pm. How to do this without a plugin ?
The RSS feed is "updated" every time you post something new. If you want it to always be updated at 12pm then schedule your posts to always be published at 12pm.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "rss, feed" }
How to disable the_excerpt from one post I have this code for the_excerpt : function get_excerpt(){ $excerpt = get_the_content(); $excerpt = preg_replace(" (\[.*?\])",'',$excerpt); $excerpt = strip_shortcodes($excerpt); $excerpt = strip_tags($excerpt); $excerpt = substr($excerpt, 0, 640); $excerpt = substr($excerpt, 0, strripos($excerpt, " ")); $excerpt = trim(preg_replace( '/\s+/', ' ', $excerpt)); $excerpt = $excerpt.'<a class="read-more" <a href="'. get_permalink($post->ID) . '">read more.</a>'; return $excerpt; }` I want to disable from one post the_excerpt. I think that this part of function helps but this is not happened. if( in_array( $post->ID, array(post_ID) ) ) get_the_content(); else get_excerpt();
First of all, WordPress already includes a function for displaying excerpts: `the_excerpt()` Secondly, your second piece of code isn't actually displaying anything. You need to use the `echo` statement for displaying text on the page. However, WordPress provides functions that actually display the content and excerpt on the page: `the_content()` and `the_excerpt()`, respectively. if( in_array( $post->ID, array(post_ID) ) ) the_content(); else the_excerpt();
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, the content, excerpt" }
Landing Page - Redirect Loop? Recently this solution was given (Thanks Mr.D), for this Wordpress redirect to landing page if not logged in thread <?php if($_SERVER['REQUEST_URI'] != '.../' || $_SERVER['REQUEST_URI'] != '.../'){ if(!is_user_logged_in()) { wp_redirect( ' 301 ); exit; } } I recently tried this piece of code and it works if i substitute say "< However, if I substitute it with mydomain.com/landingpage i get a redirect loop error. Any ideas? Thanks!
What's happening is you're sending an unauthenticated visitor to a certain page. The code in that page also picks up that the user is unauthenticated, and sends them to the page that they're already on. Because the page keeps on sending the visitor to the same page, the visitor can't go anywhere. This is called a **redirect loop**. You're on the right track with the `$_SERVER['REQUEST_URI']` check. However, paths like `../` and `.../` won't work. You need to use the actual URL of the page that you're redirecting to (sans the domain and protocol). Essentially, you need to use this code: if ( trim( $_SERVER['REQUEST_URI'], '/' ) != 'landingpage' && ! is_user_logged_in() ) { wp_redirect( home_url( 'landingpage' ), 301 ); exit; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, redirect" }
Why would admin-ajax.php redirect to the home page for logged out users? I am using the wp-polls plugin on my website. This plugin relies on using AJAX requests of the form When I log in, this request works fine: it pulls the poll results from the server, and then displays them on the desired web page. However, when I log out, this request redirects me to the home page. Thus, instead of the poll results appearing, I get the home page loaded where the poll results are supposed to be. Why would admin-ajax.php redirect visitors to my Wordpress-powered site who are not logged in to the home page of my website?
It only redirects when accessed directly, as do all files located in `wp-admin/`. AJAX requests should work fine regardless of authentication status. **Edit:** `wp-admin/admin-ajax.php` should _not_ redirect in any situation. Perhaps a plugin is redirecting all unauthenticated users to the homepage? By default, accessing files inside wp-admin/ when not logged in should redirect to the login page.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "ajax, poll" }
The comment login form is visible to me but not to the user I am beginner in wordpress & i am working on my own blog ( < ). Right now i am facing an issue with the comment form. The comment form is visible to me & it's work fine but is not visible to the user. Check this < I want a comment form like smashing magazine have. Please give your suggestion thanks :)
You have commenting turned off for logged-out users. To change this setting, visit the _Settings > Discussion_ page in your WordPress admin and uncheck the **Users must be registered and logged in to comment** box. Remember to update the setting by clicking the **Save Changes** button. !WordPress Discussion Settings
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "comments, comment form, wp login form" }
Delete post from admin but not from database Is it possible to have a post not deleted from the MySQL database on deleting from the wp-admin panel ?
By default wordpress do not delete posts but rather moves them to the trash. They do not appear in the normal posts admin, but you can still see them in the trash and recover them from it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, customization" }
Import / Export Settings API fields values? I've been storing all my theme options using Settings API for some time now and it's lacking one functionality. I have multiple pages (different servers) using my custom themes and I would love to move settings between them, I mean I'd like to export all the Settings API fields values from theme 1 and import them to theme 2. Are there any plugins out there / any ideas how to achieve that?
I just came across this wp.tuts tutorial a few days ago: > Creating a Simple Backup/Restore Settings Feature > `Lee Pham on Jun 22nd 2012` > In this tutorial, I’m going to show you how to create a simple backup/restore feature for your WordPress blog. With this feature, you can backup all options to another place, that you can restore them from at any time without configuring them again. It's wrapped as plugin, so you can jump straight to testing. As it is, it exports **all the site options** using the function `get_alloptions`. So, the first thing is change that to your own option - supposing you are following the best practice of having all of them into a single serialized value. Works quite nice :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "settings api" }
Using dynamic conditions in 'posts_where' filter I have the following code which gives be posts that are published in the last 100 days function smbd_cats_by_days ($where = '') { $where .= " AND post_date < '" . date('y-m-d', strtotime("-100 days")) . "'"; return $where; } add_filter('posts_where', 'smbd_cats_by_days'); It is working fine. But now I want to make this function generic. (ie) I want the number of days to be stored in a variable instead of hard coding it as 100. How to do that?
I was afraid you wanted that one. You can't really do that. Follow the link for some workarounds. You could also set a variable or a constant in `functions.php`, or create a theme option for this. Then use that in your function. function smbd_cats_by_days ($where = '') { // global $days_limit; // if a variable // $days_limit = DAYS_LIMIT; // if a constant // $days_limit = get_option('days_limit',100); // you have to uncomment one of the above, // depending on your choice of mechanisms $where .= " AND post_date < '" . date('y-m-d', strtotime("-{$days_limit} days")) . "'"; return $where; } add_filter('posts_where', 'smbd_cats_by_days'); <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "query posts, filters, query, posts where" }
how to list subpages in sidebar without widget I am trying to create a list of subpages of a parent page, which will appear in the sidebar of my wordpress site. This sidebar will appear on every page. So for example, I have a page with an ID of 54. This page has 7 subpages. I would like to display these 7 pages in the sidebar (just the titles), as well as any more subpages that get added. There is a currently a widget called 'Pages' that will do this, but I would like to do this via code directly in the sidebar.php rather than using a widget as there are a few constraints with using the widget.
Simplest solution would be: <li><ul> <?php wp_list_pages('title_li=&child_of='.$post->ID.''); ?> </ul></li> Use this code for more flexibility: <?php if ( is_page() ) { ?> <?php if($post->post_parent) $children = wp_list_pages('title_li=&child_of='.$post->post_parent.'&echo=0'); else $children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0'); if ($children) { ?> <li> <h2> <?php $parent_title = get_the_title($post->post_parent); echo $parent_title; ?> </h2> <ul> <?php echo $children; ?> </ul> </li> <?php } } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, sidebar, children" }
hide block of code from showing on certain pages Just to warn you, I am a complete PHP novice! I have one sidebar for all pages, however I would like to display certain elements on this sidebar for certain pages. I know there are a few widget plugins, however I am not using widgets, I am just coding in the sidebar.php file. I am aware I can do this... <?php if( is_page('37') ):?> SHOW STUFF <?php endif;?> ... for showing the content if on that page, but what is the opposite of this? So that 'SHOW STUFF' does not show if we are on page 37? Thanks in advance
So, you can use: <?php if( !is_page('37') ):?> SHOW STUFF <?php endif;?> P.S. ! (not parameter) Good tutorial - <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "conditional tags" }
Showing code only on Front Page "Posts Page" I have some code that I would only like to be displayed on the sidebar when on the blog (the page that displays the posts). Now I am using this code... <?php if(is_page('37')) { ?> ...Show code... <?php } ?> The strange thing is if I enter any other page ID, it works as expected and shows the code, however, when I enter ID 37 (blog page), the code does not show on the blog page. Do I need to do something differently as it is my main post page and not a regular page? _P.S By Post page, I mean the page I have set in the wordpress admin where posts should be displayed._ !wp-admin reading settings
Got it! Turns out I should be using `is_home` which seems to work. More info here.. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "conditional tags" }
problem with not displaying content on selected pages My objective - Display some code on every page apart from 2 pages. Now this code works fine with only one page (if its not `is_home`, display code)... <?php if (!is_home()) { ?> (some content) <?php ?> ... but when I try to do it for two pages, the rule fails, and the code is displayed on both the pages where I do not want it visible... <?php if( !is_home() or !is_archive()) { ?> (some content) <?php ?> I am unsure why this fails, any help would be great. Thanks in advance.
If you're testing against two falses you have to use the logical AND operator, because BOTH have the be false. <?php if( !is_home() && !is_archive()) { ?> (some content) <?php ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "conditional tags" }
How to create a second posts page which client can update Bit of a wordpress novice and so just wanted to know the best way to do this. I am currently creating a wordpress site for a client. They have a Latest News section which is the primary 'blog'/posts page. The sidebar also displays the latest blog post. Now what I would like to do is create a Special Offers page, which works the same as the blog post page, displaying the latest offers, and which the client can update easily through the admin. I would also like to feature the latest special offer in the sidebar. What would be the best way to do this, as I am assuming you can only have one main posts page? Any help would be greatly appreciated. Thanks
This is a perfect case for custom post types Simply create a post type called "specials" and you can use it just like your regular posts. EDIT: If you're new to WordPress and aren't interested in editing PHP, you can use a plugin like the Custom Post Type UI
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts" }
Changing wp_link_pages() to "Next Page" and "Previous Page" buttons? Currently I am using `<!--nextpage-->` to split a post into multiple pages, but I would like to change from `Pages: 1 2 3 4` to `Next Page` and `Previous Page` links similar to what you see on this multipaged post In my `single.php` I have: <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'pearl' ), 'after' => '</div>' ) ); ?> How can I change this to a next and a previous button?
Use the `'next_or_number'` parameter: wp_link_pages( array ( 'next_or_number' => 'next' ) ); See the Codex for details.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, loop, pages, single, wp link pages" }
order by multiple meta_keys? Hi i'd like to order by multiple meta_keys want to make it order using these keys adminscore + user_like + _count-views_all + comment_count combine these keys how should i array order it?? i try this but not work.. $args = array( 'meta_key' => 'adminscore' + 'user_like' + '_count-views_all' + 'comment_count', 'numberposts' => $number_posts, 'post_status' => $post_status, 'post_type' => $custom_post_type, 'orderby' => 'meta_value_num' ); Thanks for check my question, hope someone has answer for it.
This line is wrong: 'meta_key' => 'adminscore' + 'user_like' + '_count-views_all' + 'comment_count', `'meta_key'` only accepts string value. What you need is an additional meta key, e.g. "totalscore" that holds the total value of the scores you have for all the meta values. You can manually run a php function that calculates and store the totalscore value from time to time or use wp_schedule_event to run the function on a set interval. You can then write the $args as such: $args = array( 'meta_key' => 'totalscore', 'numberposts' => $number_posts, 'post_status' => $post_status, 'post_type' => $custom_post_type, 'orderby' => 'meta_value_num' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "post meta, meta value" }
How do I get link URLs from the Wordpress links backend into an array? I'm currently running a blogroll on a site I'm working on by defining a variable with an array that has all the rss feed urls I want to pull from. Like this for example: <?php // Get RSS Feed(s) include_once(ABSPATH . WPINC . '/feed.php'); $rsslist = array( ' ' ' ); $rss = fetch_feed($rsslist); if (!is_wp_error( $rss ) ) : $maxitems = $rss->get_item_quantity(25); $rss_items = $rss->get_items(0, $maxitems); endif; ?> What I would like to figure out is rather than entering in each feed url in the code as above I want to pull the rss links from the wordpress links backend. Using something like the wp_get_bookmarks() function. Any help would be greatly appreciated! Thanks much!
I believe that you're looking for the `get_bookmarks()` function, which returns an array of bookmark objects. You could then implement this into your code: <?php // Get RSS Feed(s) include_once(ABSPATH . WPINC . '/feed.php'); $bookmarks = get_bookmarks(); $rsslist = array(); foreach ( $bookmarks as $bm ) { if ( $bm->link_rss ) $rsslist[] = $bm->link_rss; } $rss = fetch_feed( $rsslist ); if ( ! is_wp_error( $rss ) ) { $maxitems = $rss->get_item_quantity(25); $rss_items = $rss->get_items( 0, $maxitems ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "links, rss, array, feed, get bookmarks" }
Move from old custom field to new post_thumbnails I've just taken over a busy WordPress site that's got ~800 posts so far. The site's been around long enough that it was started up before post_thumbnails was available. They worked around that shortcoming with a custom field called 'Image' that held a value of the relative path to the image, e.g., "/wp-content/uploads/2012/11/image.jpg" The theme is using Tim Thumb to make the different thumb sizes. I'd love to get away from this and just use the post_thumbnails feature and set the sizes in functions.php and get rid of timthumb.php altogether. I've searched, but haven't found a good way to make the switch. Any suggestions?
Had the same issue last week and here is what i did: if (has_post_thumbnail()) //if the post already has a post thumbnail then just use that the_post_thumbnail($size = 'post-thumbnail', $attr = ''); else{ //if not then convert the custom field to the post thumbnail and display that $at_url = get_post_meta($post->ID, 'image', true); $at_id = get_image_id_by_url($at_url); delete_post_meta($post->ID, 'image'); if ($at_id){ set_post_thumbnail($post, $at_id); the_post_thumbnail($size = 'post-thumbnail', $attr = ''); }else{ //else just display a default image or not :) } }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "custom field, post thumbnails" }
How do you use prepare when asking for a list of id's I'm looking to get a number of records back from the database given a list of numbers and was wondering how I would use $wpdb->prepare to do this (to take advantage of the sanitising vs SQL injection attacks that it gives me). A wrong way of going about what I'd like to achieve is `$wpdb->query($wpdb->prepare('SELECT * FROM wp_postmeta WHERE post_id IN (' . implode(',', $ids) .')` but this gives the chance of an SQL Injection attack (imagine one of the ids having the value "0); DROP TABLE wp_posts;"). NOTE: I'm not trying to select data from wp_postmeta, I'm just using it as example.
`$wpdb->prepare()` use the same syntax for formatting like php's `printf()`. SSo you will need something like `... WHERE post_id IN (%d,%d,%d) ...` This will fit for three ids. But what if we got more or less than three ids? We will use the php tools to create the needed formatting string (assuming `$ids` is an array with the ids): Count the IDs count( $ids ) Create a string with a '%d,' for every ID in $ids str_repeat( '%d,', count( $ids ) ) Now we have a string like `%d,%d,%d,`. There is one comma to much at the end. Let's remove it $ids_format_string = rtrim( str_repeat( '%d,', count( $ids ) ), ',' ); And use this in this way `'... WHERE post_id IN (' . $ids_format_string . ') ...'`
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "wpdb, sql" }
jQuery inluclude still seems ncessary for script to work within post I have a jQuery script that works fine within a WordPress post as long as I include a reference to the jQuery libarary within the post. `<script src=" From what I have read this is not the proper way to reference jQuery as it is already included within WordPress (using v3.4.2). If I remove the inline reference the script fails and the console says that "$" is undefined. I also tried replacing "$" with "jQuery" according to articles that talk about NoConflict mode in jQuery. My jQuery script can be viewed here in jsFiddle.
In order to use $ inside your script (You only need to change the wrapper of your script), use the following wrapper. jQuery(document).ready(function($) { // $() will work as an alias for jQuery() inside of this function }); Make sure you enqueue jQuery in one of your plugins or theme using `wp_enqueue_script('jquery');` Read more on Codex > < The following article contains useful tips on using jQuery with WordPress. > <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, jquery" }
Royalty-Free Sliders used in theme development I am wanting to develop a premium Wordpress theme, and would like to know what is the best way to go on choosing a slider. I'm not skilled enough yet to write one from scratch. The ideal situation for me would be to use a Royalty-free slider (slides.js?) and then create different designs from that single slider. Is that okay? Any help would be appreciated. Thanks!
What about Anything Slider? I think it's open source. <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, theme development, jquery, licensing" }
How to modify/ customise NextGen Gallery's templates? I would like to customise the "Image browser" template in particular. I'm trying to make clicking on an image redirects to the next image in a gallery, just like how Facebook image browser works. (This is not a cosmetic change with CSS - CSS change is not what I mean by customising the tempaltes) I can always edit `/wp-content/plugins/nextgen-gallery/view/imagebrowser.php` but it's a hack and it's not upgradable when next version of NextGen Gallery is out. Is there anyway I can overwrite the template imagebrowser.php in my theme?
One can do that by copying `imagebrowser.php` from /`wp-content/plugins/nextgen-gallery/view/ to yourthemedirectory/nggallery.php` If you want to customise other templates, you can do the same too. Some more information can also be found here.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, templates, plugin nextgen gallery, template hierarchy" }
Shortcode output appears before post body > **Possible Duplicate:** > short code output too early How can I insert my plugin code via shortcode inside post body in exact position? The problem is that wp engine inserts the plugin code **BEFORE** post body all the time. Can it be fixed? For example: I have some `[shortcode option="value"]`, that generates some text with image inside div container. When I put it inside the post **AFTER** the text, wp outputs this code: `<div> here is my plugin code </div> <p> here is the text of the post </p>` … and so it gets in the top of the post. Where is my fault?
I have had this problem before: shortcodes shouldn't **display** any content (using `print` or `echo`), instead `return` the content to be outputted. If it's too much trouble converting all of your output statements, or you need to use a function that will always display the output, you can use **output buffering**. A buffer will 'catch' any `echo`'d or `print`'d content and allow you to write it to a variable. function my_awesome_shortcode( $atts, $content = null ) { // begin output buffering ob_start(); // output some text echo 'foo' . "bar\n"; $greeting = 'Hello'; printf( '%s, %s!', $greeting, 'World' ); // end output buffering, grab the buffer contents, and empty the buffer return ob_get_clean(); } add_shortcode( 'awesome', 'my_awesome_shortcode' ); Learn more about Output Buffering Control and the different Output Control Functions that you can use.
stackexchange-wordpress
{ "answer_score": 14, "question_score": 4, "tags": "plugins, shortcode" }
Count singular post views automatically I'm trying to add some function to each loop called in the themes. What I'm doing is I add a function to count post view from here post views without plugin, to use the function I need to add this line `<?php setPostViews(get_the_ID()); ?>` to `single.php`, `page.php`, etc. I want to know whether I can use some hook to automatically add the `<?php setPostViews(get_the_ID()); ?>` line without hard code it for each `single.php`, `page.php` files.
You could hook into `template_redirect` and execute a helper function: add_action( 'template_redirect', 'wpse_75558_count' ); function wpse_75558_count() { if ( is_singular() ) setPostViews( get_the_ID() ); } To **display** the post views, you have to use a later hook. I would recommend `the_content`: add_filter( 'the_content', 'wpse_75558_show_count' ); function wpse_75558_show_count( $content ) { $count = getPostViews( get_the_ID() ); if ( ! is_numeric( $count ) ) $count = ''; // prevent errors showing to visitors else $count = "<p class='view-count'>Views: $count</p>"; return $content . $count; } Just an idea, I haven’t tested the code.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, loop, hooks, actions, count" }
How to use same email for multiple users I have a very big multisite. And I got a request to enable option that multiple users can use the same email. I found a plugin "Allow Multiple Accounts" which doesn't work properly. I should figure out some other solution for that. I know that I could use something like adding +sometext to every email, so it will show different to Wordpress. Do you have some other solution, that can be done here?
You can use `wpmu_validate_user_signup` filter to remove the error and then define `WP_IMPORTING` just to skip the `email_exist()` check in `wp_insert_user()` function: add_filter('wpmu_validate_user_signup', 'skip_email_exist'); function skip_email_exist($result){ if(isset($result['errors']->errors['user_email']) && ($key = array_search(__('Sorry, that email address is already used!'), $result['errors']->errors['user_email'])) !== false) { unset($result['errors']->errors['user_email'][$key]); if (empty($result['errors']->errors['user_email'])) unset($result['errors']->errors['user_email']); } define( 'WP_IMPORTING', 'SKIP_EMAIL_EXIST' ); return $result; } **UPDATE** : for a non Multi-site setup try this code: add_filter('pre_user_email', 'skip_email_exist'); function skip_email_exist($user_email){ define( 'WP_IMPORTING', 'SKIP_EMAIL_EXIST' ); return $user_email; }
stackexchange-wordpress
{ "answer_score": 16, "question_score": 15, "tags": "multisite, users" }
wp_insert_post disable HTML filter I have input value "`<iframe>....</iframe>`" (param 'post_content'). When i execute wp_insert_post, function cut off my tag. How to disable HTML filter in **wp_insert_post** ?
You could use call kses_remove_filters() before saving and call kses_init_filters() afterwards, but pay attention it will also remove filtering from title, excerpt and comments, So what you should do is just unset the content filters. // Post filtering remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses'); and after the post is saved // Post filtering add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
stackexchange-wordpress
{ "answer_score": 12, "question_score": 2, "tags": "security, wp insert post" }
Redirect user on second visit on page I have a page like a welcome page which should be visited only once by each subscriber. After registration, they will redirected on my welcome page. Then I want that page not be available on same user for the second time, if the will try, I want them to be redirected. Is this possible?, should I use plugin? Thanks. :)
As mentioned in a comment above the cookie solution will not totally do the trick. If it's ok that they can revisited the welcome page from a different browser or if they delete cookies. This is fine. If not I would use the database. I think easiest would be to regard the time the user was registered. Like if the user registered within the last 60 minutes offer the welcome page. If not forward somewhere else. This solution does not require you to alter the database and does not have the drawbacks of the cookie. If you want to offer a limited time offer for newly registered this might be a good way. You can even combine this with the cookie. That way you make sure the visitor can only see it once on his first device. And if he logs in on his second device more than 60 minutes later he will not see it either.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugin recommendation, redirect" }
When do I need to use esc_attr when using WordPress internal functions When I am putting a WordPress value inside the attribute tag, for example, the following method does not need `esc_attr` e.g. // JS code alert('<?php echo get_bloginfo('name');?>'); the following method does need `esc_attr` // JS code alert('<?php echo esc_attr($post->post_title);?>'); What is the convention used?
You can look at the Codex. > Encodes < > & " ' (less than, greater than, ampersand, double quote, single quote). Will never double encode entities. Given that, arguably, both of those strings need sanitization. Imagine a site name like `>> "My" Website's Great Title <<"` Also, since you are using this in Javascript, you should probably be using `esc_js` instead. The convention is, "understand how markup works, and how malicious hackers work, and act accordingly." That is how you know how to use these functions. Also, **Trust No One**. See also this article from our member Stephen Harris: Data Sanitization and Validation With WordPress
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "plugins, plugin development, escaping" }
Automatically adding images to a certain page through the Media Uploader I have a plugin that calls the Media Uploader to allow users to add images to a Page. The uploader is being displayed and taking images fine, but it is not attaching them to Page ID 65 as I wish (or showing images attached to that Page as in the Gallery). Am I missing something, or is this just not possible in WP? Thanks. jQuery(document).ready(function($){ $('.manage-images-button a.button-secondary').on('click', function(){ tb_show('Manage Front Page Images', 'media-upload.php?referer=dd-options&TB_iframe=true&post_id=65', false); return false; }); });
Bizarrly, the answer to this is to simply swap two of the parameters around - tb_show('Manage Front Page Images', 'media-upload.php?referer=dd-options&post_id=65&TB_iframe=true', false);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, media library" }
Create a shortcode that creates a form for users to edit their information I want to make it so that logged in users can edit their information on a page in my site, so that I can avoid having them go to the admin side all together. I was thinking that I could create a shortcode (in functions.php) that would create the correct table and insert it into the page. I am just starting out with PHP/WordPress so I'm not sure if this is the right path to follow - are there any good resources out there to point me in the right direction?
This very Stack is a great source of information. It'd be a matter of adapting a good answer and making a shortcode out of it. For this case, it is better to create your own plugin, see: Where to put my code: plugin or functions.php?. So you can swap themes and your shortcode will keep working.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "shortcode, users, front end" }
Practical Solutions to HTML5 Video on WordPress I was directed here from Stack Overflow -- We work with clients who have WordPress sites and one thing we keep struggling with is implementing HTML5 video across all browsers and devices in the WordPress environment. We've tried multiple plugins (JW Player, MediaElement, Sublime Video). It seems like each one has its own bugs, and are difficult to implement video play-lists on (Not to mention having a good UI for the client to manage/add videos themselves). What is a solid, reliable solution to HTML5 video on WordPress? Something that can support up to 4 file types at once (.mp4, .webm, ogg, flash) and possible have a playlist functionality. Should I ditch the plugin solution entirely and write the code myself?
In an old project, I ended up writing my own. And working with WordPress library to feed the players (audio and video), so there's no foreign UI and a template builds the player with the proper attachment info. The audio player was implemented with JPlayer. > ### The jQuery HTML5 Audio / Video Library > > jPlayer is the completely free and open source (GPL/MIT) media library written in JavaScript. A jQuery plugin, jPlayer allows you to rapidly weave cross platform audio and video into your web pages. jPlayer's comprehensive API allows you to create innovative media solutions while support and encouragement is provided by jPlayer's active and growing community. If my memory serves me well, I think I had to use another library to the video due to some playlist issues. And that was done with this premium player: HTML5 Video Player with Playlist. They have a WordPress plugin version, but I needed something very customized, so built my plugin with the Html5 code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, plugin recommendation, html5, video player" }
Show message on wordpress admin dashboard I have created a form. On success of the form, I am redirecting the user the their dashboard. Now, I want to be able to show a success message/notice on the dashboard. What is the convention to show such messages ?
When you redirect the user to the admin dashboard pass on a GET variable named "success_notice", for example. So you get a URL like this: `/wp-admin/index.php?success_notice=1`. With that setup, just add the code that shows the success message on the dashboard only if that GET variable is set. add_action('admin_notices', 'wpse75629_admin_notice'); function wpse75629_admin_notice() { global $pagenow; // Only show this message on the admin dashboard and if asked for if ('index.php' === $pagenow && ! empty($_GET['success_notice'])) { echo '<div class="updated"><p>Your success message!</p></div>'; } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "plugin development, wp admin" }
the_excerpt() or get_the_excerpt with shortcode escape I have few posts which have a dropcap shortcode wrapped around the first character like so: [dropcap]T[/dropcap]his is a dropcap. The replacement for this shortcode yields: <span class="dropcap">T</span>his is a dropcap. However, when I call the_excerpt() or get_the_excerpt() on these posts, its returning: "his is a dropcap". I need it to return "This is a dropcap" as if no shortcode exists.
You can make WordPress execute your shortcode in the excerpt by hooking into `get_the_excerpt` filter and overwriting the default `wp_trim_excerpt` function, which is responsible of stripping the shortcode tags from the excerpt as pointed by Chip: add_filter('get_the_excerpt', 'do_my_shortcode_in_excerpt'); function do_my_shortcode_in_excerpt($excerpt) { return do_shortcode(wp_trim_words(get_the_content(), 55)); } This is applied to both `the_excerpt()` and `get_the_excerpt()` outputs. If you want to apply it only for `the_excerpt()` output, hook to `the_excerpt` filter: add_filter('the_excerpt', 'do_my_shortcode_in_excerpt'); function do_my_shortcode_in_excerpt($excerpt) { return do_shortcode(wp_trim_words(get_the_content(), 55)); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "excerpt" }
Plugin:Read More Right Here , How to change the name (more...) to Read More Hi all I am using Read More Right Here Plugin when i using the `<!--more-->` Tag it appears like `(more...)` I need to know how to change the `(more...)` to Read More` Anyone Much appreciated!!
Add this to your functions.php file: function new_excerpt_more( $more ) { return 'Read More'; } add_filter('excerpt_more', 'new_excerpt_more');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, read more" }
Limit Loop to 5 Posts? Heres my current loop: <?php if ( ! empty ( $GLOBALS['post'] ) && is_single() && in_category( 'movies', $GLOBALS['post'] ) ) : $movies = new Wp_Query('tag=movie-reviews'); while ( $movies->have_posts() ) : $movies->the_post(); ?> <?php get_template_part( 'sidebar-reviews', get_post_format() ); ?> <?php endwhile; ?> <?php else : ?> <?php get_template_part( 'no-results', 'index' ); ?> <?php endif; ?>
$movies = new Wp_Query('tag=movie-reviews&posts_per_page=5');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, loop" }
How to add a Custom Meta Box for more than one Post Type? I am using the following code in `functions.php` for adding a custom meta box. The custom post type is `themes`. I want to add more post types, how can I? add_meta_box( 'my-meta-box-id', 'Demo & Download', 'cd_meta_box_cb', 'themes', 'normal', 'high' );
Whenever in doubt about a WordPress function, consult the Codex. < There, you'll see that you need to add one meta box to each post type. add_action( 'add_meta_boxes', 'myplugin_add_custom_box' ); function myplugin_add_custom_box() { add_meta_box( 'myplugin_sectionid', __( 'My Post Section Title', 'myplugin_textdomain' ), 'myplugin_inner_custom_box', 'post' ); add_meta_box( 'myplugin_sectionid', __( 'My Post Section Title', 'myplugin_textdomain' ), 'myplugin_inner_custom_box', 'page' ); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, custom field" }
Display old posts if no future posts exist I have a loop setup to display future posts but would like to set up an if statement where if there are no future posts, it will show a certain amount of published posts. My current query below: <?php query_posts('posts_per_page=5&order=ASC&post_status=future'); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> Any ideas?
example: <?php query_posts('posts_per_page=5&order=ASC&post_status=future'); if ( !have_posts() ) query_posts('posts_per_page=5&order=DESC&post_status=publish'); if( have_posts() ) : while ( have_posts() ) : the_post(); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "query" }
add short code not working I am new to wordpress, I am creating a plugin and for the short code, I am using the short code api. But when I insert this shortcode in my page, it displayes as it is, it does not display the required output. Can asny body tell me what i am doing wrong? Am I calling or creating the function on right place or not? Below is my code function show_review() { echo "this is a review form"; } add_shortcode('urp_review', 'show_review'); I have created the file named as urp_functions.php in my plugin directory and created the above function. Any help will be appreciated
Your code seems Ok, but is your plug-in correctly installed? You have to upload your urp_functions.php in a folder inside the /wp-content/plugins/ folder and in your urp_functions.php file, you have to insert comments so it gets detected as a plugin. here is the example comment on WordPress codex : <?php /* Plugin Name: Magic Plugin Plugin URI: Description: Magic Plugin performs magic Version: 2.3 Author: Mr. Magic Author URI: */ Then once you have done this, you still have to go inside your admin panel and activate the plugin! Have you done all this?
stackexchange-wordpress
{ "answer_score": -3, "question_score": 0, "tags": "plugin development, shortcode, template tags" }
How to add hook to the_title() and get_the_title() I've having trouble with accented characters now if i do utf8_decode() before echoing the title the problem is solved but instead of changing this all over my theme, can't I do this in one place that upgrade proof? I'm not really familiar with hooks but I think thats they way to do it, havent found out how to do it tho.
The filter for `the_title` functions is this one: add_filter( 'the_title', 'f711_title_filter' ); function f711_title_filter( $title ) { return utf8_decode( $title ); }
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "hooks, get the title" }
How to add an admin alert for missing plugins I'm trying to add an admin alert that reminds the user to install a certain plugin in case it is missing. I have found a way to generally add an alert box: function addAlert() { ?> <script type="text/javascript"> $j = jQuery; $j().ready(function(){ $j('.wrap > h2').parent().prev().after('<div class="update-nag">This is a test alert. Do with it what you want.</div>'); }); </script> <?php } add_action('admin_head','addAlert'); How do I only make it appear if the plugin is missing? I was thinking about something in the lines of `<?php if ( function_exists('...') ) ?>` but I am not too sure. I also need a way of adding a link to the plugin and a link to dismiss the box.
To check if a plugin is installed and activated, use the `is_plugin_active()` function. Note that you need to include this function first on the front-end before you can use it: include_once ABSPATH.'wp-admin/includes/plugin.php'; Avoid `function_exists()` for doing the check. Plugins may refactor their code and a previously existing function might disappear. You never know.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, theme development, admin" }
Get current category details the user is currently on in category.php I want to get the current category details that the user is on in category.php. $category = get_the_category(); $slug = $category[0]->slug; // Why is this an array ? In most cases (where there are no sub-categories) it returns and array of single length. But if there are sub-categories it (parent category and ) returns an array of 2 or more. -> get_the_category() returns an array of 2 -> get_the_category() returns an array of 2
You are using the wrong function. Try: $thiscat = $wp_query->get_queried_object(); var_dump($thiscat); I don't know exactly what you want to do with this information but you will get an object (stdClass) with ~15 items in it. You should be able to find what you need.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "categories" }
How to Add Custom CSS to the Media Thickbox? I've added a couple of custom fields to the Edit Media screen, but when these are displayed in the WP Media Thickbox (when adding images from the Edit Post screen, for example), the styling is gone. Is there a hook to add my custom css to the Thickbox iframe when it loads?
In WordPress 3.5, this hook works for me: add_action( 'print_media_templates', 'wpse_75746_print_style_35' ); function wpse_75746_print_style_35() { ?> <style> .media-modal-content, .media-sidebar { background: #FFF2D4 !important; } </style> <?php } In 3.4.2, this is the one: add_action( 'admin_print_styles-media-upload-popup', 'wpse_75746_print_style_342' ); function wpse_75746_print_style_342() { ?> <style> #media-upload { background: #FFF2D4 !important; } </style> <?php }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "css, hooks, media, thickbox, iframe" }
What is a Theme textdomain? I've found that any WordPress theme uses this functions, but I don't understand what is the purpose of it and what is it, in this case `'themify'`? Here are some examples in Themify `functions.php`: 1). load_theme_textdomain( 'themify', TEMPLATEPATH.'/languages' ); 2). if (function_exists('register_nav_menus')) { register_nav_menus( array( 'main-nav' => __( 'Main Navigation', 'themify' ), 'footer-nav' => __( 'Footer Navigation', 'themify' ), ) ); } And in tempate file: 3). `<?php _e( 'Sorry, nothing found.', 'themify' ); ?>` And many more! My doubt is what is `'themify'` stand for? What is their purpose? Could I Change it or delete it? What is the place, `'themify'`, for?
In this case, `'themify'` is the defined _textdomain_ for the Theme, used to make the Theme _translatable_. (Codex reference: **`load_theme_textdomain()`**). Making a Theme translation-ready requires a few steps. 1. Define the Theme's _textdomain_ : load_theme_textdomain( 'themify', TEMPLATEPATH.'/languages' ); 2. Define _translatable strings_ in the template. This is done using one of a few translation functions: **`__()`** (for _returned_ strings), **`_e()`** (for _echoed_ strings), and **`_x()`**/ **`_ex()`** (for _gettext context_ strings). There are others, but you get the idea... A static text string, such as `<p>Hello world!</p>`, is wrapped in an appropriate translation function, such as `<p><?php _e( 'Hello World!', 'themify' ); ?></p>`, to make it available for translation. 3. Generate the .mo/.po files _reference onhow to edit language files_
stackexchange-wordpress
{ "answer_score": 26, "question_score": 23, "tags": "theme development, translation, textdomain" }
Add Field to WordPress Register Form How can I add a field to the WordPress Register form? For example, I want to add the "First Name" field in the users profile to the Register form, but I can't figure out how to do that. The field's name is first_name, but adding `<input type="text" name="first_name" id="first_name" value="<?php echo $_POST['first_name']; ?>" required="required" placeholder="<?php _e('First Name'); ?>" />` doesn't work for some reason. The form submits fine, but the profile doesn't get the "First Name" field filled in in the back end. I'm editing this plugin to tweak the register form: <
I found an excellent, free plugin that gets the job done. < Very easy to use, adds fields to both the register and the profile pages.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, user registration" }
how can I do something on new user registration? When I register a new user to my blog, I always receive an email. The code in simple terms should look like this. on_new_user_registration(){ //send email to admin //I want to do something else. } I would like to do more than receiving an email. Can someone point me to the right code. I have tried using the `wp_insert_user()` function in wordpress but that creates the user inside the editor. thanks a lot.
You want to use the `user_register` hook, probably. Then use the Filesystem API to make the folder. Be aware that filesystem manipulation is dependent upon server configuration and may not always work, but using the API should ameliorate that problem as much as possible.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, php, themes" }
Why does abstracting html from plugin code result in loss of access to wordpress functions? When defining the callback that produces the HTML content for an admin settings page, I'd like to abstract the HTML into a separate file, but the HTML uses some wordpress functions, specifically current_user_can and screen_icon. These are claimed to be undefined when called through the included file but work fine inline. function admin_menu_page_content() { if ( !current_user_can( 'manage_options' ) ) { wp_die( __( 'You do not have sufficient permissions to access this page.' ) ); } ?> <div class="wrap"> <?php include(plugins_url('plugin_name/forms/admin_form.php')) ?> </div> <?php }
Use `plugin_dir_path()` to include executable files. `plugins_url()` returns the web address, that’s not what you need. <?php include(plugin_dir_path(__FILE__) . 'forms/admin_form.php') ?>
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "php, include" }
querying posts by custom taxonomy terms right from a querystring based URL The following URL seems to work for cats and tags only. `yoursite.com?cat=2&tag=bread1+bread2` what if you wanted to get into custom taxonomy and terms and do something similar? is there an equivalent to something like the following? `yoursite.com?taxonomy=food&tag=bread1+bread2`
This should work : yoursite.com/taxonomyname/bread1,bread2 So for example, on my site, I actually use : mysite.com/location/barcelona,paris And I get a list of all posts tagged with Barcelona or Paris
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "custom taxonomy, wp query" }
wordpress plugin that show my reputation (points) in any stackexchange project in my wordpress blogs I'm seeking for a plugin show my points (reputation) of Stackexchange (not Stackoverflow) in my Wordpress blogs. or other projects in stackexchange like : 1. Superuser 2. Security 3. Serverfault 4. SharePoint or author plugin that show points like Google plus beside the picture of every authors. or help me about "how can i develop a plugin do this for me? or show my profiles in stackexchange's projects?
I don't know of a plugin but the easiest way is to just embed your stack flair: < For a more detialed solution I recommend you just fetch the Stack API using the the WordPress HTTP API, the docs are here: < The Stack API is very easy to work with and returns JSON. For you reputation for example you would query this url, you can change the site paramater to the ones you want: so you would have something like this in your plugin: $stackProfile = ' $stackAPI = wp_remote_retrieve_body( wp_remote_get($stackProfile) ); //your output The Stack paramaters you can query are here: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugins, plugin development, author, list authors, stackoverflow" }
Create site programmatically for WPMU My customer has a site, which has WP blog + vBulletin forum. Now he wants to allow vb users to have their own blog, by modifying current WP blog to WPMU network. So I want to create a button, which could be clicked by vb user and new site will be created in network for him. How can I create new site programmatically for WPMU network?
first create a user from this function $user_id = wpmu_create_user( $username, $password, $email ); then used this function to create blog wpmu_create_blog( $newdomain, $path, $title, $user_id , array( 'public' => 1 ), $current_site->id ); for detail you can see this file > /wp-admin/network/site-new.php after viewing this page you will have the exact idea what you want to do.
stackexchange-wordpress
{ "answer_score": 11, "question_score": 7, "tags": "multisite" }
Breadcrumb is not generating the correct post page url I have created a custom posts type cities and the code for its deceleration is `register_post_type('City',$args);` $labels = array( 'name' => _x('Cities', 'post type general name'), 'singular_name' => _x('City', 'post type singular name'), ...... ); and I Installed prime-strategy-bread-crumb to generate the breadcrumbs but the exact url for cities page is < and the url generated by the breadcrumb is < which ultimately takes me to the archive page of post type city so do I have to make changes in the plugin file or is it all due to page url because the url of single city post is //www.abc.com/wordpress/city/shimla/ and code to display the breadcrumbs is in this page.
The Labels are for the use in the Adminsection of your Website. If you want to change the slug in the URL of your CPT, use this values in your `register_post_type` function call. $rewrite = array( 'slug' => __( 'cities', 'your_textdomain' ), //...... ) $args = array( 'rewrite' => $rewrite, //...... );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, theme development, themes, breadcrumb" }
making users able to add their own products wp e-commerce I am using wp e-commerce plugin to build a simple e-commerce website. The problem is that I want to allow all users to post their products on the website. Right now, only the admin can add products. Does anyone know if it's possible to give users the privilege to post products?
The products are nothing but custom post type. So you have to create a custom form (say in a page template) and create custom posts accordingly in the backend. You can have a look for the approach here: < <
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "plugins, e commerce, plugin wp e commerce" }
how to find the current page is isngle activity page in buddypress? I want to check whether the current page is "Single activity page" or not, I ned like ths, `if(is_single_activity())` or if(is_page('is_single_activity')) Thanks
Try this bp_is_single_activity()
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "buddypress" }
how to make a wplang for network fill automatically I made a new network in my website its default language was ar when I add a new website it does not fill it WPLANG automatically, I made it manually but how to make it fill automatically.
OK Thanks all I found the answer update_option( 'WPLANG', 'ar' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, multisite" }
get_the_post_thumbnail wordpress 3.5 For some reason the following isn't loaded anymore in wordpress 3.5. Does anyone know how to fix the `get_the_post_thumbnail()` ? I'm using the follow code: echo "<div class='meta_apps'>"; echo "<a href='"; the_permalink(); echo "'>"; echo "<div class=\"meta-icon\">".get_the_post_thumbnail($post->post_id, 'thumbnail', $attr)."</div>"; echo "<div class=\"meta-title\">".$post->post_title."</div>"; echo "</a>"; echo "</div>";
I could be mistaken, but I don't think `$post->post_id` works to retrieve the post's ID. I believe you want `$post->ID`. So that was probably your issue to begin with, though without seeing your `$attr` array, it's hard to say. Here's a reference for `$post`'s properties. In this case, `get_the_post_thumbnail` is the more appropriate function. In your answer you posted for yourself, you're using `the_post_thumbnail` incorrectly. First off, you don't need to echo it; `the_post_thumbnail` will output the thumbnail. Side note: Any function in `WordPress` that starts with `the_` is almost always going to output something automatically. Second, You don't need to pass it `$post->ID` (again, using the wrong property). Third, the first property of `the_post_thumbnail` is the size, e.g. "thumbnail".
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "post thumbnails" }
wp_list_pages: only show subpages on the parent page? I'm using `wp_list_pages('title_li=')` on my site. Some of my pages do have subpages, however I don't want to list them unitl I'm on an actual parent page that has subpages. So imagine my front-page: — About Us — Gallery — Kitchen — Disclaimer When clicking on Gallery (and Gallery has two subpages) I want them to be listed as well. — About Us — Gallery — Subpage 1 — Subpage 2 — Kitchen — Disclaimer How am I going to do this with the `wp_list_pages()` function?
This would probably be better achieved using CSS. First, you hide all .children: .page_item .children { display: none; } Then, you show the current_page_item's children: .current_page_item .children { display: block; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "menus, pages, wp list pages, sub menu" }
Create second custom 404 page for selected post type I created a new custom post type called `event`, which works fine. I also created a custom `404` page template, which is shown if a event/page/post is not found. But now the hard part, i want to create a custom 404 page for event post type. So this 404 page is only shown if a event is not found. But the default 404 page should still work with posts or pages. Thanks
Two options: 1. Use conditional code inside of `404.php`, to output different content/markup for the post-type 2. Intercept the template at `template_redirect`, and include a separate template file for a 404 for the post-type. Personally, I'd go with option 1, as it is easier and more intuitive.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom post types, templates, page template, 404 error" }
How to delete all post and attachments of a user when I delete it? When I delete a user, WordPress can just delete the post or page of this user, not his custom post and his attachments. An idea for a special hook? add_action( 'delete_user', 'my_delete_user'); function my_delete_user($user_id) { $user = get_user_by('id', $user_id); $the_query = new WP_Query( $args ); if ( have_posts() ) { while ( have_posts() ) { the_post(); wp_delete_post( $post->ID, false ); // HOW TO DELETE ATTACHMENTS ? } } }
The hook you choose is appropriate, and here is how to use it to delete all posts of all types (posts, pages, links, attachments, etc) of the deleted user: add_action('delete_user', 'my_delete_user'); function my_delete_user($user_id) { $args = array ( 'numberposts' => -1, 'post_type' => 'any', 'author' => $user_id ); // get all posts by this user: posts, pages, attachments, etc.. $user_posts = get_posts($args); if (empty($user_posts)) return; // delete all the user posts foreach ($user_posts as $user_post) { wp_delete_post($user_post->ID, true); } } If you only want to delete user attachments, change the `post_type` arguments from `any` to `attachment` and use `wp_delete_attachment($attachment_id)` instead of `wp_delete_post()`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "users, hooks, attachments, customization" }
permalink results to "page not found" Whenever I change my permalink option from the default to /%postname%/, it results into my page cannot be found. Wordpress would complain that it cannot modify the .htaccess (because there was none), so I created it in /var/www/. The .htaccess has the same owner / permissions as my wordpress folder. Please help, I've been trying to fix this for 3 days now. Do I also need to change the mod_rewrite somewhere? EDIT: Solved! inside /var/www/.htaccess Add the line: Options +FollowSymLinks for the mod_rewrite problem: > Check for Apache Mod_ReWrite – Following lists all the loaded modules > > sudo apache2ctl -M Enable Mod_Rewrite > > sudo ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load Restart Apache view sourceprint? 1 sudo /etc/init.d/apache2 restart courtesy of <
Solved! inside /var/www/.htaccess Add the line: Options +FollowSymLinks for the mod_rewrite problem: > Check for Apache Mod_ReWrite – Following lists all the loaded modules > > sudo apache2ctl -M Enable Mod_Rewrite > > sudo ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load Restart Apache view sourceprint? 1 sudo /etc/init.d/apache2 restart courtesy of <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "permalinks, mod rewrite" }
WP native tag suggest metabox. How does it process tag id? As you know, there is a metabox that suggests tags as you type to input box. Is anyone knows how this function gets the tag's ID (term_id) which is selected? I have looked at some of the core files but it seems only the tag name is retrieved and the ajax response returns only the name, no sign of id. But it's just impossible as the tag is updated **by the tag's ID but not it's name** upon submitting or updating the post The core files i've looked at: wp-admin/includes/meta-boxes.php wp-admin/js/post.dev.js wp-admin/admin-ajax.php wp-includes/post.php wp-includes/js/jquery/suggest.dev.js wp-includes/taxonomy.php
It just passes the tag names to wp_update_post(), which eventually calls wp_set_post_tags(), which eventually converts the names to `term_id`s, using term_exists().
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "taxonomy, tags" }
How to implement styling of div in the front end using plugin admin meta box settings? I have a plugin meta box (in the Wordpress admin) with the following fields and values: Name of the div class selector= featured_content Font family= Verdana Font color= #000 They are stored in the Wordpress post meta table. In the Wordpress front end, one of the content template has this div: <div class="featured_content"> The quick brown fox jumps over the lazy dog. </div> How would I communicate with the Wordpress front end from my Wordpress meta box settings for that div? So that when the page is loaded containing the div class selector name of "featured_content", proper styling would be implemented based on the backend meta box settings. I am thinking of running a JS code to scan all id and class selectors then query via AJAX to retrieve the settings and implement them, but I'm not sure if this is the best way. Thank you for any tips.
The answer is really simple, I never thought at first. You will simply create a custom CSS function inside your plugin and then use PHP to output the meta values and hook that to wp head.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, ajax" }
How to make remove display none to this div container in post meta box? I am adding meta box via add_meta_box hook but it is not showing in the admin panel, I double check the source code and it seems hidden because of this line: <div class="postbox-container" id="postbox-container-2" style="display: none;"> These are all my attempts to remove this display:none but all are not working: a.) Using CSS like: #postbox-container-2 {display:block;} b.) Using jQuery like: $('#postbox-container-2').css('style',''); OR $('#postbox-container-2').show(); OR $('#postbox-container-2').css('display','block'); OR $('#postbox-container-2').removeAttr()('display'); How to make that div appear? Thank you for any tips.
This did the trick, in jQuery: //get page title var edit_title_page=$("html head title").text(); //Confirm if this is right Edit page if (edit_title_page.indexOf("Edit Form") >= 0) { $('#postbox-container-2').removeClass("postbox-container"); $('#postbox-container-2').css('width','100%'); $('#postbox-container-2').css('float','left'); $('#mymetaboxID').show(); } It will first check for edit page title, if it's on the right page, remove the post-box container containing the display none, then apply a new css styling. Finally show the meta box added using add_meta_box, this works for me.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "metabox" }
Click link on plugin/theme page and open the contextual help on a specific tab I've added a help section using the add_help_tab() function. I'd like to be able to click a link somewhere on the theme/plugin page and have the help panel open at whichever tab I need. Can someone help me out with the required JS for this? Each tab panel has a unique hash link associated with it so I'd need to use this somehow I'm guessing /themes.php?page=theme_options#tab-panel-general
Maybe the Q is bordering the `off-topic`, but IMO interesting in WordPress context. I've tested this directly in FireBug, in the Dashboard page (`wp-admin/index.php`). var $ =jQuery.noConflict(); // Remove 'active' class from all link tabs $('li[id^="tab-link-"]').each(function(){ $(this).removeClass('active'); }); // Hide all panels $('div[id^="tab-panel-"]').each(function(){ $(this).css('display','none'); }); // Set our desired link/panel $('#tab-link-help-content').addClass('active'); $('#tab-panel-help-content').css('display','block'); // Force click on the Help tab $('#contextual-help-link').click();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "jquery, theme options, contextual help" }
Finding URI in Child Theme Which is best way to find URI in child Theme. <?php echo get_template_directory_uri(); ?> <?php bloginfo('template_directory'); ?> Below given code works but it has "stylesheet" in it, sounds like its a hake to find URI. Is this the only solution ? <?php echo get_stylesheet_directory_uri(); ?> <?php bloginfo('stylesheet_directory'); ?>
Yes, `stylesheet` is for child themes, `template` for parent themes. Andrew Nacin has explained that recently on wp-hackers: > child themes were originally just `style.css` and `functions.php`. That's why "template" refers to the parent theme and "stylesheet" refers to the child theme.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls, child theme" }
bloginfo('stylesheet_directory') vs. get_stylesheet_directory_uri() and include('file.php') vs. get_template_part() In my custom theme I'm using `<img src="<?php bloginfo('stylesheet_directory'); ?>/images/logo.jpg"/>` to load my custom logo. I'm using a custom sidebar for `front-page.php` and that's why I used `<?php include('sidebar-front.php') ?>` to get it. But when I'm using the 'theme-check' plugin it's suggesting to change the following: * `bloginfo('stylesheet_directory')` to `get_stylesheet_directory_uri()` * `include()` to `get_template_part()` So, I did the following: * `<img src="<?php get_stylesheet_directory_uri(); ?>/images/logo.jpg"/>`, and * `<?php get_template_part('sidebar-front.php') ?>` But both failed here. The logo doesn't load and the sidebar isn't too. I used `<?php get_sidebar('front'); ?>` and it's working fine. I just want to speculate what the problem with those suggestions? It's WP 3.4.2 here.
`get_stylesheet_directory_uri()` returns a value, it doesn’t print anything. So you have to use: echo get_stylesheet_directory_uri(); `get_template_part()` is just a wrapper for `locate_template()`. But the latter has one advantage: It returns the path of the file it has found. Try the following: $path = locate_template( 'sidebar-front.php', TRUE ); echo $path;
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "sidebar, css, include, bloginfo" }